Permutation in String

MediumSliding Window · Fixed Size🧩 Sliding WindowLeetCode #567 ↗Updated

Problem

Given two lowercase strings s1 and s2, decide whether some rearrangement of s1 appears as a contiguous substring of s2. Return true if it does, otherwise false.
Inputs1="ab", s2="eidbaooo"Outputtrue ("ba")
Inputs1="ab", s2="eidboaoo"Outputfalse

1 ≤ |s1|, |s2| ≤ 104  ·  lowercase English letters only

Try it yourself

Java
class Solution {
    public boolean checkInclusion(String s1, String s2) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
A permutation of s1 is just a window of length |s1| with the same letter counts. Slide that window over s2 and track how many of the 26 letters currently have matching counts.
PatternSliding Window

Instinct Longest, shortest or count of contiguous subarrays/substrings meeting a rule? Grow a window on the right, shrink it on the left, never step back.

Memory hack Move like a caterpillar - the head stretches forward to grab, the tail pulls up only when the body breaks the rule.

Open the Sliding Window guide →

Approaches

Brute ForceGenerate All Permutations

Time O(n! · n · m)Space O(n2)

Recursively build every ordering of s1 (n = |s1|, m = |s2|) and test each with s2.contains(...). Stop at the first hit.

Java
public boolean checkInclusion(String s1, String s2) {
    return permute("", s1, s2);
}
private boolean permute(String prefix, String rest, String s2) {
    if (rest.isEmpty()) return s2.contains(prefix);
    for (int i = 0; i < rest.length(); i++) {
        String next = rest.substring(0, i) + rest.substring(i + 1);
        if (permute(prefix + rest.charAt(i), next, s2)) return true;
    }
    return false;
}

Factorial blow-up — already 3.6 million orderings at n = 10.

At a glance

LevelApproachTimeSpace
Brute ForceGenerate All PermutationsO(n! · n · m)O(n2)
BetterSort Every WindowO(m · n log n)O(n)
OptimalSliding Window + Matched-Letters CountO(n + m)O(1)
Common pitfalls
  • Forgetting the final zeros == 26 check after the loop — misses the last window.
  • Not returning false early when |s1| > |s2| (index out of bounds).
  • Checking s2.contains(s1) only — order of letters doesn't matter here.
Interview tips
  • Restate as “does any length-|s1| window have the same letter counts?”
  • Mention the brute force only to motivate counting instead of enumerating.
  • Two-array compare (O(26·m)) is fine to code first; then refine to the counter.
Pattern
Fixed-size sliding window + frequency counts → “does a permutation/anagram of P occur in S?”
My notes saved in this browser