Skip to content

Resource · Guide or article

Knuth–Morris–Pratt Algorithm

KMP string search in one paragraph: when a mismatch happens, information in the pattern tells the search where to resume, so matched characters are not checked again.

Reviewed

Open the original: Knuth–Morris–Pratt Algorithm (opens the original site in a new tab)

Practice this topicOpens the practice interviewer in Technical / coding mode; choose a question there.

Add to a roadmap

Keep this resource with a roadmap you follow. It appears as your own extra resource; the roadmap's steps don't change and it doesn't count toward your tracked steps.

Source content: English

The Knuth–Morris–Pratt string searching algorithm (or KMP algorithm) searches for occurrences of a "word" W within a main "text string" T by employing the observation that when a mismatch occurs, the word itself embodies sufficient information to determine where the next match could begin, thus bypassing re-examination of previously matched characters.

PrepKit overview

PrepKit editors wrote and reviewed this overview from the source repository. It is not text from the resource itself.

Suited to
The source does not state a level
Format
Reference

What it covers

  • States the core idea of skipping re-examination after a mismatch
  • Gives time O(|W| + |T|) against the naive O(|W| * |T|), and space O(|W|)

How to use it

PrepKit study advice, not a claim made by the source.

Build the prefix (failure) table for a few patterns by hand using an outside source, then use this page to check your complexity explanation.

Scope and limitations

No explanation of the prefix table, no walkthrough and no exercises. Learning the method depends on the linked Wikipedia and YouTube references.

Access and format

Brief README on GitHub, trekhleb/javascript-algorithms (MIT). English, free.

Reviewed by PrepKit on Oct 2, 2026. Listing source commit: 85293e3e2b88

Evidence behind this overview
  • src/algorithms/string/knuth-morris-pratt/README.md

Pages that include this

Get the PrepKit newsletter

Optional. You don't need it to use PrepKit.

How we handle your email