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.
1function findAnagrams(s, p) {
2 const pCount = new Array(26).fill(0);
3 const sCount = new Array(26).fill(0);
4 const result = [];
5 const aCharCode = 'a'.charCodeAt(0);
6
7 for (const char of p) {
8 pCount[char.charCodeAt(0) - aCharCode]++;
9 }
10
11 for (let i = 0; i < s.length; i++) {
12 sCount[s[i].charCodeAt(0) - aCharCode]++;
13
14 if (i >= p.length) {
15 sCount[s[i - p.length].charCodeAt(0) - aCharCode]--;
16 }
17
18 if (arraysEqual(pCount, sCount)) {
19 result.push(i - p.length + 1);
20 }
21 }
22 return result;
23}
24
25function arraysEqual(arr1, arr2) {
26 for (let i = 0; i < 26; i++) {
27 if (arr1[i] !== arr2[i]) return false;
28 }
29 return true;
30}
This JavaScript solution uses two frequency arrays to keep count of the characters in p
and a sliding window in s
. The window size is maintained to be the length of p
. As the window slides through s
, we check if the two frequency arrays (for the window and p
) are equal, indicating an anagram found.
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.
1import java.util.*;
2
3
This Java approach employs two arrays to store the frequency of each character. We iterate over s
with a sliding window of size equal to p
, updating these arrays accordingly. If both frequency arrays match at any point, it indicates the presence of an anagram.