Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Replace each element of Array with it's corresponding rank
Next article icon

Replace each element of Array with it's corresponding rank

Last Updated : 14 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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] Using Brute Force Method - O(n^2) time and O(n) space

The idea is to iterate through each element in the array and find the rank of element. The rank of each element is 1 + the count of smaller elements in the array for the current element.

C++
// C++ program to replace each element of // Array with it's corresponding rank #include <iostream> #include <vector> #include <unordered_set> using namespace std;  vector<int> replaceWithRank(vector<int> &arr){     int n = arr.size();          vector<int> res(n);          // For each value      for (int i=0; i<n; i++) {                  // Set to store unique elements only         unordered_set<int> set;                  for (int j=0; j<n; j++) {                          // If value is smaller and not              // included in set yet.             if (arr[j]<arr[i] && set.find(arr[j])==set.end()) {                 set.insert(arr[j]);             }         }                  // Rank will be count of smaller elements + 1.         res[i] = set.size() + 1;     }          return res; }  int main() {     vector<int> arr = {100, 5, 70, 2};     vector<int> res = replaceWithRank(arr);          for (int val: res) {         cout << val << " ";     }     cout << endl;      return 0; } 
Java
// Java program to replace each element of // Array with it's corresponding rank import java.util.*;  class GfG {     static int[] replaceWithRank(int[] arr) {         int n = arr.length;                  int[] res = new int[n];                  // For each value          for (int i = 0; i < n; i++) {                          // Set to store unique elements only             Set<Integer> set = new HashSet<>();                          for (int j = 0; j < n; j++) {                                  // If value is smaller and not                  // included in set yet.                 if (arr[j] < arr[i] && !set.contains(arr[j])) {                     set.add(arr[j]);                 }             }                          // Rank will be count of smaller elements + 1.             res[i] = set.size() + 1;         }                  return res;     }      public static void main(String[] args) {         int[] arr = {100, 5, 70, 2};         int[] res = replaceWithRank(arr);                  for (int val : res) {             System.out.print(val + " ");         }         System.out.println();     } } 
Python
# Python program to replace each element of # Array with it's corresponding rank  def replaceWithRank(arr):     n = len(arr)          res = [0] * n          # For each value      for i in range(n):                  # Set to store unique elements only         unique_set = set()                  for j in range(n):                          # If value is smaller and not              # included in set yet.             if arr[j] < arr[i] and arr[j] not in unique_set:                 unique_set.add(arr[j])                  # Rank will be count of smaller elements + 1.         res[i] = len(unique_set) + 1          return res  if __name__ == "__main__":     arr = [100, 5, 70, 2]     res = replaceWithRank(arr)          print(" ".join(map(str, res))) 
C#
// C# program to replace each element of // Array with it's corresponding rank using System; using System.Collections.Generic;  class GfG {     static List<int> replaceWithRank(List<int> arr) {         int n = arr.Count;                  List<int> res = new List<int>(new int[n]);                  // For each value          for (int i = 0; i < n; i++) {                          // Set to store unique elements only             HashSet<int> set = new HashSet<int>();                          for (int j = 0; j < n; j++) {                                  // If value is smaller and not                  // included in set yet.                 if (arr[j] < arr[i] && !set.Contains(arr[j])) {                     set.Add(arr[j]);                 }             }                          // Rank will be count of smaller elements + 1.             res[i] = set.Count + 1;         }                  return res;     }      static void Main() {         List<int> arr = new List<int> {100, 5, 70, 2};         List<int> res = replaceWithRank(arr);                  Console.WriteLine(string.Join(" ", res));     } } 
JavaScript
// JavaScript program to replace each element of // Array with it's corresponding rank  function replaceWithRank(arr) {     let n = arr.length;          let res = new Array(n);          // For each value      for (let i = 0; i < n; i++) {                  // Set to store unique elements only         let set = new Set();                  for (let j = 0; j < n; j++) {                          // If value is smaller and not              // included in set yet.             if (arr[j] < arr[i] && !set.has(arr[j])) {                 set.add(arr[j]);             }         }                  // Rank will be count of smaller elements + 1.         res[i] = set.size + 1;     }          return res; }  let arr = [100, 5, 70, 2]; let res = replaceWithRank(arr);  console.log(res.join(" ")); 

Output
4 2 3 1  

