sagelearnai

Permutation in String

Difficulty: Medium · Pattern: Sliding Window · LeetCode #567

Return true if some contiguous substring of s2 is a rearrangement (permutation) of s1. Both contain lowercase letters only.

Examples

text
s1 = "ab",  s2 = "eidbaooo"   →  true    ("ba")
s1 = "ab",  s2 = "eidboaoo"   →  false
s1 = "adc", s2 = "dcda"       →  true    ("cda")

Hints

  1. Any matching substring has exactly len(s1) characters, so this is a fixed-size window.
  2. Compare letter counts of the window with the counts of s1.
  3. Track how many of the 26 letters currently have matching counts, to update in O(1) per step.

Approach

Build counts for s1 and for the first window of s2. Keep matches = number of letters (out of 26) whose counts agree. Slide the window one step at a time: add the entering letter and remove the leaving letter, adjusting matches for exactly those two letters. If matches == 26 at any point, a permutation exists.

Complexity

Time: O(n + m). Space: O(26).

Python solution
def checkInclusion(s1, s2):
    n, m = len(s1), len(s2)
    if n > m:
        return False
    a, b = [0] * 26, [0] * 26
    for i in range(n):
        a[ord(s1[i]) - 97] += 1
        b[ord(s2[i]) - 97] += 1
    matches = sum(a[i] == b[i] for i in range(26))
    for r in range(n, m):
        if matches == 26:
            return True
        for idx, delta in ((ord(s2[r]) - 97, 1), (ord(s2[r - n]) - 97, -1)):
            before = a[idx] == b[idx]
            b[idx] += delta
            after = a[idx] == b[idx]
            matches += after - before
    return matches == 26
JavaScript solution
function checkInclusion(s1, s2) {
  const n = s1.length, m = s2.length;
  if (n > m) return false;
  const a = new Array(26).fill(0), b = new Array(26).fill(0);
  for (let i = 0; i < n; i++) { a[s1.charCodeAt(i) - 97]++; b[s2.charCodeAt(i) - 97]++; }
  let matches = 0;
  for (let i = 0; i < 26; i++) if (a[i] === b[i]) matches++;
  for (let r = n; r < m; r++) {
    if (matches === 26) return true;
    for (const [idx, d] of [[s2.charCodeAt(r) - 97, 1], [s2.charCodeAt(r - n) - 97, -1]]) {
      const before = a[idx] === b[idx];
      b[idx] += d;
      const after = a[idx] === b[idx];
      matches += (after ? 1 : 0) - (before ? 1 : 0);
    }
  }
  return matches === 26;
}