Longest Substring Without Repeating Characters
Topic: 06. Hashing & Strings
Link: LeetCode 3 - Longest Substring
1. Logical Breakdown
- [x] Core Logic: Sliding Window
[left, right]. - [x] Constraint: If duplicate found, shrink window from left.
2. Visualization
graph LR
Expand["Expand Right"] --> Check["Duplicate in Window?"]
Check -- Yes --> Shrink["Remove Left & Increment Left"]
Check -- No --> Add["Add Char & Update Max"]
Shrink --> Check
3. Complexity
- Time: O(N)
- Space: O(K)
4. Code
package com.dsa.hashing;
import java.util.HashSet;
import java.util.Set;
public class LongestSubstring {
public int solve(String s) {
int n = s.length();
int left = 0, right = 0, maxLen = 0;
Set<Character> window = new HashSet<>();
while (right < n) {
if (!window.contains(s.charAt(right))) {
window.add(s.charAt(right));
maxLen = Math.max(maxLen, right - left + 1);
right++;
} else {
window.remove(s.charAt(left));
left++;
}
}
return maxLen;
}
}