O(N) time and O(1) Space solution c++ greedy approach


#1

int Solution::anytwo(string A) {
int i1,i2;
int n = A.size();
unordered_map<char,int> mp; // MAX_SPACE is O(26) = O(1)
int count = 0;
int prev_i = -1;
for(int i =0;i<A.size();i++)
{
if(mp.find(A[i]) == mp.end())
{
mp[A[i]] = i;
}
else
{
if(mp[A[i]]>prev_i) {count++; if(count >1) return 1;
prev_i = mp[A[i]];
mp[A[i]] = i;
}
}
}
return 0;
}