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.
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<vector>usingnamespacestd;// Function to search for all occurrences of 'pat' in 'txt' using Naive Approachvector<int>search(conststring&pat,conststring&txt){// Length of the patternintm=pat.length();// Length of the textintn=txt.length();vector<int>ans;// Slide the pattern over text one by onefor(inti=0;i<=n-m;i++){intj;// Check for pattern match at index ifor(j=0;j<m;j++){if(txt[i+j]!=pat[j])break;}// If pattern matches, store indexif(j==m)ans.push_back(i);}returnans;}intmain(){stringtxt="aabaacaadaabaaba";stringpat="aaba";vector<int>res=search(pat,txt);for(autoit:res){cout<<it<<" ";}return0;}
Java
importjava.util.ArrayList;publicclassGFG{// Function to search for all occurrences of 'pat' in 'txt' using Naive ApproachstaticArrayList<Integer>search(Stringpat,Stringtxt){// Length of the patternintm=pat.length();// Length of the textintn=txt.length();ArrayList<Integer>ans=newArrayList<>();// Slide the pattern over text one by onefor(inti=0;i<=n-m;i++){intj;// Check for pattern match at index ifor(j=0;j<m;j++){if(txt.charAt(i+j)!=pat.charAt(j))break;}// If pattern matches, store indexif(j==m)ans.add(i);}returnans;}publicstaticvoidmain(String[]args){Stringtxt="aabaacaadaabaaba";Stringpat="aaba";ArrayList<Integer>res=search(pat,txt);for(intit:res){System.out.print(it+" ");}}}
Python
# Function to search for all occurrences of 'pat' in 'txt' using Naive Approachdefsearch(pat,txt):# Length of the patternm=len(pat)# Length of the textn=len(txt)ans=[]# Slide the pattern over text one by oneforiinrange(n-m+1):# Check for pattern match at index ij=0whilej<m:iftxt[i+j]!=pat[j]:breakj+=1# If pattern matches, store indexifj==m:ans.append(i)returnansdefmain():txt="aabaacaadaabaaba"pat="aaba"res=search(pat,txt)foritinres:print(it,end=" ")if__name__=="__main__":main()
C#
usingSystem;usingSystem.Collections.Generic;classGFG{// Function to search for all occurrences of 'pat' in// 'txt' using Naive ApproachpublicstaticList<int>search(stringpat,stringtxt){// Length of the patternintm=pat.Length;// Length of the textintn=txt.Length;List<int>ans=newList<int>();// Slide the pattern over text one by onefor(inti=0;i<=n-m;i++){intj;// Check for pattern match at index ifor(j=0;j<m;j++){if(txt[i+j]!=pat[j])break;}// If pattern matches, store indexif(j==m)ans.Add(i);}returnans;}staticvoidMain(){stringtxt="aabaacaadaabaaba";stringpat="aaba";List<int>res=search(pat,txt);foreach(intitinres){Console.Write(it+" ");}}}
JavaScript
// Function to search for all occurrences of 'pat' in 'txt'// using Naive Approachfunctionsearch(pat,txt){// Length of the patternletm=pat.length;// Length of the textletn=txt.length;letans=[];// Slide the pattern over text one by onefor(leti=0;i<=n-m;i++){letj;// Check for pattern match at index ifor(j=0;j<m;j++){if(txt[i+j]!==pat[j])break;}// If pattern matches, store indexif(j===m)ans.push(i);}returnans;}// driver codelettxt="aabaacaadaabaaba";letpat="aaba";letres=search(pat,txt);console.log(res.join(" "));
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.