Stone Removal Game
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Alice and Bob are playing a game where they take turns removing stones from a pile, with Alice going first.
- Alice starts by removing exactly 10 stones on her first turn.
- For each subsequent turn, each player removes exactly 1 fewer**** stone**** than the previous opponent.
The player who cannot make a move loses the game.
Given a positive integer n, return true if Alice wins the game and false
otherwise.
Examples
Example 1
Input: n = 12
Output: true
Explanation:
* Alice removes 10 stones on her first turn, leaving 2 stones for Bob.
* Bob cannot remove 9 stones, so Alice wins.
Example 2
Input: n = 1
Output: false
Explanation:
* Alice cannot remove 10 stones, so Alice loses.
Constraints
1 <= n <= 50
Solution
Method 1 - Simulate the Game
Intuition
Simulate the game turn by turn. Alice starts by removing 10 stones, then each player removes 1 less than the previous move. The player who cannot make a move loses.
Approach
- Start with Alice's turn, removing 10 stones.
- Alternate turns, each time removing 1 less stone than the previous move.
- If a player cannot remove the required number of stones, they lose.
Code
C++
class Solution {
public:
bool stoneGame(int n) {
int turn = 0, remove = 10;
while (n >= remove) {
n -= remove;
remove--;
turn ^= 1;
}
return turn == 1; // If it's Alice's turn, she lost; if Bob's, Alice won
}
};
Go
func stoneGame(n int) bool {
turn, remove := 0, 10
for n >= remove {
n -= remove
remove--
turn ^= 1
}
return turn == 1
}
Java
class Solution {
public boolean stoneGame(int n) {
int turn = 0, remove = 10;
while (n >= remove) {
n -= remove;
remove--;
turn ^= 1;
}
return turn == 1;
}
}
Kotlin
fun stoneGame(n: Int): Boolean {
var turn = 0; var remove = 10; var stones = n
while (stones >= remove) {
stones -= remove
remove--
turn = turn xor 1
}
return turn == 1
}
Python
def stoneGame(n: int) -> bool:
turn, remove = 0, 10
while n >= remove:
n -= remove
remove -= 1
turn ^= 1
return turn == 1
Rust
pub fn stone_game(mut n: i32) -> bool {
let mut turn = 0;
let mut remove = 10;
while n >= remove {
n -= remove;
remove -= 1;
turn ^= 1;
}
turn == 1
}
TypeScript
function stoneGame(n: number): boolean {
let turn = 0, remove = 10;
while (n >= remove) {
n -= remove;
remove--;
turn ^= 1;
}
return turn === 1;
}
Complexity
- ⏰ Time complexity:
O(1)(since the number of turns is at most 10) - 🧺 Space complexity:
O(1)