KatInterview

Cluster Viewers by Recent Watch Set

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashinghash-mapset-operationsgrouping

Last 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 least k elements.

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