Relative Ranks | Array Problem | LeetCode 506

4 years ago Lalit Bhagtani 0

Problem Statement

You have given a scores of N athletes, write a program to find out their relative ranks.

Athletes with the top three highest scores will be awarded medals: “Gold Medal“, “Silver Medal“, “Bronze Medal“.

Example 

Relative Ranks

Input :- [5, 4, 3, 2, 1]
Output :- Gold Medal, Silver Medal, Bronze Medal, 4, 5,
Input :- [3, 1, 5, 4, 2]
Output :- Bronze Medal, 5, Gold Medal, Silver Medal, 4,

Solution

TreeMap with decreasing sorting order can be used to solve this problem. If the score is used as a key and index of the score is used as a value, we can easily find out the athletes with top to a low score and can assign them rank by using their index.

This problem can be solved in following steps :-

  1. Create an object of TreeMap (Decreasing Sorted Order) with key as a score and value as an index of the score in a given array of scores.
  2. Iterate through the array of scores and put value and index in the TreeMap.
  3. Create a string of size N to output the result.
  4. Iterate through the entry set of TreeMap and assign a rank to each score.

Program

import java.util.Map;
import java.util.TreeMap;

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		String[] result = main.findRelativeRanks(new int[] {5, 4, 3, 2, 1});
		for(String str : result) {
			System.out.print(str+", ");
		}										
	}
	
	/* Solution */    
	public String[] findRelativeRanks(int[] nums) {
        
        Map<Integer, Integer> map = new TreeMap<>((a, b) -> b - a);
        for(int i=0; i<nums.length; i++){
            map.put(nums[i], i);
        }
        
        int rank = 1;
        String[] result = new String[nums.length];
        for(Map.Entry<Integer, Integer> entry : map.entrySet()){
            
            if(rank == 1){
                result[entry.getValue()] = "Gold Medal";
            }else if(rank == 2){
                result[entry.getValue()] = "Silver Medal";
            }else if(rank == 3){
                result[entry.getValue()] = "Bronze Medal";
            }else {
                result[entry.getValue()] = rank + "";
            }
            rank++;
        }
        return result;
    }
}

Result

Bronze Medal, 5, Gold Medal, Silver Medal, 4, 

Similar Post

  1. Check if Coordinates make a Straight Line
  2. Design Min Stack Data Structure
  3. Design Max Stack Data Structure

That’s all for Relative Ranks in Java, If you liked it, please share your thoughts in a comments section and share it with others too.