Notes
All notes

Graphs (LeetCode #11)

A graph is nodes connected by edges. Most graph problems are one of four things: flood fill a region, traverse to reach something, order tasks, or detect a cycle. Grids are graphs too — each cell is a node with up to four neighbours. This post covers the thirteen NeetCode Graph problems.

The technique

Adjacency list. For each node, store its neighbours. Space \(O(V+E)\).

DFS. Go deep first; keep a seen set. BFS. Visit by distance using a queue — finds shortest paths on unweighted graphs. Mark visited on enqueue to avoid duplicates.

from collections import deque

def bfs(graph, start):
    dist = {start: 0}
    q = deque([start])
    while q:
        node = q.popleft()
        for nb in graph[node]:
            if nb not in dist:
                dist[nb] = dist[node] + 1
                q.append(nb)
    return dist

Topological sort (Kahn’s). Repeatedly remove a node with no remaining prerequisites; a cycle leaves some nodes unremoved.

Union-Find (from the DSA course) handles connectivity and cycle detection when edges arrive over time.

Number of Islands

The question. Count connected regions of '1' (4-directional).

Input:  [["1","1","0"],["0","1","0"],["0","0","1"]]  -> 2

The idea. Scan every cell; on unvisited land, count an island and flood fill its whole region to '0'.

Walk it through on the example. Cells are scanned row by row:

first land found sink wipes out running count
(0,0) (0,0), (0,1), (1,1) 1
(2,2) (2,2) 2
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.55cm, minimum height=0.5cm, font=\scriptsize\ttfamily}]
  \foreach \r in {0,1,2} { \foreach \c in {0,1,2} { \node[c, fill=blue!4] at (\c*0.61,-\r*0.56) {}; } }
  \node[c, fill=green!25] at (0,0) {1}; \node[c, fill=green!25] at (0.61,0) {1}; \node[c, fill=green!25] at (0.61,-0.56) {1};
  \node[c, fill=orange!25] at (1.22,-1.12) {1};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0.61,-1.95) {flood fill wipes one island at a time};
\end{tikzpicture}

Every other cell is '0' or already wiped by the time the scan reaches it, so it adds nothing.

def num_islands(grid):
    rows, cols = len(grid), len(grid[0])
    def sink(r, c):
        if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != "1":
            return
        grid[r][c] = "0"
        sink(r+1, c); sink(r-1, c); sink(r, c+1); sink(r, c-1)
    count = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "1":
                count += 1; sink(r, c)
    return count

Why it works. Each '1' belongs to exactly one island. The scan finds each island once (at its topmost-leftmost surviving cell), and sink destroys the whole island so it can never be counted again.

Complexity. \(O(R \cdot C)\) time (every cell is visited, then wiped once) and \(O(R \cdot C)\) worst-case stack space on a solid block of land.

Edge cases. All water → 0. All land → 1. The grid is mutated in place, so callers that need it must copy first.

Clone Graph

The question. Deep-copy a connected undirected graph.

The idea. A map from original node to clone. Create the clone, store it before recursing (to break cycles), then clone its neighbours.

Walk it through on 1: [2, 4], 2: [1, 3], 3: [2, 4], 4: [1, 3]. dfs(1) makes 1' and stores it, then recurses into neighbour 2: dfs(2) makes 2' and recurses into 1, which is already in the map and comes back as 1' — no infinite loop. Back at 1, neighbour 4 makes 4', whose neighbour 3 makes 3'; when 3' asks for 4 and 2, both are already stored. Each original node gets exactly one clone.

def clone_graph(node):
    clones = {}
    def dfs(n):
        if n is None:
            return None
        if n in clones:
            return clones[n]
        copy = Node(n.val)
        clones[n] = copy
        copy.neighbors = [dfs(nb) for nb in n.neighbors]
        return copy
    return dfs(node)

Why store before recursing. The clone must exist in the map before any of its neighbours are cloned; otherwise two mutually adjacent nodes would recurse into each other forever. The seen check then turns every repeated visit into a pointer to the already-built clone.

