You get two strings, text1 and text2. A subsequence is what is left after crossing out any letters you like (or none) while keeping the rest in their order: "tp" is a subsequence of "trap", "pt" is not.
Return the length of the longest string that is a subsequence of both. If they share no letter, return 0.
Example 1
Input: text1 = "tap", text2 = "trap" Output: 3 Why: cross out the r in "trap" and both read "tap"
2 more examples and the constraints
Example 2
Input: text1 = "planet", text2 = "plate" Output: 4 Why: "plat" (or "plae") appears in order in both
Example 3
Input: text1 = "dog", text2 = "cat" Output: 0 Why: not a single shared letter
Constraints
- 1 ≤ length of text1, length of text2 ≤ 1,000
- Both strings use only lower-case English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion + memoO(m·n)
- Bottom-up tableO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for two 1,000-letter strings | Verdict |
|---|---|---|---|
| Recursion + memo | O(m·n) | Passes; deep recursion | |
| Bottom-up table | O(m·n) | Best; plain loops |
m = length of text1, n = length of text2. Without the memo, plain recursion is O(2^(m+n)).
Edge cases to test
- Nothing shared. "dog" and "cat" give 0, not an error.
- Equal strings. The answer is the whole length.
- Same letters, wrong order. "abcd" and "dcba" give 1: order counts, so only one letter survives.
- Repeated letters. "aaaa" and "aa" give 2; each letter can be used once.
Common mistakes
- Confusing a subsequence with a substring and requiring the letters to be next to each other.
- Off-by-one indexing:
dp[i][j]compares text1[i − 1] with text2[j − 1]. - On a match, taking max(up, left) + 1 instead of the diagonal + 1, which can reuse a letter.
How to talk through it
- 1Clarify. Subsequence, not substring? Only the length, or the string too? Can a string be empty?
- 2Find the choice. Compare one letter from each. Match: take both. No match: drop one of them.
- 3Name the overlap. The same pair of prefixes comes up many times, so memoise or tabulate.
- 4Code the table. Zero border, fill row by row, return the bottom-right cell.
- 5Test out loud. Run "dog"/"cat" and "abcd"/"dcba" before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?