Climbing the Leaderboard - HackerRank Solution (Javascript) ๐Ÿš€

Climbing the Leaderboard - HackerRank Solution (Javascript) ๐Ÿš€

ยท

2 min read

An arcade game player wants to climb to the top of the leaderboard and track their ranking. The game uses Dense Ranking, so its leaderboard works like this:

  • The player with the highest score is ranked number 1 on the leaderboard.

  • Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number.

Function Description

Complete the climbingLeaderboard function in the editor below.

climbingLeaderboard has the following parameter(s):

  • int ranked[n]: the leaderboard scores

  • int player[m]: the player's scores

Returns

int[m]: the player's rank after each new score Input Format

The first line contains an integer n, the number of players on the leaderboard. The next line contains n space-separated integers ranked[i], the leaderboard scores in decreasing order. The next line contains an integer, m, the number games the player plays. The last line contains m space-separated integers [j], the game scores.

function climbingLeaderboard(ranked, player) {
    // Write your code here
    // Remove duplicates from the ranked list and sort in descending order
    let uniqueRanks = [...new Set(ranked)];

    let playerRankings = [];
    let index = uniqueRanks.length - 1;

    player.forEach(score => {
        while (index >= 0 && score >= uniqueRanks[index]) {
            index--;
        }
        playerRankings.push(index + 2); // Rank is index + 2 because index starts from 0 and we want the 1-based rank
    });

    return playerRankings;
}