Complexity. \(O(V+E)\) time (each node and edge visited once) and \(O(V)\) space.

Edge cases. Empty graph (None) → None. A single node → a lone clone. Nodes are used as map keys, so they must be the original objects (identity), not just equal values.

Max Area of Island

The question. Return the size of the largest island.

The idea. Same flood fill, but the fill returns its region size and the scan keeps the maximum. Hitting a land cell starts a new region whose size is 1 + sizes of all four recursive calls (out-of-bounds or water contributes 0), so the total adds every cell exactly once.

Walk it through on [[1,1,0],[0,1,0],[0,0,0]]: sink(0,0) counts itself plus the fills of (0,1) and (1,1) for a total of 3; every later land cell is already 0, so the answer is 3.

def max_area_of_island(grid):
    rows, cols = len(grid), len(grid[0])
    def sink(r, c):
        if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != 1:
            return 0
        grid[r][c] = 0
        return 1 + sink(r+1, c) + sink(r-1, c) + sink(r, c+1) + sink(r, c-1)
    best = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == 1:
                best = max(best, sink(r, c))
    return best

Why the counts never double. Cells are zeroed on entry, so no recursive call can re-enter a counted cell; the 1 + chain therefore counts each region cell exactly once. Note this version uses integer 1/0, not the string '1' of Number of Islands.

Complexity. \(O(R \cdot C)\) time, \(O(R \cdot C)\) worst-case stack.

Edge cases. No land → 0. Tie islands → either maximal area. The grid is mutated, as in Number of Islands.

Pacific Atlantic Water Flow

The question. Return cells from which water can reach both the top/left (Pacific) and bottom/right (Atlantic) oceans, flowing to equal-or-lower neighbours.

The idea. Reverse it: from each ocean’s border, climb to equal-or-taller neighbours, and intersect the two reachable sets. Forward flow is many-to-many; backward reachability is two simple traversals. If water can flow downhill from cell X to the ocean, then from the ocean you can climb uphill back to X — the two directions visit exactly the same cells.

Walk it through on the classic example

heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]

Pacific starts are the top row and left column; Atlantic starts are the bottom row and right column. The climb from the Pacific border reaches up the 6→7→... ridge on the left and spreads to (2,2) (height 5, entered from a taller-or-equal neighbour), while the Atlantic climb comes up from the bottom. The cells reachable from both sides are [0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0] — for instance (2,2) is 5, which the Pacific reaches by climbing 1→2→4→5 and the Atlantic reaches from below.

def pacific_atlantic(heights):
    rows, cols = len(heights), len(heights[0])
    def reach(starts):
        seen, stack = set(starts), list(starts)
        while stack:
            r, c = stack.pop()
            for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
                nr, nc = r+dr, c+dc
                if (0 <= nr < rows and 0 <= nc < cols and (nr, nc) not in seen
                        and heights[nr][nc] >= heights[r][c]):
                    seen.add((nr, nc)); stack.append((nr, nc))
        return seen
    pac = reach([(r,0) for r in range(rows)] + [(0,c) for c in range(cols)])
    atl = reach([(r,cols-1) for r in range(rows)] + [(rows-1,c) for c in range(cols)])
    return [[r,c] for r,c in pac & atl]

Why not start the flow from every cell. Each forward flood could scan the whole grid, giving \(O((RC)^2)\). Two backward traversals visit each cell at most twice — once per ocean.

Why mark on push. A cell is added to seen before it enters the stack, so the check (nr, nc) not in seen never admits a duplicate and each cell is expanded once.

Complexity. \(O(R \cdot C)\) time and space.

Edge cases. One row or column — the Pacific and Atlantic borders overlap, so every cell qualifies. A single cell qualifies trivially.

Surrounded Regions

The question. Flip every 'O' region that is fully surrounded by 'X' (i.e. not connected to the border) to 'X'.

The idea. Any 'O' connected to the border is safe. So flood fill from every border 'O' and mark those safe (e.g. 'S'). Then flip the remaining 'O's to 'X' and the 'S's back to 'O'.

Walk it through on

