Longest Substring Without Repeating Characters
Algorithm/HashSet
Intuition
The problem asks us to find the length of the longest substring without repeating characters. A sliding window technique is well-suited for this problem.
We use two pointers to represent the window's boundaries and expand or shrink the window dynamically to maintain a set of unique characters. As the window grows, we track the maximum length of a substring with distinct characters.
Approach
Below is the step-by-step breakdown of the approach:
- Initialization:
- Use a hash set to store the characters in the current sliding window.
- Initialize two pointers:
left
to represent the start of the window andright
to iterate over the string. - Use a variable
ans
to store the maximum length of the substring found.
- Sliding Window Process:
- Iterate over the string using the
right
pointer.- If the character at
right
already exists in the hash set, remove characters from the start (by moving theleft
pointer) until the duplicate is removed. - Add the current character at
right
to the hash set. - Update
ans
to be the maximum of the currentans
and the window size (right - left + 1
).
- If the character at
- Iterate over the string using the
- Return the Result:
- After processing the string, return
ans
as the length of the longest substring with unique characters.
- After processing the string, return
Complexity
- Time Complexity: , where
n
is the length of the input string. Each character is processed at most twice—once by theright
pointer and once by theleft
pointer. - Space Complexity: , where
m
is the size of the character set. The hash set stores the characters in the current window.