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: [5,3,4,2,8,6,7,1,3]
💡 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 3

Constraints

  • 0 ≤ arr.length ≤ 105
  • -109 ≤ arr[i] ≤ 109

Visualization

Tap to expand
Rank Transform of an Array INPUT Original Array: 40 i=0 10 i=1 20 i=2 30 i=3 Replace each element with its rank Rank Rules: • Starts from 1 • Larger = Higher rank • Equal = Same rank arr = [40,10,20,30] ALGORITHM STEPS 1 Copy and Sort sorted = [10,20,30,40] 2 Create Rank Map Map value to rank Value Rank 10 1 20 2 30 3 40 4 3 Replace Values Use map to get ranks 4 Return Result O(n log n) time FINAL RESULT Value to Rank Transform: 40 --> 4 10 --> 1 20 --> 2 30 --> 3 Output Array: 4 1 2 3 [4, 1, 2, 3] OK Key Insight: Sort the array to determine relative ordering. Use a HashMap to store value-to-rank mappings. Only assign new rank when encountering a new (larger) value. This handles duplicates automatically. TutorialsPoint - Rank Transform of an Array | Optimal Solution
Asked in
Amazon 15 Facebook 12 Google 8 Microsoft 6
89.4K Views
Medium Frequency
~12 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen