# Replace Each Element Of Array With Its Corresponding Rank

Posted: 10 Dec, 2020

Difficulty: Easy

#### Given an array of integers 'ARR’ of size ‘N’. Replace each element of this array with its corresponding rank.

#### The rank of an element is an integer between 1 to ‘N’ inclusive that represents how large the element is in comparison to other elements of the array. The rank of an element can also be defined by the following rules.

```
1. It is an integer starting from 1.
2. The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
3. It should be as small as possible.
```

##### Input Format :

```
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘2*T’ lines represent the ‘T’ test cases.
The first line of each test case contains an integer ‘N’ representing the number of elements in ‘ARR’.
The second line of each test contains ‘N’ space-separated integers representing the elements present in ‘ARR’.
```

##### Output Format :

```
For each test case, print space separated elements of ‘ARR’ where the value at index ‘i’ is replaced by the rank of the element at index ‘i’ in ‘ARR’.
```

##### Note :

```
You do not need to print anything it has already been taken care of. Just return the integer array ‘ARR’ after replacing every element with its rank.
```

##### Constraints :

```
1 <= T <= 50
1 <= N <= 10^4
-10^9 <= ARR[i] <= 10^9
Where 'ARR[i]' denotes the 'ith' element of the array.
Time limit: 1 sec
```

Approach 1

- First, make an array ‘temp’ of size ‘N’ and copy all the elements of ’ARR’ in it.
- Run a loop where ‘i ranges from 0 to N-1 -:

1. Declare a HashMap and initialise a variable ‘rank’= 1

2. Iterate over array ‘temp’ and increment ‘rank’ by one whenever we find an element in ‘temp’ which is strictly less than ‘ARR[i]’ and not present in HashMap. After that insert the element in HashMap.

3. Replace the value in ‘ARR[i]’ with ‘rank’. - Return the array ‘ARR’.

Approach 2

- First, make an array ‘temp’ of size ‘N’ and copy all the elements of ’ARR’ in it.
- Sort the array ‘temp’ in non-decreasing order.
- Create a HashMap that will map each element with its rank.
- Initialize a variable ‘rank’ := 1.
- Run a loop where ‘i’ ranges from 0 to N-1. For each ‘i’ If ‘temp[i]’ is not present in HashMap then insert the key ‘temp[i]’ in HashMap and map its value with ‘rank’ and after that increment the variable ‘rank’ by 1.
- Iterate over the array ‘ARR’ and replace each element with its corresponding value in HashMap.
- Return the array ‘ARR’.

SIMILAR PROBLEMS

# Game of 3

Posted: 11 Jul, 2021

Difficulty: Easy

# Lexicographic Permutation Rank

Posted: 13 Jul, 2021

Difficulty: Moderate

# Zero Pair Sum

Posted: 22 Jul, 2021

Difficulty: Moderate

# Implement a Queue

Posted: 27 Jul, 2021

Difficulty: Easy

# Remove K Corner Elements

Posted: 31 Jul, 2021

Difficulty: Easy