Hi! I attended a meetup a couple days ago revolving around problem solving practice for coders. The questions were pulled from Hackerrank, which is great tool for algorithm-based problems, but unfortunately, most of the answers online are in Python or Java… So today, thought I’d go through one of the problems and show how I approached and solved it using Javascript in hopes that this’ll come in handy for someone else!
Question (level medium on Hackerrank)
Andy loves playing games. He wants to play a game with his little brother, Bob, using an array, A, of n distinct integers. The rules are as follows:
- Bob always plays first and the two players move in alternating turns.
- In a single move, a player chooses the maximum element currently present in the array and removes it as well as all the other elements to its right. For example, if A = [2, 3, 5, 4, 1], then it becomes A = [2, 3] after the first move because we remove the maximum element (i.e. 5,) and all elements to its right (i.e. 4, and 1).
- The modifications made to the array during each turn are permanent, so the next player continues the game with the remaining array. The first player who is unable to make a move loses the game.
Andy and Bob play g games. Given the initial array for each game, can you find and print the name of the winner on a new line? If Andy wins, print ANDY; if Bob wins, print BOB.
Solution

Since the instructions say Bob always goes first, we set him equal to a variable to indicate he’s the starting player. We also create a shallow copy of the array using slice — it’s good practice to leave the originals untouched in case we ever need to refer it in the future.
Then, we loop through the copy of the array, and as long as there are values in the array, we do a check to see who the current player is, then perform the following: switch the player’s name to indicate a change in turn, find the maximum value in the array, and as per the instructions, get rid of the maximum value and any values to the right of the max value.
Once there are no longer any values in the array, we exit out of the loop and make sure we return the winning player’s name in all capital letters.

