Python 3232.py
class Solution:
def canAliceWin(self, nums: List[int]) -> bool:
total = sum(nums)
one = sum(n for n in nums if n < 10)
two = sum(n for n in nums if 10 <= n < 100)
return one > total - one or two > total - two
Difficulty
and has an acceptance rate of about 82% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single method canAliceWin. The method receives a list of integers, computes aggregate values, and returns a Boolean indicating whether a specific winning condition is satisfied. The logic is concise, relying on Python’s built-in sum function and generator expressions to process the input in a functional style.
Core Steps
The method proceeds through three distinct calculations before arriving at the final Boolean expression.
total = sum(nums)
The first step aggregates the entire list, producing the overall sum of all elements. This value serves as the baseline against which partial sums are compared.
one = sum(n for n in nums if n < 10)
The second step isolates numbers that are strictly less than ten. By iterating over nums with a generator expression, it accumulates the sum of these single-digit values. The condition n < 10 implicitly includes negative numbers and zero, ensuring that any integer falling below the threshold contributes to one.
two = sum(n for n in nums if 10 <= n < 100)
The third step targets the two-digit range, capturing numbers from ten up to ninety-nine inclusive. The compound comparison 10 <= n < 100 filters the list accordingly, and the generator expression aggregates their sum into two.
The final return statement combines the computed aggregates:
return one > total - one or two > total - two
It evaluates whether the sum of single-digit numbers exceeds the sum of all remaining elements, or whether the sum of two-digit numbers exceeds the sum of the rest. The logical or short-circuits: if the first comparison is true, the second is not evaluated, saving a minor amount of work.
Edge Cases Handled
The implementation gracefully handles several boundary conditions without additional checks.
- Empty input: When
numsis empty,total,one, andtwoall evaluate to zero. Both comparisons become0 > 0, which is false, leading the method to returnFalse. No exception is raised. - All elements below ten: In this scenario
oneequalstotal, making the expressionone > total - onesimplify tototal > 0. If the total sum is positive, the method returnsTrue; otherwise it returnsFalse. The second term involvingtwois irrelevant because the first term already determines the outcome. - All elements of three digits or more: Neither generator expression captures any element, so both
oneandtworemain zero. The return expression reduces to0 > totalfor both sides, which is false, yieldingFalse. - Mixed sign values: Negative numbers satisfy the
n < 10predicate and therefore contribute toone. This inclusion means the method correctly accounts for scenarios where negative single-digit values affect the winning condition. - Boundary values 10 and 99: The inclusive lower bound (
10 <= n) and exclusive upper bound (n < 100) ensure that exactly ten and ninety-nine are counted intwo, while nine and one hundred are not. This precise handling avoids off-by-one errors.
Performance Optimizations
The code leverages several language features that contribute to efficient execution.
- Built-in aggregation: Using
sumwith generator expressions delegates the iteration to CPython’s optimized C loops, reducing overhead compared with explicit Pythonforloops. - Lazy evaluation: Generator expressions produce values on the fly without constructing intermediate lists, conserving memory especially for large input arrays.
- Short-circuit logic: The
oroperator stops evaluation after the first true condition, preventing the second comparison from being performed when unnecessary. Although bothoneandtwoare already computed, the second relational check (two > total - two) is avoided when the first condition succeeds. - Single pass for total: The overall sum is computed once at the beginning, avoiding repeated full traversals of the list for each partial sum. Subsequent calculations reuse this pre-computed
totalvalue.
Collectively, these choices keep the runtime linear in the size of nums while maintaining a low memory footprint. The method’s compact structure makes it straightforward to read and reason about, reflecting a clear mapping from the problem statement to the implemented logic.
ELI5 - Simplified Explanation
Imagine having a big pile of number cards. Some cards have small numbers written on them, like single digits from zero to nine, and other cards have bigger numbers that are two digits long, like ten or higher.
The first step is to add up every single number in the whole pile to see the grand total. After that, look through the pile to find all the small cards and add those up together. Next, look through the pile again to find all the two-digit cards and add those up together as well.
The goal is to see if one group of cards is stronger than all the other cards put together. If the pile of small cards is bigger than the rest of the pile, or if the pile of two-digit cards is bigger than the rest of the pile, that marks a special win. It is just like checking if one side of a scale is heavier than the other side after sorting the cards by their size.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||
|---|---|---|---|---|---|---|---|
| author | solutions | ||||||
| www | AlgoMonster | Java | C++ | Python | TS | ||
| WalkCCC | Java | C++ | Python | ||||
| leetcode.ca | Java | C++ | Go | Python | TS | ||
| Progiez | Java | C++ | Python | ||||
| github | charles-wangkai | Java | |||||
| everthis | JS | ||||||
| fsq | C++ | ||||||
| varunu28 | Java | ||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||
| WalkCCC | C++, Python, Java | ||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||
| Progiez | C++, Java, Python | ||||||
| charles-wangkai | Java | ||||||
| everthis | JavaScript | ||||||
| fsq | C++ | ||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 1295: Find Numbers with Even Number of Digits
- problem 2180: Count Integers With Even Digit Sum
Solved On The Same Day
- problem 3220: Odd and Even Transactions
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality