Bird
Raised Fist0
DSA Javascriptprogramming~5 mins

Rabin Karp String Matching in DSA Javascript - Cheat Sheet & Quick Revision

Choose your learning style10 modes available
Recall & Review
beginner
What is the main idea behind the Rabin Karp string matching algorithm?
It uses hashing to find a pattern in a text by comparing hash values of the pattern and substrings of the text, reducing the number of direct character comparisons.
Click to reveal answer
intermediate
How does Rabin Karp handle hash collisions?
When hash values match, Rabin Karp performs a direct character-by-character check to confirm the match, because different strings can have the same hash.
Click to reveal answer
intermediate
What is the time complexity of Rabin Karp in the average case?
The average time complexity is O(n + m), where n is the length of the text and m is the length of the pattern, because hashing allows quick skipping of non-matching substrings.
Click to reveal answer
intermediate
Why is a rolling hash used in Rabin Karp?
A rolling hash allows efficient calculation of the hash for the next substring by updating the previous hash, avoiding recomputing from scratch.
Click to reveal answer
beginner
What happens if the pattern length is greater than the text length in Rabin Karp?
No match is possible, so the algorithm immediately returns no occurrences without any hashing or comparisons.
Click to reveal answer
What does Rabin Karp primarily use to speed up string matching?
ADynamic Programming
BSorting
CBinary Search
DHashing
What is checked after hash values match in Rabin Karp?
ACharacter-by-character comparison
BSorting the substring
CNothing, match is confirmed
DRecomputing the hash
What is the purpose of a rolling hash in Rabin Karp?
ATo quickly update hash for next substring
BTo sort the text
CTo store all substrings
DTo reverse the string
If the pattern length is 5 and text length is 3, what will Rabin Karp do?
AThrow an error
BTry to match anyway
CReturn no match immediately
DReverse the text
What is the worst-case time complexity of Rabin Karp?
AO(n + m)
BO(n * m)
CO(log n)
DO(1)
Explain how Rabin Karp uses hashing and rolling hash to find a pattern in a text.
Think about how to avoid checking every character every time.
You got /3 concepts.
    Describe the advantages and possible drawbacks of using Rabin Karp for string matching.
    Consider speed and accuracy trade-offs.
    You got /4 concepts.

      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