Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count how many nodes are 'safe' (every path from them ends at a terminal node) in a directed graph.

Problem: Count how many nodes are 'safe' (every path from them ends at a terminal node) in a directed graph.
def safe(g):
    color = [0] * len(g)
    def ok(u):
        if color[u]: return color[u] == 2
        color[u] = 1
        if any(not ok(v) for v in g[u]): return False
        color[u] = 2
        return True
    return [u for u in range(len(g)) if ok(u)]
print(safe([[1, 2], [2, 3], [5], [0], [5], [], []]))
What is printed?
  1. A. [5, 6]
  2. B. [2, 4, 5, 6]
  3. C. [2, 4, 5]
  4. D. [1, 2, 4, 5, 6]

Correct answer: B. [2, 4, 5, 6]

A node is unsafe if it can reach a cycle. 0 → 1 → 3 → 0 is a cycle, so 0, 1, 3 stay grey (colour 1) and are unsafe; 2 → 5, 4 → 5, and terminals 5 and 6 are safe. Grey nodes left from a failed search correctly count as unsafe later. O(V + E).

More Coding Interview Problems questions

Exams that ask this topic