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:

A string ‘B’ is a substring of a string ‘A’ if ‘B’ that can be obtained by deletion of, several characters(possibly none) from the start of ‘A’ and several characters(possibly none) from the end of ‘A’. 
Follow up :
Can you try to solve this problem in O(N) time and O(1) space.
Example :
If ‘S’ = “ninninja”

Then, “ninnin” is the longest substring that contains at most two distinct characters. We will print the length of this substring which is equal to 6.
Detailed explanation ( Input/output format, Notes, Images )
Constraints :
1 ≤ T ≤ 10      
1 ≤ |S| ≤ 1000
Where 'S' contains lowercase English alphabets

Time limit: 1 sec

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

Popular posts from this blog

LeetCode 3Sum

30. Substring with Concatenation of All Words

Lowest common ancestor in a binary Tree