~/problems
Problems
Basics first, then the classics, then company-style assessments. Every problem has tests you run right here; multi-level ones unlock as you go. See the roadmap.
Union-Find
Path compression + union by rank; connectivity and grouping.
Notes
Recognise it when: grouping by connectivity, components, "are x and y connected", merging accounts, detecting a cycle in an undirected graph, Kruskal.
def find(x):
root = x
while parent[root] != root: root = parent[root]
while parent[x] != root: parent[x], x = root, parent[x] # compress
return root
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb: return False
if rank[ra] < rank[rb]: ra, rb = rb, ra
parent[rb] = ra
rank[ra] += rank[ra] == rank[rb]
return True
Gotchas: recursive find blows the recursion limit on long chains, so write it iteratively. Keep a count of components.
9 problems
Interview roadmap
Weighted graphs Dijkstra, union-find, spanning trees.
Union-Find guide
- Basics: count groups with find and union basics py · c++ · java easy
- Pooled lunch money easy
- Number of Provinces py · c++ · java easy
- Redundant Connection py · c++ · java medium
- Accounts Merge py · c++ · java medium
- Union-Find class with component count easy
- Pin board connectivity Pinterest py · c++ · java medium
- Minimum triggers to absorb all balls Uber py · c++ · java medium
- Graph Valid Tree py · c++ · java medium