Rank Transform of an Array Problem
Description
LeetCode Problem 1331.
Given an array of integers arr, replace each element with its rank.
The rank represents how large the element is. The rank has the following rules:
- Rank is an integer starting from 1.
- The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
- Rank should be as small as possible.
Example 1:
Input: arr = [40,10,20,30]
Output: [4,1,2,3]
Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.
Example 2:
Input: arr = [100,100,100]
Output: [1,1,1]
Explanation: Same elements share the same rank.
Example 3:
Input: arr = [37,12,28,9,100,56,80,5,12]
Output: [5,3,4,2,8,6,7,1,3]
Constraints:
0 <= arr.length <= 10^5-10^9 <= arr[i] <= 10^9
Solution
Approach: Sort the Distinct Values
The rank of a value is 1 plus the number of distinct values smaller than it. Equal elements then get the same rank, larger elements get larger ranks, and there are no gaps, which is exactly what "as small as possible" asks for.
So we take the distinct values of arr, sort them, and give them the ranks 1, 2, 3, ... in that order, in a hash map from value to rank (the C++ version finds the rank with a binary search in the sorted list instead). Then each element of arr is replaced by the rank of its value.
The tricky case is duplicates: the ranks must be given to distinct values, otherwise [100,100,100] would wrongly become [1,2,3]. An empty array simply gives an empty answer.
Complexity: O(n log n) time for sorting, and O(n) extra space for the sorted values and the map.
class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
# The rank of a value is its position among the distinct values, in increasing order.
rank = {x: i + 1 for i, x in enumerate(sorted(set(arr)))}
return [rank[x] for x in arr]