Longest Stretch of Non-Repeating Characters
StringsAuto-graded · 22 test casesLast updated
Find the length of the longest contiguous run in a string where every character is distinct, using a linear-time sliding window with index tracking.
Longest Run of Distinct Characters
You are given a string text. Find the longest contiguous block of characters in which no character appears more than once, and return how long that block is.
Comparison is case-sensitive, so 'a' and 'A' are different characters. Spaces, digits, and punctuation are ordinary characters and are treated like any other.
A block must be contiguous, meaning a run of neighbouring characters. Picking characters that are not adjacent (a subsequence) does not count.
Input
text: a string of lengthn.
Output
- An integer: the length of the longest contiguous block of
textwhose characters are all different. - If
textis empty, return0.
Constraints
0 <= len(text) <= 10^5textcontains English letters, digits, symbols, and spaces (printable ASCII).- The solution should run in
O(n)time. - Extra space should be
O(min(n, m)), wheremis the size of the character set (at most 128).
Examples
Example 1
Input: longest_distinct_run('abcabcbb')
Output: 3
Example 2
Input: longest_distinct_run('bbbbb')
Output: 1
Example 3
Input: longest_distinct_run('pwwkew')
Output: 3
Example 4
Input: longest_distinct_run('')
Output: 0
Hints
Hint 1
Think of a window over the string that you grow one character at a time on the right. What must stay true about the characters inside it?
Hint 2
Store, for each character, the last index at which you saw it. When the new character was already seen inside the current window, the window's left edge must move to just after that earlier position.
Hint 3
Be careful with stale entries: a character's recorded index may lie before the window's left edge, in which case it must not move the left edge. The left edge should never move backward (try `"abba"`).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Maintain a window [left, right] that always contains distinct characters. Walk right across the string one position at a time. A dictionary last_seen records the most recent index of each character.
When text[right] was last seen at an index that is inside the current window (that index is at least left), the window would contain a duplicate. Move left to one past that earlier index, which removes the duplicate in a single jump. Otherwise left stays where it is. Then record the new index for the character and update the best length with right - left + 1.
The check last_seen[ch] >= left matters because the dictionary is never cleared and can hold indices that are already outside the window. Without the check, left could move backward. For "abba", at the final 'a' the stored index is 0 but left is already 2, so the window must not shrink back to start at 1.
Why it is correct
Invariant: after processing index right, text[left..right] has no duplicates and left is the smallest start with that property.
- If the new character does not occur in the window, extending the window keeps it valid, and
leftcannot be smaller because earlier characters were excluded because of some other duplicate. - If it does occur in the window, it occurs exactly once there (the window was duplicate-free), at
last_seen[ch]. Any valid window ending atrightmust start after that index, and starting there is sufficient.
Every substring ends at some index, and for each index we compute the longest valid substring ending there, so the maximum over all indices is the answer.
Complexity
- Time:
O(n), sincerightvisits each index once and each step does constant dictionary work. - Space:
O(min(n, m)), one dictionary entry per distinct character.
Edge cases
- Empty string: the loop does not run and the result is
0. - All identical characters: the window shrinks to size 1 each step, result
1. - All distinct characters:
leftstays at 0, resultlen(text).
Solution
def longest_distinct_run(text: str) -> int:
last_seen = {}
left = 0
best = 0
for right, ch in enumerate(text):
if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1
last_seen[ch] = right
best = max(best, right - left + 1)
return best