Skip to content
Veltoryx Technologies
FreeProblem 29● MediumLeetCode #567 ↗4 min readUpdated 30 October 2026

Permutation in String

Check whether any contiguous substring of s2 is an anagram permutation of s1 using a fixed sliding window of character frequencies.

01The problem

Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. In other words, return true if one of s1's permutations is a contiguous substring of s2.

InputOutputWhy
s1 = "ab", s2 = "eidbaooo"trues2 contains substring "ba" which is a permutation of "ab"
s1 = "ab", s2 = "eidboaoo"falseNone of the length-2 substrings equal "ab" or "ba"
s1 = "a", s2 = "a"trueExact single-letter match
s1 = "adc", s2 = "dcda"trueSubstring "cda" at the end is an anagram of "adc"

Constraints: 1 to 10,000 characters, lowercase English letters only.

02How to spot it

  • Looking for a substring of s2 that has the same characters and counts as s1.
  • The candidate substring length is fixed at s1.length().
  • Two strings are permutations of each other if and only if their 26-letter frequency counts match.

So: fixed-size sliding window with frequency counts.

03Pseudocode

text
need = counts of s1
win = counts of first n chars of s2
if need == win: return true
for i from n to len(s2) - 1:
  win[s2[i]] += 1
  win[s2[i - n]] -= 1
  if need == win: return true
return false
  1. Count the letters of s1.
  2. Slide a window of size len(s1) across s2.
  3. If window counts match need at any position, return true.

04Watch it work

Visualizer · step through the algorithms1 = "ab", s2 = "eidbaooo"
e0
i1
d2
b3
a4
o5
o6
o7
LR

Count letters of s1 ("ab") and initialize window of size 2 on s2: "ei".

Pseudocode

  1. need = counts of s1
  2. win = counts of first n chars of s2
  3. if need == win: return true
  4. for i from n to len(s2) - 1:
  5. win[s2[i]] += 1
  6. win[s2[i - n]] -= 1
  7. if need == win: return true
  8. return false

Variables

n
2
window
ei
step 1 / 6

05Step-by-step dry run

  1. 1
    e0
    i1
    d2
    b3
    a4
    o5
    o6
    o7
    LR

    Count letters of s1 ("ab") and initialize window of size 2 on s2: "ei".

    n = 2window = ei

  2. 2
    e0
    i1
    d2
    b3
    a4
    o5
    o6
    o7
    LR

    First window "ei" does not match s1 counts. Slide window right.

    match = false

  3. 3
    e0
    i1
    d2
    b3
    a4
    o5
    o6
    o7
    LR

    Slide window to [1..2]: add 'd', drop 'e'. Current window: "id".

    start = 1i = 2window = id

  4. 4
    e0
    i1
    d2
    b3
    a4
    o5
    o6
    o7
    LR

    Slide window to [2..3]: add 'b', drop 'i'. Current window: "db".

    start = 2i = 3window = db

  5. 5
    e0
    i1
    d2
    b3
    a4
    o5
    o6
    o7
    LR

    Slide window to [3..4]: add 'a', drop 'd'. Current window: "ba".

    start = 3i = 4window = ba

  6. 6
    e0
    i1
    d2
    b3
    a4
    o5
    o6
    o7
    LR

    Window "ba" has identical letter counts to "ab". Return true.

    result = true

06Java solution

PermutationInString.java
import java.util.Arrays;

public class PermutationInString {
    public static boolean checkInclusion(String s1, String s2) {
        int n = s1.length(), m = s2.length();
        if (n > m) return false;
        int[] need = new int[26], win = new int[26];
        for (int i = 0; i < n; i++) {
            need[s1.charAt(i) - 'a']++;
            win[s2.charAt(i) - 'a']++;
        }
        if (Arrays.equals(need, win)) return true;
        for (int i = n; i < m; i++) {
            win[s2.charAt(i) - 'a']++; // entering char
            win[s2.charAt(i - n) - 'a']--; // leaving char
            if (Arrays.equals(need, win)) return true;
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println(checkInclusion("ab", "eidbaooo"));
        System.out.println(checkInclusion("ab", "eidboaoo"));
        System.out.println(checkInclusion("a", "a"));
        System.out.println(checkInclusion("adc", "dcda"));
    }
}
Expected output
true
false
true
true

Tricky lines, decoded

  • c - 'a': Normalizes 'a'–'z' to indices 0–25.
  • Arrays.equals(need, win): Performs 26 integer comparisons. Because the alphabet size is constant (26), each comparison runs in O(1) time.

07Why it works

Two strings are permutations of each other if and only if every character appears with the exact same frequency. Since any permutation of s1 must have length n = s1.length(), only windows of length n in s2 can possibly match. Sliding a window of size n by adding one character on the right and removing one on the left lets us check all m - n + 1 candidates in a single pass.

Invariant: win holds the frequency counts of s2[i - n + 1 .. i].

08Time and space

  • Time: O(26 · m). There are m - n + 1 windows, and each check compares 26 integers.
  • Space: O(1). Two fixed arrays of length 26.

09Edge cases

InputOutputWhy it matters
s1 = "a", s2 = "a"trueSingle character match
s1 = "abc", s2 = "ab"falses1 is longer than s2
s1 = "adc", s2 = "dcda"trueMatch occurs at the very end of s2
s1 = "aa", s2 = "aba"falseCharacter counts must match exactly
s1 = "hello", s2 = "ooolleoooleh"falseRequired characters spread out non-contiguously

10Common mistakes

  • Generating permutations. Generating all n! permutations of s1 will cause a Time Limit Exceeded error even for n = 10. Always compare character frequencies instead.
  • Sorting every window. Extracting and sorting each substring costs O(m · n log n), which is far too slow for 10,000 characters.
  • Skipping the initial check. Failing to check Arrays.equals(need, win) before entering the slide loop misses matches located at index 0.

11Other approaches

ApproachTimeSpaceUse when
Generate permutationsO(n! · m)O(n)Never
Sort every windowO(m · n log n)O(n)Tiny strings only
Sliding countsO(26 · m)O(1)Default interview answer
Counts + matches counterO(m)O(1)Strict linear time without factor 26

12In the interview

  • Return all match locations? This is Problem 30 (Find All Anagrams in a String): instead of returning true at the first match, collect all start indices i - n + 1.
  • Unicode support? Replace the int[26] array with a HashMap<Character, Integer> and maintain a match count of distinct characters.

13Check your understanding

Quiz · 2 questions

0 of 2 answered

  1. 1. Why is comparing character frequency arrays sufficient to detect a permutation?

  2. 2. What happens if we forget the check before the slide loop?

14Solve it yourself

Try it on LeetCode #567.