File tree 1 file changed +34
-0
lines changed
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 15
15
16
16
return false
17
17
} ;
18
+
19
+ // another
20
+
21
+ /**
22
+ * @param {string[] } dict
23
+ * @return {boolean }
24
+ */
25
+ const differByOne = function ( dict ) {
26
+ const M = dict . length ,
27
+ N = dict [ 0 ] . length
28
+ const hash = Array ( M ) . fill ( 0 ) ,
29
+ ord = ( c ) => c . charCodeAt ( 0 ) ,
30
+ MOD = 1e13 , seen = new Set ( )
31
+ // 1. generate each i-th rolling hash
32
+ for ( let i = 0 ; i < M ; ++ i ) {
33
+ let base = 1
34
+ for ( let j = 0 ; j < N ; ++ j ) {
35
+ hash [ i ] = ( hash [ i ] + base * ord ( dict [ i ] [ j ] ) ) % MOD
36
+ base = ( 123 * base ) % MOD
37
+ }
38
+ }
39
+ // 2. remove each j-th char from each i-th rolling hash to 🔍 find a diff collision 💥
40
+ for ( let i = 0 ; i < M ; ++ i ) {
41
+ let base = 1
42
+ for ( let j = 0 ; j < N ; ++ j ) {
43
+ const diff = ( hash [ i ] - base * ord ( dict [ i ] [ j ] ) ) % MOD
44
+ if ( seen . has ( diff ) ) return true // 🎯 found a diff collision 💥
45
+ seen . add ( diff )
46
+ base = ( 123 * base ) % MOD
47
+ }
48
+ }
49
+ return false
50
+ }
51
+
You can’t perform that action at this time.
0 commit comments