← Practice
πŸ“– Sliding windowsliding-window-longest-unique
LessonΒ·difficulty 4/5Β·~20 min

Sliding window: longest substring without repeating

Sliding window: longest substring without repeating

A sliding window is a sub-range [left, right] that you slide along a sequence, growing on the right and shrinking on the left to keep some rule true. It turns an O(n^2) "check every substring" search into a single O(n) pass:

python
left = 0
for right, c in enumerate(s):
    # extend the window to include c...
    # ...then move left forward until the window is valid again

This is LeetCode #3. The rule here: every character inside the window must be unique. A set (a hash set) tells us in O(1) whether a character is already in the window.

Your task

Write length_of_longest_substring(s) returning the length of the longest substring of s whose characters are all distinct.

python
length_of_longest_substring("abcabcbb")   # 3   ("abc")
length_of_longest_substring("bbbbb")       # 1   ("b")
length_of_longest_substring("pwwkew")      # 3   ("wke")
length_of_longest_substring("")            # 0

Hint: keep a set of characters in the current window. When s[right] is already in the set, remove s[left] and advance left until the duplicate is gone. Track the largest window size you ever reach.

Tests

  • abcabcbb
  • all same
  • pwwkew
  • empty
  • all unique (hidden)
  • repeat far (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.