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:
max_unique_length: The maximum length among all contiguous substrings ofsin which every character is distinct (0whensis empty).first_unique_index: The0-based position of the leftmost character insthat appears only once across the entire strings, or-1if no character has total frequency1(including whensis 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^5scontains only lowercase English letters ('a'through'z')
Step-by-step walkthrough
Split into two independent string tasks
Given a string
sof length0to10^5, we need to return a tuple(max_unique_length, first_unique_index)answering two separate questions:- 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. - First non-repeating character: the
0-based index of the earliest character inswhose total count across the entire string is1(or-1if every character repeats, or ifsis 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.
- Longest unique substring: the maximum length of a substring (a contiguous slice
Why brute force gets slow on 100,000 characters
- For Task 1, testing every possible
(left, right)slice checksO(n^2)substrings (up to5 billionslices whenn = 10^5). - For Task 2, calling
s.count(s[i])at every indexiscans the whole10^5-character string up to10^5times — anotherO(n^2)loop (10 billioncharacter 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.- For Task 1, testing every possible
Task 1: slide a duplicate-free window with last-seen indices
Maintain a contiguous window
s[left : right + 1]that never contains duplicate characters, expandingrightone character at a time from0tolen(s) - 1:- Store
last_seen[ch], the most recent index where each characterchappeared. - When
s[right]is a characterchthat already sits inside the current window (last_seen[ch] >= left), any window containing bothlast_seen[ch]andrighthas a duplicate! So the earliest valid start for a window ending atrightis right after that previous copy:left = last_seen[ch] + 1.
Why is the
last_seen[ch] >= leftcheck so important? Traces = "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!)- Store
Code longest_unique_substring
Each character is visited once by
right, and each dictionary lookup and update isO(1), givingO(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_lengthTask 2: count all characters first, then scan left to right
Can we tell whether
s[0]is non-repeating before reading the end ofs? No — in"abca",'a'at index0looks unique until the very last character!So we split Task 2 into two simple
O(n)passes:- Count pass: build
char_counts[ch]over the entire strings. - Index pass: walk
enumerate(s)from left to right and return the firstidxwithchar_counts[ch] == 1(or-1if 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- Count pass: build
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).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):
- Sliding window:
right = 0 ('a')->"a"(len 1);right = 1 ('b')->"ab"(len 2);right = 2 ('a')sees'a'inside the window at0, movingleftto1("ba",len 2);right = 3 ('c')->"bac"(len 3);right = 4 ('b')sees'b'at1 >= 1, movingleftto2("acb",len 3);right = 5 ('d')->"acbd"(len 4,best = 4). - Frequency map:
char_counts = {'a': 2, 'b': 2, 'c': 1, 'd': 1}. Scanningsfrom index0skips'a','b','a'(all count2) and stops at index3('c', count1), 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_substringvisits each of thenindices once withO(1)average dictionary lookups, andfirst_unique_indexmakes two sequentialO(n)passes overswithO(1)dictionary lookups. - Space:
O(min(n, sigma)), which simplifies toO(1)here. Bothlast_seenandchar_countshold at most one entry per distinct character — at most26keys regardless of how largengrows.
Edge cases
- Empty string (
""): neither loop runs, returning(0, -1). - Single character (
"z"): longest unique window has length1and index0has count1, returning(1, 0). - All identical characters (
"aaaa"): every duplicate immediately advancesleft = right, giving(1, -1). - All distinct characters (
"abcdef"):leftstays0throughout and index0is unique, giving(6, 0). - Duplicate outside the current window (
"abba"): when the second'a'arrives at index3,leftis already2, so checkinglast_seen['a'] >= left(0 >= 2is false) stopsleftfrom moving backward and returns(2, -1). - Only unique character at the very end (
"aabbc"): returns(2, 4).
Common mistakes
- Omitting
last_seen[ch] >= left: jumpingleft = last_seen[ch] + 1unconditionally movesleftbackward whenchlast appeared beforeleft(causing"abba"to report length3for"bba"instead of2). - Clearing the entire window on a duplicate: restarting
left = rightdiscards valid distinct characters between the old copy andright(failing on"dvdf"). - Off-by-one window length (
right - leftinstead ofright - left + 1): whenleft == right == 0, the slices[0:1]has1character, not0. - 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"))is3('a','b','c'), whereas"bb"prevents'a'and'c'from sharing a duplicate-free slice so the longest unique substring has length2("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-1can 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 of26-slot arrays, it handles arbitrary Unicode code points (the numerical IDs Python'sstriterates over) with zero changes, keepingO(n)time while space becomesO(min(n, sigma))for a much larger alphabetsigma. 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 withunicodedata.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 arepeatedset for characters seen two or more times. Whencharrives atstream_index, ifch in seen_once, delete it fromseen_onceand add it torepeated; else ifch not in repeated, setseen_once[ch] = stream_index. At any instant, the first value inseen_once(next(iter(seen_once.values()), -1)) answers the query inO(1)time using onlyO(sigma)memory (<= 26entries 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 andO(min(n, sigma))space, which is alreadyO(1)asymptotic space for a fixed26-letter alphabet. To shrink constant memory overhead and eliminate dictionary hashing, replacelast_seenwith[-1] * 26andchar_countswith[0] * 26plusfirst_idx = [-1] * 26indexed byord(ch) - ord('a'): Task 2 then needs only a single pass oversfollowed by a26-element loop pickingmin(first_idx[c] for c in range(26) if char_counts[c] == 1).
Follow-up questions
- What adjustments are needed if the input contains arbitrary Unicode text instead of ASCII lowercase letters?
- How would you maintain the earliest non-repeating character over an unbounded character stream?
- How do the runtime and memory scale, and how can you tighten memory overhead when the character set is fixed to 26 letters?
Similar questions
- Secure Browser-to-S3 Uploads, TypeScript Structural Typing, and Async React Effects
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One