KatInterview

Find User Pairs with Enough Overlapping Interests

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashinghash-mapsetsco-occurrence

Last updated

Tests your ability to invert a membership index and use co-occurrence counting to efficiently find all pairs sharing at least k common items.

Problem Statement

You are given a list of user-interest subscriptions. Each entry is a two-element list [user_id, interest_id] indicating that the given user has subscribed to that interest.

Your task is to find every pair of users who have at least k interests in common, and return their shared interests along with their IDs.

Each result must be a three-element list [user_a, user_b, shared_list] where:

  • user_a and user_b are the two user IDs.
  • shared_list is the sorted list of interest IDs they both subscribe to.
  • user_a < user_b (lexicographic order) to avoid reporting the same pair twice.

The overall result list must be sorted by (user_a, user_b) in lexicographic order.

Duplicate entries in the input (the same [user_id, interest_id] appearing more than once) must not cause an interest to be counted more than once for any pair.

Constraints

  • subscriptions is a list of [user_id, interest_id] pairs where both IDs are non-empty strings.
  • 1 <= len(subscriptions) <= 100,000
  • k >= 1
  • The number of distinct users and distinct interests can each be up to 10,000.
  • Comparison between user IDs uses standard Python string ordering (lexicographic, case-sensitive). For example, "Bob" < "alice" because uppercase letters sort before lowercase.
  • If no pair meets the threshold, return an empty list.

Examples

Example 1

Input: find_shared_interests([['Alice', 'Math'], ['Alice', 'History'], ['Bob', 'Math'], ['Bob', 'Physics'], ['Charlie', 'Math'], ['Charlie', 'History']], 2)

Output: [['Alice', 'Charlie', ['History', 'Math']]]

Example 2

Input: find_shared_interests([['A', 'x'], ['B', 'x'], ['C', 'y'], ['D', 'z']], 1)

Output: [['A', 'B', ['x']]]

Example 3

Input: find_shared_interests([['s1', 'c1'], ['s1', 'c2'], ['s2', 'c1'], ['s2', 'c2'], ['s3', 'c1'], ['s3', 'c2'], ['s3', 'c3']], 2)

Output: [['s1', 's2', ['c1', 'c2']], ['s1', 's3', ['c1', 'c2']], ['s2', 's3', ['c1', 'c2']]]

Hints

Hint 1

Start by building an inverted index: for each interest, collect the set of users who subscribe to it. This tells you exactly which pairs of users could possibly share that interest.

Hint 2

For each interest's subscriber list, sort it and iterate over every (i, j) pair with i < j. This naturally enforces user_a < user_b and generates only pairs that share at least one interest — avoiding expensive all-pairs comparisons.

Hint 3

Track shared interests per pair in a dict mapping (user_a, user_b) to a set of interest IDs. After processing all interests, filter to pairs whose set size is >= k, sort each shared set, and sort the result list by (user_a, user_b).