Data Structures & AlgorithmsModerateGATE CS · TCS NQT

Consider the pattern-matching algorithms: naive, KMP, Rabin–Karp (polynomial rolling hash), Z-function. Which statement is correct?

  1. A. KMP finds all occurrences of a pattern in O(n + m) time, without backtracking the text
  2. B. Rabin–Karp always runs in O(n + m) because it never compares characters
  3. C. The naive algorithm is O(n + m) on every input because it stops at the first mismatch
  4. D. The Z-function needs a separate pass over the text for every pattern letter

Correct answer: A. KMP finds all occurrences of a pattern in O(n + m) time, without backtracking the text

KMP uses the prefix function to skip ahead, so the text pointer never moves backwards and the total work is O(n + m). Rabin–Karp needs character checks on hash matches to rule out collisions, and the naive method can take O(nm) time.

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

Exams that ask this topic