Sum Game Problem
Description
LeetCode Problem 1927.
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
iwherenum[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 because2+4+3 = 8+0+1. If the game ended withnum = "243803", then Alice wins because2+4+3 != 8+0+3.
Assuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win.
Example 1:
Input: num = "5023"
Output: false
Explanation: There are no moves to be made.
The sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.
Example 2:
Input: num = "25??"
Output: true
Explanation: Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal.
Example 3:
Input: num = "?3295???"
Output: false
Explanation: It can be proven that Bob will always win. One possible outcome is:
- Alice replaces the first '?' with '9'. num = "93295???".
- Bob replaces one of the '?' in the right half with '9'. num = "932959??".
- Alice replaces one of the '?' in the right half with '2'. num = "9329592?".
- Bob replaces the last '?' in the right half with '7'. num = "93295927".
Bob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.
Constraints:
2 <= num.length <= 10^5num.lengthis even.numconsists of only digits and'?'.
Solution
Approach: Case Analysis
Count the '?' marks in each half (cnt1, cnt2) and the sum of the known digits in each half (s1, s2).
If the total number of '?' is odd, Alice wins: she makes the last move, and whatever the two sums are before it, she can choose a digit that leaves them different.
If it is even, Bob has the last move and can answer Alice by pairing the marks: whenever Alice puts a on a '?', Bob puts 9 - a on another one, so every pair of marks adds exactly 9 to its half. In effect, each half is worth its known digits plus 9 * cnt / 2 for its cnt marks. Bob wins exactly when the two halves are worth the same, that is, s1 + 9 * cnt1 / 2 = s2 + 9 * cnt2 / 2. When they differ, Alice can always play a 0 or a 9 that Bob cannot compensate.
So Alice wins if cnt1 + cnt2 is odd or s1 - s2 differs from 9 * (cnt2 - cnt1) / 2.
Complexity: O(n) time and O(1) extra space, where n is the length of num.
class Solution:
def sumGame(self, num: str) -> bool:
n = len(num)
cnt1 = num[: n // 2].count("?")
cnt2 = num[n // 2 :].count("?")
s1 = sum(int(x) for x in num[: n // 2] if x != "?")
s2 = sum(int(x) for x in num[n // 2 :] if x != "?")
return (cnt1 + cnt2) % 2 == 1 or s1 - s2 != 9 * (cnt2 - cnt1) // 2