[
string
sliding window
]
Leetcode 0003. Longest Substring Without Repeating Characters
Problem Statement
https://leetcode.com/problems/longest-substring-without-repeating-characters
Solution
This is classical problem for sliding window. Let us keep window with elements [beg: end), where first element is included and last one is not. For example [0, 0) is empty window, and [2, 4) is window with 2 elements: 2 and 3.
Let us discuss our algorithm now:
windowis set of symbols in our window, we use set to check in $\mathcal{O}(1)$ if new symbol inside it or not.beg = end = 0in the beginning, so we start with empty window, alsoans = 0andn = len(s).- Now, we continue, until one of two of our pointers reaches the end. First, we try to extend our window to the right: check
s[end] in windowand if we can, add it to set, moveendpointer to the right and updateans. If we can not add new symbol to set, it means it is already inwindowset, and we need to move left pointer and movebegpointer to the right.
Complexity
We move both of our pointers only to the left, so time complexity is $\mathcal{O(n)}$. Space complexity is $\mathcal{O}(1)$.
Code
class Solution:
def lengthOfLongestSubstring(self, s):
window = set()
beg, end, ans, n = 0, 0, 0, len(s)
while beg < n and end < n:
if s[end] not in window:
if end + 1 < n: window.add(s[end])
end += 1
ans = max(ans, end - beg)
else:
window.remove(s[beg])
beg += 1
return ans
If you like the solution, you can upvote it on leetcode discussion section: Problem 0003