Rank Transform of an Array

Given an integer array arr, replace every element with its rank. The smallest value gets rank 1, the next larger distinct value gets rank 2, and so on. Equal values share the same rank, and ranks are as small as possible.

30:00

Rank Transform of an Array
easy
Free written solution
Topics
Companies

Given an integer array arr, replace every element with its rank. The smallest value gets rank 1, the next larger distinct value gets rank 2, and so on. Equal values share the same rank, and ranks are as small as possible.

Example 1:
Input: {"arr":[40,10,20,30]}
Output: [4,1,2,3]
Constraints:
  • 0≤arr.length≤1050 \leq \text{arr.length} \leq 10^5

  • −109≤arr[i]≤109-10^9 \leq \text{arr}[i] \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"arr":[40,10,20,30]}

A value's rank is its position among the distinct values in sorted order. Build a value-to-rank map, then look each element up.

arr (original order)

.

40

 

.

10

 

.

20

 

.

30

 

rank staircase: one step per distinct value (0 of 4)

new value climbs a step

repeat reuses its step

lookup for arr[i]

Variables
VariableValue
n4
rank size0
DepthFunction Call
Stack empty
0/10