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 is 3.

Example 2

  • Input: text1 = "drum", text2 = "drum"
  • Output: 4
  • Explanation: Because both strings are identical, keeping every character yields "drum" of length 4.

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 text1 and text2 contain only lowercase English letters ('a' through 'z').

Step-by-step walkthrough

  1. Understand the goal and subsequence rule

    Given two strings text1 (length rows) and text2 (length cols), each between 1 and 1,000 lowercase letters long, we want the length of the longest string that appears as a subsequence in both, or 0 if 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.

  2. Why brute force and greedy matching both fail

    • Brute force is exponential: A string of length n has 2^n subsequences because each character can independently be kept or skipped. Checking all of them works on tiny strings up to length 8, whereas for n = 1,000, 2^1000 is astronomically large.
    • Greedy matching gets trapped: What if we scan text1 from left to right and greedily match each letter to its earliest available copy in text2? 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.

  3. Break the problem down at the last characters

    Consider any pair of prefixes: the first i characters text1[:i] and the first j characters text2[:j]. Look at their final characters, char1 = text1[i - 1] and char2 = text2[j - 1]:

    1. Case 1 — char1 == char2 (they match): Pair these two final characters together! Any common subsequence of text1[:i] and text2[:j] can use at most one character from the end of each prefix, so matching char1 with char2 leaves the largest possible earlier prefixes text1[:i - 1] and text2[:j - 1] completely free. That gives 1 + dp[i - 1][j - 1].
    2. Case 2 — char1 != char2 (they differ): A common subsequence cannot end with two different characters at the same time, so at least one of char1 or char2 goes unused. We compare dropping char1 (dp[i - 1][j]) against dropping char2 (dp[i][j - 1]) and keep whichever is larger.
    3. Base case (i == 0 or j == 0): An empty prefix shares 0 characters 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)  |
             +-----------------+-----------------+
    
  4. Build the 2D table bottom-up

    Plain recursion on (i, j) would solve the exact same prefix pairs over and over. Since i ranges from 0 to rows and j ranges from 0 to cols, there are only (rows + 1) * (cols + 1) distinct states — at most 1,001 * 1,001 (about one million integers), which runs fast and fits comfortably in memory.

    We allocate a 2D list dp of zeros with rows + 1 rows and cols + 1 columns:

    • Row 0 and column 0 represent the empty prefix "", so their initial 0s already hold every base case.
    • Filling i from 1 to rows and j from 1 to cols guarantees dp[i - 1][j - 1], dp[i - 1][j], and dp[i][j - 1] are already computed when we fill dp[i][j].
    • Watch the 1-based vs. 0-based index shift: row i represents a prefix of length i, whose final character sits at string index i - 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)
    
  5. Trace Example 1 cell by cell

    Let's fill dp for text1 = "track" (rows = 5) and text2 = "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 down
    

    Reading the bottom-right corner dp[5][4] gives 3 (corresponding to "tac").

  6. Looking ahead: why only the previous row is needed

    Look back at the 2 x 2 window diagram: computing row i only ever reads values from row i - 1 (dp[i - 1][j - 1] and dp[i - 1][j]) and the current row i (dp[i][j - 1]). Rows 0 through i - 2 are 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 built
    

    For len <= 1,000, keeping the full 2D dp grid is clean, readable, and makes follow-up string reconstruction easy. If an interviewer asks to cut memory from O(rows * cols) down to O(min(rows, cols)), you can keep just two 1D lists (prev_row and curr_row) over the shorter string.

  7. 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":

  1. Initialize a 4 x 3 grid of zeros; row 0 and column 0 stand for "".
  2. Row 1 ('t' vs "tn"): 't' == 't' gives dp[1][1] = 0 + 1 = 1; 't' != 'n' gives dp[1][2] = max(0, 1) = 1.
  3. Row 2 ('a' vs "tn"): 'a' matches neither 't' nor 'n', so row 2 carries [0, 1, 1] down via max(top, left).
  4. Row 3 ('n' vs "tn"): 'n' != 't' keeps dp[3][1] = 1; 'n' == 'n' adds 1 to the diagonal dp[2][1] = 1, giving dp[3][2] = 2 (for "tn").

Complexity

Let n = len(text1) and m = len(text2).

  • Time: O(n * m). Two nested loops visit each of the n * m interior cells of dp once, doing a single character comparison and O(1) table lookups per cell.
  • Space: O(n * m). The 2D table dp allocates (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 to O(min(n, m)).

Edge cases

  • No shared characters ("lynx", "code"): The match branch never triggers, so 0 propagates through the entire table and returns 0.
  • Identical strings ("drum", "drum"): Every main-diagonal cell dp[i][i] matches and adds 1, returning len(text1).
  • One string is already a subsequence of the other ("axbycz", "abc"): Returns len(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 and dp[0][m] cleanly returns 0.
  • Ties between multiple longest subsequences ("abcbdab", "bdcaba"): Both "bcba" and "bdab" have length 4; max(...) preserves the shared optimal length 4 without ambiguity.

Common mistakes

  • Off-by-one string indexing: Because dp has an extra leading row and column for "", row i corresponds to text1[i - 1], not text1[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] + 1 on a mismatch or taking dp[i - 1][j - 1] instead of max(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] = 0 on a mismatch: Resetting to 0 solves 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_cache so repeated calls return in O(1). It shares the O(n * m) time and space bounds, though in Python strings of length 1000 can reach recursion depth n + m = 2000 and hit Python's default recursion limit unless raised.
  • Rolling two-row array: Keeping only prev_row and curr_row of length min(n, m) + 1 achieves the same O(n * m) runtime in O(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) dp table and walk backward from (i, j) = (n, m) until i == 0 or j == 0. Whenever text1[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 larger dp value, and finally reverse the collected characters in O(n + m) extra time.
  • How would you reduce the auxiliary memory usage from O(N * M) down to O(min(N, M))? Swap text1 and text2 up front whenever len(text2) > len(text1) so cols = min(N, M), and observe that filling row i only reads entries from row i - 1 (prev_row[j - 1] and prev_row[j]) plus the row currently being built (curr_row[j - 1]). Keeping just prev_row and curr_row of length min(N, M) + 1 preserves O(N * M) time while shrinking extra memory to O(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 at text1[i - 1] and text2[j - 1]. When text1[i - 1] == text2[j - 1], set dp[i][j] = dp[i - 1][j - 1] + 1, and on any mismatch reset dp[i][j] = 0 because a gap breaks contiguity; the final answer is the maximum entry anywhere in dp rather than dp[n][m].

Follow-up questions

Similar questions

More Roku interview questions

All 8 Roku questions →