Data Structures & AlgorithmsVery hardGATE CS · TCS NQT

Which algorithm counts occurrences of a pattern p inside a text t in O(|t| + |p|) time?

  1. A. Naive nested loop search
  2. B. KMP (prefix-function) search
  3. C. Binary search on the text
  4. D. Sorting both strings

Correct answer: B. KMP (prefix-function) search

KMP never re-reads text characters, so it runs in linear time. The naive search is O(|t| * |p|) in the worst case.

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

Exams that ask this topic