Append Characters to String to Make Subsequence - Problem
You are given two strings s and t consisting of only lowercase English letters.
Your task is to find the minimum number of characters that need to be appended to the end of s so that t becomes a subsequence of the modified string.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
Example: If s = "coaching" and t = "coding", we need to append 2 characters because "coaching" already contains "co" as a subsequence, but we need to add "ding" to get the full "coding" subsequence.
Input & Output
example_1.py โ Basic Example
$
Input:
s = "coaching", t = "coding"
โบ
Output:
4
๐ก Note:
We can match 'c' and 'o' from "coaching" with the first two characters of "coding". We need to append "ding" (4 characters) to make "coding" a subsequence.
example_2.py โ Complete Match
$
Input:
s = "abcde", t = "ace"
โบ
Output:
0
๐ก Note:
"ace" is already a subsequence of "abcde" (positions 0, 2, 4), so we don't need to append any characters.
example_3.py โ No Match
$
Input:
s = "xyz", t = "abc"
โบ
Output:
3
๐ก Note:
None of the characters in "xyz" match with "abc", so we need to append all 3 characters of "abc".
Constraints
- 1 โค s.length, t.length โค 105
- s and t consist only of lowercase English letters
- Follow-up: Can you solve this in O(n + m) time and O(1) space?
Visualization
Tap to expand
Understanding the Visualization
1
Start with Both Lists
You have your ingredients (s) and the recipe requirements (t)
2
Match in Order
Go through your ingredients and check off recipe items in sequence
3
Count Missing Items
Whatever recipe items couldn't be checked off need to be purchased
Key Takeaway
๐ฏ Key Insight: We only need to find the longest prefix of the target that exists as a subsequence in the source, then append the remaining suffix.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code