#810
Chalkboard XOR Game
HardArrayMathBit ManipulationBrainteaserGame TheoryGame TheoryBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the properties of XOR. If the XOR of all numbers is 0, Alice wins immediately. If the XOR is non-zero, the outcome depends on the number of elements: if it's even, Alice will win; if odd, Bob will win.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the XOR of all elements in nums.
- 2Step 2: If the XOR is 0, return true (Alice wins).
- 3Step 3: If the XOR is non-zero, check the length of nums: if it's even, return true (Alice wins); if odd, return false (Bob wins).
solution.py5 lines
1def xorGame(nums):
2 total_xor = 0
3 for num in nums:
4 total_xor ^= num
5 return total_xor == 0 or len(nums) % 2 == 0ℹ
Complexity note: The time complexity is O(n) because we only need to iterate through the array once to compute the XOR. The space complexity is O(1) as we are using a constant amount of space.
- 1If the total XOR is 0, Alice wins immediately.
- 2If the total XOR is non-zero, the length of the array determines the winner.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.