KMP String Matching - Problem
The KMP (Knuth-Morris-Pratt) algorithm is an efficient string matching algorithm that finds all occurrences of a pattern within a text string in linear time.
Your task is to implement the complete KMP algorithm:
- Build the failure function (also called prefix function or LPS array)
- Use the failure function to perform pattern matching
- Return a list of all starting indices where the pattern occurs in the text
The failure function lps[i] stores the length of the longest proper prefix of pattern[0...i] that is also a suffix of pattern[0...i].
Example: For pattern "ABABCABAB", the failure function is [0,0,1,2,0,1,2,3,4]
Input & Output
Example 1 — Basic Pattern Matching
$
Input:
text = "ABABCABAB", pattern = "ABAB"
›
Output:
[0,5]
💡 Note:
Pattern 'ABAB' appears at index 0 (ABAB-CABAB) and index 5 (ABABC-ABAB). The KMP algorithm finds both occurrences efficiently using the failure function.
Example 2 — No Matches
$
Input:
text = "HELLO", pattern = "WORLD"
›
Output:
[]
💡 Note:
Pattern 'WORLD' does not appear anywhere in text 'HELLO', so return empty array.
Example 3 — Overlapping Patterns
$
Input:
text = "AAAA", pattern = "AA"
›
Output:
[0,1,2]
💡 Note:
Pattern 'AA' appears at positions 0 (AA-AA), 1 (A-AA-A), and 2 (AA-AA). KMP handles overlapping matches correctly.
Constraints
- 1 ≤ text.length ≤ 104
- 1 ≤ pattern.length ≤ 103
- text and pattern contain only uppercase English letters
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code