bit manipulation January 29, 2023

Game of nim

Time O(n) Space O(1) Open original problem

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)