Permutation in String - Problem

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's permutations is the substring of s2.

A permutation is a rearrangement of characters. For example, "abc" has permutations "abc", "acb", "bac", "bca", "cab", and "cba".

Input & Output

Example 1 — Basic Permutation Found
$ Input: s1 = "ab", s2 = "eidbaooo"
Output: true
💡 Note: s2 contains "ba" which is a permutation of "ab" (same characters: a=1, b=1)
Example 2 — No Permutation
$ Input: s1 = "ab", s2 = "eidboaoo"
Output: false
💡 Note: No substring of s2 with length 2 has the same character frequencies as "ab"
Example 3 — Exact Match
$ Input: s1 = "adc", s2 = "dcda"
Output: true
💡 Note: s2 contains "dcd" which has characters d=2, c=1 but "adc" has a=1, d=1, c=1. Actually "cda" has c=1, d=1, a=1 which matches "adc"

Constraints

  • 1 ≤ s1.length, s2.length ≤ 104
  • s1 and s2 consist of lowercase English letters.

Visualization

Tap to expand
Permutation in String INPUT s1 = "ab" a b s2 = "eidbaooo" e i d b a o o o Green = permutation "ba" s1 Character Count: a: 1 b: 1 Window size = len(s1) = 2 Find permutation in s2 ALGORITHM STEPS 1 Count s1 chars Build frequency map 2 Sliding Window Size = len(s1) = 2 3 Update Window Add right, remove left 4 Compare Counts Match = permutation found Window Slides: [ei] X [id] X [db] X [ba] OK [ao] X [oo] X "ba" matches {a:1, b:1} FINAL RESULT Permutation Found at Index 3 e i d b a o o "ba" Output: true "ba" is a permutation of "ab" found in s2 Complexity: Time: O(n) Space: O(1) - 26 chars Key Insight: Use sliding window of size len(s1) and compare character frequency counts. Two strings are permutations if they have identical character frequencies. Only need to track 26 letters, making space O(1) and comparison O(1). TutorialsPoint - Permutation in String | Optimal Solution (Sliding Window)
Asked in
Facebook 45 Microsoft 38 Google 32
89.0K Views
High Frequency
~25 min Avg. Time
2.2K 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