Opening the reading…
Opening the reading…
GAME THEORY › LEVEL I
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →Start with the smallest positions. With 1, 2, or 3 stones, you take all the stones and win. With 4 stones, every move leaves 3, 2, or 1 stones for your opponent, and your opponent takes the rest. Therefore 4 is losing, while 1, 2, and 3 are winning positions.
The same idea repeats after every four stones. If you leave your opponent a multiple of 4, then whatever they remove, from 1 to 3, you remove the complementary number so the two moves remove exactly 4 stones. Starting from a non-multiple of 4, remove its remainder: 1, 2, or 3 stones. Starting from a multiple of 4, every first move gives the opponent a winning non-multiple.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(1) | The solution performs one remainder operation and one comparison, regardless of how large n is; it does not visit individual stones or game states. |
| Space | O(1) extra | Only the input value and a boolean result are used. The returned boolean is required output and is excluded from the extra-space bound, which remains constant for every valid input. |
#include <iostream>
using namespace std;
class Solution {
public:
bool canWinNim(int n) {
return n % 4 != 0;
}
};The entire proof is captured by the comparison n % 4 != 0. A remainder of 1, 2, or 3 tells you exactly how many stones to remove first. A remainder of 0 means no legal move can leave another multiple of 4, so the opponent can make the complementary response after every turn.