Sponsored
Sponsored
This approach utilizes a sliding window technique combined with character count comparisons to efficiently find all anagrams of the string p
within the string s
. By maintaining a window of length equal to p
as we iterate through s
, and by checking the frequency of characters within this window with the frequency of characters in p
, we can determine if the substring is an anagram.
Time Complexity: O(n) where n is the length of s
, because we iterate over `s` once.
Space Complexity: O(1) since the size of the character frequency array is fixed with respect to the alphabet.
1def findAnagrams(s, p):
2 from collections import Counter
3 p_count = Counter(p)
4 s_count = Counter(s[:len(p) - 1])
5 result = []
6
7 for i in range(len(p) - 1, len(s)):
8 s_count[s[i]] += 1 # Include the new character in the window
9 if s_count == p_count: # Compare window with p
10 result.append(i - len(p) + 1) # Append the start index
11 s_count[s[i - len(p) + 1]] -= 1 # Remove the character sliding out of the window
12 if s_count[s[i - len(p) + 1]] == 0:
13 del s_count[s[i - len(p) + 1]] # Clean up the count dictionary
14
15 return result
This Python solution initializes a counter for the string p
and a sliding window counter for s
of length equivalent to p
. As the window slides over s
, we update the count of characters within this window. If the window's character frequency matches with that of p
, it implies an anagram is found and we record the starting index.
This approach leverages hashmaps (or dictionaries) and a two-pointer technique to find the anagrams of p
in s
. We maintain counts of characters using hashmaps and adjust them as the two pointers traverse through s
.
Time Complexity: O(n) where n is the length of `s`.
Space Complexity: O(1) if considering character frequency hashmaps to have at most 26 entries.
1#include <vector>
2#include <string>
3#include <unordered_map>
4using namespace std;
5
6vector<int> findAnagrams(string s, string p) {
unordered_map<char, int> p_count, s_count;
vector<int> result;
int pl = p.size(), sl = s.size();
if (pl > sl) return result;
for (int i = 0; i < pl; i++) {
p_count[p[i]]++;
s_count[s[i]]++;
}
for (int i = pl; i < sl; i++) {
if (p_count == s_count) {
result.push_back(i - pl);
}
s_count[s[i]]++;
s_count[s[i - pl]]--;
if (s_count[s[i - pl]] == 0) {
s_count.erase(s[i - pl]);
}
}
if (p_count == s_count) {
result.push_back(sl - pl);
}
return result;
}
This C++ solution uses unordered maps to count occurrences of characters in both p
and the sliding window within s
. We first count characters in the initial window and then slide the window through s
. During each step, we update the counts by adding the new character and removing the old one (left behind) and check if the current window matches the character count of p
.