Problem 1403

Abstract / Summary

Given a list of numbers, pick the smallest set in non-increasing order so their sum is at least half the total sum of all numbers.

Note

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

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()
9 lines | 241 bytes | submitted January 10, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Sorting
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 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.

written by openai gpt

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.

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 = 5 | μ = 4.85 | σ = 2.10

Complexity Analysis

Time: loglinear
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 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
28 links | 16 authors | 10 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

5 solutions   January 10, 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