Equivalence classes and union/find in a functional language
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Equivalence classes let you partition a set into groups where every member is related to every other member in the same group. Union-find, also called disjoint set union, is the classic data structure for building and querying those groups efficiently.
Why Equivalence Classes Matter
An equivalence relation is reflexive, symmetric, and transitive. Once those rules hold, every element belongs to exactly one equivalence class. In practice, that model appears in problems such as connected components, type unification, clustering, and grouping accounts that refer to the same person.
Union-find gives you two core operations:
- '
find, which returns a representative for an element's class' - '
union, which merges the classes of two elements'
In imperative languages, union-find is usually implemented with mutable arrays plus path compression and union by rank. A functional language changes the design because updates produce a new structure instead of mutating the old one in place.
Modeling Union-Find Persistently
The most important shift in a functional implementation is the API shape. A find operation that performs path compression must return both the representative and the updated structure. If you throw away the updated structure, you lose the optimization.
The Haskell example below uses IntMap to store parent pointers and ranks. It is still a real union-find, but every operation returns a new version of the data structure.
Related reading
- Error calculating pi using the Chudnovsky algorithm - Java
- Estimate the minimum Distance between two Clusters
- Eugene Myers' Diff Algorithm Finding the Longest Common Subsequence of A and B
- Euler project 18 approach
- Errata in the original paper on suffix arrays?
- Error AccessControlListNotSupported when trying to create a bucket ACL in AWS
- Evenly distributing n points on a sphere
- Evenly distributing n points on a sphere

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.