[LeetCode] Find the Lexicographically Smallest Valid Sequence

3302. Find the Lexicographically Smallest Valid Sequence

You are given two strings word1 and word2.

A string x is called almost equal to y if you can change at most one character in x to make it identical to y.

A sequence of indices seq is called valid if:

  • The indices are sorted in ascending order.
  • Concatenating the characters at these indices in word1 in the same order results in a string that is almost equal to word2.

Return an array of size word2.length representing the lexicographically smallest valid sequence of indices. If no such sequence of indices exists, return an empty array.

Note that the answer must represent the lexicographically smallest array, not the corresponding string formed by those indices.

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
class Solution {
public:
vector<int> validSequence(string word1, string word2) {
if(word2.size() == 1) return {0};
int n = word1.size(), m = word2.size();
vector<int> suf(n + 1, m);
for(int i = n - 1, j = m - 1; i >= 0; i--) {
if(j >= 0 and word1[i] == word2[j]) --j;
suf[i] = j + 1;
}
vector<int> res;
for(int i = 0, j = 0, fl = false; i < word1.size() and res.size() < m; i++) {
if(word1[i] == word2[j]) res.push_back(i), j++;
else {
if(fl) continue;
if((m - suf[i+1]) + j + 1 >= m) {
res.push_back(i), j++;
fl = !fl;
}
}
}
if(res.size() != m) return {};
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/09/29/PS/LeetCode/find-the-lexicographically-smallest-valid-sequence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.