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 String to Make Subsequence INPUT String s = "coaching" c o a c h i n g 0 1 2 3 4 5 6 7 String t = "coding" c o d i n g 0 1 2 3 4 5 Goal: Find minimum chars to append to s so t is a subsequence Subsequence: Delete some chars, keep order e.g. "coing" from "coaching" ALGORITHM STEPS 1 Initialize Pointers i=0 (for s), j=0 (for t) 2 Scan s for matches If s[i]==t[j], increment j 3 Always increment i Move through s greedily 4 Return len(t) - j Unmatched chars need append Matching Process: s[0]='c' == t[0]='c' OK j=1 s[1]='o' == t[1]='o' OK j=2 s[2..7] has no 'd' STOP j stopped at 2 Remaining: "d","i","n","g" FINAL RESULT Calculation: len(t) - j = 6 - 2 = 4 Output: 4 What gets appended: Original s: "coaching" c o a c h i n g + d i n g Matched Appended (4) Key Insight: The greedy approach works because we want to match as many characters as possible from t using s. By always taking the first available match in s, we maximize the prefix of t that can be found as a subsequence. The remaining unmatched suffix of t must be appended. Time: O(n+m), Space: O(1) TutorialsPoint - Append Characters to String to Make Subsequence | Greedy - Match First Available Character
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