Skip to content
LEETFLIX

Longest Substring Without Repeating Characters

Solve on LeetCode

The sliding window pattern in its purest form — and the jump-ahead trick that makes it one pass.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

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

Constraints

  • —0 <= s.length <= 5 * 10^4
  • —s consists of English letters, digits, symbols and spaces.

Examples

Input

s =
"abcabcbb"

Output

3

s

a
0
b
1
c
2
a
3
b
4
c
5
b
6
b
7

The answer is "abc", with the length of 3.

02

Solution

2 approaches · Python and Go. Pick a tab — the walkthrough follows.

Optimal▶ Animated

Grow right one step at a time; on a repeat, jump left past the previous occurrence.

Maintain last[ch] = most recent index of each character. When s[right] was last seen inside the current window, move left to just after that position. Then record the new index and measure the window.

Algorithm

  1. last = {}, left = 0, best = 0.
  2. For each right: if s[right] in last and last[s[right]] >= left, set left = last[s[right]] + 1.
  3. last[s[right]] = right; best = max(best, right − left + 1).
  4. Return best.
Time
O(n)
Space
O(min(n, alphabet))

Each character is processed once; the map holds at most one entry per distinct character.

Solution.py
class Solution:    def lengthOfLongestSubstring(self, s: str) -> int:        last: dict[str, int] = {}  # char -> most recent index        left = 0                   # window is s[left..right]        best = 0        for right, ch in enumerate(s):            if ch in last and last[ch] >= left:                left = last[ch] + 1  # jump past the previous occurrence            last[ch] = right            best = max(best, right - left + 1)        return best
Watch this run

03

Interactive walkthrough

Playing “Sliding window with last-seen index”. Edit the input, hit Run, then scrub.

Approach: Sliding window with last-seen index

Loading animation…

Up next