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.
O(logN) - Java solution
Tip: Use Binary Search since the data is sorted.
public static List climbingLeaderboard(List ranked, List player) {
// Write your code here
List ranks = new ArrayList<>();
ranks.add(1);
for (int i = 1 ; i < ranked.size() ; i++) {
if (ranked.get(i) < ranked.get(i-1)) {
ranks.add(ranks.get(i-1) + 1);
} else {
ranks.add(ranks.get(i-1));
}
}
List playerRanks = new ArrayList<>();
int[] arr = new int[1];
for (int x : player) {
arr[0] = -1;
binarySearch(ranked, arr, 0, ranked.size() - 1,x, ranks);
if (arr[0] != -1) {
playerRanks.add(arr[0]);
} else {
playerRanks.add(ranks.get(ranks.size() - 1) + 1);
}
}
return playerRanks;
}
private static void binarySearch(List<Integer> ranked, int [] arr, int low, int high, int score, List<Integer> ranks) {
if (low > high) {
return;
}
if (high < low) {
return;
}
int mid = (low + high)/2;
if (score > ranked.get(mid)) {
arr[0] = ranks.get(mid);
binarySearch(ranked, arr, low, mid - 1, score, ranks);
} else if (score < ranked.get(mid)) {
binarySearch(ranked, arr, mid + 1, high, score, ranks);
} else {
arr[0] = ranks.get(mid);
return;
}
}
return;
}
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Climbing the Leaderboard
You are viewing a single comment's thread. Return to all comments →
O(logN) - Java solution Tip: Use Binary Search since the data is sorted. public static List climbingLeaderboard(List ranked, List player) { // Write your code here List ranks = new ArrayList<>(); ranks.add(1); for (int i = 1 ; i < ranked.size() ; i++) { if (ranked.get(i) < ranked.get(i-1)) { ranks.add(ranks.get(i-1) + 1); } else { ranks.add(ranks.get(i-1)); } } List playerRanks = new ArrayList<>();
int[] arr = new int[1];
} return; } }
}