ToolMight Logo
MediumSliding WindowTwo PointersArrays & HashingDynamic Sliding WindowCharacter Last-Seen Index Map

Longest Substring Without Repeating Characters

Find the longest contiguous substring with all distinct characters. Compare shrinking-set sliding windows against O(1) direct left-pointer jumps via an index map.

Optimal Time
O(n)
Optimal Space
O(min(n, m))
Primary Pattern
Dynamic Sliding Window
Visualizer
Open Interactive View →

Problem Statement

Given a string s, find the length of the longest substring without duplicate characters.

Examples & Constraints

Example 1
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints
  • 0 <= s.length <= 5 * 10^4
  • s consists of English letters, digits, symbols and spaces.

Pattern Recognition & Core Invariant

How to Spot This Pattern

Longest or shortest contiguous segment problems with uniqueness or frequency bounds use a two-pointer sliding window whose left bound shrinks whenever validity breaks.

Core Invariant

The active range [left, right] always holds distinct characters; if s[right] previously appeared at idx >= left, jumping left = idx + 1 restores uniqueness immediately.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Sliding Window with Character Set (Shrinking)
O(n)O(min(n, m))Maintain active window characters in a Set. Whenever s[right] already exists in the set, evict s[left] one character at a time while advancing left.
2. Sliding Window with Last-Seen Index MapOptimal
O(n)O(min(n, m))Expand the right window pointer while storing each character's latest index. When a duplicate appears, jump the left pointer forward past the previous occurrence in O(1) time.

1. Sliding Window with Character Set (Shrinking)

TimeO(n)
SpaceO(min(n, m))

Maintain active window characters in a Set. Whenever s[right] already exists in the set, evict s[left] one character at a time while advancing left.

Time ComplexityO(n)

Each character is inserted once by right and evicted at most once by left (<= 2N operations).

Space ComplexityO(min(n, m))

Set stores at most the active window's unique characters (bounded by alphabet size m).

How It Works

Shrinking the Left Boundary Step-by-Step

Before optimizing with last-seen indices, model window uniqueness with a plain Hash Set:

  1. Expand right from 0 to n - 1.
  2. While s[right] is already inside seen:
  • Remove s[left] from seen.
  • Advance left++.
  1. Insert s[right] into seen and update maxLen = max(maxLen, right - left + 1).

Even though an inner while loop appears, left visits each index at most once across the entire run, keeping total time O(n) (up to 2n operations vs n with the jump map).

Step-by-Step Dry Run

Execution Trace·Step 1 of 3
1Insert 'a', 'b', 'c'

Right adds indices 0..2 into seen set. maxLen reaches 3.

State:seen = {a, b, c}max = 3
Strengths
  • +Simple invariant: set contents literally mirror the active window
  • +Requires no index arithmetic beyond left++
Trade-offs
  • -Up to 2N passes over characters compared to single-jump N passes with an index map

Reference Implementation

Complete implementation for Sliding Window with Character Set (Shrinking) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def length_of_longest_substring_set(s: str) -> int:
seen = set()
left = 0
max_len = 0
for right, ch in enumerate(s):
while ch in seen:
seen.remove(s[left])
left += 1
seen.add(ch)
max_len = max(max_len, right - left + 1)
return max_len

2. Sliding Window with Last-Seen Index Map

Optimal
TimeO(n)
SpaceO(min(n, m))

Expand the right window pointer while storing each character's latest index. When a duplicate appears, jump the left pointer forward past the previous occurrence in O(1) time.

Time ComplexityO(n)

The right pointer makes a single pass across the string of length N. The left pointer only jumps forward. Total work is linear O(n).

Space ComplexityO(min(n, m))

Consumes memory proportional to the character set size M (e.g. 128 for standard ASCII or 256 for extended ASCII).

How It Works

The Core Mental Model: An Elastic Expanding Window

A naive brute force checks every possible substring of length 1 to N, taking O(n³) time to check uniqueness.

