'How can i reduce the time complexity of an algorithm?
How can I reduce the complexity of an algorithm? I'm currently doing hackerrank, where I made a solution for climbing the leaderboard, but two tests are failing because of the time limit.
I'm trying to learn how to refactor my code, with less time complexity, but I have no idea how I could reduce the two for loops into one, because I have to iterate through both of the arrays to check if the player score is higher or equal to the ranked leaderboard.
The description of the task: https://www.hackerrank.com/challenges/climbing-the-leaderboard/
I could search a solution for this, but I want to learn how can I reduce time complexity in codes that I write, what my thinking should look like when I try to do this?
function climbingLeaderboard(ranked, player) {
let positions = [];
let temp = new Set(...[ranked]);
ranked = Array.from(temp);
for(let i = 0; i < player.length; i++) {
for(let j = 0; j < ranked.length; j++) {
if(player[i] > ranked[j] || player[i] === ranked[j]) {
positions.push(j+1);
break;
} else if(j === ranked.length-1) {
positions.push(j+2);
break;
}
}
}
return positions;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
