Home
DSA Course
Strings
Naive Pattern Search
Naive Pattern Search
Visualize finding all occurrences of a pattern in a text by checking every position.
Ready to search for pattern.
A
0A
1B
2A
3A
4C
5A
6A
7D
8A
9A
10B
11A
12A
13B
14A
150
Matches Found
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.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:
- Loop
ifrom0toN - M. - For each
i, loopjfrom0toM - 1. - If
text[i+j] != pattern[j], break inner loop. - 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.
