First Longest Window of Distinct Characters
StringsAuto-graded · 25 test casesLast updated
Tests whether a candidate can apply the sliding window technique with a hash map to find the earliest, longest non-repeating character run in a string.
Problem
Given a string text, find the longest contiguous run of characters in which every character appears exactly once. If two or more runs share that maximum length, return the one that starts closest to the beginning of the string.
Return the substring itself. If the input is empty, return an empty string.
Constraints
0 <= len(text) <= 10^6textmay contain any standard ASCII characters (letters, digits, punctuation, spaces, etc.).- Your solution must run in O(n) time, where
n = len(text).
Examples
Example 1
Input: first_longest_distinct_run('abcabcbb')
Output: 'abc'
Example 2
Input: first_longest_distinct_run('bbbbb')
Output: 'b'
Example 3
Input: first_longest_distinct_run('')
Output: ''
Hints
Hint 1
Think about maintaining a window [left, right] that is always free of duplicates. What should happen to the left boundary when a repeated character enters from the right?
Hint 2
A dictionary that maps each character to the last index where it was seen lets you jump the left boundary forward in O(1) instead of shrinking one step at a time.
Hint 3
When you find a window whose length ties the current best, do not replace the best — the problem asks for the leftmost one. Make sure your comparison uses strict greater-than, not greater-than-or-equal.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why brute force falls short
Checking every possible substring for uniqueness costs O(n²) time. With strings up to 10⁶ characters that is too slow; we need a linear pass.
Sliding window with last-seen indices
Keep a window [left, right] that contains no duplicate characters at every step. Sweep right from left to right one character at a time:
- Look up the most recent index where the current character appeared (
prev). - If
previs inside the current window (prev >= left), the window now has a duplicate. Movelefttoprev + 1— the smallest position that drops the earlier copy. - Record
last_seen[char] = right. - The window is now duplicate-free. If
right - left + 1is strictly greater than the best length recorded so far, save this window as the new best.
After the loop, slice the string once: text[best_start : best_start + best_length].
The stale-index trap
A character may have been seen before the current window began. That old index must not pull left backward. The guard prev >= left handles this exactly. Without it, a string like "abba" would misplace left when the final 'a' is processed — its recorded index is 0, but left is already 2, so moving left back to 1 would break the invariant.
Why this gives the leftmost result on ties
The best window is updated only when the new length is strictly greater than the stored maximum. A later window of equal length never overwrites an earlier one. Because right increases monotonically, the first window to reach any given length is always the leftmost one.
For example, in "abcabcbb" the windows "abc", "bca", and "cab" all have length 3. Only "abc" (ending at index 2) triggers the strict-greater update; the other two do not replace it.
Correctness invariant
After each step, [left, right] is the longest duplicate-free window that ends at right. No window starting before prev + 1 can include both occurrences of the repeated character, so prev + 1 is the leftmost valid start. The global maximum is the largest of these per-position bests.
Complexity
- Time: O(n). Each character is processed once. Dictionary operations are O(1) average.
leftonly ever moves right, so characters are never re-scanned. The final slice is O(answer length) ≤ O(n). - Space: O(min(n, k)), where k is the alphabet size. The dictionary holds at most one entry per distinct character — at most 128 for standard ASCII, effectively O(1) auxiliary space.
Edge cases
| Input | What happens | Output |
|---|---|---|
"" | Loop never executes; best_length stays 0 | "" |
"bbbbb" | left jumps to right each step; length stays 1 | "b" |
"abcdef" | No duplicates; window expands to the full string | "abcdef" |
"abba" | Stale index for 'a' at the end is correctly ignored | "ab" |
"abcabcbb" | Three tied windows of length 3; strict > keeps the first | "abc" |
Reference solution
def first_longest_distinct_run(text: str) -> str:
last_seen = {} # char -> most recent index seen
left = 0 # left boundary of the current valid window
best_start = 0
best_length = 0
for right, char in enumerate(text):
prev = last_seen.get(char, -1)
# Only move the left boundary if the previous occurrence
# of this character is still inside the current window.
# Ignoring stale indices prevents jumping left, which
# would reintroduce duplicates (e.g., "abba" at the final 'a').
if prev >= left:
left = prev + 1
last_seen[char] = right
length = right - left + 1
# Strict '>' preserves the leftmost window on ties.
if length > best_length:
best_start = left
best_length = length
return text[best_start:best_start + best_length]