Winner in XOR Game of Alternate Moves

Last Updated : 10 Oct, 2026

Given an array arr[] of positive integers, two players take turns removing exactly one element from the array.

  • Before every turn, if the bitwise XOR of all remaining elements is 0, the player whose turn it is wins immediately.
  • If the XOR is not 0, the player must remove one element.
  • Both players play optimally.
  • If an array becomes empty, the XOR is considered as 0.

Return true if the second player wins; otherwise, return false.

Examples:

Input: arr[] = [1, 2, 3]
Output: false
Explanation: The XOR is 1 ^ 2 ^ 3 = 0. Therefore, the first player wins immediately.

Input: arr[] = [1, 2, 4]
Output: true
Explanation: The initial XOR is non-zero, so the first player must remove an element. The game continues until the array becomes empty. Since the initial number of elements is odd, the second player gets the winning position.

[Naive Approach] Recursive Game Simulation - O(n * 2 ^ n) Time and O(n) Space

The idea is to simulate all possible moves and find the winner by assuming that both players play optimally.

We try every possible permutation of the array. We mainly try every possible value for every turn. For every value, calculate the XOR of the remaining elements and pick a value that makes remaining XOR non-zero.

Working of Approach:

  • Calculate the XOR of the remaining elements before each turn.
  • If the XOR is zero, the current player wins immediately.
  • Otherwise, try removing each remaining element one by one.
  • Recursively check whether the opponent can win after each removal.
  • If any move makes the opponent lose, the current player can win.
C++
#include <iostream>
#include <vector>
using namespace std;

// Check whether the current player can win.
bool canWin(vector<int> &arr, int mask)
{
    int xr = 0;
    int n = arr.size();

    // Calculate XOR of the remaining elements.
    for (int i = 0; i < n; i++)
    {
        if (mask & (1 << i))
            xr ^= arr[i];
    }

    // The current player wins if XOR is zero.
    if (xr == 0)
        return true;

    // Try removing each remaining element.
    for (int i = 0; i < n; i++)
    {
        if (mask & (1 << i))
        {
            if (!canWin(arr, mask ^ (1 << i)))
                return true;
        }
    }

    return false;
}

bool makeZero(vector<int> &arr)
{
    int xr = 0;

    // Calculate the initial XOR.
    for (int x : arr)
        xr ^= x;

    // The first player wins if XOR is initially zero.
    if (xr == 0)
        return false;

    // Check whether the second player wins.
    return !canWin(arr, (1 << arr.size()) - 1);
}

int main()
{
    vector<int> arr = {1, 2, 4};

    cout << boolalpha << makeZero(arr) << endl;
    return 0;
}
Java
import java.util.Arrays;

public class GFG {

    // Check whether the current player can win.
    public static boolean canWin(int[] arr, int mask)
    {
        int xr = 0;
        int n = arr.length;

        // Calculate XOR of the remaining elements.
        for (int i = 0; i < n; i++) {
            if ((mask & (1 << i)) != 0)
                xr ^= arr[i];
        }

        // The current player wins if XOR is zero.
        if (xr == 0)
            return true;

        // Try removing each remaining element.
        for (int i = 0; i < n; i++) {
            if ((mask & (1 << i)) != 0) {
                if (!canWin(arr, mask ^ (1 << i)))
                    return true;
            }
        }

        return false;
    }

    public static boolean makeZero(int[] arr)
    {
        int xr = 0;

        // Calculate the initial XOR.
        for (int x : arr)
            xr ^= x;

        // The first player wins if XOR is initially zero.
        if (xr == 0)
            return false;

        // Check whether the second player wins.
        return !canWin(arr, (1 << arr.length) - 1);
    }

    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 4 };

        System.out.println(makeZero(arr));
    }
}
Python
def canWin(arr, mask):
    xr = 0
    n = len(arr)

    # Calculate XOR of the remaining elements.
    for i in range(n):
        if mask & (1 << i):
            xr ^= arr[i]

    # The current player wins if XOR is zero.
    if xr == 0:
        return True

    # Try removing each remaining element.
    for i in range(n):
        if mask & (1 << i):
            if not canWin(arr, mask ^ (1 << i)):
                return True

    return False

def makeZero(arr):
    xr = 0

    # Calculate the initial XOR.
    for x in arr:
        xr ^= x

    # The first player wins if XOR is initially zero.
    if xr == 0:
        return False

    # Check whether the second player wins.
    return not canWin(arr, (1 << len(arr)) - 1)

arr = [1, 2, 4]
print(makeZero(arr))
C#
using System;

public class GFG {
    // Check whether the current player can win.
    public static bool CanWin(int[] arr, int mask)
    {
        int xr = 0;
        int n = arr.Length;

        // Calculate XOR of the remaining elements.
        for (int i = 0; i < n; i++) {
            if ((mask & (1 << i)) != 0)
                xr ^= arr[i];
        }

        // The current player wins if XOR is zero.
        if (xr == 0)
            return true;

        // Try removing each remaining element.
        for (int i = 0; i < n; i++) {
            if ((mask & (1 << i)) != 0) {
                if (!CanWin(arr, mask ^ (1 << i)))
                    return true;
            }
        }

        return false;
    }

