NeetCode #121LC-28EasyArrays & Hashing
← Back to All Problems#121 · #28 · Find the Index of the First Occurrence in a String(找出字符串中第一个匹配项的下标)
📌 Problem Statement & Constraints
Given two strings
haystack and needle, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Constraints: 1 <= haystack.length, needle.length <= 10^4. The follow-up asks for an O(n + m) algorithm.💡 Core Algorithmic Approaches
- The naive scan is O(n * m) in the worst case (consider
haystack = "aaaa...a",needle = "aaa...ab"). - KMP achieves O(n + m) by precomputing the longest proper prefix that is also a suffix (the
lpsarray) forneedle. - On a mismatch, the
lpsarray tells you how far to fall back inneedlewithout ever moving thehaystackpointer backwards. - An empty
needlereturns 0 by convention, matching most library implementations.
💻 Benchmark Python3 Implementation
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
n, m = len(haystack), len(needle)
# build the longest-proper-prefix-suffix table for needle
lps = [0] * m
j = 0
for i in range(1, m):
while j and needle[i] != needle[j]:
j = lps[j - 1] # fall back
if needle[i] == needle[j]:
j += 1
lps[i] = j
# scan haystack without ever rewinding
j = 0
for i in range(n):
while j and haystack[i] != needle[j]:
j = lps[j - 1]
if haystack[i] == needle[j]:
j += 1
if j == m:
return i - m + 1 # full match
return -1⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n + m) with KMP: building the table is O(m) and the scan is O(n), because the j pointer never moves backwards more than it has advanced.
💾 Space Complexity
O(m) for the lps table. A rolling-hash (Rabin-Karp) solution would be O(1) space but probabilistic.
⚠️ Interview Pitfalls & Follow-ups
- Rewinding
haystackon a mismatch: that is the naive O(n * m) algorithm. KMP's whole point is to avoid it. - Forgetting the
jguard in the while loops:needle[j]would index out of range whenj == 0. - Off-by-one in the match index: the answer is
i - m + 1, noti - m. - Assuming the empty
needlecase cannot occur: it is a standard edge case in the API contract.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
找出字符串中第一个匹配项的下标
给你两个字符串 haystack 和 needle,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 −1。约束:1 ≤ haystack.length, needle.length ≤ 10^4;haystack 和 needle 仅由小写英文字符组成。
核心要点
- 朴素匹配(O(n · m)) :枚举 haystack 的每个起始位置,逐字符比较 needle。实现简单,但最坏情况(如 haystack 全为 a、needle 为 aaa...ab)会退化。
- KMP 算法(O(n + m)) :预处理 needle 的「最长公共前后缀」数组(next / failure 数组),匹配失败时利用该数组把 needle 的指针回退到合适位置,避免回溯 haystack。
- KMP 的核心思想 :当发生失配时,已匹配的前缀中包含的信息可以复用——若该前缀有长度为 k 的公共前后缀,则 needle 指针可以只回退到 k 而不是 0。
- 工程实践 :Python 的 str.find 底层使用高效的 Two-Way 算法(O(n + m) 且常数小),实际工程中应优先使用;KMP 是面试中展示算法功底的答案。
常见陷阱
- 朴素匹配的切片开销 : haystack[i:i+m] == needle 每次切片是 O(m),整体 O(n · m) 且常数较大。逐字符比较可减少常数。
- KMP 的 next 数组定义搞混 : next[i] 表示 needle[:i+1] 的最长公共前后缀长度(不含自身),失配时回退到 next[j-1] 。不同教材的下标约定不同,写代码前要明确。
- KMP 中忘记处理 j == len(needle) 后继续匹配 :若要求找出 所有 匹配位置,需在命中后令 j = nxt[j-1] 继续;本题只求第一个,直接返回即可。
- 边界:needle 为空 :题目约束 needle 长度 ≥ 1,无需处理;但通用实现中空 needle 应返回 0。
参考实现
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
# 工程写法:CPython 的 find 使用 Two-Way 算法,O(n + m)
return haystack.find(needle)
# 朴素实现(面试可先给这个,再引出 KMP):
# n, m = len(haystack), len(needle)
# for i in range(n - m + 1):
# if haystack[i:i + m] == needle:
# return i
# return -1
# KMP 实现(O(n + m),无回溯):
# class Solution:
# def strStr(self, haystack: str, needle: str) -> int:
# if not needle: return 0
# # 1) 构造 next 数组:next[i] = needle[:i+1] 的最长公共前后缀长度
# nxt = [0] * len(needle)
# j = 0
# for i in range(1, len(needle)):
# while j > 0 and needle[i] != needle[j]:
# j = nxt[j - 1]
# if needle[i] == needle[j]:
# j += 1
# nxt[i] = j
# # 2) 匹配:失配时只回退 needle 指针
# j = 0
# for i, c in enumerate(haystack):
# while j > 0 and c != needle[j]:
# j = nxt[j - 1]
# if c == needle[j]:
# j += 1
# if j == len(needle):
# return i - len(needle) + 1
# return -1