You are given the same user movie-watching histories as in the previous problem. Each user’s history is an ordered list of movie IDs from earliest to latest.
Assume:
histories
is a dictionary/map from
user_id
to a list of
movie_id
.
K
movies.
Task
Given integers K and M (1 ≤ M ≤ K), find all unordered pairs of distinct users (u1, u2) such that:
L(u)
is the list of the last
K
movies in user
u
's history, then the number of common movies between
L(u1)
and
L(u2)
(treated as sets or as lists ignoring order and duplicates) is at least
M
.
Formally, define:
S(u) = set of the last K movies in user u's history
.
(u1, u2)
with
u1 < u2
(or any consistent ordering) such that
|S(u1) ∩ S(u2)| ≥ M
.
Input
K
(1 ≤ K ≤ 10^3).
M
(1 ≤ M ≤ K).
histories: user_id → [movie_id1, movie_id2, ..., movie_idN]
where N ≥ K for each user.
Output
(u1, u2)
that satisfy
|S(u1) ∩ S(u2)| ≥ M
.
Example Let K = 4, M = 2 and:
Then:
We have:
So the output should include the pair (A, B) only.
Design an efficient algorithm for large numbers of users and movies, and analyze its time and space complexity.