Bitpath

Boss lesson · Unit 03

Union-find

Track groups as they merge, in almost constant time

12 exercisesabout 3 min

What you practise

  • Find with path compression, union, counting components

Try a question from this lesson

Pick one

Friendships arrive one at a time, and after each you must say whether two given people are in the same friend group. What is the cheapest thing to keep up to date?

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Parents and roots

Give every item a parent. The leader of a group, its root, is its own parent.

To find the group of an item, follow parents until you reach a root. Two items are in the same group exactly when they reach the same root.

parent = [0, 0, 1, 3, 3]

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

print(find(2), find(4))   # 0 3
const parent = [0, 0, 1, 3, 3];

function find(x) {
  while (parent[x] !== x) {
    x = parent[x];
  }
  return x;
}

console.log(find(2), find(4)); // 0 3
const parent = [0, 0, 1, 3, 3];

function find(x: number): number {
  while (parent[x] !== x) {
    x = parent[x];
  }
  return x;
}

console.log(find(2), find(4)); // 0 3

TypeScript note(x: number): number reads "takes a number, returns a number": an item goes in and its root comes out.

10 more exercises in the app

  • 3× type the answer
  • 1× order the lines
  • 3× multiple choice
  • 1× fill the blanks
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy