Leetcode 3083. Existence of a Substring in a String and Its Reverse
Given two strings s1
and s2
, check if any permutation of s1
exists as a substring in s2
or its reverse. Return true
if such a permutation exists, otherwise return false
.
s1
and s2
?s1
and s2
contain only lowercase/uppercase letters or any character?s1
or s2
is an empty string?Assuming:
s1
and s2
can contain only lowercase English letters.s1
and s2
is sufficiently within typical problem constraints (e.g., up to 10^4
).s1
is longer than s2
, immediately return false
.s1
being a substring of s2
or its reverse hints that we need to check all substrings of s2
with the same length as s1
.s1
to check all substrings in s2
.s1
.s2
and its reversed version.#include <vector>
#include <string>
#include <algorithm>
bool checkInclusion(const std::string &s1, const std::string &s2) {
if (s1.size() > s2.size()) {
return false;
}
std::vector<int> s1Count(26, 0), s2Count(26, 0);
int n1 = s1.size(), n2 = s2.size();
// Count the frequency of characters in s1.
for (char c : s1) {
s1Count[c - 'a']++;
}
// Sliding window over s2
for (int i = 0; i < n1; ++i) {
s2Count[s2[i] - 'a']++;
}
if (s1Count == s2Count) {
return true;
}
for (int i = n1; i < n2; ++i) {
s2Count[s2[i] - 'a']++;
s2Count[s2[i - n1] - 'a']--;
if (s1Count == s2Count) {
return true;
}
}
// Check the reverse of s2
std::string s2Rev = s2;
std::reverse(s2Rev.begin(), s2Rev.end());
std::fill(s2Count.begin(), s2Count.end(), 0);
for (int i = 0; i < n1; ++i) {
s2Count[s2Rev[i] - 'a']++;
}
if (s1Count == s2Count) {
return true;
}
for (int i = n1; i < n2; ++i) {
s2Count[s2Rev[i] - 'a']++;
s2Count[s2Rev[i - n1] - 'a']--;
if (s1Count == s2Count) {
return true;
}
}
return false;
}
s1
takes O(n1), where n1
is the length of s1
.s2
and s2
’s reverse each takes O(n2), where n2
is the length of s2
.The function checkInclusion
effectively checks for the existence of permutations of s1
in s2
or its reverse using a sliding window and frequency count approach, ensuring a time-efficient solution.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?