AlgoInsight

DSA problem

Find the Index of the First Occurrence in a String

EasyStringsPattern: String Matchingtop600AmazonGoogle

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

This is the classic substring-search (pattern-matching) problem. You must locate the first starting position where the entire needle string appears contiguously inside haystack. Both strings consist of lowercase English letters, and needle is guaranteed to be non-empty, so the answer is the smallest valid index or -1 when no match exists.

Examples

Example 1
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and also at index 6. The first occurrence is at index 0, so we return 0.
Example 2
Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" never occurs as a contiguous substring of "leetcode", so the function returns -1.
Example 3
Input: haystack = "abc", needle = "c"
Output: 2
Explanation: The single-character needle "c" first appears at index 2.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stringtwo-pointersstring-matching

Browse all DSA problems