Search Pattern (Rabin-Karp Algorithm) in Java10 May 2025 | 4 min read The Rabin-Karp Algorithm is an efficient string-matching method that uses hashing to find a pattern within a text. Rather than examining each character individually, it computes a hash value for the pattern and compares it with the hash values of text substrings. When a hash match occurs, the algorithm performs a character-wise check to validate the match. Example 1: Finding a Word in a Sentence Input: Text = "WELCOME TO JAVA PROGRAMMING" Pattern = "JAVA" Output: Pattern found at index: 11 Example 2: Searching for Multiple Occurrences Input: Text = "ABABCABAB" Pattern = "ABAB" Output: Pattern found at index: 0, 5 How to Compute Hash Value in Rabin-Karp?Step 1: Select Base and Modulus Choose a prime number q as the modulus to minimize hash collisions and prevent overflow. Set d as the base, which represents the number of possible characters (e.g., 256 for ASCII). Step 2: Initialize Hash Values Set the initial hash values of both the pattern and the first window of text to zero. Step 3: Compute Initial Hash for Pattern and Text Traverse the pattern and the first segment of text, computing their hash values using: Step 4: Slide the Pattern Across the Text Calculate the hash value for the first substring in the text, then shift the pattern over the text one position at a time. Step 5: Update the Hash for Each Shift For each shift, update the hash using: This efficiently removes the contribution of the outgoing character and adds the new character. Step 6: Check for Matches If a substring's hash matches the pattern’s hash, perform a character-by-character comparison to confirm the match, as different substrings may produce the same hash. Top of Form Bottom of Form AlgorithmStep 1: Compute the hash value of the specified pattern and the initial window of the text employing a rolling hash function while precomputing the hash base for more efficient sliding. Step 2: Move through the text by advancing the window one character at a time and compare the current window's hash value with that of the pattern. Step 3: When the hash values are the same, carry out a character-by-character comparison between the pattern and the current text window to verify a legitimate match. Step 4: Calculate the hash for the upcoming window by eliminating the initial character, incorporating the subsequent character, and making adjustments for negative values if necessary. Step 5: Keep moving the window, look for matches, revise the hash values, and display all positions where the pattern appears in the text. Let’s implement the above steps in a Java program. File Name: RabinKarp.java Output: Match found at index: 24 Time Complexity: The worst-case complexity is O(N × M) due to hash collisions, while the average case runs in O(N + M) using efficient rolling hash computations. Auxiliary Space Complexity: The algorithm requires only a few integer variables for hash calculations, making its auxiliary space complexity O(1). |
The Thread class offers constructors and functions for creating and controlling threads. It serves as a subclass of Objects and also implements the Runnable interface. Deprecated methods are no longer considered significant and should not be used because they may be eliminated from the class in future...
6 min read
Java offers a number of data systems that allow the developers to work with collections of records effectively. When more than one threads are involved, concurrent collections come to be essential to make sure data integrity and thread safety. In this section, we will discover concurrent...
5 min read
Problem Statement Given a binary string we need to find the maximum difference of 0s and 1s inside the given binary string. Here, you treat 0 as +1 and 1 as -1, and then seek the maximum value of contiguous subarray. This maximum sum of a subarray...
4 min read
In Java, the Future and Callable interfaces are important components of the java.util.concurrent package. They give you a mechanism to manage the outcomes of asynchronous tasks and work with asynchronous tasks. Although they both have similar functions, there are some significant variations between them that are...
3 min read
Java programming challenges are complex problems that we have to solve through logic and implement that logic in any programming language. Solving programming challenges develops logical thinking, analytical skill. If you are preparing for interviews, you must solve these programming challenges once. It is advisable to...
22 min read
Introduction: A dynamic array-like data structure that lets you store and work with objects is the Java Vector class. Sorting the components of a Vector in a precise order might often be necessary, whether you are working on a small project or a large-scale application. In this...
3 min read
in Java In Java, is a problem in which we need to find the shortest route that covers each city exactly once and returns to the starting point. Hamiltonian Cycle is another problem in Java that is mostly similar to . The main difference between TSP...
4 min read
Given two numbers, N and K, our task is to determine the lowest value X such that N < X*K. Example 1: Input: int num = 8 int K = 7 Output: The largest factor of N is 2. Explanation: For the given number, numbers less than K divisible by N are 1, 2,...
5 min read
The binary search algorithm is one of the commonly used algorithms in programming. It is used to search and find an element in a sorted array. The binary search algorithm is a highly efficient search technique used to locate a specific element in a sorted dataset. It...
5 min read
Given a 2-dimensional array ARR with N rows and M columns, where each element contains a value of 0 or 1, convert the given matrix into a Good matrix. In a Good matrix, if an element is 0, all elements in its row and column should...
5 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India