All practice tasks

Coding (Algo)

Find a Pattern in a Stream

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

2

A mismatch must reuse an overlapping prefix.

Example 2

{
  "pattern": "aaaa",
  "text": "aaa"
}

Returns

-1

The pattern is longer than the text.

Required complexity

O(text.length + pattern.length) time and O(pattern.length) extra space

What this task practices

Find a Pattern in a Stream is a coding (algo) interview exercise that trains prompt interpretation, explicit assumptions, a concrete response, and a clear explanation of tradeoffs. The catalog marks it as hard difficulty. It focuses on Technical Reasoning, Testing, Validation. The signed-in workspace provides the tools for the round and evaluates the attempt against task-specific criteria. Reference solutions, hidden checks, evaluator instructions, and candidate work remain private.

Sign in to startThe workspace and evaluation open after sign in.