Expert: advanced patterns and interviews · Graphs · topic 46 of 61 · 40 min
Graph problem patterns
Explanation
Spotting a graph in disguise
Problems rarely say "here is a graph". Ask two questions. What are the things? Those are the vertices. What connects two things? Those are the edges. The edges do not have to be stored anywhere; often you generate them when you need them. Such a graph is called an implicit graph.
| The problem sounds like… | Vertices | Edges | Tool |
|---|---|---|---|
| Fewest moves on a board or grid | Cells or board states | One legal move | BFS |
| Can everything be finished? In what order? | Tasks | Must come before | Topological sort |
| Split into two groups with no conflict inside a group | People or items | A conflict | Bipartite check |
| Paint or count a connected area | Pixels or cells | Same colour, side by side | Flood fill (DFS or BFS) |
| Change one letter at a time | Words | Differ in one letter | BFS on an implicit graph |
| Cheapest route | Places | Roads with costs | Dijkstra |
Bipartite check: two colours
A graph is bipartite if you can split its vertices into two groups so that every edge goes between the groups, never inside one. Think of planning two exam sessions so that no two students who share a bench sit the same session.
To check it, colour the start vertex 0, colour its neighbours 1, their neighbours 0, and so on, with BFS or DFS. If you ever find an edge whose two ends have the SAME colour, the graph is not bipartite. A graph is bipartite exactly when it has no cycle of odd length; a triangle can never be two-coloured. The graph may have several components, so start a new colouring from every uncoloured vertex. Time O(V + E).
Flood fill
Flood fill is the paint-bucket tool in a drawing app. Start at one pixel, remember its old colour, and repaint every pixel connected to it (up, down, left, right) that has that old colour. It is DFS or BFS on a grid where the edges join neighbouring pixels of the same colour. One trap: if the new colour equals the old colour, nothing should change, but a search that uses "has the old colour" as its visited test would keep finding the same pixels forever. Return straight away in that case.
Cloning a graph
To make a deep copy of a graph of node objects, walk it with BFS or DFS and keep a dictionary from each original node to its copy. Create a copy the first time you see a node; after that, always reuse the copy from the dictionary. The dictionary also works as the visited set, so cycles do not cause an endless loop.
class Node:
def __init__(self, val, neighbors=None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
def clone_graph(node):
if node is None:
return None
copies = {node: Node(node.val)}
stack = [node]
while stack:
cur = stack.pop()
for nb in cur.neighbors:
if nb not in copies:
copies[nb] = Node(nb.val)
stack.append(nb)
copies[cur].neighbors.append(copies[nb])
return copies[node]
a, b = Node(1), Node(2)
a.neighbors.append(b)
b.neighbors.append(a)
c = clone_graph(a)
print(c.val, c.neighbors[0].val, c is a, c.neighbors[0].neighbors[0] is c)
# Output: 1 2 False TrueWord ladder: BFS on an implicit graph
Word ladder: turn "hit" into "cog" by changing one letter at a time, where every word on the way must be in a given word list. Each word is a vertex, and two words are joined when they differ in exactly one letter. The fewest steps is a BFS question. You do not build the edges in advance: for the current word, try every position and every letter a to z, and keep the results that are in the word set. With N words of length L, that is about N × L × 26 candidates, and each set lookup hashes a string of length L.
Remove a word from the set (or mark it visited) when you add it to the queue, so it is never used twice. The usual answer counts WORDS in the sequence, so "hit → hot → dot → dog → cog" has length 5.
Common mistakes
- Checking bipartiteness only from vertex 0 when the graph has several components. Fix: loop over every vertex and colour each uncoloured one.
- Flood fill with the new colour equal to the old colour, which never ends. Fix: return the image unchanged straight away.
- Word ladder: forgetting that the end word must be in the list, or counting steps when the problem counts words. Fix: read the rule and test the smallest case.
- Clone graph: making a new copy every time a node is seen, which breaks shared neighbours and loops forever on cycles. Fix: one dictionary from original to copy.
- Recursive flood fill on a large image, causing RecursionError. Fix: an explicit stack or a queue.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Graph problem patterns · 1/8
This lesson shows how to spot graph problems that do not say "graph", and the patterns that solve them.
Prefer a video by a teacher? Find free videos on “graph interview patterns bipartite flood fill word ladder clone graph” on YouTube ↗
In real life: Two question-paper sets in an exam hall
A college wants students on the same bench to get different question-paper sets, A and B, so they cannot copy. Students are vertices and "share a bench" is an edge. Giving out two sets is exactly two-colouring the graph. If three students share a bench, the triangle makes two sets impossible, and the college needs a third set. Real seating plans also look at rows and columns, but the bipartite check is the core of it.
from collections import deque
benches = {"Asha": ["Ravi"], "Ravi": ["Asha", "Meena"], "Meena": ["Ravi"], "Kabir": []}
paper = {}
ok = True
for student in benches:
if student in paper:
continue
paper[student] = "A"
queue = deque([student])
while queue:
u = queue.popleft()
for v in benches[u]:
if v not in paper:
paper[v] = "B" if paper[u] == "A" else "A"
queue.append(v)
elif paper[v] == paper[u]:
ok = False
print(ok, paper)Practice (0/4 done)
Write is_bipartite(graph) for an UNDIRECTED graph with vertices 0 to n − 1, where graph[u] is the list of neighbours of u (every edge is listed at both ends). The graph may have several components. Return True if the vertices can be coloured with two colours so that every edge joins different colours. An empty graph is bipartite. Example: is_bipartite([[1, 3], [0, 2], [1, 3], [0, 2]]) returns True.
Write flood_fill(image, sr, sc, color). image is a list of lists of ints. Starting at row sr, column sc, repaint that pixel and every pixel connected to it up, down, left or right that has the SAME original colour, using color. Change image in place and return it. If color equals the original colour, return image unchanged. Use a stack or queue (one test is a 100 × 100 image).
Write word_ladder_length(begin, end, words). You may change one letter at a time, and every word you step on (including end) must be in the list words; begin does not have to be in it. All words are lowercase and the same length, and begin != end. Return the number of WORDS in the shortest sequence from begin to end (both counted), or 0 if there is none. Use BFS. Example: "hit" → "hot" → "dot" → "dog" → "cog" gives 5.
Write shortestPath(graph, start, goal) in JavaScript. graph is an object mapping a node name to an array of neighbour names (DIRECTED edges); a node that is not a key has no outgoing edges. Return an array with the nodes of a path from start to goal with the FEWEST edges (both ends included), [start] if start === goal, and [] if goal cannot be reached. Use BFS, look at neighbours in the listed order and remember the first parent of each node; return the path that this BFS finds.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Topological sortGraphs · same module
- Depth-first search (DFS)Graphs · same module
- Minimum spanning treesTries, union-find and bit manipulation
- Core DSA patterns in C++C++ Programming (modern C++ and DSA) · Competitive programming, interviews and careers
- Traversals: DFS and BFSTrees and binary search trees
- Tries (prefix trees)Tries, union-find and bit manipulation
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
A graph is bipartite exactly when it has no…
Answer: Cycle of odd length
An odd cycle forces two neighbours to share a colour; even cycles and trees are fine.
Flood fill is called with a new colour equal to the old colour, and the code uses "pixel has the old colour" as its only visited test. What happens?
Answer: It keeps revisiting the same pixels and may never end
Repainted pixels still have the "old" colour, so they are found again and again. Return early.
In word ladder, what are the vertices and the edges?
Answer: Words; two words that differ in exactly one letter
It is an implicit graph whose edges are generated by changing one letter.
Why does clone graph keep a dictionary from original node to copy?
Answer: To reuse each copy and to stop at cycles
Every original has exactly one copy, and a node already in the dictionary is not explored again.
"Fewest moves for a chess knight from one square to another." Which tool fits best?
Answer: BFS over the board squares
Squares are vertices, knight moves are unweighted edges, so BFS gives the fewest moves.
An undirected graph has 5 edges. What do all the degrees add up to?Related
Answer: 10
Every edge touches two vertices, so it adds 2 to the total: 2 × 5 = 10.
What is the time of BFS on a graph stored as an adjacency list?Related
Answer: O(V + E)
Each vertex is queued once and each edge is checked a constant number of times.
How do you count the connected components of an undirected graph?Related
Answer: Start a DFS from every unvisited vertex and count the starts
Each new start finds a piece no earlier DFS could reach.
Kahn's algorithm outputs 4 vertices of a 6-vertex graph. What does that tell you?Related
Answer: The graph has a cycle
Vertices on a cycle never reach in-degree 0, so they are left out.
From Topological sort
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- This is the last topic of “Graphs”. The module exam comes next.
- Module 9 exam: Graphs · 14 questions · 25 min, without help. 6 topics of this module still to finish first.
- Then the next module, Tries, union-find and bit manipulation. 61 topics left in the course before the final exam.