Skip to content

Commit 046504a

Browse files
authored
Merge pull request #3641 from austin-weeks/main
Create 0438-find-all-anagrams-in-a-string.ts
2 parents 9d31115 + a2e7866 commit 046504a

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Diff for: typescript/0438-find-all-anagrams-in-a-string.ts

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
//Time Complexity -> O(n)
2+
//Space Complexity -> O(n)
3+
function findAnagrams(s: string, p: string): number[] {
4+
if (p.length > s.length) return [];
5+
6+
const anagramIndexes: number[] = [];
7+
const pCount = new Map<string, number>();
8+
const sCount = new Map<string, number>();
9+
for (const char of p) pCount.set(char, (pCount.get(char) || 0) + 1);
10+
for (let i = 0; i < p.length; i++) sCount.set(s[i], (sCount.get(s[i]) || 0) + 1);
11+
12+
let l = 0;
13+
let r = p.length - 1;
14+
while (r < s.length) {
15+
let isAnagram = true;
16+
for (const [char, count] of pCount) {
17+
if (!sCount.has(char) || sCount.get(char) !== count) {
18+
isAnagram = false;
19+
break;
20+
}
21+
}
22+
if (isAnagram) anagramIndexes.push(l);
23+
24+
sCount.set(s[l], (sCount.get(s[l]) || 1) - 1);
25+
if (sCount.get(s[l]) === 0) sCount.delete(s[l]);
26+
l++;
27+
28+
r++;
29+
sCount.set(s[r], (sCount.get(s[r]) || 0) + 1);
30+
}
31+
32+
return anagramIndexes;
33+
}

0 commit comments

Comments
 (0)