Sum Game - Problem

Alice and Bob take turns playing a game, with Alice starting first.

You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num:

  • Choose an index i where num[i] == '?'.
  • Replace num[i] with any digit between '0' and '9'.

The game ends when there are no more '?' characters in num.

For Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal.

For example, if the game ended with num = "243801", then Bob wins because 2+4+3 = 8+0+1. If the game ended with num = "243803", then Alice wins because 2+4+3 != 8+0+3.

Assuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win.

Input & Output

Example 1 — Alice Advantage
$ Input: num = "5?2?"
Output: true
💡 Note: Left sum = 5, right sum = 2. Current diff = 3. Alice can maintain this difference since 2*3 + 9*0 = 6 ≠ 0.
Example 2 — Perfect Balance Possible
$ Input: num = "??1??2"
Output: true
💡 Note: Left sum = 1, right sum = 2. Diff = -1, net_questions = 2-2 = 0. Since 2*(-1) + 9*0 = -2 ≠ 0, Alice wins.
Example 3 — Equal Question Marks
$ Input: num = "??22"
Output: true
💡 Note: Left sum = 0, right sum = 4. Diff = -4, net_questions = 2-0 = 2. Since 2*(-4) + 9*2 = 10 ≠ 0, Alice wins.

Constraints

  • 2 ≤ num.length ≤ 105
  • num.length is even
  • num consists only of digits and '?'

Visualization

Tap to expand
Sum Game - Alice vs Bob INPUT String: num = "5?2?" 5 ? 2 ? i=0 i=1 i=2 i=3 First Half Second Half Game Rules: - Alice starts first - Players replace '?' with 0-9 - Bob wins: sum1 == sum2 - Alice wins: sum1 != sum2 - Both play optimally ALGORITHM STEPS 1 Count '?' in each half Left: 1, Right: 1 2 Calculate digit sums Left sum: 5, Right sum: 2 3 Compute difference diff = (5-2) + 9*(1-1)/2 = 3 4 Apply winning formula Alice wins if diff != 0 Formula: q1 = '?' count in left q2 = '?' count in right diff = sum1 - sum2 Alice wins: diff + 9*(q1-q2)/2 != 0 FINAL RESULT true Alice Wins! Analysis: q1 = 1 (left '?') q2 = 1 (right '?') sum1 = 5 sum2 = 2 diff = 5 - 2 = 3 3 + 9*(0)/2 = 3 3 != 0 --> OK Alice always wins! Key Insight: Each '?' pair (one from each side) can be neutralized by Bob with 9 total. But since Alice moves first, she can create imbalance. Alice wins if: (sum_diff) + 9 * (q_diff) / 2 is NOT zero, where Alice controls the odd '?' advantage. Here diff=3 cannot be balanced, so Alice wins regardless of play! TutorialsPoint - Sum Game | Optimal Solution
Asked in
Google 12 Microsoft 8
15.4K Views
Medium Frequency
~25 min Avg. Time
432 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