Climbing the Leaderboard : HackerRank Solution in Python
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 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
Solution in Python 3
Firstly, we will convert the ranked into a set as there might be multiple scores in the leaderboard of the same value and thus of the same rank.
ranked = set(ranked)
Then, we will convert the ranked set back to a list and sort it in a descending order(we convert the set to list because we cannot slice a set). Thus the equation will be.
ranked = sorted(list(set(ranked)), reverse=True)
then we will also sort the player in a reverse manner.
player = sorted(player, reverse=True)
After performing above operations we will store the length of ranked in a variable l, assign 0 to a new variable j, and declare an empty list ans to store our answer. Thus the code will be:-
Then we will traverse the length of player through variable i using a for loop:-
for i in range(len(player)):
Then we will increment j by 1 using a while loop, which will execute until both of the following conditions are True:
- variable j is less than l i.e length of ranked.
- player[i]<ranked[j]
when one or both of the above condition become False we will append j+1 to the ans list i.e the rank of the corresponding score in player. Thus the for loop will be :-
While traversing the for loop, i.e for a player[i], if j>l then the ranked list is completely traversed so we cannot add another rank and if player[i] ≥ ranked[j] then rank of the player is obtained and thus we exit the while loop.
At the end we return ans in a reverse manner as we had reversed both ranked and player earlier.
The full solution is:-