DSUF-P1

Union-find

Practice 1 of 5Union-find8 tests

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 of x’s set: the same element for every member of the set.
  • union(a, b) joins the two sets and returns True, or returns False if a and b were already in one set.
  • connected(a, b) says whether they are in one set, size(x) is the number of elements in x’s set, and groups() 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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

8 tests, not run yet
Test results
#TestResultReads · time
1Union and findNot run
2Union twiceNot run
3Sizes and groupsNot run
4One representativeNot run
5A long chainNot run
6A chain the other wayNot run
7Equal unionsNot run
8200,000 random unionsNot run