Locate the First Occurrence of a Needle in a Haystack
StringsAuto-graded · 27 test casesLast 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
needleis the empty string, return0, even whenhaystackis also empty. - If
haystackis empty andneedleis not, return-1. - If
needleis longer thanhaystack, 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A brute-force search tries every starting offset and compares from scratch, which can cost O(n * m) on inputs like needle = "aaab" and haystack = "aaaa...a". The Knuth-Morris-Pratt idea avoids this by never re-reading haystack characters.
- Build a border table for the needle. For each prefix
needle[:i+1], store the length of its longest proper prefix that is also a suffix of that prefix. This is computed with the same fall-back logic used in the search itself, run on the needle against itself. - Scan the haystack once. Keep
k, the number of needle characters currently matched. For each haystack character:- While
k > 0and the character does not equalneedle[k], setk = border[k - 1]. - If the character equals
needle[k], incrementk. - If
kreachesm, the match ends at the current indexi, so it starts ati - m + 1. Return it.
- While
- If the scan finishes without a full match, return
-1. - An empty needle returns
0immediately. An empty haystack with a non-empty needle never letskgrow, so the result is-1. A needle longer than the haystack can never reachk == m, so it also gives-1.
Why it is correct
After processing haystack[i], k is the length of the longest prefix of the needle that is a suffix of haystack[:i+1]. On a mismatch, the next-longest candidate that could still be a suffix must be a border of the currently matched prefix, which is exactly border[k - 1]. No shorter or longer candidate is skipped, so no occurrence is missed. All occurrences have the same length, so the first one to complete (smallest ending index) also has the smallest starting index.
Complexity
- Time:
O(n + m).kincreases by at most one per character, and each fall-back step decreases it, so the total number of fall-backs is bounded by the total number of increases. - Space:
O(m)for the border table.
Reference solution
def find_first_occurrence(haystack: str, needle: str) -> int:
m = len(needle)
if m == 0:
return 0
# Border (failure) table: border[i] is the length of the longest proper
# prefix of needle[:i+1] that is also its suffix.
border = [0] * m
k = 0
for i in range(1, m):
while k and needle[i] != needle[k]:
k = border[k - 1]
if needle[i] == needle[k]:
k += 1
border[i] = k
# Scan the haystack once.
k = 0
for i, ch in enumerate(haystack):
while k and ch != needle[k]:
k = border[k - 1]
if ch == needle[k]:
k += 1
if k == m:
return i - m + 1
return -1