Find the greatest number of characters that two strings can share while preserving their original order.
Problem
Input. Two Python strings, first and second.
Output. Return the length of their longest common subsequence, not the actual subsequence.
Rules. A subsequence may skip characters but must retain their relative order in each string. Matching uses exact code-point equality. The chosen characters need not be adjacent. Preserve both strings. If either is empty, return zero.
Example. For first = "abc" and second = "ac", return 2, witnessed by "ac".
For "abc" and "cba", return 1, not 3, because the common order cannot be reversed.
Picture
Define as the best length for first[:i] and second[:j].
Every empty-prefix border is zero.
This cell’s dependencies have different storage locations:
Reference drawing
A match extends the diagonal; a mismatch compares the two shorter prefixes
Derivation
Equal endpoints can extend an optimal shorter pair by one.
An optimal common sequence can use those endpoints: move its final matching occurrences there, or append the shared endpoint.
On a mismatch, a common sequence cannot use both unequal endpoints together.
It must skip at least one; max(up,left) covers both cases.
Problem trace
Matching characters extend the diagonal subproblem by one
- base
- (0, 0)
- columns
- empty, a, c
- row axis
- empty, a, b, c
- current
- not shown→(1, 1)
- diagonal
- not shown→(0, 0)
- base
- (0, 0)→not shown
- current
- (1, 1)→(1, 2)
- left
- not shown→(1, 1)
- up
- not shown→(0, 2)
- current
- (1, 2)→(2, 1)
- left
- (1, 1)→(2, 0)
- up
- (0, 2)→(1, 1)
- current
- (2, 1)→(2, 2)
- left
- (2, 0)→(2, 1)
- up
- (1, 1)→(1, 2)
- current
- (2, 2)→(3, 1)
- left
- (2, 1)→(3, 0)
- up
- (1, 2)→(2, 1)
- current
- (3, 1)→(3, 2)
- diagonal
- not shown→(2, 1)
- left
- (3, 0)→not shown
- Recognize it
- Use it when two sequences must retain relative order while allowing skips, and the answer for two prefixes depends only on shorter prefixes of one or both sequences.
- Keep true
- After writing current[index], it is the LCS length for the processed first-string prefix and second[:index]; previous holds the complete answers for the prior first-string prefix.
- Reuse it
- For ordered matching problems, define a state on two prefixes; matching endpoints consume both, while mismatching endpoints branch by skipping one side and combining optimal smaller states.
Reference drawing
Problem trace
Matching characters extend the diagonal subproblem by one
Execution trace
- base
- (0, 0)
- columns
- empty, a, c
- row axis
- empty, a, b, c
- current
- not shown→(1, 1)
- diagonal
- not shown→(0, 0)
- base
- (0, 0)→not shown
- current
- (1, 1)→(1, 2)
- left
- not shown→(1, 1)
- up
- not shown→(0, 2)
- current
- (1, 2)→(2, 1)
- left
- (1, 1)→(2, 0)
- up
- (0, 2)→(1, 1)
- current
- (2, 1)→(2, 2)
- left
- (2, 0)→(2, 1)
- up
- (1, 1)→(1, 2)
- current
- (2, 2)→(3, 1)
- left
- (2, 1)→(3, 0)
- up
- (1, 2)→(2, 1)
- current
- (3, 1)→(3, 2)
- diagonal
- not shown→(2, 1)
- left
- (3, 0)→not shown
- Recognize it
- Use it when two sequences must retain relative order while allowing skips, and the answer for two prefixes depends only on shorter prefixes of one or both sequences.
- Keep true
- After writing current[index], it is the LCS length for the processed first-string prefix and second[:index]; previous holds the complete answers for the prior first-string prefix.
- Reuse it
- For ordered matching problems, define a state on two prefixes; matching endpoints consume both, while mismatching endpoints branch by skipping one side and combining optimal smaller states.
Columns run through the empty prefix, a, then ac.
Rows run through the empty prefix, a, ab, then abc.
Completed rows are [0,0,0], [0,1,1], [0,1,1], [0,1,2].
Code
Fill left-to-right: previous preserves up and diagonal; current[-1] supplies left.
Replace previous only after the entire current row is complete.
def longest_common_subsequence(first: str, second: str) -> int:
previous = [0] * (len(second) + 1)
for first_char in first:
current = [0]
for index, second_char in enumerate(second, 1):
if first_char == second_char:
current.append(1 + previous[index - 1])
else:
current.append(max(current[-1], previous[index]))
previous = current
return previous[-1]
For lengths , there are comparison cells plus boundary and row work.
Including empty-boundary cases, time is and storage is slots.
Here is len(second), not automatically the shorter length.
These are scalar-operation bounds.
Python strings compare code points, not automatically grapheme clusters or normalized text.
Failure Check
Longest common substring requires adjacency; it would reject the noncontiguous "ac" witness in "abc".
Overwriting old-row values too early loses required diagonals.
Two rows compute length but do not retain a ready-made witness.
Change the Storage Axis
New task: One string is much longer, and only length is needed.
Picture and change: Length is symmetric in the inputs. Make the shorter string the column axis, then use the unchanged recurrence.
def lcs_short_axis(first, second):
if len(second) > len(first):
first, second = second, first
return longest_common_subsequence(first, second)
Check: ("ac","abc") still returns 2; ("","abc") returns 0.
Row storage becomes slots without retaining an alignment.
Use when: Symmetric length output permits reorientation.
Change to Witness Output
New task: Return one actual common subsequence.
Picture and change: Retain the full prefix table. Walk backward through matches or a maximizing predecessor; move up on mismatch ties.
def lcs_witness(first, second):
table = [[0] * (len(second) + 1)
for _ in range(len(first) + 1)]
for first_index, first_char in enumerate(first, 1):
for second_index, second_char in enumerate(second, 1):
if first_char == second_char:
table[first_index][second_index] = (
table[first_index - 1][second_index - 1] + 1)
else:
table[first_index][second_index] = max(
table[first_index - 1][second_index],
table[first_index][second_index - 1])
first_index, second_index = len(first), len(second)
answer = []
while first_index and second_index:
if first[first_index - 1] == second[second_index - 1]:
answer.append(first[first_index - 1])
first_index -= 1
second_index -= 1
elif table[first_index - 1][second_index] >= table[first_index][second_index - 1]:
first_index -= 1
else:
second_index -= 1
return "".join(reversed(answer))
Check: ("abc","ac") returns "ac".
Check order in both inputs and equality between witness length and the reference result.
The full table uses slots, unlike two-row length computation.
Ties can admit several valid witnesses.
Use when: A subsequence must be recovered and full-table storage is acceptable.
Transfer Check
What does edit distance share with this algorithm, and what changes?
Answer
Both use a two-prefix dependency graph and safe row updates. LCS maximizes matched length with free skips. Edit distance minimizes priced operations, with nonzero costs on its empty-prefix borders.