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.
"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 <= 1000text1 and text2 consist of only lowercase English characters.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:
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:
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_lengthInstead 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:
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]| Case | How to Handle |
|---|---|
| One or both input strings are empty | The dynamic programming table initialization with zeros naturally results in a length of zero being returned. |
| Strings of length one with a matching character | The base case comparison correctly identifies the match and returns a length of one. |
| Strings of length one with no matching characters | The nested loops evaluate the characters, find no matches, and return zero. |
| Strings with no common characters at all | 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 | The algorithm accumulates matches sequentially, correctly returning the length of the shorter string. |
| Strings containing many duplicate characters | The character-by-character state transitions correctly track relative order without prematurely consuming shared duplicates. |
| Maximum length strings approaching constraints | Space-optimized dynamic programming using two rows prevents memory limit exceed errors by reducing space complexity to linear. |
| Completely identical strings | Every character comparison succeeds along the diagonal, and the algorithm returns the full length of the input string. |