Longest Substring Without Repeating Characters - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

We scan the string with a sliding window bounded by two pointers, left and right, and a set that stores the characters currently inside the window (i.e., the current valid substring with no repeats). The variable maxLength tracks the best length seen so far.

  • Pointers:
    • left: start index of the current valid substring (inclusive).
    • right: index of the character we are about to include. While s[right] is not yet added, the window is half-open [left, right). Immediately after adding s[right] (and before advancing right), the window becomes [left, right]. We then increment right to restore the half-open form for the next iteration.
  • Data structure: a set charSet to test membership in O(1) and to add/remove characters as the window moves.
  • Main loop (while right < s.length):
    1. Read candidate: let rightChar = s[right].
    2. Resolve conflict (shrink from the left): While rightChar is already present in charSet (meaning that character exists somewhere in the current window), shrink the window from the left by removing s[left] from the set and incrementing left until rightChar is no longer in the window β€” making it safe to expand the window from the right.
    3. Extend window: add rightChar to charSet. The window [left, right] is now a valid substring with all unique characters.
    4. Update answer: compute newLength = right - left + 1; if larger than maxLength, update maxLength.
    5. Advance: increment right to examine the next character.
  • Why this works: the window always contains unique characters. On a conflict, we discard the minimal prefix needed (by moving left) to make the new character admissible, then continue to grow. Each character is added and removed at most once, so the process is linear.
  • Result: when the loop finishes, maxLength is the length of the longest substring without repeating characters.

Time Complexity

Let n be the length of the string. Each character is added to the set at most once and removed at most once as the window slides. Both pointers (left and right) move forward at most n times total. Therefore, the running time is O(n).

Space Complexity

We store at most one instance of each unique character from the current substring in charSet. Therefore, the auxiliary space is O(m), where m is the number of unique characters in the input string s β€” note that m cannot exceed the size of the character alphabet.

Visucodize editorial solution titled JS Solution for LeetCode's Longest Substring Without Repeating Characters coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/longest-substring-without-repeating-characters.