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:

  1. Build the failure function (also called prefix function or LPS array)
  2. Use the failure function to perform pattern matching
  3. 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
INPUTALGORITHMRESULTText: ABABCABABABABCABABPattern: ABABABABFind all positions wherepattern occurs in text1Build Failure FunctionLPS = [0, 0, 1, 2]2Pattern MatchingUse LPS to skip on mismatch3Linear Time O(n+m)Never re-examine characters4Collect All MatchesReturn array of indicesMatches Found[0, 5]Position 0: ABABPosition 5: ABABEfficiency:Time: O(n + m)Space: O(m)Key Insight:Pre-analyzing the pattern's internal structure allows intelligent skipping during matching,achieving linear time complexity without ever re-examining text characters.TutorialsPoint - KMP String Matching | Advanced Algorithm
Asked in
Google 85 Microsoft 72 Amazon 65 Facebook 58
28.5K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen