Example 1
- Input
- s1 = "ab", s2 = "eidbaooo"
- Output
- true
The substring "ba" at indices 3 to 4 is a permutation of "ab".
Given strings s1 and s2, return true when some contiguous substring of s2 is a rearrangement of s1, using exactly the same multiset of characters.
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 permutations is a substring of s2.
A permutation keeps the exact multiset of letters, so the task equals asking whether some window of s2 with length s1.length has identical letter counts to s1. For s1 = "ab" and s2 = "eidbaooo" the window "ba" matches, so the answer is true.
1 <= s1.length, s2.length <= 10^4s1 and s2 consist of lowercase English letters.The substring "ba" at indices 3 to 4 is a permutation of "ab".
No length-2 window of s2 holds exactly one "a" and one "b".
The required length is 3 but the text has only 2 characters, so no candidate window exists.
The first window aaa has three a letters and no b, so it fails. The next window aab at indices 1 through 3 has exactly two a letters and one b, so it succeeds; merely finding both distinct letters would not suffice.
A permutation changes order but preserves how many copies of each letter exist. A window is a contiguous group of characters; any candidate here must have exactly m = s1.length characters. In Example 1, ab needs one a and one b, so ba succeeds even though the order differs. Counting letters avoids generating permutations. Neighbouring windows share all but their entering and departing characters, letting us update the counts instead of recounting them.
Reveal Brute Force: intuition, complexity, and code
s1.length, so only those fixed-size windows need checking.s1 is longer than s2: no window of the required size exists, so the answer is false.s1 = "a" and s2 = "a": the first window already matches and the answer is true.s2 is all one repeated letter, such as s1 = "ab" with s2 = "aaaa": counts never align and the answer is false.For anagram or permutation checks inside a string, hold one fixed-size window and update its frequency counts incrementally instead of rebuilding them.