MediumNo. 0003
Longest Substring Without Repeating Characters — LeetCode 3 Python Solution
- Pattern
- Sliding Window
- Topics
- Hash Table, String, Sliding Window
- On study lists
- Blind 75, NeetCode 150, Grind 75 and Top Interview 150
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a string s, find the length of the longest substring without duplicate characters.
Example
- Input
- s = "abcabcbb"
- Output
- 3
- Explanation
- The answer is "abc", with the length of 3. Note that "bca" and "cab" are also correct answers.
Python solution
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
cnt = Counter()
ans = l = 0
for r, c in enumerate(s):
cnt[c] += 1
while cnt[c] > 1:
cnt[s[l]] -= 1
l += 1
ans = max(ans, r - l + 1)
return ansComplexity
- Time
- O(n), where n is the length of the string
- Space · auxiliary
- O(|Σ|), where Σ represents the character set, and the size of Σ is 128
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 3. Longest Substring Without Repeating Characters is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0030 | Substring with Concatenation of All Words | Hard |
| 0076 | Minimum Window Substring | Hard |
| 0187 | Repeated DNA Sequences | Medium |
| 0395 | Longest Substring with At Least K Repeating Characters | Medium |
| 0424 | Longest Repeating Character Replacement | Medium |
| 0438 | Find All Anagrams in a String | Medium |
Frequently asked questions
- How hard is LeetCode 3. Longest Substring Without Repeating Characters?
LeetCode 3. Longest Substring Without Repeating Characters is rated Medium on LeetCode.
- What is the time complexity of LeetCode 3. Longest Substring Without Repeating Characters?
The Python solution on this page runs in O(n), where n is the length of the string.
- What is the space complexity of LeetCode 3. Longest Substring Without Repeating Characters?
The Python solution on this page uses O(|Σ|), where \Sigma represents the character set, and the size of \Sigma is 128 auxiliary space.
- What topics does LeetCode 3. Longest Substring Without Repeating Characters cover?
LeetCode 3. Longest Substring Without Repeating Characters is tagged Hash Table, String and Sliding Window on LeetCode.