Skip to main content
3 of 5
added 32 characters in body; edited tags; edited title
mdfst13
  • 21.7k
  • 6
  • 33
  • 68

Climbing the leaderboard (Hacker Rank) via binary search

I am trying to solve the Climbing the leaderboard problem on Hacker Rank. My code passes all the test cases except Test Cases 6 to 9, which I assume are using large data sets.

I'm using binary search to find the optimal insertion point for each score and using the index as the rank. I know there are loads of solutions online but I want to pass the test cases with my own code. (Apologies in advance if my formatting is incorrect.)

https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem#

 def climbingLeaderboard(ranked, player):
    
    climb = []

    ranked2 = sorted(set(ranked),reverse = True)
    
    for i in player:
        if i in ranked2:
            climb.append(ranked2.index(i)+1)
        elif i > ranked2[0]:
            climb.append(1)
            ranked2.insert(0, i)
        elif  i < ranked2[-1]:
            climb.append(len(ranked2) + 1)
            ranked2.append(i)
        else:
            a = binary_search(ranked2, i, 0,len(ranked2))
            climb.append(a+1)
            ranked2.insert(a, i)
        
    return climb


def binary_search(arr, n, lo, hi):
    
    mid = int((hi+lo)/2)
    
    if lo > hi:
        return lo
    elif arr[mid] < n:
        return binary_search(arr, n, lo, mid -1)
    elif arr[mid] > n:
        return binary_search(arr, n, mid + 1, hi)
    else:
        return mid

Where can I optimise my code?

MM360
  • 43
  • 4