We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Algorithms
  3. Implementation
  4. Climbing the Leaderboard
  5. Discussions

Climbing the Leaderboard

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • Kanahaiya
    3 years ago+ 14 comments

    Hello friends,

    climbing the leaderboard can be optimized by applying binary search

    If interested to know more about the generic algorithm in details-

    click here for the video explanation of generic algorithm with complexity analysis.

    or you can click on the image too to follow youtube tutorial.

    Here is the working solution:-

    source code :

    static int[] climbingLeaderboard(int[] scores, int[] alice) {
    	int n = scores.length;
    	int m = alice.length;
    
    	int res[] = new int[m];
    	int[] rank = new int[n];
    
    	rank[0] = 1;
    
    	for (int i = 1; i < n; i++) {
    		if (scores[i] == scores[i - 1]) {
    			rank[i] = rank[i - 1];
    		} else {
    			rank[i] = rank[i - 1] + 1;
    		}
    	}
    
    	for (int i = 0; i < m; i++) {
    		int aliceScore = alice[i];
    		if (aliceScore > scores[0]) {
    			res[i] = 1;
    		} else if (aliceScore < scores[n - 1]) {
    			res[i] = rank[n - 1] + 1;
    		} else {
    			int index = binarySearch(scores, aliceScore);
    			res[i] = rank[index];
    
    		}
    	}
    	return res;
    
    }
    
    private static int binarySearch(int[] a, int key) {
    
    	int lo = 0;
    	int hi = a.length - 1;
    
    	while (lo <= hi) {
    		int mid = lo + (hi - lo) / 2;
    		if (a[mid] == key) {
    			return mid;
    		} else if (a[mid] < key && key < a[mid - 1]) {
    			return mid;
    		} else if (a[mid] > key && key >= a[mid + 1]) {
    			return mid + 1;
    		} else if (a[mid] < key) {
    			hi = mid - 1;
    		} else if (a[mid] > key) {
    			lo = mid + 1;
    		}
    	}
    	return -1;
    }
    

    Would really appreciate your feedback like, dislike , comment etc. on my video.

    Do not forget to upvote, if you find it useful.

    132|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature