Bird
Raised Fist0
Interview Preptopological-sortmediumAmazonGoogle

Find Eventual Safe States

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize variables and reverse graph structure

Create an empty reverse graph with the same number of nodes as the input graph and initialize the in-degree array to zero for all nodes.

💡 Setting up the reverse graph and in-degree array prepares the data structures needed to track node dependencies in the reversed graph.
Line:n = len(graph) reverse_graph = [[] for _ in range(n)] in_degree = [0] * n
💡 The reverse graph will store edges reversed from the original graph, and in-degree will count outgoing edges in the original graph.
📊
Find Eventual Safe States - Watch the Algorithm Execute, Step by Step
Watching each step of Kahn's Algorithm applied to the reversed graph reveals how safe nodes are identified by progressively removing nodes that lead only to terminal or safe nodes.
Step 1/14
·Active fill★Answer cell
Visiting: none
0
1
2
3
4
5
6
Visiting: 0
0
1
2
3
4
5
6
Visiting: 1
0
1
2
3
4
5
6
Visiting: 2
0
1
2
3
4
5
6
Visiting: 3
0
1
2
3
4
5
6
Visiting: 4
0
1
2
3
4
5
6
Visiting: 5
0
1
2
3
4
5
6
Visiting: 6
0
1
2
3
4
5
6
Visiting: none
0
1
2
3
4
5
6
Queue / Stack
56
Visiting: 5
Edge: 5 → 2
0
1
2
3
4
5
6
Queue / Stack
624
Visiting: 6
0
1
2
3
4
5
6
Queue / Stack
24
Visiting: 2
Edge: 2 → 0
0
1
2
3
4
5
6
Queue / Stack
4
Visiting: 4
0
1
2
3
4
5
6
Visiting: none
0
1
2
3
4
5
6

Key Takeaways

✓ Reversing the graph and using in-degree counts allows identification of safe nodes by starting from terminal nodes.

This insight is difficult to grasp from code alone because it requires understanding the reversed graph's role in safety propagation.

✓ Nodes become safe only when all their outgoing edges lead to safe nodes, reflected by their in-degree dropping to zero.

Visualizing in-degree decrement and queue updates clarifies how safety propagates backward through the graph.

✓ Terminal nodes are the initial safe nodes and serve as the base case for the algorithm's BFS traversal.

Seeing terminal nodes enqueued first helps concretely understand why they are inherently safe.

Practice

(1/5)
1. Consider the following buggy code snippet for topological sort positions. Which line contains the subtle bug that can cause incorrect matrix construction?
medium
A. Line where graph[u].append(v) is called
B. Line where queue is initialized with nodes of zero in-degree
C. Line where pos[node] is assigned idx
D. Line where in_degree[u] is incremented instead of in_degree[v]

Solution

  1. Step 1: Identify how in-degree is updated

    In-degree should count incoming edges; incrementing in_degree[u] is incorrect because u is the source, not the target.
  2. Step 2: Understand impact of bug

    Incorrect in-degree counts cause wrong zero in-degree nodes, breaking topological order and matrix correctness.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Correct in-degree update is critical for cycle detection and ordering [OK]
Hint: In-degree counts incoming edges, not outgoing [OK]
Common Mistakes:
  • Mixing source and target when updating in-degree
  • Assuming graph edges are undirected
2. Consider the following buggy implementation of Kahn's Algorithm for course scheduling. Which line contains the subtle bug that can cause incorrect or infinite behavior?
medium
A. Line 6: graph[a].append(b) -- edge direction reversed
B. Line 7: in_degree[a] += 1 -- incorrect in-degree increment
C. Line 10: queue initialization -- wrong nodes enqueued
D. Line 15: in_degree[nei] -= 1 -- decrementing in-degree incorrectly

Solution

  1. Step 1: Analyze edge construction

    Prerequisite pairs are (a, b) meaning b -> a edge; reversing to graph[a].append(b) flips direction.
  2. Step 2: Consequences of reversed edges

    In-degree counts and BFS queue become invalid, causing wrong order or infinite loop.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Correct edge direction is critical for topological sort correctness [OK]
