Climbing the Leaderboard

  • + 0 comments

    Binary search would do and turns out it was pretty straight forward. Here is my snippet in Javascript.

    function binarySearch(arr, val) {
        let start = 0;
        let end = arr.length - 1;
    
        while (start <= end) {
            const mid = Math.floor((start + end) / 2);
    
            if (arr[mid] === val) {
                return mid + 1; // Found the exact value
            } else if (val > arr[mid]) {
                end = mid - 1; // Search in the left half
            } else {
                start = mid + 1; // Search in the right half
            }
        }
    
        // Determine the rank based on the insertion position
        return start + 1;
    }
    
    function climbingLeaderboard(ranked, player) {
        // Write your code here
        const uniqRanked = [...new Set(ranked)];
        return player.map((score) => {
            return binarySearch(uniqRanked, score);
        });
    }