Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: A node of a directed graph is 'safe' if every path from it ends at a terminal node (no outgoing edges). List the safe nodes.

Problem: A node of a directed graph is 'safe' if every path from it ends at a terminal node (no outgoing edges). List the safe nodes.
def safe(g):
    color = [0] * len(g)       # 0 new, 1 on stack, 2 safe
    def dfs(u):
        if color[u]: return color[u] == 2
        color[u] = 1
        for v in g[u]:
            if not dfs(v): return False
        color[u] = 2
        return True
    return [u for u in range(len(g)) if dfs(u)]
print(safe([[1], [2], [0, 3], [4], [], [4, 6], []]))
What is printed?
  1. A. [3, 4, 5, 6]
  2. B. [3, 4, 6]
  3. C. [4, 6]
  4. D. [2, 3, 4, 5, 6]

Correct answer: A. [3, 4, 5, 6]

0 → 1 → 2 → 0 is a cycle, so 0, 1 and 2 are unsafe even though 2 also points at the safe node 3. Node 3 leads only to terminal 4, and 5 leads only to terminals 4 and 6, so the safe nodes are 3, 4, 5 and 6.

More Coding Interview Problems questions

Exams that ask this topic