LeetCode 28, Easy. Topics: Two Pointers, String, String Matching. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 18 parametrized pytest cases, and a playground notebook:
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.
Examples
Constraints
- 1 <= haystack.length, needle.length <= 10^4
- haystack and needle consist of only lowercase English characters.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026