To solve the problem of finding the length of the longest substring without repeating characters, we can use the Sliding Window technique. This approach is efficient and works well for problems involving contiguous sequences, like substrings.
Approach: Sliding Window
Idea:
-
Sliding Window Concept:
- Imagine a window that can expand and contract to cover a portion of the string
s.
- The window will maintain the current substring without repeating characters.
- We'll move the window through the string to find the maximum length of such substrings.
-
Use a Hash Map (or Dictionary):
- We'll keep track of the characters in the current window and their latest positions.
- This helps in determining when a character repeats and where to move the start of the window.
Steps:
-
Initialize:
- A dictionary
char_index_map to store characters and their latest indices.
- Two pointers
left and right to define the current window. Both start at 0.
- A variable
max_len to keep track of the maximum length found.
-
Iterate Over the String:
- Move the
right pointer one step at a time through the string.
- For each character at the
right pointer:
- If the character is already in
char_index_map and its index is within the current window (left <= char_index_map[char]):
- Move the
left pointer to char_index_map[char] + 1 to exclude the repeated character.
- Update or add the character's latest index in
char_index_map.
- Calculate the current window length (
right - left + 1) and update max_len if necessary.
-
Result:
- After iterating through the string,
max_len will hold the length of the longest substring without repeating characters.
Time and Space Complexity:
- Time Complexity: O(n), where n is the length of the string. Each character is visited at most twice (once by
right and once by left).
- Space Complexity: O(min(m, n)), where m is the size of the character set. In the worst case, we might store all characters in the string.
Python Implementation
Here's how you can implement the above approach in Python:
def length_of_longest_substring(s: str) -> int:
char_index_map = {}
max_len = 0
left = 0 # Left pointer of the sliding window
for right, char in enumerate(s):
# If the character is found in the map and is inside the current window
if char in char_index_map and char_index_map[char] >= left:
# Move the left pointer to the right of the same character's previous index
left = char_index_map[char] + 1
# Update or add the character's latest index
char_index_map[char] = right
# Update the maximum length if needed
current_window_length = right - left + 1
max_len = max(max_len, current_window_length)
# Debug statements (optional)
# print(f"Char: {char}, Left: {left}, Right: {right}, Current Max: {max_len}")
return max_len
Explanation of the Code:
-
Initialization:
char_index_map: An empty dictionary to store the latest index of each character.
max_len: Stores the maximum length found, initialized to 0.
left: The starting index of the current window, initialized to 0.
-
Iterating Through the String:
- Using
enumerate to get both the index (right) and the character (char) at each step.
- Check for Repeats:
- If the current character
char is already in char_index_map and its last recorded index is greater than or equal to left, it means the character is within the current window and is a repeating character.
- Update
left to be one position right of the previous occurrence to ensure all characters in the new window are unique.
- Update Character Index:
- Record the current index of
char in char_index_map.
- Update Maximum Length:
- Calculate the length of the current window (
right - left + 1) and update max_len if this window is larger than the previous maximum.
-
Return the Result:
- After processing all characters, return
max_len as the length of the longest substring without repeating characters.
Testing the Function:
Let's test the function with the provided examples:
# Test cases
print(length_of_longest_substring("abcabcbb")) # Output: 3 ("abc")
print(length_of_longest_substring("bbbbb")) # Output: 1 ("b")
print(length_of_longest_substring("pwwkew")) # Output: 3 ("wke")
print(length_of_longest_substring("")) # Output: 0
print(length_of_longest_substring(" ")) # Output: 1
print(length_of_longest_substring("au")) # Output: 2
Expected Output:
3
1
3
0
1
2
Conclusion
The sliding window technique provides an efficient way to solve the problem with linear time complexity. By maintaining a window of unique characters and adjusting it dynamically, we can find the longest substring without repeating characters without unnecessary computations.