CodingNodes / Arrays & Hashing / Find the Index of the First Occurrence in a String System design Space play · ←→ step · R restart

Problem

You are given two strings, haystack and needle.

Return the index where needle first appears inside haystack as one unbroken run of characters. If it never appears, return -1.

Constraints

  • 1 ≤ haystack.length, needle.length ≤ 10⁴
  • Both strings use lowercase English letters

Examples: pick one to animate

Solutions

TimeO(n · m) SpaceO(1)

Time: There are at most n − m + 1 start positions, and each one compares up to m letters.

Space: Only a few integer variables are used. No extra structure grows with the input.

Try every start position in the haystack. At each one, compare the needle letter by letter. The first start where all m letters match is the answer.