What if you could find a needle in a haystack without checking every straw?
Why Rabin Karp String Matching in DSA Go?
Imagine you have a huge book and you want to find every place where a certain sentence appears. You try to read every word and compare it with your sentence manually.
This manual way is very slow and tiring. You might miss some places or make mistakes because you have to check every word one by one, again and again.
Rabin Karp uses a clever math trick called hashing to quickly check if parts of the book might match your sentence. It avoids checking every word fully unless it really needs to, saving a lot of time.
for i := 0; i <= len(text)-len(pattern); i++ { if text[i:i+len(pattern)] == pattern { fmt.Println("Found at", i) } }
patternHash := hash(pattern) textHash := hash(text[0:len(pattern)]) for i := 0; i <= len(text)-len(pattern); i++ { if patternHash == textHash && text[i:i+len(pattern)] == pattern { fmt.Println("Found at", i) } if i < len(text)-len(pattern) { textHash = rollHash(textHash, text[i], text[i+len(pattern)]) } }
It makes searching for patterns in large texts fast and efficient, even when the text is huge.
Search engines use this method to quickly find words or phrases in billions of web pages.
Manual searching is slow and error-prone.
Rabin Karp uses hashing to speed up pattern matching.
This method is great for fast text searching in big data.
Practice
Rabin Karp string matching algorithm compared to a simple brute force search?Solution
Step 1: Understand Rabin Karp's approach
Rabin Karp uses a hash function to convert substrings into numbers for quick comparison.Step 2: Compare with brute force
Brute force checks each character one by one, while Rabin Karp first compares hash values to skip unnecessary checks.Final Answer:
It uses hashing to quickly find potential matches before checking characters -> Option AQuick Check:
Hashing speeds up matching = A [OK]
- Thinking Rabin Karp sorts the text
- Assuming it uses recursion
- Believing it only works on numbers
Solution
Step 1: Recall hash calculation formula
The rolling hash is computed as (previous_hash * base + current_char) mod prime.Step 2: Match formula with options
hash = (hash*base + int(char)) % prime matches the correct formula for rolling hash calculation.Final Answer:
hash = (hash*base + int(char)) % prime -> Option BQuick Check:
Rolling hash formula = A [OK]
- Using addition instead of multiplication for rolling hash
- Mixing up base and prime positions
- Using XOR (^) instead of power or multiplication
package main
import "fmt"
func main() {
text := "ababc"
pattern := "abc"
// Simplified hash values for illustration
patternHash := 294
textHash := 0
base := 256
prime := 101
for i := 0; i <= len(text)-len(pattern); i++ {
if i == 0 {
for j := 0; j < len(pattern); j++ {
textHash = (textHash*base + int(text[j])) % prime
}
} else {
textHash = (base*(textHash-int(text[i-1])*intPow(base, len(pattern)-1)) + int(text[i+len(pattern)-1])) % prime
if textHash < 0 {
textHash += prime
}
}
if textHash == patternHash {
fmt.Println("Pattern found at index", i)
}
}
}
func intPow(a, b int) int {
result := 1
for b > 0 {
result *= a
b--
}
return result
}Solution
Step 1: i=0, substring "aba"
Initial textHash computed with sequential (textHash*base + char) % 101, resulting in value <101 !=294. No print.Step 2: i=1, substring "bab"
Rolling hash: (base*(textHash - text[i-1]*base^{2}) + newchar) % 101, normalized if negative, so 0-100 !=294. No print.Step 3: i=2, substring "abc"
Similarly, textHash after %101 (and +prime if <0) is 0-100 !=294. No print.Final Answer:
No pattern found -> Option DQuick Check:
textHash always %101 <101, patternHash=294 >101, no match = D [OK]
- Assuming match at index 0 without hash check
- Forgetting to adjust negative hash values
- Incorrect rolling hash update
textHash = (base*(textHash-int(text[i-1])*intPow(base, len(pattern))) + int(text[i+len(pattern)-1])) % primeWhat is the issue?
Solution
Step 1: Understand rolling hash update formula
The correct formula uses base^(pattern_length-1) to remove the leftmost character's contribution.Step 2: Check the power used in intPow
The code uses len(pattern), which is one too many, causing wrong hash calculation.Final Answer:
The power used in intPow should be len(pattern)-1, not len(pattern) -> Option CQuick Check:
Power = pattern length minus one [OK]
- Using full pattern length power instead of one less
- Forgetting modulo operation
- Incorrect subtraction of character value
Solution
Step 1: Understand hash collisions in Rabin Karp
Different substrings can have the same hash value, causing false positives.Step 2: Best practice to reduce false positives
Use a large prime to reduce collisions and verify matches by comparing actual substrings.Final Answer:
Use a large prime number and verify matches by direct string comparison -> Option AQuick Check:
Large prime + verify strings = D [OK]
- Using small primes increasing collisions
- Skipping substring verification
- Using base 1 which causes poor hashing
Ready to prove it?
Pass the test and this pattern moves unknown