Time Complexity: O(n^2) 
Auxiliary Space: O(n) to store elements in the set.

[Efficient Approach - 1] Using Sorting - O(n * log n) time and O(n) space

The idea is to first create a sorted copy of the original array to determine the correct ranks of elements, then use a hash map to store the rank of each unique element, and finally traverse the original array to replace each element with its corresponding rank from the hash map.

Step by step approach:

  1. Copy the input array into a new array and sort it in ascending order
  2. Create a hash map and traverse the sorted array - for each unique element, assign it a rank (skip duplicates to keep same rank) and increment rank counter
  3. Create a result array and traverse the original array - for each element, look up its rank in the hash map and store it at the same index in result array
  4. Return the result array containing ranks
C++
// C++ program to replace each element of // Array with it's corresponding rank #include <bits/stdc++.h> using namespace std;  vector<int> replaceWithRank(vector<int> &arr){     int n = arr.size();          // Array to store input array      // in sorted manner.     vector<int> sorted(arr.begin(), arr.end());     sort(sorted.begin(), sorted.end());          // Hashmap to store rank of each element     unordered_map<int, int> ranks;     int rank = 1;          for (int i=0; i<n; i++) {                  // If rank of current value is         // assigned, so skip it.         if (i>0 && sorted[i]==sorted[i-1]) {             continue;         }                  // Assign rank of current value.         ranks[sorted[i]] = rank++;     }          vector<int> res(n);          // Traverse the original array and      // store their corresponding ranks.     for (int i=0; i<n; i++) {         res[i] = ranks[arr[i]];     }          return res; }  int main() {     vector<int> arr = {100, 5, 70, 2};     vector<int> res = replaceWithRank(arr);          for (int val: res) {         cout << val << " ";     }     cout << endl;      return 0; } 
Java
// Java program to replace each element of // Array with it's corresponding rank import java.util.*;  class GfG {     static int[] replaceWithRank(int[] arr) {         int n = arr.length;                  // Array to store input array          // in sorted manner.         int[] sorted = arr.clone();         Arrays.sort(sorted);                  // Hashmap to store rank of each element         Map<Integer, Integer> ranks = new HashMap<>();         int rank = 1;                  for (int i = 0; i < n; i++) {                          // If rank of current value is             // assigned, so skip it.             if (i > 0 && sorted[i] == sorted[i - 1]) {                 continue;             }                          // Assign rank of current value.             ranks.put(sorted[i], rank++);         }                  int[] res = new int[n];                  // Traverse the original array and          // store their corresponding ranks.         for (int i = 0; i < n; i++) {             res[i] = ranks.get(arr[i]);         }                  return res;     }      public static void main(String[] args) {         int[] arr = {100, 5, 70, 2};         int[] res = replaceWithRank(arr);                  for (int val : res) {             System.out.print(val + " ");         }         System.out.println();     } } 
Python
# Python program to replace each element of # Array with it's corresponding rank  def replaceWithRank(arr):     n = len(arr)          # Array to store input array      # in sorted manner.     sortedArr = sorted(arr)          # Hashmap to store rank of each element     ranks = {}     rank = 1          for i in range(n):                  # If rank of current value is         # assigned, so skip it.         if i > 0 and sortedArr[i] == sortedArr[i - 1]:             continue                  # Assign rank of current value.         ranks[sortedArr[i]] = rank         rank += 1          res = [0] * n          # Traverse the original array and      # store their corresponding ranks.     for i in range(n):         res[i] = ranks[arr[i]]          return res  if __name__ == "__main__":     arr = [100, 5, 70, 2]     res = replaceWithRank(arr)          print(" ".join(map(str, res))) 
C#
// C# program to replace each element of // Array with it's corresponding rank using System; using System.Collections.Generic;  class GfG {     static List<int> replaceWithRank(List<int> arr) {         int n = arr.Count;                  // Array to store input array          // in sorted manner.         List<int> sorted = new List<int>(arr);         sorted.Sort();                  // Hashmap to store rank of each element         Dictionary<int, int> ranks = new Dictionary<int, int>();         int rank = 1;                  for (int i = 0; i < n; i++) {                          // If rank of current value is             // assigned, so skip it.             if (i > 0 && sorted[i] == sorted[i - 1]) {                 continue;             }                          // Assign rank of current value.             ranks[sorted[i]] = rank++;         }                  List<int> res = new List<int>(new int[n]);                  // Traverse the original array and          // store their corresponding ranks.         for (int i = 0; i < n; i++) {             res[i] = ranks[arr[i]];         }                  return res;     }      static void Main() {         List<int> arr = new List<int> {100, 5, 70, 2};         List<int> res = replaceWithRank(arr);                  Console.WriteLine(string.Join(" ", res));     } } 
JavaScript
// JavaScript program to replace each element of // Array with it's corresponding rank  function replaceWithRank(arr) {     let n = arr.length;          // Array to store input array      // in sorted manner.     let sorted = [...arr].sort((a, b) => a - b);          // Hashmap to store rank of each element     let ranks = new Map();     let rank = 1;          for (let i = 0; i < n; i++) {                  // If rank of current value is         // assigned, so skip it.         if (i > 0 && sorted[i] === sorted[i - 1]) {             continue;         }                  // Assign rank of current value.         ranks.set(sorted[i], rank++);     }          let res = new Array(n);          // Traverse the original array and      // store their corresponding ranks.     for (let i = 0; i < n; i++) {         res[i] = ranks.get(arr[i]);     }          return res; }  let arr = [100, 5, 70, 2]; const res = replaceWithRank(arr); console.log(res.join(" ")); 

