Coordinate compression
Intermediate · 7 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Coordinate compression swaps huge or scattered values (like timestamps or big ID numbers) for their rank, 1st, 2nd, 3rd and so on, keeping the order but shrinking the range so you can use small arrays. It makes other fast tools usable.
Practical use cases
- Web app: Orders per timestamp on an analytics page. A dashboard counts how many orders happened before each moment, but timestamps are huge numbers like 1700000000. A table with a slot for every second would use gigabytes. Replacing the 10,000 distinct timestamps by ranks 1 to 10,000 lets a small array do the counting. The dashboard answers in milliseconds, and the server does not crash from trying to allocate a giant table.
- Web app: Leaderboard rank and percentile. A quiz site shows "you scored better than 82% of players". Scores are arbitrary. Mapping each distinct score to its rank lets the site count players below a score quickly with a small counting structure. Each score lookup is instant, so the result page can show a rank to millions of players.
- Web app: Seat or ticket numbers with big gaps. An event system has ticket IDs like 9000000001 and 9000450223, but only a few thousand are in use. Compressing them to 1..N lets you use a simple counting array for range questions. It takes a few kilobytes instead of crashing on a table with billions of slots.
- System: Sweep line with huge coordinates. Map tools and CAD programs have coordinates up to billions, but only a few thousand of them matter. Compression keeps just those interesting values, so even a world-sized map is processed as quickly as a small town.
The story: The Ticket Numbers That Were Too Big
The school fair gave out raffle tickets with long, fancy numbers printed on them: 42, 500, 77777 and even 900000. Only six children bought tickets, but Kabir had to count how many times each number was drawn.
Kabir wanted a neat tally board with one box per number. Then he realized the board had to be as long as the biggest number. Nine hundred thousand boxes, for six children! The school hall was not big enough.
Mrs. Sharma looked at the six numbers and said, "You do not care that 900000 is nine hundred thousand. You only care that it is the biggest, and 42 is the smallest. Give them rank cards instead: 0, 1, 2, 3."
Kabir made a mini tally board with four boxes and a small list that translated big numbers into rank numbers. Problem solved. Squeezing huge values into small ranks while keeping their order is called coordinate compression.
How to spot this problem, and where you need it
Your values are huge or scattered, so using them as array positions would waste enormous memory, even though you only care about their order or how many there are.
Signs you need it
- You want to use an array or counting structure indexed by a value like a timestamp, ID or price, but the range is millions or billions.
- Only the relative order of values matters, such as who is bigger or smaller, not their exact size.
- Memory runs out or the program crashes when you try to allocate an array for the biggest value.
Where to use it in a project
- Analytics and reports over timestamps or large IDs where only the order of values matters.
- Leaderboards, percentile and rank features that show how a user compares with everyone else.
- Preparing input for counting and range-query tools that need small, tidy numbers.
The solution
Collect all the values you will use, remove duplicates and sort them. Number the sorted list 1, 2, 3 and so on. Keep a lookup from each original value to its number. From then on, use the small number everywhere inside your algorithm, and translate back to the real value only when you show results.
Payoff: Before: an array with a billion slots that cannot even be created. After: an array of 10,000 slots that uses a few kilobytes.
Explain it like I am 8
Imagine a class photo where kids stand by height. You do not need their exact centimetres to say who is taller: just call them 1st, 2nd, 3rd. Replacing the big complicated numbers by "who is 1st, 2nd, 3rd" is compression.
How it works, step by step
- Copy all the values into a list, remove duplicates and sort it.
- The position of a value in that sorted list is its new small number (its rank).
- Build a look-up from value to rank (a map, or binary search on the sorted list).
- Replace every original value by its rank and run your normal algorithm on small numbers.
- Translate back at the end if you need the real values.
The code in four languages
PHP
<?php
// Replace big values by small ranks (0 = smallest), keeping their order.
function compress(array $values): array {
$uniq = array_values(array_unique($values)); // 1. distinct values
sort($uniq); // 2. sorted
$rank = array_flip($uniq); // 3. value => rank
return [array_map(fn($v) => $rank[$v], $values), $uniq];
}
$tickets = [900000, 42, 77777, 42, 500, 900000];
[$ranks, $sorted] = compress($tickets);
echo implode(',', $ranks), "\n"; // 3,0,2,0,1,3
// Now a tiny array is enough to count:
$count = array_fill(0, count($sorted), 0);
foreach ($ranks as $r) $count[$r]++;
foreach ($sorted as $r => $original) echo "$original appears $count[$r] time(s)\n";JavaScript
// Replace big values by small ranks (0 = smallest), keeping their order.
function compress(values) {
const uniq = [...new Set(values)].sort((a, b) => a - b); // distinct and sorted
const rank = new Map(uniq.map((v, i) => [v, i])); // value => rank
return [values.map(v => rank.get(v)), uniq];
}
const tickets = [900000, 42, 77777, 42, 500, 900000];
const [ranks, sorted] = compress(tickets);
console.log(ranks.join(',')); // 3,0,2,0,1,3
// Now a tiny array is enough to count:
const count = new Array(sorted.length).fill(0);
for (const r of ranks) count[r]++;
sorted.forEach((original, r) => console.log(original + ' appears ' + count[r] + ' time(s)'));Java
import java.util.*;
public class Main {
record Compressed(int[] ranks, int[] sorted) {}
// Replace big values by small ranks (0 = smallest), keeping their order.
static Compressed compress(int[] values) {
int[] uniq = Arrays.stream(values).distinct().sorted().toArray(); // distinct and sorted
Map<Integer, Integer> rank = new HashMap<>(); // value => rank
for (int i = 0; i < uniq.length; i++) rank.put(uniq[i], i);
int[] ranks = new int[values.length];
for (int i = 0; i < values.length; i++) ranks[i] = rank.get(values[i]);
return new Compressed(ranks, uniq);
}
public static void main(String[] args) {
int[] tickets = {900000, 42, 77777, 42, 500, 900000};
Compressed c = compress(tickets);
System.out.println(Arrays.toString(c.ranks())); // [3, 0, 2, 0, 1, 3]
// Now a tiny array is enough to count:
int[] count = new int[c.sorted().length];
for (int r : c.ranks()) count[r]++;
for (int r = 0; r < c.sorted().length; r++) {
System.out.println(c.sorted()[r] + " appears " + count[r] + " time(s)");
}
}
}Go
package main
import (
"fmt"
"sort"
)
// compress replaces big values by small ranks (0 = smallest), keeping their order.
// It also returns the sorted distinct values, so rank r maps back to uniq[r].
func compress(values []int) ([]int, []int) {
seen := map[int]bool{}
var uniq []int
for _, v := range values { // 1. distinct values
if !seen[v] {
seen[v] = true
uniq = append(uniq, v)
}
}
sort.Ints(uniq) // 2. sorted
rank := map[int]int{}
for i, v := range uniq { // 3. value => rank
rank[v] = i
}
ranks := make([]int, len(values))
for i, v := range values {
ranks[i] = rank[v]
}
return ranks, uniq
}
func main() {
tickets := []int{900000, 42, 77777, 42, 500, 900000}
ranks, sorted := compress(tickets)
fmt.Println(ranks) // [3 0 2 0 1 3]
// Now a tiny array is enough to count:
count := make([]int, len(sorted))
for _, r := range ranks {
count[r]++
}
for r, original := range sorted {
fmt.Printf("%d appears %d time(s)\n", original, count[r])
}
}Time: O(n log n) · Extra space: O(n). Sorting is the main cost; afterwards every value is a small number from 0 to n-1.
Watch out for
- Forgetting to remove duplicates, which gives equal values different ranks.
- Using compression when the actual distance between values matters (e.g. sums of the values). Only the order survives.
- Sorting strings or mixed types with the default sort: in JavaScript always pass
(a, b) => a - bfor numbers.
Quick check
- What does compression keep?
- The order of values
- The exact gaps between values
- Nothing
- Values [10, 1000, 10, 50]. What is the rank of 50?
- 2
- 1
- 3
- Why compress at all?
- To make numbers prettier
- To avoid sorting
- To use a small array instead of a giant one