Longest Run With No Repeated Character
StringsAuto-graded · 27 test casesLast updated
Find the length of the longest contiguous block of a string with no repeated character, using a linear-time sliding window with exact, case-sensitive comparison.
You are given a string text. Find the largest possible length of a contiguous piece of text in which no character occurs more than once.
A piece is contiguous if it consists of neighbouring characters taken in their original order. Selecting characters that are not adjacent in text does not count. The empty piece is allowed, so an empty text gives the answer 0.
Details
- Characters are compared exactly as they appear. An uppercase letter and its lowercase version are two different characters.
- Spaces, digits and punctuation marks are ordinary characters and may repeat just like letters.
- Several different pieces may reach the maximum length. Only that length is required.
Function
Implement longest_unique_run(text), which returns a single integer: the length of the longest repeat-free contiguous piece of text.
Constraints
0 <= len(text) <= 50000- Every character of
textis printable ASCII (codes 32 through 126), including the space. - Since only 95 distinct characters exist, the answer is at most
min(len(text), 95).
Examples
Example 1
Input: longest_unique_run('streets')
Output: 4
Example 2
Input: longest_unique_run('aAbBa')
Output: 4
Example 3
Input: longest_unique_run('')
Output: 0
Hints
Hint 1
Start with brute force: test every substring for repeats. Then ask why that wastes work when two neighbouring substrings overlap almost entirely.
Hint 2
Maintain a window [left, i] that is always repeat-free. When you add text[i], the only possible conflict is an earlier copy of that same character.
Hint 3
Store the most recent index of each character. If that index lies inside the current window, move left to just past it; if it lies before left, ignore it, since otherwise left could move backwards (try "abba").
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Checking every substring is O(n^2) substrings (or O(n^3) with rescanning), which is too slow for 50,000 characters. Instead, use a sliding window [start, i] that is always free of repeats.
For each position i, adding text[i] to a repeat-free window can only create one kind of conflict: an earlier copy of text[i]. So we track, in a dictionary, the latest index at which each character appeared. When we read text[i]:
- Look up
prev, the last index of this character (or-1if unseen). - If
prev >= start, the earlier copy is inside the window, so setstart = prev + 1. - Record
last_seen[text[i]] = i. - The window
[start, i]is now repeat-free; update the best length withi - start + 1.
Why it is correct
Invariant: after handling index i, the window [start, i] has no repeated character and start is the smallest index with that property.
If the previous window [start, i-1] was repeat-free and minimal, then a window ending at i is invalid exactly when it contains the most recent earlier copy of text[i] (at prev). Hence the smallest valid start is max(start, prev + 1). The check prev >= start is what makes this a maximum: without it, a stale index from outside the window could pull start backwards (for "abba", the final a would wrongly give 3 instead of 2).
The best repeat-free substring ends at some index, and for that index our window is the longest valid one ending there. Taking the maximum over all i therefore gives the global answer. Characters are dictionary keys as-is, so a and A are distinct, and the empty string never enters the loop, returning 0.
Complexity
- Time: O(n), one pass with constant-time dictionary operations;
startonly moves forward. - Space: O(min(n, 95)), effectively O(1) because the alphabet is bounded.
Reference solution
def longest_unique_run(text: str) -> int:
last_seen = {} # character -> index of its latest occurrence
start = 0 # left edge of the current repeat-free window
best = 0
for i, ch in enumerate(text):
prev = last_seen.get(ch, -1)
# Only shift the window if the earlier copy is inside it.
if prev >= start:
start = prev + 1
last_seen[ch] = i
length = i - start + 1
if length > best:
best = length
return best