Python 1403.py
class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
total = sum(nums)
nums.sort()
have = 0
while have <= total // 2:
have += nums[-1]
yield nums.pop()
Difficulty
and has an acceptance rate of about 74% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Sorting
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 class with a single method that extracts a subsequence of numbers from an input list. The goal of the method is to accumulate the largest elements until their sum exceeds half of the total sum of the original list. The method uses built-in aggregation, sorting, and a loop that progressively removes elements from the end of the sorted list while tracking the accumulated sum.
Key Steps and Corresponding Code
The method begins by calculating the total sum of the input collection.
total = sum(nums)
Sorting the list in ascending order prepares the data for efficient removal of the largest values.
nums.sort()
An accumulator variable is initialized to zero. This variable records the sum of the elements that have been selected so far.
have = 0
A loop runs while the accumulated sum does not exceed half of the total sum. Inside the loop, the largest remaining element (the last item in the sorted list) is added to the accumulator, and that element is removed from the list and yielded to the caller.
while have <= total // 2:
have += nums[-1]
yield nums.pop()
Edge Cases Handled
When the input list is empty, the initial sum is zero, the sorted list remains empty, and the loop condition have <= total // 2 evaluates to 0 <= 0. Because there is no element to pop, the loop body is never entered, resulting in an empty generator output.
If the list contains a single element, the total sum equals that element. The half-sum computed with integer division is either zero or the element itself, depending on its value. The loop will execute once, adding the sole element to the accumulator and yielding it, satisfying the condition that the selected subsequence’s sum exceeds half of the total.
When all elements are identical, the sorted order does not change the relative magnitude of any element. The loop continues to pop elements from the end until the accumulated sum surpasses half of the total, which naturally yields the minimal number of identical elements required to meet the condition.
For lists with very large integer values, the use of Python’s arbitrary-precision integers ensures that the sum and accumulator calculations remain accurate without overflow, allowing the loop to terminate correctly once the threshold is crossed.
Performance Optimizations Observed
The algorithm performs a single sort operation, which organizes the data in O(n log n) time and enables constant-time access to the largest element via indexing nums[-1]. By repeatedly using pop() on the end of the list, the removal of elements occurs in O(1) time per iteration, avoiding the overhead of shifting elements that would be incurred by popping from the front.
The loop condition leverages integer division (total // 2) to compute the threshold once, eliminating repeated floating-point division inside the loop. Accumulating the sum in the variable have avoids recomputing partial sums, ensuring that each iteration performs only a single addition and a single comparison.
Yielding elements as they are selected allows the caller to process the subsequence lazily, which can reduce memory pressure when the result is consumed incrementally rather than materialized all at once. This generator-style output aligns with Python’s iterator protocol and can be more efficient in scenarios where only a portion of the subsequence is needed.
ELI5 - Simplified Explanation
Imagine a box filled with numbered blocks. The goal is to pick some blocks so that the numbers on them add up to more than half of the total value of all the blocks in the box. To make this easy, the steps start by adding up all the numbers in the box to see what the halfway point is. Then, the blocks are lined up from the smallest number to the biggest number. Because the biggest numbers help reach the halfway point the fastest, the code looks at the very end of the line where the biggest block lives. It takes that block out, adds its number to a pile, and checks if that pile is already bigger than half of the total. If the pile is still too small, it keeps going back to the end of the line to grab the next biggest block until the pile is finally heavy enough.
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 | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | |||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2210: Count Hills and Valleys in an Array
Solved On The Same Day
- problem 1391: Check if There is a Valid Path in a Grid
- problem 1409: Queries on a Permutation With Key
- problem 1415: The k-th Lexicographical String of All Happy Strings of Length n
- problem 1471: The k Strongest Values in an Array
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