Problem Description
Alice and Bob play a game with n piles of stones. Each turn, a player removes any positive number of stones from any non-empty pile. Alice moves first. The player who is unable to make a move loses. Given the array of piles, determine if Alice, playing optimally, can guarantee a win.
Key Insights
- This is a classic Nim game.
- The key is to compute the Nim-sum (bitwise XOR of the counts in the piles).
- If the Nim-sum is non-zero, the first player (Alice) can force a win; if it is zero, Bob wins.
- The solution involves a simple linear pass over the piles array.
Space and Time Complexity
Time Complexity: O(n) because we iterate through the list of piles once. Space Complexity: O(1) as we only use a constant amount of extra space.
Solution
The problem is solved using principles from the Nim game. The idea is to calculate the XOR (also known as the Nim-sum) of all the piles. If the result is non-zero, it means the current player (Alice) can force a win with optimal play. Otherwise, the second player (Bob) wins because any move by Alice will leave a non-zero Nim-sum for Bob. We use a simple loop to compute the Nim-sum which directly gives us the answer.