The problem asks us to determine if any permutation of string exists in string . There are several possible intuitions for solving this problem: one is to check if every substring in is an anagram of string . We can achieve this by checking if equals . But checking it for every substring would mean a runtime of - coding this solution gives us a Leetcode TLE (Time limit exceeded error)
To optimize our approach, we use a sliding window. We maintain a window of over string and move it till the end. We also maintain a frequency map populated by characters of and their frequencies.
When we slide our window over , we update the frequencies in the map with characters of our current window.
A) reduce the frequency of a character at the right pointer by one
B) increase the frequency of a character at the left pointer by one as it leaves the window
When all the frequencies in the array hit zero, that means we have found our anagram/permutation.
Code:
Python (using Counter
object)
Java
Big O Analysis
-
Runtime The runtime complexity here is , since for each character of string s2 we would iterate over frequency array of length 26 once.
-
Memory The memory usage is . Although we are using an array, its always going to be of length 26.
— A