TRT
Sign in
mediumAdvancedLeetCode#two-string DP

Longest common subsequence

Find the length of the longest subsequence shared by two strings with a table over their prefixes.

The Runtime Theory Team1 min read
Taught inGrids and stringsPro — members onlyTwo-dimensional DP fills a table whose cells depend on their neighbors above and to the left. On grids it counts or optimizes paths; on two strings, a cell compares two prefixes, which is how diff tools, spell checkers and DNA alignment work.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

intext1 = abcde, text2 = ace

out3

intext1 = abc, text2 = abc

out3

intext1 = abc, text2 = def

out0

Return the length of the longest common subsequence of two strings: characters in order, not necessarily contiguous.

Before you code

dp[i][j] is the LCS of the first i characters of one and the first j of the other. Look at the last characters of the two prefixes.

Hints

  1. Match: dp[i-1][j-1] + 1. Otherwise: max(dp[i-1][j], dp[i][j-1]).
  2. Row 0 and column 0 are 0.
  3. Two rows suffice for the length; reconstruct the subsequence by walking back through a full table.

Production & complexity notes

When solving Longest common subsequence on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Grids and strings to reinforce the underlying pattern.

What it practices

The prefix-pair table, from Grids and strings.

Not started

Sign in to save your learning progress.

Sign in to save