1. Naive String Search
Intuition
For each position i from 0 to n - m, compare txt[i + j] with pat[j] for j from 0 to m - 1. If all match, record i.
When to apply: Basic baseline comparison.
Algorithm
- Initialize
res = []. - For
ifrom 0 ton - m: -
match = true - For
jfrom 0 tom - 1: - If
txt[i + j] != pat[j]:match = false; break. - If
match:res.push(i). - Return
res.
Naive String Search
2 of 2 questions left todayObservation: Outer loop starts at index $i = 0$
Observation: Outer loop starts at index i = 0. Pattern length M = 4.
Decision: Compare character-by-character: G==G, E==E, E==E, K==K. Match at index 0! Add to results: [0].
Invariant: Character-by-character loop verifies exact matches.
#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("AABA", "AABAACAADAABAABA"); for (int x : ans) std::cout << x << " "; // 0 9 12 std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O((N - M + 1) * M)— Performs up to (N - M + 1) * M character comparisons. - Space complexity:
O(1)
Why Brute Force Doesn't Scale:
Rolling hash skips expensive full-string comparisons for 99.9% of non-matching positions.
Operates in O(1) auxiliary space using a few primitive integer registers.