Longest Substring Without Repeating Characters
MediumNeetCode 150Top Interview 150 Sliding WindowVisaInfosysBloombergOracleDeloitteAmazonProblem
You are given a string s. Find the length of the longest contiguous piece of
s in which no character appears more than once.
A substring must be one unbroken run of characters. Picking letters from different places does not count.
Constraints
- 0 ≤ s.length ≤ 5 · 10⁴
- s may contain letters, digits, symbols and spaces
Examples: pick one to animate
Solutions
TimeO(n)
SpaceO(min(n, alphabet))
Time: right visits each index once, and left only moves forward, so each letter is added and removed at most once: 2n set operations in total.
Space: The set never holds a repeated letter, so it has at most min(n, alphabet size) entries.
Grow a window with right. Whenever the new letter is already inside, shrink from
left one letter at a time until it is gone. Each index enters and leaves the set at most once.