Given an array of distinct integers, replace each array element by its corresponding rank in the array.

The minimum array element has the rank 1; the second minimum element has a rank of 2, and so on… For example,

Input:  { 10, 8, 15, 12, 6, 20, 1 }
 
Output: { 4, 3, 6, 5, 2, 7, 1 }

Practice this problem

The idea is to store each element’s index in an ordered map (Since the array contains all distinct integers, we can use array elements and their index as key-value pairs in the map). Since elements are stored in sorted order in an ordered map, if we iterate through the map, we get elements in increasing order. Therefore, for each element in increasing order, we start assigning values starting from number 1 to n.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

4 3 6 5 2 7 1

Java


Download  Run Code

Output:

[4, 3, 6, 5, 2, 7, 1]

Python


Download  Run Code

Output:

[4, 3, 6, 5, 2, 7, 1]

The time complexity of the above solution is O(n.log(n)), where n is the size of the input. This assumes O(log(n)) time operation for std::map or TreeMap. The auxiliary space required by the program is O(n).

 
We can also use a heap to solve this problem. The idea remains similar to the previous approach, but we store array elements and their index as key-value pairs in a max-heap. The primary benefit of using max-heap is that we get elements in decreasing order if we remove pairs from it. Therefore, for each element in decreasing order, we start assigning values starting from number n till 1. Note that min-heap can also be used.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

4 3 6 5 2 7 1

Java


Download  Run Code

Output:

[4, 3, 6, 5, 2, 7, 1]

Python


Download  Run Code

Output:

[4, 3, 6, 5, 2, 7, 1]

The time complexity of the above solution remains the same as the previous approach, i.e., O(n.log(n)). The auxiliary space required by the program also remains O(n).

 
Exercise: Convert the above solution to use min-heap.