Replace each number with its rank among the distinct values in the array.
Given an integer array, assign a rank to every element based on its value relative to the other distinct values in the array.
- The smallest distinct value gets rank 1.
- The next larger distinct value gets rank 2.
- Equal values receive the same rank.
Return a new array where each position contains the rank of the original value at that position.
Input Format
- An integer array
arr. - The array may contain duplicate values and negative numbers.
Output Format
- Return an integer array
rankedof the same length asarr. ranked[i]is the rank ofarr[i]among the distinct values inarr.
Constraints
1 <= arr.length- Ranks are 1-indexed.
- Equal values must map to the same rank.
- Use the relative ordering of distinct values only, not the magnitude gaps between them.
Example 1
Input
arr = [40, 10, 20, 30]
Output
[4, 1, 2, 3]
Explanation
The distinct values in sorted order are [10, 20, 30, 40]. Their ranks are 1, 2, 3, and 4 respectively.
Example 2
Input
arr = [100, 100, 100]
Output
[1, 1, 1]
Explanation
All elements are equal, so they all receive the same smallest rank.
Show 1 more example
Example 3
Input
arr = [37, 12, 28, 9, 100, 56, 80, 5, 12]
Output
[5, 3, 4, 2, 8, 6, 7, 1, 3]
Explanation
After sorting the distinct values, each number is replaced by its 1-indexed position among the unique values.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.