LeetCode 28: Find the Index of the First Occurrence in a String is an Easy array / string problem. This Python walkthrough develops a substring scan solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Easy |
|---|---|
| Topic | Array / String |
| Reusable pattern | substring scan |
| Complexity | O((n-m+1)m) worst-case time and O(1) extra space |
Recognizing the pattern
Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.
For this problem specifically, check every feasible starting position and return the first slice equal to the needle. The invariant worth writing beside the code is: All starts before the current position have already been proven not to match.
Step-by-step algorithm
- Identify the input state consumed by
strStr(haystack, needle)and initialize the data required by the substring scan pattern. - Check every feasible starting position and return the first slice equal to the needle.
- After each update, verify the page’s central invariant: All starts before the current position have already been proven not to match.
- Finish only after the boundary behavior is covered: An empty needle matches at zero; a longer needle cannot match.
Python solution
class Solution:
def strStr(self, haystack, needle):
if needle == "":
return 0
for start in range(len(haystack) - len(needle) + 1):
if haystack[start:start + len(needle)] == needle:
return start
return -1Reading the implementation
The main entry point is strStr(haystack, needle). The implementation keeps little named state because each operation can be resolved directly from the current input position.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, check every feasible starting position and return the first slice equal to the needle.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Check every feasible starting position and return the first slice equal to the needle. Each update records the current item without invalidating earlier decisions; consequently, all starts before the current position have already been proven not to match.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O((n-m+1)m) worst-case time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().strStr("sadbutsad","sad") == 0Common mistakes and edge cases
- Problem-specific boundary: An empty needle matches at zero; a longer needle cannot match.
- Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
- Invariant check: after every update, confirm that all starts before the current position have already been proven not to match.
Interview review checklist
- Explain why substring scan matches the structure of this input.
- State the invariant in one sentence before tracing code: All starts before the current position have already been proven not to match.
- Derive O((n-m+1)m) worst-case time and O(1) extra space from how many times each element or state is visited.
- Test the boundary explicitly: An empty needle matches at zero; a longer needle cannot match.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 6. Zigzag Conversion · Next: 68. Text Justification