My Easy soln C++


string Solution::longestCommonPrefix(vector &A) {
string ans="";
int n=A.size();
string s=A[n-1];

    for(int j=0;j<A[0].size();j++)

return ans;


Can you explain the traversing part, I mean how you are coming to 2nd string in the vector?


He doesn’t need to come to the second string.

He is sorting all the strings in the vector. So order of strings is changed to make sure the first string is always the shortest and the last to be the longest.

At the end he only compares first and the last string and takes the prefix of these two. Whatever letters are common between these two are guaranteed to be common between all the strings between them. So the solution is O (N * log N) + O(K) where N = number of strings in the vector and K = common characters between all the strings.


string Solution::longestCommonPrefix(vector &A) {
string pref=A[0];
for(auto x: A){
string t;
for(int i=0;i<min(x.size(),pref.size());i++){
else break;
return pref;