Math 2.0

Computer science Definition

Knuth–Morris–Pratt algorithm

Builds on AlphabetStringString-searching algorithm

Definition

Let P=p1⋯pmP = p_1 \cdots p_m and T=t1⋯tnT = t_1 \cdots t_n be strings over a finite alphabet, with m≥1m \ge 1. The failure function of PP is the map π ⁣:{1,…,m}→{0,…,m−1}\pi \colon \set{1, \dots, m} \to \set{0, \dots, m - 1} such that π(q)\pi(q) is the largest k<qk < q with p1⋯pk=pq−k+1⋯pqp_1 \cdots p_k = p_{q - k + 1} \cdots p_q. The Knuth–Morris–Pratt algorithm is the string-searching algorithm that computes π\pi and then runs these steps.

  1. Set q=0q = 0.
  2. For i=1,…,ni = 1, \dots, n: while q>0q > 0 and pq+1≠tip_{q + 1} \ne t_i, set q=π(q)q = \pi(q).
  3. Still for this ii: if pq+1=tip_{q + 1} = t_i, increase qq by 11.
  4. Still for this ii: if q=mq = m, report an occurrence at position i−m+1i - m + 1 and set q=π(m)q = \pi(m).

After step 3 for index ii, qq is the length of the longest prefix of PP that is a suffix of t1⋯tit_1 \cdots t_i.

Remarks

Example: for P=ababP = abab the failure function is π(1)=0\pi(1) = 0, π(2)=0\pi(2) = 0, π(3)=1\pi(3) = 1, π(4)=2\pi(4) = 2. For instance π(4)=2\pi(4) = 2 because abab is both a prefix and a suffix of abababab, while abaaba is not a suffix of it. On the text T=abababT = ababab the algorithm reports positions 11 and 33.

Non-example: the value k=qk = q is excluded in the failure function. Allowing it would give π(q)=q\pi(q) = q, and step 2 would never move the pattern.

The failure function itself is computed by the same scan applied to PP against itself, in time O(m)O(m). Each step 2 loop lowers qq, and qq rises by at most 11 per character, so the search takes time O(n)O(n) and the whole algorithm O(n+m)O(n + m).

Reading path

To understand this page from the ground up, read these 4 pages in order. The foundations come first.

Show the path as a graph
Each page uses the pages above it. The colour of the bar on a box shows how strong the evidence is, and the box also gives it as text. The list has the same pages.
  • no evidence level
  1. Alphabet concept
  2. String concept
  3. String-searching algorithm concept
  4. Knuth–Morris–Pratt algorithm definition

Further reading

  1. Web https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
About this page
TagXADN5F6SCP
URIm2://XADN5F6SCP
Kinddefinition
WritingW0 stub
MSC68W32, 68R15, 68W40
DefinesKnuth–Morris–Pratt algorithm
UsesAlphabet, String, String-searching algorithm
Changed3 November 2026

Markdown · JSON · Edit on GitHub

What this page needs for W1

  • an inventory row: the row of the inventory that the node accounts for (0 of 1)
  • a source with a locator (0 of 1)

The writing levels say how complete the text of a page is. They do not measure its truth.

What links here

No page links to this page yet.