Append Characters to String to Make Subsequence — LeetCode 2486 Python Solution
- Problem
- #2486
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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 - jComplexity
| Measure | Complexity |
|---|---|
| Time | O(m + n), where m and n are the lengths of strings s and t respectively |
| Space | O(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.