HackerRank Climbing the Leaderboard Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Climbing the Leaderboard Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

Climbing the Leaderboard   problem solution
Climbing the Leaderboard Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank Climbing the Leaderboard

Task

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

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 player[j], the game scores.

Constraints

  • 1 <= n <= 2 x 105
  • 1 <= m <= 2 x 105
  • 0 <= ranked[i] <= 109 for 0 <= i < n 
  • 0 <= player[j] <= 109 for 0 <= j < m
  • The existing leaderboard, ranked, is in descending order.
  • The player’s scores, player, are in ascending order.

Subtask

For 60% of the maximum score:

  • 1 <= n <= 200
  • 1 <= m <= 200

Sample Input 1

7
100 100 50 40 40 20 10
4
5 25 50 120

Sample Output 1

6421

Explanation 1

Alice starts playing with 7 players already on the leaderboard, which looks like this:

image

After Alice finishes game 0, her score is 5 and her ranking is 6:

image

After Alice finishes game 1, her score is 25 and her ranking is 4:

image

After Alice finishes game 2, her score is 50 and her ranking is 2:

image

After Alice finishes game 3, her score is 120 and her ranking is 1:

image

Sample Input 2

6
100 90 90 80 75 60
5
50 65 77 90 102

Sample Output 2

65421

HackerRank Climbing the Leaderboard Solution

Climbing the Leaderboard Solution in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int n; 
    scanf("%d",&n);
    int *scores = malloc(sizeof(int) * n);
    for(int scores_i = 0; scores_i < n; scores_i++){
       scanf("%d",&scores[scores_i]);
        if(scores_i){
            if(scores[scores_i]==scores[scores_i-1]){
                scores_i--;
                n--;
            }
        }
    }
    //printf("%d\n",n);//
    int m; 
    scanf("%d",&m);
    int *alice = malloc(sizeof(int) * m);
    for(int alice_i = 0; alice_i < m; alice_i++){
       scanf("%d",&alice[alice_i]);
    }
    int rank=n;
    for(int j=0; j<m; j++){
        while(alice[j]>=scores[rank-1] && rank>0){
            rank--;
            if(rank==0) break;
        }
        printf("%d\n",rank+1);
    }
    
    
    // your code goes here
    return 0;
}

Climbing the Leaderboard Solution in Cpp

#include<bits/stdc++.h>

using namespace std;

#define FOR(i,n)	for(int i=0;i<(int)n;i++)
#define FOB(i,n)	for(int i=n;i>=1;i--)
#define MP(x,y)	make_pair((x),(y))
#define ii pair<int, int>
#define lli long long int
#define ulli unsigned long long int
#define lili pair<lli, lli>
#ifdef EBUG
#define DBG	if(1)
#else
#define DBG	if(0)
#endif
#define SIZE(x) int(x.size())
const int infinity = 2000000999 / 2;
const long long int inff = 4000000000000000999;

typedef complex<long double> point;

template<class T>
T get() {
    T a;
    cin >> a;
    return a;
}

template <class T, class U>
ostream& operator<<(ostream& out, const pair<T, U> &par) {
    out << "[" << par.first << ";" << par.second << "]";
    return out;
}

template <class T>
ostream& operator<<(ostream& out, const set<T> &cont){
    out << "{";
    for (const auto &x:cont) out << x << ", ";
    out << "}";
    return out;
}

template <class T, class U>
ostream& operator<<(ostream& out, const map<T,U> &cont){
    out << "{";
    for (const auto &x:cont) out << x << ", ";
    out << "}"; return out;
}

template <class T>
ostream& operator<<(ostream& out, const vector<T>& v) {
  FOR(i, v.size()){
    if(i) out << " ";
    out << v[i];
  }
  out << endl;
  return out;
}

bool ccw(point p, point a, point b){
  if((conj(a - p) * (b - p)).imag() <= 0) return(0);
  else return(1);
}

