Skip to content

Instantly share code, notes, and snippets.

@karpolan
Last active September 8, 2019 12:48
Show Gist options
  • Save karpolan/42cf03131bc33f4bb5f7535c8b872570 to your computer and use it in GitHub Desktop.
Save karpolan/42cf03131bc33f4bb5f7535c8b872570 to your computer and use it in GitHub Desktop.
O(m+n) for HackerRank - Climbing the Leaderboard (https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem)
// For https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem
function climbingLeaderboard(scores, alice) {
let positionsCount = 1;
const uscores = [scores[0]]; // Unique scores only, shorter array
scores.reduce((prev, curr) => {
if (prev != curr) {
positionsCount++;
uscores.push(curr)
}
return curr;
})
let prevScoreIndex = uscores.length; // Latest index + outside
let prevScoreValue = uscores[uscores.length - 1] - 1; // Smallest value - something
let positionPivot = positionsCount + 1; // Latest postion + outside
const result = [];
alice.forEach((value) => {
if (value > prevScoreValue) {
// Alice's position has been improved
let currentScore = uscores[prevScoreIndex - 1];
let positionsToSkip = 0
for (let i = prevScoreIndex - 1; i >= 0; i--) {
// Increase positionsToSkip on every score value changes
if (uscores[i] != currentScore) {
positionsToSkip++;
currentScore = uscores[i]
}
// Search for index to add new value
if (uscores[i] > value) {
// Our value should be inserted into uscore[i + 1]
prevScoreIndex = i + 1;
prevScoreValue = value;
uscores[prevScoreIndex] = value;
positionPivot = positionPivot - positionsToSkip;
break;
}
if (i == 0) {
// New value is the same or higer than first/biggest one
prevScoreIndex = 0;
prevScoreValue = value;
uscores[prevScoreIndex] = value;
positionPivot = 1;
}
}
}
result.push(positionPivot);
})
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment