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:
Example 1:
Input: arr = [40,10,20,30] Output: [4,1,2,3] Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.
Example 2:
Input: arr = [100,100,100] Output: [1,1,1] Explanation: Same elements share the same rank.
Example 3:
Input: arr = [37,12,28,9,100,56,80,5,12] Output: [5,3,4,2,8,6,7,1,3]
Constraints:
0 <= arr.length <= 105-109 <= arr[i] <= 109This approach involves sorting the array to determine the rank of each element. After sorting, unique elements are mapped to their ranks.
The C solution involves sorting the array and creating a map of ranks. Sorted unique elements are assigned ranks incrementally. The original elements are then mapped to their ranks using this mapping.
C++
Java
Python
C#
JavaScript
Time Complexity: O(N log N) due to sorting.
Space Complexity: O(N) for storing the sorted array and rank map.
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.
The C coordinate compression solution involves sorting the array and creating a rank map by compressing coordinates. This map is used for rank assignment efficiently.
C++
Python
Time Complexity: O(N log N) due to sorting and binary search operations.
Space Complexity: O(N) for rank maps.
| Approach | Complexity |
|---|---|
| Sorting and Ranking | Time Complexity: O(N log N) due to sorting. |
| Using Coordinate Compression | Time Complexity: O(N log N) due to sorting and binary search operations. |
Rank Transform of an Array | Leetcode 1331 • Techdose • 4,088 views views
Watch 9 more video solutions →Practice Rank Transform of an Array with our built-in code editor and test cases.
Practice on FleetCode