Skip to content

Commit 44042f9

Browse files
committed
fix: Rabin-Karp missed matches at index 0 and with long patterns
1 parent 5c39e87 commit 44042f9

2 files changed

Lines changed: 34 additions & 4 deletions

File tree

‎Search/RabinKarp.js‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,23 @@ function rabinKarpSearch(text, pattern) {
2626
// Calculate the hash of the first substring in the text
2727
hashText[0] = hash(text, patternLength)
2828

29-
// Precompute BASE^(patternLength-1) % MOD
30-
const basePow = Math.pow(BASE, patternLength - 1) % MOD
29+
// Precompute BASE^(patternLength-1) % MOD step by step, so that it stays exact
30+
// (Math.pow loses precision once BASE^(patternLength-1) exceeds 2^53)
31+
let basePow = 1
32+
for (let i = 1; i < patternLength; i++) {
33+
basePow = (basePow * BASE) % MOD
34+
}
35+
36+
// The first window (index 0) has to be checked as well
37+
if (
38+
textLength >= patternLength &&
39+
hashText[0] === hashPattern &&
40+
text.substring(0, patternLength) === pattern
41+
) {
42+
indices.push(0)
43+
}
3144

32-
for (let i = 1; i <= textLength - patternLength + 1; i++) {
45+
for (let i = 1; i <= textLength - patternLength; i++) {
3346
// Update the rolling hash by removing the first character
3447
// and adding the next character in the text
3548
hashText[i] =

‎Search/test/RabinKarp.test.js‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ describe('Rabin-Karp Search', function () {
1313
it('should handle multiple occurrences of the pattern', function () {
1414
const text = 'ABABABABABAB'
1515
const pattern = 'ABAB'
16-
const expected = [2, 4, 6, 8]
16+
const expected = [0, 2, 4, 6, 8]
1717

1818
const result = rabinKarpSearch(text, pattern)
1919
expect(result).to.deep.equal(expected)
@@ -27,4 +27,21 @@ describe('Rabin-Karp Search', function () {
2727
const result = rabinKarpSearch(text, pattern)
2828
expect(result).to.deep.equal(expected)
2929
})
30+
31+
it('should find a pattern at the start of the text', function () {
32+
expect(rabinKarpSearch('ABCABC', 'ABC')).to.deep.equal([0, 3])
33+
expect(rabinKarpSearch('abc', 'a')).to.deep.equal([0])
34+
expect(rabinKarpSearch('abc', 'abc')).to.deep.equal([0])
35+
})
36+
37+
it('should find a long pattern', function () {
38+
const pattern = 'abcdefghijkl'
39+
expect(rabinKarpSearch(pattern + 'x' + pattern, pattern)).to.deep.equal([
40+
0, 13
41+
])
42+
})
43+
44+
it('should return an empty array when the text is shorter than the pattern', function () {
45+
expect(rabinKarpSearch('ab', 'abc')).to.deep.equal([])
46+
})
3047
})

0 commit comments

Comments
 (0)