This is such a tricky coding puzzle, you won't believe the algorithm I had to make to solve it.

function addToLeaderboard(player, ranked) { }

// Can you write the code for the addToLeaderboard() function?

console.log(addToLeaderboard([80, 60, 60, 10], [90])); // [1]
console.log(addToLeaderboard([80, 60, 60, 10], [90, 100])); // [2, 1]
console.log(
  addToLeaderboard([80, 60, 60, 10], [90, 60, 5]) // [1, 3, 5]
);

So first let's understand what the puzzle is about.

You have a function that takes two inputs:

  • a player array -- a list of player scores

  • a ranked array -- a list of scores already on the leaderboard

So each of the scores in ranked are ranked.

For example:

  • Player scores: 80, 60, 10

  • Resulting ranking: 1, 2, 3 -- respectively

Ignoring how bad you have to be get 10 in any sort of game where others are scoring 80...

What if the players what if the players are tied? For example:

  • 80, 60, 60, 10

Result ranking:

  • 1, 2, 2, 3

You give the same rank to the tied players, and then the next players get the rank after that.

So what does the function do? It adds the new batch of scores in player to the leaderboard in ranked -- which ranks them

The function will return an array of the new ranks of these new scores that just got added.

For example if the player array is [90] -- just one item, it will return [1] -- the scores are now 90, 80, 60, 10.

So if the array is [90, 60, 5], what will it return?

It will be [1, 3, 5] -- NOT [1, 2, 4] or [1, 2, 5] like you might mistakenly guess.

So this is where we are:

JavaScriptCopied!

function addToLeaderboard(ranked, players) {
    
}

console.log(addToLeaderboard([80, 60, 60, 10], [90])); // [1]
console.log(addToLeaderboard([80, 60, 60, 10], [90, 100])); // [2, 1]
console.log(
  addToLeaderboard([80, 60, 60, 10], [90, 60, 5]) // [1, 3, 5]
);

So how we go about it? How do we get the ranks of the newly added scores.

I can see that data from both arrays are being combine into each other to give the updated leaderboard data.

You can also see that this is a leaderboard of scores -- which clearly means sorting is going on...

Can you see where this is going?

Initially, I thought…

Built for Managers, Not Engineers

AI isn’t just for developers. The AI Report gives business leaders daily, practical insights you can apply to ops, sales, marketing, and strategy.

No tech jargon. No wasted time. Just actionable tools to help you lead smarter.

Start where it counts.

Choose the Right AI Tools

With thousands of AI tools available, how do you know which ones are worth your money? Subscribe to Mindstream and get our expert guide comparing 40+ popular AI tools. Discover which free options rival paid versions and when upgrading is essential. Stop overspending on tools you don't need and find the perfect AI stack for your workflow.

Keep Reading

No posts found