[LeetCode] Subsequence After One Replacement

3983. Subsequence After One Replacement

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public:
bool canMakeSubsequence(string s, string t) {
int n = s.size(), m = t.size();
if (n > m) return false;

vector<int> f(n, -1), b(n, -1);

for (int i = 0, j = 0; i < n and j < m; i++) {
while (j < m and s[i] != t[j]) j++;
if (j < m) f[i] = j++;
else break;
}

for (int i = n - 1, j = m - 1; i >= 0 and j >= 0; i--) {
while (j >= 0 and s[i] != t[j]) j--;
if (j >= 0) b[i] = j--;
else break;
}

if (f[n - 1] != -1) return true;

if (n == 1) return m >= 1;

if (b[1] != -1 and b[1] >= 1) return true;
if (f[n - 2] != -1 and f[n - 2] + 1 < m) return true;

for (int i = 1; i + 1 < n; i++) {
if (f[i - 1] != -1 and b[i + 1] != -1 and f[i - 1] + 1 < b[i + 1]) {
return true;
}
}

return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/subsequence-after-one-replacement/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.