Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the hash value for the pattern.
DSA C#
int patternHash = 0; for (int i = 0; i < pattern.Length; i++) { patternHash = (patternHash * baseVal + pattern[i]) % [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 as modulo causes division by zero error.
Using pattern.Length or text.Length as modulo leads to poor hashing.
✗ Incorrect
The hash value is computed modulo a prime number to reduce collisions.
2fill in blank
mediumComplete the code to update the rolling hash when sliding the window over the text.
DSA C#
textHash = (textHash - text[i] * highBase) * baseVal + text[i + pattern.Length];
textHash = (textHash + [1]) % prime;Attempts:
3 left
💡 Hint
Common Mistakes
Not adding prime before modulo causes negative hash values.
Using incorrect values instead of prime leads to wrong hash updates.
✗ Incorrect
Adding prime before modulo ensures the hash value stays positive.
3fill in blank
hardFix the error in the hash comparison condition to avoid false positives.
DSA C#
if (patternHash == textHash && text.Substring(i, pattern.Length) == [1]) { result.Add(i); }
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing substring with text or hash values causes logic errors.
Skipping substring comparison leads to false matches.
✗ Incorrect
After hash match, confirm by comparing the actual substring with the pattern.
4fill in blank
hardFill both blanks to compute the highest base power used in rolling hash.
DSA C#
int highBase = 1; for (int i = 0; i < [1] - 1; i++) { highBase = (highBase * [2]) % prime; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using text.Length instead of pattern.Length causes wrong power calculation.
Using prime instead of baseVal in multiplication is incorrect.
✗ Incorrect
The highest base power is baseVal^(pattern.Length-1) modulo prime.
5fill in blank
hardFill all three blanks to complete the Rabin-Karp search loop.
DSA C#
for (int i = 0; i <= text.Length - [1]; i++) { if (patternHash == textHash) { if (text.Substring(i, [2]) == [3]) { result.Add(i); } } if (i < text.Length - [1]) { textHash = (textHash - text[i] * highBase) * baseVal + text[i + [1]]; textHash = (textHash + prime) % prime; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using text.Length instead of pattern.Length causes index errors.
Comparing substring with text instead of pattern causes false matches.
✗ Incorrect
Use pattern.Length for substring length and loop limit, and compare substring with pattern.
