Module 5 · Drill 1 · graph reps

Graph traversal drills

Three problems, three different traversal flavors. Each one shows up in FAANG loops verbatim.

1 — Number of islands (DFS or BFS)

2 — Course schedule (cycle in directed graph / topological sort)

Given numCourses and a list of [a, b] prerequisites meaning "to take a, you must take b first," return whether you can finish all courses (no cycle).

3 — Word ladder (BFS on implicit graph)

Shortest transformation sequence from begin to end changing one character at a time, with each intermediate word in word_list. Return the length of the shortest sequence (counting both endpoints), or 0 if impossible.

Solutions

1 — Number of islands

def num_islands(grid):
    if not grid: return 0
    rows, cols = len(grid), len(grid[0])
    count = 0

    def dfs(r, c):
        if r < 0 or r >= rows or c < 0 or c >= cols: return
        if grid[r][c] != '1': return
        grid[r][c] = '0'   # sink the land
        dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)

    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == '1':
                count += 1
                dfs(r, c)
    return count
  
function numIslands(grid) {
  if (!grid.length) return 0;
  const rows = grid.length, cols = grid[0].length;
  let count = 0;
  function dfs(r, c) {
    if (r < 0 || r >= rows || c < 0 || c >= cols) return;
    if (grid[r][c] !== '1') return;
    grid[r][c] = '0';
    dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1);
  }
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (grid[r][c] === '1') { count++; dfs(r, c); }
    }
  }
  return count;
}
  
function numIslands(grid: string[][]): number {
  if (!grid.length) return 0;
  const rows = grid.length, cols = grid[0].length;
  let count = 0;
  function dfs(r: number, c: number): void {
    if (r < 0 || r >= rows || c < 0 || c >= cols) return;
    if (grid[r][c] !== '1') return;
    grid[r][c] = '0';
    dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1);
  }
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (grid[r][c] === '1') { count++; dfs(r, c); }
    }
  }
  return count;
}
  
O(rows × cols) time, O(rows × cols) space for recursion (BFS variant uses O(min(rows,cols)) for the queue). Sinking visited land to '0' is O(1) extra space — and is the in-place trick interviewers love.

2 — Course schedule (cycle detection)

from collections import defaultdict, deque

def can_finish(num_courses, prereqs):
    # Kahn's algorithm — BFS topological sort
    graph = defaultdict(list)
    indeg = [0] * num_courses
    for a, b in prereqs:
        graph[b].append(a)   # b -> a (b must come first)
        indeg[a] += 1
    q = deque(i for i in range(num_courses) if indeg[i] == 0)
    done = 0
    while q:
        v = q.popleft()
        done += 1
        for u in graph[v]:
            indeg[u] -= 1
            if indeg[u] == 0:
                q.append(u)
    return done == num_courses
  
function canFinish(numCourses, prereqs) {
  const graph = Array.from({ length: numCourses }, () => []);
  const indeg = new Array(numCourses).fill(0);
  for (const [a, b] of prereqs) { graph[b].push(a); indeg[a]++; }
  const q = []; let head = 0;
  for (let i = 0; i < numCourses; i++) if (indeg[i] === 0) q.push(i);
  let done = 0;
  while (head < q.length) {
    const v = q[head++];
    done++;
    for (const u of graph[v]) {
      if (--indeg[u] === 0) q.push(u);
    }
  }
  return done === numCourses;
}
  
function canFinish(numCourses: number, prereqs: number[][]): boolean {
  const graph: number[][] = Array.from({ length: numCourses }, () => []);
  const indeg = new Array(numCourses).fill(0);
  for (const [a, b] of prereqs) { graph[b].push(a); indeg[a]++; }
  const q: number[] = []; let head = 0;
  for (let i = 0; i < numCourses; i++) if (indeg[i] === 0) q.push(i);
  let done = 0;
  while (head < q.length) {
    const v = q[head++];
    done++;
    for (const u of graph[v]) {
      if (--indeg[u] === 0) q.push(u);
    }
  }
  return done === numCourses;
}
  
