Longest Repeat-Free Substring
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement a function that inspects an input string s and finds the longest contiguous slice (s[i:j]) whose characters are all distinct:
def longest_unique_substring(s: str) -> List[object]:
Return a two-element list [length, substring] where:
substringis a contiguous substring ofsin which every character (Unicode code point) appears at most once.lengthequalslen(substring)and is the largest length achievable across all repeat-free substrings ofs.- If
sis empty (""), return[0, ""]. - If several contiguous substrings share the same maximum length, returning any valid longest substring is accepted (for instance, the earliest one starting at the smallest index).
Characters are matched by exact Unicode code point: uppercase and lowercase letters differ ('a' != 'A'), spaces and punctuation count as ordinary characters, and non-ASCII characters such as accented letters or emoji each count as one code point.
Examples
Example 1
Input: s = "xyyzxvwz"
Output: [5, "yzxvw"]
Indices 2..6 give "yzxvw" with five distinct characters. Note that 'x' at index 4 does not conflict with 'x' at index 0 because the window already moved past index 1 when 'y' repeated at index 2.
Example 2
Input: s = "mmmm"
Output: [1, "m"]
Every adjacent pair repeats 'm', so no repeat-free substring can exceed length 1.
Example 3
Input: s = "mnomk"
Output: [4, "nomk"]
When 'm' repeats at index 3, sliding the window start just past the earlier 'm' at index 0 keeps "nom" intact so 'k' extends it to "nomk" of length 4.
Example 4
Input: s = "résumé"
Output: [5, "résum"]
Each accented 'é' is a single Unicode code point; the first five characters "résum" are all distinct before 'é' repeats at index 5.
Constraints
0 <= len(s) <= 10^5smay contain arbitrary Unicode code points, including ASCII letters, digits, spaces, symbols, accented characters, and emoji.- Target
O(len(s))time complexity.
Step-by-step walkthrough
Understand contiguity, ties, and Unicode
Given an input string
s, we need[length, substring]for the longest substring (a contiguous slices[i:j]with no skipped positions) in which every character appears at most once:'xyyzxvwz'->[5, 'yzxvw']'mnomk'->[4, 'nomk'](contiguity matters:'mnok'skips the second'm', making it a subsequence rather than a substring)''->[0, '']
Two practical details keep our implementation clean: - Tie-breaking: Whenever two windows tie for the maximum length, keeping the leftmost window (by updating our best answer only on strict
>) deterministically returns a valid answer. - Unicode: A Pythonstralready indexes by Unicode code point (a character's numeric ID), so accented characters like'é'in'résumé'and emoji like'😀'act as single characters inlen(s),s[i], and dictionary keys.Start with brute force and spot the wasted work
A direct nested loop tries every starting index
i, expandsjrightward while asetchecks for duplicates, and stops as soon as a character repeats:def brute_longest_len(s: str) -> int: best = 0 for i in range(len(s)): seen = set() for j in range(i, len(s)): if s[j] in seen: break seen.add(s[j]) best = max(best, j - i + 1) return bestWhen
shasndistinct characters, the inner loop runsn + (n - 1) + ... + 1 = O(n²)iterations — roughly5 * 10^9steps forn = 10^5. Notice why shiftingione step at a time wastes work when a character repeats:s = "m n o m k" ^-----^ i = 0 stops at index 3 because 'm' repeats (earlier 'm' was at index 0) ^---^ i = 1 drops the earlier 'm' right away — no need to re-scan 'n' and 'o'!In general, if
chrepeats an earlier copy at indexprev, every window starting at or beforeprevand reachingrightstill contains both copies ofch. We can jump the start directly toprev + 1and keep the characters already in between!Key idea: sliding window and loop-invariant proof
Maintain a sliding window
s[left : right + 1]asrightsteps from0tolen(s) - 1. At the end of each iterationright, we enforce one loop invariant (a condition guaranteed to hold after every step):leftis the smallest starting index for whichs[left : right + 1]has no repeated characters.Why does this single invariant prove correctness? 1. Every contiguous substring of
sends at some indexright(0 <= right < len(s)). 2. Among all repeat-free substrings ending atright, the longest one begins at the smallest valid start — namelyleft. 3. Taking the maximum ofright - left + 1over everyrightchecks the longest valid candidate for every ending position, so it is guaranteed to find the global maximum.When
rightadvances by1to inspectch = s[right]: -leftcan never move left of its current position (otherwise an earlier duplicate would re-enter the window). - Ifchappeared before atprev,leftmust also sit at least atprev + 1.Combining both rules gives
left = max(left, prev + 1):Before reading index 3 ('m'): m n o m k [-------] left = 0, right = 2 ("mno") At index 3 ('m', prev = 0): m n o m k [-------] left jumps to 0 + 1 = 1 ("nom")Avoid the stale-index trap with `last_seen`
We store each character's latest index in a hash dictionary
last_seenforO(1)average-time lookups.Watch out for characters whose previous occurrence already lies to the left of
left! Look at index4('x') in Example 1,s = "xyyzxvwz":Index: 0 1 2 3 4 Chars: x y y z x At right = 2 ('y'): duplicate 'y' at 1 -> left jumps to 2. Window is "y". At right = 4 ('x'): last_seen['x'] is 0, which is BEFORE left = 2! - WRONG: left = last_seen['x'] + 1 = 1 --> moves left BACKWARD to "yyzx" (contains two 'y's!) - RIGHT: ignore last_seen['x'] < left --> left stays 2, window becomes "yzx" (all distinct!)Checking
if ch in last_seen and last_seen[ch] >= left:enforcesmax(left, prev + 1)soleftonly moves forward. Be sure to testlast_seen[ch]before updatinglast_seen[ch] = right.Save indices during the scan and slice once
Slicing
s[left : right + 1]inside the loop wheneverbest_lengrows would copy1 + 2 + ... + n = O(n²)characters on an all-unique input. Instead, record two integersbest_startandbest_lenduring the scan and perform a singleO(best_len)slice at the end.def scan_unique_windows(s: str): last_seen = {} left = 0 best_start = 0 best_len = 0 for right, ch in enumerate(s): if ch in last_seen and last_seen[ch] >= left: left = last_seen[ch] + 1 last_seen[ch] = right window_len = right - left + 1 if window_len > best_len: best_len = window_len best_start = left return [best_len, s[best_start : best_start + best_len]]Trace Example 1 (`'xyyzxvwz'`) step by step
Let's trace
s = 'xyyzxvwz'across all eight indices:right ch last_seen[ch] >= left? left window window_len best (len, sub) ----- -- --------------------------- ---- -------- ---------- --------------- 0 x not seen 0 "x" 1 (1, "x") 1 y not seen 0 "xy" 2 (2, "xy") 2 y yes (1 >= 0) -> left = 2 2 "y" 1 (2, "xy") 3 z not seen 2 "yz" 2 (2, "xy") 4 x no (0 < 2, stale!) 2 "yzx" 3 (3, "yzx") 5 v not seen 2 "yzxv" 4 (4, "yzxv") 6 w not seen 2 "yzxvw" 5 (5, "yzxvw") 7 z yes (3 >= 2) -> left = 4 4 "xvwz" 4 (5, "yzxvw")For
s = '', the loop executes zero iterations ands[0:0]evaluates to'', returning[0, '']cleanly.Complete solution
Here is the complete linear-time implementation:
from typing import Any, Dict, List, Optional, Set, Tuple def longest_unique_substring(s: str) -> List[object]: """Return [length, substring] for the leftmost longest substring with no repeated characters.""" # Maps each character to the most recent index where it appeared, e.g. {'x': 0, 'y': 2}. last_seen: Dict[str, int] = {} # Invariant: s[left : right + 1] is the widest repeat-free window ending at `right`. left = 0 # Store indices during the scan and slice once at the end to avoid O(n^2) string copies. best_start = 0 best_len = 0 # Phase 1: Expand the window one character at a time from left to right. for right, ch in enumerate(s): # Shrink only if the previous copy of `ch` sits INSIDE the current window (>= left); # older copies to the left of `left` (like 'x' at 0 in "xyyzxvwz") are stale and ignored. if ch in last_seen and last_seen[ch] >= left: left = last_seen[ch] + 1 # Record `ch`'s newest index AFTER checking its previous occurrence. last_seen[ch] = right # Strict '>' keeps the first (leftmost) window whenever multiple substrings tie. window_len = right - left + 1 if window_len > best_len: best_len = window_len best_start = left # Phase 2: Extract the winning substring once in O(best_len) time. best_substring = s[best_start : best_start + best_len] return [best_len, best_substring]✅ Submit now — all tests should pass.
Intuition & how it works
Picture sliding an adjustable window frame from left to right over a row of letter tiles so that no two tiles inside the frame ever match. On every step, you move the right edge of the frame one tile further. Whenever the newly revealed tile differs from everything currently inside the frame, the window simply widens; the instant the new tile matches a tile already inside the frame, you jump the left edge right past that earlier matching tile so the duplicate is evicted in a single step.
Why does a naive nested loop fall short? Testing every starting index i and scanning rightward until a character repeats takes O(n²) time when all n characters are distinct, because advancing from i to i + 1 discards everything already verified and re-checks the same distinct letters over and over. Using a sliding window (a contiguous slice s[left : right + 1] whose endpoints never move backward) together with a hash dictionary last_seen that looks up each character's latest index in average O(1) time (constant lookup work regardless of input length) visits every character just once.
Let's trace s = "xyyzxvwz" step by step:
right=0 ('x'): window "x" (left=0, len=1) -> best = [1, "x"]
right=1 ('y'): window "xy" (left=0, len=2) -> best = [2, "xy"]
right=2 ('y'): 'y' was at 1 (>= left=0), jump left to 2 -> window "y" (len=1)
right=3 ('z'): window "yz" (left=2, len=2)
right=4 ('x'): 'x' was at 0 (< left=2, stale!), keep left=2 -> window "yzx" (len=3) -> best = [3, "yzx"]
right=5 ('v'): window "yzxv" (left=2, len=4) -> best = [4, "yzxv"]
right=6 ('w'): window "yzxvw" (left=2, len=5) -> best = [5, "yzxvw"]
right=7 ('z'): 'z' was at 3 (>= left=2), jump left to 4 -> window "xvwz" (len=4)
Final answer: [5, "yzxvw"]
Complexity
Let n be len(s) and k be the number of distinct characters appearing in s (k <= n).
- Time:
O(n). Each of thenloop iterations performs oneO(1)average-time dictionary lookup, oneO(1)dictionary write, and constant-time index math, followed by a single final slice ofbest_len <= k <= ncharacters. - Space:
O(k).last_seenstores one integer index per distinct character (kkeys), and the returned substring has length at mostk.
Edge cases
- Empty input (
""):best_startandbest_lenremain0, the loop runs zero times, ands[0:0]returns[0, ""]. - All identical characters (
"mmmm"): Every step after index0seeslast_seen['m'] == right - 1 >= leftand shiftslefttoright, returning[1, "m"]. - All distinct characters (
"abcdef"):leftstays at0throughout, returning[6, "abcdef"]. - Stale earlier duplicates (
"xyyzxvwz","abba"): In"xyyzxvwz", whenright = 4('x'),last_seen['x']is0, which sits left ofleft = 2. Checkinglast_seen[ch] >= leftkeepsleftfrom moving backward. - Unicode code points vs. grapheme clusters: Python strings index by Unicode code point (a numeric character identifier such as
'é'U+00E9 in"résumé"or'😀'U+1F600), so single-code-point non-ASCII characters work out of the box. If a caller instead defines a "character" as a visual grapheme cluster (for example'e'plus combining acute accent U+0301, or a multi-code-point emoji sequence), normalize first viaunicodedata.normalize("NFC", s)or segment into grapheme clusters and run the identical window scan over that list. - Case sensitivity and spaces:
'a'and'A'have distinct code points, and spaces count as ordinary characters ("a b"->[3, "a b"]).
Common mistakes
- Setting
left = last_seen[ch] + 1without checking>= left: On"xyyzxvwz"or"abba", seeing an old character whose previous index is< leftpullsleftbackward over an already evicted duplicate. - Writing
last_seen[ch] = rightbefore theifcheck: Overwritinglast_seen[ch]first makeslast_seen[ch] == right >= lefttrue on every iteration, shrinking every window to length0. - Slicing
s[left : right + 1]inside the loop: On a string of all distinct characters,best_lenincreasesntimes and copies1 + 2 + ... + n = O(n²)characters total. Recordbest_startandbest_lenand slice once at the end. - Resetting
left = righton a repeat: On"mnomk", resettingleftto3when'm'repeats discards"no"and misses"nomk"(leftshould jump to0 + 1 = 1). - Returning a subsequence instead of a substring: Deduplicating the whole string ignores contiguity (
"mnok"is not a contiguous slice of"mnomk").
Alternative approaches
- Two pointers with a
set: Keep the current window's characters in aset; whiles[right]is in the set, removes[left]and advanceleftby1. Bothleftandrightmove forward at mostntimes, givingO(n)time without storing indices. - Fixed-size array for ASCII: When inputs are restricted to 7-bit ASCII (
ord(ch) < 128), a128-element integer list[-1] * 128can replace thelast_seenhash dictionary for slightly smaller constant factors.
Follow-up questions
- How would you return every substring that ties for the maximum unique length rather than just one? Track
best_starts: List[int] = []alongsidebest_len. Whenwindow_len > best_len, setbest_len = window_lenandbest_starts = [left]; whenwindow_len == best_len(andwindow_len > 0), appendlefttobest_starts. Afterward, build[s[i : i + best_len] for i in best_starts](and optionally deduplicate withlist(dict.fromkeys(...))if identical text appearing at multiple positions, such as'ab'twice in'abab', should only appear once). - How does the sliding window change if the substring may contain at most K distinct characters (or at most one repeated character)? Replace
last_seenwith a frequency mapcounts: Dict[str, int]overs[left : right + 1]. Incrementcounts[s[right]]asrightadvances, and in awhileloop shrink fromleft(decrementingcounts[s[left]]and deleting zero-count keys) whenever the constraint is violated —len(counts) > Kfor at mostKdistinct characters, orduplicate_pairs > 1for at most one repeat. Because both pointers still only advance, total runtime staysO(n). - How would you find the longest repeat-free substring in a multi-gigabyte character stream that cannot fit in RAM? By the pigeonhole principle, no repeat-free window can ever exceed
kcharacters (the number of distinct symbols in the alphabet). Maintain only the active window inside acollections.deque(bounded bykelements), store stream-wide integer offsets inlast_seen, and materialize a string copy only whenwindow_len > best_len. Becausebest_lencan grow at mostktimes across the entire stream, snapshotting improvements costs at mostO(k²)total work while keeping memory bounded atO(k)regardless of stream length.
Follow-up questions
- How would you return every substring that ties for the maximum unique length rather than just one?
- How does the sliding window change if the substring may contain at most K distinct characters (or at most one repeated character)?
- How would you find the longest repeat-free substring in a multi-gigabyte character stream that cannot fit in RAM?
Similar questions
- Python Runtime Internals and Production Engineering Practices
- Cloud Architecture and Operations Fundamentals
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance