← Questions

Friend groups by matching last k movies

0
NetflixCodingLast asked Jan 2026

A streaming service stores each customer's full viewing history, oldest title first. Two customers are friends when the set of their last k watched titles is the same. Order inside that window does not matter, and a title watched twice in the window counts once.

Implement:

def friend_groups(customer_ids: list[str], movies: list[list[str]], k: int) -> list[list[str]]
  • customer_ids holds distinct IDs; movies[i] is the history of customer_ids[i].
  • Return every friend group with at least two customers. Sort the IDs inside each group, and sort the groups by their first ID.
  • A customer who has watched fewer than k titles has no full window and belongs to no group.

Constraints: 1 <= k <= 100, up to 10^5 customers, histories up to 10^4 titles each.

Example 1

customer_ids = ["u1", "u2", "u3", "u4"]
movies = [
  ["Heat", "Alien", "Up", "Jaws"],
  ["Jaws", "Up", "Alien"],
  ["Alien", "Jaws", "Up"],
  ["Jaws", "Heat", "Up"],
]
k = 3  ->  [["u1", "u2", "u3"]]

u1, u2 and u3 all end with the set {Alien, Jaws, Up}. u4 ends with {Jaws, Heat, Up}.

Example 2

Same input with k = 1 returns [["u3", "u4"]]: both last watched Up.

Be ready for follow-ups: friends who share at least m of the last k titles, histories that grow as events stream in, and data too large for one machine.

Write and test your solution herePython in your browser, the question's tests level by level, saved for you.Sign in to start coding