Data Structures & AlgorithmsVery hardProduct company OA
Union–find with union by rank and full path compression. What is printed?
Union–find with union by rank and full path compression. What is printed?
p = list(range(8)); rank = [0] * 8
def find(x):
if p[x] != x: p[x] = find(p[x])
return p[x]
def union(a, b):
a, b = find(a), find(b)
if a == b: return False
if rank[a] < rank[b]: a, b = b, a
p[b] = a
if rank[a] == rank[b]: rank[a] += 1
return True
ops = [(0, 1), (2, 3), (1, 3), (4, 5), (6, 7), (5, 7), (3, 7), (0, 2)]
res = [union(a, b) for a, b in ops]
print(p, res.count(False), max(rank))
find(6)
print(p)- A. [0, 0, 0, 0, 0, 4, 4, 4] 1 3 [0, 0, 0, 0, 0, 4, 0, 4]
- B. [0, 0, 0, 0, 0, 4, 4, 4] 1 3 [0, 0, 0, 0, 0, 4, 4, 4]
- C. [0, 0, 0, 0, 0, 0, 0, 0] 1 3 [0, 0, 0, 0, 0, 0, 0, 0]
- D. [0, 0, 0, 2, 0, 4, 4, 4] 1 2 [0, 0, 0, 2, 0, 4, 0, 4]
Correct answer: A. [0, 0, 0, 0, 0, 4, 4, 4] 1 3 [0, 0, 0, 0, 0, 4, 0, 4]
Unions 0–1, 2–3, 4–5, 6–7 make four rank-1 trees; 1–3 joins roots 0 and 2 (rank 2), 5–7 joins 4 and 6 (rank 2). For 3–7, find(3) compresses 3 → 0 and find(7) compresses 7 and 6 straight to 4; equal ranks, so 4 goes under 0 and rank 0 becomes 3. 0–2 is already joined (the only False). Compression only touches nodes on a find path, so 5, 6, 7 still point at 4 until find(6) re-routes just 6 to 0. Expecting every node to point at the root is the common misconception.
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
- 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…
- How many topological orders does this DAG on 6 vertices have? (counted by DP over bitmasks of already-placed vertices) python from…
- Fenwick (binary indexed) tree, 1-based, built by point additions; then a[3] += 10. What is printed (the internal array, a range sum and a…
- Segment tree for range-minimum with lazy range-add (the pending add stays at a node and is applied on the way up instead of being pushed…
- Four cities, symmetric distances; the bitmask DP (Held–Karp) is compared with the nearest-neighbour heuristic, both starting and ending at…
- Maximum-weight independent set on a tree (no two chosen nodes adjacent) by tree DP returning (best if u taken, best if u skipped)…