Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns

Topic · 7 patterns

Graphs patterns

Model the problem as nodes and edges first; the algorithm follows from what you're asked. BFS and DFS cover reachability, components and unweighted shortest paths, topological sort orders dependencies, union-find tracks groups as they merge, Dijkstra, Bellman-Ford and Floyd-Warshall find weighted shortest paths, and a minimum spanning tree connects everything at the least cost.

The patterns

  1. Graph BFS / DFS

    O(V + E)

    Explore with a queue (BFS) or recursion/stack (DFS), marking visited so you never revisit a node.

    Spot it: Grid or graph: islands, flood fill, regions, clone, reachability, or fewest steps on an unweighted / implicit graph.

    Learn first: Tree BFS (Level Order), Tree DFS (Paths & Recursion)

    Learn Graph BFS / DFSCheat sheet and practice
  2. Topological Sort

    O(V + E)

    Repeatedly take nodes with in-degree 0 (Kahn's), or DFS and emit on the way out; a cycle means no ordering.

    Spot it: Prerequisites, dependencies, build order on a DAG; cycle detection in a directed graph; DP over a DAG; order from comparisons (alien dictionary).

    Learn first: Graph BFS / DFS

    Learn Topological SortCheat sheet and practice
  3. Union-Find (Disjoint Set)

    ~O(α(n))

    Each set has a representative; union merges two roots, find returns a root. Path compression + union by rank keep it near-constant.

    Spot it: Connectivity with only additions: count components, group equivalents (accounts, equations), redundant edge in an undirected graph, Kruskal.

    Learn Union-FindCheat sheet and practice
  4. Dijkstra (Weighted Shortest Path)

    O(E log V)

    Greedily expand the closest unfinalized node using a min-heap keyed by distance-so-far.

    Spot it: Min time/cost/effort on a weighted graph or grid with non-negative weights; minimax paths; max-probability paths (weights <= 1).

    Learn first: Graph BFS / DFS, Top-K Elements

    Learn DijkstraCheat sheet and practice
  5. Bellman-Ford

    O(V · E)

    Relax every edge V−1 times; the k-stops variant just caps the number of relaxation rounds at k+1.

    Spot it: Shortest path with negative edge weights, detect a negative cycle, or cheapest path using at most K edges / stops.

    Learn first: Dijkstra (Weighted Shortest Path)

    Learn Bellman-FordCheat sheet and practice
  6. Floyd-Warshall

    O(V³)

    For every intermediate node k, test whether routing i→k→j beats the current i→j distance.

    Spot it: Shortest paths or reachability between all pairs on a small graph: V up to ~400-500, or a small state graph like 26 letters.

    Learn first: 1D / Fibonacci-style

    Learn Floyd-WarshallCheat sheet and practice
  7. Minimum Spanning Tree

    O(E log V)

    Kruskal: sort edges, add the cheapest that doesn't form a cycle (union-find). Prim: grow from a node via a heap.

    Spot it: Connect all points/cities at minimum total cost, or the minimax (bottleneck) edge between two vertices — it lies on the MST.

    Learn first: Union-Find (Disjoint Set), Greedy

    Learn Minimum Spanning TreeCheat sheet and practice

Which one? Match the signal

If the problem saysReach for
Grid/graph: islands, flood fill, connected regions, clone, unweighted shortest pathGraph BFS / DFSO(V+E)
Prerequisites / dependencies / build order on a DAG; "can you finish?"Topological SortO(V+E)
Connectivity / "number of components" / merge groups / redundant edgeUnion-Find~O(α)
Weighted shortest path, non-negative weights (min time/effort/cost)DijkstraO(E log V)
Shortest path with negative weights, or "cheapest within at most k stops"Bellman-FordO(V·E)
Shortest paths between ALL pairs of nodes (small graph)Floyd-WarshallO(V³)
Connect every node at minimum total costMST (Kruskal/Prim)O(E log V)

Easy to confuse

  • Reconstruct Itinerary looks like Graph BFS / DFS, but it’s Eulerian Path / Circuit (Hierholzer)

    Every ticket (edge) must be used exactly once: Hierholzer, not plain DFS with backtracking.

  • Cheapest Flights Within K Stops looks like Dijkstra (Weighted Shortest Path), but it’s Bellman-Ford

    The stop limit invalidates per-vertex optimality; k+1 Bellman-Ford rounds (or Dijkstra over (city, stops)).

  • Path with Maximum Probability looks like Bellman-Ford, but it’s Dijkstra (Weighted Shortest Path)

    Multiplying probabilities <= 1 never increases a path's value, so Dijkstra with a max-heap is valid.

  • Path With Minimum Effort looks like Graph BFS / DFS, but it’s Dijkstra (Weighted Shortest Path)

    Cost is the max edge on the path: minimax Dijkstra (or binary search + BFS, or union-find).

  • Swim in Rising Water looks like Graph BFS / DFS, but it’s Dijkstra (Weighted Shortest Path)

    Minimax over cell heights; plain BFS ignores the cost.

  • Longest Increasing Path in a Matrix looks like Grid / Matrix DP, but it’s Topological Sort

    Moves go in four directions, so there is no row-major order; the strict increase makes a DAG for memo DFS / Kahn.

Used together

  • Binary Search on the Answer + Graph BFS / DFS

    When: minimise the maximum height/effort along a path. Minimax path costs become reachability at a threshold.

  • Offline Query Processing + Union-Find (Disjoint Set)

    When: queries 'connected using edges with weight < limit'; reverse deletions. Each query asks connectivity under a weight limit; sorted processing makes it monotone.

  • Minimum Spanning Tree + Union-Find (Disjoint Set) + Greedy

    When: connect all nodes at minimum cost. Kruskal is the canonical three-way composition.

  • Topological Sort + 1D / Fibonacci-style

    When: longest path / number of paths in a DAG; longest increasing path in a grid. DP needs an acyclic evaluation order.

Where to start

then the The 128 and The 365 sheets

Graph BFS / DFS

  • Flood FillEasy
  • Number of IslandsMedium

Topological Sort

  • Course ScheduleMedium
  • Course Schedule IIMedium

Union-Find (Disjoint Set)

  • Number of ProvincesMedium

Dijkstra (Weighted Shortest Path)

  • Shortest Routes IMedium
  • Network Delay TimeMedium

Bellman-Ford

  • Network Delay TimeMedium
  • Cheapest Flights Within K StopsMedium

Floyd-Warshall

  • Find the City With the Smallest Number of Neighbors at a Threshold DistanceMedium
  • Shortest Routes IIMedium

Minimum Spanning Tree

  • Road ReparationMedium

Further reading

free, outside Lessgo
  • Graph Theory playlistWilliam Fiset

    Best visual explanations: BFS/DFS, topo sort, Dijkstra, Bellman-Ford, MST, flows.

  • Graph TraversalUSACO Guide

    BFS/DFS and connected components with graded problems.

  • Disjoint Set Unioncp-algorithms

    Path compression + union by size, with applications.

  • Dijkstracp-algorithms

    Proof plus the priority-queue implementation you will actually write.

  • Topological sortingcp-algorithms

    DFS-based topo order; pair with Kahn's for interviews.

  • Shortest paths visualizerVisuAlgo

    Step through Bellman-Ford and Dijkstra on your own graphs.

  • Graph cheatsheetTech Interview Handbook

    Interview-grade graph representation and problem list.

← TreesAll 49 patternsDynamic Programming →
TodayReviewPatternsProblems