VOOZH about

URL: https://www.geeksforgeeks.org/dsa/naive-algorithm-for-pattern-searching/

⇱ Naive algorithm for Pattern Searching - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Naive algorithm for Pattern Searching

Last Updated : 31 Mar, 2026

Given a text string of length n and a pattern of length m, find all starting indices where the pattern occurs in the text.
Note: You may assume that n>m.

Examples:

Input: text = "geeksforgeeks", pattern = "geeks"
Output: [0, 8]
Explanation: The string "geeks" occurs at index 0 and 8 in text.

Input:  text =  "aabaacaadaabaaba", pattern = "aaba"
Output: [0, 9, 12]

👁 kmp-algorithm-for-pattern-searching

Naive Pattern Searching Algorithm

The pattern moves over the text one position at a time and characters are compared. If all characters match, the index is stored; otherwise, the next position is checked.


Output
0 9 12 

Best Case Scenario

The best case occurs when the first character of the pattern does not match any character in the text.

Example: txt = "AABCCAADDEE" , pat = "FAA" . Only one comparison is done at each position. Time Complexity: O(n)

Worst Case Scenario

The worst case occurs when many characters match repeatedly.

Case 1: All characters are the same. Example: txt = "AAAAAAAAAAAAAAAAAA" , pat = "AAAAA"

Case 2: Only the last character is different. Example: txt = "AAAAAAAAAAAAAAB", pat = "AAAAB"

In these cases, most characters match at every position, leading to repeated comparisons. Time Complexity: O(m × (n - m + 1))

Time Complexity

O(n × m), because every possible starting position in the text is checked and up to m characters are compared at each position.

Auxiliary Space

O(1), only a few variables are used, and no extra data structures are required.

Although strings which have repeated characters are not likely to appear in English text, they may well occur in other applications (for example, in binary texts). The KMP matching algorithm improves the worst case to O(n). We will be covering KMP in the next post. Also, we will be writing more posts to cover all pattern searching algorithms and data structures.

Related Articles

Comment