Learn-dsa..in 30 days!



























CC-16 : Replace array values by rank.

Description:

Given an array of integers, find the rank of each integer. The largest integer will have rank 1, the second largest will have rank 2 and so on. Put each integers ranks it’s the same index in a new array and return the same.

Test cases and expected outputs:

Input Parameters Expected outputs
Nums :
33,22,55,11,99
Ranks :
3,4,2,5,1

Pseudocode:

Class NumIndex:

Create an internal class NumIndex.
The instances of NumIndex will hold reference to the integer and its index in the input array.

Class SortByNum:

This class implements Comparator.compare() method. The method takes 2 instances of NumIndex and helps to sort the same by magnitude of the integer.

Method replaceArrElementByRank ():

This method takes input integer array as parameter.
Initialize a PriorityQueue instance named heap. Provide an instance of NumIndex to the constructor the PriorityQueue to sort by magnitude of the integer.
Iterate though nums from index 0 to index chars.length-1:
Create a NumIndex Instance and set the values of variables I and index.
Add the NumIndex instance created above to heap. The comparator provided to heap, automatically adds NumIndex to heap as per required heap’s integer magnitude sorting order.
Initialize an integer array named ranks with same size as size of input array.
Initialize integer variable currRank to 1.
While currRank <= ranks.length:
Remove a NumIndex instance from top of heap and extract index value from it and set in a variable named currLargestIndex.
Set ranks[currLargestIndex] to currRank.
Increment currRank by 1.
Return ranks integer array.

Code:

public class HeapReplaceArrElementByRank {
	
class NumIndex{
	int i;
	int index;	
}

class SortByNum implements Comparator<NumIndex> {
	public int compare(NumIndex c1, NumIndex c2) {
		if (c1.i < c2.i) {return 1;}
		if (c1.i > c2.i) {return -1;}
		return 0;
	}	
}
 
public int[] replaceArrElementByRank(int[] nums) {
	PriorityQueue<NumIndex> heap=new PriorityQueue<NumIndex>(new SortByNum());
	for (int idx=0; idx < nums.length; idx++) {
		NumIndex numIndex=new NumIndex();
		numIndex.i=nums[idx];
		numIndex.index=idx;
		heap.add(numIndex);
	}	
	int[] ranks=new int[nums.length];
	int currRank=1;
	while(currRank <=ranks.length) {
		int currLargestIndex=heap.remove().index;
		ranks[currLargestIndex]=currRank;
		currRank++;
	}
	return ranks;
}
}

Click here to download and run code and test cases !