Pattern #47

Graphs

Important interview questions, thinking patterns, Adjacency List setup, Visited Set rules, Unweighted BFS shortest paths, Grid-to-Graph conversion, and Go templates.

Must Solve

20 core questions — solve these first.

  1. 1.Number of Islands
    medium
  2. 2.Clone Graph
    medium
  3. 3.Number of Provinces
    medium
  4. 4.Flood Fill
    easy
  5. 5.Rotting Oranges
    medium
  6. 6.Course Schedule
    medium
  7. 7.Course Schedule II
    medium
  8. 8.Pacific Atlantic Water Flow
    medium
  9. 9.Surrounded Regions
    medium
  10. 10.Max Area of Island
    medium
  11. 11.Graph Valid Tree
    medium
  12. 12.Redundant Connection
    medium
  13. 13.Is Graph Bipartite?
    medium
  14. 14.Word Ladder
    hard
  15. 15.Open the Lock
    medium
  16. 16.Evaluate Division
    medium
  17. 17.Reorder Routes to Make All Paths Lead to Zero
    medium
  18. 18.Shortest Path in Binary Matrix
    medium
  19. 19.Network Delay Time
    medium
  20. 20.Cheapest Flights Within K Stops
    medium

Also Important

10 more questions worth practicing.

  1. 21.Accounts Merge
    medium
  2. 22.Alien Dictionary
    hard
  3. 23.Minimum Height Trees
    medium
  4. 24.Find Eventual Safe States
    medium
  5. 25.Keys and Rooms
    medium
  6. 26.Possible Bipartition
    medium
  7. 27.All Paths From Source to Target
    medium
  8. 28.Detonate the Maximum Bombs
    medium
  9. 29.Find Closest Node to Given Two Nodes
    medium
  10. 30.Minimum Genetic Mutation
    medium

How to Think

  1. Things are connected to other things?Graph (Nodes & Edges)
  2. Need explore connected area?DFS / BFS + Visited Set
  3. Need count groups?Connected Components
  4. Need shortest path with every edge same cost?BFS (Level-by-level rings)
  5. Need detect cycle?DFS 3-state / Union Find
  6. Dependencies / prerequisites?Directed Graph + Topological Sort
  7. Weighted shortest path?Dijkstra (non-negative weights)

Go Graph Code Templates

Graph DFS & Unweighted Shortest Path BFS in Go

// 1. Graph DFS (Adjacency List + Visited Set)
func graphDFS(n int, edges [][]int) {
    adj := make([][]int, n)
    for _, e := range edges {
        u, v := e[0], e[1]
        adj[u] = append(adj[u], v)
        adj[v] = append(adj[v], u) // Undirected: Add both!
    }

    visited := make([]bool, n)
    var dfs func(u int)
    dfs = func(u int) {
        visited[u] = true
        for _, neighbor := range adj[u] {
            if !visited[neighbor] {
                dfs(neighbor)
            }
        }
    }

    for i := 0; i < n; i++ {
        if !visited[i] {
            dfs(i) // Discover each connected component
        }
    }
}

// 2. Unweighted Shortest Path BFS (Mark visited WHEN ENQUEUED!)
func shortestPathBFS(n int, edges [][]int, start, target int) int {
    adj := make([][]int, n)
    for _, e := range edges {
        u, v := e[0], e[1]
        adj[u] = append(adj[u], v)
        adj[v] = append(adj[v], u)
    }

    visited := make([]bool, n)
    queue := []int{start}
    visited[start] = true // Mark when enqueued!
    dist := 0

    for len(queue) > 0 {
        size := len(queue)
        for i := 0; i < size; i++ {
            curr := queue[0]
            queue = queue[1:]
            if curr == target {
                return dist
            }
            for _, neighbor := range adj[curr] {
                if !visited[neighbor] {
                    visited[neighbor] = true // Mark when enqueued!
                    queue = append(queue, neighbor)
                }
            }
        }
        dist++
    }
    return -1
}

👉 Total Time: O(V + E) | Space: O(V + E)

Visited Set & Mandatory BFS Enqueue Rule

