Nim Game - Problem

You are playing the following Nim Game with your friend:

Initially, there is a heap of stones on the table. You and your friend will alternate taking turns, and you go first. On each turn, the person whose turn it is will remove 1 to 3 stones from the heap. The one who removes the last stone is the winner.

Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false.

Input & Output

Example 1 — Small Winning Position
$ Input: n = 4
Output: false
💡 Note: No matter what you choose (1, 2, or 3 stones), your opponent can take the remaining stones and win. If you take 1, opponent can take 3. If you take 2, opponent can take 2. If you take 3, opponent can take 1.
Example 2 — Winning Move Available
$ Input: n = 1
Output: true
💡 Note: You can take the last stone directly and win the game.
Example 3 — Strategic Winning
$ Input: n = 5
Output: true
💡 Note: You can take 1 stone, leaving 4 stones for your opponent. From 4 stones, your opponent will be in a losing position (any move they make puts you in a winning position).

Constraints

  • 1 ≤ n ≤ 2³¹ - 1

Visualization

Tap to expand
Nim Game - Optimal Solution INPUT Heap of Stones (n = 4) 1 2 3 4 n = 4 Number of stones Rules: - Remove 1-3 stones per turn - Last stone wins - You go first ALGORITHM STEPS 1 Identify Pattern If n % 4 == 0, you lose 2 Why n=4 Loses Take 1,2,3 --> Friend wins 3 Mathematical Proof Friend always makes total 4 4 Apply Formula return n % 4 != 0 Game Scenarios for n=4 You Take Left Friend 1 3 Takes 3 2 2 Takes 2 3 1 Takes 1 Friend always wins! FINAL RESULT Calculation: n % 4 != 0 4 % 4 = 0 false You cannot win! With n=4 stones, no matter how many you take (1-3), your friend takes the rest. return n % 4 != 0; Key Insight: The game state repeats every 4 stones. If n is divisible by 4, you're in a losing position because your opponent can always mirror your moves to ensure they take the last stone. Time: O(1), Space: O(1) TutorialsPoint - Nim Game | Optimal Mathematical Solution
Asked in
Adobe 15 Microsoft 8
32.0K Views
Medium Frequency
~5 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen