Code Logo

Find First Occurrence

Published at10 Jan 2026
Pattern Matching Easy 20 views
Like12

In Find First Occurrence, you are given two strings: haystack and needle.

Your goal is to return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

For example, if haystack = "sadbutsad" and needle = "sad", the answer is 0 because "sad" starts at index 0. If haystack = "leetcode" and needle = "leeto", the answer is -1 because "leeto" never appears.

This is a fundamental string matching problem often known as strStr() in C or indexOf() in Java.

Example Input & Output

Example 1
Input
haystack = "sadbutsad", needle = "sad"
Output
0
Explanation

"sad" occurs at index 0 and 6. The first occurrence is at index 0.

Example 2
Input
haystack = "leetcode", needle = "leeto"
Output
-1
Explanation

"leeto" did not occur in "leetcode", so we return -1.

Algorithm Flow

Recommendation Algorithm Flow for Find First Occurrence
Recommendation Algorithm Flow for Find First Occurrence

Best Answers

java
class Solution {
    public String reverse_string(String s) {
        return new StringBuilder(s).reverse().toString();
    }
}