Skip to content

visual walkthrough

Permutation in String

MediumFixed-size Window + Frequency MapReported at: MicrosoftAppleAmazon+4

Compare frequency maps incrementally as the window slides.

Solve on LeetCode

The idea

A permutation of s1 is any window of s2 with the same length and the same letter counts. Instead of re-counting every window, update the counts as the window slides: one letter enters, one leaves.

Comparing the two small count tables each step is cheap, and the first match answers the question.

Complexity

approachtimespace
Sort every windowO(n · m log m)O(m)
Slide with countsO(n)O(1)

More walkthroughs