#1927
Sum Game
MediumMathStringGreedyGame 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)
In the optimal approach, we focus on the difference between the sums of the two halves and the number of '?' characters. By strategically replacing '?' characters, we can ensure Alice wins if she can create a situation where Bob cannot balance the sums.
⚙️
Algorithm
4 steps- 1Step 1: Calculate the sum of digits in both halves, ignoring '?' characters.
- 2Step 2: Count the number of '?' in both halves.
- 3Step 3: Determine the difference between the two sums and the total '?' characters.
- 4Step 4: Check if Alice can create an imbalance by replacing '?' optimally.
solution.py15 lines
1def sumGame(num):
2 n = len(num)
3 half = n // 2
4 left_sum = sum(int(num[i]) for i in range(half) if num[i] != '?')
5 right_sum = sum(int(num[i]) for i in range(half, n) if num[i] != '?')
6 left_q = num[:half].count('?')
7 right_q = num[half:].count('?')
8
9 total_q = left_q + right_q
10 diff = abs(left_sum - right_sum)
11
12 if diff % 9 == 0 and total_q == 0:
13 return False
14 return True
15ℹ
Complexity note: The time complexity is O(n) because we only traverse the string a couple of times to compute sums and counts, making it efficient.
- 1Alice can always win if she can create a situation where Bob cannot balance the sums.
- 2The difference in sums can be manipulated using '?' characters.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.