Data Structures & AlgorithmsVery hardTCS NQT Digital · Product Company SDE

Problem: A string s (length n) must be searched for a pattern p (length m) in text. Which algorithm guarantees O(n+m) worst-case time regardless of the text/pattern content?

  1. A. Rabin-Karp with a weak hash and no collision check
  2. B. Naive sliding comparison of the pattern at every position
  3. C. Sorting both strings and comparing
  4. D. Knuth-Morris-Pratt (KMP), using the pattern's failure function to avoid re-scanning

Correct answer: D. Knuth-Morris-Pratt (KMP), using the pattern's failure function to avoid re-scanning

KMP precomputes the longest-prefix-suffix (failure) function in O(m), then scans the text once in O(n), never re-examining a text character on a mismatch, giving O(n+m) worst case.

More Coding Interview Problems questions

Exams that ask this topic