Python Course · Advanced algorithms
Advanced Python Coding Interviews: Recursion and Optimization
Explore recursion, memoization and subset-sum optimization with a tested bounded Python solution.
Learn the pattern, trace runnable code, and test an edge case.
Core idea
The state definition decides whether repeated work can be removed.
Prove transition
Bound memory
The direct answer
Optimize repeated states only after defining the state.
Recursion and backtracking are useful when a choice branches into smaller decisions. The difficulty is identifying repeated states and bounding work. This lesson solves a small subset-sum question, compares naive recursion with a reachable-sums method, and explains when memoization is appropriate.
The runnable example supports nonnegative integers and a nonnegative target. It was tested under Python 3.12.14, including empty input and invalid negative values. The synced course pricing block follows this introduction. Python’s functools documentation explains caching tools for suitable recursive state.
Course access
Choose your next step in Python.
Review the current course options and access details here.
Heycademy Courses · Coming Soon
Master Python with Heycademy
We’re preparing an interactive learning experience with practical exercises, skill assessments and personalized learning to help you build confidence and master new skills.
We’re putting the finishing touches on this course. Please check back for updates.
State and search tree
Name what a recursive call must know.
For subset sum, a state can be (position, remaining_target). At each position, choose to include the current value or skip it. The base cases are “remaining target is zero” (success) and “no values remain” (failure unless already zero). Repeated states arise when different paths reach the same position and remaining amount.
| Technique | Keeps | Typical tradeoff |
|---|---|---|
| Naive backtracking | Current path and recursion stack. | Can revisit equivalent states exponentially. |
| Memoized recursion | Result for each state. | Uses memory to avoid repeated work. |
| Reachable-sums iteration | Set of totals attainable so far. | May be simpler for nonnegative bounded target. |
Do not say all subset-sum inputs are easy. General subset sum is computationally difficult in terms of input bit length. The bounded nonnegative target permits a pseudopolynomial-style dynamic program whose cost depends on numeric target value.
Worked bounded example
Can 3, 7 and 11 make 10?
Input values [3, 7, 11], target 10. Begin with reachable total {0}. After 3: {0,3}. After 7: {0,3,7,10}. Since 10 is present, a subset exists: 3+7. After 11, values above target are not needed under the nonnegative assumption. A target of 9 remains unreachable.
| Processed | Reachable totals at or below 10 |
|---|---|
| Nothing | {0} |
| 3 | {0,3} |
| 3,7 | {0,3,7,10} |
| 3,7,11 | {0,3,7,10} |
The code uses a new set of additions per value, so the same input value is not accidentally reused multiple times in one step. That detail distinguishes 0/1 subset sum from unbounded coin change.
Tested solution
Keep totals within the stated bound.
def subset_sum(values, target):
"""Return True if a subset of nonnegative integers sums to target."""
if (not isinstance(target, int) or isinstance(target, bool) or target < 0
or any(not isinstance(value, int) or isinstance(value, bool) or value < 0
for value in values)):
raise ValueError("Only nonnegative integers are supported")
reachable = {0}
for value in values:
reachable |= {total + value for total in reachable if total + value <= target}
return target in reachableThe invariant is that reachable contains exactly the attainable totals not exceeding the target from processed values. The next value creates new totals by adding it once to the old reachable set. Because all values are nonnegative, discarding totals above the target is safe: later additions cannot bring them down.
assert subset_sum([3, 7, 11], 10) is True
assert subset_sum([3, 7, 11], 9) is False
assert subset_sum([], 0) is True
assert subset_sum([], 1) is FalseThe implementation intentionally rejects negative values. With negatives, pruning totals above the target can be incorrect because a later negative could reduce them.
Keep building this skill
Turn the example into a tested solution.
Return to the course options whenever you are ready.
What the bound costs
Separate n, target and input encoding.
At most target+1 distinct nonnegative totals can remain in the set. For n input values, the bounded approach uses O(n·target) work in this simplified integer model and O(target) state space. This is not polynomial in the number of bits needed to write a large target. For example, a target of one million is much larger as a numeric bound than its digit count suggests.
A memoized recursion over (index, remaining) can also avoid repeated states, but its recursion depth and memory behavior should be checked. Python has a recursion limit, so a deep input may need an iterative approach. Memoization is useful only when the same subproblem recurs and the state is hashable.
When a Boolean is not enough
Recover the chosen subset.
The current function returns only True or False. If the task asks for the actual subset, store a predecessor for each newly reached total or backtrack through decisions. Clarify how to handle multiple valid subsets: return any, shortest, lexicographically smallest, or all. The output requirement changes the state you must preserve.
If all combinations are requested, output size may itself be exponential. No amount of memoization can avoid writing exponentially many distinct results. State that limit before promising a fast algorithm.
Transfer check
Change one assumption and predict the effect.
Would the current code correctly handle [8, -3] for target 5? It raises ValueError by contract. If you removed the check but kept pruning totals over 5, it would discard 8 and miss the valid subset 8 + (-3). The nonnegative condition is therefore part of the proof, not an arbitrary input restriction.
What does empty input with target zero return?
True. The empty subset sums to zero; reachable begins as {0}. Empty input with a positive target returns False.
After this lesson, use a different recursive pattern from the 20-problem set and define its state before coding.
Memoization comparison
Cache a result for a complete state.
A recursive subset-sum helper can ask whether values from index i onward can reach a remaining total. A cache key must include both i and remaining total. Caching only the remaining total is unsound because different suffixes contain different available values. Caching only the index is unsound because the remaining target changes the answer. This is the general skill behind memoization: identify all variables that affect future choices.
Python’s cache documentation supports memoizing functions with hashable arguments. A cache can save repeated work but consumes memory; in a long-running application an unbounded cache needs an operating policy. In an interview, compare the bounded state count and recursion depth before choosing it over the iterative reachable-set solution.
A small recursive decision tree
Include or skip each value.
For values [3,7,11] and target 10, a recursive search at position 0 either includes 3, leaving 7, or skips 3, leaving 10. The include branch can then include 7 and reach zero: success. The skip branch explores different subsets. If the same (position, remaining target) is reached by multiple paths, memoization can reuse the answer. If the state differs in either coordinate, the future choices may differ and it should not share a cached result.
| State | Choice | Next state | Result |
|---|---|---|---|
| (0,10) | Include 3 | (1,7) | Can include 7. |
| (1,7) | Include 7 | (2,0) | Success. |
| (0,10) | Skip 3 | (1,10) | Other branch still possible. |
Base cases deserve explicit tests. Target zero is true even with no values because the empty subset sums to zero. Empty values and a positive target are false. A negative value is rejected by this bounded lesson’s contract. Once those boundaries are fixed, compare the recursive and iterative approaches on the same small input; both should agree before you argue about performance.
Recursion and memory constraints
Choose the form that fits the input size.
A recursive solution can be elegant on small inputs, but Python limits recursion depth. A deeply branching problem may also create many states even when each call is short. Memoization trades memory for fewer repeated computations. The iterative reachable-set method avoids Python call-stack depth, yet the set can still grow with the numeric target bound.
When discussing optimization, report the dimensions that drive cost: number of input values, target magnitude, number of distinct states and output size. Do not describe a pseudopolynomial target-bound method as simply “linear” without saying in what variable. If the interviewer asks for an actual subset rather than a Boolean, additional predecessor data is needed. That requirement changes memory and reconstruction work.
FAQ
Questions about this skill.
Is subset sum always polynomial?
No. This bounded nonnegative approach depends on the numeric target and is pseudopolynomial.
Why reject negative values?
The pruning rule would be unsound when later negatives could lower a total.
When should I use memoization?
When equivalent hashable states recur and the memory tradeoff is justified.
Continue with the course
Build reliable Python interview skills.
Review the course options and choose your next learning step.