Finding a word inside a long text sounds simple until repeated letters make a naive search revisit the same characters. The Knuth–Morris–Pratt algorithm, usually called KMP, preprocesses the pattern so that a mismatch does not erase everything already learned. Its prefix function records the length of the longest proper prefix that is also a suffix of each pattern prefix. That border information says how far the candidate match can fall back while keeping characters already proved equal. Mathematics matters because equality, induction and a potential-style amortised argument turn a clever reuse rule into a worst-case linear-time guarantee.
The practical search question is not simply “what is this named method?” but “which mathematical structure makes the method work, what does it guarantee, and what evidence would show that it is a poor choice?” This article keeps those questions together so students can connect mathematics education with computing, engineering, data reasoning and careful everyday decisions without turning one technique into a career promise.
Quick navigation: Why it matters · Mechanism · Worked example · Deeper ideas · Investigations · Limits · Learning route · Parent guidance · FAQs · Sources
Why this mathematics matters
Mathematics is important here because it turns an apparently visual or computational trick into a chain of reasons. The representation tells us what information is kept. The equation or invariant explains each legal step. The complexity analysis describes the work. The boundary conditions say when a conclusion should not be trusted. That combination is a practical form of problem-solving literacy.
A strong learner should be able to move in both directions: from a real task to a mathematical model, and from a formal guarantee back to its real meaning. Naming an algorithm is not enough. The useful achievement is to explain why the next operation is valid, check a small instance independently, and notice which assumptions the implementation has added.
Source: SIAM record for Knuth, Morris and Pratt’s 1977 string-matching paper.
Primary or implementation reference: Archived copy of “Fast Pattern Matching in Strings”.
How the mechanism works
First compute the prefix array π for the pattern. At position i, let j be the border length inherited from i−1. While the next pattern characters disagree, replace j by π[j−1]; if they agree, increase j. During the text scan, j means that the first j pattern characters equal the latest j text characters. On a mismatch, repeatedly move j to π[j−1] without moving the text index backwards. On a match, increment j. When j reaches the pattern length, report an occurrence and set j to π[j−1] if overlapping matches are wanted. The same fallback chain supports both preprocessing and search.
For a string P, π[i]=max{k:0≤k<i+1 and P[0..k−1]=P[i−k+1..i]}; the strict inequality makes the border proper. The search invariant is P[0..j−1]=T[i−j+1..i] after processing text position i. A failed extension can only preserve a candidate that is itself a border, hence j←π[j−1]. Although one text character can trigger several fallbacks, j increases at most once per processed character and every fallback decreases it. Summed over the run, increases and decreases are linear, giving O(m+n) time for pattern length m and text length n, plus O(m) storage.
Keep a four-column notebook labelled object, rule, guarantee and caveat. In the first column name the inputs and stored state. In the second write one update precisely. In the third state what remains true after the update. In the fourth record a tie, approximation, domain restriction or hardware assumption. This routine prevents symbols from drifting away from their meaning.
Worked example and core calculations
Take pattern P=ABABAC. Its prefix values are [0,0,1,2,3,0]: ABABA has border ABA of length 3, while the final C destroys every nonempty border. Search text T=ABABABAC. After matching ABABA, the next text character is B but P[5] is C. KMP does not restart at the next text position. It falls back from j=5 to π[4]=3; the same B now matches P[3], and the scan continues through A and C. The full pattern ends at text index 7, so the occurrence starts at 7−6+1=2. No text character was moved backwards.
How to audit the calculation
- Recompute every intermediate value directly from the definition.
- Keep labels, indices, signs, units and normalisation visible.
- Test a case with a known exact answer.
- State tie rules, random seeds, tolerances and boundary conventions.
- Compare with a slower transparent baseline or trusted implementation.
- Separate agreement of numbers from suitability of the real-world model.
Small examples are not childish; they are diagnostic instruments. A five-line trace can reveal a reversed inequality, a missing scale factor or an inconsistent label convention before a large dataset hides the same error behind plausible output.
Four deeper ideas
Borders are reusable evidence
A border is simultaneously a prefix and suffix. When a longer candidate fails, its borders are the only shorter candidates consistent with characters already matched.
To transfer this idea, ask what would remain true if labels, scale or input order changed. Then identify the step whose justification would fail if the stated assumption were removed. This turns the paragraph into a reusable reasoning pattern rather than a fact to memorise.
Did you know? The prefix table is built by the same idea as the search
Preprocessing treats the pattern as its own stream: a mismatch follows earlier borders, so table construction is linear for the same amortised reason.
To transfer this idea, ask what would remain true if labels, scale or input order changed. Then identify the step whose justification would fail if the stated assumption were removed. This turns the paragraph into a reusable reasoning pattern rather than a fact to memorise.
Linear time is a global accounting result
One iteration may perform several fallbacks. The proof counts all rises and falls of j over the whole scan rather than claiming constant work at every character.
To transfer this idea, ask what would remain true if labels, scale or input order changed. Then identify the step whose justification would fail if the stated assumption were removed. This turns the paragraph into a reusable reasoning pattern rather than a fact to memorise.
Exact matching still needs a representation contract
Unicode normalisation, case folding, token boundaries and byte versus character indexing can change what “the same string” means before KMP begins.
To transfer this idea, ask what would remain true if labels, scale or input order changed. Then identify the step whose justification would fail if the stated assumption were removed. This turns the paragraph into a reusable reasoning pattern rather than a fact to memorise.
Twelve practical investigations
1. Prefix-table trace
Build π for ABABAC. Record j before and after every comparison.
What the mathematics reveals: Borders encode reusable matches. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: A proper prefix cannot equal the full prefix. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
2. Overlapping matches
Search AAAAA for AAA. Resume from π[m−1] after each hit.
What the mathematics reveals: One character can belong to several occurrences. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Resetting to zero would miss overlaps. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
3. No match
Search a repeated-pattern text for a final differing symbol. Count comparisons and fallbacks.
What the mathematics reveals: Worst-case repetition remains linear. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Do not infer constant comparisons per position. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
4. Single character
Use a one-symbol pattern. Show π=[0] and scan directly.
What the mathematics reveals: Boundary cases simplify the invariant. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Define empty-pattern behaviour separately. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
5. Empty pattern policy
Pass an empty pattern to an API. Inspect its documented result.
What the mathematics reveals: Mathematics permits conventions; software must choose one. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Do not index P[0] blindly. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
6. Unicode normalisation
Compare composed and decomposed accents. Normalise before searching.
What the mathematics reveals: Visual sameness can differ from code-point equality. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Record the chosen normal form. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
7. Case folding
Search a case-insensitive corpus. Transform both sides consistently.
What the mathematics reveals: Preprocessing depends on the equality relation. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Locale rules can matter. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
8. Token search
Look for he inside the. Add boundary conditions.
What the mathematics reveals: Substring matching differs from word matching. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Tokenisation is a separate model. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
9. Streaming text
Feed chunks without discarding j. Carry the KMP state across boundaries.
What the mathematics reveals: The invariant supports online processing. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Retain enough indexing information for reports. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
10. Many patterns
Search thousands of keywords. Compare with a trie automaton.
What the mathematics reveals: KMP is a one-pattern design. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Aho–Corasick may share work better. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
11. Library benchmark
Compare KMP with a standard search routine. Use controlled pattern and text families.
What the mathematics reveals: Worst-case guarantees and constants differ. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Benchmarking one input proves little. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
12. Property testing
Generate random strings. Compare all positions with a naive baseline.
What the mathematics reveals: A slow oracle validates exact results. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Keep seeds and include repeated alphabets. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
Limits and misconceptions
KMP solves exact pattern matching under a chosen equality rule. It does not by itself handle spelling variation, approximate matches, semantic similarity, regular expressions or locale-aware collation. Preprocessing is worthwhile when the pattern is nonempty and the representation is stable; library routines may outperform a handwritten version through vectorisation or specialised search heuristics. The prefix array consumes pattern-sized memory. Returning every occurrence can require output proportional to the number of matches. Unicode text should be normalised deliberately, and indexing code points is not the same as indexing grapheme clusters. Linear worst-case time does not mean every use is fastest in practice, and finding a substring does not establish context, authorship or meaning.
Five misconceptions to challenge
- A mismatch always restarts at pattern position zero: KMP follows the longest border that could still match.
- The text pointer moves backwards: Only the pattern state falls back.
- Each character causes constant work individually: Some cause several fallbacks; the total is linear by amortised analysis.
- The prefix value counts every repeated substring: It counts only the longest proper prefix that is also a suffix.
- Exact string equality settles language meaning: Normalisation, tokenisation and context are separate decisions.
Another broad misconception is that advanced mathematics automatically creates intelligence, admission, income or employment. It does not. Deliberate study can strengthen modelling, abstraction, calculation and explanation, while real pathways also depend on interests, communication, domain knowledge, opportunities and circumstances outside one topic.
A learning route for students
Move from a visible trace to a symbolic rule, then to code and critique. For every step below, prepare three pieces of evidence: a correct hand example, a boundary or failure case, and a short explanation using the relevant invariant. Do not advance merely because software returned a number.
Step 1: Identify borders of a string
Begin with the smallest non-trivial instance that lets you identify borders of a string. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 2: Compute a prefix function
Begin with the smallest non-trivial instance that lets you compute a prefix function. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 3: State the search invariant
Begin with the smallest non-trivial instance that lets you state the search invariant. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 4: Trace fallback transitions
Begin with the smallest non-trivial instance that lets you trace fallback transitions. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 5: Prove amortised linear time
Begin with the smallest non-trivial instance that lets you prove amortised linear time. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 6: Report overlapping matches
Begin with the smallest non-trivial instance that lets you report overlapping matches. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 7: Handle empty-pattern policy
Begin with the smallest non-trivial instance that lets you handle empty-pattern policy. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 8: Define a text equality convention
Begin with the smallest non-trivial instance that lets you define a text equality convention. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 9: Compare one-pattern and many-pattern search
Begin with the smallest non-trivial instance that lets you compare one-pattern and many-pattern search. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 10: Test against a naive oracle
Begin with the smallest non-trivial instance that lets you test against a naive oracle. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
A four-week practice plan
- Week 1 — vocabulary and diagrams: define each object, redraw the mechanism and reproduce the worked example.
- Week 2 — equations and manufactured tests: derive the key relation and test inputs with known answers.
- Week 3 — implementation and evidence: use a trusted library, record parameters and compare with a transparent baseline.
- Week 4 — transfer and critique: apply the method to a new context, report limits and identify when a different method is better.
Guidance for parents and educators
Ask “what stays true?” and “what could make this conclusion fail?” before asking for speed. Invite the student to draw the input and output, estimate the result and locate the first step that disagrees with a reference. These prompts reveal conceptual understanding more clearly than memorised terminology.
Advanced enrichment should sit beside secure school foundations in algebra, functions, geometry, statistics and computational thinking. It need not accelerate a student into a fixed career identity. A healthy goal is curiosity with discipline: the learner becomes comfortable reading unfamiliar notation, checking an example, revising a model and communicating uncertainty.
Evidence prompts for a useful conversation
- Which quantity is observed and which is inferred?
- Which step saves work, and why is it allowed?
- Is the claim exact, approximate, probabilistic or empirical?
- What units and conventions are in use?
- Which input makes the method struggle?
- What simple baseline could check the answer?
- What would count as evidence that the parameters are poor?
Mini-project assessment
A strong mini-project contains the original question, a small reproducible dataset, a hand-worked example, code or a spreadsheet trace, at least one boundary test, a comparison with a baseline, and a paragraph on limits. Assess the reasoning trail as well as the final output. Repairing a model after a surprising result is valuable mathematical progress.
Six evidence checks for a finished project
Check 1: Identify borders of a string
Ask the student to demonstrate how to identify borders of a string without relying on a hidden software step. The evidence should include a labelled input, the exact rule used, one intermediate state and a result that can be checked independently. If the answer changes after labels or order change, the student should say whether that reflects the mathematics or only a convention.
Then request one deliberately awkward example. The learner should predict the difficulty before running the method, explain what the output does and does not establish, and name a reasonable alternative or safeguard. This check joins correctness with judgement: a technically valid calculation is useful only when its assumptions and interpretation remain visible.
Check 2: Compute a prefix function
Ask the student to demonstrate how to compute a prefix function without relying on a hidden software step. The evidence should include a labelled input, the exact rule used, one intermediate state and a result that can be checked independently. If the answer changes after labels or order change, the student should say whether that reflects the mathematics or only a convention.
Then request one deliberately awkward example. The learner should predict the difficulty before running the method, explain what the output does and does not establish, and name a reasonable alternative or safeguard. This check joins correctness with judgement: a technically valid calculation is useful only when its assumptions and interpretation remain visible.
Check 3: State the search invariant
Ask the student to demonstrate how to state the search invariant without relying on a hidden software step. The evidence should include a labelled input, the exact rule used, one intermediate state and a result that can be checked independently. If the answer changes after labels or order change, the student should say whether that reflects the mathematics or only a convention.
Then request one deliberately awkward example. The learner should predict the difficulty before running the method, explain what the output does and does not establish, and name a reasonable alternative or safeguard. This check joins correctness with judgement: a technically valid calculation is useful only when its assumptions and interpretation remain visible.
Check 4: Trace fallback transitions
Ask the student to demonstrate how to trace fallback transitions without relying on a hidden software step. The evidence should include a labelled input, the exact rule used, one intermediate state and a result that can be checked independently. If the answer changes after labels or order change, the student should say whether that reflects the mathematics or only a convention.
Then request one deliberately awkward example. The learner should predict the difficulty before running the method, explain what the output does and does not establish, and name a reasonable alternative or safeguard. This check joins correctness with judgement: a technically valid calculation is useful only when its assumptions and interpretation remain visible.
Check 5: Prove amortised linear time
Ask the student to demonstrate how to prove amortised linear time without relying on a hidden software step. The evidence should include a labelled input, the exact rule used, one intermediate state and a result that can be checked independently. If the answer changes after labels or order change, the student should say whether that reflects the mathematics or only a convention.
Then request one deliberately awkward example. The learner should predict the difficulty before running the method, explain what the output does and does not establish, and name a reasonable alternative or safeguard. This check joins correctness with judgement: a technically valid calculation is useful only when its assumptions and interpretation remain visible.
Check 6: Report overlapping matches
Ask the student to demonstrate how to report overlapping matches without relying on a hidden software step. The evidence should include a labelled input, the exact rule used, one intermediate state and a result that can be checked independently. If the answer changes after labels or order change, the student should say whether that reflects the mathematics or only a convention.
Then request one deliberately awkward example. The learner should predict the difficulty before running the method, explain what the output does and does not establish, and name a reasonable alternative or safeguard. This check joins correctness with judgement: a technically valid calculation is useful only when its assumptions and interpretation remain visible.
Frequently asked questions
What does KMP find?
Exact occurrences of one pattern in a text.
What is a border?
A proper prefix that is also a suffix.
What does π[i] store?
The length of the longest border of the prefix ending at i.
Why does the text index not retreat?
The border state reuses the suffix already known to match.
What is the time complexity?
O(m+n) for preprocessing and search.
Can it find overlapping occurrences?
Yes, by falling back with the prefix table after a match.
Does it support approximate matching?
No, that requires a different model.
What about an empty pattern?
Choose and document an API convention.
Is KMP always the fastest implementation?
No; constants, libraries and input distributions matter.
What should students know first?
String indices, prefixes, suffixes, loops and invariants.
Useful next reading and sources
Source: SIAM record for Knuth, Morris and Pratt’s 1977 string-matching paper.
Source: Archived copy of “Fast Pattern Matching in Strings”.
Related eduKateSG reading: Boyer–Moore search and text skips.
Related eduKateSG reading: Aho–Corasick multi-pattern matching.
Related eduKateSG reading: Hirschberg linear-space sequence alignment.
Read sources with a question in mind: which definition, theorem, default or limitation is being supported? An authoritative link is useful evidence, but it does not replace a worked calculation or a clear statement of how the source applies to the example.
A cheerful final thought
Mathematics becomes friendlier when every symbol has a job and every claim has a boundary. Start small, make the state visible, test the awkward case, and celebrate the moment when a pattern becomes explainable. That is the practical benefit of learning mathematics: not certainty about every future, but a growing ability to ask better questions and build trustworthy answers.
