Problem
You are given two strings s and t consisting of only lowercase English letters.
Return the minimum number of characters that need to be appended to the end of s so that t becomes a subsequence of s.
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.
Examples
Example 1:
| |
Explanation: Append the characters “ding” to the end of s so that s = “coachingding”. Now, t is a subsequence of s ("coachingding"). It can be shown that appending any 3 characters to the end of s will never make t a subsequence.
Example 2:
| |
Explanation: t is already a subsequence of s ("abcde").
Example 3:
| |
Explanation: Append the characters “abcde” to the end of s so that s = “zabcde”. Now, t is a subsequence of s (“zabcde”). It can be shown that appending any 4 characters to the end of s will never make t a subsequence.
Solution
Method 1 - Two Pointer Technique
- compute the lengths for
s, tstore in|s|, |t|. - Transverse the whole string s with control variable i, & move the pointer j when
s[i]==t[j] - Finally, we return the length of unmatched string in
t, aka|t|-jis the answer
Code
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(n)