Skip to main content
Back to problems
Leetcode
Medium
Game Theory
Math
Bit Manipulation
Nim Game

Determine whether the first player can force a win in a take-away game with nn stones.

Acceptance 0%
Problem Statement

Nim Game

You are playing a simple impartial game with one pile of stones.

  • There are initially n stones in the pile.
  • Two players take turns.
  • On each turn, a player must remove 1, 2, or 3 stones from the pile.
  • The player who removes the last stone wins.

Assuming both players play optimally, determine whether the first player has a winning strategy.

This is a classic game-theory problem that can often be solved by spotting the losing positions in the game state space.

Input Format

  • A single integer n representing the number of stones in the pile.

Output Format

  • Return true if the first player can force a win.
  • Otherwise, return false.

Constraints

  • 1n1 \le n is within the usual integer range for the platform version of this problem.
  • Both players play optimally.
  • On each move, a player may remove 1, 2, or 3 stones only.
Examples
Sample cases returned by the problem API.

Example 1

Input

n = 4

Output

false

Explanation

No matter whether the first player removes 1, 2, or 3 stones, the second player can take the remaining stones and win.

Example 2

Input

n = 5

Output

true

Explanation

The first player can remove 1 stone, leaving 4 stones for the opponent, which is a losing position.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.