Naive Text Search
Naive search checks for each position in the text whether the pattern matches. On a mismatch, it shifts by 1.
Easy to understand, but slow on long texts with recurring patterns.
First hit: Find the Index of the First Occurrence in a String [1].
$$T[s:s+m]\stackrel{?}{=}P$$
Where used
Small patterns, one-time searches, teaching purposes. Replace in hot paths with indexOf, automata, or index structures.
Depth
The naive text search aligns the pattern one by one at each possible starting position of the text. For each alignment, characters are compared from left to right until a difference is found or the entire pattern is confirmed.
After a difference, the method shifts the pattern by one position and starts the comparison again. Recognized matches are not systematically utilized. The method is still valuable because it is short, correct, and often sufficient for small inputs or short patterns.
Difficulty levels
- Check all alignments of a pattern in a short text.
- Understand early exits for unequal first characters.
- Construct inputs that cause many repeated comparisons.
Pitfalls
The last valid starting position can easily be skipped by an incorrect loop boundary. Empty patterns also require an explicitly chosen semantics so that implementation and tests match.
Sources
Tasks
Card Info
- Topic: Algorithms and Data Structures
- Difficulty: Beginner
- Completed: 0 users