medium

Longest Substring Without Repeating Characters

Find the length of the longest run of characters in a string with no repeats.

1. Define the problem

Longest Substring Without Repeating Characters

Given a string s, return the length of the longest substring without repeating characters . Grow a window on the right and shrink from the left whenever a duplicate enters, so the window never holds the same character twice.

Constraints

  • 0 ≤ s.length ≤ 5 × 104
  • s consists of English letters, digits, symbols and spaces

Example

Inputs = "abcabcbb"
Output3

Explanation The answer is "abc", with length 3.

2. Visualize the solution

Expand until a duplicate, then shrink left

Expand until a duplicate, then shrink left
Statusgrow

Window [a]; best = 1.

What happens in this step

window = [0, 0]  ("a")

before: seen = {}, best = 0
  add s[0] = 'a' → seen = {a}

seen now holds just 'a'; the window length 1 becomes the new best.
Step 1 of 5

Steps to visualize

  1. Grow right and add each new character into a seen set.
  2. When the new char is already in the set, shrink left until the duplicate is gone.
  3. After each add, the window holds only unique characters.
  4. Track the longest valid window length as best.
  5. Continue until right reaches the end of the string.
3. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Expand until a duplicate, then shrink left
Statusgrow

Window [a]; best = 1.

What happens in this step

window = [0, 0]  ("a")

before: seen = {}, best = 0
  add s[0] = 'a' → seen = {a}

seen now holds just 'a'; the window length 1 becomes the new best.
Step 1 of 5
4. Solution

Solution

solution.tsTypeScript
function lengthOfLongestSubstring(s) {
  const seen = new Set();
  let left = 0;
  let best = 0;

  for (let right = 0; right < s.length; right++) {
    const c = s[right];
    while (seen.has(c)) {
      seen.delete(s[left]);
      left++;
    }
    seen.add(c);
    best = Math.max(best, right - left + 1);
  }

  return best;
}
Time
O(n)
Space
O(min(n, charset))
5. Test cases

Test cases

InputExpectedCovers
s = "abcabcbb"3Docstring example — longest unique window is "abc"
s = ""0Empty string has length 0
s = "a"1Single character
s = "abcdef"6Entire string is unique
s = "bbbbb"1All identical characters
s = "pwwkew"3Classic pwwkew case — "wke"
s = "dvdf"3Must shrink past first d to take "vdf"
s = "a b c a"3Spaces and repeats far apart