Comparison Mode

Side-by-side: use case, requirements, complexity, strengths, weaknesses, example problems, and a clear “choose this when…”.

KMPStrings
Rabin-KarpStrings
Use caseFind one pattern in a text deterministically in linear time.Find one or many patterns by comparing rolling hashes; substring fingerprinting.
RequirementsThe failure (LPS) table of the pattern.A rolling hash with a modulus and base; a hash set of pattern hashes for multiple patterns.
Time complexityO(n + m) worst case.Expected O(n + m); worst O(n * m) with many collisions.
Space complexityO(m) for the table.O(1) per pattern hash (plus the set for multiple patterns).
StrengthsGuaranteed linear; never re-reads text characters; the failure table itself solves prefix/suffix problems.Simple to write; extends naturally to many patterns, 2D matching and duplicate-substring detection.
WeaknessesOne pattern at a time; the table construction is fiddly to write under pressure.Probabilistic unless matches are verified; collisions can be engineered against a fixed modulus.
Example problemsImplement strStr, shortest palindrome, repeated substring pattern.Repeated DNA sequences, longest duplicate substring, implement strStr.
Choose this whenChoose KMP when you need a deterministic linear-time single-pattern search or need the prefix function itself.Choose Rabin-Karp when searching for many patterns of the same length, comparing many substrings, or when simplicity beats determinism.