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".

Visualization

Tap to expand
Recipe Matching AlgorithmYour Ingredients (s):โœ“ Chicken (c)โœ“ Onion (o)Apple (a)Carrot (c)Herbs (h)Recipe Needs (t):โœ“ Chicken (c)โœ“ Onion (o)โœ— Dill (d)โœ— Ice (i)โœ— Nuts (n)Shopping List:Need to buy: Dill, Ice, NutsTotal items: 3
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.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(2^n * m)

We generate 2^n subsequences where n is length of s, and for each we compare with t of length m

n
2n
โš  Quadratic Growth
Space Complexity
O(2^n)

We need to store all possible subsequences

n
2n
โš  Quadratic Space

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?
Asked in
Google 45 Amazon 38 Meta 22 Microsoft 15
24.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen