progress

~/problems / Arrays & hashing / Sorting, custom keys, coordinate compression

Rank among distinct values

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~10 min

Write compress(xs: list[int]) -> list[int] that replaces every value with its rank among the distinct values of xs, from 0: the smallest distinct value becomes 0, the next 1, and so on. Return a new list.

compress([100, 5, 100, 42])     # [2, 0, 2, 1]
compress([-3, 10**12, -3])      # [0, 1, 0]
compress([])                    # []

Constraints: len(xs) <= 2·10^5, values in [-10^18, 10^18].

⭐ Bonus: a speed test with 200,000 values earns a star in O(n log n).

Show hint

this is coordinate compression. Sort the distinct values once, then make each rank lookup O(1).

Topic: Sorting, custom keys, coordinate compression. sorted(key=...), multi-key and stable sorts, cmp_to_key, compressing coordinates.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc