Example 1
- Input
- haystack = "sadbutsad", needle = "sad"
- Output
- 0
The substring sad begins at both 0 and 6. The earliest complete occurrence starts at 0, so the answer is 0.
Find the earliest starting index where a pattern occurs in a string. Return -1 when no complete match exists, even if a prefix of the pattern occurs.
Given lowercase English strings haystack and needle, return the zero-based index of the first occurrence of needle in haystack. Return -1 if there is no occurrence.
A match must contain every character of needle consecutively and in order. If multiple matches exist, return the smallest starting index.
1 <= haystack.length, needle.length <= 10^4The substring sad begins at both 0 and 6. The earliest complete occurrence starts at 0, so the answer is 0.
The first four characters match blue, but the next character is c instead of o. No later starting position contains blueo, so there is no complete occurrence.
The needle is longer than the entire haystack. No placement can contain both required characters.
Starts 0 and 1 each match three a characters before failing on the required b. At index 2, the four characters are aaab, so the first complete match is 2.
Imagine placing the needle over each possible starting position of the haystack. In sadbutsad, the needle sad fits at indices 0 and 6, but scanning starts from the left and must return 0. Comparing each placement from scratch repeats work. A rolling hash compresses a fixed-length window into a number that can be updated when it moves; equal hashes still need character verification. The Z algorithm instead records how much of a string's prefix matches at each position and reuses previously confirmed character matches.
Reveal Compare Every Placement: intuition, complexity, and code
Repeated substring comparisons can be reduced either by a rolling fingerprint that filters candidates or by reusing proven prefix matches. Hashing needs collision verification for an exact answer; Z matching gives a deterministic linear bound by keeping a precise prefix-match invariant.