Stone Game IX - Problem

Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones, where stones[i] is the value of the ith stone.

Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones. The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3. Bob will win automatically if there are no remaining stones (even if it is Alice's turn).

Assuming both players play optimally, return true if Alice wins and false if Bob wins.

Input & Output

Example 1 — Alice Wins
$ Input: stones = [2,1]
Output: true
💡 Note: Alice picks 2 (sum=2), Bob must pick 1 (sum=3), Bob loses since 3 is divisible by 3
Example 2 — Bob Wins
$ Input: stones = [2]
Output: false
💡 Note: Alice must pick 2 (sum=2), no stones left for Bob, so Bob wins automatically
Example 3 — Only Multiples of 3
$ Input: stones = [3,6,9]
Output: false
💡 Note: Any first move by Alice creates sum divisible by 3, so Alice loses immediately

Constraints

  • 1 ≤ stones.length ≤ 105
  • 1 ≤ stones[i] ≤ 104

Visualization

Tap to expand
Stone Game IX: Avoid Sum Divisible by 321Initial stones: [2, 1]Alice picks 2Bob picks 1Sum = 2Sum = 3 ≡ 0 (mod 3)Bob loses! Sum divisible by 3Alice wins: true
Understanding the Visualization
1
Input
Array of stone values: [2,1]
2
Game Play
Players alternate, lose if sum ≡ 0 (mod 3)
3
Output
true if Alice wins, false if Bob wins
Key Takeaway
🎯 Key Insight: Alice wins if she can force Bob into making a sum divisible by 3
Asked in
Google 35 Microsoft 28 Amazon 22
28.5K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen