Permutation in String

Does s2 contain any permutation of s1? Fixed-size sliding window over a frequency vector.

Medium
Time O(n) Space O(1)
LeetCode
4 min read
sliding-window string

Problem#

Return true iff s2 contains a substring that is a permutation of s1.

Examples#

  • s1 = "ab", s2 = "eidbaooo"true ("ba")
  • s1 = "ab", s2 = "eidboaoo"false

Constraints#

  • 1 <= s1.length, s2.length <= 10^4, lowercase.

Approach#

Fixed-length window equal to s1.size(). Maintain a 26-int frequency vector for the window in s2; compare to s1’s frequency. Each shift updates two slots.

Solution#

Permutation in String
class Solution {
public:
bool checkInclusion(string s1, string s2) {
int n = s1.size(), m = s2.size();
if (n > m) return false;
int a[26] = {0}, b[26] = {0};
for (int i = 0; i < n; ++i) { ++a[s1[i] - 'a']; ++b[s2[i] - 'a']; }
if (memcmp(a, b, sizeof a) == 0) return true;
for (int i = n; i < m; ++i) {
++b[s2[i] - 'a'];
--b[s2[i - n] - 'a'];
if (memcmp(a, b, sizeof a) == 0) return true;
}
return false;
}
};

Editorial#

Each window comparison is O(26) = O(1), and the window updates are also constant. Total O(n). The memcmp over fixed-size buffers compiles to a couple of SIMD instructions on modern compilers — beats element-wise comparison.

Complexity#

  • Time: O(n + m).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.