Coordinate compression: shrinking big values to ranks

Video lessonComing soon

1 Values too big to be indexes

For each value in an array, we want to know how many values after it are strictly smaller. Our running example is:

400-7110⁹2403124-75
nums: six values, one of them 10⁹

The answer is [3, 0, 3, 2, 1, 0]. The 40 at the front has −7, 12 and −7 after it. The other 40 is equal to it, so it does not count.

A good plan walks from the right and keeps a count array of the values seen so far, as in the lesson on counting with arrays and maps. At each value v, the answer is the total of the slots below v. The Fenwick tree from the last lesson gives that total quickly, even as the counts change.

The plan breaks on the values themselves. They go from −10⁹ to 10⁹, so the count array needs about 2 × 10⁹ slots. That is around 8 GB, far more memory than a program gets. And −7 has no slot at all, since an index cannot be negative.

Yet the array holds only six values. And the question never asks how big a value is. It only asks whether one value is smaller than another.

2 Only the places matter

A race result lists each runner's time, like 2:41:07 or 2:39:55. To know who beat whom, we do not need the times. The places are enough: 1st, 2nd, 3rd. Two runners with the same time share a place.

We do the same with the array. Each value gets its rank: its place among the distinct values, counting from the smallest. The distinct values here are −7, 12, 40 and 10⁹, so they get the ranks 1, 2, 3 and 4.

400-7110⁹2403124-75
nums
301142332415
ranks: the same order, in small numbers

Replacing every value by its rank is coordinate compression. The ranks keep everything a comparison can see:

  • A smaller value gets a smaller rank. The distinct values are listed in increasing order, so a value further left in the list is smaller.
  • Equal values get the same rank. Each value appears in the list once, so both 40s land on 3, and both −7s on 1.

So any question that only compares values has the same answer on the ranks. And the ranks are small. With n values there are at most n distinct ones, so the ranks run from 1 to at most n. A count array over the ranks needs only n + 1 slots.

3 Sort, remove duplicates, look up

Compression takes three steps. We sort a copy of the array, remove the duplicates from it, and look up each value's place in what is left. The list that is left is distinct.

From values to ranks
400-7110⁹2403124-75
nums
-70-7112240340410⁹5
Sort a copy

To find a value in distinct, we binary search for it. The lower bound from the binary search lesson, the first index whose value is at least v, lands on v itself, because v is in the list. Indexes start at 0, so the rank is the index plus 1.

ValueLower bound in distinctRank
4023
−701
10⁹34
1212

The second 40 and the second −7 find the same indexes as the first ones. That is the reason for step 2. With the duplicates gone, every value has one place, and the ranks run 1, 2, 3, 4 with no gaps.

A map works for the lookup too. We walk distinct once and store each value's rank. The map must be filled from the sorted list, though, because a map by itself keeps no order.

4 Counting smaller values over the ranks

Now the plan from the first section works on the ranks [3, 1, 4, 3, 2, 1]. We walk from the right and keep seen: for each rank, how many values with that rank lie to the right of the current one. At index i:

  1. The answer is how many seen values have a rank below rank. That is the total of seen[1] to seen[rank - 1].
  2. Then we add 1 to seen[rank].

We ask before we add, so a value never counts itself. That matters for a question like "smaller or equal", where the total runs up to the rank itself.

In the steps below, the blue slots are the ones we add up, and the orange slot is the one that gets 1 more. Slot 0 is never used, because ranks start at 1:

Walking from the right with seen
301142332415i
ranks
0011020304
rank 1: nothing below. counts[5] = 0

The same walk as a table, where seen is shown after the add:

inums[i]rankTotal below rankcounts[i]seen[1..4] after
5−71001, 0, 0, 0
4122111, 1, 0, 0
3403221, 1, 1, 0
210⁹4331, 1, 1, 1
1−71002, 1, 1, 1
0403332, 1, 2, 1

Row 0 shows why equal values must share a rank. When the front 40 asks, seen[3] holds the other 40. The total stops at rank 2, so that 40 is left out, as "strictly smaller" requires.

