Show problems as
Classic problem #292EasyMathBrainteaserMinimaxGame TheoryNim GameImpartial Game

Nim Game

Real-world version: Taking the Last Tile
Tracked in this browser only
Read Nim Game on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A single stack holds count tiles. You and one opponent take turns, and you take the first turn. On a turn the player whose turn it is removes 1, 2 or 3 tiles from the stack; a player may never pass and may never remove more tiles than the stack holds. Whoever removes the very last tile wins.

Both players see the whole stack and play as well as the position allows. Return true if you can win from this stack no matter how your opponent replies, and false if your opponent can win no matter how you play.

Examples

Example 1

Input
count = 7
Output
true

You open by taking 3 tiles. Your opponent then takes 1, 2 or 3 of the 4 tiles left, and each of those replies leaves you a stack you clear on your next turn.

Example 2

Input
count = 96
Output
false

Whichever of 1, 2 or 3 tiles you open with, your opponent has a reply that keeps you from ever taking the last tile.

Example 3

Input
count = 3
Output
true

Taking 3 tiles is legal on a single turn, so you clear the stack immediately and the last tile is yours.

Constraints

  • 1 <= count <= 2^31 - 1

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def can_take_last(count: int) -> bool:
Java
public boolean canTakeLast(int count)