AlgoTales · Roadmap

Path compression

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Path compression is a clean-up trick used during find: after you walk up to the leader, you point every item you passed straight at the leader. The next question about any of them takes one step instead of many.

Practical use cases

  • Web app: Dependency resolver for a package manager. A tool like Composer or npm decides which version of a library stands for many aliases. After resolving a chain of five aliases once, every alias is pointed at the final answer, so later lookups during the same install are instant.
  • Web app: Web crawler removing duplicate pages. A crawler learns that many URLs redirect to the same page. By pointing every URL in a redirect chain directly at the final one, repeated checks stop following long chains of redirects. The crawler spends its time fetching new pages rather than following the same redirect chain again and again.
  • System: Compilers and route caches. Compilers keep track of which names mean the same thing, and networks cache the final hop for a destination. Both flatten long chains after the first lookup.

The story: The Shortcut Painted on the Railway Wall

Every morning Aarav's tiffin-delivery boys at the railway station asked the same thing: "Which platform manager is in charge of Platform 7?" The answer was a long chain. Boy asks the porter, the porter asks the supervisor, the supervisor asks the station master, and finally you get the name. Three hand-offs, every single time.

After a week, Mira noticed something silly. The answer never changed! Yet everyone kept walking the same long road. "Why not write the final answer on the wall once we learn it?" she asked.

So the next time the chain was followed, on the way back everyone crossed out their old note and wrote the station master's name directly. The porter: station master. The supervisor: station master. The very next question took a single hop.

That is path compression: after a find, every item on the walked path is pointed directly at the root. It flattens the tree as a happy side effect, and it makes later finds much faster for everyone using that branch.

How to spot this problem, and where you need it

Your lookups follow long chains of "points to" links, and the same chains are walked again and again, making each lookup slower over time.

Signs you need it

  • You have parent or redirect chains such as A -> B -> C -> D and keep walking them for every query.
  • Profiling shows the find or lookup function as the hot spot after many merges.
  • The same items are asked about again and again, so repeated walks are pure waste.
  • Results never change by shortcutting, only the speed does.

Where to use it in a project

  • Union-find based connectivity features that handle many queries.
  • Redirect, alias and dependency resolvers where chains can grow long.

The solution

During find, first walk up to the leader. Then walk the same path again (or do it recursively on the way back) and set each visited item's parent directly to the leader. The structure now has shorter paths, and the next find for any of those items is one hop. The meaning of the groups never changes.

Payoff: Before: climbing 5 or more links on each lookup. After: after the first lookup, every later one is a single hop.

Explain it like I am 8

You walk through five doors in a row to reach the principal's office. On the way back you stick a note on each door: "Principal's office is here, go straight." Next time everyone zooms past the doors.

How it works, step by step

  1. Walk up as usual to find the root, remembering the items you pass.
  2. Walk the path again (or unwind the recursion) and set each item's parent to the root.
  3. Recursive version: parent[x] = find(parent[x]). The returned root is stored on the way back.
  4. Path halving is a lighter cousin: parent[x] = parent[parent[x]] as you climb, so each hop skips a level.
  5. Result: the more you ask, the flatter the tree gets. It does not change who is in which set; it only changes the shape.

The code in four languages

PHP

<?php
// Find with path compression (recursive: fix the pointer on the way back)
function find(array &$parent, int $x): int {
    if ($parent[$x] !== $x) {
        $parent[$x] = find($parent, $parent[$x]);   // point straight at the root
    }
    return $parent[$x];
}

// the chain from the picture: 3 -> 2 -> 1 -> 0, and 5 -> 2, 4 -> 0
$parent = [0, 0, 1, 2, 0, 2];
echo "before: " . implode(", ", $parent) . "\n";

echo "find(3) = " . find($parent, 3) . "\n";          // 0
echo "after:  " . implode(", ", $parent) . "\n";      // 0, 0, 0, 0, 0, 2

// path halving, the iterative cousin
function findHalving(array &$parent, int $x): int {
    while ($parent[$x] !== $x) {
        $parent[$x] = $parent[$parent[$x]];            // skip one level
        $x = $parent[$x];
    }
    return $x;
}
echo "find(5) = " . findHalving($parent, 5) . "\n";    // 0

