AlgoTales · Roadmap

Make set

Beginner · 6 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Make-set is the starting move of union-find: every item begins as its own tiny group with itself as the leader. It is the clean slate from which you later merge items together as you learn which ones belong in the same group.

Practical use cases

  • Web app: Starting a network of separate machines. A DevOps dashboard lists 500 servers and wants to show which ones can talk to each other. At the start nobody is known to be connected, so each server is its own group. Later, every link report merges two groups, and the dashboard can answer "are A and B connected?" instantly.
  • Web app: Seating groups for an event booking. A wedding-hall booking page lets guests be linked as "same family" one by one. Each guest starts alone in a group of one, and as the organiser ties guests together the groups grow, so the page can count tables needed without recalculating everything. Nothing is rebuilt later; each link just points one guest group at another, and the table count stays correct.
  • System: Maze generators and image labelling. A maze generator starts with every cell walled off alone, and image tools start with every pixel as its own region. Make-set is the starting line before regions are joined. It looks trivial, yet every later merge and lookup depends on this clean starting point being set up correctly.

The story: The Lone Captains of the School Fair

On the morning of the school fair, Mrs. Sharma stood in the playground with a register and a problem. Forty students were turning up, and each one would soon be told: "You are on the same stall team as these friends." But nobody knew yet who would be teamed with whom. Teams would be formed all day, as friendships and stalls were decided.

Mira asked the obvious question: "What do we write in the register for someone with no team?" Kabir shrugged. "Leave it blank?" But a blank slot is a trap. When the first two students joined up, how would you say who the captain was? What would you point at?

Mrs. Sharma had a neat trick. "Everybody starts as the captain of a team of one. Next to your name, write your own name." So Mira wrote Mira beside Mira, Kabir wrote Kabir beside Kabir. Later, when teams merge, a captain simply swaps their note to point at a new captain.

That starting step is called make-set. Every item gets its own set, and the item is its own representative. It costs one tiny action per student, and it is the base on which the whole Disjoint Set Union (Union-Find) structure is built.

How to spot this problem, and where you need it

You will receive a stream of facts like "A and B belong together" and must later tell whether two things are in the same group, so you first need every item to start out as its own group.

Signs you need it

  • The problem talks about groups, teams, clusters, regions or components that get merged over time.
  • At the start nothing is connected; connections are revealed one by one.
  • You need a quick "same group?" check later, and a list of lists is getting messy.
  • The words "union", "connected" or "friends of friends" appear in the problem.

Where to use it in a project

  • Initialising a connectivity tracker for servers, users, devices or map cells.
  • The setup step before reading a list of links, friendships or merge requests.

The solution

Give every item a parent pointer and set it to point to itself, which means "I am my own leader". Optionally give it a size of 1 or a rank of 0 for later merging rules. This takes one small step per item and prepares the structure so that union and find operations can work.

Payoff: Before: ad-hoc lists of groups that are hard to merge. After: n tiny groups ready in n quick steps, so later merges are cheap.

Explain it like I am 8

Imagine every kid in class holds up a card that says "I am my own boss." That is all make-set does. Later, when kids join a team, they just change their card to point at their new leader.

How it works, step by step

  1. Pick your things and number them 0 to n-1 (students, computers, cities, anything).
  2. Make an array called parent with one slot for each thing.
  3. Set each slot to its own number: parent[i] = i. Everyone is their own captain.
  4. Optional helper arrays start simple: size[i] = 1 (a team of one) or rank[i] = 0. You will meet them in the later lessons.
  5. A root is a slot that points at itself. Right now every slot is a root, which means there are exactly n teams.

The code in four languages

PHP

<?php
// make-set: every item starts as the captain of its own team of one
function makeSets(int $n): array {
    $parent = [];
    for ($i = 0; $i < $n; $i++) {
        $parent[$i] = $i;          // "my boss is me"
    }
    return $parent;
}

$parent = makeSets(6);
echo "parent: " . implode(", ", $parent) . "\n";   // 0, 1, 2, 3, 4, 5

// Count the roots: slots that point at themselves
$teams = 0;
foreach ($parent as $i => $p) {
    if ($i === $p) $teams++;
}
echo "teams: " . $teams . "\n";                    // 6

JavaScript

// make-set: every item starts as the captain of its own team of one
function makeSets(n) {
  const parent = [];
  for (let i = 0; i < n; i++) {
    parent[i] = i;                // "my boss is me"
  }
  return parent;
}

const parent = makeSets(6);
console.log("parent: " + parent.join(", "));   // 0, 1, 2, 3, 4, 5

// Count the roots: slots that point at themselves
let teams = 0;
parent.forEach((p, i) => { if (i === p) teams++; });
console.log("teams: " + teams);                // 6

Java

import java.util.*;

public class Main {
    // make-set: every item starts as the captain of its own team of one
    static int[] makeSets(int n) {
        int[] parent = new int[n];
        for (int i = 0; i < n; i++) {
            parent[i] = i;                 // "my boss is me"
        }
        return parent;
    }

    public static void main(String[] args) {
        int[] parent = makeSets(6);
        System.out.println("parent: " + Arrays.toString(parent).replaceAll("[\\[\\]]", ""));   // 0, 1, 2, 3, 4, 5

        // Count the roots: slots that point at themselves
        int teams = 0;
        for (int i = 0; i < parent.length; i++) {
            if (i == parent[i]) teams++;
        }
        System.out.println("teams: " + teams);                                                 // 6
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

// makeSets: every item starts as the captain of its own team of one.
func makeSets(n int) []int {
	parent := make([]int, n)
	for i := range parent {
		parent[i] = i // "my boss is me"
	}
	return parent
}

// join turns a slice of ints into "a, b, c".
func join(nums []int) string {
	parts := make([]string, len(nums))
	for i, v := range nums {
		parts[i] = strconv.Itoa(v)
	}
	return strings.Join(parts, ", ")
}

func main() {
	parent := makeSets(6)
	fmt.Println("parent: " + join(parent)) // 0, 1, 2, 3, 4, 5

	// Count the roots: slots that point at themselves
	teams := 0
	for i, p := range parent {
		if i == p {
			teams++
		}
	}
	fmt.Println("teams:", teams) // 6
}

Time: O(n) · Extra space: O(n). One tiny step and one array slot per item, and you only do it once at the start.

Watch out for

  • Starting the array with zeros: parent = [0,0,0...] means everyone already reports to student 0, so everything looks merged.
  • Making the array too small. If your items are numbered 1 to n, allocate n + 1 slots or shift the numbers by one.
  • Forgetting that numbers must be small integers. For names or strings, map each name to a number first (a dictionary does this).

Quick check

  1. After make-set on 6 items, how many separate sets are there?
    • 3
    • 1
    • 6
    • 0
  2. What marks an item as a root (a team captain)?
    • parent[i] is -1 only
    • parent[i] equals i
    • It has no number
    • parent[i] is 0
  3. Why not leave the slots empty at the start?
    • It would use more memory
    • Empty arrays are slower
    • There would be no captain to point at when teams merge
    • PHP forbids it