1. Naive Window Sliding (Quadratic Check)
Intuition
For every index i from 0 to n - m, compare characters txt[i + j] and pat[j] for j from 0 to m - 1. If all m characters match, append i to results. If a mismatch occurs, increment i by 1 and start over.
When to apply: Basic baseline comparison.
Algorithm
- Initialize
res = []. - Loop
ifrom 0 ton - m: - For
jfrom 0 tom - 1: - If
txt[i + j] != pat[j]: break. - If
j == m: appenditores. - Return
res.
Interactive Trace
2 of 2 questions left todayCompute LPS for "aaa": lps = [0, 1, 2]
Compute LPS for "aaa": lps = [0, 1, 2].
#include <iostream>#include <string>#include <vector> class Solution {public: std::vector<int> search(std::string pat, std::string txt) { std::vector<int> res; int n = txt.size(), m = pat.size(); if (n < m) return res; for (int i = 0; i <= n - m; ++i) { int j = 0; while (j < m && txt[i + j] == pat[j]) { j++; } if (j == m) { res.push_back(i); } } return res; }}; int main() { Solution sol; auto ans = sol.search("aaa", "aaaaa"); for (int x : ans) std::cout << x << " "; // 0 1 2 std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O((N - M + 1) * M)— Up to N - M + 1 positions check up to M characters. - Space complexity:
O(1) extra space
Why Brute Force Doesn't Scale:
Guarantees strictly O(N + M) runtime in all scenarios, avoiding the O(N * M) worst-case trap.
Only uses an integer array of size M.