Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the base value for hashing.
DSA C++
const int base = [1];Attempts:
3 left
💡 Hint
Common Mistakes
Using a base value too small to cover all characters.
Choosing a prime number instead of the character set size.
✗ Incorrect
The base value 256 is commonly used for ASCII character set in Rabin Karp hashing.
2fill in blank
mediumComplete the code to compute the initial hash of the pattern.
DSA C++
for (int i = 0; i < m; i++) { pattern_hash = (pattern_hash * base + pattern[i]) % [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using base as modulus causes incorrect hashing.
Using pattern length as modulus leads to collisions.
✗ Incorrect
We use a large prime modulus to reduce hash collisions and keep hash values within integer limits.
3fill in blank
hardFix the error in the rolling hash update inside the loop.
DSA C++
text_hash = (base * (text_hash - text[i] * [1]) + text[i + m]) % prime_mod;Attempts:
3 left
💡 Hint
Common Mistakes
Using pow(base, m) causes incorrect subtraction.
Using pow(base, m+1) leads to wrong hash values.
✗ Incorrect
We remove the leftmost character's contribution by multiplying it with base^(m-1).
4fill in blank
hardFill both blanks to correctly check and update the rolling hash.
DSA C++
if (pattern_hash == text_hash && text.substr(i, m) == [1]) { result.push_back(i); } text_hash = (base * (text_hash - text[i] * [2]) + text[i + m]) % prime_mod;
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with text.substr(i, m) instead of pattern.
Using wrong power of base in hash update.
✗ Incorrect
We compare the current substring with the pattern and update the hash by removing the leftmost character multiplied by base^(m-1).
5fill in blank
hardFill all three blanks to complete the Rabin Karp search function.
DSA C++
vector<int> rabinKarp(const string& text, const string& pattern) {
int n = text.size(), m = pattern.size();
const int base = [1];
const int prime_mod = 101;
int pattern_hash = 0, text_hash = 0;
int power = 1;
vector<int> result;
for (int i = 0; i < m - 1; i++)
power = (power * base) % prime_mod;
for (int i = 0; i < m; i++) {
pattern_hash = (pattern_hash * base + pattern[i]) % prime_mod;
text_hash = (text_hash * base + text[i]) % prime_mod;
}
for (int i = 0; i <= n - m; i++) {
if (pattern_hash == text_hash && text.substr(i, m) == [2]) {
result.push_back(i);
}
if (i < n - m) {
text_hash = (base * (text_hash - text[i] * [3]) + text[i + m]) % prime_mod;
if (text_hash < 0) text_hash += prime_mod;
}
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong base value.
Comparing with wrong substring.
Not using power for rolling hash update.
✗ Incorrect
Base is 256 for ASCII, compare substring with pattern, and use power for rolling hash subtraction.
