Faaez Razeen

Longest Substring without Repeating Characters

  • 3 min read
  • String
  • LC-Medium
  • Sliding Window

3 years ago

(Good) Solution

TimeSpaceExplanation
O(n)O(min(m, n))
def lengthOfLongestSubstring(self, s: str) -> int: l = longest_len = 0 chars_seen = set() for r in range(len(s)): while s[r] in chars_seen: chars_seen.remove(s[l]) l += 1 chars_seen.add(s[r]) longest_len = max(longest_len, r - l + 1) return longest_len

(Better) Solution

Instead of iterating one by one till our substring doesn't have empty characters, we can keep track of the indexes so that once a duplicate is seen, we can immediately jump to the new index.

There is an extra condition:

TimeSpaceExplanation
O(n)O(min(m, n))
def lengthOfLongestSubstring(self, s: str) -> int: l = ans = 0 chars_seen = {} for r, ch in enumerate(s): if ch in chars_seen and l <= chars_seen[ch]: l = chars_seen[ch] + 1 chars_seen[ch] = r ans = max(ans, r - l + 1) return ans