Longest Substring with At Most Two Distinct Characters
Problem statement
You are given a string ‘S’, you need to find the length of the longest substring that contains at most two distinct characters.
Note:
Follow up :Example :Constraints :
Intution:
This question is a sliding window question. for every right, we need to calculate l where substring(l,r) has at most 2 distinct characters. now the question is how do we calculate distinct characters in the substring in O(1) complexity. This can be done using freq array, we check character at r in freq array, if value was 0 we increment distinct count.
if distinct count after adding rth character is >2 then we increment l till it is less than or equal to 2 using a while loop.
we keep track of max at every iteration of r, and return final ans;
Comments
Post a Comment