Sum Game — LeetCode 1927 Python Solution
MediumGreedyMathStringGame Theory
- Problem
- #1927
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- num = "5023"
- Output
- false
- Explanation
- There are no moves to be made.
Python solution
Python
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) // 2Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1927. Sum Game is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1927. Sum Game?
- LeetCode 1927. Sum Game is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1927. Sum Game?
- The Python solution on this page runs in O(n), where n is the length of the string.
- What is the space complexity of LeetCode 1927. Sum Game?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1927. Sum Game cover?
- LeetCode 1927. Sum Game is tagged Greedy, Math, String and Game Theory on LeetCode.