Skip to content

Find the Index of the First Occurrence in a String

EasySliding Window
Decode it first. Clues, constraints, pattern and plan before any code.

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).

haystack = "banana", needle = "ana"   →  1
haystack = "abcabd", needle = "abd"   →  3
haystack = "aaa",    needle = "b"     →  -1

Constraints

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