Append Characters to String to Make Subsequence - Greedy - Two Pointers [JS]
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
Post a Comment