Search Pattern (KMP-Algorithm) | Practice | GeeksforGeeks

Given two strings, one is a text string, txt and other is a pattern string, pat. The task is to print the indexes of all the occurences of pattern string in the text string. For printing, Starting Index of a string should be taken as 1.

Example 1:
Input:
txt = "batmanandrobinarebat", pat = "bat"
Output: 1 18
Explanation: The string "bat" occurs twice
in txt, one starts are index 1 and the other
at index 18. 

Example 2:
Input: 
txt = "abesdu", pat = "edu"
Output: -1
Explanation: There's not substring "edu"
present in txt.


Your Task:
You don't need to read input or print anything. Your task is to complete the function search() which takes the string txt and the string pat as inputs and returns an array denoting the start indices (1-based) of substring pat in the string txt. 
Note: Return an empty list incase of no occurences of pattern. Driver will print -1 in this case.

Expected Time Complexity: O(|txt|).
Expected Auxiliary Space: O(|txt|).

Constraints:
1 ≤ |txt| ≤ 105
1 ≤ |pat| < |S|
0
mahesh_phutane4 days ago
Simple java solution O(|txt|*|pat|) → 0.4sec
class Solution
{
    ArrayList<Integer> search(String pat, String txt)
    {
        ArrayList<Integer> res = new ArrayList<>();
        int n = txt.length();
        int k = pat.length();
        
        for(int i = 0;i<n-k+1;i++){
            int flag = 1;
            if(txt.charAt(i)!=pat.charAt(0)) continue; //this will reduce extra time 
            for(int j = i;j<(i+k);j++){
                if(txt.charAt(j)!=pat.charAt(j-i)){
                    flag = 0;
                    break;
                }
            }
            if(flag==1){
                res.add(i+1);
            }
        }
        return res;
    }
}
0
rajjener2 weeks ago
 vector <int> search(string pat, string txt)       {                      int pos=0;            vector <int> v;           int n=txt.length();           int m=pat.length();           int i=0;           while(i<n)           {              if(txt.substr(i,m)==pat){              v.push_back(i+1);              }                           i++;                                       }           return v;       }
