A2Z Lesson

Log in
← Back to the A2Z sheet

Step 07 Recursion — Subsequence Pattern Problems

Learn All Patterns of Subsequences (Theory)

Theory

Almost every recursion problem in this module — subsets, combination sums, subsequences with sum K — is built on one pattern: at each element you branch into 'pick it' or 'skip it'. This lesson pins down the vocabulary (subsequence vs substring vs subset) and that pick / not-pick recursion pattern, including how to attach conditions like a target sum and how to reason about its 2^n cost.

Subsequence vs substring vs subset

Given a sequence, a subsequence keeps some elements in their original relative order, possibly skipping others. A substring is stricter: the elements must be contiguous. A subset ignores order entirely — it is just a set of chosen elements.

For [1, 2, 3]: subsequences include [1, 3], [2], [1, 2, 3] and the empty sequence — 8 in total. Substrings (contiguous) are only [1], [2], [3], [1, 2], [2, 3], [1, 2, 3] — 6. For an array of n elements there are exactly 2^n subsequences (each element is independently in or out), but only n(n+1)/2 substrings/subarrays. That 2^n is why subsequence problems are exponential by nature and why n is usually small (or why DP enters the picture later).

The pick / not-pick pattern

Write a recursive function f(index, current) that decides the fate of elements from index to the end. At each call you branch twice: once taking arr[index] into current, once leaving it out. When index reaches n, current is one complete subsequence — record it.

The recursion tree has two children per node and depth n, so it has 2^n leaves — one per subsequence. Discipline matters: append the element, recurse, then pop it (backtracking), so a single shared list is reused instead of copying lists at every call.

def subsequences(arr): n = len(arr) result = [] current = [] def dfs(i): if i == n: result.append(list(current)) return current.append(arr[i]) # pick arr[i] dfs(i + 1) current.pop() # undo, then skip arr[i] dfs(i + 1) dfs(0) return result

Attaching a condition: sum K

Most problems add a filter. Three standard variants appear in this module:

Existence — 'is there a subsequence with sum K?' Carry the running sum as a parameter. The moment sum == K at a leaf, return True and let it propagate up immediately; the early exit prunes the rest of the tree, so the best case is far below 2^n.

Counting — 'how many subsequences sum to K?' Return 1 at a successful leaf and 0 otherwise; each internal node returns left + right. No early exit is possible because every branch contributes.

Printing one — keep a flag or return the found subsequence up the chain instead of collecting all of them.

Passing the sum (or remaining target) down as a parameter, instead of recomputing it from current each time, keeps each call O(1).

def count_subseq_with_sum(arr, k): n = len(arr) def dfs(i, remaining): if i == n: return 1 if remaining == 0 else 0 pick = dfs(i + 1, remaining - arr[i]) skip = dfs(i + 1, remaining) return pick + skip return dfs(0, k)

Duplicates and pruning

If the array has duplicate values, plain pick / not-pick generates duplicate subsets. The standard fix for subset-style problems: sort the array first, and at each level skip a value if the same value was just skipped at that level (the 'skip duplicates in the not-pick branch' rule used in Subsets II and Combination Sum II).

Pruning cuts work when the condition allows it: if all numbers are positive and the running sum already exceeds K, the pick branch can be abandoned. With negatives present, no such prune is valid — a later negative could bring the sum back down. Recognising which prunes are legal for the given constraints is the difference between a solution that passes and one that times out.

Complexity and common mistakes

Generating all subsequences costs O(2^n * n) time (2^n leaves, up to n work to copy each result) and O(n) recursion depth. Counting variants are O(2^n) time. This is only feasible for n up to roughly 20-25; beyond that, the problem is secretly a DP problem (subset-sum DP) or needs meet-in-the-middle.

Common mistakes: forgetting the empty subsequence is a valid leaf result; mutating a shared list without popping after the pick branch, which corrupts sibling branches; recomputing the sum of current at every node (O(n) per node) instead of passing it as a parameter; and, in duplicate problems, deduplicating with a set of tuples at the end — it works but explodes memory compared with the sort-and-skip rule.

Key points

  • A subsequence preserves order but may skip elements; an array of size n has exactly 2^n subsequences, including the empty one.
  • Pick / not-pick recursion: branch on taking arr[index] or skipping it, append-pop to reuse one list.
  • Existence problems can early-exit on the first success; counting problems must explore the whole tree and sum left + right.
  • Duplicates are handled by sorting first and skipping equal values in the skip branch at each level.
  • Cost is O(2^n) leaves — fine for n <= ~22; larger n signals DP or meet-in-the-middle instead.

Suggested questions

Power Set ↗ Generate every subsequence/subset of a string or array — the pure pick / not-pick pattern.
Check if there exists a subsequence with sum K ↗ The existence variant — practise the early-exit version of the recursion.
Count all subsequences with sum K ↗ The counting variant — return left + right with no early exit.
Subsets I ↗ All subsets with sum variations; warm up before tackling duplicates.
Subsets II ↗ Adds duplicate values — apply the sort-and-skip rule from this lesson.

Source note: this lesson follows the structure of Striver's public A2Z DSA course (takeUforward). Each problem links to its original platform, and all problems and content belong to their respective owners — STUDY-BUDDY does not claim ownership of the sheet or its problems, and no permission beyond public linking is claimed.