Skip to content

Commit 434170a

Browse files
authored
Update 1554-strings-differ-by-one-character.js
1 parent c58ad69 commit 434170a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

1554-strings-differ-by-one-character.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,37 @@
1515

1616
return false
1717
};
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+

0 commit comments

Comments
 (0)