150NeetCode 150

18.Permutation in String

MediumSliding Window ยท 4/6

Problem

Given two strings s1 and s2, return true if s2 contains a permutation of s1 as a substring, otherwise return false.

In other words, is there a contiguous block of s2 of length s1.length() that uses exactly the same letters, with the same counts, as s1?

Examples

Input:  s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains "ba" (indices 3โ€“4), which is a permutation of "ab".
Input:  s1 = "ab", s2 = "eidboaoo"
Output: false
Explanation: No length-2 window of s2 contains exactly one 'a' and one 'b'.

Constraints

  • 1 <= s1.length, s2.length <= 10^4
  • s1 and s2 consist of lowercase English letters.

๐Ÿ’ก Key Insight

Two strings are permutations of each other iff their letter-frequency vectors are equal. Since the target window has a fixed length m = s1.length(), slide a window of size m across s2: adding one character and removing one changes only two counts. Track how many of the 26 letters currently have matching counts โ€” when all 26 match, we found a permutation.

Brute Force (Sort Every Window)

TimeO(n ยท m log m)SpaceO(m)

Intuition

A window is a permutation of s1 iff sorting both gives the same string. So sort s1 once, then sort every length-m window of s2 and compare.

Algorithm

  1. If m > n, return false.
  2. Sort s1 into target.
  3. For each start i from 0 to n - m: sort s2[i..i+m-1]; if it equals target, return true.
  4. Return false.

Visualization

s1 = "ab" โ†’ sorted "ab"
s2 = "eidbaooo"

"ei"โ†’"ei" โœ—  "id"โ†’"di" โœ—  "db"โ†’"bd" โœ—  "ba"โ†’"ab" โœ“ โ†’ true

Code

java
import java.util.Arrays;

class Solution {
    public boolean checkInclusion(String s1, String s2) {
        int m = s1.length(), n = s2.length();
        if (m > n) {
            return false;
        }
        char[] target = s1.toCharArray();
        Arrays.sort(target);
        for (int i = 0; i + m <= n; i++) {
            char[] window = s2.substring(i, i + m).toCharArray();
            Arrays.sort(window); // permutations become identical once sorted
            if (Arrays.equals(window, target)) {
                return true;
            }
        }
        return false;
    }
}

Complexity

  • Time: O(n ยท m log m) โ€” n - m + 1 windows, each sorted in O(m log m).
  • Space: O(m) โ€” the copy of each window.

Complexity Comparison

Approach Time Space
Brute Force (sort windows) O(n ยท m log m) O(m)
Sliding Window + compare arrays O(26 ยท n) O(1)
Sliding Window + matches counter O(n) O(1)

Common Pitfalls

  • Generating all permutations of s1 โ€” that is O(m!) and explodes immediately.
  • Forgetting the m > n early exit; the initial loop would index past the end of s2.
  • Checking matches == 26 only inside the loop and forgetting the last window โ€” return matches == 26 after the loop.
  • In the matches update, only decrementing when counts "become unequal" without checking they were equal before โ€” that double-counts and corrupts matches.