Heaps Top K
412. Rank Transform of an Array
You are given an array of integers arr. Replace each element with its rank, and return the array of ranks.
The answer keeps the order of arr: its element i is the rank of arr[i].
The rank of an element says where its value sits among the different values in arr, from smallest to
largest. The smallest value has rank 1, the next larger value has rank 2, and so on. Equal elements share one
rank, and the ranks have no gaps: after two elements of rank 1, the next larger value has rank 2.
If arr is empty, return an empty array.
Example 1
Input: arr = [40, -5, 12, 40, 0]
[4,1,3,4,2]Explanation: The different values, from smallest to largest, are −5, 0, 12 and 40. So −5 has rank 1, 0 has rank 2, 12 has rank 3, and both 40s have rank 4.
Example 2
Input: arr = [-8, 1000000000, -8, -1000000000]
[2,3,2,1]Explanation: −109 is the smallest value, so it has rank 1. The two −8s share rank 2, and 109 has rank 3.
Example 3
Input: arr = [6, 6, 6]
[1,1,1]Explanation: Every element is 6, so every element has rank 1.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ arr.length ≤ 105-109 ≤ arr[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.