Naive algorithm for Pattern Searching (original) (raw)
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]
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.
C++ `
#include using namespace std;
// Function to search for all occurrences of 'pat' in 'txt' using Naive Approach vector search(const string &pat, const string &txt) { // Length of the pattern int m = pat.length();
// Length of the text
int n = txt.length();
vector<int> ans;
// Slide the pattern over text one by one
for (int i = 0; i <= n - m; i++)
{
int j;
// Check for pattern match at index i
for (j = 0; j < m; j++)
{
if (txt[i + j] != pat[j])
break;
}
// If pattern matches, store index
if (j == m)
ans.push_back(i);
}
return ans;}
int main() { string txt = "aabaacaadaabaaba"; string pat = "aaba";
vector<int> res = search(pat, txt);
for (auto it : res)
{
cout << it << " ";
}
return 0;}
Java
import java.util.ArrayList;
public class GFG {
// Function to search for all occurrences of 'pat' in 'txt' using Naive Approach
static ArrayList<Integer> search(String pat, String txt)
{
// Length of the pattern
int m = pat.length();
// Length of the text
int n = txt.length();
ArrayList<Integer> ans = new ArrayList<>();
// Slide the pattern over text one by one
for (int i = 0; i <= n - m; i++)
{
int j;
// Check for pattern match at index i
for (j = 0; j < m; j++)
{
if (txt.charAt(i + j) != pat.charAt(j))
break;
}
// If pattern matches, store index
if (j == m)
ans.add(i);
}
return ans;
}
public static void main(String[] args)
{
String txt = "aabaacaadaabaaba";
String pat = "aaba";
ArrayList<Integer> res = search(pat, txt);
for (int it : res)
{
System.out.print(it + " ");
}
}}
Python
Function to search for all occurrences of 'pat' in 'txt' using Naive Approach
def search(pat, txt):
# Length of the pattern
m = len(pat)
# Length of the text
n = len(txt)
ans = []
# Slide the pattern over text one by one
for i in range(n - m + 1):
# Check for pattern match at index i
j = 0
while j < m:
if txt[i + j] != pat[j]:
break
j += 1
# If pattern matches, store index
if j == m:
ans.append(i)
return ansdef main(): txt = "aabaacaadaabaaba" pat = "aaba"
res = search(pat, txt)
for it in res:
print(it, end=" ")if name == "main": main()
C#
using System; using System.Collections.Generic;
class GFG { // Function to search for all occurrences of 'pat' in // 'txt' using Naive Approach public static List search(string pat, string txt) { // Length of the pattern int m = pat.Length;
// Length of the text
int n = txt.Length;
List<int> ans = new List<int>();
// Slide the pattern over text one by one
for (int i = 0; i <= n - m; i++) {
int j;
// Check for pattern match at index i
for (j = 0; j < m; j++) {
if (txt[i + j] != pat[j])
break;
}
// If pattern matches, store index
if (j == m)
ans.Add(i);
}
return ans;
}
static void Main()
{
string txt = "aabaacaadaabaaba";
string pat = "aaba";
List<int> res = search(pat, txt);
foreach(int it in res) { Console.Write(it + " "); }
}}
JavaScript
// Function to search for all occurrences of 'pat' in 'txt' // using Naive Approach function search(pat, txt) { // Length of the pattern let m = pat.length;
// Length of the text
let n = txt.length;
let ans = [];
// Slide the pattern over text one by one
for (let i = 0; i <= n - m; i++) {
let j;
// Check for pattern match at index i
for (j = 0; j < m; j++) {
if (txt[i + j] !== pat[j])
break;
}
// If pattern matches, store index
if (j === m)
ans.push(i);
}
return ans;}
// driver code let txt = "aabaacaadaabaaba"; let pat = "aaba";
let res = search(pat, txt);
console.log(res.join(" "));
`
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.
