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?- A. [5, 6]
- B. [2, 4, 5, 6]
- C. [2, 4, 5]
- 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
- Problem: Find the minimum effort path in a grid where effort is the maximum absolute height difference between consecutive cells. python…
- Problem: Return the number of steps to reach the exit of a maze grid ('.' open, '+' wall) from an entrance, where an exit is an open…
- Problem: Count paths modulo 10⁹ + 7 from the top-left to the bottom-right of a 3 × 3 board whose centre is blocked, moving right, down or…
- Problem: Find the maximum number of points you can collect in a grid going right/down from top-left to bottom-right and then reconstruct…
- Problem: n ≤ 10⁵ tasks with durations and deadlines; complete as many tasks as possible, one at a time, each finishing by its deadline…
- Problem: Find the median of two sorted arrays of sizes m and n (up to 10⁶ each) in better than linear time. What is the optimal complexity?