LeetCode 3: Longest Substring Without Repeating Characters — Python Solution

Solve LeetCode 3: Longest Substring Without Repeating Characters in Python with a last-seen sliding window approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyMedium
TopicSliding Window
Reusable patternlast-seen sliding window
ComplexityO(n) time and O(k) space

What the problem is testing

Track each character’s latest index and move the left boundary past a repeated occurrence when it lies inside the current window.

Algorithm

  1. Track each character’s latest index and move the left boundary past a repeated occurrence when it lies inside the current window.
  2. Maintain this invariant: The active window contains no duplicate characters.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

class Solution:
    def lengthOfLongestSubstring(self, s):
        last = {}; left = best = 0
        for right, char in enumerate(s):
            if char in last and last[char] >= left: left = last[char] + 1
            last[char] = right
            best = max(best, right - left + 1)
        return best

Why this is correct

The proof follows the maintained state: The active window contains no duplicate characters. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(n) time and O(k) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

The repeated character may have occurred before the current window and should then be ignored.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 209. Minimum Size Subarray Sum · Next: 30. Substring with Concatenation of All Words