Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to calculate the initial hash value for the pattern.
DSA Go
var patternHash int for i := 0; i < len(pattern); i++ { patternHash = (patternHash*[1] + int(pattern[i])) % prime }
Attempts:
3 left
💡 Hint
Common Mistakes
Using a base value smaller than 256 causes incorrect hash calculations.
Forgetting to use modulo operation to keep hash values manageable.
✗ Incorrect
The base value 256 is used because it covers all ASCII characters for hashing.
2fill in blank
mediumComplete the code to update the rolling hash when sliding the window over the text.
DSA Go
textHash = (textHash - int(text[i])*h) * [1] + int(text[i+len(pattern)]) textHash %= prime if textHash < 0 { textHash += prime }
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different base than initial hash causes mismatch.
Not adjusting negative hash values after modulo.
✗ Incorrect
The base 256 is used consistently for rolling hash updates.
3fill in blank
hardFix the error in the code that calculates the value of h (the highest power of base).
DSA Go
h := 1 for i := 0; i < len(pattern)-1; i++ { h = (h * [1]) % prime }
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong base value for h causes incorrect rolling hash updates.
Not applying modulo operation inside the loop.
✗ Incorrect
The base 256 is used to calculate h for the rolling hash correctly.
4fill in blank
hardFill both blanks to complete the substring comparison after hash match.
DSA Go
if patternHash == textHash { match := true for j := 0; j < len(pattern); j++ { if text[i+[1]] != pattern[[2]] { match = false break } } if match { fmt.Println("Pattern found at index", i) } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong indices causes incorrect substring comparison.
Comparing text[i] with pattern[i] instead of offset by j.
✗ Incorrect
We compare characters at offset j in both text and pattern to verify the match.
5fill in blank
hardFill all three blanks to complete the main Rabin-Karp search function.
DSA Go
func rabinKarpSearch(text, pattern string, prime int) {
m := len(pattern)
n := len(text)
h := 1
for i := 0; i < m-1; i++ {
h = (h * [1]) % prime
}
patternHash, textHash := 0, 0
for i := 0; i < m; i++ {
patternHash = (patternHash*[2] + int(pattern[i])) % prime
textHash = (textHash*[2] + int(text[i])) % prime
}
for i := 0; i <= n-m; i++ {
if patternHash == textHash {
match := true
for j := 0; j < m; j++ {
if text[i+j] != pattern[j] {
match = false
break
}
}
if match {
fmt.Println("Pattern found at index", i)
}
}
if i < n-m {
textHash = (textHash - int(text[i])*h) * [3] + int(text[i+m])
textHash %= prime
if textHash < 0 {
textHash += prime
}
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Mixing different base values causes hash mismatches.
Forgetting modulo operation after hash updates.
✗ Incorrect
The base 256 is consistently used for hashing and rolling hash updates.
