Algorithms · Visualized
Game: Nim
Game Theory & Minimax
Two-player games — who wins with perfect play, and by how much.
In the classic Nim game, two players alternate removing any number of objects from a single pile (or one of several piles), and whoever takes the last object wins. Time: O(n) average, O(n) worst; space: O(1).
Big-O: Winning positions, DP over states, and minimax evaluation.
Nim Game (XOR)
Game Theory / MinimaxIn the classic Nim game, two players alternate removing any number of objects from a single pile (or one of several piles), and whoever takes the last object wins. Remarkably, the entire outcome can be predicted instantly using XOR: if the XOR of all pile sizes is non-zero, the first player can always force a win; if it's zero, the second player can.
How Nim Works
- Compute the XOR of the sizes of all piles.
- If the result is non-zero, the position is a 'winning' position for the player about to move — they can always make a move that leaves a XOR of 0 for their opponent.
- If the result is zero, the position is a 'losing' position for the player about to move — no matter what they do, they'll leave a non-zero XOR for their opponent.
- To find a winning move from a non-zero XOR position: find a pile where reducing it would make the total XOR become 0, and remove enough objects from that pile to achieve it.
- Repeating this strategy every turn guarantees a win for whoever holds the advantage.
Nim Worked Example
Input: [3, 4, 5]
XOR of piles: 3 XOR 4 XOR 5 = 2 (non-zero) → first player wins with correct play. To find the move: try reducing pile1 (3) to make total XOR 0 — target value for pile1 is (4 XOR 5)=1, so reduce pile1 from 3 to 1 (remove 2 objects). New piles [1,4,5], XOR=1^4^5=0 — now it's a losing position for the opponent.
def nim_game(piles):
xor_all = 0
for p in piles:
xor_all ^= p
# first player wins unless xor of all piles is 0
return xor_all != 0Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Nim Time & Space Complexity
When to Use Nim
- A foundational result in combinatorial game theory; the XOR trick generalizes to many other 'take-away' games (Nim-variants) used in game AI and puzzle design.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.