Longest Common Subsequence

Medium

This is an extra practice problem. It doesn't have walkthrough slides. You can solve it with the pattern template you already know. Open the hints if you get stuck.

Question

Two ancient scrolls each carry a line of runes, written left to right.

Find the length of the longest sequence of runes that shows up on both scrolls in the same order. The matching runes don't need to be next to each other on either scroll. They don't need to line up in position either. Only the order has to agree.

Input: a = "abc", b = "acb"

Output: 2

"ab" appears in order on both scrolls (a then b). So does "ac" (a then c). No sequence of 3 runes appears in order on both.

Input: a = "aaaa", b = "aa"

Output: 2

The second scroll only has two runes. That means the longest shared sequence can be at most 2 runes long. "aa" shows up in order on the first scroll too.

Input: a = "abcdefgh", b = "ijklmnop"

Output: 0

The two scrolls don't share any runes. That means the longest common sequence is empty.

Clarify the problem

What are some questions you'd ask an interviewer?

Understand the problem

What should our base case be? Assume we use how many runes of each scroll are left to consider as our memoization state.
f(0, 0) = 1
f(i, 0) = 0 and f(0, j) = 0
f(i, 0) = i and f(0, j) = j
f(i, j) = 0 only when a and b are completely different scrolls

Remember to understand the problem and plan your approach before you start coding.