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?- A. [3, 4, 5, 6]
- B. [3, 4, 6]
- C. [4, 6]
- 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
- Problem: Find the bridges and articulation points of an undirected graph using DFS discovery times and low-links. python import sys…
- Problem: Count the strongly connected components and the number of edges in the condensation DAG (Kosaraju). python n = 8 E =…
- Problem: Check whether each graph is bipartite with BFS 2-colouring (graphs may be disconnected). python from collections import deque def…
- Problem: Burst balloons; bursting balloon i earns left × a[i] × right using its current neighbours (1 beyond the ends). Maximise the…
- Problem: Count the ways to split s into a sequence of dictionary words. python def count(s, words): W = set(words); dp = [1] + [0] len(s)…
- Problem: Regular-expression matching where '.' matches any one character and 'x' matches zero or more x (the whole string must match)…