Prefix function · Hard
A scanner searches a long in-memory text for the first occurrence of a pattern. Repetitive text makes restart-at-every-position matching quadratic. The scanner needs a worst-case linear algorithm, not a call to the built-in substring search.
Return the first zero-based index where pattern matches text exactly in worst-case linear time or -1 if it never matches.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "text": string, "pattern": string }.
Fields
- text and pattern are printable ASCII strings. Matching is case-sensitive; spaces count as characters.
Output
Return value
- Return an index into text, not the matched substring.
- An empty pattern matches at 0, including when text is empty.
- Do not call indexOf, includes, search, regular expressions or another substring-search library in the implementation.
Constraints
- 0 <= text.length, pattern.length <= 100000. ASCII codes are 32..126.
- The target bound is worst-case linear; repeated prefixes are tested.
Examples
Example 1
{
"pattern": "ababac",
"text": "abababac"
}Returns
2A mismatch must reuse an overlapping prefix.
Example 2
{
"pattern": "aaaa",
"text": "aaa"
}Returns
-1The pattern is longer than the text.
Required complexity
O(text.length + pattern.length) time and O(pattern.length) extra space