Data Structures & AlgorithmsHardGATE CS · DSA

Rabin–Karp with a good rolling hash is used to find a pattern of length m in a text of length n. Which statement is correct?

  1. A. O(n log m) because the rolling hash needs a logarithm
  2. B. Expected O(n + m), but O(nm) in the worst case when many windows produce hash collisions
  3. C. Always O(nm)
  4. D. Always O(n + m) because hashes are compared in O(1)

Correct answer: B. Expected O(n + m), but O(nm) in the worst case when many windows produce hash collisions

Rolling the hash costs O(1) per shift, but each hash hit must be verified character by character; adversarial or unlucky collisions can force Θ(m) checks at most positions.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic