Skip to content
Naive

Naive Pattern Matching

The brute-force approach to finding a substring.

Time Complexity
O(N * M)
Space Complexity
O(1)

Interactive Visualization

Playback Speed
Execution State
STEP 1 / 18
Text (N)
A
0
B
1
C
2
A
3
B
4
C
5
D
6
Pattern (M)
A
0
B
1
C
2
D
3
Process Description

Checking for match at index 0

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

  • 1
    Aligning the pattern at index 0 of the text.
  • 2
    Comparing characters left-to-right.
  • 3
    On failure, resetting the comparison and shifting the alignment by 1.
  • 4
    Repeating 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.