Problem 3232

Abstract / Summary

Given a string of digits, determine if the first player can win the digit game where players take turns picking numbers.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
6 lines | 262 bytes | submitted July 30, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 82% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 nums is empty, total, one, and two all evaluate to zero. Both comparisons become 0 > 0, which is false, leading the method to return False. No exception is raised.
  • All elements below ten: In this scenario one equals total, making the expression one > total - one simplify to total > 0. If the total sum is positive, the method returns True; otherwise it returns False. The second term involving two is irrelevant because the first term already determines the outcome.
  • All elements of three digits or more: Neither generator expression captures any element, so both one and two remain zero. The return expression reduces to 0 > total for both sides, which is false, yielding False.
  • Mixed sign values: Negative numbers satisfy the n < 10 predicate and therefore contribute to one. 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 in two, 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 sum with generator expressions delegates the iteration to CPython’s optimized C loops, reducing overhead compared with explicit Python for loops.
  • Lazy evaluation: Generator expressions produce values on the fly without constructing intermediate lists, conserving memory especially for large input arrays.
  • Short-circuit logic: The or operator stops evaluation after the first true condition, preventing the second comparison from being performed when unnecessary. Although both one and two are 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 total value.

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.04 | σ = 1.50

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
19 links | 8 authors | 6 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

1 medium
2 solutions   July 30, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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