Given a string s, find the length of the longest substring without duplicate characters.
s consists of English letters, digits, symbols and spaces.s[r] already in the set, you have a duplicate.l until s[r] is no longer in the set. Keep removing s[l] from the set and incrementing l until the duplicate is gone.l directly past the duplicate.Network routers must detect and drop duplicate packets in a stream. A sliding window keeps track of only the packets in the current "fresh" window — using a hash set for O(1) lookup. When a duplicate arrives, the window shrinks from the left until the duplicate is evicted, then the new packet is added. This is exactly the two-pointer algorithm — and it processes millions of packets per second with O(n) time and O(k) space (where k is the alphabet/charset size).
This is a variable-size sliding window problem. The window [l, r] always contains unique characters. We grow it by advancing r, and shrink from the left whenever a duplicate is detected.
charSet = set(), l = 0, res = 0.r through the string. If s[r] is already in charSet, remove s[l] and increment l until the duplicate is gone.s[r] to charSet.res = max(res, r - l + 1).res.Each character is inserted and removed from the set at most once, so total work is O(n). Space is O(k) where k is the character set size (at most 128 for ASCII).
Discussion
…