Data Structures & AlgorithmsHardAmazon · Microsoft coding round

Problem: Rabin-Karp pattern matching uses a rolling hash to compare a pattern against every window of the text. What is its typical time complexity, and when does it degrade?

  1. A. O(n+m) on average; degrades to O(nm) worst case under many hash collisions
  2. B. O(n log m) always, using binary search on hash values
  3. C. O(nm) always, regardless of hashing
  4. D. O(log n) because hashing is constant time

Correct answer: A. O(n+m) on average; degrades to O(nm) worst case under many hash collisions

Hashing lets most mismatching windows be rejected in O(1), giving O(n+m) on average, but an adversarial input causing many hash collisions forces full O(m) character checks at each position, degrading to O(nm).

More Coding Interview Problems questions

Exams that ask this topic