longest-substring-without-repeating-characters.py
sliding-window/longest-substring-without-repeating-characters.py · Python · 1.3 KiB · 2026-05-07 20:14
# Keep a set of seen characters and two pointers. Move the right pointer until we see a duplicate, then move the left pointer until we remove the duplicate from the set. Keep track of the maximum length at each step. # sliding-window # Brute force - O(n^2) time, O(1) space def lengthOfLongestSubstring(s: str) -> int: maxlen = 0 for l in range(len(s)): seen = set() for r in range(l, len(s)): if s[r] in seen: break seen.add(s[r]) maxlen = max(maxlen, r-l) return maxlen # Sliding window - O(n) time, O(m) space (m: unique chars in s) def lengthOfLongestSubstring(s: str) -> int: charSet = set() l = 0 res = 0 for r in range(len(s)): while s[r] in charSet: charSet.remove(s[l]) l += 1 charSet.add(s[r]) res = max(res, r - l + 1) return res # Sliding window (optimal) - O(n) time, O(m) space (m: unique chars in s) def lengthOfLongestSubstring(s: str) -> int: if not s: return 0 l, r = 0, 0 seen = {} maxlen = 0 while r < len(s): curr = s[r] if curr in seen: l = max(l, seen[curr] + 1) seen[curr] = r maxlen = max(maxlen, r-l +1) r += 1 return maxlen