Some whole numbers, nums, are written on a board. Alice and Bob take turns, Alice first, and on each turn the player must wipe exactly one number off the board.
Two rules decide the game, using the XOR of everything still on the board (the XOR of an empty board is 0). A player who begins a turn with the board's XOR equal to 0 wins right away. A player whose erase makes the XOR become 0 loses.
Return true if Alice wins when both players play as well as they can.
Example 1
Input: nums = [5,3,6] Output: true Why: 5 XOR 3 XOR 6 = 0 before Alice moves
2 more examples and the constraints
Example 2
Input: nums = [4,4,1] Output: false Why: every line of play forces Alice to make the XOR 0
Example 3
Input: nums = [2,7] Output: true Why: an even count: Bob is left with the last number
Constraints
- 1 ≤ nums.length ≤ 1,000
- 0 ≤ nums[i] ≤ 65,535
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Search the game with a memoO(2ⁿ)
- Parity and XORO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | States for 1,000 different numbers | Verdict |
|---|---|---|---|
| Search the game with a memo | O(2ⁿ · n) | Only for few distinct values | |
| Parity and XOR | O(n) | Best; one pass |
n = the length of nums.
Edge cases to test
- XOR is 0 at the start. Alice wins at once, even with an odd count, as in [5, 3, 6] or [0].
- A single non-zero number. Alice must erase it, the board XOR becomes 0, and she loses.
- An even count. Always true, whatever the values; the proof is a safe erase always exists.
- Zeros on the board. Erasing a 0 never changes the XOR, so it is always safe when the XOR is non-zero.
Common mistakes
- Returning only
len(nums) % 2 == 0and missing odd boards whose XOR is already 0. - Returning only
xor == 0and missing that every even board is a win. - Trying a full game search, which is exponential for 1,000 numbers.
How to talk through it
- 1Clarify. Does a player win when they start a turn on XOR 0, even before moving? What is the XOR of an empty board?
- 2Small cases. Search a few tiny boards by hand and notice even counts always win.
- 3Prove it. If every erase gave XOR 0, every number would equal the XOR, and an even number of equal values XORs to 0.
- 4Finish the rule. Odd count: Alice wins only if the XOR is already 0. O(n) time, O(1) space.
- 5Test out loud. Try [5, 3, 6], [4, 4, 1] and [9].
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?