Problem
Given a strings, find the length of the longest substring without duplicate characters.
Examples
Constraints
- 0 <= s.length <= 5 * 10^4
- s consists of English letters, digits, symbols and spaces.
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 3 with 13 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 3 # by problem number
lcpy gen -s longest_substring_without_repeating_characters # by problem name
s, find the length of the longest substring without duplicate characters.
Input: s = "abcabcbb"
Output: 3
Input: s = "bbbbb"
Output: 1
Input: s = "pwwkew"
Output: 3
class Solution:
# Time: O(n)
# Space: O(min(m, n)) where m is charset size
def length_of_longest_substring(self, s: str) -> int:
seen: set[str] = set()
left = max_len = 0
for right in range(len(s)):
while s[right] in seen:
seen.remove(s[left])
left += 1
seen.add(s[right])
max_len = max(max_len, right - left + 1)
return max_len
| Time | Space |
|---|---|
| O(n) | O(min(m, n)) where m is charset size |