Taro Logo

Longest Common Subsequence

#195 Most AskedMedium
Topics:
StringsDynamic Programming

Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

  • For example, "ace" is a subsequence of "abcde".

A common subsequence of two strings is a subsequence that is common to both strings.

Example 1:

Input: text1 = "abcde", text2 = "ace" 
Output: 3  
Explanation: The longest common subsequence is "ace" and its length is 3.

Example 2:

Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.

Example 3:

Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no such common subsequence, so the result is 0.

Constraints:

  • 1 <= text1.length, text2.length <= 1000
  • text1 and text2 consist of only lowercase English characters.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of text1 and text2, and are we guaranteed that the inputs will only consist of lowercase English letters?
  2. How should we handle empty strings or inputs where there is no common subsequence; should it return 0?
  3. To confirm the definition, are we looking for a subsequence (where characters do not need to be contiguous) rather than a substring?
  4. If there are multiple longest common subsequences of the same maximum length, does the interviewer care which one is formed, or do we only need to return the integer length?
  5. Are we guaranteed that the memory available can support a 2D table of size $O(M \times N)$ where $M$ and $N$ are the lengths of the strings, or should I consider space-optimized approaches?

Brute Force Solution

Approach

Imagine you are given two secret messages and want to find the longest shared secret phrase hidden inside both, even if the matching letters have other letters scattered between them. The brute force strategy works by systematically writing down every single possible hidden combination of letters from the first message and checking each one to see if it also appears hiding somewhere inside the second message.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first letter of the first message.
  2. Create a list of every possible combination of letters you can make by picking letters from the first message while keeping them in their original order.
  3. Include combinations of all different lengths, starting from single letters all the way up to the entire message.
  4. Take the first combination from your list and search through the second message to see if those exact letters appear in that same order.
  5. Repeat this checking process for every single combination on your list.
  6. As you find combinations that successfully appear in both messages, keep track of them.
  7. Once you have checked every single possibility, look at the ones that worked and pick the one that has the most letters in it.

Code Implementation

def longest_common_subsequence(first_message, second_message):
    # Generate all subsequences recursively to explore every possible letter combination
    def generate_subsequences(message_slice):
        if not message_slice:
            return ['']
        subsequences_without = generate_subsequences(message_slice[1:])
        subsequences_with = [message_slice[0] + sub for sub in subsequences_without]
        return subsequences_without + subsequences_with

    all_combinations = generate_subsequences(first_message)
    longest_sequence_length = 0

    # Check every generated combination against the second message in original order
    for candidate_phrase in all_combinations:
        candidate_index = 0
        for current_letter in second_message:
            if candidate_index < len(candidate_phrase) and current_letter == candidate_phrase[candidate_index]:
                candidate_index += 1

        # Keep track of the maximum length among all valid matching subsequences found
        if candidate_index == len(candidate_phrase):
            if len(candidate_phrase) > longest_sequence_length:
                longest_sequence_length = len(candidate_phrase)

    return longest_sequence_length

Big(O) Analysis

Time Complexity
O(2^n) – To generate every possible subsequence from the first message of length n, the algorithm makes a binary choice for each character to either include it or exclude it, resulting in 2^n total combinations. For each of these exponentially many combinations, the algorithm must scan the second message of length m to verify if the letters appear in order. This leads to approximately 2^n * m operations, which simplifies to an exponential time complexity of O(2^n).
Space Complexity
O(2^n) – The brute force strategy requires generating a list of every possible combination of letters from the first message, which results in an exponential number of subsets for a string of length N. The auxiliary memory needed to store this massive list of subsequences grows exponentially relative to the input size of the first message. Additionally, keeping track of the best shared combination requires a constant number of variables, but the sheer volume of generated combinations dominates the extra memory usage. Consequently, the auxiliary space complexity scales exponentially as the length of the input message increases.

Optimal Solution

Approach

Instead of checking every single possible way to match letters, the best approach builds the solution piece by piece by comparing the two texts from left to right. It remembers past matches so you never have to waste time solving the same smaller puzzle twice.

Here's how the algorithm would work step-by-step:

  1. Line up both texts side by side to start comparing them from the very beginning.
  2. Look at the first letter of each text; if they match, celebrate that you found a common piece and move forward in both texts.
  3. If the letters do not match, try two separate paths: temporarily skip ahead in the first text while staying put in the second, and also try the opposite by skipping ahead in the second text while staying put in the first.
  4. Whenever you find a matching letter, remember the score so far so you can build upon it later instead of recounting from scratch.
  5. Continue this process of matching and exploring paths until you reach the end of both texts.
  6. Combine all the saved successful matches to reveal the longest shared sequence possible.

Code Implementation

def longest_common_subsequence(first_text_string, second_text_string):
    row_count = len(first_text_string)
    column_count = len(second_text_string)
    dynamic_table = [[0] * (column_count + 1) for _ in range(row_count + 1)]

    # We build solutions iteratively to avoid recalculating overlapping subproblems.
    for first_index in range(1, row_count + 1):
        for second_index in range(1, column_count + 1):
            if first_text_string[first_index - 1] == second_text_string[second_index - 1]:
                # Matching characters extend the previously found subsequence length by one.
                dynamic_table[first_index][second_index] = dynamic_table[first_index - 1][second_index - 1] + 1
            else:
                # When characters differ, we inherit the maximum length from adjacent explored paths.
                dynamic_table[first_index][second_index] = max(dynamic_table[first_index - 1][second_index], dynamic_table[first_index][second_index - 1])

    return dynamic_table[row_count][column_count]

Big(O) Analysis

Time Complexity
O(m * n) – To solve this, we use dynamic programming to build a 2D grid of size (m + 1) by (n + 1), where m and n represent the lengths of the two text inputs. For every single cell in this grid, we perform a constant time lookup and comparison by checking the corresponding letters from both texts. This requires iterating through every character of the first text for every character of the second text, resulting in m * n total operations. Therefore, the total operations approximate the formula m * n, which simplifies to the Big O time complexity of O(m * n).
Space Complexity
O(M * N) – The plain English explanation describes remembering past matches to build upon them later without recounting from scratch. This requires an auxiliary two-dimensional grid or memoization table of size (M + 1) by (N + 1), where M and N represent the lengths of the two input texts. The memory consumed is strictly driven by storing these intermediate results for every possible character combination. As the input sizes grow, this table scales proportionally to the product of their lengths. Ultimately, simplifying this storage requirement yields a Big O space complexity of O(M * N).

Edge Cases

One or both input strings are empty
How to Handle:
The dynamic programming table initialization with zeros naturally results in a length of zero being returned.
Strings of length one with a matching character
How to Handle:
The base case comparison correctly identifies the match and returns a length of one.
Strings of length one with no matching characters
How to Handle:
The nested loops evaluate the characters, find no matches, and return zero.
Strings with no common characters at all
How to Handle:
The recurrence relation will never increment the match count, resulting in a final return value of zero.
One string is entirely a subsequence of the other
How to Handle:
The algorithm accumulates matches sequentially, correctly returning the length of the shorter string.
Strings containing many duplicate characters
How to Handle:
The character-by-character state transitions correctly track relative order without prematurely consuming shared duplicates.
Maximum length strings approaching constraints
How to Handle:
Space-optimized dynamic programming using two rows prevents memory limit exceed errors by reducing space complexity to linear.
Completely identical strings
How to Handle:
Every character comparison succeeds along the diagonal, and the algorithm returns the full length of the input string.
0/245 completed