Adding up the slots with a loop costs up to n steps per value, so about n² in all. The Fenwick tree does both jobs in O(log n). prefix(rank - 1) gives the total below the rank, and update(rank, 1) adds the 1. Its array has n + 1 slots, because the ranks never pass n.

5 The code

This is Count of Smaller Numbers After Self, so the function is countSmaller. The Fenwick tree is the one from the last lesson. The solution compresses, then walks from the right as in the table.

C++

unique does not shrink the vector. It moves the repeats to the end and returns where they start, and erase cuts them off. It only catches repeats that sit next to each other, so the sort comes first. lower_bound returns an iterator, and subtracting begin() turns it into an index.

Arrays.binarySearch is safe here. With repeats in the array, it can return any of the equal values. In distinct every value appears once, so it returns that value's index.

sorted(set(nums)) removes the duplicates and sorts what is left. bisect_left is the lower bound.

Sort with (a, b) => a - b. Without it, sort compares the numbers as text and gives [-7, 1000000000, 12, 40], so 10⁹ would get rank 2. There is no built-in binary search, so lowerBound is the loop from the binary search lesson.

sort.SearchInts is the lower bound. Go has no remove-duplicates call for this, so the loop keeps a value only when it differs from the one before it in sorted order.

Sort before dedup. It only removes neighbours that are equal. partition_point returns the first index where the condition fails, which is the lower bound. Ranks are usize, and i & i.wrapping_neg() is the lowest set bit.

Array.BinarySearch is safe here. With repeats in the array, it can return any of the equal values. In distinct every value appears once, so it returns that value's index. Distinct() needs using System.Linq;.

Every tab returns [3, 0, 3, 2, 1, 0] on our array.

6 What it costs

  • Time: O(n log n). The sort takes n log n steps. Each of the n lookups is a binary search, and each Fenwick query and update takes log n steps. At n = 10⁵ that is a few million steps, well inside the time limit.
  • Space: O(n). The sorted copy, counts and the Fenwick array each hold about n values, whatever the size of the values.

The lesson on counting pairs while merge sorting answers the same question in O(n log n) too. Merge sort compares the values directly, so it needs no ranks. The Fenwick walk takes values one at a time, so it also fits problems where values arrive in order and each one asks about those already seen.

7 Mistakes and edge cases

  • Giving equal values different ranks. Numbering the sorted copy 1 to 6 without removing duplicates gives the two 40s the ranks 4 and 5. If the front 40 gets 5, it counts the other 40 as smaller, and counts[0] comes out 4 instead of 3.
  • Rank 0 in the Fenwick tree. Without the + 1, −7 gets rank 0. update(0, 1) adds 0 & -0 to i. That is 0, so i never moves and the loop never ends. The program gets TLE.
  • Looking up a value that is not in the list. To count the values at most 30, the lower bound of 30 gives index 2, the 40, so rank 3 would count the 40s too. The right call is prefix(2), where 2 is the upper bound: how many distinct values are at most 30. For a value in the list, both bounds give the same rank, so this bug only shows on a missing value.
  • A hash map in place of the sort. Giving each new value the next number, in the order the values appear, gives 40 → 1, −7 → 2, 10⁹ → 3 and 12 → 4. These are labels, not ranks: 12 now looks larger than 40. Labels are fine for questions about equal values, such as counting repeats, and wrong for anything about order.

8 When to compress

The sign is a plan that wants an array indexed by value, with values that are too large or negative, while the question only compares them. Count of Smaller Numbers After Self is that shape, with values up to 10⁹. Create Sorted Array through Instructions keeps the same counts while walking from the left: each value asks how many earlier values are smaller and how many are larger.

The same three steps help in other places:

  • Intervals with huge endpoints. Compress all the start and end points, then run a difference array over the ranks. distinct turns a rank back into the real point when a length is needed.
  • A few points on a huge grid. Compress the x values and the y values separately, each axis with its own list.
  • A segment tree over values. The next lesson's segment tree can sit over the ranks in the same way, for a maximum instead of a count.
Before building an array indexed by value, look at the range of the values. If it is much larger than n, sort, remove duplicates and work with ranks.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.