Longest Common Subsequence Length
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
You are given two strings, text1 and text2. Compute and return the length of the longest string that occurs as a subsequence in both inputs. When the two strings share no characters at all, return 0.
Deleting zero or more characters from a string—while leaving the remaining characters in their original left-to-right order—produces a subsequence. Kept characters do not have to sit adjacent to one another in the source string; for instance, "grn" is a subsequence of "garden", whereas "gnr" is not because 'n' appears after 'r'.
def longest_common_subsequence(text1: str, text2: str) -> int:
Examples
Example 1
- Input:
text1 = "track",text2 = "taco" - Output:
3 - Explanation: Keeping
't','a', and'c'in order produces"tac", which appears as a subsequence in both"track"(t–r–a–c–k) and"taco"(t–a–c–o). No four-character subsequence is shared, so the answer is3.
Example 2
- Input:
text1 = "drum",text2 = "drum" - Output:
4 - Explanation: Because both strings are identical, keeping every character yields
"drum"of length4.
Example 3
- Input:
text1 = "lynx",text2 = "code" - Output:
0 - Explanation: The two strings have no letters in common, so no non-empty subsequence exists in both.
Constraints
1 <= len(text1), len(text2) <= 1000- Both
text1andtext2contain only lowercase English letters ('a'through'z').
Step-by-step walkthrough
Understand the goal and subsequence rule
Given two strings
text1(lengthrows) andtext2(lengthcols), each between1and1,000lowercase letters long, we want the length of the longest string that appears as a subsequence in both, or0if they share no characters at all.A subsequence deletes zero or more characters without changing the left-to-right order of the ones kept:
"garden" --> keep 'g', skip "a", keep 'r', skip "de", keep 'n' --> "grn" (valid subsequence) "garden" --> "gnr" is NOT a subsequence because 'n' comes after 'r' in "garden"Notice that we only need to return the maximum matching length, not reconstruct the string itself.
Why brute force and greedy matching both fail
- Brute force is exponential: A string of length
nhas2^nsubsequences because each character can independently be kept or skipped. Checking all of them works on tiny strings up to length8, whereas forn = 1,000,2^1000is astronomically large. - Greedy matching gets trapped: What if we scan
text1from left to right and greedily match each letter to its earliest available copy intext2? Look at"xaaa"and"aaax":
Greedy grabs 'x' first: [x]aaa vs aaa[x] --> length 1 (nothing left after 'x' in text2!) Optimal skips 'x': x[aaa] vs [aaa]x --> length 3 ("aaa")Because matching one early letter can block many better matches later, we need a systematic way to compare keeping versus skipping without repeating the same subproblems.
- Brute force is exponential: A string of length
Break the problem down at the last characters
Consider any pair of prefixes: the first
icharacterstext1[:i]and the firstjcharacterstext2[:j]. Look at their final characters,char1 = text1[i - 1]andchar2 = text2[j - 1]:- Case 1 —
char1 == char2(they match): Pair these two final characters together! Any common subsequence oftext1[:i]andtext2[:j]can use at most one character from the end of each prefix, so matchingchar1withchar2leaves the largest possible earlier prefixestext1[:i - 1]andtext2[:j - 1]completely free. That gives1 + dp[i - 1][j - 1]. - Case 2 —
char1 != char2(they differ): A common subsequence cannot end with two different characters at the same time, so at least one ofchar1orchar2goes unused. We compare droppingchar1(dp[i - 1][j]) against droppingchar2(dp[i][j - 1]) and keep whichever is larger. - Base case (
i == 0orj == 0): An empty prefix shares0characters with any string.
col j - 1 col j +-----------------+-----------------+ row i-1 | dp[i - 1][j - 1]| dp[i - 1][j] | | (diagonal: +1 | (drop char1) | | when equal) | | +-----------------+-----------------+ row i | dp[i][j - 1] | dp[i][j] | | (drop char2) | (current cell) | +-----------------+-----------------+- Case 1 —
Build the 2D table bottom-up
Plain recursion on
(i, j)would solve the exact same prefix pairs over and over. Sinceiranges from0torowsandjranges from0tocols, there are only(rows + 1) * (cols + 1)distinct states — at most1,001 * 1,001(about one million integers), which runs fast and fits comfortably in memory.We allocate a 2D list
dpof zeros withrows + 1rows andcols + 1columns:- Row
0and column0represent the empty prefix"", so their initial0s already hold every base case. - Filling
ifrom1torowsandjfrom1tocolsguaranteesdp[i - 1][j - 1],dp[i - 1][j], anddp[i][j - 1]are already computed when we filldp[i][j]. - Watch the 1-based vs. 0-based index shift: row
irepresents a prefix of lengthi, whose final character sits at string indexi - 1.
rows = len(text1) cols = len(text2) dp = [[0] * (cols + 1) for _ in range(rows + 1)] for i in range(1, rows + 1): char1 = text1[i - 1] for j in range(1, cols + 1): char2 = text2[j - 1] if char1 == char2: dp[i][j] = dp[i - 1][j - 1] + 1 else: best_skip_text1 = dp[i - 1][j] best_skip_text2 = dp[i][j - 1] dp[i][j] = max(best_skip_text1, best_skip_text2)- Row
Trace Example 1 cell by cell
Let's fill
dpfortext1 = "track"(rows = 5) andtext2 = "taco"(cols = 4):"" t a c o (j = 0..4) "" 0 0 0 0 0 t 0 [1] 1 1 1 <-- i=1, j=1: 't' == 't', diagonal 0 + 1 = 1 r 0 1 1 1 1 <-- i=2: 'r' matches nothing, copies max(top, left) a 0 1 [2] 2 2 <-- i=3, j=2: 'a' == 'a', diagonal 1 + 1 = 2 c 0 1 2 [3] 3 <-- i=4, j=3: 'c' == 'c', diagonal 2 + 1 = 3 k 0 1 2 3 3 <-- i=5: 'k' matches nothing, carries 3 downReading the bottom-right corner
dp[5][4]gives3(corresponding to"tac").Looking ahead: why only the previous row is needed
Look back at the
2 x 2window diagram: computing rowionly ever reads values from rowi - 1(dp[i - 1][j - 1]anddp[i - 1][j]) and the current rowi(dp[i][j - 1]). Rows0throughi - 2are never read again:row i - 2: [ . . . . ] <-- never read again once row i - 1 is done row i - 1: [ . D T . ] <-- only the diagonal (D) and top (T) come from here row i: [ . L ? . ] <-- left (L) comes from the row being builtFor
len <= 1,000, keeping the full 2Ddpgrid is clean, readable, and makes follow-up string reconstruction easy. If an interviewer asks to cut memory fromO(rows * cols)down toO(min(rows, cols)), you can keep just two 1D lists (prev_rowandcurr_row) over the shorter string.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def longest_common_subsequence(text1: str, text2: str) -> int: rows = len(text1) cols = len(text2) # dp: (rows + 1) x (cols + 1) grid where dp[i][j] stores the LCS length of # prefixes text1[:i] and text2[:j]; row 0 and col 0 stay 0 for empty prefixes. dp = [[0] * (cols + 1) for _ in range(rows + 1)] # Fill row by row so top, left, and top-left cells are already computed. for i in range(1, rows + 1): char1 = text1[i - 1] # 1-based prefix length i maps to 0-based index i - 1 for j in range(1, cols + 1): char2 = text2[j - 1] if char1 == char2: # Matching end characters extend the best match before both characters. dp[i][j] = dp[i - 1][j - 1] + 1 else: # Both end characters cannot appear together; skip one and keep the larger result. best_skip_text1 = dp[i - 1][j] best_skip_text2 = dp[i][j - 1] dp[i][j] = max(best_skip_text1, best_skip_text2) return dp[rows][cols]✅ Submit now — all tests should pass.
Intuition & how it works
Imagine lining up two playlists (text1 and text2) and crossing out songs from either list until the remaining songs match in the exact same order; we want to keep as many songs as possible. A subsequence is any string formed by deleting zero or more characters without changing the left-to-right order of what stays (unlike a substring, which requires kept characters to sit right next to each other with no gaps).
Checking every possible subsequence of text1 against text2 tries 2^n combinations, which becomes impossibly slow past length 25 or 30. Trying a greedy shortcut—matching each character of text1 to its earliest occurrence in text2—also fails: on "xaaa" and "aaax", greedily matching 'x' jumps to the very end of "aaax" and returns 1, missing "aaa" of length 3.
Instead, we solve smaller prefix puzzles (a prefix text[:i] is the first i characters of text). Because exploring both "skip from text1" and "skip from text2" visits the exact same (i, j) pairs repeatedly—a property called overlapping subproblems—we use dynamic programming (DP), a technique that solves each unique subproblem once and stores its answer in a table. For cell dp[i][j] (comparing text1[:i] and text2[:j]):
- If
text1[i - 1] == text2[j - 1], those matching end letters extend the best answer before them:dp[i][j] = dp[i - 1][j - 1] + 1. - Otherwise, they cannot both end a common subsequence, so we drop one letter and keep the better option:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]).
Walk through text1 = "tan" and text2 = "tn":
- Initialize a
4 x 3grid of zeros; row0and column0stand for"". - Row
1('t'vs"tn"):'t' == 't'givesdp[1][1] = 0 + 1 = 1;'t' != 'n'givesdp[1][2] = max(0, 1) = 1. - Row
2('a'vs"tn"):'a'matches neither't'nor'n', so row2carries[0, 1, 1]down viamax(top, left). - Row
3('n'vs"tn"):'n' != 't'keepsdp[3][1] = 1;'n' == 'n'adds1to the diagonaldp[2][1] = 1, givingdp[3][2] = 2(for"tn").
Complexity
Let n = len(text1) and m = len(text2).
- Time:
O(n * m). Two nested loops visit each of then * minterior cells ofdponce, doing a single character comparison andO(1)table lookups per cell. - Space:
O(n * m). The 2D tabledpallocates(n + 1) * (m + 1)integers. If only the length is needed and memory is tight, keeping just the previous and current rows reduces extra space toO(min(n, m)).
Edge cases
- No shared characters (
"lynx","code"): The match branch never triggers, so0propagates through the entire table and returns0. - Identical strings (
"drum","drum"): Every main-diagonal celldp[i][i]matches and adds1, returninglen(text1). - One string is already a subsequence of the other (
"axbycz","abc"): Returnslen(shorter)regardless of which string is passed first. - Repeated characters (
"aaaa","aa"->2): Advancing from(i - 1, j - 1)consumes one index from each string per match, preventing a single'a'from matching multiple'a's. - Empty string (
"","drum"): The outer or inner loop runs zero times anddp[0][m]cleanly returns0. - Ties between multiple longest subsequences (
"abcbdab","bdcaba"): Both"bcba"and"bdab"have length4;max(...)preserves the shared optimal length4without ambiguity.
Common mistakes
- Off-by-one string indexing: Because
dphas an extra leading row and column for"", rowicorresponds totext1[i - 1], nottext1[i]. - Using
[[0] * (cols + 1)] * (rows + 1)to create the grid: That Python shorthand aliases every row to the same list object in memory, corrupting earlier rows as you write. Always use a list comprehension[[0] * (cols + 1) for _ in range(rows + 1)]. - Adding
dp[i - 1][j - 1] + 1on a mismatch or takingdp[i - 1][j - 1]instead ofmax(dp[i - 1][j], dp[i][j - 1]): Dropping only one end character ((i - 1, j)or(i, j - 1)) can preserve a match that dropping both ((i - 1, j - 1)) would throw away. - Resetting
dp[i][j] = 0on a mismatch: Resetting to0solves Longest Common Substring (contiguous characters), whereas a subsequence carries forward previous matches across gaps.
Alternative approaches
- Top-down recursion with memoization: Memoization caches the return value of a recursive helper
solve(i, j)in a dictionary or@lru_cacheso repeated calls return inO(1). It shares theO(n * m)time and space bounds, though in Python strings of length1000can reach recursion depthn + m = 2000and hit Python's default recursion limit unless raised. - Rolling two-row array: Keeping only
prev_rowandcurr_rowof lengthmin(n, m) + 1achieves the sameO(n * m)runtime inO(min(n, m))memory, as shown in the follow-ups below.
Follow-up questions
- How can you recover an actual longest common subsequence string rather than only computing its length? Keep the full
(n + 1) x (m + 1)dptable and walk backward from(i, j) = (n, m)untili == 0orj == 0. Whenevertext1[i - 1] == text2[j - 1], that character belongs to an optimal match, so append it to a list and step diagonally to(i - 1, j - 1); otherwise step to whichever neighbor(i - 1, j)or(i, j - 1)holds the largerdpvalue, and finally reverse the collected characters inO(n + m)extra time. - How would you reduce the auxiliary memory usage from O(N * M) down to O(min(N, M))? Swap
text1andtext2up front wheneverlen(text2) > len(text1)socols = min(N, M), and observe that filling rowionly reads entries from rowi - 1(prev_row[j - 1]andprev_row[j]) plus the row currently being built (curr_row[j - 1]). Keeping justprev_rowandcurr_rowof lengthmin(N, M) + 1preservesO(N * M)time while shrinking extra memory toO(min(N, M))(with the trade-off that recovering the string itself then requires either retaining the full grid or applying Hirschberg's algorithm, a divide-and-conquer technique that finds the midpoint of the optimal path using forward and backward rolling-row sweeps before recursing on the two halves). - What changes in the recurrence if the problem asks for the longest common contiguous substring instead of a subsequence? Redefine
dp[i][j]as the length of the longest shared contiguous block that ends right attext1[i - 1]andtext2[j - 1]. Whentext1[i - 1] == text2[j - 1], setdp[i][j] = dp[i - 1][j - 1] + 1, and on any mismatch resetdp[i][j] = 0because a gap breaks contiguity; the final answer is the maximum entry anywhere indprather thandp[n][m].
Follow-up questions
- How can you recover an actual longest common subsequence string rather than only computing its length?
- How would you reduce the auxiliary memory usage from O(N * M) down to O(min(N, M))?
- What changes in the recurrence if the problem asks for the longest common contiguous substring instead of a subsequence?
Similar questions
- Real-Time Bidding Ad Exchange at 1M QPS
- Global Video-on-Demand Streaming Platform
- Decomposing Squared Prediction Error into Bias and Variance
- Communicating Bias-Variance Tradeoffs to Business Leaders
- Java Concurrent Maps, Cache Partitioning, and Batch Joins
- Causal Engagement Lift from Optional Speaker Adoption
More Roku interview questions
- Real-Time Bidding Ad Exchange at 1M QPS Medium
- Global Video-on-Demand Streaming Platform Medium
- Communicating Bias-Variance Tradeoffs to Business Leaders Easy Pro
- Decomposing Squared Prediction Error into Bias and Variance Medium Pro
- Java Concurrent Maps, Cache Partitioning, and Batch Joins Medium Pro
- Causal Engagement Lift from Optional Speaker Adoption Medium Pro
- Rolling 7-Day Gross Profit by Category Medium Pro