Sponsored
Sponsored
This approach involves sorting the array to determine the rank of each element. After sorting, unique elements are mapped to their ranks.
Time Complexity: O(N log N) due to sorting.
Space Complexity: O(N) for storing the sorted array and rank map.
1var arrayRankTransform = function(arr) {
2 const sorted = [...arr].sort((a, b) => a - b);
3
4 const rankMap = new Map();
5 let rank = 1;
6 for (let num of sorted) {
7 if (!rankMap.has(num)) {
8 rankMap.set(num, rank++);
9 }
10 }
11
12 return arr.map(num => rankMap.get(num));
13};
The JavaScript solution sorts the array and uses a Map to remember ranks for unique elements. Using this map, it efficiently transforms the original array.
Coordinate compression is a method to map large ranges of numbers to smaller ranges, maintaining their relative order. This approach uses this idea to assign ranks.
Time Complexity: O(N log N) due to sorting and binary search operations.
Space Complexity: O(N) for rank maps.
1def arrayRankTransform(arr):
2 sorted_arr =
Coordinate compression in this Python solution involves using sorting and a dictionary for mapping ranks. The sorted elements guide the rank allocation to the array with minimal memory use.