Find the longest contiguous piece of a string in which every character occurs only once.
Problem
Input. A Python string text.
Output. Return the maximum length of a substring containing no repeated character.
Rules. A substring is contiguous; skipping interior characters is not allowed. Compare exact Python code points, so case and whitespace remain significant. Return only the length and leave the string unchanged. Empty input returns zero.
Example. "abba" returns 2, witnessed by "ab" or "ba".
For "bbbb", return 1; for "", return 0.
Picture: Repair Only the Newly Repeated Character
Problem trace
An old duplicate cannot move the left boundary backward
Reference drawing
Problem trace
An old duplicate cannot move the left boundary backward
Execution trace
- L
- 0
- R
- 0
- range
- empty before reading index 0
- key a
- not shown→0
- range
- empty before reading index 0→[0..0] = "a"
- length
- not shown→0 - 0 + 1 = 1
- key b
- not shown→1
- R
- 0→1
- range
- [0..0] = "a"→[0..1] = "ab"
- key b
- 1→2
- L
- 0→2
- R
- 1→2
- key a
- 0→3
- R
- 2→3
- range
- [2..2] = "b"→[2..3] = "ba"
- Recognize it
- Use it when the answer is a longest contiguous span constrained by uniqueness and a repeated value tells exactly how far the left boundary can safely jump.
- Keep true
- After processing index R, [L..R] has no repeated character; L never moves backward, and best is the maximum length of every valid window ending at or before R.
- Reuse it
- For longest windows repaired by the newest violation, store enough history to jump over the violating occurrence, but clamp the new left boundary so stale history can never move it backward.
The figure’s L, R correspond to left, right in code.
| Read index | Previous occurrence | New left | Window | Best |
|---|---|---|---|---|
| 0: a | Absent | 0 | a | 1 |
| 1: b | Absent | 0 | ab | 2 |
| 2: b | 1, inside | 2 | b | 2 |
| 3: a | 0, outside | 2 | ba | 2 |
Before extension, the window has no duplicates. Only the incoming character can break that property.
Its latest occurrence is the furthest-right conflict; jumping past it also excludes all older copies.
Use max(left, last_seen[char]+1) to retain previous exclusions.
After repair, this is the longest valid suffix ending at right; checking every endpoint finds the global maximum.
Code
def length_of_longest_substring(text: str) -> int:
last_seen: dict[str, int] = {}
left = 0
best = 0
for right, char in enumerate(text):
if char in last_seen:
left = max(left, last_seen[char] + 1)
last_seen[char] = right
best = max(best, right - left + 1)
return best
Expected time is with ordinary map operations; space is for distinct code points seen. The map retains history, not just characters currently inside the window.
Change 1: Return the Text
New task. Return one longest substring; retain the first encountered best on ties.
Picture and change. Save its start only on strict improvement. Copy the winning slice once, after scanning.
Code.
def longest_unique_text(text):
last_seen = {}
left = best_left = best_length = 0
for right, character in enumerate(text):
left = max(left, last_seen.get(character, -1) + 1)
last_seen[character] = right
if right - left + 1 > best_length:
best_left, best_length = left, right - left + 1
return text[best_left:best_left + best_length]
Check. "abba" returns "ab"; empty input returns "". Copying costs the returned length.
Use when. The caller needs a witness, not just a number.
Change 2: Allow At Most a Declared Number of Distinct Characters
New task. Repetitions are allowed, but at most limit distinct characters may occur. Require a nonnegative integer limit.
Picture and change. Count the current window. Remove from the left until its positive-count keys fit.
Code.
def longest_k_distinct(text, limit):
counts = {}
left = best = 0
for right, character in enumerate(text):
counts[character] = counts.get(character, 0) + 1
while len(counts) > limit:
outgoing = text[left]
counts[outgoing] -= 1
if counts[outgoing] == 0:
del counts[outgoing]
left += 1
best = max(best, right - left + 1)
return best
Check. ("eceba", 2) gives 3 from "ece"; ("abc", 0) gives 0.
Use when. Validity counts distinct values instead of forbidding repeats.
Failure: A Backward Jump
Without max, the final a in "abba" moves left back to 1, admitting invalid "bba" and reporting 3.
Transfer Check
Must entries left of the window be deleted?
Reasoned Answer
No. The clamp makes stale history harmless; each saved index still identifies the latest occurrence.
Preserve the Validity Rule, Not Just the Loop Shape
Update last_seen only after using its previous value to repair the boundary.
Saving right first would make the incoming character conflict with itself.
The distinct-count variant needs actual current counts, including deletion when a count reaches zero.
Otherwise len(counts) would include characters no longer in the window.
Each endpoint moves only forward, so total shrinking work is linear despite the nested loop.
Its state holds at most limit+1 keys during insertion, subject to the available alphabet.
These are expected hash-cost bounds, not worst-case guarantees against every hash behavior.
A subsequence need not be contiguous and requires a different contract. Code-point uniqueness also differs from uniqueness of visible grapheme clusters; normalization and segmentation would be explicit task changes.