Word distance-2

how do I handle the case when both word 1 and word 2 are
equal.
suggest the change in my code.

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

int mindist(vectorl,int n,string word1,string word2)
{
int ans=l.size(),w1=-1,w2=-1;
for(int i=0;i<l.size();i++)
{
if(l[i]==word1)w1=i;
if(l[i]==word2)w2=i;
if(w1!=-1&&w2!=-1)
ans=min(ans,abs(w1-w2));
}
return ans;
}

int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin>>n;
vectorl;
for(int i=0;i<n;i++)
{
string temp;
cin>>temp;
l.push_back(temp);
}
string word1;string word2;
cin>>word1>>word2;
cout<<mindist(l,n,word1,word2);
return 0;
}

hello @akshugoyal705
add an extra if statement.
if word1==word2 then simply compute distance=current index of word1 - last occurence of word1 .

check this for implementation->

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.