function naivePatternMatch(text: string, pattern: string): number[] {
const result: number[] = [];
const n = text.length;
const m = pattern.length;
for (let i = 0; i <= n - m; i++) {
let j = 0;
while (j < m && text[i + j] === pattern[j]) {
j++;
}
if (j === m) {
result.push(i);
}
}
return result;
}
console.log(naivePatternMatch("abracadabra", "abra"));The pattern "abra" appears twice in the text "abracadabra". Once starting at index 0 and again starting at index 7.
The naive algorithm compares the pattern at each possible position in the text. For text length n=5 and pattern length m=3, it tries (5 - 3 + 1) = 3 positions, each with up to 3 comparisons, totaling 9 comparisons.
function naiveMatch(text: string, pattern: string): number[] {
const result: number[] = [];
const n = text.length;
const m = pattern.length;
for (let i = 0; i < n - m; i++) {
let j = 0;
while (j < m && text[i + j] === pattern[j]) {
j++;
}
if (j === m) {
result.push(i);
}
}
return result;
}
console.log(naiveMatch("hellohello", "hello"));The for loop uses i < n - m instead of i <= n - m. This causes it to miss checking the last valid position where the pattern could match, so it only finds the first occurrence.
function naivePatternMatch(text: string, pattern: string): number[] {
const result: number[] = [];
const n = text.length;
const m = pattern.length;
for (let i = 0; i <= n - m; i++) {
let j = 0;
while (j < m && text[i + j] === pattern[j]) {
j++;
}
if (j === m) {
result.push(i);
}
}
return result;
}
console.log(naivePatternMatch("aaaa", "aa"));The pattern "aa" appears starting at indices 0, 1, and 2 in the text "aaaa" because matches can overlap.
The naive algorithm compares the pattern at each position in the text, and each comparison can take up to m steps, resulting in O(n * m) time complexity.
