Skip to content
Decoder

Find the Index of the First Occurrence in a String

Easy

Problem

Given two strings haystack and needle, return the index where needle first appears in haystack as a contiguous piece. If it never appears, return -1. Try it without the built-in search (find, indexOf).

Example 1

Input
haystack = "banana", needle = "ana"
Output
1

Example 2

Input
haystack = "abcabd", needle = "abd"
Output
3

Example 3

Input
haystack = "aaa", needle = "b"
Output
-1

Constraints

  • 1 <= haystack.length, needle.length <= 10^4
  • Both strings contain only lowercase English letters.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.