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
Sliding Window: Finding PermutationTarget: s1 = "ab" โ†’ Need: {a: 1, b: 1}eidbaoooba{b: 1, a: 1} โœ“ MATCH!Window slides right, updating frequencies: O(1) per step
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!
Asked in
Facebook 45 Microsoft 38 Amazon 32 Google 28
52.4K Views
High Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen