Longest stretch without repeats
Find the longest contiguous part of a string in which no character repeats. A sliding window with a last-seen map – in a single pass.
An ID generator checks how long a piece of a log can be taken without repeating a character. For a string s find the longest contiguous fragment (substring) in which each character occurs at most once.
Task
Return the fragment itself (not its length). When several fragments have the same maximum length, return the leftmost one. For an empty string – an empty string. Spaces and punctuation are ordinary characters.
Signatures: longestUniqueSubstring(s) (JS/TS), longest_unique_substring(s) (Python), Solution.LongestUniqueSubstring (C#), Solution.longestUniqueSubstring (Java), LongestUniqueSubstring (Go).
Examples
s | Result |
|---|---|
"abcabcbb" | "abc" |
"bbbbb" | "b" |
"pwwkew" | "wke" – "pwke" is not contiguous |
"abba" | "ab" – "ba" is as long, but further right |
"dvdf" | "vdf" |
Constraints
0 ≤ s.length ≤ 200,000, ASCII characters (codes 32–126).
Expected complexity
O(n) time, O(σ) memory, where σ is the alphabet size (here at most 95).