pranay_teja
11/17/2018 - 7:01 AM

RollingLCP-LongestCommonPrefix

#include<bits/stdc++.h>
using namespace std;

// https://www.youtube.com/watch?v=Tj0VRPcj8pQ

string LCP(vector<string> a){
    if(a.size()==0){
        return "";
    }
    string curr=a[0];
    for(int i=1;i<a.size();i++){
        string temp;
        for(int j=0;j<curr.size();j++){
            if(j<a[i].size() && curr[j]==a[i][j]){
                temp.push_back(curr[j]);
            }else{
                break;
            }
        }
        curr=temp; // update curr lcp
        if(temp.size()==0){
            return temp; // if lcp is "" return it as no other lcp is possible
        }
    }
    return curr;
}

int main(){
    // freopen("ip.txt","r",stdin);
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        vector<string> a(n);
        for(int i=0;i<n;i++){
            cin>>a[i];
        }
        cout<<LCP(a)<<endl;
    }
    return 0;
}