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). |
Day by Day, technology is changing and grooming the world with its exploring advancements in the world. Thus enhancement in technology demands an evolution in the programming language also. One such programming language is Java programming language that is always in demand and a popular programming...
6 min read
Java, a widely-used and versatile programming language, is known for its robustness and reliability. However, like any software, Java applications are not immune to errors and exceptions. Among these, uncaught exceptions stand out as a critical aspect of Java programming that developers must understand and handle...
4 min read
The java.lang.reflect.Field has get() method that is utilized to retrieve the field object's value. When a field has a primitive type, an object is automatically wrapped around its value. The argument of obj is disregarded if the field is static; it could be null. In the...
4 min read
Add Elements to Array in Java In Java, arrays are basic data structures for storing elements of the same type in consecutive memory locations. Although arrays have a fixed size once they are created, there are different ways to add elements or create new arrays with...
5 min read
Caching is the process of storing and accessing data from memory (cache memory). The main feature of caching is to reduce the time to access specific data. Caching aims at storing data that can be helpful in the future. The reason for caching is that accessing...
6 min read
In this section, we will learn what is a sublime number and also create Java programs to check if the given number is a sublime number or not. The sublime number program is frequently asked in Java coding interviews and academics. Sublime Number A natural number N is...
2 min read
Generic is used for creating Java code for graphs. Java's HashMap class is used to implement the Graph class. As we know, HashMap has a key and a value; in the graph, nodes are represented as keys, and their adjacency is listed as values. What is Generic? Generics...
9 min read
In this tutorial, we are going to learn the Null pointer exception in Java. Null pointer exception is a runtime exception. Null is a special kind of value that can be assigned to the reference of an object. Whenever one tries to use a reference that...
7 min read
In Java programming, Graphical User Interfaces (GUIs) play an important role in facilitating interaction and user-friendliness. The two most commonly used options for user input in the Java GUI are checkboxes and radio buttons. While both are designed to give users choice, they have different characteristics...
6 min read
In ious section, we have discussed many numbers programs that are usually asked in interviews. In this section, we are going to discuss what is trimorphic number and how to check if the number is trimorphic or not. Trimorphic Number A number T is said to be trimorphic...
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