#2486
Append Characters to String to Make Subsequence
MediumTwo PointersStringGreedyTwo PointersGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a two-pointer technique to efficiently find the longest prefix of `t` that is a subsequence of `s`. This approach minimizes unnecessary checks and directly calculates how many characters need to be appended.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two pointers, one for `s` and one for `t`.
- 2Step 2: Iterate through `s` and `t` simultaneously. If characters match, move both pointers forward.
- 3Step 3: If characters do not match, only move the pointer for `s`.
- 4Step 4: The number of characters to append is the length of `t` minus the number of matched characters.
solution.py10 lines
1# Full working Python code
2
3def min_chars_to_append(s, t):
4 i, j = 0, 0
5 while i < len(s) and j < len(t):
6 if s[i] == t[j]:
7 j += 1
8 i += 1
9 return len(t) - j
10ℹ
Complexity note: The time complexity is O(n) because we traverse each string at most once. The space complexity is O(1) since we only use a few variables for tracking indices.
- 1Understanding subsequences is crucial; a subsequence can skip characters.
- 2Using two pointers can significantly reduce the complexity of the problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.