From 44042f905f4b2bdfe5546cb83aeeea0eeb1b1ef9 Mon Sep 17 00:00:00 2001 From: Jay Pokale Date: Fri, 27 Nov 2026 15:14:57 +0530 Subject: [PATCH] fix: Rabin-Karp missed matches at index 0 and with long patterns --- Search/RabinKarp.js | 19 ++++++++++++++++--- Search/test/RabinKarp.test.js | 19 ++++++++++++++++++- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/Search/RabinKarp.js b/Search/RabinKarp.js index e6d6394ede..d9ad188c35 100644 --- a/Search/RabinKarp.js +++ b/Search/RabinKarp.js @@ -26,10 +26,23 @@ function rabinKarpSearch(text, pattern) { // Calculate the hash of the first substring in the text hashText[0] = hash(text, patternLength) - // Precompute BASE^(patternLength-1) % MOD - const basePow = Math.pow(BASE, patternLength - 1) % MOD + // Precompute BASE^(patternLength-1) % MOD step by step, so that it stays exact + // (Math.pow loses precision once BASE^(patternLength-1) exceeds 2^53) + let basePow = 1 + for (let i = 1; i < patternLength; i++) { + basePow = (basePow * BASE) % MOD + } + + // The first window (index 0) has to be checked as well + if ( + textLength >= patternLength && + hashText[0] === hashPattern && + text.substring(0, patternLength) === pattern + ) { + indices.push(0) + } - for (let i = 1; i <= textLength - patternLength + 1; i++) { + for (let i = 1; i <= textLength - patternLength; i++) { // Update the rolling hash by removing the first character // and adding the next character in the text hashText[i] = diff --git a/Search/test/RabinKarp.test.js b/Search/test/RabinKarp.test.js index 3d10097509..a8a612241d 100644 --- a/Search/test/RabinKarp.test.js +++ b/Search/test/RabinKarp.test.js @@ -13,7 +13,7 @@ describe('Rabin-Karp Search', function () { it('should handle multiple occurrences of the pattern', function () { const text = 'ABABABABABAB' const pattern = 'ABAB' - const expected = [2, 4, 6, 8] + const expected = [0, 2, 4, 6, 8] const result = rabinKarpSearch(text, pattern) expect(result).to.deep.equal(expected) @@ -27,4 +27,21 @@ describe('Rabin-Karp Search', function () { const result = rabinKarpSearch(text, pattern) expect(result).to.deep.equal(expected) }) + + it('should find a pattern at the start of the text', function () { + expect(rabinKarpSearch('ABCABC', 'ABC')).to.deep.equal([0, 3]) + expect(rabinKarpSearch('abc', 'a')).to.deep.equal([0]) + expect(rabinKarpSearch('abc', 'abc')).to.deep.equal([0]) + }) + + it('should find a long pattern', function () { + const pattern = 'abcdefghijkl' + expect(rabinKarpSearch(pattern + 'x' + pattern, pattern)).to.deep.equal([ + 0, 13 + ]) + }) + + it('should return an empty array when the text is shorter than the pattern', function () { + expect(rabinKarpSearch('ab', 'abc')).to.deep.equal([]) + }) })