EasyTwo PointersString

Implement strStr()

LeetCode
1 approach, code in all languages

Given two strings, a haystack and a needle, return the index of the first position in the haystack where the needle appears as a contiguous substring, or -1 if the needle never occurs.

By convention, an empty needle is considered to match at index 0.

Example 1

Input: haystack = "hello", needle = "ll"

Output: 2

The substring "ll" begins at index 2 of "hello".

Example 2

Input: haystack = "aaaaa", needle = "bba"

Output: -1

There is no place in "aaaaa" that lines up with "bba", so the search fails.

Constraints

  • 1 ≤ haystack.length, needle.length ≤ 10^4
  • haystack and needle consist of lowercase English letters.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now