Given an array of integers arr
, where each integer is not necessarily unique, perform a “rank transform” of the array. The rank of each element is its position in the list of unique values sorted in ascending order. The smallest element receives a rank of 1, the second smallest a rank of 2, and so on.
arr = [40, 10, 20, 30]
[4, 1, 2, 3]
arr
:
def arrayRankTransform(arr):
if not arr:
return []
# Step 1: Get the sorted list of unique elements
sorted_unique = sorted(set(arr))
# Step 2: Create a rank mapping
rank_map = {val: rank + 1 for rank, val in enumerate(sorted_unique)}
# Step 3: Transform the original array to its rank representation
return [rank_map[val] for val in arr]
# Example usage
arr = [40, 10, 20, 30]
print(arrayRankTransform(arr)) # Output: [4, 1, 2, 3]
The time complexity of this solution is:
n
is the number of elements in the input array.Thus, the overall time complexity is O(n log n) due to the sorting step. The space complexity is O(n) due to the storage of the rank_map
and the unique sorted values.
If there are further specific constraints or requirements, please let me know!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?