Given a string, find the longest substring containing distinct characters.

The problem differs from the problem of finding the longest subsequence with distinct characters. Unlike subsequences, substrings are required to occupy consecutive positions within the original string.

 
For example,

Input:  findlongestsubstring
 
Output: The longest substring with all distinct characters is dlongest or ubstring
 
 
Input:  longestsubstr
 
Output: The longest substring with all distinct characters is longest
 
 
Input:  abbcdafeegh
 
Output: The longest substring with all distinct characters is bcdafe
 
 
Input:  aaaaaa
 
Output: The longest substring with all distinct characters is a

Practice this problem

A simple solution would be to generate all the given string substrings and return the longest substring containing all distinct characters. The time complexity of this solution is O(n3) since it takes O(n2) time to generate all substrings for a string of length n and O(n) time to process each substring.

 
We can easily solve this problem in O(n) time. The idea is to use a sliding window technique. In the sliding window technique, a window is maintained that satisfies the problem constraints. The window is unstable if it violates the problem constraints, and it tries to stabilize by increasing or decreasing its size.

So for the current problem, the window (substring) is stable if it contains all distinct characters at any point. If the window includes duplicates characters, it shrinks by removing characters from the left till it becomes stable again. A steady window tends to increase its size by adding characters to it until it becomes unstable again. The process continues until the window reaches the last character in the string. At each point the window size changes, update the maximum window size.

 
Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

bcdafe

Java


Download  Run Code

Output:

bcdafe

Python


Download  Run Code

Output:

bcdafe

The time complexity of the above solution is O(n) as it does two traversals of the given string of length n.