Problem Description
Given two strings s and t consisting of only lowercase English letters, determine 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.
Key Insights
- Use two pointers to iterate over s and t concurrently.
- Match characters of t in s in order; every match moves the pointer for t.
- The unmatched part of t (from the current pointer to the end) represents the characters needed to be appended.
- This is a greedy approach ensuring the longest possible match of t in s.
Space and Time Complexity
Time Complexity: O(n + m), where n = len(s) and m = len(t).
Space Complexity: O(1)
Solution
We traverse string s with one pointer and string t with another pointer. For each character in s, if it matches the current character in t, advance the t pointer. After processing s, the remaining characters in t that were not matched must be appended to s. This direct two-pointer method efficiently determines the number of characters required for appending.