Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Subset Sum Implementation in Python

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Subset Sum runs in O(n*S) time and O(n*S) space, in Python as in every other language.
  • ✓Nothing in the stdlib solves this for you; you build the row. Three real choices: a list[bool] rolling row; bytearray(S + 1), one byte per cell and far more cache-friendly; or the big-int bitset trick, since Python's int is arbitrary precision, so bits |= bits << x starting from bits = 1 marks every newly reachable sum in one operation and (bits >> S) & 1 reads the answer.
  • ✓Reviewers want the rolling 1-D row and the descending loop for s in range(target, x - 1, -1), with a comment stating why it descends (each item may be used once).
  • ✓The Python trap: Two traps that are Python's alone. First, [[False] * (S + 1)] * (n + 1) creates n+1 references to ONE list, so dp[i][s] = True writes every row at once.
  • ✓Each list[bool] cell is a pointer to the interned True/False singleton, so a row of 100k costs roughly 800 KB of pointers and every read is a dereference; bytearray is one byte per cell and streams through cache.

What Subset Sum actually is

Subset Sum asks: given n non-negative integers and a target S, is there a subset that adds to exactly S? The standard solution is a boolean DP over (items considered) x (0..S): reachable[s] is true when s can be formed from the items seen so far. Time O(n*S), space O(S) with a rolling row. That S in the bound is the value, not the input size, so this is pseudo-polynomial and only practical when S is small. Engineers reach for it in partitioning and load balancing, making change from fixed denominations, budget/knapsack feasibility checks, and as the canonical reduction target in NP-hardness proofs.

Subset Sum in Python: what you actually reach for

Nothing in the stdlib solves this for you; you build the row. Three real choices: a list[bool] rolling row; bytearray(S + 1), one byte per cell and far more cache-friendly; or the big-int bitset trick, since Python's int is arbitrary precision, so bits |= bits << x starting from bits = 1 marks every newly reachable sum in one operation and (bits >> S) & 1 reads the answer. functools.lru_cache over a recursive can(i, s) is the memoised alternative, and itertools.combinations brute force is only defensible for tiny n.

Python implementation

Reviewers want the rolling 1-D row and the descending loop for s in range(target, x - 1, -1), with a comment stating why it descends (each item may be used once). They reject dp = [[False] * (S + 1)] * (n + 1) on sight, reject building a Python set of all sums when S is dense, and expect an early continue for x > target plus an early return once dp[target] flips. Type hints (Sequence[int] -> bool) and a guard on negative input are standard.
python
from typing import Sequence


def subset_sum(nums: Sequence[int], target: int) -> bool:
    if target < 0:
        return False
    reachable = bytearray(target + 1)
    reachable[0] = 1
    for x in nums:
        if x <= 0 or x > target:
            continue
        for s in range(target, x - 1, -1):
            if reachable[s - x]:
                reachable[s] = 1
        if reachable[target]:
            return True
    return bool(reachable[target])


def subset_sum_bitset(nums: Sequence[int], target: int) -> bool:
    bits = 1
    mask = (1 << (target + 1)) - 1
    for x in nums:
        if 0 < x <= target:
            bits = (bits | (bits << x)) & mask
    return (bits >> target) & 1 == 1

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Python-specific trap

Two traps that are Python's alone. First, [[False] * (S + 1)] * (n + 1) creates n+1 references to ONE list, so dp[i][s] = True writes every row at once. Use a comprehension. Second, Python indexes negatively instead of raising, so dp[s - x] with s < x silently reads from the END of the row and reports a bogus True: no IndexError, no traceback, just a wrong answer that survives small test cases. The descending bound range(target, x - 1, -1) is precisely what keeps the index non-negative, which is why reviewers insist on that exact form rather than a guard inside the loop.

Performance in Python, beyond the O(n*S)

Each list[bool] cell is a pointer to the interned True/False singleton, so a row of 100k costs roughly 800 KB of pointers and every read is a dereference; bytearray is one byte per cell and streams through cache. The interpreter loop dominates everything else at about 50-100 ns per cell (measured near 95 ns for this bytearray sweep), so n*S near 1e8 takes roughly 5-10 seconds and 1e9 is where you cross into minutes. The big-int bitset moves the whole inner loop into CPython's C long shift/or, doing S/30 30-bit digits per item (CPython packs 30 value bits into each 32-bit digit), so the shift-or runs entirely in C over that digit array, and is routinely 50-200x faster at the identical O(n*S). The asymptotic cost is the same in every language, O(n*S) time and O(n*S) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Subset Sum between languages.

Real-World Applications

Subset Sum applies wherever its problem shape appears in your own code. In Python, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Subset Sum helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Subset Sum appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Subset Sum over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Subset Sum to build pattern recognition. In Python, demonstrate proficiency with list comprehensions and generator expressions to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Python code that is both correct and maintainable.

Frequently Asked Questions

Which Python type or library should I use for Subset Sum?

Nothing in the stdlib solves this for you; you build the row. Three real choices: a list[bool] rolling row; bytearray(S + 1), one byte per cell and far more cache-friendly; or the big-int bitset trick, since Python's int is arbitrary precision, so bits |= bits << x starting from bits = 1 marks every newly reachable sum in one operation and (bits >> S) & 1 reads the answer. functools.lru_cache over a recursive can(i, s) is the memoised alternative, and itertools.combinations brute force is only defensible for tiny n.

What is the most common Python mistake when implementing Subset Sum?

Two traps that are Python's alone. First, [[False] * (S + 1)] * (n + 1) creates n+1 references to ONE list, so dp[i][s] = True writes every row at once. Use a comprehension. Second, Python indexes negatively instead of raising, so dp[s - x] with s < x silently reads from the END of the row and reports a bogus True: no IndexError, no traceback, just a wrong answer that survives small test cases. The descending bound range(target, x - 1, -1) is precisely what keeps the index non-negative, which is why reviewers insist on that exact form rather than a guard inside the loop.

How does Subset Sum actually perform in Python?

Each list[bool] cell is a pointer to the interned True/False singleton, so a row of 100k costs roughly 800 KB of pointers and every read is a dereference; bytearray is one byte per cell and streams through cache. The interpreter loop dominates everything else at about 50-100 ns per cell (measured near 95 ns for this bytearray sweep), so n*S near 1e8 takes roughly 5-10 seconds and 1e9 is where you cross into minutes. The big-int bitset moves the whole inner loop into CPython's C long shift/or, doing S/30 30-bit digits per item (CPython packs 30 value bits into each 32-bit digit), so the shift-or runs entirely in C over that digit array, and is routinely 50-200x faster at the identical O(n*S). Time complexity is O(n*S) and space is O(n*S).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

If you are a student, see what Replit offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.