Skip to content
mlmentorship

Define two-prefix answers before compressing the table to rows

Derive matching and skipping dependencies, preserve old-row values, then change storage orientation or recover a subsequence.

Published · 13 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Define two-prefix answers before compressing the table to rows

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Fill prefix states left to right: a match takes diagonal + 1; a mismatch takes max(left, up).

A match takes the diagonal; a mismatch compares the two shorter prefixes

A match takes the diagonal; a mismatch compares the two shorter prefixesThe actual LCS table for AB versus ACB contains final value two. Matching B with B uses diagonal value one plus one. The B-versus-C mismatch instead compares up one and left one to retain one. The arrow connects the actual matched diagonal parent to its result.Rows: prefix of AB; columns: prefix of ACBemptyACBempty0000A0111B0112B = B: diagonal 1 + 1 -> 2B != C: max(up 1, left 1) -> 1
At B = B, extend the diagonal value to two. At B != C, keep the larger shorter-prefix value, one. The parents solve different prefix questions.
Full interview answer 13 min read

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

A match extends the diagonal, not an arbitrary neighborFor AB versus ACB, matching B extends diagonal value 1 to 2. At mismatch C, compare the up and left subproblems instead.A matching character extends thediagonal predecessorRows: AB prefixes. Columns: ACBprefixes.emptyAACACBemptyAAB000001110112Matching B extends the shorter-prefixsubsequence to two.
Derivation
A match takes the diagonal; a mismatch compares the two shorter prefixesThe actual LCS table for AB versus ACB contains final value two. Matching B with B uses diagonal value one plus one. The B-versus-C mismatch instead compares up one and left one to retain one. The arrow connects the actual matched diagonal parent to its result.Rows: prefix of AB; columns: prefix of ACBemptyACBempty0000A0111B0112B = B: diagonal 1 + 1 -> 2B != C: max(up 1, left 1) -> 1
At B = B, extend the diagonal value to two. At B != C, keep the larger shorter-prefix value, one. The parents solve different prefix questions.
Read it this way: For AB versus ACB, matching B extends diagonal value 1 to 2. At mismatch C, compare the up and left subproblems instead. Which predecessor is extended when B matches B?

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

Input and goalFind the longest sequence of characters that appears in two strings in the same order. Characters do not need to be next to each other.
Initialize empty-prefix answersFor abc and ac, initialize every empty-prefix answer to zero.
0base000??0??0??
columnsempty, a, crowAxisempty, a, b, c
base
(0, 0)
columns
empty, a, c
row axis
empty, a, b, c

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.
For abc and ac, initialize every empty-prefix answer to zero. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does matching c with c use one plus the diagonal value rather than one plus the left value?
Reference drawing

Problem trace

Matching characters extend the diagonal subproblem by one

Worked example: a matching pair extends the diagonal subproblemFor AB versus ACB, B matches B and extends diagonal 1 to 2. A mismatch compares the two shorter-prefix answers instead.A matching character extends thediagonal predecessorRows: AB prefixes. Columns: ACBprefixes.emptyAACACBemptyAAB000001110112Matching B extends the shorter-prefixsubsequence to two.
Execution trace
Input and goalFind the longest sequence of characters that appears in two strings in the same order. Characters do not need to be next to each other.
Initialize empty-prefix answersFor abc and ac, initialize every empty-prefix answer to zero.
0base000??0??0??
columnsempty, a, crowAxisempty, a, b, c
base
(0, 0)
columns
empty, a, c
row axis
empty, a, b, c

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.
For abc and ac, initialize every empty-prefix answer to zero. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does matching c with c use one plus the diagonal value rather than one plus the left value?
Read it this way: For AB versus ACB, B matches B and extends diagonal 1 to 2. A mismatch compares the two shorter-prefix answers instead. If the last characters differ, is the diagonal-plus-one transition still permitted?

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.