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 - Optimal Solution INPUT stones array 2 index 0 1 index 1 Classify by mod 3: cnt0=0 cnt1=1 cnt2=1 2 mod 3 = 2 1 mod 3 = 1 stones = [2, 1] n = 2 ALGORITHM STEPS 1 Count remainders Group stones by value mod 3 2 Check special case If cnt1=0 or cnt2=0, check cnt0 3 General case Compare cnt1 and cnt2 diff 4 Determine winner Apply optimal strategy rules Decision Logic: cnt0=0, cnt1=1, cnt2=1 Both cnt1 > 0 AND cnt2 > 0 |cnt1 - cnt2| = 0 <= 2 cnt0 is even (0) Alice can win! FINAL RESULT Optimal Play Simulation Turn 1: Alice picks 1 Sum = 1 (not divisible by 3) Turn 2: Bob picks 2 Sum = 3 (divisible by 3!) Bob LOSES! Alice WINS Output: true Key Insight: The game depends on counting stones by their remainder when divided by 3. Stones with remainder 0 swap the advantage between players. Alice wins when both cnt1 and cnt2 are positive, and either |cnt1-cnt2| > 2, or cnt0 is even. With cnt0=0 (even), cnt1=1, cnt2=1: Alice has a winning strategy! TutorialsPoint - Stone Game IX | Optimal Solution
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