Longest Distinct Substring and First Non-Repeating Index

Easy · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Write a function analyze_string(s) that inspects a string s of lowercase English letters and returns a two-element tuple (max_unique_length, first_unique_index) summarizing two independent metrics:

  1. max_unique_length: The maximum length among all contiguous substrings of s in which every character is distinct (0 when s is empty).
  2. first_unique_index: The 0-based position of the leftmost character in s that appears only once across the entire string s, or -1 if no character has total frequency 1 (including when s is empty).
def analyze_string(s: str) -> Tuple[int, int]:
    ...

Examples

Example 1

Input:  s = "cadbcbad"
Output: (4, -1)

Explanation: Both "cadb" (s[0:4]) and "bcad" (s[4:8]) have 4 distinct characters, while any slice of length 5 repeats at least one letter, so max_unique_length = 4. Across the full string, 'c', 'a', 'd', and 'b' each occur twice, giving first_unique_index = -1.

Example 2

Input:  s = "abacbd"
Output: (4, 3)

Explanation: The longest duplicate-free contiguous slice is "acbd" (s[2:6], length 4). Full-string frequencies are 'a': 2, 'b': 2, 'c': 1, and 'd': 1; the earliest character with frequency 1 is 'c' at index 3.

Constraints

  • 0 <= len(s) <= 10^5
  • s contains only lowercase English letters ('a' through 'z')

