File: find-the-index-of-the-first-occurrence-in-a-string/solution.py

Date: 2026-06-06

Time: 16:46

Purpose

This file solves LeetCode 28 — Find the Index of the First Occurrence in a String. It implements substring search: given haystack and needle, return the index where needle first appears, or -1 if absent.

It uses the KMP (Knuth-Morris-Pratt) algorithm rather than Python's built-in str.find() or str.index(), making the algorithmic intent explicit.

Key Components

Solution.strStr(haystack, needle) -> int

The single method. Two phases:

Phase 1 — Build the LPS (Longest Proper Prefix which is also Suffix) array (lines 12–21):

Phase 2 — Search haystack using the LPS table (lines 24–33):

Patterns

Dependencies

Imports: None.

Imported by: The testsolution.py in the same directory, plus the "Imported By" list in the prompt shows hundreds of other test files — this is an artifact of the test harness importing all solutions uniformly, not a real dependency relationship. Only find-the-index-of-the-first-occurrence-in-a-string/testsolution.py exercises this code meaningfully.

Flow


strStr("hello", "ll")
  1. Build LPS for "ll" → [0, 1]
  2. Search:
     i=0, j=0: 'h' vs 'l' → mismatch, j=0, advance i
     i=1, j=0: 'e' vs 'l' → mismatch, j=0, advance i
     i=2, j=0: 'l' vs 'l' → match, i=3, j=1
     i=3, j=1: 'l' vs 'l' → match, i=4, j=2, j==m → return 4-2=2

Invariants

Error Handling

None. The method always returns an int — either a valid index or -1. No exceptions are raised. Input validation is deferred to LeetCode's constraints (both inputs are guaranteed to be lowercase English strings with 1 <= needle.length <= haystack.length <= 10^4, though the code handles empty needle correctly anyway).

Topics to Explore

Beliefs