X X X X          X X X X
X O O X          X X X X
X X O X    ->    X X X X
X O X X          X O X X

The scan finds exactly one border 'O', at (3,1), and marks it 'S'; nothing adjacent is 'O', so the region is done. The final sweep sees three untouched interior 'O's (they become 'X') and one 'S' (restored to 'O').

def solve(board):
    rows, cols = len(board), len(board[0])
    def mark(r, c):
        if 0 <= r < rows and 0 <= c < cols and board[r][c] == "O":
            board[r][c] = "S"
            mark(r+1, c); mark(r-1, c); mark(r, c+1); mark(r, c-1)
    for r in range(rows):
        mark(r, 0); mark(r, cols-1)
    for c in range(cols):
        mark(0, c); mark(rows-1, c)
    for r in range(rows):
        for c in range(cols):
            if board[r][c] == "O": board[r][c] = "X"
            elif board[r][c] == "S": board[r][c] = "O"

Why invert the problem. “Surrounded” means “not connected to the border”, which is hard to test directly — a region’s interior gives no local signal. Its complement, “connected to the border”, is one flood fill from known starting points, and the flip pass keeps everything else.

Complexity. \(O(R \cdot C)\) time and \(O(R \cdot C)\) worst-case stack.

Edge cases. A board of all 'O's survives (everything touches the border). One row or column — every 'O' is a border 'O'.

Rotting Oranges

The question. Each minute, every fresh orange adjacent to a rotten one becomes rotten. Return the minutes until no fresh orange remains, or -1 if impossible. This is multi-source BFS.

The idea. Start BFS from all rotten oranges at once (distance 0). Each level is one minute. Track how many fresh oranges get infected; if any remain, return -1.

Walk it through on [[2,1,1],[1,1,0],[0,1,1]]. Six cells start fresh, one already rotten at (0,0):

minute queue front newly rotten fresh left
0 (0,0) — 6
1 (0,1), (1,0) 2 4
2 (0,2), (1,1) 2 2
3 (2,1) (from (1,1)) 1 1
4 (2,2) (from (2,1)) 1 0

minutes tracks the largest t popped, so it ends at 4 and fresh == 0 gives the answer 4.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.55cm, minimum height=0.5cm, font=\scriptsize\ttfamily}]
  \foreach \r in {0,1,2} { \foreach \c in {0,1,2} { \node[c, fill=blue!4] at (\c*0.61,-\r*0.56) {}; } }
  \node[c, fill=orange!40] at (0,0) {2};
  \node[c, fill=orange!25] at (0.61,0) {1}; \node[c, fill=orange!25] at (0,-0.56) {1};
  \node[c, fill=orange!12] at (1.22,0) {1}; \node[c, fill=orange!12] at (0.61,-0.56) {1};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0.61,-1.95) {wavefronts expand from every source at once};
\end{tikzpicture}
from collections import deque

def oranges_rotting(grid):
    rows, cols = len(grid), len(grid[0])
    q = deque()
    fresh = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == 2: q.append((r, c, 0))
            elif grid[r][c] == 1: fresh += 1
    minutes = 0
    while q:
        r, c, t = q.popleft()
        minutes = max(minutes, t)
        for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
            nr, nc = r+dr, c+dc
            if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
                grid[nr][nc] = 2
                fresh -= 1
                q.append((nr, nc, t + 1))
    return minutes if fresh == 0 else -1

Why seed every rotten orange first. With all of them at t = 0, the BFS wavefronts expand simultaneously, so each cell’s infection time t+1 is the minimum over all initial sources — exactly “minutes since the nearest rotten neighbour”.

Why rewriting the grid works as seen. A fresh cell becomes 2 when enqueued, and the check grid[nr][nc] == 1 rejects it from then on, so no cell is queued twice; fresh only needs to count down.

Complexity. \(O(R \cdot C)\) time and space.

Edge cases. No fresh oranges anywhere → 0 minutes. A fresh orange walled off by 0s stays fresh → -1. Starting with only fresh oranges → the queue is empty and fresh > 0 → -1.

Walls and Gates

