String Matching Pattern matching

578. Find the Index of the First Occurrence in a String

Easy 147 DSA Sheet

You are given two strings, haystack and needle. Return the index where needle first appears in haystack, or -1 if it does not appear at all.

needle appears at index i when the letters of haystack from index i on spell out needle, in order and next to each other. Indexes start at 0. If needle appears more than once, return the smallest index.

Example 1

Input: haystack = "bananarama", needle = "anar"

Output: 3

Explanation: At index 1 the letters a, n, a match, but the next letter is n, not r. The first full match starts at index 3.

Example 2

Input: haystack = "cat", needle = "cats"

Output: -1

Explanation: needle is longer than haystack, so it cannot appear in it.

Example 3

Input: haystack = "tictactic", needle = "tic"

Output: 0

Explanation: tic appears at index 0 and at index 6. The first one counts.

Check your understanding

Work out the answer for this input before you write any code.

haystack = "aaab", needle = "aab"

Constraints

  • 1 ≤ haystack.length, needle.length ≤ 105
  • haystack and needle hold only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.