Examples:
abcabcbb
3
aaaaaaa
1
For the search operation, we use a hashset that takes constant search time. Everytime we remove elements from the queue, we also need to remove elements from the hashset (removal is also constant time).
from collections import deque
def lengthOfLongestSubstring(s: str) -> int:
q = deque()
seen = set()
ans = 0
for l in s:
if l in seen:
ans = max(ans, len(q))
while q:
tmp = q.popleft()
seen.remove(tmp)
if tmp == l:
break
q.append(l)
seen.add(l)
return max(ans, len(q))
The time complexity of this solution is \(O(n)\) as we are not using any nested loop, and
l in seen
,popleft
, andremove
operations are \(O(1)\).
Here is an example:
## 3