Search topics...
All Problems

strstr (Implement strStr)

Solution Approach
Was this helpful?
EasystringExpected: O((N−M) time, O(1) space

Problem

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

Example 1:

Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 (and 6), return the first occurrence.

Example 2:

Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" is not found in "leetcode".
Reference solution unlocks after your first submission
Loading...