Cluster Viewers by Recent Watch Set
Arrays & HashingAuto-graded · 18 test casesLast updated
Tests dictionary grouping, set operations on list suffixes, and canonical key construction for equivalence classes.
You have access to viewing logs for multiple viewers. Each log records the sequence of content IDs a viewer consumed, ordered chronologically from first to most recent.
Your task is to cluster viewers into groups where everyone in a cluster watched the same collection of items in their most recent k views, regardless of the order within those k items.
More formally: extract the last k content IDs from each viewer's history and treat them as a set (duplicates collapse, order doesn't matter). Viewers belong to the same cluster if and only if these sets are identical.
Input
k: a positive integer indicating how many recent items to examine (1 ≤ k ≤ 1000)watch_logs: a dictionary mapping viewer identifiers (strings) to lists of content identifiers (each identifier can be any hashable type: string, integer, etc.). Every list contains at leastkelements.
Output
Return a list of clusters. Each cluster is a list of viewer identifiers. Only include clusters containing two or more viewers. Single-viewer clusters should be omitted.
Constraints
- 1 ≤ k ≤ 1000
- All history lists have length ≥ k
- Content identifiers are hashable
- Viewer identifiers are strings
- At least one viewer is present in the input
Examples
Example 1
Input: cluster_by_recent_watches(3, {'A': ['m1', 'm2', 'm3', 'm4', 'm5'], 'B': ['m7', 'm3', 'm4', 'm5'], 'C': ['m2', 'm3', 'm4', 'm6']})
Output: [['A', 'B']]
Example 2
Input: cluster_by_recent_watches(2, {'u1': [1, 2, 3], 'u2': [8, 2, 3], 'u3': [4, 5, 6], 'u4': [0, 5, 6]})
Output: [['u1', 'u2'], ['u3', 'u4']]
Example 3
Input: cluster_by_recent_watches(1, {'alice': ['x', 'y'], 'bob': ['z', 'y'], 'carol': ['y', 'y'], 'dave': ['q', 'r']})
Output: [['alice', 'bob', 'carol']]
Hints
Hint 1
Think about how to create a consistent representation for a set that can serve as a dictionary key
Hint 2
The last k items form a window—you don't need to process the entire history
Hint 3
Use a hashable, order-insensitive collection type to group viewers with identical recent watch sets
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires grouping viewers based on a computed property: the set of their most recent k watched items. The standard pattern is to build a canonical key for each viewer and use a hash map to bucket viewers with identical keys.
For each viewer, we:
- Extract the last
kelements from their watch history using slice notationhistory[-k:] - Convert this sequence into a set to eliminate duplicates and ignore order
- Use an immutable, hashable version of this set as a dictionary key
Python's frozenset is ideal here—it's an immutable set type that can serve as a dictionary key, and two frozensets are equal precisely when they contain the same elements.
After bucketing all viewers by their frozen set keys, we filter to keep only clusters with at least two members, as single-viewer clusters don't represent shared viewing patterns.
Why This Works
Two viewers are placed in the same cluster if and only if their frozenset keys are equal, which occurs exactly when their recent watch sets contain the same items. This correctly implements the equivalence relation defined in the problem.
The set semantics mean that if a viewer's last k items contain duplicates (e.g., [m1, m1, m2]), those duplicates collapse into a single element in the set. This matches the problem's definition of treating recent views as a collection where repetition within the window doesn't affect grouping.
Complexity
-
Time: O(U · k) where U is the number of viewers
- Slicing the last k elements: O(k) per viewer
- Creating the frozenset: O(k) per viewer
- Hashing and dictionary operations: O(k) per viewer (expected)
- Final filtering: O(U)
- Note: we only process the last k items, not the entire history, so total history length doesn't affect runtime
-
Space: O(U · k) in the worst case
- Up to U distinct frozenset keys, each containing up to k elements
- Lists of viewer IDs totaling U elements
- Temporary storage for slices and frozensets
Edge Cases Handled
- All viewers have identical recent watches → single large cluster returned
- All viewers have unique recent watches → empty list returned
- History length exactly equals k → entire history becomes the window
- Duplicate items within the k-item window → collapsed by set semantics
- Same items in different orders within the window → correctly grouped together
from collections import defaultdict
from typing import Dict, List
def cluster_by_recent_watches(k: int, watch_logs: Dict[str, List]) -> List[List[str]]:
clusters = defaultdict(list)
for viewer_id, history in watch_logs.items():
signature = frozenset(history[-k:])
clusters[signature].append(viewer_id)
return [viewer_list for viewer_list in clusters.values() if len(viewer_list) >= 2]