Data Structures & AlgorithmsHardProduct Company SDE pattern
What is printed? (strongly connected components count, Kosaraju)
What is printed? (strongly connected components count, Kosaraju)
g = {0: [1], 1: [2], 2: [0, 3], 3: [4], 4: [5], 5: [3], 6: [5, 7], 7: []}
order, seen = [], set()
def dfs1(u):
seen.add(u)
for v in g[u]:
if v not in seen: dfs1(v)
order.append(u)
for u in g:
if u not in seen: dfs1(u)
rg = {u: [] for u in g}
for u in g:
for v in g[u]: rg[v].append(u)
seen.clear(); count = 0
def dfs2(u):
seen.add(u)
for v in rg[u]:
if v not in seen: dfs2(v)
for u in reversed(order):
if u not in seen: count += 1; dfs2(u)
print(count)- A. 3
- B. 4
- C. 5
- D. 2
Correct answer: B. 4
SCCs: {0, 1, 2}, {3, 4, 5}, {6} and {7}. Kosaraju runs DFS once to get finishing order, then DFS on the reversed graph in decreasing finish time; each second-pass tree is one SCC. O(V + E).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- What is printed? (greedy fractional knapsack) python items = [(10, 60), (20, 100), (30, 120)] # (weight, value) cap, total = 50, 0.0 for…
- What is printed? (minimum platforms / overlapping intervals with a heap) python import heapq iv = sorted([(1, 4), (2, 3), (3, 6), (5, 7)…
- A complete binary tree is stored in an array with the root at index 1. A node at index 37 – what are its parent, left child and right…
- What is printed? (Catalan-style recursion with memo: number of ways to fully parenthesise a product of n matrices) python from functools…
- Union–find with union by rank and full path compression. What is printed? python p = list(range(8)); rank = [0] 8 def find(x): if p[x] !=…
- 0-1 BFS on a grid: stepping into '#' costs 1 (a wall to break), stepping onto '.' or 'T' costs 0. What is the minimum number of walls to…