Browse Curriculum

Naive Pattern Search

Visualize finding all occurrences of a pattern in a text by checking every position.

Ready to search for pattern.
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

0

Matches Found

See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

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 dashed box represents the pattern.
  • It moves one step at a time.
  • Green border = Match, Red border = Mismatch.

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".

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep