Game of nim

January 29, 2023

bit-manipulation

Problem URL: Game of nim

We will calculate the XOR sum of all the piles, and check whether it's zero or not. For non zero value player 1 wins, otherwise player 2 wins.

class Solution:
    def nimGame(self, piles: List[int]) -> bool:
        nim_sum = 0
        for p in piles:
            nim_sum ^= p
        return nim_sum != 0

Time complexity: O(n)
Space complexity: O(1)