diff --git a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java index 81e16dbbbf07..35d696f2a2f2 100644 --- a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java +++ b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java @@ -13,9 +13,14 @@ public static int search(String pattern, String text, int primeNumber) { int index = -1; // -1 here represents not found int patternLength = pattern.length(); int textLength = text.length(); - int hashForPattern = 0; - int hashForText = 0; - int h = 1; + if (patternLength > textLength) { + return index; + } + + // long, so hash * ALPHABET_SIZE cannot overflow for large primes such as 1_000_000_007 + long hashForPattern = 0; + long hashForText = 0; + long h = 1; // The value of h would be "pow(d, patternLength-1)%primeNumber" for (int i = 0; i < patternLength - 1; i++) { diff --git a/src/test/java/com/thealgorithms/searches/RabinKarpAlgorithmTest.java b/src/test/java/com/thealgorithms/searches/RabinKarpAlgorithmTest.java index 40e1acce9c3a..3e2314ad89cd 100644 --- a/src/test/java/com/thealgorithms/searches/RabinKarpAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/searches/RabinKarpAlgorithmTest.java @@ -8,7 +8,7 @@ class RabinKarpAlgorithmTest { @ParameterizedTest - @CsvSource({"This is an example for rabin karp algorithmn, algorithmn, 101", "AAABBDDG, AAA, 137", "AAABBCCBB, BBCC, 101", "AAABBCCBB, BBCC, 131", "AAAABBBBCCC, CCC, 41", "ABCBCBCAAB, AADB, 293", "Algorithm The Algorithm, Algorithm, 101"}) + @CsvSource({"This is an example for rabin karp algorithmn, algorithmn, 101", "AAABBDDG, AAA, 137", "AAABBCCBB, BBCC, 101", "AAABBCCBB, BBCC, 131", "AAAABBBBCCC, CCC, 41", "ABCBCBCAAB, AADB, 293", "Algorithm The Algorithm, Algorithm, 101", "nzdjsjggwx, jggw, 1000000007", "AB, ABC, 101"}) void rabinKarpAlgorithmTestExample(String txt, String pat, int q) { int indexFromOurAlgorithm = RabinKarpAlgorithm.search(pat, txt, q); int indexFromLinearSearch = txt.indexOf(pat);