Alice and Bob take turns playing a game with Alice starting first.
In this game, there are n piles of stones. On each player’s turn, the player should remove any positive number of stones from a non-empty pile of his or her choice. The first player who cannot make a move loses, and the other player wins.
Given an integer array piles, where piles[i] is the number of stones in the ith pile, return trueif Alice wins, orfalseif Bob wins.
Input: piles =[1]Output: trueExplanation: There is only one possible scenario:- On the first turn, Alice removes one stone from the first pile. piles =[0].- On the second turn, there are no stones left for Bob to remove. Alice wins.
Example 2:
1
2
3
4
5
6
Input: piles =[1,1]Output: falseExplanation: It can be proven that Bob will always win. One possible scenario is:- On the first turn, Alice removes one stone from the first pile. piles =[0,1].- On the second turn, Bob removes one stone from the second pile. piles =[0,0].- On the third turn, there are no stones left for Alice to remove. Bob wins.
Example 3:
1
2
3
4
5
6
7
8
Input: piles =[1,2,3]Output: falseExplanation: It can be proven that Bob will always win. One possible scenario is:- On the first turn, Alice removes three stones from the third pile. piles =[1,2,0].- On the second turn, Bob removes one stone from the second pile. piles =[1,1,0].- On the third turn, Alice removes one stone from the first pile. piles =[0,1,0].- On the fourth turn, Bob removes one stone from the second pile. piles =[0,0,0].- On the fifth turn, there are no stones left for Alice to remove. Bob wins.
Constraints:
n == piles.length
1 <= n <= 7
1 <= piles[i] <= 7
Follow-up: Could you find a linear time solution? Although the linear time
solution may be beyond the scope of an interview, it could be interesting to
know.
The classic Nim game is solved using the XOR of all pile sizes. If the XOR is zero, the current player loses (Bob wins); otherwise, the current player wins (Alice wins). This is because XOR encodes the parity of the game state, and any nonzero XOR means the first player can always force a win with optimal play.