1429. Nim Winning Moves

Easy1.5 points estimatedGame TheoryBit Manipulation

Two players take turns at a game of stone piles. On a turn a player picks one pile in the array piles and removes at least one stone from it; the player who takes the last stone wins, and both play perfectly. Count how many different winning first moves the starting player has, where a move is identified by the pile it is made on (each pile has at most one winning reduction). Return 0 if the position is already lost. Let X be the XOR of all piles: reducing pile i to piles[i] ^ X wins exactly when that value is smaller than piles[i]. The expected running time is O(n) with O(1) extra space.

Example 1

Input:
piles = [3,4,5]
Output:
1
Explanation:

The XOR is 2; only pile 3 can drop to 3 ^ 2 = 1, so there is exactly one winning move.

Example 2

Input:
piles = [1,2,3]
Output:
0
Explanation:

The XOR is 0, so the position is lost and no winning move exists.

Constraints

1 ≤ n = piles.length ≤ 1000
0 ≤ piles[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…