Append Characters to String to Make Subsequence (LeetCode 2486): Solution and Explanation

Medium
Two Pointers
String
Greedy

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

  1. Set j = 0.
  2. For each character ch of s: if j < len(t) and ch == t[j], increment j.
  3. After the scan, t[0..j-1] is the longest prefix of t that is a subsequence of s.
  4. Return len(t) - j.

Step-by-step example

s = "coaching", t = "coding"
  1. s[0] = 'c' matches t[0], so j = 1. s[1] = 'o' matches t[1], so j = 2.
  2. Now the scan looks for t[2] = 'd'. The letters 'a', 'c', 'h', 'i', 'n', 'g' are not 'd', so j stays 2.
  3. The scan ends with j = 2: only "co" is found in order.
  4. 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) - j
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + m)

s is scanned once and j only moves forward through t, so each string is walked at most once.

Space

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.