KatInterview

Locate the First Occurrence of a Needle in a Haystack

StringsAuto-graded · 27 test cases
MediumAuto-gradedStringsstringskmptwo-pointers

Last updated

Find the earliest starting index of a pattern inside a text in linear time, handling empty inputs and repetitive patterns, using a prefix-function (KMP-style) scan.

You are given two strings: a haystack and a needle. Return the zero-based index at which needle first appears as a contiguous substring of haystack. If needle never appears, return -1.

Rules:

  • Matching is exact and case-sensitive, comparing characters one by one.
  • If needle is the empty string, return 0, even when haystack is also empty.
  • If haystack is empty and needle is not, return -1.
  • If needle is longer than haystack, return -1.
  • Overlapping occurrences are allowed, and you must report the one with the smallest starting index.

Do not use built-in substring search helpers such as str.find, str.index, in, or regular expressions. Aim for a solution that runs in O(n + m) time using O(m) extra space, where n is the length of haystack and m is the length of needle. A naive approach that restarts the comparison at every offset can be too slow on repetitive inputs.

Constraints

  • 0 <= len(haystack), len(needle) <= 10^5
  • Both strings consist of arbitrary characters (any Unicode code points); indices refer to characters, not bytes.
  • The function returns a single integer: the first starting index, or -1.

Examples

Example 1

Input: find_first_occurrence('hello world', 'world')

Output: 6

Example 2

Input: find_first_occurrence('aaaaaa', 'aaaa')

Output: 0

Example 3

Input: find_first_occurrence('abc', '')

Output: 0

Example 4

Input: find_first_occurrence('abc', 'd')

Output: -1

Hints

Hint 1

Think about what is wasted when a naive search hits a mismatch and restarts one position after the previous start. Can you reuse the characters you already matched?

Hint 2

Precompute, for each prefix of the needle, the length of its longest proper prefix that is also a suffix (a border). This tells you how far to fall back on a mismatch.

Hint 3

Scan the haystack once with a counter of currently matched needle characters. On mismatch, follow the border table to shrink the counter instead of moving backward in the haystack. When the counter equals the needle length, the start index is i - m + 1. Handle the empty needle up front.