Longest Common Prefix

Hey, fam!

The problem we are working on today is "Longest Common Prefix" from Leetcode. The question is to find the longest sequence which is common among all the strings and is present at the start of each string. For example:

Input - ["flower", "flow", "flight"] Output - "fl"

Because "fl" is common between flower, flow, flight.

Input - ["reflower", "flow", "flight"] Output - ""

Because nothing is common among the three.

My approach:

We find the string with the smallest length and then check if that string is present at the start of each string because the longest common prefix cannot be longer than the smallest string. Then to check if it is present in other strings, we keep popping the last character of the smallest string until the resultant is present in other strings.

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

int main()
{
    vector<string> s;
    for(int i=0;i<3;i++){
        string t;
        cin>>t;
        s.push_back(t);
    }

    string ans=s[0];

    for(int i=0;i<s.size();i++)
    {
       if(ans.length()>s[i].length()){
           ans=s[i];
       }
    }

    for(int i=0;i<s.size();i++)
    {
        size_t idx=s[i].find(ans);
        if(idx==-1 || idx!=0)
        {
            while((idx==-1 || idx!=0) && ans.length()>0)
            {
                ans.pop_back();
                //cout<<endl<<ans;
                idx=s[i].find(ans);
            }
        }

    }

    cout<<ans;

}

Hope you got the approach. If not, feel free to drop your questions in the comment box. Also, I would love to learn a better approach if you've got one :) Byee👋