Tensorum
LeetCode 28 · String Matching (KMP / Rabin-Karp)

Find the Index of the First Occurrence in a String

LeetCode 28 · Easy · solution, intuition & step-by-step walkthrough

Check every start position until one fully matches.

EasyTwo PointersStringString MatchingZ AlgorithmKnuth–Morris–Pratt Algorithm
3 msruntime · beats 11%
19.3 MBmemory · beats 11%
1approach
11accepted runs · last 4 Jun 2026

This is how I solved Find the Index of the First Occurrence in a String (LeetCode 28), an easy problem from the String Matching (KMP / Rabin-Karp) pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Slide a window of the needle's length across the haystack and compare character by character; the first full match gives the answer.

Approach

  1. 1

    For each start up to n − m.

  2. 2

    Compare needle[i] against haystack[start + i]; break on mismatch.

  3. 3

    If the last character matched, return start.

How I solved it

Brute-force windowPythonO(n·m) time · O(1) space
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n=len(haystack)
        m = len(needle)
        window_start=0
        while window_start<n-m+1:
            for i in range(m):
                if haystack[window_start+i]!=needle[i]:
                    break
                if i==m-1:
                    return window_start
            window_start=window_start+1
        return -1
Loading the step-through…

Find the Index of the First Occurrence in a String — FAQ

What is the intuition behind Find the Index of the First Occurrence in a String?

Slide a window of the needle's length across the haystack and compare character by character; the first full match gives the answer.

How do you solve Find the Index of the First Occurrence in a String (LeetCode 28)?

1. For each start up to n − m. 2. Compare needle[i] against haystack[start + i]; break on mismatch. 3. If the last character matched, return start.

What is the time and space complexity of Find the Index of the First Occurrence in a String?

Time: O(n · m). Space: O(1). (Accepted approach: Brute-force window.)

What are common mistakes in Find the Index of the First Occurrence in a String?

KMP brings this down to O(n + m).