Prefix function · Medium
A text analyzer counts every position at which an exact pattern begins. Matches may share characters, so skipping ahead by the full pattern length after a match would lose valid occurrences. Long repeated prefixes also make repeated substring comparisons too expensive.
Count every exact occurrence of pattern in text including overlapping matches and explicitly defined empty-pattern boundaries.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ text: string, pattern: string }
Fields
- text is the searched string; pattern is the exact sequence to match.
- Strings contain printable ASCII characters only. Comparisons are case-sensitive; spaces count as characters.
Output
Return value
- Return an integer count. Overlaps count separately because their starting positions differ.
- An empty pattern matches at every boundary, including both ends: return text.length + 1.
Constraints
- 0 <= text.length <= 200000; 0 <= pattern.length <= 100000.
Examples
Example 1
{
"pattern": "aa",
"text": "aaaa"
}Returns
3Example 2
{
"pattern": "",
"text": "abc"
}Returns
4Required complexity
O(n + m) time and O(m) auxiliary space