1. Sliding Window Substring Comparison
Intuition
For each starting index i from 0 to N - M: check if haystack[i + j] == needle[j] for all j from 0 to M - 1. If all match, return i. If no match after full search, return -1.
When to apply: Basic baseline comparison.
Algorithm
- If
needle.length > haystack.length: return -1. - For
ifrom 0 tohaystack.length - needle.length: -
matched = true. - For
jfrom 0 toneedle.length - 1: - If
haystack[i + j] != needle[j]:matched = false; break. - If
matched: returni. - Return -1.
Sliding Window Substring Comparison Trace
2 of 2 questions left todayObservation: Extract window of length $M = 3$ starting at index 0
Observation: Extract window of length M = 3 starting at index 0.
Decision: "sad" === "sad". Match verified!
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 > n) return -1; for (int i = 0; i <= n - m; ++i) { int j = 0; while (j < m && haystack[i + j] == needle[j]) { j++; } if (j == m) 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 window positions, each checking up to M characters. - Space complexity:
O(1)
Why Brute Force Doesn't Scale:
KMP never backtracks the text index i.
Only stores an O(M) integer array.