Algorithms · Visualized
String: Naive Search
String Matching
Find a pattern inside a text efficiently — from the naive slide to prefix-function smartness.
The simplest way to find a pattern inside text: try matching the pattern starting at every possible position in the text, checking character by character, and moving to the next starting position whenever a mismatch occurs. Time: O(n × m) average, O(n × m), where n = text length, m = pattern length worst; space: O(1).
Big-O: Naive O(n·m); KMP & Z O(n+m); Rabin–Karp O(n+m) average with hashing.
Naive String Search
String MatchingThe simplest way to find a pattern inside text: try matching the pattern starting at every possible position in the text, checking character by character, and moving to the next starting position whenever a mismatch occurs.
How Naive Search Works
- Loop through every possible starting position in the text (from 0 to text length minus pattern length).
- At each starting position, compare the pattern against the text character by character.
- If all characters match, record this starting position as a match.
- If any character doesn't match, stop this attempt and move to the next starting position.
- Continue until every starting position has been tried.
Naive Search Worked Example
Input: {text: AABAACAADAABAABA, pattern: AABA}
Try position0: 'AABA' vs 'AABA' → match! Try position1: 'ABAA' vs 'AABA' → mismatch at char2. Try position2,3...continue trying each position. Matches are found starting at positions 0, 9, and 12.
def naive_search(text, pat):
n, m = len(text), len(pat)
out = []
for i in range(n - m + 1):
if text[i:i + m] == pat:
out.append(i)
return outBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Naive Search Time & Space Complexity
When to Use Naive Search
- Simple, short text searches where the overhead of building a preprocessing table (like KMP does) isn't worth it.
- A baseline to compare against faster algorithms like KMP, Rabin-Karp, and Z-algorithm.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.