ExamAdda Logo

Find the Index of the First Occurrence in a String

Easy

Given two strings haystack and needle, return the index of the first occurrence of needle in haystack.

If needle does not occur in haystack, return:

-1

 

Example

Input:

haystack = "sadbutsad"

needle = "sad"

 

The first occurrence of "sad" starts at index 0.

Output

0

 

Main Idea

We need to check every possible starting position in haystack.

For each position:

  1. Check whether there are enough characters remaining.
  2. Compare the substring starting at that position with needle.
  3. If all characters match, return that index.
  4. If no position matches, return -1.

Example

haystack = "hello"

needle   = "ll"

 

Check:

h e → no

e l → no

l l → match

 

Therefore:

Answer = 2

 

Important Point

We need the first occurrence, so we return immediately when a match is found.

Example 1

Input

sadbutsad
sad

Output

0

Explanation

"sad" first appears at index 0.

Example 2

Input

leetcode
leeto

Output

-1

Explanation

"leeto" does not occur in "leetcode".

Constraints

1 <= haystack.length
needle.length <= 10^4
haystack and needle consist of English letters.

Hints:

Hint 1

Try every possible starting position in haystack.

Hint 2

A match is possible only while enough characters remain for the complete needle.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 17, 2026

Last updated

Aug 18, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output