Skip to main content

Longest Common Prefix

Task: Given an array of strings, Find the longest common prefix among all the strings in the array.

Example:
Input:
1
4
geeksforgeeks geeks geek geezer
Output:
gee

Here is the Code:
Program in C++:

  1. #include<iostream>
  2. using namespace std;
  3. void longestCommonPrefix(string *a,int n)
  4. {
  5.     string s1= a[0];
  6.     for(int i=1;i<n;i++)
  7.     {
  8.         string s2=a[i];
  9.         int j=0;
  10.         while(j<s1.length())
  11.         {
  12.             if(s1[j]==s2[j])
  13.             {
  14.                 j++;
  15.             }
  16.             else
  17.             {
  18.                 s1.erase(j,s1.length());
  19.                 break;
  20.             }
  21.         }
  22.     }
  23.     if(s1.length()==0)
  24.     {
  25.         cout<<-1;
  26.     }
  27.     else
  28.     {
  29.         cout<<s1;
  30.     }
  31.     return;
  32. }
  33. int main()
  34.  {
  35. int t;
  36. cin>>t;
  37. while(t--)
  38. {
  39.     int n;
  40.     cin>>n;
  41.     string a[n];
  42.     for(int i=0;i<n;i++)
  43.     {
  44.         cin>>a[i];
  45.     }
  46.     longestCommonPrefix(a,n);
  47.     cout<<endl;
  48. }
  49. return 0;
  50. }

Here is the Video: