1. Naive Sliding Window Substring Slicing
Intuition
If needle.length == 0, return 0. If haystack.length < needle.length, return -1. Loop i from 0 to n - m: check if haystack.substring(i, i + m) matches needle. If it matches, return i. If loop finishes with no match, return -1.
When to apply: Basic initial implementation.
Algorithm
- If
m == 0, return 0; ifn < m, return -1. - Loop
ifrom0ton - m: - Extract substring
haystack[i ... i + m - 1]. - If substring equals
needle, returni. - Return -1.
Naive Sliding Window Substring Slicing Trace
2 of 2 questions left todayObservation: Needle length is $M = 3$
Observation: Needle length is M = 3. Extract substring from haystack starting at i = 0: "sad".
Decision: Compare slice "sad" against target "sad". They are identical!
Invariant: First occurrence found at index 0.
#include <iostream>#include <string> class Solution {public: int strStr(std::string haystack, std::string needle) { int n = haystack.size(), m = needle.size(); if (m == 0) return 0; if (n < m) return -1; for (int i = 0; i <= n - m; ++i) { if (haystack.substr(i, m) == needle) { return i; } } return -1; }}; int main() { Solution sol; std::cout << sol.strStr("sadbutsad", "sad") << std::endl; // 0 std::cout << sol.strStr("leetcode", "leeto") << std::endl; // -1 return 0;}Time & Space Complexity
- Time complexity:
O((N - M + 1) * M)— Up to N - M + 1 starting positions are checked, each comparing up to M characters. - Space complexity:
O(1) or O(M) for substring
Why Brute Force Doesn't Scale:
The LPS array encodes internal pattern self-similarity in O(M) preprocessing time.
The LPS table only consumes O(M) auxiliary memory.