πDay 5. Search Pattern (KMP Algorithm) π§
The problem can be found at the following link: Problem Link
π‘ Problem Description:
You are given two strings:
txt: The text string in which the pattern is to be searched.pat: The pattern string to search for.
The task is to print all indices in txt where pat starts, using 0-based indexing. Return an empty list if no occurrences are found.
π Example Walkthrough:
Input:
txt = "abcab", pat = "ab"
Output:
[0, 3]
Explanation:
The pattern ab appears at indices 0 and 3 in the text string.
Input:
txt = "aaaaa", pat = "aa"
Output:
[0, 1, 2, 3]
Input:
txt = "hello", pat = "world"
Output:
[]
Constraints:
1 <= txt.length, pat.length <= 10^6Both strings consist of lowercase English alphabets.
π― My Approach:
The Knuth-Morris-Pratt (KMP) algorithm is an efficient pattern matching algorithm that avoids unnecessary comparisons, making it well-suited for this task.
Compute the Longest Prefix Suffix (LPS) Array:
Preprocess the pattern string
patto build the LPS array.The LPS array stores the length of the longest prefix which is also a suffix for substrings of
pat.This preprocessing helps in skipping characters during comparisons.
Search Using the LPS Array:
Traverse the
txtand use thepatLPS array to efficiently find matches.If a mismatch occurs, use the LPS array to skip unnecessary comparisons.
Output the Indices:
Store the starting indices of matches found in
txt.
π Time and Auxiliary Space Complexity
Preprocessing (LPS Array): O(m), where
mis the length of the pattern string.Searching: O(n), where
nis the length of the text string.Overall Time Complexity: O(n + m).
Auxiliary Space Complexity:
Space for LPS Array: O(m).
π Solution Code
Code (C)
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