The question. Fill each empty room with the distance to its nearest gate (0), leaving walls (-1) alone. Impossible rooms stay INF.

The idea. Multi-source BFS from all gates at once, expanding outward. The first time a room is reached is its shortest distance — the same ring argument as Rotting Oranges, with distance carried in the cell itself.

Walk it through on the classic grid (INF = 2147483647):

INF  -1   0  INF          3  -1   0   1
INF INF INF  -1    ->     2   2   1  -1
INF  -1 INF  -1          1  -1   2  -1
  0  -1 INF INF          0  -1   3   4

Rings expand from both gates at once: wave 1 fills (0,3), (1,2), and (2,0); wave 2 fills (1,0), (1,1), and (2,2); wave 3 writes (3,2) = 3 from (2,2); finally (3,3) = 4 from (3,2). Walls and the unreachable-by-mistake cells are untouched, and a room behind walls would keep INF.

from collections import deque

def walls_and_gates(rooms):
    rows, cols = len(rooms), len(rooms[0])
    q = deque()
    for r in range(rows):
        for c in range(cols):
            if rooms[r][c] == 0:
                q.append((r, c))
    INF = 2147483647
    while q:
        r, c = q.popleft()
        for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
            nr, nc = r+dr, c+dc
            if 0 <= nr < rows and 0 <= nc < cols and rooms[nr][nc] == INF:
                rooms[nr][nc] = rooms[r][c] + 1
                q.append((nr, nc))
    return rooms

Why the == INF check is the visited set. Only never-reached rooms still equal INF, so a room is enqueued at most once — the first arrival, which in BFS order is the shortest distance from any gate. Since rooms are overwritten with rooms[r][c] + 1, walls (-1) and gates (0) never match and are left alone.

Complexity. \(O(R \cdot C)\) time, \(O(R \cdot C)\) queue space. Note the function now returns rooms for convenience.

Edge cases. No gates → nothing is written. A room behind walls keeps INF.

Course Schedule

The question. Given prerequisites [a, b] (b before a), can all courses be finished? This is cycle detection in a directed graph.

The idea. Topological sort with indegrees: repeatedly remove a course with no remaining prerequisites. A course with indegree 0 is free to take now; removing it frees its dependents. If a cycle exists, its nodes never reach indegree 0 and the count falls short.

Walk it through on num_courses = 2, prerequisites = [[1, 0]]. The graph is {0: [1], 1: []} and indegree = [0, 1]: queue starts as [0] (the only free course). Pop 0 (seen = 1), drop 1’s indegree to 0, enqueue it. Pop 1 (seen = 2). 2 == 2 → True. With a cycle [[1,0],[0,1]], indegree = [1, 1], the queue starts empty, and seen = 0 != 2 → False.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\ttfamily, inner sep=0pt},
  a/.style={->, thick}]
  \node[n, fill=green!15] (z) at (0,0) {0}; \node[n, fill=blue!8] (o) at (1.6,0) {1};
  \draw[a] (z) -- (o);
  \node[font=\scriptsize\ttfamily, anchor=north] at (0,-0.4) {indeg 0};
  \node[font=\scriptsize\ttfamily, anchor=north] at (1.6,-0.4) {indeg 1};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0.8,-0.9) {free courses first, then their dependents};
\end{tikzpicture}
def can_finish(num_courses, prerequisites):
    graph = {i: [] for i in range(num_courses)}
    indegree = [0] * num_courses
    for a, b in prerequisites:
        graph[b].append(a); indegree[a] += 1
    q = deque([i for i in range(num_courses) if indegree[i] == 0])
    seen = 0
    while q:
        node = q.popleft(); seen += 1
        for nb in graph[node]:
            indegree[nb] -= 1
            if indegree[nb] == 0: q.append(nb)
    return seen == num_courses

Why starting with every zero-indegree node matters. Courses with no prerequisites are independent roots; seeding only one would starve the rest of the graph even without a cycle. The queue then processes nodes in a valid order by construction: a node is emitted only after all its prerequisites are.

Complexity. \(O(V+E)\) time (each edge decrements one indegree) and \(O(V+E)\) space.

