Rank Transform of an Array - Problem

Given an array of integers arr, your task is to transform each element into its rank.

Think of ranking like a leaderboard in a game - the higher your score, the higher your rank! Here's how the ranking system works:

  • Ranks start from 1 (not 0)
  • Larger elements get higher ranks - if element A > element B, then rank(A) > rank(B)
  • Equal elements get equal ranks - identical values share the same rank
  • Ranks should be consecutive - use the smallest possible rank values

Example: For array [40, 10, 20, 30]:
• 10 is smallest → rank 1
• 20 is next → rank 2
• 30 is next → rank 3
• 40 is largest → rank 4
Result: [4, 1, 2, 3]

Input & Output

example_1.py — Basic ranking
$ Input: arr = [40, 10, 20, 30]
Output: [4, 1, 2, 3]
💡 Note: After sorting unique elements [10, 20, 30, 40], we get ranks: 10→1, 20→2, 30→3, 40→4. So [40,10,20,30] becomes [4,1,2,3].
example_2.py — Duplicate elements
$ Input: arr = [100, 100, 100]
Output: [1, 1, 1]
💡 Note: All elements are the same, so they all get rank 1. There's only one unique value, so all elements share the lowest rank.
example_3.py — 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: [5,9,12,28,37,56,80,100] get ranks [1,2,3,4,5,6,7,8]. Note that both 12's get rank 3.

Constraints

  • 0 ≤ arr.length ≤ 105
  • -109 ≤ arr[i] ≤ 109
  • Array elements can be negative, zero, or positive

Visualization

Tap to expand
Array Rank Transform VisualizationCompetition Scores40Alice10Bob20Carol30DavidSorted Ranking10Rank 120Rank 230Rank 340Rank 4Rank Lookup ProcessScore → Rank40 → 410 → 120 → 230 → 3Final RankingsAlice: 40 → Rank 4Bob: 10 → Rank 1Carol: 20 → Rank 2David: 30 → Rank 3Result: [4,1,2,3]
Understanding the Visualization
1
Collect all scores
Gather all unique scores from participants: [40, 10, 20, 30]
2
Sort by performance
Order scores from lowest to highest: [10, 20, 30, 40]
3
Assign consecutive ranks
Give ranks 1, 2, 3, 4 to sorted scores respectively
4
Look up each participant's rank
Map original scores to their assigned ranks: [4, 1, 2, 3]
Key Takeaway
🎯 Key Insight: Instead of comparing each element with all others (O(n²)), we can sort unique values once and create a lookup table for O(1) rank retrieval, achieving optimal O(n log n) time complexity.
Asked in
Google 42 Amazon 38 Meta 25 Microsoft 31
73.2K Views
Medium Frequency
~15 min Avg. Time
1.8K 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