Skip to content
mlmentorship

Longest Substring Without Repeating Characters

Find the longest substring with no repeated character.

Published · 13 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Longest Substring Without Repeating Characters

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Keep [L..R] duplicate-free by jumping L past a repeated character that is still inside the window.

Problem trace

An old duplicate cannot move the left boundary backward

Input and goalFind the longest substring with no repeated character.
Initialize the empty historyFor text "abba", start L = 0, best = 0, and inspect R = 0.
LRa0b1b2a3
rangeempty before reading index 0best0
saved stateempty
L
0
R
0
range
empty before reading index 0

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.
For text "abba", start L = 0, best = 0, and inspect R = 0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does the last a leave L at 2 rather than moving it backward to 1?
Full interview answer 13 min read
Reading depth

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

Worked example: an old duplicate cannot move the left boundary backwardThe last repeated a lies before the current window. Moving the boundary back to that old occurrence would bring a duplicate b inside. Keep the boundary where it is; a stale occurrence cannot reopen discarded positions.An old occurrence cannot reopen adiscarded prefixRejected: move the left boundary backto 1a0b1b2a3Keep the left boundary at 2a0b1b2a3Left one reopens both b copies. Lefttwo keeps the unique suffix ba.
Read it this way: The last repeated a lies before the current window. Moving the boundary back to that old occurrence would bring a duplicate b inside. Keep the boundary where it is; a stale occurrence cannot reopen discarded positions. Which repeated character reenters if the final a moves the left boundary backward to one?
Reference drawing

Problem trace

An old duplicate cannot move the left boundary backward

Worked example: an old duplicate cannot move the left boundary backwardThe last repeated a lies before the current window. Moving the boundary back to that old occurrence would bring a duplicate b inside. Keep the boundary where it is; a stale occurrence cannot reopen discarded positions.An old occurrence cannot reopen adiscarded prefixRejected: move the left boundary backto 1a0b1b2a3Keep the left boundary at 2a0b1b2a3Left one reopens both b copies. Lefttwo keeps the unique suffix ba.
Execution trace
Input and goalFind the longest substring with no repeated character.
Initialize the empty historyFor text "abba", start L = 0, best = 0, and inspect R = 0.
LRa0b1b2a3
rangeempty before reading index 0best0
saved stateempty
L
0
R
0
range
empty before reading index 0

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.
For text "abba", start L = 0, best = 0, and inspect R = 0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does the last a leave L at 2 rather than moving it backward to 1?
Read it this way: The last repeated a lies before the current window. Moving the boundary back to that old occurrence would bring a duplicate b inside. Keep the boundary where it is; a stale occurrence cannot reopen discarded positions. Which repeated character reenters if the final a moves the left boundary backward to one?

The figure’s L, R correspond to left, right in code.

Read indexPrevious occurrenceNew leftWindowBest
0: aAbsent0a1
1: bAbsent0ab2
2: b1, inside2b2
3: a0, outside2ba2

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.