Graphs 101
Intermediate · 4 chapters · 8 min read · Model the problem as nodes and edges, then let BFS, DFS or Dijkstra do the work.
Practise this in the app All guides
Recognising a graph problem
Nodes and edges everywhere
A graph is a set of nodes connected by edges. Edges can be directed (a prerequisite: course A before course B) or undirected (a road between two cities), and weighted (travel time) or unweighted. Trees and grids are special graphs, and many interview questions hide a graph behind a story: words that differ by one letter, cells in a matrix, people who know each other, or network nodes sending signals.
Signals in a problem statement
- "Is there a path from A to B?", "number of connected components / islands / provinces".
- "Fill", "spread", "rot", "infect" across neighbouring cells — multi-source BFS on a grid.
- "Minimum number of steps / moves / transformations" with equal cost per step — BFS.
- "Prerequisites", "order of tasks", "can all courses be finished?" — topological sort and cycle detection on a directed graph.
- "Minimum time / cost" with different edge weights — Dijkstra.
- "Group things that are connected", "redundant connection" — union-find.
Representations
Most problems give an edge list. Convert it to an adjacency list first:
from collections import defaultdict
def build(n, edges, directed=False):
g = defaultdict(list)
for u, v in edges:
g[u].append(v)
if not directed:
g[v].append(u)
return g
For grids, do not build anything: the neighbours of (r, c) are the four cells (r±1, c) and (r, c±1) that lie inside the grid.
Mental model
Ask three questions before coding: what is a node, what is an edge, and what am I searching for (reachability, shortest steps, an ordering, minimum cost)? The answer picks the algorithm.
Core patterns with templates
1. DFS for reachability and flood fill
def flood_fill(grid, r, c, new):
old = grid[r][c]
if old == new:
return grid
rows, cols = len(grid), len(grid[0])
stack = [(r, c)]
while stack:
i, j = stack.pop()
if 0 <= i < rows and 0 <= j < cols and grid[i][j] == old:
grid[i][j] = new
stack += [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]
return grid
2. BFS for fewest steps (multi-source)
from collections import deque
def minutes_to_rot(grid):
rows, cols = len(grid), len(grid[0])
q = deque((i, j) for i in range(rows) for j in range(cols) if grid[i][j] == 2)
fresh = sum(row.count(1) for row in grid)
minutes = 0
while q and fresh:
for _ in range(len(q)):
i, j = q.popleft()
for a, b in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
if 0 <= a < rows and 0 <= b < cols and grid[a][b] == 1:
grid[a][b] = 2
fresh -= 1
q.append((a, b))
minutes += 1
return -1 if fresh else minutes
3. Topological sort (Kahn's algorithm)
def can_finish(n, prereqs):
g = [[] for _ in range(n)]
indeg = [0] * n
for a, b in prereqs:
g[b].append(a)
indeg[a] += 1
q = deque(i for i in range(n) if indeg[i] == 0)
done = 0
while q:
u = q.popleft()
done += 1
for v in g[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return done == n
If some nodes never reach in-degree 0, there is a cycle.
4. Dijkstra for weighted shortest paths
import heapq
def dijkstra(n, edges, src):
g = [[] for _ in range(n + 1)]
for u, v, w in edges:
g[u].append((v, w))
dist = {src: 0}
h = [(0, src)]
while h:
d, u = heapq.heappop(h)
if d > dist.get(u, float("inf")):
continue
for v, w in g[u]:
if d + w < dist.get(v, float("inf")):
dist[v] = d + w
heapq.heappush(h, (d + w, v))
return distComplexity, mistakes and edge cases
Complexity
| Algorithm | Time | Space |
|---|---|---|
| DFS / BFS | O(V + E) | O(V) |
| Grid BFS / DFS | O(rows × cols) | O(rows × cols) |
| Topological sort | O(V + E) | O(V) |
| Dijkstra with a heap | O((V + E) log V) | O(V + E) |
| Union-find (with path compression and union by size) | almost O(1) per operation | O(V) |
Common mistakes
- Marking visited too late. In BFS, mark a node visited when you push it, not when you pop it; otherwise the same node enters the queue many times.
- Forgetting both directions for undirected edges.
- Using BFS on weighted graphs. BFS gives fewest edges, not least total weight; use Dijkstra (non-negative weights) instead.
- Negative weights with Dijkstra. It is incorrect there; mention Bellman-Ford.
- Skipping the stale-entry check (
if d > dist[u]: continue) in Dijkstra, which wastes time on outdated heap entries. - Recursion depth on large grids. A 1000 × 1000 grid can mean a million-deep recursive DFS; use an explicit stack or BFS in Python.
- Off-grid indices. Check bounds before reading
grid[a][b]. - Flood fill with the same colour, which loops forever without the
old == newguard.
Edge cases
Empty grid, a single cell, disconnected components, unreachable targets (return -1 or infinity as the problem says), self-loops, duplicate edges, the source equal to the target, and nodes numbered from 1 instead of 0.
Word-ladder style implicit graphs
When the graph is not given, generate neighbours on the fly. For words, try changing each position to each of 26 letters and keep only words in the dictionary set. That is O(L × 26) neighbours per word, much cheaper than comparing every pair of words.
Variations and practise
How interviewers twist it
- Count islands or components. Loop over every cell or node; each time you find an unvisited one, increase the count and flood it.
- Return the course order, not just whether it exists: collect nodes as Kahn's algorithm pops them.
- Detect a cycle with DFS colours. White (unvisited), grey (on the current path), black (finished). Meeting a grey node means a cycle.
- Shortest path with at most k stops. Bellman-Ford limited to
k + 1rounds, or BFS over(node, stops)states. - State-space search. The node is a whole state (a lock combination, a board, a word), and edges are legal moves. BFS still works.
- Bidirectional BFS. Search from both ends and stop when the frontiers meet; useful for word ladder when the dictionary is large.
- Union-find. Ideal for "are these connected after a series of unions?" and for finding a redundant edge.
def find(parent, x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
How to explain it
Start with the modelling: "Each cell is a node, edges join adjacent cells, and I need the fewest steps, so BFS." Interviewers grade the modelling step as heavily as the code.
Practise
The problems below cover reachability, flood fill, multi-source BFS on a grid, topological sort, Dijkstra, and an implicit word graph. For each, write down what a node and an edge are before choosing the algorithm.
Practise
Easy
- 2228. Flood Fill
- 2229. Find if Path Exists in Graph
- 2235. Hub of the Courier Network
- 2240. Richest Alliance
- 2241. The Village Elder
- 2242. Friend Count per Member
- 2243. Busiest Interchange
- 2244. Towns No Road Enters
- 2245. Last Stop on the Ticket Chain
- 2246. Matrix to Neighbor Lists
- 2247. Every Street Runs Both Ways
- 2248. Fence Around the Pond
- 2249. How Many Villages Hear the Bell
- 2250. Hops From the Lighthouse
- 2251. Ripple Order
- 2252. Explorer's Diary
- 2253. Exactly K Handshakes Away
- 2254. Widest Ring of the Ripple
- 2255. Is It a Single Trail
- 2256. Is It One Ring
- 2257. Spot the Doubled Road
- 2258. Lonely Servers
- 2259. Tips of the Branches
- 2260. Everyone Knows Everyone
- 2261. Same Number of Links
- 2262. Ranking Junctions by Traffic
- 2263. Shared Neighbours
- 2264. Friends of Friends
- 2265. Mutual Followers
- 2266. Flip Every Arrow
- 2267. Is the Itinerary Drivable
- 2268. Toll for the Planned Drive
- 2269. Robot Through the Warehouse
- 2270. Cells Within the Battery
- 2271. Can the Snowplough Trace It
- 2272. Coastline Cells
- 2273. Cheapest Wire at Each Pole
- 2274. Club Sizes
- 2275. Who Reports to Whom
- 2276. Longest Chain of Command
- 2277. Farthest Cabin From the Gate
- 2278. Links in the Missing Graph
- 2279. Suggest a New Friend
- 2280. Roads Between Two Colours
- 2281. Is the Map Coloured Properly
- 2282. One Letter Apart
- 2283. Reachable From Both Camps
- 2284. Gift Exchange Circles
- 2285. Follow the Signposts
- 2286. Is the Floor Plan One Piece
- 2287. Tallest Neighbour
- 2288. Steepest Segment of the Trail
- 2289. Route Between Two Cabins
- 2290. Team Sizes Under Each Lead
- 2291. Does the Trail Loop
- 2292. Dead Ends in the Maze
- 2294. Arrow Tile Walk
- 2295. Neighbourhood Average
- 2296. Bordering Districts
- 2297. Busiest Road
- 2298. Groups After Each Handshake
- 2299. Domino Chain Reaction
- 2300. Smallest Label in My Group
- 2301. Nearest Shared Manager
- 2302. Valley Junctions
- 2303. Right and Down Reach
- 2304. Light Truck Routing
- 2305. Same Map, Different Order
- 2306. Detour Around the Closed Station
- 2307. The Doubling Machine
- 2308. Best Friend Pairs
- 2444. Explore Until the Gate Closes
- 2447. Richest Root-to-Leaf Trail
- 2449. Valid Edge Sequence
- 2457. Leaders With Loyal Followers
Medium
- 2230. Rotting Oranges
- 2231. Course Schedule
- 2232. Network Delay Time
- 2236. Count the Archipelago
- 2237. Largest Vineyard Plot
- 2238. Sealed Lagoons
- 2293. Command Centre
- 2309. Land Without a Shore Route
- 2310. Capture the Surrounded Stones
- 2311. Outline a Painted Region
- 2312. Distinct Cookie-Cutter Shapes
- 2313. Islands Inside the Old Map
- 2314. Nearest Door Out of the Hedge Maze
- 2315. Knight on an Endless Board
- 2316. Rain Reaching Both Seas
- 2317. Portal Board Race
- 2318. Connected Pipe Tiles
- 2319. Regions Split by Mirrors
- 2320. Narrowest Causeway
- 2321. Rolling Marble Reaches the Hole
- 2322. Shortest Marble Roll
- 2323. Gentlest Hiking Route
- 2324. Widest Safe Corridor
- 2325. Letter Loop in the Grid
- 2326. Gold Mine Tour
- 2327. Every Path From Entry to Exit
- 2328. Nodes That Always Halt
- 2329. Point Every Road to the Capital
- 2330. Carpool to the Summit
- 2331. Pairs That Cannot Meet
- 2332. Rewire to Connect the Lab
- 2333. Strongest Pair of Cities
- 2334. Two Team Split
- 2335. Diameter of the Trail Network
- 2336. Best Roots for a Shallow Tree
- 2337. Time to Spread the Memo
- 2338. Hop to a Zero
- 2339. Combination Dial
- 2340. Two Bucket Measure
- 2341. Alternating Colour Hops
- 2342. Where Is the Wandering Frog
- 2343. Fireworks Chain
- 2344. Minimum Spanning Forest Weight
- 2345. Complete Friend Circles
- 2346. Heaviest Load Between Depots
- 2347. Brightest Constellation
- 2348. Pipeline Capacity Into a Single Tank
- 2349. First Meeting Point of Two Arrows
- 2350. Mixed Unlock Rules
- 2351. Peer Pressure Spread
- 2352. All Upstream Sources
- 2353. Quietest Among the Wealthier
- 2354. Distance to the Ring Road
- 2355. Fewest Terms to Graduate
- 2356. Cheapest Crossing of the Toll Grid
- 2357. Project Critical Path
- 2358. Stepping Stones Across the River
- 2359. Is a Prerequisite Of
- 2360. Zigzag Hike
- 2361. Only One Valid Order
- 2362. Where Should the Friends Meet
- 2363. Dishes You Can Cook
- 2364. Busiest Checkpoint in the Tree
- 2365. Longest Dependency Chain
- 2366. Broadcast in Rounds
- 2367. Count Routes Through the DAG
- 2368. Who Is Ranked for Sure
- 2369. Alphabetically First Schedule
- 2370. Allowed Swaps Puzzle
- 2371. Show Me the Loop
- 2372. The Extra Cable
- 2373. Merge Contact Cards
- 2375. Equal and Unequal Labels
- 2377. Smallest Equivalent Spelling
- 2379. Anagram Cousins
- 2381. Clear the Shelf Pegs
- 2383. Smallest After Group Swaps
- 2385. First Day Everyone Is Linked
- 2386. Cheapest Irrigation Grid
- 2387. Wire Up the Sensors
- 2388. Mandatory Link Spanning Tree
- 2389. Sort by Swapping Any Two
- 2390. Altitude Difference Ledger
- 2391. Cheapest Trip With Few Layovers
- 2392. Most Reliable Relay
- 2393. How Many Fastest Routes
- 2394. Coupon-Cut Fares
- 2395. Quietest Town Within Reach
- 2396. Towns With a Toll Booth
- 2397. Fewest Arrows to Reverse
- 2398. Spot the Money Loop
- 2399. Distance Lookup Table
- 2400. Cheapest Letter Rewrite
- 2401. Exactly K Flights
- 2402. Shortest Path With Debts
- 2403. Downhill Route Count
- 2404. Nearest Clinic for Each Village
- 2405. Network Goes Quiet
- 2406. Videos Watched by K-Step Friends
- 2407. Hop Home Around the Traps
- 2408. Number Transformer
- 2409. Rotate and Add Puzzle
- 2410. Same Label Descendants
- 2411. Harvest the Ripe Fruit
- 2412. Weakest Link Between Ends
- 2413. Four Flower Beds
- 2414. K-Colour the Map
- 2415. Token Game on a DAG
- 2416. Manager K Levels Up
- 2417. Ancestor Check Queries
- 2418. Strongly Linked Check
- 2419. Count the Triangles
- 2420. Best Warehouse Location
- 2421. Open Every Vault
- 2422. Loop Length in the Signposts
- 2423. Ring Around Each Node
- 2424. Signals on Two Frequencies
- 2425. Shortest Loop Through a Node
- 2426. Lexicographically First Shortest Route
- 2427. Directed Reach Within K
- 2428. Bipartite Team Sizes
- 2429. Grid Teleporters
- 2430. Lights Out Switchboard
- 2431. Rhyme Families
- 2432. Chain of Overlapping Meetings
- 2433. Transit Between Lines
- 2434. Arrive Before Closing
- 2435. Minimum Hops With Jump Boots
- 2436. Gem Cut Equivalence
- 2437. Seat the Council in a Ring
- 2438. Reopen the Stations
- 2439. Checkerboard Neighbour Teams
- 2440. Rumour With Delays
- 2441. Plan the Three-Stop Day
- 2442. Cut the Tree Into Equal Sums
- 2443. Tree Height From Every Root
- 2445. Exact-Toll Path
- 2446. Balance the Tokens on the Tree
- 2448. Fewest Broadcast Towers
- 2451. Shortest Escape Before Flooding
- 2452. Cheapest Ride Within the Time Limit
- 2453. Remove One Hub
- 2454. Merge Shared-Member Groups
- 2455. Path to the Treasure Room
- 2456. Road Trip With Refuels
- 2458. Roads on Some Fastest Route
- 2459. Distance Between Two Cabins Queries
- 2460. Separate the Capitals
- 2461. Fewest Turns Through the Maze
- 2462. Basin Sizes in a Height Map
- 2493. Mutually Reachable Clubs
- 2511. Quarantine One Infected Machine
Hard
- 2233. Word Ladder
- 2234. Critical Connections in a Network
- 2239. Outrun the Wildfire
- 2374. Tunnel Through Up to K Walls
- 2376. Fix the Conveyor Arrows
- 2378. Reclaim One Square of Sea
- 2380. Islands Rising From the Sea
- 2382. Bricks Hanging From the Ceiling
- 2384. Crossing at High Tide
- 2450. Add Streets for a Full Sweep
- 2463. Path Farthest From the Guards
- 2464. Longest Uphill Trail
- 2465. Mow Every Patch Once
- 2466. Keys to Every Lock
- 2467. Gates That Open Late
- 2468. Warehouse Crate Shove
- 2469. Six-Tile Slider
- 2470. Two-Cell Caterpillar
- 2471. Tightest Loop in the Network
- 2472. Most Layers of Neighbours
- 2473. Reversals for Every Capital
- 2474. Total Distance From Every Cabin
- 2475. Recover the Secret Alphabet
- 2476. The Extra One-Way Road
- 2477. Shared Roads for Two Couriers
- 2478. Light Loads Only
- 2479. Cities Sharing Big Divisors
- 2480. Trails Starting and Ending at the Peak
- 2481. Wells or Pipes for Every House
- 2482. Essential and Optional Spanning Edges
- 2483. Partners Sitting Together
- 2484. Second Fastest Arrival With Signals
- 2485. Two Couriers One Depot
- 2486. Touch Every Node Fast
- 2487. Delivery Round Trip
- 2488. Fill In the Unknown Road Lengths
- 2489. Group-Then-Item Ordering
- 2490. Place Numbers by Row and Column Rules
- 2491. Longest Path Without Repeating Neighbours
- 2492. Most Frequent Colour on Any Route
- 2494. Single Points of Failure
- 2495. Use Every Flight Once
- 2496. Chain the Dominoes
- 2497. Shortest Code Covering Every PIN
- 2498. Interns to Projects
- 2499. Maximum Throughput of the Pipeline
- 2500. Fewest Patrol Routes
- 2501. Satisfy Every Seating Wish
- 2502. Heaviest Cable Between Two Posts
- 2503. Hound and Hare
- 2504. Ways to Open the Wings
- 2505. Waystations on Long Roads
- 2506. Cheapest Walk Under Bitwise AND
- 2507. At Most K Courses per Term
- 2508. Collect Every Coin From Two Away
- 2509. Round Table of Favourites
- 2510. Secret Passed at Meetings
- 2512. Best Sightseeing Loop
- 2513. Route Closest to the Plan
- 2514. Codewords One Edit Apart
- 2515. Height After Pruning a Branch
- 2516. Island Shapes Up to Rotation
- 2517. Ferries With Timetables
- 2518. Cut the Fewest Junctions
- 2519. K Cheapest Journeys
- 2520. Runner-Up Spanning Tree
- 2521. Checkpoints Every Route Uses
- 2522. Many Tokens on a DAG
- 2523. Same Shape Family Trees
- 2524. Two Teams After Each Feud
- 2525. Close Pairs in a Big Tree
- 2526. Endless Profit Route
- 2527. Colour Gate Network