Typorithm · medium

Longest Substring Without Repeats

longest-substring-without-repeating-characterssliding-windowvariable-windowsetshrink
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Longest Substring Without Repeats

0%

Sliding Window

Grow the window to the right; when a repeat appears, shrink from the left until the window holds unique characters.

The window must contain only distinct characters at all times.

Expanding right adds a character; if it duplicates one already inside, shrink from the left until it is removed.

The answer is the maximum window width seen during the sweep.

01

Set tracks the window's characters.

02

Shrink left until no duplicate.

03

Window width = right - left + 1.

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

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

  return best;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Window contents

A Set holds the distinct characters in the current window.

const seen = new Set()

2. Shrink on repeat

Drop characters from the left until the duplicate is gone.

while (seen.has(s[right])) {
      seen.delete(s[left]);
      left += 1;
    }

3. Extend right

Add the new character once the window is valid.

seen.add(s[right])

4. Window length

Track the longest valid window width.

best = Math.max(best, right - left + 1)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Longest Substring Without Repeats: Lesson & Practice · Typorithm | ApplyDjinn