From b7ad28921e84888fed7b64c9084d66a24682e0de Mon Sep 17 00:00:00 2001 From: Deven <63876261+devenperez@users.noreply.github.com> Date: Wed, 26 Nov 2025 15:06:17 -0500 Subject: [PATCH] Time: 15 ms (80.93%), Space: 18.1 MB (11.97%) - LeetHub --- ...-substring-without-repeating-characters.py | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 0003-longest-substring-without-repeating-characters/0003-longest-substring-without-repeating-characters.py diff --git a/0003-longest-substring-without-repeating-characters/0003-longest-substring-without-repeating-characters.py b/0003-longest-substring-without-repeating-characters/0003-longest-substring-without-repeating-characters.py new file mode 100644 index 0000000..d08267e --- /dev/null +++ b/0003-longest-substring-without-repeating-characters/0003-longest-substring-without-repeating-characters.py @@ -0,0 +1,40 @@ +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + + """ + Complexities: + Time: O(n) + Space: O(X) + + where n = len(s) + X = len([All compatible characters]) + """ + + charsInSubstring = set({}) + + startIndex = 0 # inclusive + endIndex = 0 # exclusive + maxLengthFound = 0 + + # Use sliding window to find solution + # - O(n) -> startIndex or endIndex always increase by 1 every iteration = 2n + while endIndex < len(s): + # if next letter not in substring, then endIndex++ + if s[endIndex] not in charsInSubstring: + charsInSubstring.add(s[endIndex]) + endIndex += 1 + + # Update maxLengthFound + if endIndex - startIndex > maxLengthFound: + maxLengthFound = endIndex - startIndex + + # else pop off front until popped [next letter] + else: + while s[startIndex] != s[endIndex]: + charsInSubstring.remove(s[startIndex]) + startIndex += 1 + + charsInSubstring.remove(s[startIndex]) + startIndex += 1 + + return maxLengthFound \ No newline at end of file