I’ve been working on a JavaScript function to calculate the length of the longest substring without repeating characters. I encountered a couple of issues that I’m hoping to get some clarity on:
Using if vs. while for Duplicate Detection:
My initial implementation used an if statement to check for duplicates (if(set.has(s[right]))). However, I noticed it doesn’t work as expected, and replacing if with while (while(set.has(s[right]))) seems to solve the issue. Why does the while loop work correctly here instead of if?
Order of Operations with Increment and Deletion:
In my function, when a duplicate is detected, I tried to delete the character from the set immediately after incrementing the left pointer (left++ followed by set.delete(s[left])). This approach doesn’t seem to work properly. What’s the correct order of operations in this scenario to maintain the integrity of the sliding window?
function subs(s) {
const set = new Set();
let left = 0;
let total = 0;
for(let right = 0; right< s.length; right++) {
if(set.has(s[right])){
set.delete(s[left]);
left++;
}
set.add(s[right]);
total = Math.max(total, right - left + 1);
}
return total;
}