Skip to content
DeepForgeby svx
All problems
MediumAlgorithmsal-160

Nim Game

Problem

Given a pile of n stones and the rule that each player removes 1 to 3 stones, return True if the first player has a winning strategy.

Multiples of 4 are losing positions because every move leaves a non-multiple that the opponent can restore. Any other value is a win; n = 0 is a loss.

Hint

Whatever the opponent takes, you can take 4 minus that amount.

Test cases

case 1
in: [4]
expected: false
case 2
in: [1]
expected: true
case 3
in: [2]
expected: true
case 4
in: [5]
expected: true
case 5
in: [0]
expected: false
Starter codePython
def nim_game(n):
    # Your code here
    pass

5 test cases · run your code against them in the editor