Graphs
Nodes connected by edges - networks, maps, dependencies and grids.
- current
- visited / done
Build the adjacency list
Each edge is added in both directions: 0: [1], 1: [0, 2], 2: [1], 3: [4], 4: [3].
VARIABLES
- count
- 0
- seen
- set()
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
A graph is a set of vertices and edges. Interview graphs are usually stored as adjacency lists: each node maps to its neighbours.
Why it matters
Anything with relationships - friends, flights, prerequisites, grid cells - is a graph problem in disguise.
Think of it like this
A metro map: stations are nodes and tracks are edges.
Use it when
- Connectivity and counting components
- Paths between things
- Grids where cells connect to their neighbours
Avoid it when
- Strict hierarchies with one parent each - tree techniques are simpler
- Dense graphs where an adjacency matrix is easier
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Build an adjacency list | O(V + E) | O(V + E) |
| BFS or DFS traversal | O(V + E) | O(V) |
| Check one edge (adjacency list) | O(degree) | O(1) |
Often confused with: trees - graphs with no cycles and exactly one path between any two nodes.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- An r × c grid is a graph with up to 4 edges per cell
- Always track visited nodes - graphs can have cycles
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Adding only one direction for undirected edges
- Not tracking visited nodes - infinite loops on cycles
- Missing isolated nodes that have no edges
Edge cases to test
- No edges at all - every node is its own component
- Self-loops and duplicate edges
- A disconnected graph
Knowledge check
Quick check to lock in the intuition.
Traversing a graph with V nodes and E edges using BFS or DFS costs…
Practice
Apply what you just watched on real interview problems.