KatInterview

First Longest Window of Distinct Characters

StringsAuto-graded · 25 test cases
EasyAuto-gradedStringssliding-windowhash-maptwo-pointers

Last 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^6
  • text may 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.