LeetCode 2486: Append Characters to String to Make Subsequence

Problem Description

Explanation:

To solve this problem, we can iterate through the characters of the strings s and t simultaneously. We maintain two pointers, one for each string. If the characters at the current positions match, we move both pointers. If they don't match, we only move the pointer for string s and keep track of the number of characters we need to append to s to make t a subsequence of s.

Time Complexity:

The time complexity of this solution is O(n), where n is the length of the longer string between s and t.

Space Complexity:

The space complexity of this solution is O(1) as we are using constant extra space.


:

Solutions

class Solution {
    public int minCharacters(String s, String t) {
        int i = 0, j = 0;
        int count = 0;

        while (i < s.length() && j < t.length()) {
            if (s.charAt(i) == t.charAt(j)) {
                i++;
                j++;
            } else {
                i++;
                count++;
            }
        }

        count += t.length() - j;

        return count;
    }
}

Loading editor...