Edge cases. No prerequisites → trivially True (queue holds everything). A self-loop [a, a] is a cycle → False. Duplicate prerequisite pairs are tolerated because the indegrees still drain consistently.

Course Schedule II

The question. Return a valid order to take the courses, or [] if impossible.

The idea. Same Kahn’s algorithm, but record the order in which nodes are removed. If the order has fewer than n courses, a cycle exists.

Walk it through on num_courses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]. Indegrees are {0:0, 1:1, 2:1, 3:2}. Pop 0 → order = [0], indegrees of 1 and 2 drop to 0, both enqueue. Pop 1 → order = [0,1], 3 drops to 1. Pop 2 → order = [0,1,2], 3 drops to 0, enqueue. Pop 3 → order = [0,1,2,3]. Length 4 → return it. (Taking 2 before 1 would give [0,2,1,3] — any valid order is accepted.)

def find_order(num_courses, prerequisites):
    graph = {i: [] for i in range(num_courses)}
    indegree = [0] * num_courses
    for a, b in prerequisites:
        graph[b].append(a); indegree[a] += 1
    q = deque([i for i in range(num_courses) if indegree[i] == 0])
    order = []
    while q:
        node = q.popleft(); order.append(node)
        for nb in graph[node]:
            indegree[nb] -= 1
            if indegree[nb] == 0: q.append(nb)
    return order if len(order) == num_courses else []

Why the recorded order is valid. A course is appended only when every prerequisite has already been appended, so each pair [a, b] lands with b before a. The length check reuses the cycle signal from Course Schedule: a short order means unreachable nodes remain.

Complexity. \(O(V+E)\) time and space.

Edge cases. No prerequisites → courses come out in index order. A cycle anywhere → [] regardless of the valid parts.

Redundant Connection

The question. A connected graph with n nodes started as a tree (no cycles) and one extra edge was added. Return the edge that can be removed. Return the last such edge in the input.

The idea. Add edges one by one with Union-Find. The first edge whose two endpoints are already connected creates the cycle — that is the answer.

Walk it through on edges = [[1,2],[1,3],[2,3]]. Parents start as {1:1, 2:2, 3:3}. union(1,2): different roots, attach 1 under 2 → {1:2, 2:2, 3:3}. union(1,3): find(1) = 2, find(3) = 3, attach → {1:2, 2:3, 3:3}. union(2,3): find(2) = 3 and find(3) = 3 — already connected → return [2,3].

\begin{tikzpicture}[font=\rmfamily, >=stealth]
  \node[draw, thick, circle, minimum size=0.6cm, font=\small\ttfamily] (a) at (0,0) {1};
  \node[draw, thick, circle, minimum size=0.6cm, font=\small\ttfamily] (b) at (1.5,0) {2};
  \node[draw, thick, circle, minimum size=0.6cm, font=\small\ttfamily] (c) at (3.0,0) {3};
  \draw[thick] (a) -- (b); \draw[thick] (b) -- (c);
  \draw[thick, dashed, orange!80!black] (a) to[bend left=30] (c);
  \node[font=\scriptsize\ttfamily, text=orange!75!black, anchor=north] at (1.5,-0.5) {already connected -> cycle};
\end{tikzpicture}
class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n + 1))
    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x
    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb: return False
        self.parent[ra] = rb
        return True

def find_redundant_connection(edges):
    uf = UnionFind(len(edges))
    for a, b in edges:
        if not uf.union(a, b):
            return [a, b]
    return []

Why “already connected” means “cycle”. Union-Find maintains the invariant that each set is a tree. Joining two different sets keeps it a tree; joining two nodes inside one set adds a second path between them — a cycle — so that edge is the redundant one. Scanning the input in order and returning the first failure also satisfies the “last such edge” rule when several could qualify.

Complexity. \(O(n \alpha(n)) \approx O(n)\) time, \(O(n)\) space. n = len(edges) because a connected tree-plus-one-edge on n nodes always has exactly n edges.

Edge cases. Nodes are 1-indexed, hence range(n + 1). Exactly one answer is guaranteed.

