SDE & MLE Prep

567. Permutation in String

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