Search⌘ K
AI Features

Solution: Nim Game

Understand how to determine the winning player in the Nim Game by applying a simple modulo 4 check. This lesson helps you master the mathematical insight that if the total stones are divisible by 4, the first player loses when both play optimally. Gain the ability to implement a constant time and space solution based on this pattern.

Statement

You and a friend are playing a game called the Nim Game with a heap of stones. The rules are as follows:

  • There is a single heap containing n stones.

  • You and your friend take alternating turns, with you going first.

  • On each turn, the current player must remove between ...