Number of Connected Components in an Undirected Graph

The question. Return the number of connected components in a graph with n nodes and edges.

The idea. Union every edge; then count the distinct roots. On n = 5, edges = [[0,1],[1,2],[3,4]], the unions fuse {0,1,2} and {3,4}, so find yields two distinct roots → 2.

def count_components(n, edges):
    uf = UnionFind(n)
    for a, b in edges:
        uf.union(a, b)
    return len({uf.find(i) for i in range(n)})

Why find every node, not just count unions. An isolated node (no edges at all) is its own component and only shows up when find is called on it. The set comprehension collects every node’s final root, so both islands and loners are counted once each.

Complexity. \(O(n + E)\) time, \(O(n)\) space.

Edge cases. No edges → n (every node alone). n = 1 → 1.

Graph Valid Tree

The question. Does the graph form a valid tree? A tree with n nodes has exactly n-1 edges and is fully connected with no cycle.

The idea. Two checks: len(edges) == n - 1, and Union-Find finds no cycle while adding the edges. On n = 5, edges = [[0,1],[0,2],[0,3],[1,4]] the count matches and all four unions join different sets → True; on [[0,1],[1,2],[2,0]] the third union finds 0 and 2 already connected → False.

def valid_tree(n, edges):
    if len(edges) != n - 1:
        return False
    uf = UnionFind(n)
    for a, b in edges:
        if not uf.union(a, b):     # cycle
            return False
    return True

Why the edge count comes first. It is \(O(1)\) and rejects the two non-tree extremes immediately: too many edges guarantee a cycle, too few guarantee disconnectedness. After it passes, acyclicity alone is enough — an acyclic graph with n-1 edges on n nodes is necessarily one connected tree.

Complexity. \(O(n + E)\) time, \(O(n)\) space.

Edge cases. n = 1 with no edges → a valid single-node tree (0 == 1-1). A self-loop is a cycle → rejected at union time.

Word Ladder

The question. Transform beginWord to endWord, changing one letter at a time, every intermediate in wordList. Return the length of the shortest sequence, or 0.

The idea. Nodes are words, edges are one-letter differences; the shortest path is a BFS. Generate one-letter variants and keep those in the dictionary.

Walk it through on begin = "hit", end = "cog", wordList = [hot,dot,dog,lot,log,cog]:

steps words popped neighbours enqueued
1 hit hot
2 hot dot, lot
3 dot, lot dog (from dot), log (from lot)
4 dog, log cog (from either)
5 cog is end → return 5

Only dictionary words are queued, so hog or cit are never explored.

def ladder_length(begin, end, word_list):
    words = set(word_list)
    if end not in words: return 0
    q, seen = deque([(begin, 1)]), {begin}
    while q:
        word, steps = q.popleft()
        if word == end: return steps
        for i in range(len(word)):
            for ch in "abcdefghijklmnopqrstuvwxyz":
                cand = word[:i] + ch + word[i+1:]
                if cand in words and cand not in seen:
                    seen.add(cand); q.append((cand, steps + 1))
    return 0

Why mark on enqueue. Every generated candidate is checked against seen before it enters the queue, so each dictionary word is expanded once. The steps + 1 it carries is its shortest distance, because BFS pops words in increasing step order.

Complexity. \(O(N \cdot L \cdot 26)\) time for \(N\) words of length \(L\) (26 variants per position) and \(O(N \cdot L)\) space.

Edge cases. endWord absent from the list → 0 (checked up front). beginWord need not be in the list. Length counts words, so a direct one-letter change returns 2.

Pitfalls

QQuestionSelf-check

Why does Kahn’s algorithm detect a directed cycle? When do you use multi-source BFS?

ASolution

A cycle leaves every node in it with a positive indegree forever, so those nodes are never emitted and the ordering is too short. Multi-source BFS applies when the distance is measured from any of several starting points (all rotten oranges, all gates) — pushing all sources at distance 0 finds each cell’s nearest source in one sweep.

Next: Advanced Graphs (LeetCode #12) — weighted shortest paths and MSTs.