Search Pattern (Rabin-Karp Algorithm) | Practice | GeeksforGeeks

Given two strings, one is a text string and other is a pattern string. 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:
S = "batmanandrobinarebat", pat = "bat"
Output: 1 18
Explanation: The string "bat" occurs twice
in S, one starts are index 1 and the other
at index 18. 

â€‹Example 2:
Input: 
S = "abesdu", pat = "edu"
Output: -1
Explanation: There's not substring "edu"
present in S.


Your Task:
You don't need to read input or print anything. Your task is to complete the function search() which takes the string S and the string pat as inputs and returns an array denoting the start indices (1-based) of substring pat in the string S. 

Expected Time Complexity: O(|S|*|pat|).
Expected Auxiliary Space: O(1).

Constraints:
1<=|S|<=105
1<=|pat|<|S|
 
-1
nitinmahobe1112 weeks ago
//simple c++ solution
 
 vector <int> search(string pat, string str)       {           vector<int> ans;for(int i=0;i<str.length();i++){ int j=i; string check=""; int k=0; while(str[j]==pat[k]) {  check+=str[j];  if(check==pat)  {   ans.push_back(i+1);   break;  }  j++;  k++; }}if(ans.size()==0){    ans.push_back(-1);}return ans;       }
0
aloksinghbais022 weeks ago
C++ solution having time complexity as O(|txt|*|pat|) and auxiliary space complexity as O(1) is as follows :- 
 
Execution Time :- 0.03 / 3.4 sec
 
vector <int> search(string pat, string txt){           vector<int> ans;           for(int i = 0; i < txt.length(); i++){               if(pat[0] == txt[i]){                   int j, k;                   for(j = i, k = 0; j < txt.length() && k < pat.length(); j++,k++){                       if(txt[j] != pat[k]) break;                   }                                      if(k == pat.length()){                       ans.push_back(i+1);                   }               }           }           if(!ans.size()) ans.push_back(-1);           return (ans);       }
0
amarrajsmart1971 month ago
//C++ CODE
// Time Taken 0.1/3.4 
//***********Without Using Rabin-Krap Algorithm******************
 vector <int> search(string pat, string txt)
        {
            //code here.
             vector <int> v;
             int n=txt.length();
             int m=pat.length();
            for(int i=0;i<n;i++)
            {
                   if(txt.substr(i,m)==pat)
                   {
                        
                       v.push_back(i+1);
                   }
               
            }
            if(!v.empty())
            return v;
            else
            {
                v.push_back(-1);
                return v;
            }
            
        }
0
ravi1010prakash1 month ago
class Solution{   public:void fillLPS(string str,int *lps) {       int n=str.length(),len=0;       //int lps[n];   lps[0]=0;   int i=1;   while(i<n){       if(str[i]==str[len])       {len++;lps[i]=len;i++;}       else       {if(len==0){lps[i]=0;i++;}           else{len=lps[len-1];}       }   }}       vector <int> search(string pat, string txt)       {           vector<int>v;           int n=txt.length();           int m=pat.length();           int lps[m];           int j=0,i=0;           fillLPS(pat,lps);           while(i<n)           {               if(pat[j]==txt[i])               {                   i++;                   j++;               }               if(j==m)               {                   v.push_back(i-j+1);                   j=lps[j-1];                                  }               else if(i<n&&pat[j]!=txt[i])               {                   if(j==0)                   i++;                   else                   j=lps[j-1];               }           }             if(v.size()==0)          {              v.push_back(-1);              return v;          }           return v;       }
0
rajesh02gfg2 months ago
SLIDING WINDOW TECHNIQUE || 0.1 SEC
vector <int> search(string pat, string txt)       {           vector<int> v;           int idx=1; // according to this question For printing, Starting Index of a string should be taken as 1.           string curr="";           int i=0;           for(; i<pat.length(); i++)           {               curr+=txt[i];           }           if(pat==curr) v.push_back(idx);           for(; i<txt.length(); i++)           {               curr=curr.substr(1);               idx++;               curr+=txt[i];               if(pat==curr) v.push_back(idx);           }           if(v.empty()) v.push_back(-1);           return v;       }
0
gdhikshith12 months ago
vector<int>v;           for(int i=0;txt[i]!='\0';i++)           {               string sub=txt.substr(i,pat.length());               if(sub==pat)               {                   v.push_back(i+1);               }           }           if(v.empty()) return vector<int>{-1};           return v;
+1
kake13373 months ago
           long long t=0,p=0,h=1;// avoid overflows
           int n=txt.length(), m=pat.length();
           
           int q=1000000007; // "q" should be as big as possible(at least range of txt.length()+7, in this case range of txt.length() is 10^5 so "q" should be at least 10^5+7)
           
           int d=256;// d=256 always work(range of char)
           for(int i=1;i<m;i++)
           h=(h*d)%q;
           for(int i=0;i<m;i++)
           {
               t=(t*d+txt[i])%q;
               p=(p*d+pat[i])%q;
           }
           vector<int> v;
           for(int i=0;i<=n-m;i++)
           {
               if(t==p)
               {
                   if(txt.substr(i,m)==pat)
                   v.push_back(i+1);
               }
               if(i<n-m){
               t=(d*(t-h*txt[i])+txt[i+m])%q;
               if(t<0)
               t+=q;
               }
           }
           if(v.size()==0)
           {
               v.push_back(-1);
               return v;
           }
           return v;
0
manishmaheshwari81333 months ago
JAVA CODE
Time Complexity: O(|S|*|pat|)Space Complexity: O(1)
**without Rabin-Karp Algorithm**
class Solution
{
    ArrayList<Integer> search(String pat, String S)
    {
        ArrayList<Integer> arr=new ArrayList<>();
            if(!S.contains(pat)){
            arr.add(-1);
            return arr;
        }
        
        int n=pat.length();
        for(int i=0;i<=S.length()-n;i++){
            if(pat.equals(S.substring(i,i+n))){
                arr.add(i+1);
            }
        }
        return arr;
    }
}
 
0
akashindranagar3 months ago
*********Java Code **********Total Time (0.6)
class Solution{   ArrayList<Integer> search(String pat, String S)   {       // your code here       ArrayList<Integer>list=new ArrayList<Integer>();       if(!S.contains(pat))       {           list.add(-1);           return list;       }       for(int i=0;i<S.length()-pat.length()+1;i++)       if(S.substring(i,i+pat.length()).equals(pat))           list.add(i+1);           return list;   }}
-1
imranwahid4 months ago
Easy C++ solution
https://ide.geeksforgeeks.org/8m9q5HjfzY
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.