Command Palette

Search for a command to run...

Module 35

Advanced String Algorithms

Linear-time pattern matching with KMP and the Z-function, rolling hashes for comparing many substrings, and where Manacher fits.

Advanced 3 lessons 7 problems ~45 min of lessons

Searching for a pattern of length m in a text of length n by trying every start costs O(n × m) in the worst case. The algorithms in this module avoid re-reading characters: KMP and the Z-function remember how much of the pattern already matched, and rolling hashes compare whole substrings by number in O(1).

You'll build the KMP failure table step by step, compute Z-arrays, use Rabin-Karp hashing with collision checks, and apply them to classic problems: first occurrence, repeated patterns, shortest palindromes, happy prefixes, repeated DNA and the longest duplicated substring.

Best after: Strings, Hashing

Where this shows up in real systems

Part 1

Learn the ideas

Part 2

Solve the problems

Work through them in order. Each one shows the pattern it teaches.

  1. KMP end to end: build lps, then scan the text once.

  2. The lps of the whole string reveals its smallest period.

  3. Every rotation of s is a substring of s + s.

  4. The answer is exactly lps[n − 1].

  5. KMP on s + '#' + reverse(s) finds the longest palindromic prefix in O(n).

  6. A rolling 2-bit-per-letter code makes each 10-letter window a 20-bit integer.

  7. Binary search on the length, with a rolling-hash check for each length.