Similar Problems
Similar Problems not available
Replace each element of an array by its corresponding rank - Leetcode Solution
LeetCode: Replace each element of an array by its corresponding rank Leetcode Solution
Difficulty: Unkown
Topics: hash-table
Given an array of n elements, replace each element of the array by its corresponding rank. The rank of the lowest element is 1 and the highest element is n. Take a look at the example given below:
Input : 2, 5, 3, 7, 6
Output: 1, 3, 2, 5, 4
Explanation: Since 2 is the smallest element in the array, its rank is 1, 3 is the second smallest element its rank is 2 and so on.
Solution
The easiest way to solve this problem would be to iterate over the array and store the elements in a sorted map. The map would contain the element as key and the index of the element as the value.
Once we are done iterating over the array, we can just iterate over the sorted map. This will give us all the elements present in the sorted map in ascending order and we can fill up the rank of each element
Replace each element of an array by its corresponding rank Solution Code
1