Union Find Template: Pattern, Code & Cheat Sheet
The Union Find pattern is one of the most frequently tested coding interview patterns. Disjoint set union for tracking connected components. This template gives you a reusable code skeleton, pseudocode, and implementation in multiple languages so you can solve 6+ problems using this single mental model.
Difficulty: Medium | Time Complexity: O(α(n)) | Space Complexity: O(n)
When to Use This Template
Use the Union Find template when you see these signals in a problem:
Prerequisites: Graph basics
Problem count on W Code: 6 problems across Easy, Medium, and Hard difficulty levels.
If the problem does not match these signals, consider alternative patterns.
Pseudocode Template
function union_findSolve(input):
// Initialize data structures
result = initial_value
// Core logic for Union Find
for each element in input:
process(element)
update(result)
return resultPython Implementation
pythondef solve(input_data): """Union Find solution template.""" result = [] # Implement union find logic here for item in input_data: # Process each item result.append(item) return result
Java Implementation
javapublic Object solve(Object[] input) { // Union Find template // Implement core logic here return null; }
C++ Implementation
cppauto solve(vector<int>& input) { // Union Find template // Implement core logic return result; }
Variations & Adaptations
The Union Find pattern has several variations you should master:
Variation 1: Basic Union-Find
This variation is useful when the problem specifically requires basic union-find. Adapt the main template by modifying the core loop/recursion logic accordingly.
Variation 2: Union by Rank
This variation is useful when the problem specifically requires union by rank. Adapt the main template by modifying the core loop/recursion logic accordingly.
Variation 3: Path Compression
This variation is useful when the problem specifically requires path compression. Adapt the main template by modifying the core loop/recursion logic accordingly.
Variation 4: Weighted Union-Find
This variation is useful when the problem specifically requires weighted union-find. Adapt the main template by modifying the core loop/recursion logic accordingly.
Common Mistakes & Edge Cases
When implementing Union Find, watch out for:
Edge cases to always test:
Step-by-Step Problem Solving Guide
Frequently Asked Questions
What problems can I solve with the Union Find template?
What is the time complexity of Union Find?
What should I learn before Union Find?
How do I recognize a Union Find problem in an interview?
Practice 6+ Union Find problems on W Code with instant feedback and AI-powered hints. Start your free practice now!
Start Learning Free