06. Search Pattern (Rabin-Karp Algorithm)
β GFG solution for Rabin-Karp based substring search. Fast, efficient pattern matching using rolling hash! π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given two strings:
A text string in which to search.
A pattern string to find.
Return all starting positions (1-based) where the pattern occurs in the text. Use the Rabin-Karp Algorithm (rolling hash-based pattern matching).
π Examples
Example 1
Input: text = "birthdayboy", pattern = "birth"
Output: [1]Example 2
Input: text = "geeksforgeeks", pattern = "geek"
Output: [1, 9]π Constraints
$1 \leq \text{len(text)} \leq 5 \times 10^5$
$1 \leq \text{len(pattern)} \leq \text{len(text)}$
All characters are lowercase English letters (
a-z)
β
My Approach
The Rabin-Karp Algorithm uses hashing to match the pattern with substrings in the text.
Hashing Basics
Convert strings to numerical hash using a rolling hash formula.
If two hashes match, perform a direct string comparison to confirm (to avoid false positives from collisions).
Algorithm Steps:
Hash Function: Use a prime modulus
qand radix/based = 256(covers lowercase letters).Precompute Hashes:
Compute the hash of the
patternand the initial window intext.Use a rolling hash to update hash as the window slides by 1 character.
Match Check:
When hash matches, check characters one by one to confirm.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(N + M), where
Nis text length andMis pattern length. We compute hashes in linear time and only compare strings when hashes match.Expected Auxiliary Space Complexity: O(1), as we only use a fixed number of variables for hashing.
π§βπ» Code (C++)
π§βπ» Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated