1450. Last Stone Loses Nim

Medium3.5 points estimatedGame TheoryBit ManipulationBrainteaser

In a village game, pebbles are arranged in piles and piles[i] is the size of pile i. Two players alternate, the first player moving first. A move removes one or more pebbles from a single pile. The twist is that the player who removes the very last pebble on the table loses, so a player who faces an already empty table wins immediately. Both players play perfectly.

Return true if the first player wins and false otherwise. Your solution should run in O(n) time with O(1) extra space.

Example 1

Input:
piles = [1,1,1]
Output:
false
Explanation:
Every move takes exactly one pebble, so the first player takes the 1st and 3rd pebbles; the 3rd is the last one, and the first player loses.

Example 2

Input:
piles = [3,4,5]
Output:
true
Explanation:
Some pile is larger than 1 and the XOR 3^4^5 = 2 is non-zero, so the first player wins.

Example 3

Input:
piles = [2,2]
Output:
false
Explanation:
Some pile is larger than 1 and the XOR is 0, so the second player wins.

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…