Skip to the workspace
Pebellslearn by building
Graphs  ›  Lesson

Union-Find & Artist Dedupe

Union Find 22 minMerging groups and asking who's together

dsa / Union-Find & Artist Dedupe

Explore each scene at your own pace.

01 · Deduplicating Tunebox's artist profiles

Deduplicating Tunebox's artist profiles

Union-Find & Artist Dedupe

Definition
Union-find (a disjoint-set structure) keeps items split into groups and supports merging two groups and asking whether two items share a group, by giving each group a root that every member's parent pointers lead to.
In plain words
Think of clubs where every member only knows one other member who leads them towards the club's captain. To check whether two people are in the same club, follow the chain to each captain and see if it is the same person; to merge clubs, one captain accepts the other.

In short: union-find (a disjoint-set) keeps a collection of groups and answers "merge these two" and "are these the same group?" in effectively constant time, without ever walking a graph. Each group has a root (representative) that every member's parent pointer eventually leads to; find follows pointers to the root, union hangs one root under the other. Two add-ons make it fast: path compression (flatten pointers while you walk) and union by rank (always hang the shorter tree under the taller). Together: O(α(n)) amortized per operation — α is the inverse Ackermann function, so slow-growing it's ≤ 4 for any n you could ever store, which is why people call it "effectively constant".

A tall chain a→b→c→d before find(a), flattened on the right into a, b and c all pointing straight at root d after one compressing find

Deduplicating Tunebox's artist profiles

Three labels uploaded the same artist three times: theweeknd, the-weeknd and weeknd-official. Moderators report duplicates one pair at a time — "theweeknd is weeknd-official", then later "the-weeknd is theweeknd" — and Tunebox has to merge them transitively, then answer "same artist?" instantly while reports keep arriving. At the start nobody has merged, so everyone is their own parent — their own root:

python

find follows parent pointers until one points at itself:

What does this print?
parent = {"adele-music": "adele-hq", "adele-hq": "adele", "adele": "adele", "sza": "sza"}

def find(x):
    while parent[x] != x:
        x = parent[x]
    return x

print(find("adele-music"), find("sza"))

Two elements are in the same group exactly when find gives the same root. The mistake: pointing the element you were handed at the other, instead of pointing one root at the other — the second merge below silently undoes the first:

broken — fix it

All three profiles were reported as the same artist, so this should print True. It prints False. Fix union so merging never undoes an earlier merge.

❓ Cross-question — "Why not store the matches as a graph and run DFS?" For one question on a fixed graph, that's fine. But DFS costs O(V + E) per question, and matches keep arriving between questions. Union-find handles an interleaved stream of merges and questions at almost O(1) each.

A long chain of parents makes find slow, so path compression flattens it while you walk: once you know the root, point every element you passed through straight at it. Each arrow below is a parent pointer, and the highlighted nodes are roots:

watch it move · graph

Unlucky unions build a chain, and one find with path compression flattens it for good.

Every element starts as its own parent, so there are five one-member groups. 5 nodes, 0 edges, undirected. Frontier: a, b, c, d, e.

1 / 7
What does this print?
parent = {"d": "c", "c": "b", "b": "a", "a": "a"}

def find(x):
    if parent[x] != x:
        parent[x] = find(parent[x])
    return parent[x]

find("d")
print(parent["c"])

Union by rank avoids building tall trees in the first place: give each root a rank — an upper bound on its tree's height — and always hang the lower-ranked root under the higher one:

step through it
1parent = {n: n for n in ["a", "b", "c", "d"]}
2rank = {n: 0 for n in parent}
3 
4def find(x):
5 while parent[x] != x:
6 x = parent[x]
7 return x
8 
9for x, y in [["a", "b"], ["c", "d"], ["a", "c"]]:
10 rx, ry = find(x), find(y)
11 if rx == ry:
12 continue
13 if rank[rx] < rank[ry]:
14 rx, ry = ry, rx
15 parent[ry] = rx
16 if rank[rx] == rank[ry]:
17 rank[rx] += 1
18print(parent, rank)

Both tricks together, as a class worth keeping, drawing its own parent pointers after every change — reorder the merges and run it again:

your code, drawn · graph

Your union-find: arrows are parent pointers, highlighted nodes are roots, and compression shortens every path it walks.

python
Scene 1 of 6
Project context and further resources
You're building a piece ofTunebox — recommendations
This piece — merge_duplicates(): Collapses duplicate artist profiles into one.
Scenario Three labels uploaded the same artist under three spellings, and moderators keep reporting pairs. Tunebox merges each group into one canonical profile so plays and followers land in one place.
merge_duplicates.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
merge_duplicates(profiles, matches) → dictEvery profile mapped to its group's canonical (alphabetically first) name.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.