Permutation in String solution explained
Permutation in String asks whether some contiguous block of a text is a rearrangement of a shorter pattern. Slide a window exactly as long as the pattern across the text, update the window's letter counts as one letter enters and one leaves, and report true as soon as the counts match the pattern's. With a running mismatch counter this is O(n) time.
By Evin JohnPublished 7 min read
Restating the task
You get two strings: a short pattern and a longer text. Return true if the text has a contiguous piece whose letters are the pattern's letters shuffled, with the same number of each. The piece must be exactly as long as the pattern, since a rearrangement neither adds nor drops letters. If no such piece exists, return false.
| Pattern | Text | Result | Why |
|---|---|---|---|
owl | slowly | true | The block low uses o, w and l once each |
tap | apple | false | No block of three letters contains a t |
aab | baxaba | true | The last three letters, aba, have two a and one b |
xyz | zzyyxx | false | Every letter appears, but never all three inside one block of three |
ab | a | false | The text is shorter than the pattern |
Clarify the alphabet (lowercase English letters is the usual case), whether the pattern can be empty, and whether you need a yes or no or the actual positions. The fourth example is a good one to say aloud: having the right letters somewhere in the text is not enough, they must sit together.
Why interviewers like it
The problem tests whether you can turn "same letters, any order" into "same counts", and whether you can keep those counts current without recounting each window. It often comes after an anagram check, which asks the same counting question about two whole strings, and before harder window problems where the window size is not fixed. A candidate who recounts each window gets the right answer slowly; the follow-up is always about removing that repeated work.
Start slow: sort each block
Two strings are rearrangements of each other exactly when their sorted forms are equal. So sort the pattern once, then sort every block of the text with the same length and compare. With a pattern of length m and a text of length n, there are about n blocks, and each sort costs O(m log m), for O(n × m log m) overall. It is correct and quick to write, which makes it a good opening line.
def contains_rearrangement_slow(pattern, text):
m = len(pattern)
target = sorted(pattern)
for start in range(len(text) - m + 1):
if sorted(text[start:start + m]) == target:
return True
return FalseFaster: keep the counts in step
Neighboring windows share all but two letters. When the window moves one step to the right, exactly one letter enters and exactly one leaves. So keep a count of letters in the current window, add one for the new letter, subtract one for the departing letter, and compare with the pattern's counts. Python's Counter makes that short to write. The code deletes keys that drop to zero. Recent Python versions already treat a zero count and a missing key as equal when comparing counters, but a plain dict does not, and older versions did not either, so removing them keeps the comparison safe everywhere.
from collections import Counter
def contains_rearrangement(pattern, text):
m = len(pattern)
if m > len(text):
return False
need = Counter(pattern)
have = Counter(text[:m])
if have == need:
return True
for right in range(m, len(text)):
have[text[right]] += 1
gone = text[right - m]
have[gone] -= 1
if have[gone] == 0:
del have[gone]
if have == need:
return True
return FalseComparing two counters is not free: it walks their keys. With 26 letters that is a small constant, so this version is fine in practice. If the interviewer asks for a strict O(n), track the difference between the window's counts and the pattern's counts in one table, along with how many letters currently have a nonzero difference. Each step changes two entries, and you only need to adjust the mismatch number when an entry crosses zero. When the mismatch number is zero, the window is a match.
function containsRearrangement(pattern, text) {
const m = pattern.length;
if (m > text.length) return false;
const diff = new Map(); // count in window minus count in pattern
let off = 0; // letters whose diff is not zero
const bump = (ch, d) => {
const before = diff.get(ch) || 0;
const after = before + d;
if (before === 0) off++;
if (after === 0) off--;
diff.set(ch, after);
};
for (const ch of pattern) bump(ch, -1);
for (let i = 0; i < text.length; i++) {
bump(text[i], 1);
if (i >= m) bump(text[i - m], -1);
if (i >= m - 1 && off === 0) return true;
}
return false;
}Reading the JavaScript: diff starts as minus the pattern's counts. Each new text letter adds one, and once the window is longer than the pattern the letter that falls out subtracts one. off counts letters whose difference is not zero, and bump updates it whenever an entry leaves or reaches zero. The check starts once the first full window is in place, at index m - 1.
Complexity side by side
| Approach | Time | Extra space |
|---|---|---|
| Sort every window | O(n × m log m) | O(m) |
| Recount every window | O(n × m) | O(alphabet) |
| Sliding counter with full comparison | O(n × alphabet) | O(alphabet) |
| Difference table with mismatch counter | O(n + m) | O(alphabet) |
Cases worth running
- Pattern longer than the text: return false before building anything.
- Match in the very first window: the code must check before the slide starts.
- Match in the very last window: off-by-one errors in the loop bound usually show up here.
- Repeated letters in the pattern, such as
aab: a set-based check would wrongly acceptabb. - Pattern and text identical: true.
Typical mistakes
- Using sets instead of counts, which ignores how many times each letter appears.
- Leaving zero entries in a plain dictionary of counts, so equal windows compare as unequal. Older Python Counters behaved the same way.
- Removing the departing letter before checking the first full window, which skips it.
- Generating every permutation of the pattern and searching for each. That is factorial time and the interviewer will stop you.
- Calling the Counter comparison O(1) without qualification. It is O(alphabet), which is small but not nothing.
Follow-ups you may hear
- Return every start index where a rearrangement begins. Same window; append the start instead of returning.
- The alphabet is all of Unicode. Use a hash map for the difference table; the logic is unchanged.
- Smallest window that contains the pattern's letters, with extras allowed. The window size is no longer fixed, so it becomes a grow-and-shrink window.
- Many patterns against one text. Precompute windows per pattern length, or hash each window's counts.
Talking through it
Fictional example
- Candidate
- A rearrangement keeps the same letters with the same counts, so I'm really looking for a block of length m whose counts equal the pattern's.
- Candidate
- Each step one letter enters and one leaves, so I update two counts instead of recounting. I track how many letters disagree with the pattern, and when that hits zero I've found a match.
- Candidate
- That is linear in the text plus the pattern, with a table sized by the alphabet. I'll test the first window, the last window and a pattern with a repeated letter.
Keep going
Longest Repeating Character Replacement keeps a similar count table but lets the window grow. Longest Substring Without Repeating Characters is another variable window with a different shrink rule, and Top K Frequent Elements practices counting with a dictionary. The stack side of this set starts with Min Stack, and the coding problems hub groups everything by pattern.
Natively during practice
Natively, a desktop app for Mac and Windows, can read this problem from a screenshot while you practice and nudge you from sorting toward counting, or explain the mismatch counter if the JavaScript above looks dense. Because it transcribes the session, you can scroll back afterward and see whether you mentioned the first-window check before you coded it. The AI interview assistant page covers how practice sessions work.
Questions people ask
How do you solve Permutation in String efficiently?
Slide a window as long as the pattern across the text. Update letter counts as one letter enters and one leaves, and return true when the window's counts equal the pattern's. Tracking how many letters disagree makes each step O(1).
What is the time complexity of Permutation in String?
O(n + m) with a difference table and a mismatch counter, where n is the text length and m the pattern length. Comparing two full count tables at each step is O(n times the alphabet size), still fast for 26 letters.
Why not generate every permutation of the pattern?
A pattern of length m has up to m factorial orderings, which explodes quickly. Two strings are rearrangements of each other exactly when their letter counts match, so counting is enough.
Is Permutation in String the same as Find All Anagrams in a String?
They use the same fixed-size window. Permutation in String stops at the first match and returns true; the anagram-finding version keeps sliding and collects every start index.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
