Problem
Given two strings s1
and s2
, determine if s1
contains any substring that is an anagram of s2
.
An anagram is a rearrangement of all the letters of a string.
Return true
if such a substring exists, otherwise return false
.
Examples
Example 1
|
|
Example 2
|
|
Solution
We have a similar problem - Find anagrams of a string in another string. But there we have find the anagram, here we have to just check.
In case you don’t know what anagram is – check it out here - Anagram Definition.
Method 1 - Using Sliding window
Solution
Method 1 - Brute force
A basic brute force method is to generate all possible substrings of s1 with the same length as s2 and check each one for being an anagram.
One way to verify an anagram is by computing a hash for each string, such as assigning a unique prime number to each character and multiplying these primes for the hash; this allows linear-time comparison.
However, since there are O(N^2)
substrings and each check takes O(M)
, the overall time complexity is O(N^2 * M)
, which is inefficient and generally not recommended.
Method 2 - Sliding window
- An anagram of
s2
must have the same character counts ass2
. - We can use a sliding window of length equal to
s2
overs1
and compare character counts. - If any window matches, return
true
.
Approach
- If
len(s2) > len(s1)
, returnfalse
. - Count the frequency of each character in
s2
. - Use a sliding window of size
len(s2)
overs1
:- Maintain a count of characters in the current window.
- If the counts match at any point, return
true
.
- If no window matches, return
false
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(N)
where N is the length of string s1. - 🧺 Space complexity:
O(1)
(since the alphabet size is constant, e.g., 26 or 256).