File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments