DSA & Implementation · advanced

Graphs

BFS/DFS, topo sort, union-find.

dsagraphs

Mental model

Most graph problems are one of a few templates: reachability/components (DFS/BFS), shortest path (BFS for unweighted, Dijkstra for weighted), ordering (topological sort), or connectivity (union-find). The skill is recognizing the template and modeling the input as nodes and edges.

How to study Graphs

Begin by restating the mental model in your own words, then connect it to a concrete system you have built or operated. Name the mechanism, the constraint it addresses, and the trade-off it introduces. Use VisuAlgo — Graph Traversal to check details, but close the source before writing your explanation. Retrieval is the learning step; rereading is only preparation.

Next, compare Graphs with Shortest Path. Ask what changes in correctness, latency, resource use, operability, and failure recovery. Complete Number of islands, Number of Islands, Course Schedule and preserve the command, input, output, and one failed attempt as evidence. Finish by explaining the idea without jargon to someone who has not studied the track.

Proof of understanding

  • Explain the mechanism from first principles and identify the state it reads or changes.
  • Give one situation where the concept is the right choice and one where it is not.
  • Predict a realistic failure mode before running the drill, then compare the prediction with evidence.
  • Connect the result to a roadmap or build artifact instead of treating the concept as isolated trivia.

Common mistakes

  • No visited set — revisiting nodes and looping forever
  • Using DFS for shortest path on an unweighted graph instead of BFS
  • Not handling disconnected components

Learn from primary sources

Practice and explain it back

Number of islands

Given a grid of '1' (land) and '0' (water), count the connected land masses (4-directionally).

Expected evidence: A single integer — the island count.

Open the interactive drill →

Number of Islands

LeetCode #200 — Number of Islands. Solve on LeetCode, then implement here if you want it in your drill queue. https://leetcode.com/problems/number-of-islands/

Expected evidence: Pass all LeetCode test cases for this problem.

Open the interactive drill →

Course Schedule

LeetCode #207 — Course Schedule. Solve on LeetCode, then implement here if you want it in your drill queue. https://leetcode.com/problems/course-schedule/

Expected evidence: Pass all LeetCode test cases for this problem.

Open the interactive drill →

Review prompts

  • In BFS, do you mark a node visited when you enqueue it or when you dequeue it — and why does it matter?

Build evidence

Use a roadmap capstone to turn this concept into working evidence.

Prerequisites

Related concepts

Learning paths