Longest Unique Sequence of Media Titles
StringsAuto-graded · 21 test casesLast updated
Find the maximum length of a contiguous subsequence of string titles containing no duplicated elements using a dynamic sliding window approach.
Given a list of strings shows representing a sequence of media titles, determine the length of the longest contiguous sublist that contains no duplicate titles.
Constraints
0 <= len(shows) <= 10^5- Each element in
showsis a non-empty string consisting of printable ASCII characters. - String matching is exact (case-sensitive).
Examples
Example 1
Input: longest_unique_sequence(['A', 'B', 'C', 'A', 'B', 'D'])
Output: 4
Example 2
Input: longest_unique_sequence(['p', 'w', 'w', 'k', 'e', 'w'])
Output: 3
Example 3
Input: longest_unique_sequence(['x', 'y', 'z'])
Output: 3
Hints
Hint 1
Consider using a sliding window bounded by a start pointer and an end pointer to maintain a contiguous sublist.
Hint 2
To achieve linear time complexity, use a hash map to record the most recent index where each item appeared.
Hint 3
When you encounter an item already seen, check if its last reported position is within your current window before moving the start pointer.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We can solve this problem efficiently using a sliding window technique optimized with a hash map.
- Maintain two pointers:
leftrepresenting the start index of the current window without duplicates, andrightiterating from index0to the end of the list. - Use a hash dictionary
last_positionto store the most recent index where each show title was seen. - As
rightiterates throughshows:- If the current show is already in
last_positionand its recorded index is at or afterleft, a duplicate exists within our current window. Adjustlefttolast_position[show] + 1to exclude the previous instance. - Update
last_position[show] = right. - Update our maximum length record with
right - left + 1.
- If the current show is already in
Crucially, checking last_position[show] >= left ensures we ignore stale indices that fall outside our current active window.
Complexity
- Time Complexity: $O(N)$ where $N$ is the length of
shows. We perform a single pass across the array, doing $O(1)$ expected time lookups and updates per element (assuming average constant-time string hashing). - Space Complexity: $O(U)$ where $U$ is the number of unique show titles in the input array, required to store entries in the hash map.
from typing import List
def longest_unique_sequence(shows: List[str]) -> int:
last_position = {}
left = 0
max_length = 0
for right, show in enumerate(shows):
if show in last_position and last_position[show] >= left:
left = last_position[show] + 1
last_position[show] = right
max_length = max(max_length, right - left + 1)
return max_length