The problem
Write a union-find class for the elements 0 to n - 1 (lessons 1 to 3). At the start every element is in a set of its own.
find(x)returns the representative ofx’s set: the same element for every member of the set.union(a, b)joins the two sets and returnsTrue, or returnsFalseifaandbwere already in one set.connected(a, b)says whether they are in one set,size(x)is the number of elements inx’s set, andgroups()is the number of sets.
d = DSU(5)
d.union(0, 1) # True
d.union(1, 0) # False: already together
d.union(1, 2) # True
d.connected(0, 2) # True
d.size(2) # 3
d.groups() # 3: {0, 1, 2}, {3}, {4}
Some tests join long chains. Write find with a loop, or make sure your trees stay short (lessons 2 and 3): a recursive find on a path of 100,000 nodes stops with RecursionError.
Limits
- Up to 200,000 elements and about a million operations. Use union by size or rank, and path compression: every operation should cost nearly O(1).
Builds on DSUF-1 Disjoint sets and DSUF-2 Union by rank and DSUF-3 Path compression.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Union and find | Not run | |
| 2 | Union twice | Not run | |
| 3 | Sizes and groups | Not run | |
| 4 | One representative | Not run | |
| 5 | A long chain | Not run | |
| 6 | A chain the other way | Not run | |
| 7 | Equal unions | Not run | |
| 8 | 200,000 random unions | Not run |