Replace each element of Array with it's corresponding rank
Last Updated : 14 Feb, 2025
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(" "));
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:
- Copy the input array into a new array and sort it in ascending order
- 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
- 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
- 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(" "));
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(" "));
Time Complexity: O(n * log n)
Auxiliary Space: O(n)
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