Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Union-find with path compression answers which friends are in the same circle. How many circles remain after the unions?
Problem: Union-find with path compression answers which friends are in the same circle. How many circles remain after the unions?
parent = list(range(8))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb: return False
parent[ra] = rb; return True
res = [union(a, b) for a, b in [(0, 1), (2, 3), (1, 3), (4, 5), (0, 2), (6, 6)]]
print(len({find(i) for i in range(8)}), res)What is printed?- A. 5 [True, True, True, True, False, False]
- B. 4 [True, True, True, True, True, False]
- C. 4 [True, True, True, True, False, False]
- D. 3 [True, True, True, True, False, True]
Correct answer: C. 4 [True, True, True, True, False, False]
Unions merge {0,1,2,3} (0–2 is already connected through 1–3, so it returns False – that edge would close a cycle), {4,5}, and 6, 7 stay alone: 4 sets. A self-union (6,6) finds the same root and returns False. Near O(1) amortised per operation.
More Coding Interview Problems questions
- Problem: Find the minimum total cost to connect all offices (minimum spanning tree) using Kruskal's algorithm. python def kruskal(n…
- Problem: Find the length of the shortest transformation from a start word to an end word, changing one letter at a time, every…
- Problem: Determine whether a graph can be coloured with two colours so that no edge joins equal colours (bipartite). python from…
- Problem: Count the number of shortest paths (fewest edges) from node 0 to node n − 1 in an unweighted graph. python from collections…
- Problem: In a grid, 0 is open and 1 is a wall. Find the shortest path length (in cells) from the top-left to the bottom-right moving in 8…
- Problem: Each cell of a grid holds 0 (empty) or 1. Return a grid of the distance from each cell to its nearest 0. python from collections…