Step-by-step walkthrough

  1. Split into two independent string tasks

    Given a string s of length 0 to 10^5, we need to return a tuple (max_unique_length, first_unique_index) answering two separate questions:

    1. Longest unique substring: the maximum length of a substring (a contiguous slice s[left : right + 1] with no skipped positions) in which no character appears twice.
    2. First non-repeating character: the 0-based index of the earliest character in s whose total count across the entire string is 1 (or -1 if every character repeats, or if s is empty).

    Because the two questions do not depend on each other, writing one clean helper function for each keeps the code easy to read and test.

  2. Why brute force gets slow on 100,000 characters

    • For Task 1, testing every possible (left, right) slice checks O(n^2) substrings (up to 5 billion slices when n = 10^5).
    • For Task 2, calling s.count(s[i]) at every index i scans the whole 10^5-character string up to 10^5 times — another O(n^2) loop (10 billion character comparisons).

    We can solve both tasks in O(n) linear time using a sliding window for Task 1 and a two-pass frequency dictionary for Task 2.

  3. Task 1: slide a duplicate-free window with last-seen indices

    Maintain a contiguous window s[left : right + 1] that never contains duplicate characters, expanding right one character at a time from 0 to len(s) - 1:

    • Store last_seen[ch], the most recent index where each character ch appeared.
    • When s[right] is a character ch that already sits inside the current window (last_seen[ch] >= left), any window containing both last_seen[ch] and right has a duplicate! So the earliest valid start for a window ending at right is right after that previous copy: left = last_seen[ch] + 1.

    Why is the last_seen[ch] >= left check so important? Trace s = "abba" carefully:

    Indices:   0  1  2  3
    String:    a  b  b  a
    
    right = 0 ('a'): window [0..0] = "a",  last_seen = {'a': 0}
    right = 1 ('b'): window [0..1] = "ab", last_seen = {'a': 0, 'b': 1}
    right = 2 ('b'): 'b' seen at 1 >= left(0) -> left jumps to 1 + 1 = 2!
                     window [2..2] = "b",  last_seen = {'a': 0, 'b': 2}
    right = 3 ('a'): 'a' was last seen at 0, which is ALREADY < left(2) (outside the window)!
                     Keep left = 2 -> window [2..3] = "ba" (length 2).
                     (Without >= left, left would jump BACKWARD to 0 + 1 = 1 -> "bba", a bug!)
    
  4. Code longest_unique_substring

    Each character is visited once by right, and each dictionary lookup and update is O(1), giving O(n) time:

    from typing import Dict
    
    
    def longest_unique_substring(s: str) -> int:
        # last_seen: maps each character to the latest index where it appeared (e.g. {'a': 0, 'b': 2})
        last_seen: Dict[str, int] = {}
        # left: inclusive start index of the active duplicate-free window s[left : right + 1]
        left = 0
        best_length = 0
    
        for right, ch in enumerate(s):
            # Only jump `left` forward if the previous copy of `ch` sits INSIDE the current window (>= left).
            # An older copy with index < left is already excluded; jumping to it would move `left` backward!
            if ch in last_seen and last_seen[ch] >= left:
                left = last_seen[ch] + 1
    
            last_seen[ch] = right
            # Both endpoints `left` and `right` are inclusive, so the window holds right - left + 1 characters.
            window_length = right - left + 1
            if window_length > best_length:
                best_length = window_length
    
        return best_length
    
  5. Task 2: count all characters first, then scan left to right

    Can we tell whether s[0] is non-repeating before reading the end of s? No — in "abca", 'a' at index 0 looks unique until the very last character!

    So we split Task 2 into two simple O(n) passes:

    1. Count pass: build char_counts[ch] over the entire string s.
    2. Index pass: walk enumerate(s) from left to right and return the first idx with char_counts[ch] == 1 (or -1 if the loop finishes).
    from typing import Dict
    
    
    def first_unique_index(s: str) -> int:
        # Phase 1: build char_counts mapping each character to its total count across the whole string.
        char_counts: Dict[str, int] = {}
        for ch in s:
            char_counts[ch] = char_counts.get(ch, 0) + 1
    
        # Phase 2: scan `s` from left to right so we return the earliest index whose character has count 1.
        for idx, ch in enumerate(s):
            if char_counts[ch] == 1:
                return idx
    
        return -1
    
  6. Trace Example 2 ("abacbd") step by step

    Let's trace s = "abacbd" (a0 b1 a2 c3 b4 d5):

    Task 1 — Sliding window trace:
      right  ch  prev in window?      left  window s[left..right]  window_length  best_length
      -----  --  -------------------  ----  ---------------------  -------------  -----------
        0    a   no                    0    "a"                          1             1
        1    b   no                    0    "ab"                         2             2
        2    a   yes (at 0 >= 0)       1    "ba"                         2             2
        3    c   no                    1    "bac"                        3             3
        4    b   yes (at 1 >= 1)       2    "acb"                        3             3
        5    d   no                    2    "acbd"                       4             4
    
    Task 2 — Frequency trace:
      char_counts = {'a': 2, 'b': 2, 'c': 1, 'd': 1}
      idx = 0 ('a'): count 2 -> skip
      idx = 1 ('b'): count 2 -> skip
      idx = 2 ('a'): count 2 -> skip
      idx = 3 ('c'): count 1 -> return 3!
    

    Combining the two results returns (4, 3).

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def longest_unique_substring(s: str) -> int:
        # last_seen: maps each character to the latest index where it appeared (e.g. {'a': 0, 'b': 2})
        last_seen: Dict[str, int] = {}
        # left: inclusive start index of the active duplicate-free window s[left : right + 1]
        left = 0
        best_length = 0
    
        for right, ch in enumerate(s):
            # Only jump `left` forward if the previous copy of `ch` sits INSIDE the current window (>= left).
            # An older copy with index < left is already excluded; jumping to it would move `left` backward!
            if ch in last_seen and last_seen[ch] >= left:
                left = last_seen[ch] + 1
    
            last_seen[ch] = right
            # Both endpoints `left` and `right` are inclusive, so the window holds right - left + 1 characters.
            window_length = right - left + 1
            if window_length > best_length:
                best_length = window_length
    
        return best_length
    
    
    def first_unique_index(s: str) -> int:
        # Phase 1: build char_counts mapping each character to its total count across the whole string.
        char_counts: Dict[str, int] = {}
        for ch in s:
            char_counts[ch] = char_counts.get(ch, 0) + 1
    
        # Phase 2: scan `s` from left to right so we return the earliest index whose character has count 1.
        for idx, ch in enumerate(s):
            if char_counts[ch] == 1:
                return idx
    
        return -1
    
    
    def analyze_string(s: str) -> Tuple[int, int]:
        # Solve the two independent string queries with dedicated linear-time helpers.
        max_unique_length = longest_unique_substring(s)
        first_non_repeating = first_unique_index(s)
        return (max_unique_length, first_non_repeating)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture two everyday tasks on a row of letter tiles: for Task 1, stretch an adjustable frame across consecutive tiles as far right as possible, and whenever the newly added tile matches a tile already inside the frame, slide the left edge of the frame just past that earlier twin; for Task 2, tally how many times each letter appears across the entire row first, then walk from left to right to spot the first tile with a tally of 1. Task 1 looks for the longest duplicate-free substring (a contiguous slice of characters with no gaps) using a sliding window (two pointers left and right bounding an active slice that moves forward across the string), while Task 2 uses a frequency map (a dictionary mapping each character to how many times it occurs).

Naive approaches check every (left, right) substring or call s.count(s[i]) at each index i, both of which take O(n^2) time — billions of operations when len(s) = 100,000. Trying to answer Task 2 on the fly in a single naive pass also fails (in "abca", 'a' at index 0 appears unique until the very last character reveals a duplicate), and resetting the whole window on a duplicate in Task 1 fails on "dvdf" (throwing away 'v' when the second 'd' arrives gives "df" of length 2 instead of "vdf" of length 3).

