Sponsored
Sponsored
The game can be reduced to a theoretical observation: Alice will win if the XOR of all elements of the array (before any move) is already 0 or if the length of the array is even. This is because, under optimal play, a XOR of 0 or an even number of moves ensures Alice's win. When it's an even number, Bob will be the one forced to make a move that reduces the XOR to 0 if possible.
Time Complexity: O(n), where n is the length of nums.
Space Complexity: O(1), as no extra space is used beyond a few variables.
1using System;
2
3public class Solution {
4 public bool XorGame(int[] nums) {
5 int xorSum = 0;
6 foreach (int num in nums) {
7 xorSum ^= num;
8 }
9 return xorSum == 0 || nums.Length % 2 == 0;
10 }
11}
The C# solution uses a foreach loop to calculate the XOR of all nums. If the XOR is zero or the length of nums is even, Alice wins.
This approach builds upon understanding the subproblems of removing each number and calculating the XOR of the remaining elements. Even though its complexity is higher, this method helps us understand more granular moves and outcomes if not assuming mathematical shortcuts.
Time Complexity: O(2^n) due to the exponential number of XOR states possible.
Space Complexity: O(n), largely dictated by function call stack depth.
1import java
In Java, the solution is similar with recursive checking of possible moves and forming a unique state identifier using mask logic. Memoization is employed to limit redundant computation.