Last active
September 8, 2019 12:48
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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