Longest Common Prefix in an Array | Practice | GeeksforGeeks

Given a array of N strings, find the longest common prefix among all strings present in the array.

Example 1:
Input:
N = 4
arr[] = {geeksforgeeks, geeks, geek,
         geezer}
Output: gee
Explanation: "gee" is the longest common
prefix in all the given strings.

Example 2:
Input: 
N = 2
arr[] = {hello, world}
Output: -1
Explanation: There's no common prefix
in the given strings.


Your Task:
You don't need to read input or print anything. Your task is to complete the function longestCommonPrefix() which takes the string array arr[] and its size N as inputs and returns the longest common prefix common in all the strings in the array. If there's no prefix common in all the strings, return "-1".

Expected Time Complexity: O(N*max(|arri|)).
Expected Auxiliary Space: O(max(|arri|)) for result.

Constraints:
1 ≤ N ≤ 103
1 ≤ |arri| ≤ 103
0
abhigyanpatek4 hours ago
Simple C++ Solution:
string longestCommonPrefix (string arr[], int N)   {       sort(arr, arr+N);       string s;       for(int i = 0; i<arr[0].length(); i++){           if(arr[0][i] == arr[N-1][i])               s.push_back(arr[0][i]);           else break;       }       if(s.size() == 0) return "-1";       return s;   }
+1
harshscode1 day ago
sort(arr,arr+n);
        string ans;
        for(int i=0;i<arr[0].length();i++)
        {
            string p=arr[0];
            string q=arr[n-1];
            if(p[i]==q[i])
            ans.push_back(p[i]);
            else
            break;
        }
        return ans==""?"-1":ans;
0
kuldeepahirwarmba4 days ago
    String longestCommonPrefix(String arr[], int n){       // code here       int min = 1000;       String s ="";       int count = 0;       int temp = 1000;      for(int i=0;i<n;i++)      {          int len = arr[i].length();          if(len<min)          {              min = len;              s = arr[i];          }      }      for(int i =0;i<n;i++)      {          count =0;          for(int j=0;j<min;j++)          {              if(arr[i].charAt(j)==s.charAt(j))              {                  count++;                                }else{                  break;                               }          }          if(count<temp)          {              temp= count;          }
      }       if(temp ==0)       {           return "-1";       }else{      return s.substring(0,temp);       }   }
0
bhardwajji1 week ago
easy c++
 
string longestCommonPrefix (string arr[], int n)
    {
        string pref ="";
        if(n==1)
            return arr[0];
        bool f = true;
        int minlen =INT_MAX;
        
        for(int i=0;i<n-1;i++){
            string s1=arr[i];
            string s2=arr[i+1];
            
            int x = s1.size();
            int y = s2.size();
            minlen = min(minlen,min(x,y));
        
            string same="";
            
            for(int k=0;k<minlen;k++){
                
                if(s1[k]==s2[k]){
                    if(f==true){
                         pref+=s1[k];
                    }
                    same+=s1[k];
                }
                else 
                    f= false;
            }
            
            if(same.size() < pref.size())
                pref = same;
        }
        
        if(pref == "")
            return "-1";
            
        return pref;
    }
0
amonk
This comment was deleted.
0
vishutyagi72 weeks ago
c++ 0.4 sec solution
string find(string s,string s1)   {       int m,i;       string s2;       m=min(s.size(),s1.size());       for(i=0;i<m;i++)       {           if(s[i]!=s1[i])           {               break;           }           else           {              s2.push_back(s[i]);            }       }       return s2;   }   string longestCommonPrefix (string arr[], int N)   {       if(N!=1)       {       string str=arr[0];       for(int i=1;i<N;i++)       {           str=find(str,arr[i]);       }       if(str.size()>0)       {       return str;       }       else       {           return "-1";       }       }       else       {           return arr[0];       }   }
0
nikipyati2 weeks ago
class Solution:
    def longestCommonPrefix(self, arr, n):
        ans=''
        for i in zip(*arr):
            s="".join(i)
            if len(set(s))!=1:
                break
            else:
                ans+=s[0]
        if len(ans)==0:
            return -1
        return ans 
0
sachinupreti190
This comment was deleted.
0
ankajarya2752 weeks ago
class Solution{
    
    public static String common(String a,String b)
    {
        String sol="";
        for(int i=0;i<Math.min(a.length(),b.length());i++)
        {
            if(a.charAt(i)==b.charAt(i))
            {
                sol+=a.charAt(i);
            }
            else
            {
                break;
            }
        }
        return sol;
    }
    String longestCommonPrefix(String arr[], int n){
        // code here
        String ans= arr[0];
        for(int i=1;i<n;i++)
        {
            ans=common(ans,arr[i]);
        }
        if(ans.isEmpty())
         return "-1";
        
     return ans;  
    }
}
-1
mohiteshk2 weeks ago
C++ Total Time Taken: 0.22/1.44 
 
    string longestCommonPrefix (string arr[], int N)   {       // your code here       string longestString;              if(N == 0)           return "-1";              if(N == 1)           return arr[0];              string &first = arr[0];       int num_chars = 0, i = 0;;       bool matching_till_i = false;              while(1)       {           matching_till_i = true;           for(int i = 1; i< N; ++i)           {               if(first[num_chars] == arr[i][num_chars])                   continue;                              matching_till_i = false;           }                      if(matching_till_i)               num_chars++;           else               break;       }              if(num_chars == 0)           return "-1";              longestString = arr->substr(0, num_chars);       return longestString;   }
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.