← Back to Leo Academy Masterclass

Problem #3: Longest Substring Without Repeating Characters

Medium Sliding Window

Intuition & Strategy Breakdown

Use a sliding window with two pointers (left and right) and a hash set. Advance the right pointer to expand the window, and if a character repeats, increment the left pointer to shrink the window until all characters are unique.

Python Solution

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        char_set = set()
        left = 0
        max_len = 0
        for right in range(len(s)):
            while s[right] in char_set:
                char_set.remove(s[left])
                left += 1
            char_set.add(s[right])
            max_len = max(max_len, right - left + 1)
        return max_len

Java Solution

class Solution {
    public int lengthOfLongestSubstring(String s) {
        Set set = new HashSet<>();
        int left = 0, maxLen = 0;
        for (int right = 0; right < s.length(); right++) {
            while (set.contains(s.charAt(right))) {
                set.remove(s.charAt(left++));
            }
            set.add(s.charAt(right));
            maxLen = Math.max(maxLen, right - left + 1);
        }
        return maxLen;
    }
}
Watch Interactive Video on Leo Academy Main App