0
bahubuli3 weeks ago
```c++
	vector <int> search(string pat, string txt)
        {
            if(pat.size()>txt.size()) return {-1};
            vector<int>ans;
            
            vector<int>reset(pat.size()+1);
            
            reset[0]=-1;
            
            int i=0,j=-1;
            while(i<pat.size())
            {
                
                while(j>=0 && pat[i]!=pat[j])   j = reset[j];
                
                i++;
                j++;
                reset[i]=j;
            }
            // created lps array for pattern
            
            i=0,j=0;
            
            while(i<txt.size())
            {
                while(j>=0 && pat[j]!=txt[i])   j = reset[j];
                
                i++;
                j++;
                if(j==pat.size())
                {
                    ans.push_back(i-j+1);
                    j=reset[j];
                    //reseting  j once the pattern
                    // is matched 
                }
            }
            return ans;
            
        }
 
-1
akkeshri140420012 months ago
vector <int> search(string pat, string txt)       {           //code hee.           int n=pat.length();           int m=txt.length();           int i=0,j=0;           string r="";           vector<int>v;           while(j<m){               r+=txt[j];               if(j-i+1<n){                   j++;               }               else if(j-i+1==n){                   if(txt.substr(i,n)==pat){                       v.push_back(i+1);                   }                   r=r.substr(1);                   j++;                   i++;               }           }           return v;       }    
+1
shashankrustagii3 months ago
class Solution
{
    public:
    void lps(string pat, vector<int> &ls)
    {
        int len =0, i=1;
        ls[0]=0;
        while(i<pat.length())
        {
            if(pat[i]==pat[len]) ls[i++] = ++len;
            else
                if(len ==0) ls[i++] = 0;
                else len=ls[len-1];
        }
    }
    vector <int> search(string pat, string txt)
    {
        int n = pat.length();
        int m = txt.length();
        vector<int> ls(n);
        lps(pat, ls);
        int j=0,i=0;
        vector<int> ans;
        while(i<m)
        {
            if(txt[i]==pat[j]) i++,j++;
            if(j==n)
            {
                ans.push_back(i-j+1);
                j = ls[j-1];
            }
            else if(i<m and txt[i]!=pat[j])
            {
                if(!j) i++;
                else j = ls[j-1];
            }
        }
        return ans;
    }
};
0
rishurana2563 months ago
O(N) solution 
 
 
 vector <int> search(string pat, string txt)       {            string s = txt;            vector<int>v;           string t = pat + "#" + s;           int n = t.length();       int lps[n];         memset(lps,0,sizeof(lps));        int i=1,len=0;         while(i<n){         if(t[i]==t[len]){           while(t[i]==t[len]){           len++;           lps[i] = len;           i++;       }     }       else{           if(len>0)            len = lps[len-1];            else{             lps[i] = 0;             i++;            }       }   } //   for(int i=0;i<n;i++) // cout<<lps[i]<<" "; //   cout<<endl; int flag= 0;   int m = pat.length();   for(int i=1;i<n;i++){       if(lps[i]==m){           flag = 1;           // cout<<(i-2*m)<<endl;           v.push_back((i-2*m+1));       }   }   if(flag==0)    v.push_back(-1);    return v;}
0
palashsarkar00074 months ago
class Solution:   def __form_lps_array (self, patt, patt_s):       lps = [0 for ch in patt]       j, i = 0, 1       while (i < patt_s):           if (patt[i] == patt[j]):               lps[i] = j + 1               j += 1 ; i += 1           else:               if (j != 0):                   j = lps[j - 1]               else:                   lps[i] = 0                   i += 1       return lps
   def search (self, pattern, text):       patt_s, t_s = len(pattern), len(text)       if (patt_s > t_s):           return [-1]       if (patt_s == t_s):           return [1] if (pattern == text) else [-1]       i, j = 0, 0       lps = self.__form_lps_array(pattern, patt_s)       res = []       while (i < t_s):           if (text[i] == pattern[j]):               j += 1 ; i += 1           else:               if (j != 0):                   j = lps[j - 1]               else:                   i += 1           if (j == patt_s):               res.append(i - patt_s + 1)               j = lps[j - 1]       return res if (len(res) > 0) else [-1]
0
poraskr814 months ago
vector <int> search(string pat, string txt)       {           int n=txt.length();           int m=pat.length();           vector<int>temp;           for(int i=0;i<=n-m;i++)           {               int j;               for(j=0;j<m;j++)               {                   if(txt[j+i]!=pat[j])                   break;               }               if(j==m)               temp.push_back(i+1);           }           if(temp.size()==0)           {               temp.push_back(-1);               return temp;           }           return temp;       }
+3
abhixhek055 months ago
Using KMP Algo
class Solution
{
    public:
    
    
    void lps(string pat, vector<int> &ls){
        int len =0, i=1;
        ls[0]=0;
        while(i<pat.length()){
            if(pat[i] == pat[len]){
                len++;
                ls[i] = len;
                i++;
            }else{
                if(len ==0){
                    ls[i] = 0;
                    i++;
                }else{
                    len  = ls[len-1];
                }
            }
        }
    }
    
        vector <int> search(string pat, string txt)
        {
            //code hee.
            int n = pat.length();
            int m = txt.length();
            vector<int> ls(n);
            lps(pat, ls);
            int j=0,i=0;
            vector<int> ans;
           while(i<m){
                if(txt[i]==pat[j]){
                    i++;
                    j++;
                }
                if(j==n){
                    ans.push_back(i-j+1);
                    j = ls[j-1];
                  
                }else if(i<m && txt[i] != pat[j]){
                    if(j==0){
                        i++;
                    }else{
                        j = ls[j-1];
                    }
                }
                
            }
            return ans;
            
        }
     
};
+1
badgujarsachin835 months ago
vector <int> search(string pat, string txt)
        {
            vector<int> v;
            for(int i=0;i<txt.size()-pat.size()+1;i++){
                if(txt.substr(i,pat.size())==pat){
                    v.push_back(i+1);
                }
            }
            if(v.empty()){
                v.push_back(-1);
            }
                return v;
        }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.