Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get two strings of lowercase letters, s1 and s2. Return true if s2 contains a permutation (a rearrangement) of s1 as a substring, meaning as consecutive characters. Otherwise return false.
Constraints that matter: each string has between 1 and 10⁴ characters. If s1 is longer than s2, the answer is obviously false.
Example: s1 = "ab", s2 = "eidbaooo" → true, because s2 contains "ba". With s2 = "eidboaoo" the answer is false. Both letters are there, but never side by side.
Start with brute force
The literal approach generates every permutation of s1 and searches for each one. That's m! permutations, where m = len(s1). For m = 10 that's already 3.6 million, so forget it.
A saner brute force uses the Valid Anagram idea. "Is this block a permutation of s1?" is the same as "do they have the same letter counts?" So check every block of s2 with length m: count its letters from scratch and compare with s1's counts. That's about (n − m + 1) × m steps, up to roughly 2.5·10⁷ with these limits. It passes, but each block recounts letters the previous block already counted, and with bigger inputs it would be far too slow.
Building the intuition
Look at two neighbouring blocks of length 3 in s2 = "dcda": "dcd" and "cda". They share "cd". Going from one to the next, one letter leaves on the left and one letter enters on the right. Everything else stays.
So don't recount. Keep the counts of the current block and update just those two letters. That's a fixed-size sliding window. Its length is always exactly m, and it slides one step at a time.
Now you need a quick way to answer "do the counts match?". Comparing 26 numbers each step is fine (O(26n)). But there's a neater trick, the same one Minimum Window Substring uses:
need[c]= how many copies ofcare ins1, minus how many are in the window.missing= how many ofs1's letters the window still lacks. It starts at m.
When a letter enters the window: if need[c] > 0, it fills a gap, so missing -= 1. Either way, need[c] -= 1. When a letter leaves: need[c] += 1, and if that makes need[c] > 0, you just lost a letter s1 needed, so missing += 1.
missing == 0 means the window holds every letter of s1 with enough copies. The window is also exactly m long, so it can't hold anything extra. It's a permutation.
The optimal approach
- Fill
needwith the counts ofs1. Setmissing = m. - For each
rightins2:- add
s2[right]: ifneed[c] > 0, domissing -= 1; thenneed[c] -= 1; - if
right ≥ m, removes2[right − m], which just fell out of the window:need[out] += 1, and ifneed[out] > 0, domissing += 1; - if
missing == 0, returntrue.
- add
- Return
false.
The subtle detail: need[c] can go negative. That means the window has extra copies of c. Those extras don't fill any gap, which is why missing only drops when need[c] was positive before the decrement. When a copy leaves later, missing only rises if need[c] becomes positive again, because only then has a needed copy really gone.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
m = len(s1)
need = [0] * 26 # need[c] = copies of c in s1 minus copies in the window
for c in s1:
need[ord(c) - ord('a')] += 1
missing = m # letters of s1 the window still lacks
for right in range(len(s2)):
# The window grows by s2[right]
c = ord(s2[right]) - ord('a')
if need[c] > 0:
missing -= 1 # it filled a gap; an extra copy fills nothing
need[c] -= 1
# Keep the window exactly m long: drop the letter that falls out
if right >= m:
out = ord(s2[right - m]) - ord('a')
need[out] += 1
if need[out] > 0:
missing += 1 # we just lost a letter s1 needed
# m letters with nothing missing means the same letters as s1
if missing == 0:
return True
return Falseclass Solution {
public:
bool checkInclusion(string s1, string s2) {
int m = s1.size();
int need[26] = {0}; // need[c] = copies of c in s1 minus copies in the window
for (char c : s1) need[c - 'a']++;
int missing = m; // letters of s1 the window still lacks
for (int right = 0; right < (int)s2.size(); right++) {
// The window grows by s2[right]
int c = s2[right] - 'a';
if (need[c] > 0) missing--; // it filled a gap; an extra copy fills nothing
need[c]--;
// Keep the window exactly m long: drop the letter that falls out
if (right >= m) {
int out = s2[right - m] - 'a';
need[out]++;
if (need[out] > 0) missing++; // we just lost a letter s1 needed
}
// m letters with nothing missing means the same letters as s1
if (missing == 0) return true;
}
return false;
}
};class Solution {
public boolean checkInclusion(String s1, String s2) {
int m = s1.length();
int[] need = new int[26]; // need[c] = copies of c in s1 minus copies in the window
for (char c : s1.toCharArray()) need[c - 'a']++;
int missing = m; // letters of s1 the window still lacks
for (int right = 0; right < s2.length(); right++) {
// The window grows by s2[right]
int c = s2.charAt(right) - 'a';
if (need[c] > 0) missing--; // it filled a gap; an extra copy fills nothing
need[c]--;
// Keep the window exactly m long: drop the letter that falls out
if (right >= m) {
int out = s2.charAt(right - m) - 'a';
need[out]++;
if (need[out] > 0) missing++; // we just lost a letter s1 needed
}
// m letters with nothing missing means the same letters as s1
if (missing == 0) return true;
}
return false;
}
}/**
* @param {string} s1
* @param {string} s2
* @return {boolean}
*/
var checkInclusion = function (s1, s2) {
const a = "a".charCodeAt(0);
const m = s1.length;
const need = new Array(26).fill(0); // need[c] = copies of c in s1 minus copies in the window
for (let i = 0; i < m; i++) need[s1.charCodeAt(i) - a]++;
let missing = m; // letters of s1 the window still lacks
for (let right = 0; right < s2.length; right++) {
// The window grows by s2[right]
const c = s2.charCodeAt(right) - a;
if (need[c] > 0) missing--; // it filled a gap; an extra copy fills nothing
need[c]--;
// Keep the window exactly m long: drop the letter that falls out
if (right >= m) {
const out = s2.charCodeAt(right - m) - a;
need[out]++;
if (need[out] > 0) missing++; // we just lost a letter s1 needed
}
// m letters with nothing missing means the same letters as s1
if (missing === 0) return true;
}
return false;
};Dry run
s1 = "ab" (so m = 2 and need is a: 1, b: 1), s2 = "eidbaooo". Unlisted letters have need 0 before they enter.
| right | In | Out | need after (only changed letters) | missing | Window |
|---|---|---|---|---|---|
| 0 | e | — | e: −1 | 2 | e |
| 1 | i | — | i: −1 | 2 | ei |
| 2 | d | e | d: −1, e: 0 | 2 | id |
| 3 | b | i | b: 0, i: 0 | 1 | db |
| 4 | a | d | a: 0, d: 0 | 0 | ba → true |
At step 3, b filled a gap. At step 4, a filled the last one.
Complexity
- Time: O(n + m). Counting
s1is O(m). Then each character ofs2enters once and leaves once, with O(1) work each. - Space: O(1). One array of 26 counts and one integer.
Edge cases and traps
s1longer thans2."abc"in"ab"isfalse. The loop finishes withoutmissingever reaching 0.- Repeated letters.
"aab"in"abbab"isfalse: every block of 3 there has oneaand twobs. Counts must match, not just the set of letters. - Removing before the window is full. Only remove once
right ≥ m. Removing earlier drops letters that were never fully counted. - Checking before removing. At step
right, the window must bes2[right − m + 1 .. right]. Do the add and the remove first, then check. - Sorting each window. Comparing sorted blocks works, but it costs O(n · m log m).
Say it in the interview
"A permutation of s1 is just a block of s2 with the same length and the same letter counts. So I slide a window of exactly len(s1) across s2. Each step one letter enters and one leaves, so I only update two counts. I keep need, which is s1's counts minus the window's, and a missing counter for how many of s1's letters the window still lacks. When missing hits zero the window is a permutation. That's O(n) time and O(1) space, since there are only 26 letters."
Follow-ups interviewers ask
- "Return every starting index of an anagram of s1 in s2?" That's Find All Anagrams in a String. Run the same window, but record
right − m + 1instead of returning. - "What if the window can be any size, and you want the shortest one containing all of s1's letters?" That's Minimum Window Substring. Use the same
need/missingbookkeeping with a variable window: grow untilmissing == 0, then shrink while it stays 0. - "Unicode or a large alphabet?" Use a hash map instead of 26 slots.
missingworks unchanged.
Practise the same idea
This is Day 26 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free