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;
}
Top comments (1)
Nice and efficient solution. Using a single pointer from the bottom of the deduplicated leaderboard avoids scanning the entire ranking list for every player score, which keeps the approach close to O(n + m).
One small clarification: the comment says the ranked list is sorted, but
new Set(ranked)only removes duplicates and preserves the existing order. The solution therefore relies onrankedalready being sorted in descending order, as guaranteed by the HackerRank input.It may also be helpful to mention that the pointer is not reset because the player scores are provided in non-decreasing order. Explaining these two assumptions would make the solution easier for beginners to understand and reuse correctly.