Asked at

Find The Index Of The First Occurrence

Easy
Verified
String MatchingTwo PointersString~15 min

Return the index of the first occurrence of needle in haystack, or -1 if it is absent.

An empty needle matches at index 0. Slide a window of needle.length across haystack.

The input arrives as a single object { haystack, needle }.

Examples

in{ haystack: "sadbutsad", needle: "sad" }
out0

"sad" first occurs at index 0.

in{ haystack: "leetcode", needle: "leeto" }
out-1

"leeto" never appears.

Constraints

  • 1 ≤ haystack.length, needle.length ≤ 10⁴
  • haystack and needle consist of lowercase English letters.

Get help

🔑

Sign in to solve

Sign in to write, run, and submit your solution — and to pick up where your iOS flow left off.