

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’.
Can you try to solve this problem in O(N) time and O(1) space.
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.
The first line contains a single integer ‘T’ denoting the number of test cases, then each test case follows:
The first line of each test case contains a string ‘S’, denoting the input string.
For each test case, print the length of the longest substring containing at most two distinct characters.
Output for each test case will be printed in a separate line.
You are not required to print anything; it has already been taken care of. Just implement the function.
1 ≤ T ≤ 10
1 ≤ |S| ≤ 1000
Where 'S' contains lowercase English alphabets
Time limit: 1 sec
A standard brute force approach is to generate all the substrings, this takes ~O(N^2) time, then for each of the substring, we will check how many distinct characters it contains, therefore the total time complexity turns out to be of the order ~O(N^3).
We can further optimise the above approach by generating substrings starting that start from a particular index (let’s say ‘i’) and stopping the search when the number of characters is greater than two, we will require an additional data structure like a hash-set to keep a track of distinct characters for the substrings starting from index ‘i’. We can repeat this process for all the indices, and return the final answer.
Use two pointers, the first pointer marks the start of the current substring under observation and the second pointer marks the end of that substring. Now we can move these pointers according to the constraint mentioned in the question.
If the substring currently marked by the pointers contains greater than two distinct characters, then we will move the first pointer to remove the characters from the beginning of the current substring until we are left with just two distinct characters, else we will move the second pointer to now include the next character in our substring. Over our entire search, we can return the maximum substring length that we were able to achieve. This is a standard two-pointer technique and people call this with many other names like window sliding etc.