AlgoScope

Knuth-Morris-Pratt

AlgorithmintermediateString Matchingalso called KMP

On a mismatch, drop j to pi[j - 1] so the pattern slides without re-reading any text character.

Decision · step 2 of 11String Matching: KMP, no re-reading
txtpatpiabcabcabda✓bcabd000120a = a

'a' matches pattern[0], j = 1.

Open in the player →or start at step 2

What you will see

COMPARE -> MISMATCH -> FALLBACK; the pattern jumps by the prefix-table amount and the text pointer never moves back.

How string matching works →

Cost

BestO(n + m)
AverageO(n + m)
WorstO(n + m)
SpaceO(m)

How you work with it here

play it through, step one change at a time, scrub to any step, run it on your own input, predict what happens next.

Screen readers: Text and pattern cells announce index and character; each step announces the aligned positions, the comparison result and the shift.

Reduced motion: The pattern row snaps to its new alignment with a crossfade instead of sliding.

Leads to

Topics that need this one first.

Taught by the same lesson

String Matching covers these too, in the same run.