Implement efficient string pattern matching algorithms to find all occurrences of a pattern in a text. In this challenge, you'll implement three different pattern matching algorithms:
NaivePatternMatch- A simple brute force approach that checks every possible position.KMPSearch- The Knuth-Morris-Pratt algorithm that avoids unnecessary comparisons by using a preprocessed prefix table.RabinKarpSearch- The Rabin-Karp algorithm that uses hashing to find patterns efficiently.
func NaivePatternMatch(text, pattern string) []int
func KMPSearch(text, pattern string) []int
func RabinKarpSearch(text, pattern string) []inttext- The main text string in which to search for the pattern.pattern- The pattern string to search for.
- All functions should return a slice of integers containing the starting indices of all occurrences of the pattern in the text.
- If no matches are found, return an empty slice.
- Indices should be 0-based (the first character is at position 0).
NaivePatternMatchshould implement a straightforward brute force algorithm.KMPSearchshould implement the Knuth-Morris-Pratt algorithm.RabinKarpSearchshould implement the Rabin-Karp algorithm.- All three functions should return the same correct results.
- Pay attention to edge cases like empty strings, patterns longer than the text, etc.
NaivePatternMatch("ABABDABACDABABCABAB", "ABABCABAB")
[10]
KMPSearch("AABAACAADAABAABA", "AABA")
[0, 9, 12]
RabinKarpSearch("GEEKSFORGEEKS", "GEEK")
[0, 8]
NaivePatternMatch("AAAAAA", "AA")
[0, 1, 2, 3, 4]
- Fork the repository.
- Clone your fork to your local machine.
- Create a directory named after your GitHub username inside
challenge-23/submissions/. - Copy the
solution-template.gofile into your submission directory. - Implement the required functions.
- Test your solution locally by running the test file.
- Commit and push your code to your fork.
- Create a pull request to submit your solution.
Run the following command in the challenge-23/ directory:
go test -v- Naive Algorithm: O(n*m) time complexity where n is the length of the text and m is the length of the pattern.
- KMP Algorithm: O(n+m) time complexity.
- Rabin-Karp Algorithm: Average case O(n+m) time complexity, worst case O(n*m).