1. Empty pattern
Match empty pattern at index 0.
if (pattern.length === 0) return 0Typorithm · hard
Step 1 of 8 · intro card
Search Algorithms
KMP String Search uses a prefix table so mismatches do not force the text pointer to move backward.
KMP preprocesses the pattern into an LPS table.
LPS means longest proper prefix that is also a suffix.
When a mismatch happens after some matches, KMP moves the pattern pointer back using the table.
The text pointer never rewinds, so the search runs in O(n + m).
Build the LPS table from the pattern.
Use i for text and j for pattern.
On match, advance both.
On mismatch, fallback j with lps.
Time is O(n + m).
function kmpSearch(text, pattern) {
if (pattern.length === 0) return 0;
const lps = buildLps(pattern);
let i = 0;
let j = 0;
while (i < text.length) {
if (text[i] === pattern[j]) {
i++;
j++;
if (j === pattern.length) return i - j;
} else if (j > 0) {
j = lps[j - 1];
} else {
i++;
}
}
return -1;
}
function buildLps(pattern) {
const lps = Array(pattern.length).fill(0);
let length = 0;
let i = 1;
while (i < pattern.length) {
if (pattern[i] === pattern[length]) {
length++;
lps[i] = length;
i++;
} else if (length > 0) {
length = lps[length - 1];
} else {
i++;
}
}
return lps;
}Connect each part of the code to the concept before you type.
Match empty pattern at index 0.
if (pattern.length === 0) return 0Build the table that tells how far the pattern can fall back.
const lps = buildLps(pattern)i scans text and j scans pattern.
let i = 0;
let j = 0Advance both pointers on a matching character.
if (text[i] === pattern[j])When j reaches the pattern length, i - j is the start index.
if (j === pattern.length) return i - jOn mismatch, reuse the longest prefix that is also a suffix.
j = lps[j - 1]The helper computes fallback lengths for every pattern position.
function buildLps(pattern)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputText ababcabc · pattern abc · top row text, bottom row aligned pattern
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state