all entries
A-016Day 162026.05.18mediumleetcode #3neetcode150

Longest Substring Without Repeating Characters

#hash-table#string#sliding-window
leetcode #3 · longest-substring-without-repeating-characters
01

Problem

· problem
P.016

Longest Substring Without Repeating Characters

leetcode #3

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

constraints
  • · 0 ≤ s.length ≤ 5 × 10⁴
  • · s consists of English letters, digits, symbols and spaces
// paraphrased summary — see source for full text
examples
example 1input → output
"abcabcbb"
3
example 2input → output
"bbbbb"
1
example 3input → output
"pwwkew"
3
02

Pre-solve

· pre-solve
● 1list shown● 2select● 3reveal
  • Must the substring be contiguous?
  • What should we return for an empty string?
  • What if there are multiple valid substrings of the same maximum length?
  • Why is the maximum 26 unique characters (English letters) important?
  • Could 'bca' be a valid substring for 'abcabcbb'?
  • Should we return the substring itself?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03

Logic Structure

· logic
● 1slots shown● 2pick per slot● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Initialize character set
charSet = set()
charSet = {}
charSet = []
step 2· Initialize left pointer
l = 0
l = 1
l = -1
step 3· Initialize result variable
res = 0
res = 1
res = len(s)
step 4· Iterate with right pointer
for r in range(len(s)):
for r in range(1, len(s)):
for r in s:
step 5· Detect duplicate conditionnested
while s[r] in charSet:
if s[r] in charSet:
while s[l] in charSet:
step 6· Add current character to setnested
charSet.add(s[r])
charSet.add(s[l])
charSet.update([s[r]])
step 7· Update maximum lengthnested
res = max(res, r - l + 1)
res = max(res, r - l)
res = r - l + 1
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04

Solve · Trace

· solve
solution.py
1
class 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
mental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
"abcabcbb"
3
case 2
"bbbbb"
1
case 3
"pwwkew"
3
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.