Permutation in String - Problem
Given two strings s1 and s2, determine if s2 contains any permutation of s1 as a substring. A permutation is any rearrangement of the characters in a string.
What is a permutation? A permutation of a string is formed by rearranging its characters. For example, "abc" has 6 permutations: "abc", "acb", "bac", "bca", "cab", "cba".
Your task: Return true if any substring of s2 is a permutation of s1, otherwise return false.
Key insight: Instead of generating all permutations, we can check if any substring of s2 has the same character frequencies as s1.
Input & Output
example_1.py โ Basic permutation found
$
Input:
s1 = "ab", s2 = "eidbaooo"
โบ
Output:
true
๐ก Note:
s2 contains "ba" which is a permutation of s1 = "ab"
example_2.py โ No permutation exists
$
Input:
s1 = "ab", s2 = "eidboaoo"
โบ
Output:
false
๐ก Note:
No substring of s2 is a permutation of s1. "bo", "oa", "ao", "oo" don't match "ab"
example_3.py โ Longer pattern
$
Input:
s1 = "adc", s2 = "dcda"
โบ
Output:
true
๐ก Note:
s2 contains "dcd" + "a" = "dcda", but looking at substrings of length 3: "dcd" is not a permutation, but "cda" is a permutation of "adc"
Constraints
- 1 โค s1.length, s2.length โค 104
- s1 and s2 consist of lowercase English letters only
- Time limit: 1 second per test case
Visualization
Tap to expand
Understanding the Visualization
1
Setup Recipe
Count required ingredients from s1: {a: 1, b: 1}
2
First Measurement
Check first window 'ei': {e: 1, i: 1} - doesn't match
3
Slide Window
Move to 'id': remove 'e', add 'd' โ {i: 1, d: 1}
4
Continue Sliding
Move to 'db': remove 'i', add 'b' โ {d: 1, b: 1}
5
Found Match!
Move to 'ba': remove 'd', add 'a' โ {b: 1, a: 1} โ
Key Takeaway
๐ฏ Key Insight: Use sliding window with frequency maps to achieve O(n) time complexity instead of generating all permutations!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code