Nim Game

You and a friend take turns removing 1 to 3 stones from a single heap, and you move first. Whoever takes the last stone wins. Assuming both of you play optimally, return true if you can win with n stones on the heap.

30:00

Nim Game
easy
Free written solution
Topics
Companies

You and a friend take turns removing 1 to 3 stones from a single heap, and you move first. Whoever takes the last stone wins. Assuming both of you play optimally, return true if you can win with n stones on the heap.

Example 1:
Input: {"n":4}
Output: false
Constraints:
  • 1≤n≤231−11 \leq n \leq 2^{31} - 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":4}

4 stones on the heap, you move first. Solve small heaps first to see who wins each one.

the heap

● taken by you

● taken by friend

who wins with k stones, player to move

0

?

1

?

2

?

3

?

4

?

the rule

lose ⇔ n is a multiple of 4
Variables
VariableValue
n4
DepthFunction Call
Stack empty
0/11