567. Permutation in String
Asked at 16Microsoft50Amazon46Bloomberg42Meta40Google39Apple22Yandex69tcs42VK68Walmart Labs66Databricks54Media.net48Adobe44Cisco37Salesforce28Oracle27
Problem
Decide whether some permutation of s1 appears as a contiguous substring of s2.
Example: s1 = "ab", s2 = "eidbaooo" → true ("ba"); s2 = "eidboaoo" → false
Constraints: lowercase letters; lengths ≤ 10⁴.
Slide a window of size len(s1) over s2 and compare letter counts. Track matches = number of letters whose counts agree (0..26) to make each slide O(1).
Complexity: O(n) time, O(26) space.
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
k = len(s1)
if k > len(s2):
return False
need, win = Counter(s1), Counter(s2[:k])
if need == win:
return True
for r in range(k, len(s2)):
win[s2[r]] += 1
win[s2[r - k]] -= 1
if win[s2[r - k]] == 0:
del win[s2[r - k]]
if win == need:
return True
return False
assert Solution().checkInclusion("ab", "eidbaooo") is True
assert Solution().checkInclusion("ab", "eidboaoo") is False
class Solution {
public boolean checkInclusion(String s1, String s2) {
int k = s1.length(), n = s2.length();
if (k > n) return false;
int[] diff = new int[26]; // diff = count(window) - count(s1)
for (int i = 0; i < k; i++) { diff[s1.charAt(i) - 'a']--; diff[s2.charAt(i) - 'a']++; }
int zeros = 0;
for (int d : diff) if (d == 0) zeros++;
for (int r = k; ; r++) {
if (zeros == 26) return true;
if (r == n) return false;
int in = s2.charAt(r) - 'a', out = s2.charAt(r - k) - 'a';
if (diff[in] == 0) zeros--; if (++diff[in] == 0) zeros++;
if (diff[out] == 0) zeros--; if (--diff[out] == 0) zeros++;
}
}
}
func checkInclusion(s1 string, s2 string) bool {
k := len(s1)
if k > len(s2) {
return false
}
var need, win [26]int
for i := 0; i < k; i++ {
need[s1[i]-'a']++
win[s2[i]-'a']++
}
if need == win {
return true
}
for r := k; r < len(s2); r++ {
win[s2[r]-'a']++
win[s2[r-k]-'a']--
if win == need {
return true
}
}
return false
}