1. Visited Set is Mandatory: Unlike Trees (which are acyclic), Graphs can contain cycles (A -> B -> C -> A). Without a visited set, graph traversals enter infinite loops!

2. Mark Visited When ENQUEUED: In BFS, always mark visited[neighbor] = true as soon as you append the node to the queue! If you mark it when popping, the same node will be inserted into the queue multiple times by adjacent neighbors, exploding queue size.

Grid as Graph & Multi-Source BFS

1. Grid as Graph: Many matrix problems (Number of Islands, Flood Fill, Surrounded Regions) are secretly Graph problems! Each cell grid[r][c] is a node, and valid 4-directional adjacent cells are edges.

2. Multi-Source BFS: When expansion starts from multiple starting points at once (Rotting Oranges, Pacific Atlantic Water Flow), push ALL initial sources into the queue simultaneously at minute 0, then expand BFS in parallel waves!

Visual Memory Rule
Graph            → Nodes + Edges (May contain cycles & disconnected components)
Visited Set      → MANDATORY to prevent infinite loops (Mark WHEN ENQUEUED in BFS!)
Unweighted Path  → BFS guaranteed shortest distance in level-by-level rings
Multi-Source BFS → Push ALL initial sources into queue at minute 0 simultaneously
Shortest Path    → Unweighted (BFS) | Non-negative (Dijkstra) | Negative (Bellman-Ford)

💡 Golden Rule: "Turn the problem into ‘What are the nodes, what are the edges, and how should I explore the neighbors?’"

Common Interview Mistakes

1. Forgetting Visited Set

Omitting the visited set in a graph with cycles causes infinite recursion / stack overflow crashes!

2. Marking Visited When Popping in BFS

In BFS, always mark visited[neighbor] = true when enqueuing! Marking when popping allows duplicate queue entries.

3. Adding Both Directions to Directed Graphs

For directed edges (u -> v), only add v to adj[u]. Do NOT add u to adj[v]!

4. Using BFS for Weighted Graphs

Standard BFS only guarantees shortest path when all edge costs are equal (unweighted)! Weighted graphs require Dijkstra\'s algorithm.

Interview Rules

  1. 1. Things connected to other things?→ Graph (Nodes & Edges)
  2. 2. Explore connected area? → DFS / BFS + Visited Set
  3. 3. Count connected components?→ Loop over all nodes; if unvisited, increment count & run DFS/BFS
  4. 4. Unweighted shortest path? → BFS (Level-by-level distance rings)
  5. 5. Prerequisites / Dependencies? → Directed Graph + Topological Sort
  6. 6. Multi-Source expansion (Rotting Oranges)? → Push ALL initial sources into queue at minute 0
  7. 7. Weighted shortest path? → Dijkstra (non-negative weights) | Bellman-Ford (negative weights)
  8. 8. Overall Complexity → Time: O(V + E) | Space: O(V + E)

Small Rules

  1. Rule 1: Graphs consist of Nodes (entities) and Edges (connections).
  2. Rule 2: Visited set is mandatory to prevent infinite loops in cyclic graphs.
  3. Rule 3: Unweighted shortest path is always solved using BFS.
  4. Rule 4: Mark nodes as visited WHEN ENQUEUED in BFS.
  5. Rule 5: Matrix connected cell problems are Graph problems in disguise.

Production Thinking

Social Network Friend GraphsDetermining degrees of separation & mutual friend recommendations

Microservice Dependency GraphsDetecting circular service dependencies (Auth -> Orders -> Payments -> Auth)

Road Network NavigationCalculating shortest driving routes & travel times using weighted graph routing

Build System Package ResolutionDetermining correct package compilation order using Topological Sort

Remember This

Graph            → Nodes + Edges
DFS              → Go deep
BFS              → Level by level
Visited          → Prevent repeats & cycles
Components       → Count groups
Shortest Path    → BFS (unweighted)
Multi-Source BFS → All starts at once
Dependencies     → Directed Graph
Weighted Path    → Dijkstra
Time             → O(V + E)

💡 Golden Rule: "Turn the problem into ‘What are the nodes, what are the edges, and how should I explore the neighbors?’"