Problem Statement:
You are given an array of unique values, you need to replace the array with its corresponding rank.
Rank meaning, the first min will have rank 1, second min will have rank2 etc…
Example:
Input: arr = [1, 2, 5, 10, 4]
Output arr = [1, 2, 4, 5, 3]
Solution Explanation:
Simple approach is to sort the array and assign the rank to the elements.
We need to make copy of original array.
Then sort the copy array and insert into the map.
Then loop through the original array and replace each element with its rank from the map created earlier.
Code Solution
#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
#include <unordered_map>
using namespace std;
vector<int> solution(vector<int>& arr)
{
vector<int> dupArray = arr;
sort(dupArray.begin(), dupArray.end());
unordered_map<int, int> assignRank;
int rank = 1;
for (int num : dupArray)
{
if (assignRank.find(num) == assignRank.end())
{
assignRank[num] = rank;
rank++;
}
}
vector<int> result;
for (int num : arr)
{
result.push_back(assignRank[num]);
}
return result;
}
int main()
{
vector<int> arr = {1, 2, 5, 10, 4};
vector<int> res = solution(arr);
for (int x : res)
{
cout << x << " ";
}
return 0;
}
Output
1 2 4 5 3