KMP Substring Search With Failure Table
The failure table records the longest equal prefix-suffix per position, letting the scan reuse matched characters instead of restarting.
Code
// failure table: length of the longest proper prefix that is also a suffix at pattern[i]
fn failure_table(pattern: &[u8]) -> Vec<usize> {
let mut table = vec![0; pattern.len()];
let mut prefix = 0;
for i in 1..pattern.len() {
while prefix > 0 && pattern[i] != pattern[prefix] {
prefix = table[prefix - 1];
}
if pattern[i] == pattern[prefix] {
prefix += 1;
}
table[i] = prefix;
}
table
}
fn find(text: &str, pattern: &str) -> Option<usize> {
if pattern.is_empty() {
return Some(0);
}
let (text, pattern) = (text.as_bytes(), pattern.as_bytes());
let table = failure_table(pattern);
let mut matched = 0;
for (i, &byte) in text.iter().enumerate() {
while matched > 0 && byte != pattern[matched] {
matched = table[matched - 1];
}
if byte == pattern[matched] {
matched += 1;
if matched == pattern.len() {
return Some(i + 1 - matched);
}
}
}
None
}
fn main() {
println!("failure table: {:?}", failure_table(b"ababaca"));
println!(
"find: {:?}",
find("bamboo ababaca", "ababaca")
);
println!("find missing: {:?}", find("bamboo", "zzz"));
}How it works
KMP Substring Search With Failure Table is built around the functions failure_table, find and main.
A single loop drives the file — for i in 1..pattern.len().
Points of care
- The language toolchain itself is the only prerequisite.
Putting it to use
The one signature that matters here is fn failure_table(pattern: &[u8]) -> Vec<usize>
Output lines are prefixed (failure table:, find:, find missing:), making the effect of each step easy to see.
Launch the file; main takes over and steps through failure_table and find.
The core lines of the flow
return Some(i + 1 - matched);
return Some(0);
matched += 1;
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does KMP Substring Search With Failure Table print when run?
- Execute the whole file; each printed line is prefixed with a label like `failure table:`, `find:`, `find missing:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.