![]() |
VOOZH | about |
Given an array with N distinct elements, convert the given array to a form where all elements are in the range from 0 to N-1. The order of elements is the same, i.e., 0 is placed in the place of the smallest element, 1 is placed for the second smallest element, ... N-1 is placed for the largest element.
Examples:
Input: arr[] = {10, 40, 20}
Output: arr[] = {0, 2, 1}Input: arr[] = {5, 10, 40, 30, 20}
Output: arr[] = {0, 1, 4, 3, 2}
Naive Approach:
A simple solution is to first find the minimum element, replace it with 0, consider the remaining array and find the minimum in the remaining array and replace it with 1, and so on.
Below is the implementation of the above approach:
Given Array is 10 20 15 12 11 50 Converted Array is 0 4 3 2 1 5
Time complexity: O(N2)
Auxiliary space: O(N)
Efficient Approach:
The idea is to sort the given array and use an unordered map to store the reduced form of each value of array then update the whole array to its reduced form using values from unordered map.
Follow the below steps to implement the idea:
Below are implementations of the above idea.
Given Array is 10 20 15 12 11 50 Converted Array is 0 4 3 2 1 5
Time complexity: O(N * log N)
Auxiliary Space: O(N)
Using priority_queue and hashmap:
The idea is to sort the given array using priority_queue instead of calling sort stl and use an unordered map to store the reduced form of each value of array then update the whole array to its reduced form using values from unordered map.
Algorithm:
Below is the implementation of the approach:
Given Array is 10 20 15 12 11 50 Converted Array is 0 4 3 2 1 5
Time Complexity: O(N * log N) as insertion of N elements in priority_queue takes N*logN time. Here, N is size of the input array.
Space Complexity: O(N) as priority_queue pq and temp array has been created.
Convert an array to reduced form | Set 2 (Using vector of pairs)