1. Naive Sliding Window Character Comparison
Intuition
1. For each starting index i from 0 to N - M:
- Check if text[i + j] == pattern[j] for all 0 <= j < M.
- If all characters match, return index i.
2. If no match is found after scanning all positions, return -1.
When to apply: Simple baseline for pattern search without preprocessing overhead.
Algorithm
- Iterate index i from 0 to N - M.
- Compare characters at text[i + j] with pattern[j].
- If mismatch, advance i by 1.
- If full match found, return i.
#include <iostream>#include <string> class Solution {public: int strStr(std::string text, std::string pattern) { int n = text.size(), m = pattern.size(); if (m == 0) return 0; if (n < m) return -1; for (int i = 0; i <= n - m; ++i) { int j = 0; while (j < m && text[i + j] == pattern[j]) { j++; } if (j == m) return i; } return -1; }}; int main() { Solution sol; std::cout << sol.strStr("ABAAABCD", "ABC") << std::endl; // 4 std::cout << sol.strStr("HERE IS A SIMPLE EXAMPLE", "EXAMPLE") << std::endl; // 17 return 0;}Time & Space Complexity
- Time complexity:
O((N - M + 1) * M)— In worst case (e.g. text = "AAAAAAAAAB", pattern = "AAB"), checks M characters for every position: O(N * M). - Space complexity:
O(1)
Why Brute Force Doesn't Scale:
Naive brute force re-examines already processed substrings multiple times.
For N = 105, O(N2) requires 1010 operations (TLE), while O(N) finishes in < 10ms.