Append Characters to String to Make Subsequence — LeetCode 2486 Python Solution

MediumGreedyTwo PointersString
Problem
#2486
Reading time
2 min

The 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.

Example

Input
s = "coaching", t = "coding"
Output
4
Explanation
Append the characters "ding" to the end of s so that s = "coachingding".

Python solution

Python
class Solution:
    def appendCharacters(self, s: str, t: str) -> int:
        n, j = len(t), 0
        for c in s:
            if j < n and c == t[j]:
                j += 1
        return n - j

Complexity

MeasureComplexity
TimeO(m + n), where m and n are the lengths of strings s and t respectively
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2486. Append Characters to String to Make Subsequence is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2486. Append Characters to String to Make Subsequence?
LeetCode 2486. Append Characters to String to Make Subsequence is rated Medium on LeetCode.
What is the time complexity of LeetCode 2486. Append Characters to String to Make Subsequence?
The Python solution on this page runs in O(m + n), where m and n are the lengths of strings s and t respectively.
What is the space complexity of LeetCode 2486. Append Characters to String to Make Subsequence?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2486. Append Characters to String to Make Subsequence cover?
LeetCode 2486. Append Characters to String to Make Subsequence is tagged Greedy, Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview