Longest Common Subsequence
A medium Dynamic Programming problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Dynamic Programming
- Sheets
- 3
- Core for
- 9 roles
- Platform
- LeetCode
The problem
Given two strings, return the length of their longest common subsequence. A subsequence is a sequence that appears in the same relative order but not necessarily contiguous.
Example 1
- Input
- text1 = "abcde", text2 = "ace"
- Output
- 3
- Why
- The longest common subsequence is "ace", length 3.
Example 2
- Input
- text1 = "abc", text2 = "abc"
- Output
- 3
- Why
- The strings are identical, so the longest common subsequence is the full string.
Example 3
- Input
- text1 = "abc", text2 = "def"
- Output
- 0
- Why
- There is no common subsequence, so the result is 0.
Constraints
- 1 <= text1.length, text2.length <= 1000
- text1 and text2 consist of lowercase English letters
How to think about it
Updated 2026-09-09Looking at the final character of both prefixes reveals a strict choice: if they match, they must belong to an optimal subsequence extending whatever came before; if they differ, at least one of them is useless for this specific step, so drop one and take the better outcome.
Approaches, worst first
Naive branching
time O(2^(m+n)) · space O(m + n)
Recurse on string prefixes. When characters match, advance both pointers. When they differ, branch into dropping the character from the first string or the second. Recomputes overlapping string pairs exponentially.
2D dynamic programming grid
time O(m * n) · space O(m * n)
Construct an (m+1) x (n+1) matrix where dp[i][j] stores the LCS length for text1[0..i-1] and text2[0..j-1]. Fill row by row using matching characters as diagonal steps (+1) and mismatches as max(up, left).
Space-optimized rolling rowsWrite this one
time O(m * n) · space O(min(m, n))
Notice that computing the current row only depends on the previous row. Keep two rows (or one row with a temporary diagonal tracker) to reduce memory down to a single row.
Where people lose marks · 3
- Off-by-one errors when mapping 1-indexed DP cells to 0-indexed string characters. Cell dp[i][j] inspects text1[i-1] and text2[j-1].
- When characters match, adding 1 to max(dp[i-1][j], dp[i][j-1]) instead of dp[i-1][j-1]. Matching both characters consumes them both simultaneously.
- Swapping row dimensions during 1D optimization without ensuring the inner loop allocates for the shorter string, which wastes cache lines and space.
Full solution
Space-optimized rolling rows: the 2D LCS grid only ever needs the previous row, so two rows (rolled into one variable swap) replace the full O(m*n) matrix.
Python
def longest_common_subsequence(text1: str, text2: str) -> int:
# Keep the shorter string along the row so the rolling array stays small.
if len(text1) < len(text2):
text1, text2 = text2, text1
prev = [0] * (len(text2) + 1)
for i in range(1, len(text1) + 1):
curr = [0] * (len(text2) + 1)
for j in range(1, len(text2) + 1):
if text1[i - 1] == text2[j - 1]:
curr[j] = prev[j - 1] + 1
else:
curr[j] = max(prev[j], curr[j - 1])
prev = curr
return prev[len(text2)]
JavaScript
function longestCommonSubsequence(text1, text2) {
if (text1.length < text2.length) {
[text1, text2] = [text2, text1];
}
let prev = new Array(text2.length + 1).fill(0);
for (let i = 1; i <= text1.length; i++) {
const curr = new Array(text2.length + 1).fill(0);
for (let j = 1; j <= text2.length; j++) {
if (text1[i - 1] === text2[j - 1]) {
curr[j] = prev[j - 1] + 1;
} else {
curr[j] = Math.max(prev[j], curr[j - 1]);
}
}
prev = curr;
}
return prev[text2.length];
}
The theory behind it
Dynamic Programming — the ground this problem stands on. All Dynamic Programming problems
What Dynamic Programming is
Dynamic programming is a method for solving a complex problem by breaking it into overlapping subproblems, solving each subproblem only once, and remembering the answers in a lookup table. Instead of recalculating identical questions over and over, future steps look up previous answers directly. By assembling these saved pieces from the bottom up or storing them during recursion, a task that would take billions of steps finishes in a fraction of a second.
When to reach for it
Reach for dynamic programming when questions ask for the maximum profit, minimum cost, total number of distinct ways to achieve a goal, or whether a target can be formed. Signals include overlapping choices where making a choice now affects what choices remain later, but greedy picking fails to find the true global optimum. If drawing a recursive decision tree reveals the same subproblem states repeating across branches, dynamic programming is needed.
How the pattern works
Identify the state variables that uniquely describe a subproblem, such as an array index and remaining capacity. Write the base cases first, representing states whose answers are known without calculation. Next, write the recurrence relation that expresses the current state using previously solved states, taking the minimum, maximum, or sum among your options. Build the solution either top-down by caching recursive returns in a memo table, or bottom-up by filling an array in topological dependency order. When each state depends only on the previous row, compress storage down to a single array.
What each operation costs
| Operation | Time |
|---|---|
| fill dynamic programming table of n states | O(n) |
| solve two-dimensional grid of m by n states | O(m * n) |
| space-optimized state transition keeping one row | O(n) |
What usually goes wrong with Dynamic Programming
- Filling a bottom-up table in an order where the current cell needs values that have not been computed yet, reading uninitialized zeros.
- Failing to initialize base cases properly, such as filling a minimization table with zeros instead of infinity, which traps the answer at zero.
- Overwriting values in a 1D space-optimized knapsack array by scanning in the wrong direction, allowing the same item to be chosen multiple times.
Which roles need this problem
Dynamic Programming is a core topic for these 9 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 5 more roles, including Game Developer, Cryptography Engineer, Performance Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Dynamic Programming problems
Problem set and role mapping as of .