Count Pattern Hits in a Log Stream With a KMP Automaton
Last updated: November 29, 2026
Quick Overview
Given a pattern string, build a deterministic finite automaton whose states are the lengths of the matched prefix, then feed a character stream through it and count every (possibly overlapping) occurrence of the pattern without ever looking back at earlier characters.
0
0
0 solved
Given a pattern string, build a deterministic finite automaton whose states are the lengths of the matched prefix, then feed a character stream through it and count every (possibly overlapping) occurrence of the pattern without ever looking back at earlier characters.
A Google onsite question for streaming log scanning, where buffering the stream is not allowed. The interviewer checks that you can derive the automaton from the prefix function, handle overlapping matches through the accept state's transitions, and explain why each character costs O(1).
What the Interviewer Expects
- Compute the KMP prefix (failure) function correctly
- Build transitions for each state and alphabet character
- Map characters outside the pattern's alphabet straight to state 0
- Count a match on reaching state m and continue from that state's transitions for overlaps
- Explain O(m * sigma) build and O(1) per streamed character
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you scan for many patterns at once? (Aho-Corasick)
- How would you make the automaton case-insensitive?
- How would you persist the automaton state across log file rotations?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: non-empty pattern and an iterable stream of characters (could be unbounded). Output the number of positions where the pattern ends. Overlaps count: pattern aa in aaa occurs twice. Memor...
High-Level Design
Let m = len(pattern) and pi the prefix function. State j means the last j characters match pattern[:j]. Transition delta(j, c): if j < m and pattern[j] == c, go to j + 1; else if `j ...