Longest Common Subsequence
Problem
Given two strings text1 and text2, return the length of the longest string that appears as a subsequence of both. A subsequence keeps characters in their original order but may skip any number of them. If the strings share no characters, return 0.
- Each string can run up to a few thousand characters.
- Both strings contain only lowercase English letters.
Examples
text1 = "pumpkin", text2 = "pudding"→4, via the subsequence"puin".text1 = "flag", text2 = "flags"→4, since"flag"itself is a subsequence of"flags".text1 = "cat", text2 = "dog"→0. No character is shared at all.
Hints
- Compare the last characters of the two strings. What can you conclude if they match? What if they do not?
- The answer for a pair of prefixes depends only on answers for shorter prefixes. Which three?
- Classic 2D DP over prefix lengths:
dp[i][j]fortext1[:i]andtext2[:j].
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.