Introduction
The Longest Substring Without Repeating Characters problem involves finding the length of the longest substring that contains only unique characters.
Given a string s, the task is to:
- find the longest substring
- without repeating characters
- return its length
This problem introduces the important concept:
Sliding Window TechniqueThis problem helps in understanding:
- hashing
- sliding window
- dynamic traversal
- substring processing
Example
Input:s = "abcabcbb"
Output:
3
Explanation: Longest substring without repeating characters:
"abc"
Length = 3
Input: s = "bbbbb"
Output:
1
Explanation:
Longest substring:
"b"
Length = 1
Constraints
0 <= s.length <= 5 * 10^4s contains English letters,
digits, symbols, and spaces
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Generate all substrings
- Check whether substring contains duplicates
- Track maximum length
This approach works but checking every substring increases time complexity.
Steps
- Generate all substrings.
- Check uniqueness using set.
- If substring is unique:
- update maximum length
- Return maximum length.
Dry Run
Input:s = "abcabcbb"
Check substrings: "a" → unique
"ab" → unique
"abc" → unique "abca" → duplicate found Maximum length = 3
Final Result: 3
Brute Force Code
Complexity Analysis
Time Complexity: O(n²)Explanation:
All substrings are checked.
Space Complexity: O(n) Explanation:
Extra set is used for uniqueness checking.
Approach 2 : Optimized Solution (Sliding Window)
Explanation
The optimized solution uses the Sliding Window Technique.
The idea is:
- Maintain a window containing unique characters
- Expand window using right pointer
- Shrink window when duplicate appears
- Track maximum window size
This avoids checking all substrings repeatedly.
Steps
- Initialize:
- left = 0
- right = 0
- Use set/hashmap for tracking characters.
- Expand window using right pointer.
- Remove duplicates using left pointer.
- Update maximum length.
Dry Run
Input:s = "abcabcbb"Initially:left = 0
right = 0
Window: "a" Length = 1
Expand: "ab" Length = 2
Expand:
"abc" Length = 3
Expand: "abca" Duplicate found Move left pointer
Window becomes: "bca" Continue traversal...
Final Result: 3
Optimized Code
Complexity Analysis
Time Complexity: O(n)Explanation: Each character is added and removed
at most once.
Space Complexity: O(n) Explanation:
Extra set is used for window tracking.