KMP String Matching Visualizer

Enter text and a pattern, build the LPS table, then step through KMP comparisons and fallback jumps.

Text
19
Pattern
9
Matches
0
Compares
0

String input

Step controls

Start KMP with text length 19 and pattern length 9.

Aligned comparison

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
A
B
A
B
D
A
B
A
C
D
A
B
A
B
C
A
B
A
B
A
B
A
B
C
A
B
A
B

LPS table

IndexCharLPS
0A0
1B0
2A1
3B2
4C0
5A1
6B2
7A3
8B4

KMP output

i = 0
j = 0
comparisons = 0
matches = []
No matches found yet.

What is a KMP String Matching Visualizer?

A KMP string matching visualizer shows how the Knuth-Morris-Pratt algorithm finds a pattern inside text without restarting the scan from scratch after every mismatch. It is useful for learning prefix functions, LPS tables, string searching, and coding interview pattern-matching problems.

This tool lets you enter text and a pattern, inspect the LPS table, then step through comparisons, fallbacks, and match indexes.

For the full algorithm set, browse the Data Structure Visualizers hub.

How to use this KMP visualizer

  • Enter the text to scan.
  • Enter the pattern to search for.
  • Click Run KMP to jump to the completed match list.
  • Step forward to watch text index i, pattern index j, matches, and LPS fallbacks.
  • Green text cells are completed matches, blue cells are the current comparison, and amber cells are the current aligned prefix.

KMP and the LPS table

KMP precomputes the longest proper prefix that is also a suffix for each pattern prefix. When a mismatch happens after several matched characters, the LPS value tells the algorithm where pattern index j can safely jump.

That fallback is the key difference from a naive string search. The text index does not need to move backward.

Compare this page with the Rabin Karp Visualizer to see string matching with rolling hashes instead of prefix fallback jumps.

Frequently Asked Questions

What does KMP stand for?
KMP stands for Knuth-Morris-Pratt, the names of the string matching algorithm's authors.
What is the LPS table?
The LPS table stores the length of the longest proper prefix that is also a suffix for each pattern prefix.
Why is KMP faster than naive string search?
KMP avoids rechecking text characters after a mismatch by using the LPS table to move the pattern pointer.
What is the time complexity of KMP?
KMP runs in O(n + m) time, where n is the text length and m is the pattern length.

Related tools