Permutation in String
Medium
Topics
Given two strings s1 and s2, return true if s2 contains a permutation of s1 as a contiguous substring. (Here the first line is s1, the second is s2.)
Example 1
pattern
search
a permutation of ab
A shaded stretch is a window of
eidbaooo holding exactly the letters of ab in some order, starting at index 3 — so the answer is true. Re-sorting each window would cost n·k log k; instead the window’s letter counts take one add and one remove per step, making the scan linear.Top row is the pattern; bottom row is the string being searched.
Input: s1 = "ab", s2 = "eidbaooo" Output: true
Example 2
pattern
search
a permutation of ab
Input: s1 = "ab", s2 = "eidboaoo" Output: false
Constraints
- 1 <= s1.length, s2.length <= 10^4
- s1 and s2 consist of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A permutation of s1 is any window of s2 with the same letter counts as s1. Slide a fixed-size window (length |s1|) over s2 and compare frequency vectors.
Approach
- Build the 26-length count of s1 and of the first window of s2.
- Slide the window one char at a time, updating counts in O(1).
- Return true whenever the counts match.
Dry Run
s = "ab", t = "eidbaooo"
need = {a:1, b:1}. The window is a fixed width of len(s) = 2 that slides.
i=0 add e window {e:1}
i=1 add i window {e:1, i:1}
i=2 add d, evict e window {d:1, i:1}
i=3 add b, evict i window {b:1, d:1}
i=4 add a, evict d window {a:1, b:1} == need -> true
answer true
The eviction at `i >= len(s)` is what makes this a window rather than a growing
prefix. Remove it and the counts only ever increase, so once the window is wider
than s they can never equal `need` again -- this input then returns false, missing
the permutation at index 3.
Comparing two 26-element lists looks expensive inside a loop and is not: 26 is a
constant, so the whole scan is O(26n) = O(n). The alternative, sorting each
window and comparing strings, would be O(n k log k) -- asymptotically worse for
exactly the reason that looks like a micro-optimisation here.
Order never matters to the test. A permutation is a multiset, so counts are
precisely the right representation and nothing about position is tracked.Complexity
- Time — O(n): each character enters and leaves the window once; comparison is O(26).
- Space — O(1): two fixed 26-length arrays.
Common Pitfalls
- The window has to shrink. Without the removal at
i - len(s)the counts only ever grow, so after the window is full they can never match again and a permutation later in the string is missed. - Comparing two 26-element lists is O(26), a constant, which is what keeps this O(n). Comparing sorted substrings instead would be O(n k log k).
Full Solution — all languages
class Solution:
def checkInclusion(self, s, t):
if len(s)>len(t): return False
need=[0]*26; win=[0]*26
for c in s: need[ord(c)-97]+=1
for i,c in enumerate(t):
win[ord(c)-97]+=1
if i>=len(s): win[ord(t[i-len(s)])-97]-=1
if win==need: return True
return Falseimport java.util.*;
class Solution {
public boolean checkInclusion(String s, String t) {
if(s.length()>t.length())return false;
int[] need=new int[26],win=new int[26];
for(char c:s.toCharArray())need[c-'a']++;
for(int i=0;i<t.length();i++) {
win[t.charAt(i)-'a']++;
if(i>=s.length())win[t.charAt(i-s.length())-'a']--;
if(i>=s.length()-1&&Arrays.equals(win,need))return true;
}
return false;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool checkInclusion(string s, string t) {
if(s.size()>t.size())return false;
vector<int> need(26,0),win(26,0);
for(char c:s)need[c-'a']++;
for(int i=0;i<(int)t.size();i++) {
win[t[i]-'a']++;
if(i>=(int)s.size())win[t[i-s.size()]-'a']--;
if(i>=(int)s.size()-1&&win==need)return true;
}
return false;
}
};/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/ var checkInclusion = function(s, t) {
if(s.length>t.length)return false;
const need=new Array(26).fill(0),win=new Array(26).fill(0);
for(const c of s)need[c.charCodeAt(0)-97]++;
for(let i=0;i<t.length;i++) {
win[t.charCodeAt(i)-97]++;
if(i>=s.length)win[t.charCodeAt(i-s.length)-97]--;
if(i>=s.length-1) {
let ok=true;
for(let j=0;j<26;j++)if(win[j]!==need[j]) {
ok=false;
break;
}
if(ok)return true;
}
}
return false;
};
Asked at
Databricks