Subsequence After One Replacement Problem
#3983
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3983.
You are given two strings s and t consisting of lowercase English letters.
You may choose at most one index in s and replace the character at that index with any lowercase English letter.
Return true if it is possible to make s a subsequence of t; otherwise, return false.
Example 1:
Input: s = "cat", t = "chat"
Output: true
Explanation:
- Replace s[1] from 'a' to 'h'. The resulting string is "cht".
- "cht" is a subsequence of "chat" because we can match 'c', 'h', and 't' in order.
Example 2:
Input: s = "plane", t = "apple"
Output: false
Explanation:
- The characters 'p', 'l', and 'e' can be matched in t, but the remaining characters cannot be matched while preserving the required order.
- Even after replacing any one character in s, it is impossible to make s a subsequence of t.
Constraints:
1 <= s.length, t.length <= 10^5sandtconsist only of lowercase English letters.
Solution
Approach: Two Pointers
Matching s against t greedily works as for an ordinary subsequence check, except that one character of s may be treated as a wildcard. Keep two pointers into s while scanning t from left to right:
i0is how much ofsis matched exactly, with no replacement used.i1is how much ofsis matched when one replacement is still allowed to be used anywhere before it.
For each character t[j]:
- If
s[i1] == t[j], advancei1. - Set
i1 = max(i1, i0 + 1): the charactert[j]can always stand in fors[i0], so using the replacement there gives at leasti0 + 1. - If
s[i0] == t[j], advancei0.
After the scan, s can be made a subsequence of t exactly when i1 == |s|.
Complexity: time O(|s| + |t|), space O(1).
class Solution:
def canMakeSubsequence(self, s: str, t: str) -> bool:
m, n = len(s), len(t)
i0 = i1 = j = 0
while i1 < m and j < n:
if s[i1] == t[j]:
i1 += 1
i1 = max(i1, i0 + 1)
if s[i0] == t[j]:
i0 += 1
j += 1
return i1 == m