Polski

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.

medium · typescript · javascript · python · csharp · java · go · 20 XP

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

sResult
"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).