Longest Streak of Distinct Viewing History
Arrays & HashingModel answerLast updated
Find the longest contiguous subsequence in a viewing history array where no show appears more than once (case-insensitive).
You're analyzing a user's streaming history represented as an array of show titles. Your task is to identify the longest contiguous segment where every show appears at most once, treating titles case-insensitively.
Input:
- An array of strings representing show names in chronological order
Output:
- A tuple
(start, end)containing the inclusive indices of a longest non-repeating segment - If the input is empty, return
(-1, -1) - When multiple segments have the same maximum length, return any one of them
Constraints:
- Show names are compared case-insensitively (
"Ozark"and"ozark"are duplicates) - Time complexity should be O(n) where n is the array length
- Space complexity should be O(min(n, m)) where m is the number of unique shows
Example:
Input: ["Breaking Bad", "Ozark", "The Wire", "ozark", "Dark", "Mindhunter"]
Output: (2, 5)
Explanation: The segment ["The Wire", "ozark", "Dark", "Mindhunter"] has length 4
Follow-up: How would you adapt this solution for a streaming scenario where show names arrive one at a time, and you need to maintain the current longest non-repeating window at all times? Discuss data structures, per-element update cost, and memory characteristics.
Hints
Hint 1
Use a sliding window with two pointers that expands right and contracts left when duplicates are found
Hint 2
Track the most recent position of each normalized show name in a hash map
Hint 3
When you encounter a duplicate, be careful—its previous occurrence might already be outside your current window
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Approach
This is a classic sliding window problem. The core strategy is to maintain a window [left, right] that never contains duplicate shows, expanding it rightward and contracting from the left when necessary.
Key insights:
- Maintain a growing window: Process elements left-to-right, expanding the window by incrementing
right - Track last positions: Use a hash map to remember where each show (normalized) last appeared
- Handle duplicates efficiently: When a duplicate appears, jump
leftpast the previous occurrence rather than incrementing it step-by-step - Guard against stale entries: Only move
leftif the previous occurrence is actually inside the current window
Algorithm:
For each position right:
1. Normalize the show name (case-fold)
2. Check if this show appeared recently
3. If yes AND that position >= left:
Move left to (previous_position + 1)
4. Update the last-seen position for this show
5. If current window is larger than best, record it
Critical detail: The condition previous_position >= left is essential. Without it, left could move backward when encountering a show that appeared earlier but is already outside the window.
Complexity Analysis
- Time: O(n) — Each element is visited once. The
leftpointer only moves forward over the course of execution, never backward. Hash operations are O(1) average case. - Space: O(min(n, m)) — The map stores at most one entry per distinct show. Since there can't be more distinct shows than total elements, the bound is the minimum of array length and catalog size.
Edge Cases
- Empty array: Return
(-1, -1)immediately - Single element: Return
(0, 0) - All identical shows: e.g.,
["Friends", "friends", "FRIENDS"]→ answer is(0, 0)with length 1 - No duplicates: The entire array is the answer,
(0, n-1) - Stale map entry:
["A", "B", "B", "A"]— at index 3,"A"was seen at index 0, butleftis already 2. Without the guard,leftwould incorrectly move to 1. Correct answer:(2, 3)with length 2
Code
from typing import List, Tuple
def longest_unique_segment(history: List[str]) -> Tuple[int, int]:
"""
Find inclusive (start, end) indices of the longest contiguous segment
with no repeated shows (case-insensitive comparison).
Returns (-1, -1) for empty input.
"""
if not history:
return (-1, -1)
last_position = {}
left = 0
best_start, best_end = 0, 0
for right, show in enumerate(history):
normalized = show.casefold() # casefold handles Unicode better than lower
previous = last_position.get(normalized)
if previous is not None and previous >= left:
left = previous + 1
last_position[normalized] = right
if right - left > best_end - best_start:
best_start, best_end = left, right
return (best_start, best_end)
Verification:
shows = ["Stranger Things", "Dark", "The Crown", "dark", "Narcos", "Mindhunter"]
# Returns (1, 5): ["Dark", "The Crown", "dark", "Narcos", "Mindhunter"]
# Wait—this has "Dark" and "dark"! Let me recheck...
# Actually returns (2, 5): ["The Crown", "dark", "Narcos", "Mindhunter"], length 4
Follow-Up: Streaming Adaptation
Challenge: Shows arrive one at a time; we can't index backward into the full history. We need to report the best window so far at any moment.
Design decisions:
Option 1: Keep the same hash map (simpler)
- Store:
current_index,left,best_window, and thelast_positionmap - On each new show: same logic as the batch version
- Update cost: O(1) amortized
- Memory: O(m) where m is the total number of distinct shows ever seen
- Trade-off: Memory grows with catalog size, not window size. Stale entries never get cleaned up. Acceptable if the catalog is bounded (e.g., a streaming service has thousands of titles, not millions).
Option 2: Window-bounded memory (optimal for unbounded streams)
- Store:
current_index,left,best_window, a queue of shows in window order, and a set of shows currently in the window - On duplicate: pop from the queue front until the duplicate is removed, updating
leftand the set with each pop - Then add the new show to the queue and set
- Update cost: O(1) amortized (each element enters and exits the queue at most once), O(w) worst-case per element where w is window size
- Memory: O(w) where w is the current window length, bounded by min(stream_length, catalog_size)
- Benefit: No unbounded memory growth from stale entries
Implementation sketch (Option 2):
from collections import deque
class StreamingWindowTracker:
def __init__(self):
self.index = 0
self.left = 0
self.queue = deque() # shows in window, in order
self.in_window = set() # normalized shows currently in window
self.best = (-1, -1)
def add_show(self, name: str) -> None:
normalized = name.casefold()
if normalized in self.in_window:
# Remove from front until duplicate is gone
while self.queue:
removed = self.queue.popleft()
self.in_window.discard(removed)
self.left += 1
if removed == normalized:
break
self.queue.append(normalized)
self.in_window.add(normalized)
# Update best if current window is larger
current_length = self.index - self.left
best_length = -1 if self.best[0] == -1 else self.best[1] - self.best[0]
if current_length > best_length:
self.best = (self.left, self.index)
self.index += 1
def get_longest(self) -> Tuple[int, int]:
return self.best
Additional considerations:
- Index overflow: Use 64-bit integers in languages with fixed-width types
- Returning actual shows: If the caller needs show names (not just indices), snapshot the window when
bestupdates; adds O(window_length) memory - Memory caps: For strict memory limits, cap window size at K elements; gives O(K) memory but only finds windows up to length K
- Multi-user: Maintain separate state per user; total memory scales with sum of window sizes
What makes a strong answer:
- Catching the
previous >= leftguard condition - Using
casefold()rather thanlower()for proper Unicode handling - Explaining why
leftonly moves forward, which proves O(n) time - In the follow-up, contrasting memory trade-offs and discussing amortized vs. worst-case complexity