Append Characters to String to Make Subsequence (LeetCode 2486): Solution and Explanation
Given strings s and t, return the fewest characters that must be appended to the end of s so that t is a subsequence of the result.
Intuition
Characters can only be added at the end of s. So the letters of t that come first have to be found somewhere inside the original s, in order, and whatever is left of t gets appended.
That turns the question into: how long is the longest prefix of t that is already a subsequence of s? If that prefix has length j, the answer is len(t) - j.
The prefix can be measured greedily. Scan s once and keep a pointer j into t; every time s[i] equals t[j], use that letter and move j forward.
Taking the earliest match for each letter is always safe. A later match for t[j] would only leave less of s for t[j + 1] and the letters after it.
Approach: Greedy two pointers
- Set
j = 0. - For each character
chofs: ifj < len(t)andch == t[j], incrementj. - After the scan,
t[0..j-1]is the longest prefix oftthat is a subsequence ofs. - Return
len(t) - j.
Step-by-step example
s = "coaching", t = "coding"
- s[0] = 'c' matches t[0], so j = 1. s[1] = 'o' matches t[1], so j = 2.
- Now the scan looks for t[2] = 'd'. The letters 'a', 'c', 'h', 'i', 'n', 'g' are not 'd', so j stays 2.
- The scan ends with j = 2: only "co" is found in order.
- The tail "ding" must be appended, so the answer is 6 - 2 = 4.
Code: Python, Java, C++
1class Solution:
2 def appendCharacters(self, s: str, t: str) -> int:
3 j = 0
4 for ch in s:
5 if j < len(t) and ch == t[j]:
6 j += 1
7 return len(t) - j1class Solution {
2 public int appendCharacters(String s, String t) {
3 int j = 0;
4 for (int i = 0; i < s.length(); i++) {
5 if (j < t.length() && s.charAt(i) == t.charAt(j)) {
6 j++;
7 }
8 }
9 return t.length() - j;
10 }
11}1class Solution {
2public:
3 int appendCharacters(string s, string t) {
4 int j = 0;
5 for (char ch : s) {
6 if (j < (int)t.size() && ch == t[j]) {
7 j++;
8 }
9 }
10 return (int)t.size() - j;
11 }
12};Time and space complexity
O(n + m)
s is scanned once and j only moves forward through t, so each string is walked at most once.
O(1)
Only the pointer j is stored.
Other approaches
Binary search on the prefix length (time O((n + m) log m), space O(1))
Check with an is-subsequence test whether t[:k] is a subsequence of s, and binary search the largest such k. Correct, but it repeats the scan log m times.
Longest common subsequence (time O(n * m), space O(n * m))
Using the LCS of s and t is wrong here: the matched part must be a prefix of t, since only the end of s can be extended. LCS also costs O(n * m).
Common mistakes
- Counting letters of t that appear anywhere in s instead of in order. For s = "xyz" and t = "zyx", all three letters occur in s, yet only "z" can be matched as a prefix, so the answer is 2.
- Matching any letter of t rather than a prefix. Letters in the middle of t cannot be skipped, because appended letters can only fill in the tail.
- Reading t[j] after j has already reached len(t). Check
j < len(t)first, or stop the loop early. - Returning j instead of len(t) - j.
Frequently asked questions
Why is the greedy earliest match optimal?
If some answer uses a later position of s for t[j], swapping in the earliest possible position keeps the order valid and leaves at least as much of s for the remaining letters. So the greedy never finds a shorter prefix than any other matching.
Can the answer be 0?
Yes. If the scan matches every letter of t, t is already a subsequence of s and nothing needs to be appended.
How is this different from Is Subsequence?
It is the same scan. Is Subsequence only asks whether j reaches len(t); here the answer is how far short of len(t) the scan stops.