What is LCS
A subsequence keeps order but may skip letters. dp[i][j] is the LCS length of A[:i] and B[:j]. Equal letters take the diagonal plus one; otherwise take the better of left and up.
Brute force approach
(i, j) is reached many ways.Match the current letters and move both pointers, or skip a letter from one string. The pair of indexes repeats. Memoization stores LCS(i, j).
Each string is at most 4 letters. ABC and AC share length 2.
Memoized approach
O(mn).Each state is solved once. A dashed node is a cache hit: the call returns immediately and that branch stops.
ABC, B = AEB. The table ends at 2 (AB). Step through the DP table. The live code on the right is the DP recurrence — brute force is shown in Implementations below so you can see why it TLE.Interactive DP trace
Pseudocode & Complexity
| Operation | Time |
|---|---|
| Each cell | O(1) |
| Fill table | O(mn) |
| Space | O(mn) |
Brute force explores the same subproblems many times and will TLE on the hidden tests. The DP codes below reuse each answer once.
Implementations