Practice
Solution
Step 1: Identify sorting cost
Sorting edges costs O(m log m) where m is number of edges.Step 2: Analyze union-find operations
Union-find operations take O(α(n)) amortized per operation, so total O(m α(n)).Final Answer:
Option B -> Option BQuick Check:
Sorting dominates, union-find nearly constant -> O(m log m + m α(n)) [OK]
- Assuming union-find is O(n) per operation
- Ignoring sorting cost
- Confusing n and m in complexity
Solution
Step 1: Identify indexing issue
Input edges use 1-based node indices, but union-find expects 0-based. Missing adjustment causes wrong unions or runtime errors.Step 2: Confirm other lines are correct
Sorting edges, union calls, and connectivity checks are correct; only indexing is buggy.Final Answer:
Option D -> Option DQuick Check:
Missing "u -= 1; v -= 1" causes incorrect unions [OK]
- Ignoring 1-based to 0-based index conversion
- Misusing union-find union return value
- Skipping connectivity check for both users
Solution
Step 1: Identify grouping and sorting
Indices in each group are collected but not sorted before assignment.Step 2: Check assignment order
Assigning sorted characters to unsorted group indices causes characters to be placed incorrectly.Final Answer:
Option A -> Option AQuick Check:
Sorting group indices before assignment fixes the bug [OK]
- Not sorting indices before assignment
- Assuming group order matches index order
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, x, y):
rx, ry = self.find(x), self.find(y)
if rx == ry:
return false
if self.rank[rx] <= self.rank[ry]:
self.parent[rx] = ry
else:
self.parent[ry] = rx
if self.rank[rx] == self.rank[ry]:
self.rank[rx] += 1
return true
Solution
Step 1: Analyze union by rank condition
The condition uses '<=' which causes incorrect parent assignment when ranks are equal.Step 2: Identify correct union by rank logic
When ranks are equal, parent of ry should be set to rx and rank of rx incremented; current code reverses this.Final Answer:
Option B -> Option BQuick Check:
Incorrect rank comparison leads to wrong parent assignment [OK]
- Misusing <= instead of < in rank comparison
- Incrementing rank of wrong root after union
- Confusing which parent to assign when ranks equal
Solution
Step 1: Understand adjacency constraint
Only stones adjacent in row or column can be connected, so union-find on all stones sharing row/column is incorrect.Step 2: Choose graph DFS on adjacency edges
Build graph edges only between stones adjacent in row or column, then DFS to find connected components.Final Answer:
Option A -> Option AQuick Check:
Union-find without adjacency check unions too many stones [OK]
- Applying union-find without adjacency check
- Assuming greedy removal works
- Ignoring sorting and adjacency in graph construction
