I am going to use two examples related with Sliding window algorithm to explain this concept.
Find All Anagrams in a String:
Given a string s and a nonempty string p, find all the start indices of p’s anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
Input:
s: “cbaebabacd” p: “abc”
Output:
[0, 6]
Explanation:
The substring with start index = 0 is “cba”, which is an anagram of “abc”.
The substring with start index = 6 is “bac”, which is an anagram of “abc”.
Here is the Python code of this problem:


Firstly, we need to use collections.Counter(p)
to calculate the frequency of letter in string p
. Then “i” can be considered as the right side of the “window”. “count” means the number of letters to complete the substring.
when cp[s[i]] >= 1
, the current letter can consist this substring, so we are closer to the final substring, and we can decrease count(count = 1
).
The important thing is cp[s[i]]
should minus one as well, because in this substring, we have used one in the cp. (If the letter does not exist in the cp, the value of that letter should be <0).
Then when i >= lp
, we increase i each time, that means we will add one to the previous substring and pop the first element of the previous substring. There will be some possibility that the letter we pop out is the one we need. So when this happen, we need to count += 1
, because we pop out the first element. We need to add that back to the cp which is cp[s[iip]]
.
Minimum Window Substring
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S = “ADOBECODEBANC”
T = “ABC”
Minimum window is “BANC”.
Note:
If there is no such window in S that covers all characters in T, return the empty string “”.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
Here is the Python code of this problem:


The idea I need to highlight is Line 30 to Line 33, when ct[s[left]] == 0
, count should add one. The reason is when we pop out this number, the remainder should be 1, and just because of this action, the substring is not complete now, and we need to search another one to fill in this hole.