Find the Index of the First Occurrence in a String — LeetCode 28 Python Solution

EasyTwo PointersStringString Matching
Problem
#28
Reading time
2 min

The problem

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.

Example

Input
haystack = "sadbutsad", needle = "sad"
Output
0
Explanation
"sad" occurs at index 0 and 6.

Python solution

Python
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n, m = len(haystack), len(needle)
        for i in range(n - m + 1):
            if haystack[i : i + m] == needle:
                return i
        return -1

Complexity

MeasureComplexity
TimeO((n-m) \times m)
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 28. Find the Index of the First Occurrence in a String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 28. Find the Index of the First Occurrence in a String?
LeetCode 28. Find the Index of the First Occurrence in a String is rated Easy on LeetCode.
What is the time complexity of LeetCode 28. Find the Index of the First Occurrence in a String?
The Python solution on this page runs in O((n-m) \times m).
What is the space complexity of LeetCode 28. Find the Index of the First Occurrence in a String?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 28. Find the Index of the First Occurrence in a String cover?
LeetCode 28. Find the Index of the First Occurrence in a String is tagged Two Pointers, String and String Matching on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview