Challenge - 5 Problems
Rabin Karp Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Rabin Karp hash calculation
What is the output of the following Go code that calculates the initial hash of the pattern "abc" using a simple rolling hash with base 256 and modulo 101?
DSA Go
package main import "fmt" func main() { pattern := "abc" base := 256 mod := 101 hash := 0 for i := 0; i < len(pattern); i++ { hash = (hash*base + int(pattern[i])) % mod } fmt.Println(hash) }
Attempts:
2 left
💡 Hint
Calculate hash step by step: ((0*256 + 'a') % 101), then ((prev*256 + 'b') % 101), then ((prev*256 + 'c') % 101).
✗ Incorrect
The hash is calculated as (((0*256 + 97) % 101)*256 + 98) % 101)*256 + 99) % 101 = 90.
❓ Predict Output
intermediateRabin Karp rolling hash update output
Given the initial hash of substring "abc" is 90, base 256, modulo 101, and the highest power h = 256^2 % 101 = 88, what is the new hash after sliding the window to substring "bcd" (removing 'a', adding 'd')?
DSA Go
package main import "fmt" func main() { oldHash := 90 base := 256 mod := 101 h := 88 oldChar := 'a' newChar := 'd' newHash := (oldHash - int(oldChar)*h)*base + int(newChar) newHash = newHash % mod if newHash < 0 { newHash += mod } fmt.Println(newHash) }
Attempts:
2 left
💡 Hint
Use formula: newHash = ((oldHash - oldChar*h)*base + newChar) % mod
✗ Incorrect
Calculate: (90 - 97*88)*256 + 100 mod 101 = (90 - 8536)*256 + 100 mod 101 = (-8446)*256 + 100 mod 101 = -2162176 + 100 mod 101 = -2162076 mod 101 = 31
🧠 Conceptual
advancedWhy use modulo in Rabin Karp hashing?
Why is modulo operation used in the Rabin Karp algorithm's hash calculations?
Attempts:
2 left
💡 Hint
Think about what happens if numbers get too big in calculations.
✗ Incorrect
Modulo keeps hash values within a fixed range, preventing overflow and making calculations manageable.
🔧 Debug
advancedIdentify the bug in this Rabin Karp hash update code
What error will this Go code produce when updating the rolling hash in Rabin Karp algorithm?
DSA Go
oldHash := 90 base := 256 mod := 101 h := 88 oldChar := 'a' newChar := 'd' newHash := (oldHash - int(oldChar)*h)*base + int(newChar) newHash = newHash % mod fmt.Println(newHash)
Attempts:
2 left
💡 Hint
Check if negative values are handled after modulo operation.
✗ Incorrect
The code does not handle negative values after modulo, so newHash can be negative when printed.
🚀 Application
expertNumber of pattern matches found by Rabin Karp
Given the text "abracadabra" and pattern "abra", how many times will the Rabin Karp algorithm find the pattern in the text?
Attempts:
2 left
💡 Hint
Look for all occurrences of "abra" in "abracadabra".
✗ Incorrect
The pattern "abra" appears twice: at the start (index 0) and near the end (index 7).
