Append Characters to String to Make Subsequence - Greedy - Two Pointers [JS]

Description 

Solution: Greedy

Since we can only add new characters at the end of s,
it is optimal to match as many characters in s as possible.
Use two pointers to keep track of how many characters have been matched in s and t.
We then need to append the last (t.length - j) characters of t onto s.

n = length of s
Time Complexity: O(n)
Space Complexity: O(1)

var appendCharacters = function(s, t) {
  let j = 0;
  for (let i = 0; i < s.length && j < t.length; i++) {
    if (s[i] === t[j]) j++;
  }
  return t.length - j;
};

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]