Longest K unique characters substring

this problem is done using the sliding window technique..

In this, we will first make a map that will store characters and their count until the size of the map is less than k and increment j by one every time until the map size is less than k.

once the size of the map is k, then we can check whether this substring length is the longest or not.

if the size of the map is greater than k, in this case, we need to decrement the count of characters that are present at starting, until the size of the map becomes equal to k....one thing to keep in mind is that if any character has count value 0 in the map then remove that character using erase command of the map.

int longestKSubstr(string s, int k)

{

int n=s.length();

unordered_map<char,int> mp;

int i=0;

int j=0;

int ans=-1;

while(j<n)

{ mp[s[j]]++;

if(mp.size()<k)

{

j++;

}

else

if(mp.size()==k)

{

ans=max(ans,j-i+1);

j++;

} else

{

while(mp.size()>k)

{

mp[s[i]]--;

if(mp[s[i]]==0)

{

mp.erase(s[i]);

}

i++;

}

j++;

}

}

return ans;

}