Find the Index of the First Occurrence in a String — LeetCode 28 Python Solution
- Problem
- #28
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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 -1Complexity
| Measure | Complexity |
|---|---|
| Time | O((n-m) \times m) |
| Space | O(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.