iq.lab
Python starts when a code cell comes near or you run one
mediumDynamic programming, 2D target 25 min

Longest common subsequence

Pick some letters of a string, keep them in the order they appear, and read them off: the result is a subsequence of that string. Gaps are allowed, but the order is not changed. For example, "pig" is a subsequence of "spring" (skip the s, the r and the n), but "gip" is not, because in "spring" the g comes after the i and the p.

You get two strings, first and second. Return the length of the longest string that is a subsequence of both. When no letter appears in both strings, the answer is 0.

Example 1
Inputfirst = "spring", second = "pigs"Output3

The longest common subsequence is "pig". The s cannot join it: in "spring" it comes before the p, in "pigs" after the g.

Example 2
Inputfirst = "rabbit", second = "habit"Output4

"abit": skip the r and one b of "rabbit", and the h of "habit".

Example 3
Inputfirst = "cat", second = "dog"Output0

No letter appears in both.

Constraints
  • 1 ≤ len(first), len(second) ≤ 1,000

  • Both strings use only lowercase English letters.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.