DSA Visualizer · 25 visualizationsPermutation in String
MediumSliding Window

Permutation in String

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 a substring of s2.

s1 = "ab", s2 = "eidbaooo"Step 1 of 10
e
0
i
1
d
2
b
3
a
4
o
5
o
6
o
7
need
a:1
b:1

Count the letters needed: a:1, b:1. Slide a window of length 2 across s2.

Pythontime O(n) (26 is a constant factor) · space O(26)
1def checkInclusion(s1, s2):
2 need = [0] * 26
3 window = [0] * 26
4 for ch in s1:
5 need[ord(ch) - ord('a')] += 1
6 n = len(s1)
7 for right in range(len(s2)):
8 window[ord(s2[right]) - ord('a')] += 1
9 left = right - n + 1
10 if left > 0:
11 window[ord(s2[left - 1]) - ord('a')] -= 1
12 if left >= 0 and window == need:
13 return True
14 return False
Variables
l—
r—
matchfalse

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 a substring of s2.

Examples

Input: s1 = "ab", s2 = "eidbaooo"Output: true

s2 contains "ba", which is a permutation of s1

Input: s1 = "ab", s2 = "eidboaoo"Output: false

Constraints

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

Intuition

A permutation of s1 appearing in s2 just means some window of s2, exactly s1's length, has the *same letter counts* as s1 — order doesn't matter. So slide a fixed-size window of length s1.length across s2, keeping a running letter count for the window, and compare it to s1's letter count at every position.

Brute force → Optimal

Brute force

Generate every permutation of s1 and check whether each is a substring of s2.

Time O(n! × n)Space O(n!)
Optimal

Fixed-size sliding window with a 26-letter count array for the window, compared against s1's count array as the window slides.

Time O(n) (26 is a constant factor)Space O(26)

Complexity

Time O(n) (26 is a constant factor)Space O(26)

Edge cases

  • s1 longer than s2: no window of that size fits, so the answer is false.
  • s1 equals s2: the only possible window is the whole string, and it trivially matches itself.

Common mistakes

  • Recomputing the window's full letter count from scratch at every position instead of removing the outgoing character and adding the incoming one.
  • Comparing sorted substrings at every window position, which is correct but needlessly expensive compared to count arrays.
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free