Intuition
Play the game out: Alice takes 10, Bob takes 9, Alice takes 8, and so on. The size of each turn is fixed and only shrinks, so simulating the pile until someone can't move tells you who loses.
Explanation
Idea
The game is completely deterministic, with no choices to make. On turn 1 Alice must remove 10 stones, on turn 2 Bob must remove 9, on turn 3 Alice removes 8, and so on, each turn one smaller than the last. So we can simulate the turns until a player faces a pile too small for their required removal: that player cannot move and loses.
Walk-through (n = 12)
- Turn 1: Alice, remove 10. The pile has 12 stones and 12 ≥ 10, so Alice removes 10, leaving 2. Next required removal drops to 9.
- Turn 2: Bob, remove 9. The pile has only 2 stones and 2 < 9, so Bob cannot move. Bob loses, so Alice wins → true.
Walk-through (n = 19)
- Turn 1: Alice, remove 10. 19 ≥ 10 → remove 10, leaving 9. Next removal: 9.
- Turn 2: Bob, remove 9. 9 ≥ 9 → remove 9, leaving 0. Next removal: 8.
- Turn 3: Alice, remove 8. 0 < 8 → Alice cannot move. Alice loses → false.
Why a loop, not a formula
Track the current required removal (starting at 10) and whose turn it is (Alice first). While the pile holds at least that many stones, subtract them, drop the required removal by one, and hand the turn to the other player. When the loop stops, the player about to move is stuck, so the other player is the winner. Alice wins exactly when it is Bob who gets stuck.
Complexity
- Time: O(1). At most 10 turns run before the required removal reaches 0 (the sum 10+9+...+1 = 55 already exceeds the largest n).
- Space: O(1)
Implementation
class Solution {
public boolean canAliceWin(int n) {
int remove = 10;
boolean aliceTurn = true;
while (remove > 0 && n >= remove) {
n -= remove;
remove -= 1;
aliceTurn = !aliceTurn;
}
// The loop stops on the first player who cannot remove `remove` stones;
// that player loses, so Alice wins iff it is Bob's turn when it stops.
return !aliceTurn;
}
}