Bird
Raised Fist0
DSA Javascriptprogramming~20 mins

Rabin Karp String Matching in DSA Javascript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Rabin Karp Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Rabin Karp hash calculation
What is the output of the following JavaScript code that calculates the initial hash for the pattern 'abc' using a simple rolling hash?
DSA Javascript
const pattern = 'abc';
const base = 256;
const mod = 101;
let hash = 0;
for (let i = 0; i < pattern.length; i++) {
  hash = (hash * base + pattern.charCodeAt(i)) % mod;
}
console.log(hash);
A6
B45
C12
D90
Attempts:
2 left
💡 Hint
Calculate hash step by step: hash = (hash * base + charCode) % mod for each character.
❓ Predict Output
intermediate
2:00remaining
Rabin Karp pattern search output
What will be printed by the following code that searches for pattern 'test' in text 'this is a test text' using Rabin Karp?
DSA Javascript
function rabinKarp(text, pattern) {
  const base = 256;
  const mod = 101;
  const m = pattern.length;
  const n = text.length;
  let pHash = 0, tHash = 0, h = 1;

  for (let i = 0; i < m - 1; i++) h = (h * base) % mod;

  for (let i = 0; i < m; i++) {
    pHash = (pHash * base + pattern.charCodeAt(i)) % mod;
    tHash = (tHash * base + text.charCodeAt(i)) % mod;
  }

  for (let i = 0; i <= n - m; i++) {
    if (pHash === tHash) {
      let match = true;
      for (let j = 0; j < m; j++) {
        if (text[i + j] !== pattern[j]) {
          match = false;
          break;
        }
      }
      if (match) console.log(i);
    }
    if (i < n - m) {
      tHash = (base * (tHash - text.charCodeAt(i) * h) + text.charCodeAt(i + m)) % mod;
      if (tHash < 0) tHash += mod;
    }
  }
}
rabinKarp('this is a test text', 'test');
A8
B10
C15
D5
Attempts:
2 left
💡 Hint
Check the index where 'test' starts in the text.
🧠 Conceptual
advanced
1:30remaining
Why use modulo in Rabin Karp hashing?
Why does the Rabin Karp algorithm use modulo operation when calculating the rolling hash?
ATo keep hash values within a fixed range and avoid integer overflow
BTo make the hash values unique for every substring
CTo speed up the string comparison step
DTo convert characters to numbers
Attempts:
2 left
💡 Hint
Think about what happens if numbers get too big in calculations.
🔧 Debug
advanced
1:30remaining
Identify the bug in rolling hash update
What is the bug in the following rolling hash update code snippet used in Rabin Karp?
DSA Javascript
tHash = (base * (tHash - text.charCodeAt(i) * h) + text.charCodeAt(i + m)) % mod;
AIt should subtract text.charCodeAt(i + m) instead of adding
BIt uses wrong base value for multiplication
CIt does not add mod if tHash becomes negative
DIt should multiply by h instead of base
Attempts:
2 left
💡 Hint
Check what happens if the subtraction makes tHash negative.
🚀 Application
expert
3:00remaining
Number of hash collisions in Rabin Karp
Given a text of length 1000 and a pattern of length 5, using Rabin Karp with base=256 and mod=101, what is the maximum number of hash collisions that can occur during the search?
A995
B1000
C101
D5
Attempts:
2 left
💡 Hint
Number of substrings checked is n - m + 1; collisions can happen at each substring except the first.

Practice

(1/5)
1. What is the main idea behind the Rabin Karp String Matching algorithm?
easy
A. Sort the text and pattern before matching
B. Use recursion to search for the pattern
C. Use hashing to find pattern matches efficiently
D. Use brute force to compare every substring

Solution

  1. Step 1: Understand Rabin Karp's approach

    The algorithm uses a hash function to convert the pattern and substrings of the text into numbers.
  2. Step 2: Use hashing for efficient matching

    By comparing hash values instead of characters, it quickly finds potential matches and then verifies them.
  3. Final Answer:

    Use hashing to find pattern matches efficiently -> Option C
  4. Quick Check:

    Rabin Karp = hashing for matching [OK]
Hint: Remember: Rabin Karp uses hashing to speed up matching [OK]
Common Mistakes:
  • Thinking it uses recursion
  • Assuming it sorts strings before matching
  • Confusing it with brute force method
2. Which of the following is the correct way to compute the initial hash for a substring in Rabin Karp (assuming base = 256 and prime = 101)?
easy
A. hash = (charCode + prime) % base
B. hash = (hash * base + charCode) % prime
C. hash = (charCode * base) % prime
D. hash = (hash + base * charCode) % prime

