Subsequences are a fundamental concept in technical interviews, frequently appearing in problems involving strings and arrays. Unlike subarrays or substrings, which must be contiguous, a subsequence is formed by deleting zero or more elements from the original sequence while maintaining the relative order of the remaining elements. Because an array of size $N$ has $2^N$ possible subsequences, brute-force solutions quickly result in Time Limit Exceeded (TLE) errors. Dynamic Programming (DP) is the optimal way to reduce this exponential time complexity to polynomial time by caching overlapping subproblems.
When to use this pattern
Recognizing a subsequence DP problem is often the hardest part of an interview. Look for these strong signals in the problem description:
- Keywords: The problem explicitly asks for the "longest", "shortest", "maximum", or "number of ways" to form a sequence.
- Non-contiguous requirement: The problem allows skipping elements but strictly enforces that the original left-to-right order must be preserved.
- Multiple sequences: You are given two strings or arrays and asked to find commonalities (e.g., Longest Common Subsequence, Edit Distance).
| Feature | Subarray / Substring | Subsequence | Subset |
|---|---|---|---|
| Contiguous? | Yes | No | No |
| Order preserved? | Yes | Yes | No |
| Total combinations | $O(N^2)$ | $O(2^N)$ | $O(2^N)$ |
The core idea
The core of subsequence DP is decision making at each index. For every element in the sequence, you make a choice: do I include this element in my subsequence, or do I exclude it?
When dealing with two strings (a very common variation), the decision is based on whether the characters at the current pointers match. If they match, you usually include them and move both pointers. If they don't match, you explore two branches: skipping a character in the first string, or skipping a character in the second string.
Template
Most 2D subsequence problems (like comparing two strings) follow a standard grid-based DP template. We use a 2D array dp where dp[i][j] represents the answer for the prefix of the first string up to length i and the second string up to length j.
def subsequence_dp_template(s1: str, s2: str) -> int:
m, n = len(s1), len(s2)
# Initialize DP table with base cases (usually 0)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
# Characters match: extend the optimal solution of prefixes
dp[i][j] = dp[i - 1][j - 1] + 1
else:
# Characters don't match: take the best of excluding either character
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]Worked examples
1. Longest Common Subsequence (LCS)
Problem: Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
Approach: This is the textbook application of our template. We define dp[i][j] as the length of the LCS for text1[0...i-1] and text2[0...j-1]. If the characters match, we add 1 to the LCS of the remaining strings (dp[i-1][j-1]). If they don't match, we take the maximum of skipping a character in text1 or skipping a character in text2.
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m, n = len(text1), len(text2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if text1[i - 1] == text2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]Complexity:
- Time: $O(M \times N)$ where $M$ and $N$ are the lengths of the strings.
- Space: $O(M \times N)$ for the DP table. (Note: This can be optimized to $O(\min(M, N))$ by only keeping the previous row, which is a great optimization to mention in interviews!).
2. Longest Increasing Subsequence (LIS)
Problem: Given an integer array nums, return the length of the longest strictly increasing subsequence.
Approach: This is a 1D DP problem. We define dp[i] as the length of the longest increasing subsequence that strictly ends at index i. To calculate dp[i], we look at all previous indices j (where j < i). If nums[i] > nums[j], it means we can append nums[i] to the subsequence ending at j. We take the maximum length possible.
class Solution:
def lengthOfLIS(self, nums: list[int]) -> int:
if not nums:
return 0
n = len(nums)
dp = [1] * n # Every element is an increasing subsequence of length 1
for i in range(1, n):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)Complexity:
- Time: $O(N^2)$ because of the nested loops.
- Space: $O(N)$ for the DP array.
3. Distinct Subsequences
Problem: Given two strings s and t, return the number of distinct subsequences of s which equal t.
Approach: We define dp[i][j] as the number of ways to form the prefix t[0...j-1] using the prefix s[0...i-1].
- If
s[i-1] == t[j-1], we have two choices: we can use this character to matcht[j-1](which givesdp[i-1][j-1]ways), or we can choose NOT to use it and rely on previous characters ofs(which givesdp[i-1][j]ways). So,dp[i][j] = dp[i-1][j-1] + dp[i-1][j]. - If
s[i-1] != t[j-1], we cannot uses[i-1], so we must rely on previous characters:dp[i][j] = dp[i-1][j].
class Solution:
def numDistinct(self, s: str, t: str) -> int:
m, n = len(s), len(t)
# dp[i][j] = ways to form t[:j] from s[:i]
dp = [[0] * (n + 1) for _ in range(m + 1)]
# An empty string t can be formed from any prefix of s in exactly 1 way (by deleting all chars)
for i in range(m + 1):
dp[i][0] = 1
for i in range(1, m + 1):
for j in range(1, n + 1):
if s[i - 1] == t[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]
else:
dp[i][j] = dp[i - 1][j]
return dp[m][n]Complexity:
- Time: $O(M \times N)$
- Space: $O(M \times N)$
Variations and pitfalls
1. Space Optimization
In 2D DP problems like LCS or Distinct Subsequences, notice that dp[i][j] only ever depends on the current row i and the previous row i-1. This means you do not need to store the entire $M \times N$ matrix. You can reduce the space complexity to $O(N)$ by using two 1D arrays (one for the previous row and one for the current row). In some cases, a single 1D array is enough if you traverse it in reverse.
2. Reconstructing the Subsequence
Sometimes interviewers ask you to not just return the length of the LCS, but the actual string itself. You can do this by backtracking through your populated DP table. Start at dp[m][n]. If text1[i-1] == text2[j-1], that character is part of the LCS; append it and move to dp[i-1][j-1]. Otherwise, move in the direction of the maximum value (dp[i-1][j] or dp[i][j-1]). Finally, reverse the collected string.
3. Integer Overflow
In combinatorial problems like "Distinct Subsequences", the number of ways can grow exponentially. While LeetCode test cases usually fit within a 32-bit signed integer for the final answer, intermediate additions might overflow. In languages like C++ or Java, it's safer to use unsigned long long or long for the DP table to avoid runtime errors.
Practice checklist
To truly master this pattern, try solving these variations on your own:
- Edit Distance (very similar to LCS but with insert/delete/replace operations)
- Longest Palindromic Subsequence (Hint: LCS of the string and its reverse)
- Is Subsequence (A simpler two-pointer problem, but good for fundamentals)
Reviewing the Sliding Window Pattern is also highly recommended to ensure you don't confuse contiguous subarray problems with subsequence problems during a high-pressure interview.