{ Climbing the Leaderboard }

Solving the Programming Challenge

Climbing the Leaderboard

Problem

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.

Example

ranked = [100, 90, 90, 80]
player = [70, 80, 105]

The ranked players will have ranks 1, 2, 2, and 3, respectively. If the player’s scores are 70, 80 and 105, their rankings after each game are 4th, 3rd and 1st. Return [4, 3, 1].

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

Read more on the challenge page…

My Solution

I’m providing the solution for Python and JS, please leave on the comments if you found a better way.

def climbingLeaderboard(ranked, player):
    # get the unique ranks sorted descending
    scores = sorted(list(set(ranked)), reverse=True)
    player_ranks = []
    for score in player:
        while scores and score >= scores[-1]:
            scores.pop()
        player_ranks.append(len(scores) + 1)

    return player_ranks
function climbingLeaderboard(scores, alice) {
    // get the unique ranks sorted descending
    scores = scores.reduce((ranking, score) => {
        if (score !== ranking[ranking.length - 1]) {
            ranking.push(score);
        }
        return ranking;
    }, [scores[0]]);

    const player_ranks = [];
    for (const score of alice) {
        while (scores && score >= scores[scores.length - 1])
            scores.pop()
        player_ranks.push(scores.length + 1)
    }

    return player_ranks
}

Join the Free Newsletter

A free, weekly e-mail with the best new articles, courses, and special bonuses.

We won't send you spam. Unsubscribe at any time.