Skip to main content

String Algorithms

Efficient algorithms for string matching, searching, and processing beyond brute force.

KMP (Knuth-Morris-Pratt)

Pattern matching using a failure function (prefix table) to avoid redundant comparisons.

Key Idea

Precompute the longest proper prefix which is also a suffix (LPS array) for the pattern. On mismatch, use LPS to skip characters.
  • Time: O(n + m), Space: O(m)

Rabin-Karp

Uses rolling hash to compare pattern with substrings of text.

Key Idea

  • Compute hash of pattern and hash of each window of text
  • On hash match, verify character by character (to handle collisions)
  • Time: O(n + m) average, O(n × m) worst case
  • Good for multiple pattern matching

Z-Algorithm

Builds a Z-array where Z[i] = length of the longest substring starting from i that matches a prefix.
  • Concatenate: pattern + "$" + text, then build Z-array
  • Time: O(n + m)
  • Simpler to implement than KMP for some problems

Manacher’s Algorithm

Finds the longest palindromic substring in O(n) time.

Key Idea

  • Transform string ("abc""#a#b#c#") to handle even-length palindromes
  • Maintain a center and right boundary of the rightmost palindrome
  • Use previously computed values to skip work
  • Time: O(n), Space: O(n)

Rolling Hash

A hash function that can be updated in O(1) when the window slides.
  • Used in Rabin-Karp
  • Useful for substring comparison, duplicate detection
  • Polynomial hash: hash = s[0]*b^(n-1) + s[1]*b^(n-2) + ... + s[n-1]

Comparison

Classic Problems

  • Implement strStr() / Find the Index
  • Repeated Substring Pattern
  • Shortest Palindrome (KMP)
  • Longest Happy Prefix
  • Longest Palindromic Substring (Manacher’s)
  • Distinct Substrings (rolling hash)
  • Minimum Window Substring (sliding window, not string algo per se)