LeetCode 3: Longest Substring Without Repeating Characters — Step-by-Step Visual Trace


Medium — Sliding Window | Two Pointers | Hash Set | String

The Problem

Find the length of the longest substring within a given string that contains all unique characters with no repeating characters.

Approach

Use a sliding window technique with two pointers (left and right) and a set to track unique characters. Expand the window by moving the right pointer when characters are unique, and contract by moving the left pointer when duplicates are found.

Time: O(n) · Space: O(min(m, n))

Code

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        left, right = 0, 0
        max_length = 0
        unique_chars = set()

        while right < len(s):
            if s[right] not in unique_chars:
                unique_chars.add(s[right])
                max_length = max(max_length, right - left + 1)
                right += 1
            else:
                unique_chars.remove(s[left])
                left += 1

        return max_length

Watch It Run

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.


Comments