Hostname: page-component-6766d58669-76mfw Total loading time: 0 Render date: 2026-05-16T03:22:21.252Z Has data issue: false hasContentIssue false

Knuth–Morris–Pratt illustrated

Published online by Cambridge University Press:  30 January 2024

CAMERON MOY*
Affiliation:
Northeastern University, Boston, MA 02115, USA (e-mail: camoy@ccs.neu.edu)
Rights & Permissions [Opens in a new window]

Abstract

The Knuth–Morris–Pratt (KMP) algorithm for string search is notoriously difficult to understand. Lost in a sea of index arithmetic, most explanations of KMP obscure its essence. This paper constructs KMP incrementally, using pictures to illustrate each step. The end result is easier to comprehend. Additionally, the derivation uses only elementary functional programming techniques.

Information

Type
Functional Pearl
Creative Commons
Creative Common License - CCCreative Common License - BY
This is an Open Access article, distributed under the terms of the Creative Commons Attribution licence (http://creativecommons.org/licenses/by/4.0/), which permits unrestricted re-use, distribution and reproduction, provided the original article is properly cited.
Copyright
© The Author(s), 2024. Published by Cambridge University Press
Figure 0

Fig. 1. Naive string search (horizontal).

Figure 1

Fig. 2. Naive string search (vertical).

Figure 2

Fig. 3. Columns as lists.

Figure 3

Fig. 4. Column shapes with forward arrows.

Figure 4

Fig. 5. Column shapes with backward arrows.

Figure 5

Fig. 6. MP graph.

Figure 6

Fig. 7. KMP graph.

Figure 7

Fig. 8. KMP algorithm.

Submit a response

Discussions

No Discussions have been published for this article.