Hint: Check edge direction carefully when building graph [OK]
Common Mistakes:
  • Reversing edges when building adjacency list
  • Incrementing in-degree on wrong node
  • Forgetting to decrement in-degree
3. Examine the following code snippet for the largest color value problem. It is almost correct but contains one subtle bug. Identify the line causing the bug.
from collections import defaultdict, deque

def largestPathValue(colors, edges):
    n = len(colors)
    graph = defaultdict(list)
    indegree = [0] * n
    for u, v in edges:
        graph[u].append(v)
        indegree[v] += 1

    dp = [[0]*26 for _ in range(n)]
    queue = deque([i for i in range(n) if indegree[i] == 0])
    count = 0
    max_color_value = 0

    while queue:
        node = queue.popleft()
        count += 1
        c_index = ord(colors[node]) - ord('a')
        dp[node][c_index] += 1
        max_color_value = max(max_color_value, dp[node][c_index])

        for nei in graph[node]:
            for i in range(26):
                dp[nei][i] = max(dp[nei][i], dp[node][i])
            indegree[nei] -= 1
            if indegree[nei] == 0:
                queue.append(nei)

    if count != n:
        return -1  # cycle detected
    return max_color_value
medium
A. Line incrementing dp[node][c_index]
B. Line updating dp[nei][i] inside the nested loop
C. Line checking if count != n to detect cycles
D. Line initializing the queue with nodes having indegree zero

Solution

  1. Step 1: Understand dp update logic

    dp[nei][i] should aggregate max counts from predecessors, but the code overwrites dp[nei][i] without adding the neighbor's own color count.
  2. Step 2: Identify bug

    The bug is that dp[nei][i] = max(dp[nei][i], dp[node][i]) does not add the neighbor's own color count, causing undercounting.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Incorrect aggregation leads to wrong max color values [OK]
Hint: Check if dp updates correctly accumulate color counts [OK]
Common Mistakes:
  • Not aggregating color counts from neighbors properly
4. Examine the following buggy code snippet for sequence reconstruction using DFS postorder topological sort. Which line contains the subtle bug that can cause incorrect results when seqs is missing some elements from org?
medium
A. Line 7: Missing check if all nodes in org appear in seqs
B. Line 12: Incorrect graph edge insertion logic
C. Line 18: Incorrect cycle detection marking
D. Line 27: Missing stack reversal before comparison

Solution

  1. Step 1: Identify missing validation

    The code does not check if all elements in org appear in seqs, which can cause false positives.
  2. Step 2: Confirm other lines are correct

    Graph construction, cycle detection, and stack reversal are implemented correctly.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Missing node presence check leads to incorrect true when seqs incomplete [OK]
Hint: Always verify all org nodes appear in seqs [OK]
Common Mistakes:
  • Ignoring node presence check
  • Misplacing cycle detection flags
5. Suppose the alien dictionary problem is extended so that characters can appear multiple times in the same word and the order must reflect the first occurrence precedence only. Which modification to the topological sort approach correctly handles this variant without breaking correctness or efficiency?
hard
A. Modify graph construction to add edges for every differing character pair in all positions, not just first differing character
B. Use a brute force approach comparing all pairs of words and all character positions to build edges
C. Keep only the first differing character pair between adjacent words to add edges, ignoring subsequent differences
D. Ignore repeated characters and treat each character as unique node per occurrence

Solution

  1. Step 1: Understand variant requirement

    Order depends only on first differing character between adjacent words, even if characters repeat later.
  2. Step 2: Confirm correct approach

    Adding edges only for the first differing character pair preserves partial order and avoids cycles or redundant edges.
  3. Step 3: Reject incorrect modifications

    Adding edges for all differing pairs or treating repeated chars as unique nodes breaks correctness or efficiency.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    First differing character edge addition is minimal and sufficient [OK]
Hint: Only first differing character pair defines order [OK]
Common Mistakes:
  • Adding edges for all differing pairs causing cycles
  • Using brute force all pairs approach losing efficiency
  • Treating repeated chars as distinct nodes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard