Problem Statement
What data structure is commonly used to find the longest substring without repeating characters efficiently?
Explanation
A HashSet helps track unique characters within a sliding window. When a duplicate is found, the window start moves ahead. This achieves O(n) time for longest non-repeating substring problems.
Code Solution
SolutionRead Only
int lengthOfLongestSubstring(String s){
Set<Character> set=new HashSet<>();
int left=0,max=0;
for(int right=0;right<s.length();right++){
while(set.contains(s.charAt(right))) set.remove(s.charAt(left++));
set.add(s.charAt(right));
max=Math.max(max,right-left+1);
}
return max; }Practice Sets
This question appears in the following practice sets:
