Replace each element of Array with it’s corresponding rank

Given an array arr[] of N integers, the task is to replace each element of Array with their rank in array
 

The rank of an element is defined as the distance between the element with the first element of the array when the array is arranged in ascending order. If two or more are same in the array then their rank is also the same as the rank of the first occurrence of the element. 
For Example: Let the given array arr[] = {2, 2, 1, 6}, then rank of elements is given by: 
sorted array is: 
arr[] = {1, 2, 2, 6} 
Rank(1) = 1 (at index 0) 
Rank(2) = 2 (at index 1) 
Rank(2) = 2 (at index 2) 
Rank(6) = 4 (at index 3) 
 

Examples: 
 

Input: arr[] = [100, 5, 70, 2] 
Output: [4, 2, 3, 1] 
Explanation: 
Rank of 2 is 1, 5 is 2, 70 is 3 and 100 is 4.
Input: arr[] = [100, 2, 70, 2] 
Output: [3, 1, 2, 1] 
Explanation: 
Rank of 2 is 1, 70 is 2 and 100 is 3. 
 

 



Naive Approach: The naive approach is to find the rank of each element is 1 + the count of smaller elements in the array for the current element.
Time Complexity: O(N2
Auxiliary Space: O(1)
Efficient Approach: To optimize the above naive approach find ranks of elements and then assign the rank to the elements. Below are the steps:
 

  1. To compute the rank of the element first make a copy of given arr[] then sort that copied array in ascending order.
  2. Then traverse in the copied array and put their rank in HashMap by taking a rank variable.
  3. If the element is already present in HashMap then don’t update rank otherwise update rank of the element in HashMap and increment rank variable as well.
  4. Traverse the given array arr[] assign the rank of each element using the rank stored in HashMap.

Below is the implementation of the above approach:
 

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
  
class GFG {
  
    // Function to assign rank to
    // array eleements
    static void changeArr(int[] input)
    {
        // Copy input array into newArray
        int newArray[]
            = Arrays
                  .copyOfRange(input,
                               0,
                               input.length);
  
        // Sort newArray[] in ascending order
        Arrays.sort(newArray);
        int i;
        
        // Map to store the rank of
        // the array element
        Map<Integer, Integer> ranks
            = new HashMap<>();
  
        int rank = 1;
  
        for (int index = 0;
             index < newArray.length;
             index++) {
  
            int element = newArray[index];
  
            // Update rank of element
            if (ranks.get(element) == null) {
  
                ranks.put(element, rank);
                rank++;
            }
        }
  
        // Assign ranks to elements
        for (int index = 0;
             index < input.length;
             index++) {
  
            int element = input[index];
            input[index]
                = ranks.get(input[index]);
         
        }
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int[] arr = { 100, 2, 70, 2 };
  
        // Function Call
        changeArr(arr);
  
        // Print the array elements
        System
            .out
            .println(Arrays
                         .toString(arr));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach 
  
# Function to assign rank to
# array eleements
def changeArr(input1):
  
    # Copy input array into newArray
    newArray = input1.copy()
      
    # Sort newArray[] in ascending order
    newArray.sort()
      
    # Dictionary to store the rank of
    # the array element
    ranks = {}
      
    rank = 1
      
    for index in range(len(newArray)):
        element = newArray[index];
      
        # Update rank of element
        if element not in ranks:
            ranks[element] = rank
            rank += 1
          
    # Assign ranks to elements
    for index in range(len(input1)):
        element = input1[index]
        input1[index] = ranks[input1[index]]
  
# Driver Code
if __name__ == "__main__":
      
    # Given array arr[]
    arr = [ 100, 2, 70, 2 ]
      
    # Function call
    changeArr(arr)
      
    # Print the array elements
    print(arr)
  
# This code is contributed by chitranayal

chevron_right


[3, 1, 2, 1]

Time Complexity: O(N * log N) 
Auxiliary Space: O(N)
 

competitive-programming-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : chitranayal