O(V + E) time and space. Kahn's algorithm: start with all in-degree-0 nodes, process them, decrement neighbors. If we processed all nodes, no cycle. If any are stuck with non-zero in-degree, they're part of a cycle. Equivalent DFS approach with three-color marking also works.

3 — Word ladder length

from collections import defaultdict, deque

def ladder_length(begin, end, word_list):
    word_set = set(word_list)
    if end not in word_set: return 0

    # build pattern index: for each pattern (e.g., 'h*t'), list of words matching
    L = len(begin)
    patterns = defaultdict(list)
    for w in word_set | {begin}:
        for i in range(L):
            patterns[w[:i] + '*' + w[i+1:]].append(w)

    visited = {begin}
    q = deque([(begin, 1)])
    while q:
        word, depth = q.popleft()
        if word == end: return depth
        for i in range(L):
            pat = word[:i] + '*' + word[i+1:]
            for nxt in patterns[pat]:
                if nxt not in visited:
                    visited.add(nxt)
                    q.append((nxt, depth + 1))
            patterns[pat] = []   # prevent revisits
    return 0
  
function ladderLength(begin, end, wordList) {
  const wordSet = new Set(wordList);
  if (!wordSet.has(end)) return 0;

  const L = begin.length;
  const patterns = new Map();
  function addPatterns(w) {
    for (let i = 0; i < L; i++) {
      const p = w.slice(0, i) + '*' + w.slice(i + 1);
      if (!patterns.has(p)) patterns.set(p, []);
      patterns.get(p).push(w);
    }
  }
  for (const w of wordSet) addPatterns(w);
  if (!wordSet.has(begin)) addPatterns(begin);

  const visited = new Set([begin]);
  const q = [[begin, 1]]; let head = 0;
  while (head < q.length) {
    const [word, depth] = q[head++];
    if (word === end) return depth;
    for (let i = 0; i < L; i++) {
      const p = word.slice(0, i) + '*' + word.slice(i + 1);
      const neighbors = patterns.get(p) || [];
      for (const nxt of neighbors) {
        if (!visited.has(nxt)) { visited.add(nxt); q.push([nxt, depth + 1]); }
      }
      patterns.set(p, []);   // prevent revisits
    }
  }
  return 0;
}
  
function ladderLength(begin: string, end: string, wordList: string[]): number {
  const wordSet = new Set(wordList);
  if (!wordSet.has(end)) return 0;

  const L = begin.length;
  const patterns = new Map<string, string[]>();
  function addPatterns(w: string): void {
    for (let i = 0; i < L; i++) {
      const p = w.slice(0, i) + '*' + w.slice(i + 1);
      if (!patterns.has(p)) patterns.set(p, []);
      patterns.get(p)!.push(w);
    }
  }
  for (const w of wordSet) addPatterns(w);
  if (!wordSet.has(begin)) addPatterns(begin);

  const visited = new Set<string>([begin]);
  const q: [string, number][] = [[begin, 1]]; let head = 0;
  while (head < q.length) {
    const [word, depth] = q[head++];
    if (word === end) return depth;
    for (let i = 0; i < L; i++) {
      const p = word.slice(0, i) + '*' + word.slice(i + 1);
      const neighbors = patterns.get(p) || [];
      for (const nxt of neighbors) {
        if (!visited.has(nxt)) { visited.add(nxt); q.push([nxt, depth + 1]); }
      }
      patterns.set(p, []);
    }
  }
  return 0;
}
  
O(N × L²) time, O(N × L²) space where N = words, L = word length. Naive "compare each pair" is O(N² × L). The pattern index gives O(L) neighbor enumeration per word. Clearing patterns after use prevents re-traversal. BFS guarantees shortest path on this implicit graph.