Slide the pattern across the text and compare straight through at every shift — no setup, O(n·m) worst case.
Naïve string matching is the most direct way to find a pattern inside a longer text: line the pattern up at the very first position, compare character by character, and on any mismatch slide the pattern one place to the right and start the comparison over from the beginning. It needs zero preprocessing — which is exactly why it can waste so much work.
s = 0 (aligned with the start of the text).pattern[0], pattern[1], … against the text at that shift.s.s = s + 1, and restart comparing from pattern[0].s > n - m).function naiveSearch(text, pattern) {
const n = text.length, m = pattern.length;
const hits = [];
for (let s = 0; s <= n - m; s++) { // every shift
let j = 0;
while (j < m && text[s + j] === pattern[j]) j++;
if (j === m) hits.push(s); // full match at s
}
return hits;
}Search AAAAB for the pattern AAAB. At shift 0 it matches A, A, A, then hits a mismatch (A vs B) at the fourth character. It shifts by one and at shift 1 re-compares those same As all over again, mismatches again, and so on. Three of the four characters it just verified get re-read on the next shift — that repeated re-checking is the whole inefficiency.
AAAA…A with pattern AAA…AB. Every shift compares nearly the whole pattern before failing on the last character, giving roughly n × m comparisons.