22 * @param {string } s
33 * @return {string[] }
44 */
5- var findRepeatedDnaSequences = function ( s ) {
6- let set = new Set ( ) ;
7- let result = new Set ( ) ;
8- for ( let i = 0 ; i <= s . length - 10 ; i ++ ) {
9- let str = s . substring ( i , i + 10 )
10- set . has ( str ) ? result . add ( str ) : set . add ( str )
5+ function findRepeatedDnaSequences ( s ) {
6+ // if s.length < 10 there can't be a 10 character sequence in it
7+ if ( s . length < 10 ) return [ ] ;
8+ const charCode = {
9+ A : 1 ,
10+ C : 2 ,
11+ G : 3 ,
12+ T : 4 ,
13+ } ;
14+ const hashMap = new Map ( ) ;
15+ let rollingHash = 0 ;
16+
17+ // calculate the rolling hash for the first 9 characters
18+ for ( let i = 0 ; i < 9 ; i ++ ) {
19+ rollingHash = rollingHash * 5 + charCode [ s [ i ] ] ;
20+ }
21+
22+ const result = [ ] ;
23+
24+ for ( let i = 9 ; i < s . length ; i ++ ) {
25+ // rolling hash for the 10 character window
26+ // s[i - 9 : i]
27+ rollingHash = rollingHash * 5 + charCode [ s [ i ] ] ;
28+
29+ if ( ! hashMap . has ( rollingHash ) ) {
30+ // if seeing hash the first time
31+ // add it to result the next time you see it
32+ hashMap . set ( rollingHash , true ) ;
33+ } else if ( hashMap . get ( rollingHash ) ) {
34+ // if seen hash once before add it to result
35+ result . push ( s . slice ( i - 9 , i + 1 ) ) ;
36+ // and do not add it next time you see it
37+ hashMap . set ( rollingHash , false ) ;
1138 }
12- return [ ...result ]
13- } ;
39+
40+ // rolling hash for the 9 character window
41+ // s[i - 8 : i]
42+ rollingHash -= charCode [ s [ i - 9 ] ] * Math . pow ( 5 , 9 ) ;
43+ }
44+
45+ return result ;
46+ }
0 commit comments