Study Atlas › Computer Science › Algorithms

String algorithms and pattern matching

Efficient methods to search for patterns in text.

Edited by Alex C, EduAlx · Sources cited below

Explanation

Naive search is O(nm). Knuth–Morris–Pratt (1977) uses a failure function for O(n + m). Boyer–Moore skips ahead using bad-character rules. Rabin–Karp uses rolling hashes. Suffix arrays and tries index text; regular expressions compile to finite automata.

Example

grep and text editors' 'find' use these techniques.

Code

def kmp_table(p):
    t, k = [0]*len(p), 0
    for i in range(1, len(p)):
        while k and p[i] != p[k]: k = t[k-1]
        if p[i] == p[k]: k += 1
        t[i] = k
    return t

How it works, step by step

  1. Preprocess the pattern
  2. Scan the text
  3. On mismatch, shift using precomputed tables
  4. Report matches

Open the interactive page with diagrams →

People behind it

References

  1. D. E. Knuth, J. H. Morris, V. R. Pratt, SIAM J. Comput. 1977, 6, 323–350.
  2. R. S. Boyer, J. S. Moore, Commun. ACM 1977, 20, 762–772.

Textbooks

Related topics

Algorithms and Big-O complexityGreedy algorithms and minimum spanning treesSorting algorithms (quicksort, mergesort, heapsort)Dynamic programmingGraph algorithms: BFS, DFS and Dijkstra's shortest pathAutomata and formal languagesMemory hierarchy and cachesHeaps and priority queuesPipelining and parallel processorsRecursion