Data Structures & AlgorithmsModerateProduct placement · Amazon/Microsoft

A string of length n is searched for a pattern of length m. What are the worst-case times of the naive algorithm and of KMP?

  1. A. O(nm) and O(nm)
  2. B. O(n log n) and O(n + m)
  3. C. O(n + m) and O(n log m)
  4. D. O(nm) and O(n + m)

Correct answer: D. O(nm) and O(n + m)

The naive method can re-compare up to m characters at each of n − m + 1 shifts. KMP never moves the text pointer backwards and builds its failure table in O(m).

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

Exams that ask this topic