JavaScript

// Find with path compression (recursive: fix the pointer on the way back)
function find(parent, x) {
  if (parent[x] !== x) {
    parent[x] = find(parent, parent[x]);   // point straight at the root
  }
  return parent[x];
}

// the chain from the picture: 3 -> 2 -> 1 -> 0, and 5 -> 2, 4 -> 0
const parent = [0, 0, 1, 2, 0, 2];
console.log("before: " + parent.join(", "));

console.log("find(3) = " + find(parent, 3));          // 0
console.log("after:  " + parent.join(", "));          // 0, 0, 0, 0, 0, 2

// path halving, the iterative cousin
function findHalving(parent, x) {
  while (parent[x] !== x) {
    parent[x] = parent[parent[x]];                    // skip one level
    x = parent[x];
  }
  return x;
}
console.log("find(5) = " + findHalving(parent, 5));   // 0

Java

import java.util.*;

public class Main {
    // Find with path compression (recursive: fix the pointer on the way back)
    static int find(int[] parent, int x) {
        if (parent[x] != x) {
            parent[x] = find(parent, parent[x]);   // point straight at the root
        }
        return parent[x];
    }

    // path halving, the iterative cousin
    static int findHalving(int[] parent, int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]];         // skip one level
            x = parent[x];
        }
        return x;
    }

    static String show(int[] a) {
        return Arrays.toString(a).replaceAll("[\\[\\]]", "");
    }

    public static void main(String[] args) {
        // the chain from the picture: 3 -> 2 -> 1 -> 0, and 5 -> 2, 4 -> 0
        int[] parent = {0, 0, 1, 2, 0, 2};
        System.out.println("before: " + show(parent));

        System.out.println("find(3) = " + find(parent, 3));          // 0
        System.out.println("after:  " + show(parent));               // 0, 0, 0, 0, 0, 2

        System.out.println("find(5) = " + findHalving(parent, 5));   // 0
    }
}

Go

package main

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

// find with path compression (recursive: fix the pointer on the way back).
func find(parent []int, x int) int {
	if parent[x] != x {
		parent[x] = find(parent, parent[x]) // point straight at the root
	}
	return parent[x]
}

// findHalving is path halving, the iterative cousin.
func findHalving(parent []int, x int) int {
	for parent[x] != x {
		parent[x] = parent[parent[x]] // skip one level
		x = parent[x]
	}
	return x
}

func show(a []int) string {
	parts := make([]string, len(a))
	for i, v := range a {
		parts[i] = strconv.Itoa(v)
	}
	return strings.Join(parts, ", ")
}

func main() {
	// the chain from the picture: 3 -> 2 -> 1 -> 0, and 5 -> 2, 4 -> 0
	parent := []int{0, 0, 1, 2, 0, 2}
	fmt.Println("before: " + show(parent))

	fmt.Println("find(3) =", find(parent, 3)) // 0
	fmt.Println("after:  " + show(parent))    // 0, 0, 0, 0, 0, 2

	fmt.Println("find(5) =", findHalving(parent, 5)) // 0
}

Time: O(1) amortized (practically) · Extra space: O(1) (O(n) for recursion depth). One find may be slow, but it flattens the tree so well that, averaged over many operations, each costs almost constant time.

Watch out for

  • Using compression but forgetting to store the result: find(parent[x]) without the assignment flattens nothing.
  • Recursive compression on a million-long chain can overflow the call stack. Prefer the iterative path-halving form for huge inputs.
  • Thinking compression changes the answer. It only changes the shape; the roots and the sets stay identical.

Quick check

  1. What does path compression do after a find?
    • Deletes the root
    • Points every item on the path straight at the root
    • Sorts the array
    • Doubles the tree height
  2. In the picture, after find(3), how many hops does find(5) need?
    • 1
    • 0
    • 3
    • 2
  3. Does compression change who belongs to which set?
    • Yes, it merges sets
    • Yes, it splits sets
    • No, only the tree shape changes
    • Only for the root