DSA Tutorial
🔍

Graph Practice Problems

How to Use This Problem List

Graph problems require identifying the algorithm family before writing code. The decision flows through three questions:

GRAPH PROBLEM DECISION TREE:

Is the graph WEIGHTED?
  NO (or all equal weights) → BFS for shortest path
  YES → is the source SINGLE or ALL-PAIRS?
    ALL-PAIRS → Floyd-Warshall
    SINGLE → are there NEGATIVE weights?
      YES → Bellman-Ford
      NO  → is it a DAG?
        YES → Topological DP / DAG shortest path O(V+E)
        NO  → Dijkstra's

Does the problem ask for ORDERING or SCHEDULING?
  → Topological sort (Kahn's or DFS post-order)

Does the problem ask if nodes are CONNECTED or SAME GROUP?
  → Union-Find (DSU) or BFS/DFS components

Does the problem ask for MINIMUM COST TO CONNECT ALL nodes?
  → Minimum Spanning Tree (Kruskal's or Prim's)

Does the problem have a GRID (2D matrix)?
  → BFS/DFS on grid with 4-directional / 8-directional adjacency

Does the problem ask about CYCLES?
  → DFS (undirected: parent check; directed: pathVisited)
  → Kahn's (directed: count < V)

If algorithm is correct, review these SIGNAL WORDS:
  "shortest path, minimum hops/edges"   → BFS (unweighted)
  "minimum cost path"                   → Dijkstra / Bellman-Ford
  "all nodes receive signal"            → Dijkstra + max(dist)
  "ordering respecting dependencies"    → Topological sort
  "can finish / valid schedule"         → Kahn's cycle detection
  "minimum cost to connect all"         → MST
  "connected / same group / component"  → DSU or BFS/DFS
  "cycle detection"                     → DFS pathVisited / Kahn's
  "reachable from target"               → Reverse graph + BFS/DFS

Pattern 1: BFS — Shortest Path & Level Order

BFS gives shortest path in unweighted graphs. Multi-source BFS finds minimum distance from the nearest source.

ProblemDifficultyRecognition ClueKey Insight
Number of IslandsEasyCount connected groups of 1s in gridBFS/DFS from each unvisited 1; mark component visited; count restarts
Flood FillEasyChange connected region color in gridBFS/DFS from starting cell; update all connected same-color cells
01 MatrixMediumNearest 0 for each cell in binary matrixMulti-source BFS: enqueue ALL 0s at distance 0 simultaneously
Rotting OrangesMediumMinutes until all oranges rottenMulti-source BFS from all rotten oranges; answer = max level reached
Walls and GatesMediumFill each empty room with distance to nearest gateMulti-source BFS from all gates (distance 0)
Word LadderHardMinimum transformations between wordsBFS on implicit graph; each word = vertex, edge if one letter differs
Shortest Path in Binary MatrixMediumShortest 8-directional path in 0/1 gridBFS with 8 directions; level = path length
Jump Game IVHardMinimum jumps to reach last indexBFS on graph where same-value indices are connected
Open the LockHardMinimum turns to reach target combinationBFS on state space; each state is current digits
Pacific Atlantic Water FlowMediumCells reachable to both oceansReverse BFS from each ocean boundary inward
Minimum Genetic MutationMediumMinimum mutations between gene stringsBFS; each valid mutation = one edge
Bus RoutesHardMinimum buses to travel from source to targetBFS on routes (not stops); expand whole route when boarding

Recognition signal: "minimum steps", "minimum hops", "minimum edges", "nearest X", "level by level", "spread outward."

Pattern 2: DFS — Paths, Components & Backtracking

DFS explores all paths, finds connected components, and solves backtracking problems.

ProblemDifficultyRecognition ClueKey Insight
Clone GraphMediumDeep copy a graphDFS/BFS with HashMap from original node → cloned node
Path Sum in GraphMediumFind all paths from source to targetDFS tracking current path; add to result when target reached
All Paths Source to TargetMediumEnumerate all paths in DAG from 0 to n-1DFS backtracking; DAG means no cycle risk
Word SearchMediumFind word in character grid, no cell reuseDFS backtracking; mark visited, unmark on backtrack
Number of Distinct IslandsMediumCount unique island shapesDFS + encode path shape; use set of shapes
Surrounded RegionsMediumCapture surrounded O regionsDFS from border O cells; mark safe; convert remaining
Count Sub IslandsMediumIslands in grid2 that are subsets of grid1 islandsDFS on grid2 islands; entire island must be land in grid1
Reorder Routes to Make All Paths Lead to City 0MediumMinimum edge reversals so all paths reach 0Build undirected + direction tracking; DFS from 0; count wrong-direction edges
Maximum Area of IslandMediumLargest connected island in gridDFS returning component size; track max
Find if Path Exists in GraphEasySimple connectivity checkDFS/BFS from source; check if target is reached
Keys and RoomsMediumCan you visit all roomsDFS/BFS from room 0; rooms reached = components
Critical Connections in a NetworkHardFind bridges (edges whose removal disconnects graph)Tarjan's bridge-finding DFS with discovery time and low values

Recognition signal: "enumerate all paths", "explore all combinations", "grid word search", "reachable", "shape/structure matching."

Pattern 3: Cycle Detection

Detect cycles in directed and undirected graphs.

ProblemDifficultyRecognition ClueKey Insight
Detect Cycle Undirected (DFS)Easy"does undirected graph have a cycle"DFS with parent parameter; visited AND ≠ parent → cycle
Detect Cycle Undirected (BFS)EasySame as above, BFS versionQueue with (node, parent) Pair; visited ≠ parent → cycle
Detect Cycle DirectedMedium"does directed graph have a cycle"DFS with pathVisited[]; visited AND pathVisited → back edge
Course Schedule IMedium"can you finish all courses given prerequisites"Kahn's: count == n → no cycle → can finish
Course Schedule IIMediumReturn a valid course orderKahn's topological sort; if count < n → impossible
Find Eventual Safe StatesMedium"nodes that cannot reach a cycle"DFS: safe = not on any cycle; reverse result of cycle detection
Redundant ConnectionMediumFind extra edge that creates a cycleDSU: first edge where find(u)==find(v) is redundant
Redundant Connection IIHardDirected graph with one extra edgeMore complex — handle cases: two parents for one node, or directed cycle

Recognition signal: "is there a cycle", "can we complete tasks", "safe nodes", "redundant edge", "extra connection."

Pattern 4: Topological Sort

Order vertices in a DAG such that all prerequisites come first.

ProblemDifficultyRecognition ClueKey Insight
Course Schedule IMediumCan you finish all coursesKahn's: if count == n → valid DAG → yes
Course Schedule IIMediumReturn valid course orderKahn's result = topological order
Alien DictionaryHardInfer character order from sorted word listBuild DAG from adjacent word comparisons; topological sort
Sequence ReconstructionMediumIs target the UNIQUE topological sortAt each Kahn's step, queue must have exactly 1 element
Minimum Height TreesMediumFind roots for minimum height treesIteratively remove leaf nodes (like topological sort from leaves)
Parallel CoursesMediumMinimum semesters to complete all coursesTopological sort level by level; levels = semesters
Largest Color in a Directed GraphHardMaximum count of single color in any valid pathTopological sort + DP on DAG
Build OrderMediumOrder to build projects given dependenciesKahn's topological sort; detect cycles
Task SchedulerMediumMinimum intervals to finish tasks with cooldownsGreedy + ordering — not strictly topo but ordering-based
Sort Items by Groups Respecting DependenciesHardTopological sort within groups and across groupsTwo-level topological sort

Recognition signal: "ordering", "scheduling", "dependencies", "prerequisites", "after X comes Y", "build order", "valid sequence."

Pattern 5: Shortest Path

Find minimum cost/distance paths in weighted graphs.

ProblemDifficultyRecognition ClueKey Insight
Network Delay TimeMediumTime for signal to reach all nodesDijkstra from source; answer = max(dist)
Cheapest Flights K StopsMediumCheapest path with at most k stopsModified Dijkstra/BFS: state = (cost, node, stops_left)
Path with Minimum EffortMediumMinimum max-height-difference path in gridDijkstra on grid; weight = max(abs(height diff))
Swim in Rising WaterHardMinimum time to swim from 0,0 to n-1,n-1Dijkstra: weight = max elevation seen so far
Find the City with Smallest Number of Reachable CitiesMediumCity with fewest cities within threshold distanceFloyd-Warshall all-pairs; count reachable per city
Minimum Cost to Reach CityMediumMinimum cost directed graphDijkstra single-source
Shortest Path with Alternating ColorsMediumShortest path alternating red/blue edgesBFS with state (node, last_edge_color)
Number of Ways to Arrive on TimeMediumCount shortest paths from 0 to n-1Dijkstra + DP count: ways[v] += ways[u] when dist[v] updated
Minimum Weighted Subgraph with Required PathsHardMinimum weight subgraph connecting 3 nodesDijkstra from src1, src2, and reversed from dest; combine at each vertex
0-1 BFS (Minimum Edge Reversals)MediumMin edges to reverse for valid path0-1 BFS: original direction = 0, reversed = 1; deque BFS
Dijkstra on Implicit Graph (Word Ladder II)HardAll shortest transformation sequencesBFS + backtracking from end

Recognition signal: "minimum cost", "cheapest path", "minimum time", "all pairs distance", "signal delay", "within distance threshold."

Pattern 6: Union-Find (DSU)

Dynamic connectivity — grouping elements and querying same-group membership.

ProblemDifficultyRecognition ClueKey Insight
Number of ProvincesMediumCount friend circles / connected componentsDSU or BFS/DFS; union friends; count roots
Redundant ConnectionMediumExtra edge that creates cycleFirst edge (u,v) where find(u)==find(v)
Accounts MergeMediumMerge accounts sharing an emailDSU on emails; merge accounts with shared emails
Most Stones Removed with Same Row/ColumnMediumRemove stones sharing row/columnDSU on rows and cols; answer = stones - components
Satisfiability of Equality EquationsMediumA==B and A!=B constraintsDSU: union all == pairs; check != pairs don't share root
Smallest String with SwapsMediumMinimum string after allowed position swapsDSU on swappable positions; sort each component
Number of Islands II (dynamic)HardIslands added one by one, count after eachDSU: add cell, union with adjacent land cells, track component count
Making Large IslandHardLargest island after flipping one 0 to 1DSU all islands; for each 0, check adjacent component sizes
Swim in Rising Water (DSU)HardAlternative to Dijkstra using DSUSort edges by max height; union until source and target connected
Regions Cut by SlashesMediumCount regions formed by / and \ in gridScale grid 3×; mark cells; count components
Earliest Moment Friends Know Each OtherMediumFirst time all friends in one groupProcess events sorted by time; DSU until one component
Graph Connectivity with ThresholdHardNodes share a common divisor > thresholdUnion all multiples of each number > threshold

Recognition signal: "same group", "connected", "merge", "union", "component size after change", "dynamic connectivity."

Pattern 7: Minimum Spanning Tree

Connect all nodes with minimum total edge weight.

ProblemDifficultyRecognition ClueKey Insight
Min Cost to Connect All PointsMediumMinimum total Manhattan distance to connect pointsPrim's or Kruskal's on complete graph; edge weight = Manhattan distance
Find Critical and Pseudo-Critical EdgesHardEdges always/sometimes in MSTRun MST; for each edge: force-include (pseudo) and force-exclude (critical)
Minimum Spanning Tree (classic)MediumConnect all nodes minimum total weightKruskal's: sort edges, DSU cycle check
Optimize Water Distribution in a VillageHardWells + pipes, minimum cost for every houseAdd virtual node 0 for wells; MST on extended graph
Minimum Cost to Supply WaterHardSame as above with well costsConnect each house to virtual source at well cost; MST
Clustering (remove k-1 heaviest MST edges)MediumSplit graph into k clustersBuild MST; remove k-1 largest edges

Recognition signal: "connect all nodes/points/cities minimum cost", "minimum total weight spanning", "maximum k clusters."

Pattern 8: Advanced Graph Problems

Problems combining multiple techniques or requiring creative modelling.

ProblemDifficultyRecognition ClueKey Insight
Strongly Connected ComponentsHardGroups where every node can reach every otherKosaraju: DFS + reverse graph + DFS in finish order
Critical Connections (Bridges)HardEdges whose removal disconnects graphTarjan's bridge detection: low[v] > disc[u]
Articulation PointsHardVertices whose removal disconnects graphTarjan's AP detection: low[v] >= disc[u] for non-root
Bipartite CheckMediumCan graph be 2-colouredBFS/DFS: alternate colors; conflict = not bipartite
Maximum Bipartite MatchingHardMaximum matching in bipartite graphHungarian algorithm or Hopcroft-Karp
Vertex CoverHardMinimum vertex set covering all edgesKönig's theorem: min vertex cover = max matching (bipartite)
Eulerian Path / CircuitMediumPath/circuit using every edge exactly onceHierholzer's algorithm; check degree conditions
Hamiltonian PathHardPath visiting every vertex exactly onceDFS backtracking with bitmask DP (NP-hard in general)
Travelling SalesmanHardShortest tour visiting all citiesBitmask DP: dp[mask][v] = min cost to visit set mask ending at v
Graph Coloring (k-colorable)HardAssign colors such that no two adjacent nodes share colorBacktracking or greedy; bipartite = 2-colorable

Recognition signal: "every node reachable from every other", "remove one edge/vertex to disconnect", "2-colorable", "use every edge", "visit every city."

Pattern Recognition Quick Reference

Signal Word / PhraseAlgorithmTemplate
Minimum hops / edges / stepsBFSQueue + visited + level count
Nearest X (multi-source)Multi-source BFSPre-load all sources at dist 0
Minimum cost path (positive weights)DijkstraMin-heap + stale skip
Minimum cost path (any weights)Bellman-FordRelax all edges V-1 times
All-pairs distancesFloyd-Warshall3-nested loops over k, i, j
Ordering with dependenciesTopological sortKahn's (in-degree BFS)
Can schedule / valid DAGKahn's cycle checkcount == V → valid
Connected groups / componentsBFS/DFS outer looprestart from each unvisited
Same group / dynamic mergeUnion-Findfind + union + component count
Connect all minimum costMST (Kruskal/Prim)Sort edges + DSU
Grid explorationBFS/DFS on grid4-dir or 8-dir adjacency
Word in grid (backtrack)DFS backtrackingMark + recurse + unmark
Cycle in directed graphDFS pathVisitedvisited[] + inStack[]
Cycle in undirected graphDFS parent / BFS Pairvisited[] + parent param
Nodes safe from cyclesReverse + DFSReverse edges; safe from cycle = eventually safe
Reach target (backward)Reverse graph BFSReverse all edges; BFS from target
0/1 weighted edges0-1 BFSDeque: 0→front, 1→back

Recommended Study Order

WEEK 1 — BFS & DFS Foundations
  Pattern 1: Number of Islands, Flood Fill, Rotting Oranges, 01 Matrix
  Pattern 2: Clone Graph, All Paths Source to Target, Word Search
  Grid problems: Max Area Island, Surrounded Regions

WEEK 2 — Cycle Detection & Topological Sort
  Pattern 3: Course Schedule I & II, Redundant Connection
  Pattern 4: Alien Dictionary, Sequence Reconstruction, Parallel Courses

WEEK 3 — Weighted Graphs
  Pattern 5: Network Delay Time, Cheapest Flights, Path with Min Effort
  Dijkstra deep dive: Number of Ways to Arrive, Swim in Rising Water

WEEK 4 — DSU & MST
  Pattern 6: Number of Provinces, Accounts Merge, Satisfiability of Equality
  Pattern 7: Min Cost to Connect Points, Find Critical/Pseudo-Critical Edges

WEEK 5 — Advanced
  Pattern 8: Bipartite Check, Critical Connections, SCC
  Mixed: revisit hard problems from earlier patterns
  Mock: 2 graph problems under timed conditions

Difficulty Progression Reference

StageProblemsWhat to focus on
FoundationIslands, BFS grids, DFS pathsOuter loop for disconnected; visited[] discipline
Early IntermediateCourse Schedule I/II, Clone Graph, Word SearchPattern recognition; topological sort mechanics
IntermediateDijkstra variants, DSU applications, Accounts MergeState design; algorithm selection
Late IntermediateAlien Dictionary, Critical Connections, Cheapest FlightsModelling problems as graphs; combining techniques
AdvancedTSP, Hamiltonian, Max Bipartite Matching, SCCSpecialized algorithms; NP-hard approximations

Common Interview Problem-Solving Checklist

BEFORE CODING:
  □ Is the graph directed or undirected?
  □ Is it weighted or unweighted?
  □ Can it be disconnected? (outer loop needed?)
  □ Is it guaranteed to be a DAG? (topological sort safe?)
  □ What is the graph size? (V, E estimate → algorithm time check)
  □ Does it fit one of the 8 patterns above?

CHOOSING THE DATA STRUCTURE:
  □ Adjacency list for sparse/general graphs
  □ Adjacency matrix for dense graphs or O(1) edge check needed
  □ Edge list for MST algorithms
  □ Grid as implicit graph (no explicit adjacency list needed)

COMMON MODELLING TRICKS:
  □ Grid → graph: cell (r,c) → node r*cols+c
  □ State machine → graph: each state = node, transitions = edges
  □ Bidirectional BFS for large graphs (meet in middle)
  □ Reverse graph: "can reach target" → "reachable from target reversed"
  □ Virtual source: multi-source BFS → add supersource at distance 0
  □ State expansion: Dijkstra with extra state (stops, fuel, cooldown)

EDGE CASES TO HANDLE:
  □ Single vertex (V=1) — no edges needed for spanning tree
  □ Disconnected graph — outer loop / check all components
  □ Self-loops — skip when checking cycle in undirected
  □ Multiple edges between same pair (multigraph)
  □ Negative weights — not valid for Dijkstra; use Bellman-Ford
  □ Target unreachable — dist[target] == ∞ → return -1

COMPLEXITY CHECK:
  BFS/DFS:           O(V + E) — acceptable for V,E ≤ 10^5
  Dijkstra (heap):   O((V+E) log V) — acceptable for V,E ≤ 10^5
  Bellman-Ford:      O(VE) — only for V,E ≤ 10^3
  Floyd-Warshall:    O(V³) — only for V ≤ 500
  Topological sort:  O(V + E) — always prefer over O(V²)
  Kruskal's MST:     O(E log E) — E ≤ 10^5 fine
  Bitmask DP (TSP):  O(2^V × V) — only for V ≤ 20

Algorithm Selection Summary

GRAPH SIZE    PROBLEM TYPE                    RECOMMENDED ALGORITHM
──────────────────────────────────────────────────────────────────────
V,E ≤ 10^5   Shortest unweighted             BFS
V,E ≤ 10^5   Shortest weighted positive      Dijkstra heap
V,E ≤ 10^3   Shortest any weights            Bellman-Ford
V ≤ 500      All-pairs shortest path         Floyd-Warshall
V,E ≤ 10^5   Connected components            BFS/DFS or DSU
V,E ≤ 10^5   Dependency ordering             Kahn's topological sort
V,E ≤ 10^5   Minimum spanning tree           Kruskal's or Prim's
V,E ≤ 10^5   Cycle detection (undirected)    DFS parent / BFS Pair
V,E ≤ 10^5   Cycle detection (directed)      DFS pathVisited / Kahn's
V ≤ 20       Visit all vertices minimum cost  Bitmask DP (TSP)
Grid N×M     Flood fill / component count    BFS/DFS with 4-dir
Grid N×M     Minimum path in grid            BFS or Dijkstra on grid

Progress Tracking

After solving each graph problem, record:

  1. Pattern — which of the 8 patterns does this belong to?
  2. Algorithm chosen — BFS, DFS, Dijkstra, Bellman-Ford, Floyd-Warshall, Topo sort, DSU, MST?
  3. State design — what did each node/state represent?
  4. Modelling trick — did you reverse the graph, add a virtual node, expand state?
  5. Edge cases — disconnected graph, unreachable target, negative weights?
  6. Time to solve — target 20 min easy, 35 min medium, 45 min hard

The decisive signal that graph pattern recognition is working: when you read "minimum cost to connect all points" and immediately think "MST — Kruskal's or Prim's, sort edges by Manhattan distance, DSU cycle check, stop at V-1 edges" — before reading the constraints or examples.

Suggested Quiz

Problem: 'given a 2D grid of 0s and 1s, count the number of islands (groups of connected 1s).' Which pattern does this follow?

1/6
Graph Practice Problems