Append Characters to String to Make Subsequence - 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.

Input & Output

Example 1 — Partial Match
$ Input: s = "coaching", t = "coding"
Output: 4
💡 Note: We can match 'c' and 'o' from s, but need to append "ding" to complete the subsequence "coding"
Example 2 — Complete Match
$ Input: s = "abcde", t = "ace"
Output: 0
💡 Note: All characters 'a', 'c', 'e' from t are already present in s in correct order, so no characters need to be appended
Example 3 — No Match
$ Input: s = "xyz", t = "abc"
Output: 3
💡 Note: None of the characters in t are found in s, so we need to append all 3 characters "abc"

Constraints

  • 1 ≤ s.length, t.length ≤ 105
  • s and t consist only of lowercase English letters.

Visualization

Tap to expand
Append Characters to Make SubsequenceInput:s = "coaching"t = "coding"Process:Match characters from t in s:coding✓ Matched: "co" (2 characters)✗ Missing: "ding" (4 characters)Result: Need to append 4 characters
Understanding the Visualization
1
Input Strings
Given strings s and target t
2
Match Process
Find longest subsequence of t that exists in s
3
Calculate Result
Count remaining unmatched characters
Key Takeaway
🎯 Key Insight: Use two pointers to find the longest prefix of t that forms a subsequence in s, then append the remaining characters.
Asked in
Meta 12 Microsoft 8 Google 6
25.0K 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