Output
4 2 3 1  

Time Complexity: O(n * log n) to sort the input array.
Auxiliary Space: O(n) to store ranks in the hash map.

[Efficient Approach - 2] Using Min Heap - O(n * log n) time and O(n) space

 The idea is to use a min heap (priority queue) to process elements in sorted order, maintaining their original indices, and then assign ranks by processing elements from smallest to largest while handling duplicates.

C++
// C++ program to replace each element of // Array with it's corresponding rank #include <bits/stdc++.h> using namespace std;  vector<int> replaceWithRank(vector<int> &arr){     int n = arr.size();     vector<int> res(n);          // Create min heap of pairs (element, index)     priority_queue<pair<int,int>, vector<pair<int,int>>,      greater<pair<int,int>>> pq();          // Push elements with their indices     for(int i = 0; i < n; i++) {         pq.push({arr[i], i});     }          int rank = 0;     int lastNum = INT_MAX;          // Process elements in sorted order     while(!pq.empty()) {         int curr = pq.top().first;         int index = pq.top().second;         pq.pop();                  // Increment rank only for new numbers         if(lastNum == INT_MAX || curr != lastNum) {             rank++;         }                  // Assign rank to original position         res[index] = rank;         lastNum = curr;     }          return res; }  int main() {     vector<int> arr = {100, 5, 70, 2};     vector<int> res = replaceWithRank(arr);          for (int val: res) {         cout << val << " ";     }     cout << endl;      return 0; } 
Java
// Java program to replace each element of // Array with it's corresponding rank import java.util.*;  class GfG {     static int[] replaceWithRank(int[] arr) {         int n = arr.length;         int[] res = new int[n];          // Create min heap of pairs (element, index)         PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));          // Push elements with their indices         for (int i = 0; i < n; i++) {             pq.add(new int[]{arr[i], i});         }          int rank = 0;         int lastNum = Integer.MAX_VALUE;          // Process elements in sorted order         while (!pq.isEmpty()) {             int[] top = pq.poll();             int curr = top[0];             int index = top[1];              // Increment rank only for new numbers             if (lastNum == Integer.MAX_VALUE || curr != lastNum) {                 rank++;             }              // Assign rank to original position             res[index] = rank;             lastNum = curr;         }          return res;     }      public static void main(String[] args) {         int[] arr = {100, 5, 70, 2};         int[] res = replaceWithRank(arr);          for (int val : res) {             System.out.print(val + " ");         }         System.out.println();     } } 
Python
# Python program to replace each element of # Array with it's corresponding rank import heapq  def replaceWithRank(arr):     n = len(arr)     res = [0] * n      # Create min heap of pairs (element, index)     pq = []      # Push elements with their indices     for i in range(n):         heapq.heappush(pq, (arr[i], i))      rank = 0     lastNum = float('inf')      # Process elements in sorted order     while pq:         curr, index = heapq.heappop(pq)          # Increment rank only for new numbers         if lastNum == float('inf') or curr != lastNum:             rank += 1          # Assign rank to original position         res[index] = rank         lastNum = curr      return res  if __name__ == "__main__":     arr = [100, 5, 70, 2]     res = replaceWithRank(arr)      print(" ".join(map(str, res))) 
C#
// C# program to replace each element of // Array with it's corresponding rank using System; using System.Collections.Generic;  class GfG {     static List<int> replaceWithRank(List<int> arr) {         int n = arr.Count;         List<int> res = new List<int>(new int[n]);          // Create min heap of pairs (element, index)         SortedSet<(int, int)> pq = new SortedSet<(int, int)>();          // Push elements with their indices         for (int i = 0; i < n; i++) {             pq.Add((arr[i], i));         }          int rank = 0;         int lastNum = int.MaxValue;          // Process elements in sorted order         foreach (var item in pq) {             int curr = item.Item1;             int index = item.Item2;              // Increment rank only for new numbers             if (lastNum == int.MaxValue || curr != lastNum) {                 rank++;             }              // Assign rank to original position             res[index] = rank;             lastNum = curr;         }          return res;     }      static void Main() {         List<int> arr = new List<int> {100, 5, 70, 2};         List<int> res = replaceWithRank(arr);          Console.WriteLine(string.Join(" ", res));     } } 
JavaScript
// JavaScript program to replace each element of // Array with it's corresponding rank  function replaceWithRank(arr) {     let n = arr.length;     let res = new Array(n);      // Create min heap of pairs (element, index)     let pq = [];      // Push elements with their indices     for (let i = 0; i < n; i++) {         pq.push([arr[i], i]);     }      // Sort the array based on the first value (element)     pq.sort((a, b) => a[0] - b[0]);      let rank = 0;     let lastNum = Number.MAX_SAFE_INTEGER;      // Process elements in sorted order     for (let [curr, index] of pq) {         // Increment rank only for new numbers         if (lastNum === Number.MAX_SAFE_INTEGER || curr !== lastNum) {             rank++;         }          // Assign rank to original position         res[index] = rank;         lastNum = curr;     }      return res; }  let arr = [100, 5, 70, 2]; const res = replaceWithRank(arr); console.log(res.join(" ")); 

