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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem