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.
| Input | Output | Why |
|---|---|---|
s1 = "ab", s2 = "eidbaooo" | true | s2 contains substring "ba" which is a permutation of "ab" |
s1 = "ab", s2 = "eidboaoo" | false | None of the length-2 substrings equal "ab" or "ba" |
s1 = "a", s2 = "a" | true | Exact single-letter match |
s1 = "adc", s2 = "dcda" | true | Substring "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
s2that has the same characters and counts ass1. - 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
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- Count the letters of
s1. - Slide a window of size
len(s1)acrosss2. - If window counts match
needat any position, returntrue.
04Watch it work
Count letters of s1 ("ab") and initialize window of size 2 on s2: "ei".
Pseudocode
- 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
Variables
- n
- 2
- window
- ei
05Step-by-step dry run
- 1e0i1d2b3a4o5o6o7LR
Count letters of s1 ("ab") and initialize window of size 2 on s2: "ei".
n = 2window = ei
- 2e0i1d2b3a4o5o6o7LR
First window "ei" does not match s1 counts. Slide window right.
match = false
- 3e0i1d2b3a4o5o6o7LR
Slide window to [1..2]: add 'd', drop 'e'. Current window: "id".
start = 1i = 2window = id
- 4e0i1d2b3a4o5o6o7LR
Slide window to [2..3]: add 'b', drop 'i'. Current window: "db".
start = 2i = 3window = db
- 5e0i1d2b3a4o5o6o7LR
Slide window to [3..4]: add 'a', drop 'd'. Current window: "ba".
start = 3i = 4window = ba
- 6e0i1d2b3a4o5o6o7LR
Window "ba" has identical letter counts to "ab". Return true.
result = true
06Java solution
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"));
}
}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 + 1windows, and each check compares 26 integers. - Space: O(1). Two fixed arrays of length 26.
09Edge cases
| Input | Output | Why it matters |
|---|---|---|
s1 = "a", s2 = "a" | true | Single character match |
s1 = "abc", s2 = "ab" | false | s1 is longer than s2 |
s1 = "adc", s2 = "dcda" | true | Match occurs at the very end of s2 |
s1 = "aa", s2 = "aba" | false | Character counts must match exactly |
s1 = "hello", s2 = "ooolleoooleh" | false | Required characters spread out non-contiguously |
10Common mistakes
- Generating permutations. Generating all
n!permutations ofs1will 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
| Approach | Time | Space | Use when |
|---|---|---|---|
| Generate permutations | O(n! · m) | O(n) | Never |
| Sort every window | O(m · n log n) | O(n) | Tiny strings only |
| Sliding counts | O(26 · m) | O(1) | Default interview answer |
| Counts + matches counter | O(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
trueat the first match, collect all start indicesi - n + 1. - Unicode support? Replace the
int[26]array with aHashMap<Character, Integer>and maintain a match count of distinct characters.
13Check your understanding
Quiz · 2 questions
0 of 2 answered
1. Why is comparing character frequency arrays sufficient to detect a permutation?
2. What happens if we forget the check before the slide loop?
14Solve it yourself
Try it on LeetCode #567.