Strings

Problem shape

Advanced
4
8
15
16
23
42
Core idea

Precompute prefix information so mismatches skip redundant comparisons.

Step 1 / 5
Problem shape
Current lesson

KMP String Search Lab

Strings Advanced

KMP String Search

Welcome to the KMP String Search algorithm lab. Precompute prefix information so mismatches skip redundant comparisons. Use it when: Use for fast exact substring matching. The time complexity is O(n + m), and the space complexity is O(m). The pseudocode is: build lps pattern table i = 0, j = 0 while i < text length if text[i] == pattern[j] advance both else if j > 0 j = lps[j - 1] else i++ As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

O(n + m)

Space

O(m)

Pseudocode

build lps pattern table
i = 0, j = 0
while i < text length
  if text[i] == pattern[j] advance both
  else if j > 0 j = lps[j - 1]
  else i++
Open deeper structure lesson
1.0x