Rank Transform of an Array
Given an array of integers arr, replace each element with its rank. The rank is a 1-indexed integer representing the position of the element when the array is sorted in ascending order. Equal values share the same rank. For example, the smallest element gets rank 1, the next smallest gets rank 2, and so on.
The solution sorts a copy of the array with duplicates removed, then assigns ranks to unique values. A hash map stores the rank of each unique value. Finally, iterate through the original array and replace each element with its rank from the map.
This uses sorting for ordering and a hash map for O(1) lookup during the replacement pass. The time is O(n log n) for sorting plus O(n) for the passes. Memory is O(n) for the hash map and sorted array.
Edge cases include an empty array (return []), a single element (return [1]), all elements equal (return array of 1s), and negative values.
The rank transform combines sorting with hash map lookups: sort unique values, assign ranks in order, then map each original element to its rank via the hash map. This two-phase approach (build mapping, then apply) is a common pattern in array transformation problems.
The rank transform has applications in data normalization and competitive ranking where absolute values are replaced with relative ordering positions.Example Input & Output
Single element.
40->4, 10->1, 20->2, 30->3.
Same rank for equal values.
Empty.
12 appears twice, both rank 3.
Algorithm Flow

Solution Approach
Sort unique values. Assign ranks in a hash map. Replace each element with its rank.
Time O(n log n), Space O(n).
Best Answers
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
int[] sorted=arr.clone();
Arrays.sort(sorted);
Map<Integer,Integer> rank=new HashMap<>();
int r=1;
for (int v:sorted) {
if (!rank.containsKey(v)) rank.put(v,r++);
}
int[] res=new int[arr.length];
for (int i=0;i<arr.length;i++) res[i]=rank.get(arr[i]);
return res;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
