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
- Preprocess the pattern
- Scan the text
- On mismatch, shift using precomputed tables
- Report matches
Open the interactive page with diagrams →
People behind it
- Donald Knuth (b. 1938), Computer science, USA: Stanford professor; author of The Art of Computer Programming and creator of TeX. Turing Award 1974.
- James H. Morris
- Vaughan Pratt
- Robert S. Boyer
- J Strother Moore
- Michael O. Rabin
- Richard Karp (b. 1935), Theoretical computer science, USA: Showed 21 problems are NP-complete (1972). Turing Award 1985.
References
- D. E. Knuth, J. H. Morris, V. R. Pratt, SIAM J. Comput. 1977, 6, 323–350.
- R. S. Boyer, J. S. Moore, Commun. ACM 1977, 20, 762–772.
Textbooks
- Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein (MIT Press, 4th ed. 2022). 'CLRS', the standard algorithms text.
- Algorithms, Robert Sedgewick, Kevin Wayne (Addison-Wesley, 4th ed. 2011). Practical algorithms with Java code.
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