Begin Algo
String Algorithms · Comparison

String matching algorithms compared

String hashing, Rabin-Karp, KMP, the Z algorithm, Manacher and tries: what each preprocesses, what it guarantees, and the problem shape each is built for.

AlgorithmTimeSpacePreprocessesGuaranteeProblem shapeDifficulty
String HashingString hashingO(n)O(n)Text (prefix hashes)ProbabilisticAny two substrings compared in O(1)Intermediate
Rabin-KarpRolling hash matchingO(n+m) averageO(1)Pattern (one hash)Average O(n+m)Several patterns at onceIntermediate
KMPPrefix-function matchingO(n+m)O(m)Pattern (failure function)Worst case O(n+m)One pattern, streaming textHard
Z-AlgorithmThe Z functionO(n+m)O(n)Pattern + text (concatenated)Worst case O(n+m)Longest prefix match at every positionHard
ManacherLongest palindromeO(n)O(n)Text (with separators)O(n)PalindromesHard
Trie ApplicationsTries in practiceO(L)O(ΣL)Dictionary (all patterns)O(L) per queryPrefix queries, dictionary lookupsIntermediate

When to pick which

Choosing guide

  • One pattern, one text → KMP. For something simpler use the built-in find / strstr; they are usually linear too.
  • Many patterns → equal lengths: a Rabin-Karp hash set; mixed lengths found in one pass: Aho-Corasick (a trie plus KMP, not covered on this site).
  • Substring equality, repeats, comparisons → string hashing, the only O(1) way to compare two arbitrary substrings, at the price of being probabilistic.
  • Palindromes → Manacher. Centre expansion at O(n²) is fine for n ≤ 1000; get it right first, then switch.
  • Prefixes → a trie. Suffixes or arbitrary substring structure → suffix arrays or suffix automata (not covered on this site).