![]() |
VOOZH | about |
Given an array arr[] of n integers, convert it into its reduced form. In the reduced form, each element is replaced by its rank. The smallest element should be replaced with 0, the second smallest with 1, and so on, until the largest element is replaced with n - 1.
Examples:
Input: arr[] = [10, 40, 20]
Output: [0, 2, 1]
Explanation: The elements in sorted order are [10, 20, 40]. Therefore, 10, 20, and 40 are assigned ranks 0, 1, and 2 respectively.Input: arr[] = [0, 2, 1]
Output: [0, 2, 1]
Explanation: The array is already in reduced form.The elements 0, 1, and 2 are the smallest, second smallest, and largest elements respectively.Input: arr[] = [1, 5, 3, 4, 3]
Output: [0, 4, 1, 3, 2]
Explanation: The elements of the array in sorted order are [1, 3, 3, 4, 5]. Assigning ranks from 0 to n - 1 gives 1 as rank 0, the first 3 as rank 1, the second 3 as rank 2, 4 as rank 3 and 5 as rank 4.
Table of Content
The idea is to determine the rank of every element independently. For a given element, its rank is equal to the number of elements that are smaller than it. Since equal elements must receive different ranks based on their original order, we also count the equal elements that appear before the current element. The resulting count is the rank of that element.
0 2 1
The idea is to first store each element along with its original index as a pair (value, index). Then, we perform a stable sort based on the values. After sorting, the position of each pair in the sorted array represents its rank. Finally, using the stored indices, we place these ranks back into their original positions in the array. Stable sorting ensures that equal elements retain their relative order, so an earlier occurrence receives a smaller rank than a later occurrence.
For the array arr[] = [1, 5, 3, 4, 3]
Step 1: Convert each element into a pair (value, index): [(1, 0), (5, 1), (3, 2), (4, 3), (3, 4)]
Step 2: Perform a stable sort based on the values: [(1, 0), (3, 2), (3, 4), (4, 3), (5, 1)]
Step 3: Assign ranks according to the position in the sorted array:
Step 3: Assign ranks, We start rank from 1:
Step 4: Place the ranks back using the original indices:
Step 5: The final reduced form of the array is: [0, 4, 1, 3, 2]
0 2 1