Longest common prefix | Practice | GeeksforGeeks

Given two strings str1 and str2 of the same length. Find the longest prefix of str1 which is common in str2.  

Example 1:
Input: 
str1 = "geeks"
str2 = "dgeek"
Output: 0 3
Explanation: 
Longest prefix from str1
present in str2 is "geek" 
starting at index 0 in str1
and ending at index 3.
Example 2:
Input:
str1 = "practicegeeks"
str2 = "coderpractice"
Output: 0 7
Explanation: 
Longest prefix from str1
present in str2 is "practice"
starting at index 0 and ending 
at index 7 in str1.
Your Task:
You don't need to read input or print anything. Complete the function longestCommonPrefix() which takes strings str1 and str2 as input parameters and returns a list of integers whose first two elements denote the start and end index of str1 at which the longest common prefix of str1 is found in str2. 
If there is no common prefix then the returning list should contain [-1,-1].
 
Expected Time Complexity: O(|str1|*|str2|)
Expected Auxiliary Space: O(|str1|)
 
Constraints:
1 <= |str1|, |str2| <= 1000
str1 and str2 contain only lowercase alphabets.
+1
wxyzpl3 weeks ago
TC: O(N) SC: O(N)  TIME: 0.27   USING KMP ALGORITHM
pattern string as s1 and given string as s2make str=s1+'&'+s2find lps array of strtraverse lps array from index = s1.length()+1 to lps.lengthfind max valuereturn {0,maxVal-1}
pattern string as s1 and given string as s2
make str=s1+'&'+s2
find lps array of str
traverse lps array from index = s1.length()+1 to lps.length
find max value
return {0,maxVal-1}
CODE
// for finding lps array
 int[] findLps(String str){       int[] lps=new int[str.length()];       int i=1;int len=0;       while(i<str.length()){           if(str.charAt(i)==str.charAt(len)){               len++;               lps[i]=len;               i++;           }           else{               if(len>0){                   len=lps[len-1];               }               else{                   lps[i]=0;                   i++;               }           }       }       return lps;   }
 
// given function
public int[] longestCommonPrefix(String s1, String s2){       String str=s1+'&'+s2;       int[] lps=findLps(str);       int max=0;       for(int i=s1.length()+1;i<lps.length;i++){           max=Math.max(max,lps[i]);       }       int[] arr=new int[2];       arr[0]=0;       arr[1]=max-1;       return arr;   }
 
SOURCE :  peepcoding KMP algorithm
0
patildhiren443 months ago
JAVA - 0.29
 
public int[] longestCommonPrefix(String s1, String s2){
        int[] arr = new int[2];
        
        for(int i=1; i<s1.length(); i++){
            if(s2.contains(s1.substring(0,i))){
                arr[0] = 0;
                arr[1] = i-1;
            }
        }
        return arr;
    }
+1
kake13375 months ago
    vector<int> longestCommonPrefix(string str1, string str2){
       int i=0,j=0;
       int r=-1;
       while(i<str1.length() && j<str2.length())
       {
           if(str1[i]==str2[j])
           {
               i++;
               j++;
           }
           else
           {
               if(i!=0){
                 r=max(r,i);
                 i=0;
               }
               else
               j++;
           }
       }
       if(r==-1)
       r=i;
       vector<int> v;
       if(r==0)
       {
           v.push_back(-1);
           v.push_back(-1);
           return v;
       }
       v.push_back(0);
       v.push_back(r-1);
       return v;
   }
0
radheshyamnitj7 months ago
  int i=0;
        string ans="";
        while(i<str1.length()) 
        {

            ans.push_back(str1[i]);

            if(str2.find(ans)!=string::npos)
            {
                i++;
            }

            else
            {
                break;
            }
        }

        if(i==0)
        {
            return {-1,-1};
        }

        return {0,i-1};
    }

0
mrdonno8 months ago
class Solution:   def longestCommonPrefix(self, str1, str2):       # code here       Ex = ''       n  = len(str1)       end = 0       res = []       res2 = [-1,-1]       i = 0       while(i<n):                      if str1[0] not in str2:               return res2                      Ex = Ex+str1[i]                      if Ex not in str2:                              res.append(0)               if i==0:                   res.append(0)               else:                   res.append(i-1)               break           i+=1               
0
abhinavbansal05
This comment was deleted.
0
abhinavbansal05
This comment was deleted.
0
Imran Wahid10 months agoEasy C++ solutionclass Solution{public:    vector<int> longestCommonPrefix(string str1, string str2)    {        int i=0;        string tmp="";        while(i<str1.length()) <br=""/>        {            tmp.push_back(str1[i]);            if(str2.find(tmp)!=string::npos)            {                i++;            }            else            {                break;            }        }        if(i==0)        {            return {-1,-1};        }        return {0,i-1};    }};Reply Open ExternallyShow 0 RepliesLoading...
Imran Wahid
Easy C++ solution
class Solution{public:    vector<int> longestCommonPrefix(string str1, string str2)    {        int i=0;        string tmp="";        while(i<str1.length()) <br=""/>        {            tmp.push_back(str1[i]);            if(str2.find(tmp)!=string::npos)            {                i++;            }            else            {                break;            }        }        if(i==0)        {            return {-1,-1};        }        return {0,i-1};    }};
0
Bheema Ram10 months agohttps://uploads.disquscdn.c...Reply Open ExternallyShow 0 RepliesLoading...
Bheema Ram
https://uploads.disquscdn.c...
0
Bheema Ram
This comment was deleted.
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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.