    public static bool MakeZero(int[] arr)
    {
        int xr = 0;

        // Calculate the initial XOR.
        foreach(int x in arr) xr ^= x;

        // The first player wins if XOR is initially zero.
        if (xr == 0)
            return false;

        // Check whether the second player wins.
        return !CanWin(arr, (1 << arr.Length) - 1);
    }

    public static void Main()
    {
        int[] arr = { 1, 2, 4 };

        Console.WriteLine(MakeZero(arr));
    }
}
JavaScript
function canWin(arr, mask)
{
    let xr = 0;
    const n = arr.length;

    // Calculate XOR of the remaining elements.
    for (let i = 0; i < n; i++) {
        if (mask & (1 << i)) {
            xr ^= arr[i];
        }
    }

    // The current player wins if XOR is zero.
    if (xr === 0) {
        return true;
    }

    // Try removing each remaining element.
    for (let i = 0; i < n; i++) {
        if (mask & (1 << i)) {
            if (!canWin(arr, mask ^ (1 << i))) {
                return true;
            }
        }
    }

    return false;
}

function makeZero(arr)
{
    let xr = 0;

    // Calculate the initial XOR.
    for (let x of arr) {
        xr ^= x;
    }

    // The first player wins if XOR is initially zero.
    if (xr === 0) {
        return false;
    }

    // Check whether the second player wins.
    return !canWin(arr, (1 << arr.length) - 1);
}

// Driver Code
const arr = [ 1, 2, 4 ];
console.log(makeZero(arr));

Output
true

[Expected Approach] XOR and Array Size - O(n) Time and O(1) Space

The idea is to calculate the XOR of all array elements.

  • If the XOR is zero, the first player wins immediately.
  • Otherwise the result depends on parity of the array. If array size, the second player wins else the first player.

Why does Array Size Parity Work? A player can always pick an element to ensure that the remaining values have non-zero XOR in cases when XOR is not zero. For example, in array [1, 1, 2], the player can pick 1 to ensure that the remaining elements have non-zero XOR.

Working of Approach:

  • Initialize xor_sum to zero.
  • Traverse the array and calculate the XOR of all elements.
  • If xor_sum is zero, return false because the first player wins immediately.
  • If the XOR is non-zero, check whether the array size is odd.
  • Return true if the size is odd; otherwise, return false.

Let us understand with an example:
Input: arr[] = [1, 2, 4]

  • Initialize xor_sum = 0 and traverse the array to calculate XOR.
  • After processing all elements, xor_sum = 1 ^ 2 ^ 4 = 7.
  • Since xor_sum != 0, check the size of the array.
  • The array size is 3, which is odd, so the condition arr.size() % 2 == 0 is false.
  • Therefore, the function returns true, indicating that the second player wins.

Output: true.

C++
#include <iostream>
#include <vector>
using namespace std;

bool makeZero(vector<int> &arr)
{
    int xor_sum = 0;

    // Calculate the XOR of all elements.
    for (int val : arr)
    {
        xor_sum ^= val;
    }

    // If XOR is zero, the first player wins immediately.
    if (xor_sum == 0)
        return false;

    // If XOR is non-zero, the second player wins
    // when the array size is odd.
    return arr.size() % 2 == 1;
}

int main()
{
    vector<int> arr = {1, 2, 4};

    cout << boolalpha << makeZero(arr) << endl;
    return 0;
}
Java
import java.util.Arrays;

public class GFG {
    public static boolean makeZero(int[] arr)
    {
        int xor_sum = 0;

        // Calculate the XOR of all elements.
        for (int val : arr) {
            xor_sum ^= val;
        }

        // If XOR is zero, the first player wins
        // immediately.
        if (xor_sum == 0)
            return false;

        // If XOR is non-zero, the second player wins
        // when the array size is odd.
        return arr.length % 2 == 1;
    }

    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 4 };

        System.out.println(makeZero(arr));
    }
}
Python
def makeZero(arr):
    xor_sum = 0

    # Calculate the XOR of all elements.
    for val in arr:
        xor_sum ^= val

    # If XOR is zero, the first player wins immediately.
    if xor_sum == 0:
        return False

    # If XOR is non-zero, the second player wins
    # when the array size is odd.
    return len(arr) % 2 == 1


if __name__ == "__main__":
    arr = [1, 2, 4]
    print(makeZero(arr))
C#
using System;

class GFG {
    static bool makeZero(int[] arr)
    {
        int xor_sum = 0;

        // Calculate the XOR of all elements.
        foreach(int val in arr) { xor_sum ^= val; }

        // If XOR is zero, the first player wins
        // immediately.
        if (xor_sum == 0)
            return false;

        // If XOR is non-zero, the second player wins
        // when the array size is odd.
        return arr.Length % 2 == 1;
    }

    static void Main()
    {
        int[] arr = { 1, 2, 4 };

        Console.WriteLine(makeZero(arr));
    }
}
JavaScript
function makeZero(arr)
{
    let xor_sum = 0;

    // Calculate the XOR of all elements.
    for (let val of arr) {
        xor_sum ^= val;
    }

    // If XOR is zero, the first player wins immediately.
    if (xor_sum === 0)
        return false;

    // If XOR is non-zero, the second player wins
    // when the array size is odd.
    return arr.length % 2 === 1;
}

// Driver Code
let arr = [ 1, 2, 4 ];
console.log(makeZero(arr));

Output
true
Comment