Pattern Matching Automaton - Problem

Build a deterministic finite automaton (DFA) from a given pattern and simulate it to find all matches in a text string. A DFA is a state machine that processes characters one by one and determines if the current prefix matches the pattern or leads to a potential match.

Given a pattern string pattern and a text string text, return an array of all starting indices where the pattern appears in the text.

The automaton should use the failure function (similar to KMP algorithm) to efficiently handle mismatches by jumping to the appropriate state rather than restarting from the beginning.

Example: If pattern = "aba" and text = "abababa", the pattern appears at indices [0, 2, 4], so return [0, 2, 4].

Input & Output

Example 1 — Basic Pattern Matching
$ Input: pattern = "aba", text = "abababa"
Output: [0,2,4]
💡 Note: Pattern 'aba' appears at indices 0 ('aba'babba), 2 (ab'aba'ba), and 4 (abab'aba')
Example 2 — No Matches
$ Input: pattern = "abc", text = "def"
Output: []
💡 Note: Pattern 'abc' does not appear anywhere in text 'def'
Example 3 — Single Character Pattern
$ Input: pattern = "a", text = "aaa"
Output: [0,1,2]
💡 Note: Single character 'a' appears at every position: indices 0, 1, and 2

Constraints

  • 1 ≤ pattern.length ≤ 1000
  • 1 ≤ text.length ≤ 104
  • pattern and text consist of lowercase English letters only

Visualization

Tap to expand
INPUTALGORITHMRESULTPattern: ABAABAText: ABABABAABABABA01234561Build Failure Functionfailure = [0, 0, 1]2Scan Text with DFASmart state transitions3Record MatchesWhen pattern fully matched4Continue ScanningLinear time O(n + m)Matches Found:[0, 2, 4]Pattern appears at:• Index 0: ABA|baba• Index 2: ab|ABA|ba• Index 4: abab|ABA✓ Linear TimeO(n + m) complexityNo backtracking neededKey Insight:The failure function pre-computes how much of the pattern can be reused after a mismatch,enabling linear-time pattern matching without backtracking in the text.TutorialsPoint - Pattern Matching Automaton | KMP Algorithm
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
23.4K Views
Medium Frequency
~35 min Avg. Time
892 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