Subset Sum Implementation in Python
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 in Python: what you actually reach for
Python implementation
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 FreeThe Python-specific trap
Performance in Python, beyond the O(n*S)
Real-World Applications
Interview Tips & Practice
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).
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 trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.