Longest Substring Without Repeating Characters (LeetCode 3): Solution and Explanation

Medium
Hash Table
String
Sliding Window

Given a string, find the length of the longest contiguous substring in which no character appears more than once.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force enumerates every substring and checks whether its characters are unique. There are O(n²) substrings and checking each one costs up to O(n), so it is cubic, or quadratic if you extend each start until the first repeat. The waste is that after finding a repeat you throw everything away and start over from the next index, even though most of the window you just built is still valid.

Think of the substring as a window [l, r] that you grow to the right one character at a time. As long as the new character s[r] is not already inside the window, the window stays valid and you can record its length. When s[r] is already in the window, the window must shrink from the left, but only until the earlier copy of s[r] has been removed. Everything after that copy is still duplicate-free, so there is no reason to restart from scratch.

A hash set holding the characters currently in the window makes both checks constant time. Growing means adding s[r]; shrinking means removing s[l] and incrementing l. Because l and r only ever move to the right, each character is added once and removed at most once, which gives linear time even though there is a while loop nested inside the for loop.

Approach: Sliding window with a hash set

  1. Create an empty set charSet, set the left edge l = 0, and the best length res = 0.
  2. Loop the right edge r over every index of s.
  3. While s[r] is already in charSet, remove s[l] from the set and increment l.
  4. Add s[r] to charSet. The window s[l..r] now has no repeats.
  5. Update res = max(res, r - l + 1).
  6. Return res after the loop.

Step-by-step example

s = "abcabcbb"
  1. r = 0, 1, 2 add 'a', 'b', 'c'. The window is "abc" and res = 3.
  2. r = 3 ('a'): 'a' is in the set, so remove s[0] = 'a' and set l = 1. Add 'a'. The window is "bca", length 3.
  3. r = 4 ('b'): remove s[1] = 'b', l = 2, add 'b'. Window "cab". r = 5 ('c'): remove s[2] = 'c', l = 3. Window "abc".
  4. r = 6 ('b'): remove 'a' (l = 4), 'b' is still present so remove 'b' (l = 5). Add 'b'. Window "cb", length 2.
  5. r = 7 ('b'): remove 'c' (l = 6) and 'b' (l = 7), then add 'b'. Window "b". The answer is 3.

Code: Python, Java, C++

1class Solution:
2    def lengthOfLongestSubstring(self, s: str) -> int:
3        charSet = set()
4        l = 0
5        res = 0
6        
7        for r in range(len(s)):
8            while s[r] in charSet:
9                charSet.remove(s[l])
10                l += 1
11            charSet.add(s[r])
12            res = max(res, r - l + 1)
13        return res

Time and space complexity

Time

O(n)

Each character is added to the set once when r reaches it and removed at most once when l passes it, so the total work across both loops is at most 2n set operations.

Space

O(min(n, k))

The set holds the characters of the current window, which is at most the string length and at most the alphabet size k (for example 128 for ASCII).

Other approaches

Sliding window with last-seen index map (time O(n), space O(min(n, k)))

Store the last index of each character. When s[r] was seen inside the window, jump l directly to one past that index instead of removing characters one at a time. Same bound, fewer steps in practice.

Check every start index (time O(n × min(n, k)), space O(min(n, k)))

From each starting index, extend right with a fresh set until a repeat appears. It is simple and correct but restarts the work at every index.

Common mistakes

  • Using if instead of while when shrinking. The repeated character may be several positions inside the window, so a single removal is not enough.
  • Computing the window length as r - l instead of r - l + 1. Both ends are inclusive.
  • In the index-map variant, moving l backward when the last occurrence of a character lies before the current window. Use l = max(l, last[c] + 1).
  • Forgetting that spaces, digits and symbols count as characters. The string " " has an answer of 1, not 0.

Frequently asked questions

Why is the sliding window O(n) when it has a nested while loop?

The inner loop only moves l forward, and l can never pass r. Over the whole run, l advances at most n times in total, so the combined work is linear.

Set or hash map for this problem?

A set is enough when you shrink one character at a time. A map of last-seen indices lets you jump the left edge directly to the right spot, which saves steps but has the same O(n) bound.

What is the answer for an empty string?

0. The loop never runs and res keeps its initial value.

Does this return the substring itself?

No, only its length. To return the substring, also record the l and r values whenever res improves, then slice the string at the end.