int main(){
    cin.sync_with_stdio(false);
    cout.sync_with_stdio(false);
    int n = get<int>();
    vector<int> score;
    FOR(i, n) score.push_back(get<int>());
    int m = get<int>();
    vector<int> pos;
    FOR(i, n){
        pos.push_back((i ? (score[i] == score[i - 1] ? pos.back() : pos.back() + 1) : 1));
    }
    int id = n - 1;
    FOR(i, m){
        int sc = get<int>();
        while(id >= 0 && score[id] < sc){
            id --;
        }
        if(id == -1) cout << 1 << endl;
        else if(score[id] == sc) cout << pos[id] << endl;
        else cout << pos[id] + 1 << endl;
    }
}

Climbing the Leaderboard Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        List<Integer> scores = new ArrayList<Integer>();
        for (int i = 0; i < n; i++){
            int score = in.nextInt();
            if (scores.size() == 0 || scores.get(scores.size() - 1) != score)
                scores.add(score);
        }
        int m = in.nextInt();
        for (int i = 0; i < m; i++){
            int score = in.nextInt();
            int min = 0;
            int max = scores.size();
            while (max > min){
                int mid = (min + max) / 2;
                if (scores.get(mid) <= score)
                    max = mid;
                else
                    min = mid + 1;
            }
            System.out.println(min + 1);
        }
    }
}

Climbing the Leaderboard Solution in Python

#!/bin/python

import sys

def compute_sums(A, B):
    i = 0
    y = A[i]
    s = 0

    result = {}
    for x in B:
        while x > y:
            result[y] = s
            i += 1
            if i >= len(A):
                return result
            
            y = A[i]
        s += 1
    for y in A[i:]:
        result[y] = s
    return result



n = int(raw_input().strip())
A = map(int,raw_input().strip().split(' '))
m = int(raw_input().strip())
B = map(int,raw_input().strip().split(' '))
A = list(set(A))
A.sort()

l = compute_sums(B,A)
for i in B:
    print len(A)-l[i]+1

Climbing the Leaderboard Solution using JavaScript

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function main() {
    var n = parseInt(readLine());
    scores = readLine().split(' ');
    scores = scores.map(Number);
    var m = parseInt(readLine());
    alice = readLine().split(' ');
    alice = alice.map(Number);
    
    var temp = scores[0];
    var vals = [temp];
    for(var i=1; i<n; i++){
        if(scores[i]!=temp){
            temp = scores[i];
            vals.push(temp);
        }
    }
    
    var j = vals.length-1;
    for(var i=0; i<m; i++){
        while(vals[j]<=alice[i]){
            j--;
        }
        console.log(j+2);
    }

}

Climbing the Leaderboard Solution in Scala

object Solution {

  def main(args: Array[String]) {
    val sc = new java.util.Scanner (System.in)
    var n = sc.nextInt()
    var scores = new Array[Int](n)
    for(scores_i <- 0 to n-1) {
      scores(scores_i) = sc.nextInt()
    }
    var m = sc.nextInt();
    var alice = new Array[Int](m);
    for(alice_i <- 0 to m-1) {
      alice(alice_i) = sc.nextInt();
    }
    val distinctLeaderScoresWithRank = scores.distinct.zipWithIndex.reverse.toList
    alice.foldLeft(distinctLeaderScoresWithRank) {
      (leadersToDethrone, score) => val remainingLeaders = leadersToDethrone.dropWhile(x => x._1 < score)
                if(remainingLeaders.nonEmpty) {
                  if (remainingLeaders.head._1 > score) println(remainingLeaders.head._2 + 2)
                  else println(remainingLeaders.head._2 + 1)
                }
                else {
                  println(1)
                }
                remainingLeaders
    }
  }
}

Climbing the Leaderboard Solution in Pascal

var n,r,x,i,m:longint;
    a,b:array[0..1000000] of longint;
begin
    readln(n);
    for i:=1 to n do read(a[i]);
    for i:=1 to n do 
    begin
        b[i]:=b[i-1];
        if (a[i]<a[i-1]) or (i=1) then inc(b[i]);
    end;
    b[n+1]:=b[n]+1;
    readln(m);
    r:=n+1;
    for i:=1 to m do 
    begin
        read(x);
        while (r>1) and (x>=a[r-1]) do dec(r);
        writeln(b[r]);
    end;
end.

Disclaimer: This problem (Climbing the Leaderboard) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.

FAQ:

1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedi


Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment