Append Characters to String to Make Subsequence

medium string two pointers greedy

Problem

You are given two strings s and t made of lowercase letters. In one operation you may append any single character to the end of s. Return the minimum number of such appends needed so that t becomes a subsequence of s. A subsequence keeps the characters of t in order, but they need not be next to each other in s.

Inputs = "coaching", t = "code"
Output2
Scanning s we can match "c" then "o" of t, but "d" and "e" never appear afterward. Appending "de" gives "coachingde", which contains "code" as a subsequence, so 2 appends are needed.

def append_characters(s, t):
    j = 0
    for ch in s:
        if j < len(t) and ch == t[j]:
            j += 1
    return len(t) - j
function appendCharacters(s, t) {
  let j = 0;
  for (let i = 0; i < s.length; i++) {
    if (j < t.length && s[i] === t[j]) j++;
  }
  return t.length - j;
}
class Solution {
    public int appendCharacters(String s, String t) {
        int j = 0;
        for (int i = 0; i < s.length(); i++) {
            if (j < t.length() && s.charAt(i) == t.charAt(j)) j++;
        }
        return t.length() - j;
    }
}
int appendCharacters(string s, string t) {
    int j = 0;
    for (int i = 0; i < (int)s.size(); i++) {
        if (j < (int)t.size() && s[i] == t[j]) j++;
    }
    return (int)t.size() - j;
}
Time: O(n + m) Space: O(1)