![]() |
VOOZH | about |
Given a string s having lowercase characters, find the length of the longest substring without repeating characters.
Examples:
Input: s = "geeksforgeeks"
Output: 7
Explanation: The longest substrings without repeating characters are "eksforg” and "ksforge", with lengths of 7.Input: s = "aaa"
Output: 1
Explanation: The longest substring without repeating characters is "a"Input: s = "abcdefabcbb"
Output: 6
Explanation: The longest substring without repeating characters is "abcdef".
Table of Content
The idea is to find length of longest substring with distinct characters starting from every index and maximum of all such lengths will be our answer.
To find the length of the longest substring with distinct characters starting from an index, we create a new visited array of size = 26 to keep track of included characters in the substring. vis[0] checks for 'a', vis[1] checks for 'b', vis[2] checks for 'c' and so on.
Note: The array size is fixed at 26, representing the lowercase English alphabet as a constant
7
Time Complexity: O(n2), The outer loop runs O(n) times and the inner loop may also run up to O(n) in the worst case. The visited array initialization costs O(26), which is constant and does not affect overall complexity.
Auxiliary Space: O(1), vis array has size 26 which is constant.
The idea is to maintain a window of distinct characters. The window is initialized as single character. We keep extending the window on the right side till we see distinct characters. When we see a repeating character, we remove characters from the left side of the window. We keep track of the maximum length window.
Below are the detailed steps:
right pointer moves from left to right, extending the current window.Working:
7
The approach stores the last indexes of already visited characters. The idea is to maintain a window of distinct characters. Start from the first character, and keep extending the window on the right side till we see distinct characters. When we see a repeating character, we check for the last index of the repeated character:
- If last index of repeated character >= starting index of the current window, then we update the starting index of the current window to last index of repeated character + 1 to remove the repeated character.
- If last index of repeated character <starting index of the current window, then it means that the repeated character is already outside the current window so the window size remains unchanged.
After iterating over all the characters, the largest window size will be our answer.
Working:
7