Browse curriculum

Naive Pattern Search

Naive pattern search finds all occurrences of a pattern in a text by checking every position.

30 COMPARISONS TOTAL

MATCH

A

0

A

1

B

2

A

3

A

4

C

5

A

6

A

7

D

8

A

9

A

10

B

11

A

12

A

13

B

14

A

15

Comparisons

1

Matches

0

/* The pattern, offset to sit under the window it is being compared against — which is what makes the re-comparison after a slide visible. */

Pattern, aligned at index 0

A
A
B
A

 

'A' at 0 matches pattern[0].

Next

'A' at 1 matches pattern[1].

Text

Pattern

Intuition

Slide the pattern over the text one by one and check for a match. If a match is found, record the index. If a mismatch occurs, shift the pattern by one position.

Concept

  • Sliding Window: The pattern acts as a window of length M.
  • Comparison: Compare character by character.
  • Shift: Move window by 1 after every check.

How it Works

Algorithm:

  1. Loop i from 0 to N - M.
  2. For each i, loop j from 0 to M - 1.
  3. If text[i+j] != pattern[j], break inner loop.
  4. If inner loop completes (j == M), pattern found at i.

Step-by-Step Breakdown

Watch the visualization:

  • The pattern row sits under the part of the text it is being compared against, and slides one position at a time.
  • Solid blue: The character pair being compared; it turns red on a mismatch.
  • Pale blue with a blue outline: Characters already matched at this alignment.
  • Green: Text characters of an occurrence that was found.

When to Use

  • Small texts or patterns.
  • When simplicity is preferred over performance.

When NOT to Use

  • Large texts (O(N*M) is too slow). Use KMP or Rabin-Karp instead.

How to Identify

"Find occurrence of pattern", "Substring search".

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description

Frequently Asked Questions

Why is the worst case O(N*M)?

Each of the roughly N starting positions can match M-1 characters before failing, as the pattern aaab does against a text of all a characters. The window then slides by one and repeats nearly the same comparisons.


Is it ever the right choice?

Yes. It needs no preprocessing and no extra memory, and when the alphabet is large most windows fail on the first character, which makes the average case close to O(N).


What do the faster algorithms do differently?

They use information the naive scan throws away. KMP precomputes how far the pattern can safely jump after a mismatch, and Rabin-Karp compares a rolling hash so most windows are rejected in O(1).