Find the Index of the First Occurrence in a String

Easy

Topics
StringTwo Pointers

Given two strings s (haystack) and t (needle), return the index of the first occurrence of t in s, or -1 if not present.

Example 1

haystacksadbutsad
needlesad
The needle first matches at index 0.
Top row is the string searched; below it the pattern.
Input:  s = "sadbutsad", t = "sad"
Output: 0

Example 2

haystackleetcode
needleleeto
The needle does not occur, so the answer is -1.
Input:  s = "leetcode", t = "leeto"
Output: -1

Constraints

  • 1 <= s.length, t.length <= 10^4
  • Both consist of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Check every starting position and compare. That is the naive scan, and it is what the solution does: n - m + 1 candidate offsets, each compared in up to m characters, so O(n*m) worst case.

With both strings capped at 10^4, the worst case is around 10^8 character comparisons on an adversarial input like "aaaa...a" against "aaa...ab" — slow but survivable, and in practice the comparison aborts on the first mismatch, so typical inputs are closer to O(n).

The linear-time answer is KMP, which is the point of the problem at a harder difficulty. 💡 KMP precomputes, for each prefix of the needle, the length of the longest proper prefix that is also a suffix. On a mismatch that table says how far the needle can shift without re-examining text already matched, so the text pointer never moves backwards and the whole search is O(n + m). Rabin-Karp (rolling hash) is the other standard answer, O(n + m) expected.

Approach

  1. For each offset i in 0 .. n-m, compare the window against the needle.
  2. Return the first match, or -1.

Dry Run

s = "sadbutsad", t = "sad"

i=0  "sad" == "sad"  -> return 0

s = "leetcode", t = "leeto"
i=0  "leetc" vs "leeto"  mismatch at index 4
i=1  "eetco" mismatch at 0
i=2  "etcod" mismatch at 0
i=3  "tcode" mismatch at 0
no offsets left -> -1

Complexity

  • Time — O(n*m) worst case: every offset compared across most of the needle. KMP is O(n + m) and is the expected answer if the interviewer asks for linear.
  • Space — O(1) for the index arithmetic — but note that s[i:i+m] in Python allocates a copy of the window on every offset, making this O(m) space and adding real constant-factor cost. Comparing character by character, or using the language's built-in find, avoids it. KMP needs O(m) for its table.

Common Pitfalls

  • Looping i to n rather than n - m, which reads past the end or silently compares short windows.
  • Claiming O(1) space while slicing the window out on each iteration.
  • Returning a boolean rather than the index, or returning 0 for "not found" — 0 is a valid match position, so the sentinel must be -1.
  • Forgetting the empty-needle convention, which returns 0. The constraints here guarantee a non-empty needle, so the case cannot arise, but it is the first thing an interviewer probes.

Full Solution — all languages

class Solution:
    def strStr(self, s, t):
        n, m = len(s), len(t)
        for i in range(n - m + 1):
            if s[i:i+m] == t:
                return i
        return -1
Asked at Cognizant Expedia TCS
SensAI
Beta
Tap the mic to stop voice mode