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:

  • substring is a contiguous substring of s in which every character (Unicode code point) appears at most once.
  • length equals len(substring) and is the largest length achievable across all repeat-free substrings of s.
  • If s is 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^5
  • s may 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

  1. Understand contiguity, ties, and Unicode

    Given an input string s, we need [length, substring] for the longest substring (a contiguous slice s[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 Python str already indexes by Unicode code point (a character's numeric ID), so accented characters like 'é' in 'résumé' and emoji like '😀' act as single characters in len(s), s[i], and dictionary keys.

  2. Start with brute force and spot the wasted work

    A direct nested loop tries every starting index i, expands j rightward while a set checks 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 best
    

    When s has n distinct characters, the inner loop runs n + (n - 1) + ... + 1 = O(n²) iterations — roughly 5 * 10^9 steps for n = 10^5. Notice why shifting i one 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 ch repeats an earlier copy at index prev, every window starting at or before prev and reaching right still contains both copies of ch. We can jump the start directly to prev + 1 and keep the characters already in between!

  3. Key idea: sliding window and loop-invariant proof

    Maintain a sliding window s[left : right + 1] as right steps from 0 to len(s) - 1. At the end of each iteration right, we enforce one loop invariant (a condition guaranteed to hold after every step):

    left is the smallest starting index for which s[left : right + 1] has no repeated characters.

    Why does this single invariant prove correctness? 1. Every contiguous substring of s ends at some index right (0 <= right < len(s)). 2. Among all repeat-free substrings ending at right, the longest one begins at the smallest valid start — namely left. 3. Taking the maximum of right - left + 1 over every right checks the longest valid candidate for every ending position, so it is guaranteed to find the global maximum.

    When right advances by 1 to inspect ch = s[right]: - left can never move left of its current position (otherwise an earlier duplicate would re-enter the window). - If ch appeared before at prev, left must also sit at least at prev + 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")
    
  4. Avoid the stale-index trap with `last_seen`

    We store each character's latest index in a hash dictionary last_seen for O(1) average-time lookups.

    Watch out for characters whose previous occurrence already lies to the left of left! Look at index 4 ('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: enforces max(left, prev + 1) so left only moves forward. Be sure to test last_seen[ch] before updating last_seen[ch] = right.

  5. Save indices during the scan and slice once

    Slicing s[left : right + 1] inside the loop whenever best_len grows would copy 1 + 2 + ... + n = O(n²) characters on an all-unique input. Instead, record two integers best_start and best_len during the scan and perform a single O(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]]
    
  6. 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 and s[0:0] evaluates to '', returning [0, ''] cleanly.

  7. 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 the n loop iterations performs one O(1) average-time dictionary lookup, one O(1) dictionary write, and constant-time index math, followed by a single final slice of best_len <= k <= n characters.
  • Space: O(k). last_seen stores one integer index per distinct character (k keys), and the returned substring has length at most k.

Edge cases

  • Empty input (""): best_start and best_len remain 0, the loop runs zero times, and s[0:0] returns [0, ""].
  • All identical characters ("mmmm"): Every step after index 0 sees last_seen['m'] == right - 1 >= left and shifts left to right, returning [1, "m"].
  • All distinct characters ("abcdef"): left stays at 0 throughout, returning [6, "abcdef"].
  • Stale earlier duplicates ("xyyzxvwz", "abba"): In "xyyzxvwz", when right = 4 ('x'), last_seen['x'] is 0, which sits left of left = 2. Checking last_seen[ch] >= left keeps left from 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 via unicodedata.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] + 1 without checking >= left: On "xyyzxvwz" or "abba", seeing an old character whose previous index is < left pulls left backward over an already evicted duplicate.
  • Writing last_seen[ch] = right before the if check: Overwriting last_seen[ch] first makes last_seen[ch] == right >= left true on every iteration, shrinking every window to length 0.
  • Slicing s[left : right + 1] inside the loop: On a string of all distinct characters, best_len increases n times and copies 1 + 2 + ... + n = O(n²) characters total. Record best_start and best_len and slice once at the end.
  • Resetting left = right on a repeat: On "mnomk", resetting left to 3 when 'm' repeats discards "no" and misses "nomk" (left should jump to 0 + 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 a set; while s[right] is in the set, remove s[left] and advance left by 1. Both left and right move forward at most n times, giving O(n) time without storing indices.
  • Fixed-size array for ASCII: When inputs are restricted to 7-bit ASCII (ord(ch) < 128), a 128-element integer list [-1] * 128 can replace the last_seen hash 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] = [] alongside best_len. When window_len > best_len, set best_len = window_len and best_starts = [left]; when window_len == best_len (and window_len > 0), append left to best_starts. Afterward, build [s[i : i + best_len] for i in best_starts] (and optionally deduplicate with list(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_seen with a frequency map counts: Dict[str, int] over s[left : right + 1]. Increment counts[s[right]] as right advances, and in a while loop shrink from left (decrementing counts[s[left]] and deleting zero-count keys) whenever the constraint is violated — len(counts) > K for at most K distinct characters, or duplicate_pairs > 1 for at most one repeat. Because both pointers still only advance, total runtime stays O(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 k characters (the number of distinct symbols in the alphabet). Maintain only the active window inside a collections.deque (bounded by k elements), store stream-wide integer offsets in last_seen, and materialize a string copy only when window_len > best_len. Because best_len can grow at most k times across the entire stream, snapshotting improvements costs at most O(k²) total work while keeping memory bounded at O(k) regardless of stream length.

Follow-up questions

Similar questions

More Lowe's interview questions

All 3 Lowe's questions →