Instead, we maintain an elastic sliding window [left, right] that represents the current valid substring without duplicates:

  1. Maintain a hash map (or fixed array of 128/256 ASCII entries) storing the most recent index where each character was seen.
  2. Maintain left = 0 and maxLength = 0.
  3. Expand right from 0 to n - 1:
  • If s[right] was previously seen at prevIndex >= left, we have a duplicate inside our current active window!
  • Jump left = prevIndex + 1 (skipping the duplicate immediately without moving left one step at a time).
  • Update the character's last-seen index in our map: map[s[right]] = right.
  • Update our best window size: maxLength = max(maxLength, right - left + 1).
  1. Return maxLength.

Invariant: Window Never Contracts Backwards

Notice the check prevIndex >= left. If a character was seen at index 2, but our left pointer is already at index 5, that previous occurrence is outside the current window and can be safely ignored. This ensures left only moves forward.

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1Window [0..0] ('a')

Expand right to 0 ('a'). 'a' not seen. window: 'a', max = 1.

State:left = 0right = 0 ('a')map = {'a': 0}max = 1
Strengths
  • +Optimal O(n) single pass runtime
  • +Left pointer jumps directly without one-by-one decrements
Trade-offs
  • -Requires character set index array or hash map memory

Reference Implementation

Complete implementation for Sliding Window with Last-Seen Index Map in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def length_of_longest_substring(s: str) -> int:
last_seen = {}
max_len = 0
left = 0
for right, char in enumerate(s):
if char in last_seen and last_seen[char] >= left:
left = last_seen[char] + 1
last_seen[char] = right
max_len = max(max_len, right - left + 1)
return max_len
if __name__ == "__main__":
test1 = "abcabcbb"
test2 = "pwwkew"
print("test1 length:", length_of_longest_substring(test1))
print("test2 length:", length_of_longest_substring(test2))
Interactive Visualizer

Trace Array & Matrix mechanics in memory

Step through custom inputs in the Array & Matrix visualizer to inspect pointer updates, array shifts, and call-stack state alongside Longest Substring Without Repeating Characters.

Open Array & Matrix visualizer

Frequently Asked Questions

Why use a last-seen index map instead of a hash set?

A hash set forces left to walk forward step-by-step deleting skipped characters. An index map lets left jump straight to prevIndex + 1 in one O(1) assignment, cutting inner-loop work to zero.

Why is `lastSeen[char] >= left` critical on inputs like "abba"?

When scanning the trailing 'a' at index 3, lastSeen['a'] still equals 0 even though left already moved to 2. Without >= left (or left = max(left, lastSeen[c] + 1)), left would jump backward to 1 and re-include the duplicate 'b's.

Why is the space complexity O(min(n, m))?

The map holds at most one slot per distinct symbol in the alphabet (m, e.g., 128 ASCII chars) and never more than string length n.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • Empty string ("") returns 0.
  • All identical characters ("bbbbb") stays length 1.
  • Stale repeat before left ("abba"): when right=3 sees 'a' from index 0 while left=2, left MUST stay at 2 rather than regressing to 1.
  • Strings containing spaces, digits, and ASCII punctuation (up to 5 * 10^4 chars).

Common Bugs to Avoid

  • Setting `left = lastSeen[char] + 1` blindly without guarding `lastSeen[char] >= left`, which drags left backwards on inputs like "abba".
  • Returning length of a subsequence (disjoint unique characters like "pwke" for "pwwkew") rather than a contiguous substring.
  • Reallocating a brand-new hash set per starting index (degrading runtime to O(n²)).

Interview Follow-Up Variations

  • Longest Substring with At Most K Distinct Characters (or Longest Repeating Character Replacement).
  • Minimum Window Substring: sliding window with target character frequency deficit tracking.

Related Problems

All problems
EasyTwo Pointers

Valid Palindrome

Check whether a string reads identically forward and backward over alphanumeric characters. Compare build-and-reverse against O(1)-space converging pointers.

Pattern: Two Pointers Converging
O(n) · O(1)
Solve
EasyArrays & Hashing

Two Sum

Find indices of two array elements summing to target. Compare O(n²) brute-force scanning against O(n) one-pass complement lookup with a Hash Map.

Pattern: Hash Map
O(n) · O(n)
Solve
EasyArrays & Hashing

Contains Duplicate

Check whether any integer repeats inside an array. Compare early-exit O(n) Hash Set membership testing against O(1)-space in-place sorting.

Pattern: Hash Set
O(n) · O(n)
Solve