Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Search a pattern of length m in a text of length n = 10⁶ (m up to 10⁵) and report all match positions. Which method guarantees the best worst-case time?

  1. A. Naive sliding comparison – O(n + m) in the worst case
  2. B. Rabin–Karp – O(n + m) guaranteed in the worst case
  3. C. KMP (prefix function) – O(n + m)
  4. D. Sorting all suffixes – O(n) worst case

Correct answer: C. KMP (prefix function) – O(n + m)

KMP never re-reads text characters, giving O(n + m) worst case. The naive method is O(nm) worst case (text 'aaaa…', pattern 'aa…ab'). Rabin–Karp is O(n + m) expected but O(nm) worst case if many hash collisions must be verified. Building a suffix array is O(n log n) or more.

More Coding Interview Problems questions

Exams that ask this topic