Rank Transform of an Array (LeetCode 1331): Solution and Explanation
Replace every element of an integer array with its rank: the smallest value becomes 1, the next larger distinct value becomes 2, and equal values share a rank. Ranks have no gaps.
Intuition
The rank of a value is 1 plus the number of distinct values smaller than it. Nothing else about the array matters.
Sorting puts the values in exactly the order ranks are handed out. Walking the sorted copy, every value you have not met before is the next distinct value, so it gets the next rank.
Duplicates sit next to each other after sorting. The second copy is already in the map, so it is skipped and keeps the shared rank.
Once the map from value to rank exists, the answer is a single lookup per element in the original order.
Approach: Sort a copy, then map value to rank
- Make a sorted copy of
arr(the original order is needed for the output). - Create an empty map
rank. - For each value
vin the sorted copy, ifvis not inrank, setrank[v] = len(rank) + 1. - Build the answer by replacing each
arr[i]withrank[arr[i]].
Step-by-step example
arr = [40,10,20,30]
- Sorted copy: [10,20,30,40].
- 10 is new, rank[10] = 1. 20 is new, rank[20] = 2.
- 30 is new, rank[30] = 3. 40 is new, rank[40] = 4.
- Map the original order: 40 -> 4, 10 -> 1, 20 -> 2, 30 -> 3.
- Return [4,1,2,3].
Code: Python, Java, C++
1class Solution:
2 def arrayRankTransform(self, arr: List[int]) -> List[int]:
3 rank = {}
4 for v in sorted(arr):
5 if v not in rank:
6 rank[v] = len(rank) + 1
7 return [rank[v] for v in arr]1class Solution {
2 public int[] arrayRankTransform(int[] arr) {
3 int[] sorted = arr.clone();
4 Arrays.sort(sorted);
5 Map<Integer, Integer> rank = new HashMap<>();
6 for (int v : sorted) {
7 if (!rank.containsKey(v)) {
8 rank.put(v, rank.size() + 1);
9 }
10 }
11 int[] result = new int[arr.length];
12 for (int i = 0; i < arr.length; i++) {
13 result[i] = rank.get(arr[i]);
14 }
15 return result;
16 }
17}1class Solution {
2public:
3 vector<int> arrayRankTransform(vector<int>& arr) {
4 vector<int> sorted = arr;
5 sort(sorted.begin(), sorted.end());
6 unordered_map<int, int> rank;
7 for (int v : sorted) {
8 if (!rank.count(v)) {
9 rank.emplace(v, (int)rank.size() + 1);
10 }
11 }
12 vector<int> result(arr.size());
13 for (size_t i = 0; i < arr.size(); i++) {
14 result[i] = rank[arr[i]];
15 }
16 return result;
17 }
18};Time and space complexity
O(n log n)
Sorting dominates. Building the map and the lookups are O(n) on average.
O(n)
The sorted copy and the map each hold up to n entries.
Other approaches
Sort distinct values and binary search (time O(n log n), space O(n))
Sort the set of distinct values, then for each element find its index with binary search and add 1. Same complexity, no hash map.
Sort indices (time O(n log n), space O(n))
Sort the indices 0..n-1 by value and walk them, increasing the rank only when the value changes. This writes ranks straight into the result without a map.
Count smaller values for each element (time O(n^2), space O(n))
For each element, count the distinct values smaller than it. Correct but quadratic, too slow for 10^5 elements.
Common mistakes
- Using the index in the sorted array as the rank. With duplicates that leaves gaps; ranks must count distinct values only.
- Sorting the input in place and then losing the original order needed for the output.
- Using the default JavaScript sort, which compares numbers as strings and puts 100 before 20. Pass a numeric comparator.
- Forgetting the empty array, which must return an empty array.
Frequently asked questions
Why do equal values get the same rank?
The rank only measures how many distinct values are smaller. Equal values have the same set of smaller values, so their ranks match.
Do negative numbers need special handling?
No. Sorting orders negatives before positives, and the map keys work for any integer.
Can this be done in linear time?
Not in general, because the ranks reveal the sorted order of the distinct values, which needs comparison sorting. With a small value range a counting sort would make it linear.