Rank Transform of an Array - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
arr = [40,10,20,30]
›
Output:
[4,1,2,3]
💡 Note:
40 is the largest (rank 4), 10 is smallest (rank 1), 20 is second smallest (rank 2), 30 is third smallest (rank 3)
Example 2 — Duplicate Values
$
Input:
arr = [100,100,100]
›
Output:
[1,1,1]
💡 Note:
All elements are equal, so they all get the same rank 1 (smallest possible)
Example 3 — Mixed with Duplicates
$
Input:
arr = [37,12,28,9,100,56,80,5,12]
›
Output:
[6,2,4,1,8,7,3,5,2]
💡 Note:
Unique sorted values are [5,9,12,28,37,56,80,100] with ranks 1-8. Element 12 appears twice and both get rank 2
Constraints
- 0 ≤ arr.length ≤ 105
- -109 ≤ arr[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Original array with possibly duplicate values
2
Find Unique & Sort
Extract unique values and sort to determine rank order
3
Assign Ranks
Transform each element to its corresponding rank
Key Takeaway
🎯 Key Insight: Sort unique values first to establish the rank order, then map each element to its rank position
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code