Length of the longest substring Visualization & Animation
Finds the longest substring with no repeating characters using a sliding window and hash set; O(n).
## What is it?
Find the length of the longest substring that contains no repeating characters. Classic sliding window problem solved with a hash set tracking the current window contents.
## How it works
- Use `left` and `right` pointers both starting at 0
- Expand the window by moving `right` forward
- If `str[right]` is already in the current window (set), shrink the window by moving `left` forward until the duplicate is removed
- At each step, `maxLen = max(maxLen, right - left + 1)`
- Return `maxLen`
## When to use
- Any problem asking for the longest/shortest window satisfying a uniqueness or frequency constraint
- Template for variable-size sliding window problems
## Key Points
- O(n) time — each character enters and leaves the window at most once
- O(k) space where k is the size of the character set (26 for lowercase letters, 128 for ASCII)
- Use a `HashMap` (char → last index) for an optimized version that jumps `left` directly
Category: algorithms
Difficulty: intermediate
- two-pointers-palindrom
- strings
Time Complexity: O(n)
Space Complexity: O(k)
View Length of the longest substring VisualizationLength of the longest substring
intermediateFinds the longest substring with no repeating characters using a sliding window and hash set; O(n).
PhaseInit
Window—
MaxLen0
L0
R—
a
[0]b
[1]c
[2]a
[3]b
[4]c
[5]b
[6]b
[7]Window chars
Unvisited character
Best window (complete)
Duplicate / being removed
Left behind (past window)
Input: "abcabcbb" (lowercased). L=0, R=-1. Sliding window starts empty — expand R to grow the window.
1 / 22