#2029
Stone Game IX
MediumArrayMathGreedyCountingGame TheoryGame TheoryGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the properties of modular arithmetic and the game structure. By counting the stones based on their values modulo 3, we can determine the winner without simulating all possible moves.
⚙️
Algorithm
3 steps- 1Step 1: Count the number of stones with values % 3 == 0, % 3 == 1, and % 3 == 2.
- 2Step 2: If there are no stones with value % 3 == 0, Alice can always win by removing stones strategically.
- 3Step 3: If there are stones with value % 3 == 0, Alice must avoid making the sum of removed stones divisible by 3.
solution.py5 lines
1def canAliceWin(stones):
2 count = [0, 0, 0]
3 for stone in stones:
4 count[stone % 3] += 1
5 return count[1] > count[2] or (count[1] == count[2] and count[0] == 0)ℹ
Complexity note: This complexity is linear because we only need to traverse the array once to count the stones, leading to a very efficient solution.
- 1Understanding the properties of modular arithmetic is crucial for solving this problem efficiently.
- 2Optimal play involves recognizing when to force the opponent into a losing position.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.