Browse curriculum

FAANGPrep Sprint

Longest Substring Without Repeating Characters

Find the length of the longest substring without repeating characters.

Examples

Input:s = "abcabcbb"
Output:3
Explain:

"abc" is the longest stretch with no repeated character, so the answer is 3.

Input:s = "bbbbb"
Output:1
Explain:

Every character is "b", so no stretch longer than 1 avoids a repeat.

Input:s = "pwwkew"
Output:3
Explain:

"wke" is the longest repeat-free stretch, length 3. "pwke" does not count: its letters are not contiguous in the input, so it is a subsequence rather than a substring.

Problem Understanding

We need to find the length of the longest substring in a given string s that contains no duplicate characters.

A substring is a contiguous sequence of characters. For example, in "abcabcbb", "abc" is a substring, but "acb" is not (it skips characters).

Algorithm Strategy

We use the Sliding Window technique with a Hash Map (or Array for fixed charsets) to track characters in the current window.

  1. Initialize left = 0 and max_len = 0.
  2. Use a map to store the most recent index of each character.
  3. Iterate right from 0 to end of string:
    • If s[right] is in map and its index is >= left, it means we found a repeat inside our current window. Move left to map[s[right]] + 1 to skip the previous occurrence.
    • Update map[s[right]] to the current right index.
    • Update max_len = max(max_len, right - left + 1).
  4. Return max_len.

Key Insight: Instead of shrinking the window one character at a time, we can jump the left pointer directly past the duplicate. Both versions are O(N); the jump just skips the inner shrinking loop.

Interactive Visualization

"dvdf"

EMPTY WINDOW

d

0

v

1

d

2

f

3

left

0

right

—

Length

—

Best

0

map (char:last index)

Empty

 

left starts at 0, the map is empty and the best length is 0

Next

Read 'd' at 0

String

Watch how the window expands and jumps the left pointer when a duplicate is found.