Problem Description
Given an array of integers, replace each element with its rank. The rank of an element is defined as its position in the sorted order of the unique elements of the array (starting from 1). If two elements are equal, they share the same rank.
Key Insights
- Sorting the unique elements of the array helps to assign the smallest rank to the smallest element.
- A hash table (dictionary/map) is used to map each unique element to its corresponding rank.
- Iterating over the array and replacing elements using the hash table results in the final rank-transformed array.
- Handling duplicate elements properly ensures that equal elements receive the same rank.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the unique elements. Space Complexity: O(n) for the hash table and the output array.
Solution
We can solve the problem using the following approach:
- Extract the unique elements from the array.
- Sort these unique elements in ascending order.
- Create a mapping (hash table) where each unique element is assigned its rank (starting from 1).
- Iterate through the original array and replace each element with its corresponding rank from the mapping. This approach efficiently handles duplicates and ensures that the rank is as small as possible for each element.