Have a way to keep track of the duplicated characters.
Have a way to kep track of the max length.
Note that in this problem, we’re looking for substring, not subsequence here, so this is a perfect candidate for the sliding window technique, where we utilize two pointers to track the left and right side of a window. Then we can essentially slide the window by shrinking or extending it based on different conditions.
We’ll use:
A set to help keep track of the duplicated character and a normal variable to keep track of the max length.
A while loop to iterate through the input string and update the set and the max length accordingly.
Two pointers, start, end for our sliding window technique.
A variable, maxLength to track the maximum substring length.
As we iterate through the while loop, we’ll:
Increment start and remove the character at character from the set if the current character is duplicated
Add the current character to the set, increment end, and update maxLength
Complexity Explanation
Since we’re utilitize a single while loop with only constant operations inside, the time complexity is O(N), where N is the length of the input string.
Even though we removed duplicates from the set. the space complexity, at worst, can be O(N) in the case that input string has no repeating characters, so our set would contain every character.
We can slightly optimize the above solution by changing the set into a hash table/dictionary and allow the start pointer to jump more than 1 position at a time.
By changing the set into a dictionary, we can now keep track of the duplicated character’s most recent index, which we will use to determine whether or not the start pointer can skip to. As a trick, we can also save the most recent index as most recent index + 1 to use as the start pointer’s new position.
As a result, we will have the following changes:
if the current string is a duplicated, move start to the duplicated character’s last recorded index + 1 if it is farther right than start’s current position. This will allow us to shrink the window significantly.
Increment end pointer, update maxLength and duplicated hash table.
Complexity Explanation
Even though, we optimized the previous solution, the big O time and space complexity stays the same. However, now start is able to skip more than 1 index at a time.