Solution

  1. Step 1: Understand hash calculation formula

    The rolling hash is computed by multiplying the current hash by base and adding the new character code, then taking modulo prime.
  2. Step 2: Match formula with options

    hash = (hash * base + charCode) % prime matches the formula: hash = (hash * base + charCode) % prime.
  3. Final Answer:

    hash = (hash * base + charCode) % prime -> Option B
  4. Quick Check:

    Rolling hash formula = hash = (hash * base + charCode) % prime [OK]
Hint: Rolling hash multiplies old hash by base, adds char, mod prime [OK]
Common Mistakes:
  • Adding base multiplied by charCode instead of multiplying hash
  • Mixing up modulo operations
  • Using wrong order of operations
3. What will be the output of the following code snippet using Rabin Karp to find pattern 'abc' in text 'ababc'?
const text = 'ababc';
const pattern = 'abc';
// Assume base=256, prime=101
// Simplified hash function and matching logic
function rabinKarp(text, pattern) {
  const m = pattern.length;
  const n = text.length;
  for (let i = 0; i <= n - m; i++) {
    if (text.substring(i, i + m) === pattern) {
      return i;
    }
  }
  return -1;
}
console.log(rabinKarp(text, pattern));
medium
A. 2
B. 1
C. -1
D. 3

Solution

  1. Step 1: Check substring matches

    Check substrings of length 3 in 'ababc': 'aba'(index 0), 'bab'(1), 'abc'(2).
  2. Step 2: Identify matching index

    'abc' matches at index 2, so function returns 2.
  3. Final Answer:

    2 -> Option A
  4. Quick Check:

    Pattern found at index 2 [OK]
Hint: Check substrings of pattern length for exact match [OK]
Common Mistakes:
  • Returning first partial match index
  • Off-by-one errors in loop
  • Confusing substring indices
4. Identify the bug in this Rabin Karp implementation snippet:
function rabinKarp(text, pattern) {
  const base = 256;
  const prime = 101;
  let patternHash = 0, textHash = 0;
  const m = pattern.length;
  const n = text.length;
  let h = 1;

  for (let i = 0; i < m; i++) {
    h = (h * base) % prime;
  }

  for (let i = 0; i < m; i++) {
    patternHash = (base * patternHash + pattern.charCodeAt(i)) % prime;
    textHash = (base * textHash + text.charCodeAt(i)) % prime;
  }

  for (let i = 0; i <= n - m; i++) {
    if (patternHash === textHash) {
      if (text.substring(i, i + m) === pattern) {
        return i;
      }
    }
    if (i < n - m) {
      textHash = (base * (textHash - text.charCodeAt(i) * h) + text.charCodeAt(i + m)) % prime;
      if (textHash < 0) textHash += prime;
    }
  }
  return -1;
}
medium
A. Not updating patternHash inside the loop
B. Missing check for negative textHash after update
C. Using substring instead of charAt for comparison
D. Incorrect calculation of h in the first loop

Solution

  1. Step 1: Examine the h calculation

    The variable h should be base^(m-1) % prime to multiply the outgoing character's contribution.
  2. Step 2: Identify the loop error

    The loop runs from i=0 to i
  3. Final Answer:

    Incorrect calculation of h in the first loop -> Option D
  4. Quick Check:

    h = base^(m-1) % prime requires loop m-1 times [OK]
Hint: Check h calculation loop carefully for off-by-one errors [OK]
Common Mistakes:
  • Forgetting to add prime if textHash becomes negative
  • Incorrect loop range for h calculation
  • Not verifying substring match after hash match
5. Given a large text and multiple patterns, which modification to the Rabin Karp algorithm helps efficiently find all patterns in the text?
hard
A. Precompute hashes of all patterns and use a hash set for quick lookup
B. Sort all patterns and use binary search on text substrings
C. Use a single hash function and check each pattern separately
D. Use recursion to match patterns one by one

Solution

  1. Step 1: Understand multiple pattern matching challenge

    Checking each pattern separately is slow for many patterns.
  2. Step 2: Use hashing for all patterns

    Precompute hashes of all patterns and store in a hash set for O(1) lookup during text scanning.
  3. Step 3: Efficiently find all matches

    When scanning text substrings, compute hash and check if it exists in the pattern hash set to find matches quickly.
  4. Final Answer:

    Precompute hashes of all patterns and use a hash set for quick lookup -> Option A
  5. Quick Check:

    Multiple patterns = precompute hashes + hash set [OK]
Hint: Precompute pattern hashes and use hash set for fast matching [OK]
Common Mistakes:
  • Checking each pattern separately causing slow performance
  • Sorting patterns instead of hashing
  • Using recursion unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard