Naive
Naive Pattern Matching
The brute-force approach to finding a substring.
Time Complexity
O(N * M)
Space Complexity
O(1)
Interactive Visualization
Technical Guide
The Naive string-matching algorithm is the baseline approach. It slides the pattern across the text one position at a time and performs a character-by-character comparison. If any character mismatches, it shifts the pattern by exactly one. While simple to implement, its worst-case performance is O(N * M), which occurs with highly repetitive text like matching 'AAAAAB' in 'AAAAAAAAAA'.
Logical Phases
- 1Aligning the pattern at index 0 of the text.
- 2Comparing characters left-to-right.
- 3On failure, resetting the comparison and shifting the alignment by 1.
- 4Repeating until index N-M is reached.
Implementation
for (let i = 0; i <= n - m; i++) {
if (text.substr(i, m) === p) return i;
}Expert Pitfalls
Catastrophic backtracking performance on large, repetitive datasets.