Output
4 2 3 1  

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


Next Article
Replace each element of Array with it's corresponding rank

O

offbeat
Improve
Article Tags :
  • Greedy
  • Searching
  • Sorting
  • Mathematical
  • Hash
  • Competitive Programming
  • DSA
  • Arrays
  • HashTable
  • Hash
  • Java-HashMap
Practice Tags :
  • Arrays
  • Greedy
  • Hash
  • Hash
  • Mathematical
  • Searching
  • Sorting

Similar Reads

    Rank of all elements in a Stream in descending order when they arrive
    Given a stream of numbers as arr, the task is to find the rank of each element in the stream in descending order when they arrive. Rank is defined as the total number of elements that is greater than the arriving element, where rank 1 defines the maximum value in the stream. Each value in the array
    11 min read
    Count array elements with rank not exceeding K
    Given an array arr[] consisting of N integers and an integer K, the task is to find the count of array elements having rank at most K. Equal array elements will have equal ranks. Any array element numerically smaller than its immediate greater array element will be ranked one greater than the total
    7 min read
    Replace every elements in the array by its frequency in the array
    Given an array of integers, replace every element by its frequency in the array. Examples: Input : arr[] = { 1, 2, 5, 2, 2, 5 } Output : 1 3 2 3 3 2 Input : arr[] = { 4 5 4 5 6 6 6 } Output : 2 2 2 2 3 3 3 Approach: Take a hash map, which will store the frequency of all the elements in the array.Now
    5 min read
    Deleting Elements in an Array - Array Operations
    In this post, we will look into deletion operation in an Array, i.e., how to delete an element from an Array, such as:Delete an Element from the Beginning of an ArrayDelete an Element from a Given Position in an ArrayDelete First Occurrence of Given Element from an ArrayRemove All Occurrences of an
    4 min read
    Make all Array elements equal by replacing it with adjacent elements
    Given an array A[] of size N, the task is to find the minimum number of moves required to make array elements equal where you can make adjacent elements equal in one move. Examples: Input: A = {1, 6, 5, 1, 7, 1}, N = 6Output: 3Explanation: Replace 6 with 1, 5 with 1, and then at last replace 7 with
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences