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.
1import java.util.*;
2
3class Solution {
4 public boolean xorGame(int[] nums) {
5 int xorSum = 0;
6 for (int num : nums) {
7 xorSum ^= num;
8 }
9 return xorSum == 0 || nums.length % 2 == 0;
10 }
11}
This Java solution calculates the XOR of all elements in the nums array. If the result is zero or the number of elements 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.