Technique
Coordinate Compression
Replace large or sparse coordinates by their ranks among all values that matter, so arrays, BITs, and segment trees can index them.
0/10 solved
Recognise it
The signal
values up to 1e9 but only n of them matter
1Brute force
Allocate arrays of size max value (too large) or use maps everywhere.
2The observation
Memory proportional to value range: only relative order is needed.
3Why it works
rank(x) < rank(y) iff x < y for all relevant values.
Reach for it when
- +BIT/seg-tree over values
- +sweep over sparse coordinates
Not when
- ×online queries with unseen values (use ordered map or dynamic/sparse seg-tree)
- ×distances between coordinates matter (store original values per rank)
Practice
- Salary QueriesCSESMedium
- Distinct Values QueriesCSESMedium
- Area of RectanglesCSESHard
- Rectangle Area IIHard
- Maximum Sum QueriesHard
- Count of Smaller Numbers After SelfGoogle, CitadelHard
- Reverse PairsGoogle, CitadelHard
- Increasing Subsequence IICSESHard
- Count of Range SumHard
- Nested Ranges CountCSESHard
Pitfalls
Misconceptions
- !forgetting to include query values (not just data values) before compressing
Go deeper4 combinations · resources
Combinations
Difference Array & Line Sweep+Coordinate Compression
concurrency/overlap counts with huge time values
- Difference Array & Line Sweep:
- range add as two point events
- Coordinate Compression:
- maps 1e9 coordinates to dense indices
Sweep Line (events + active set)+Segment Tree / Fenwick (BIT)+Coordinate Compression
area/perimeter of union of rectangles
- Sweep Line (events + active set):
- moves over x events
- Segment Tree / Fenwick (BIT):
- maintains covered length on y with range add
- Coordinate Compression:
- maps y endpoints to segment tree leaves
Segment Tree / Fenwick (BIT)+Coordinate Compression
count elements smaller/greater than x to the left/right; inversions
- Segment Tree / Fenwick (BIT):
- counts values in ranges (BIT)
- Coordinate Compression:
- maps values to ranks
Count of Smaller Numbers After SelfReverse PairsSalary Queries
Longest Increasing Subsequence+Segment Tree / Fenwick (BIT)+Coordinate Compression
count increasing subsequences; LIS with weights
- Longest Increasing Subsequence:
- dp over chains ending at each value
- Segment Tree / Fenwick (BIT):
- prefix max/sum over smaller values
- Coordinate Compression:
- value ranks