Walk through Example 2 (s = "abacbd", 6 characters):

  1. Sliding window: right = 0 ('a') -> "a" (len 1); right = 1 ('b') -> "ab" (len 2); right = 2 ('a') sees 'a' inside the window at 0, moving left to 1 ("ba", len 2); right = 3 ('c') -> "bac" (len 3); right = 4 ('b') sees 'b' at 1 >= 1, moving left to 2 ("acb", len 3); right = 5 ('d') -> "acbd" (len 4, best = 4).
  2. Frequency map: char_counts = {'a': 2, 'b': 2, 'c': 1, 'd': 1}. Scanning s from index 0 skips 'a', 'b', 'a' (all count 2) and stops at index 3 ('c', count 1), returning (4, 3).

Complexity

Let n = len(s) and sigma be the number of distinct characters in the alphabet (sigma <= 26 for lowercase English letters).

  • Time: O(n). longest_unique_substring visits each of the n indices once with O(1) average dictionary lookups, and first_unique_index makes two sequential O(n) passes over s with O(1) dictionary lookups.
  • Space: O(min(n, sigma)), which simplifies to O(1) here. Both last_seen and char_counts hold at most one entry per distinct character — at most 26 keys regardless of how large n grows.

Edge cases

  • Empty string (""): neither loop runs, returning (0, -1).
  • Single character ("z"): longest unique window has length 1 and index 0 has count 1, returning (1, 0).
  • All identical characters ("aaaa"): every duplicate immediately advances left = right, giving (1, -1).
  • All distinct characters ("abcdef"): left stays 0 throughout and index 0 is unique, giving (6, 0).
  • Duplicate outside the current window ("abba"): when the second 'a' arrives at index 3, left is already 2, so checking last_seen['a'] >= left (0 >= 2 is false) stops left from moving backward and returns (2, -1).
  • Only unique character at the very end ("aabbc"): returns (2, 4).

Common mistakes

  • Omitting last_seen[ch] >= left: jumping left = last_seen[ch] + 1 unconditionally moves left backward when ch last appeared before left (causing "abba" to report length 3 for "bba" instead of 2).
  • Clearing the entire window on a duplicate: restarting left = right discards valid distinct characters between the old copy and right (failing on "dvdf").
  • Off-by-one window length (right - left instead of right - left + 1): when left == right == 0, the slice s[0:1] has 1 character, not 0.
  • Confusing substring with subsequence (or distinct character count): len(set(s)) counts distinct letters across the whole string ignoring contiguity — on "abbc", len(set("abbc")) is 3 ('a', 'b', 'c'), whereas "bb" prevents 'a' and 'c' from sharing a duplicate-free slice so the longest unique substring has length 2 ("ab" or "bc").
  • Iterating over an unordered hash map in Task 2: in languages whose hash maps do not preserve insertion order, iterating map keys instead of string indices 0..n-1 can return a later unique character before an earlier one.

Follow-up questions

  • What adjustments are needed if the input contains arbitrary Unicode text instead of ASCII lowercase letters? Because our code already uses hash maps (dict) instead of 26-slot arrays, it handles arbitrary Unicode code points (the numerical IDs Python's str iterates over) with zero changes, keeping O(n) time while space becomes O(min(n, sigma)) for a much larger alphabet sigma. In production, clarify what counts as one "character": "é" can be encoded either as one precomposed code point or as 'e' plus a combining accent (normalize first with unicodedata.normalize("NFC", s)), and multi-code-point emoji require splitting into grapheme clusters (user-perceived characters) before running the exact same algorithm on the list of clusters.
  • How would you maintain the earliest non-repeating character over an unbounded character stream? You cannot wait for the end of an infinite stream, so maintain two small structures as characters arrive: an insertion-ordered dictionary seen_once ({char: first_index}, remembering arrival order) for characters seen once so far, and a repeated set for characters seen two or more times. When ch arrives at stream_index, if ch in seen_once, delete it from seen_once and add it to repeated; else if ch not in repeated, set seen_once[ch] = stream_index. At any instant, the first value in seen_once (next(iter(seen_once.values()), -1)) answers the query in O(1) time using only O(sigma) memory (<= 26 entries for lowercase letters, even after billions of streamed characters).
  • How do the runtime and memory scale, and how can you tighten memory overhead when the character set is fixed to 26 letters? Both helpers run in O(n) time and O(min(n, sigma)) space, which is already O(1) asymptotic space for a fixed 26-letter alphabet. To shrink constant memory overhead and eliminate dictionary hashing, replace last_seen with [-1] * 26 and char_counts with [0] * 26 plus first_idx = [-1] * 26 indexed by ord(ch) - ord('a'): Task 2 then needs only a single pass over s followed by a 26-element loop picking min(first_idx[c] for c in range(26) if char_counts[c] == 1).

Follow-up questions

Similar questions

More Boeing interview questions

All 2 Boeing questions →