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
- Match:
dp[i-1][j-1] + 1. Otherwise:max(dp[i-1][j], dp[i][j-1]). - Row 0 and column 0 are 0.
- 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.