This post shows how to find the longest substring without repeating characters in JavaScript using the Sliding Window technique — a classic string problem asked frequently in technical interviews.
Longest substring without repeating characters (Sliding Window) in JavaScript:
Explanation:
This is a variable-size sliding window: instead of a fixed window length, the window grows by moving a right pointer forward, and shrinks by moving a left pointer forward whenever a repeated character is found. We use a Set to track which characters are currently inside the window, which lets us check for duplicates in constant time.
JavaScript Program to Find the Longest Substring Without Repeating Characters
function longestUniqueSubstring(str) {
const seen = new Set();
let left = 0;
let maxLength = 0;
for (let right = 0; right < str.length; right++) {
while (seen.has(str[right])) {
seen.delete(str[left]);
left++;
}
seen.add(str[right]);
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
const text = "abcabcbb";
console.log("Length of longest substring without repeating characters:", longestUniqueSubstring(text));
Output:
Length of longest substring without repeating characters: 3
This problem is one of the most commonly asked sliding window questions in interviews — it also pairs well with our anagram-checking logic for building a broader toolkit of string techniques. Practice similar problems in our Interview Prep section.
Frequently Asked Questions About the Longest Substring Problem
Why use a Set instead of an object to track characters?
A Set gives O(1) average time for checking whether a character exists and for adding or removing it, which keeps the overall algorithm at O(n) time. An object would work similarly, but a Set communicates "membership tracking" more clearly.
What makes this a "variable-size" sliding window?
Unlike a fixed-size window (like finding the max sum of a window of size K), this window's size changes as it expands and contracts based on whether a duplicate character is found — both pointers only ever move forward, which keeps the algorithm O(n) instead of O(n²).
What's the time complexity of this solution?
O(n), where n is the length of the string. Although there's a nested while loop, the left pointer only ever moves forward and never resets, so each character is processed at most twice overall.
