Permutation In String
MediumNeetCode 150 Sliding WindowProblem
You are given two lowercase strings s1 and s2. Return true if some
contiguous piece of s2 is a rearrangement of s1, meaning it uses exactly the same
letters the same number of times. Otherwise return false.
Constraints
- 1 ≤ s1.length, s2.length ≤ 10⁴
- s1 and s2 have only lowercase English letters
Examples: pick one to animate
Solutions
TimeO(n)
SpaceO(1)
Time: The window slides once across s2. Each step adds one letter, drops one letter and compares two tables of 26 numbers, which is constant work.
Space: Two count tables of 26 slots each, independent of the input length.
Two strings are rearrangements of each other exactly when their letter counts are equal. Count
s1 once. Then slide a window of length len(s1) over s2: add the new letter,
drop the one that fell off the left, and compare the two count tables.