LeetSolved

Find solutions to all LeetCode problems here.

3.

Longest Substring Without Repeating Characters

Medium

Problem Description

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

Examples

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Constraints

Approach to Solve

Use a sliding window technique with a hash set to keep track of unique characters in the current substring.

Code Implementation

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        char_set = set()
        max_length = 0
        left = 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_length = max(max_length, right - left + 1)
        return max_length

Explanation

We use a sliding window approach with two pointers, left and right. We expand the window by moving the right pointer and add characters to a set. If we encounter a repeated character, we remove characters from the left until the repeated character is removed. We keep track of the maximum length of the window. The time complexity is O(n) because each character is processed at most twice (once by the right pointer and once by the left pointer). The space complexity is O(min(m, n)), where m is the size of the character set.

Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(min(m, n))
Code copied to clipboard!