Skip to content

Instantly share code, notes, and snippets.

@hongtaoh
Created October 8, 2024 03:04
Show Gist options
  • Save hongtaoh/cfa35d261927cdffd427442ae002e716 to your computer and use it in GitHub Desktop.
Save hongtaoh/cfa35d261927cdffd427442ae002e716 to your computer and use it in GitHub Desktop.
Solution to Leetcode 3 Longest Substring Without Repeating Characters
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
charSet = set()
left = 0
maxLen = 0
for right in range(len(s)):
while s[right] in charSet:
charSet.remove(s[left])
left += 1
charSet.add(s[right])
maxLen = max(maxLen, len(charSet))
return maxLen
@hongtaoh
Copy link
Author

This solution has a higher complexity $O(n^2)$ because the in operation in deque takes $O(m)$ where m is the length of the substring.

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        import collections
        dq = collections.deque([])
        left = 0
        maxLen = 0
        for right in range(len(s)):
            while s[right] in dq:
                dq.popleft()
            dq.append(s[right])
            maxLen = max(maxLen, len(dq))
        return maxLen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment