Problem
Given a string s, return the length of the longest substring that contains no repeated characters.Example(s)
Consider the following example(s) to understand the expected input and output.Input
s = "abcabcbb" Output
3
Solution
This solution uses the Sliding Window technique along with a HashSet to maintain a window containing only unique characters.The right pointer expands the window by moving through the string. Whenever a duplicate character is encountered, the left pointer moves forward and removes characters from the HashSet until the duplicate character is removed.
Once the window contains only unique characters, the current window length is calculated as right - left + 1. The maximum window length found during the traversal is stored as the answer.
This approach ensures that the window always contains unique characters while efficiently finding the longest valid substring.
public int lengthOfLongestSubstring(String s) {
int left = 0;
int max = 0;
Set<Character> set = new HashSet<>();
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
while (set.contains(c)) {
set.remove(s.charAt(left));
left++;
}
set.add(c);
max = Math.max(max, right - left + 1);
}
return max;
}
Complexity
The algorithm traverses the string using two pointers. Since each character is added to and removed from the HashSet at most once, the overall time complexity is O(n).The HashSet stores the characters in the current window, so the extra space complexity is O(n) in the worst case when all characters are unique.
Comments
No comments yet. Ask a question or share what helped.