Find User Pairs with Enough Overlapping Interests
Arrays & HashingAuto-graded · 23 test casesLast 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_aanduser_bare the two user IDs.shared_listis 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
subscriptionsis a list of[user_id, interest_id]pairs where both IDs are non-empty strings.1 <= len(subscriptions) <= 100,000k >= 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).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea: inverted index + co-occurrence
The straightforward approach — enumerate every pair of users and intersect their interest sets — costs O(U²) pair checks where U is the number of users. With U up to 10,000 that is about 50 million intersections, most of them empty and wasteful.
A better approach inverts the problem. Instead of asking "what interests do users A and B share?", ask "for each interest, which user pairs both subscribe to it?" Build a map from each interest to its subscriber set. Two users can only share an interest if they both appear in that interest's subscriber list. So the only pairs worth examining are those that co-occur in at least one subscriber list.
For each interest's subscriber list:
- Sort the list so that iterating index
iwith indexj > ialways givesuser_a < user_b. - Emit every such
(user_a, user_b)pair, and add the current interest to that pair's shared set.
After processing all interests, filter to pairs whose shared set has at least k entries.
Why this is correct
Completeness. If users A and B share interests I₁…Iₜ, then both appear in each Iᵢ's subscriber list. The co-occurrence pass will add each Iᵢ to shared[(A, B)], so the final set contains every shared interest.
Soundness. An interest is added to shared[(A, B)] only while iterating that interest's subscriber list, which means both users genuinely subscribe to it.
No duplicates or self-pairs. Sorting the subscriber list and pairing index i only with indices strictly greater than i produces each unordered pair exactly once in (smaller, larger) order. Subscriber lists are sets, so a user never appears twice in one list.
Duplicate input entries are absorbed when building the inverted index because subscriber lists are sets.
Output ordering. Each pair's shared list is sorted before appending, and the result list is sorted by (user_a, user_b), giving a fully deterministic output.
Edge cases
klarger than any user's subscription count. No pair can reach the threshold, so the function returns[].- No overlapping subscriptions. Every subscriber list has size 1, so no pairs are generated and the function returns
[]. - Many pairs share exactly
kinterests. The check is>=, so all of them are included. - Duplicate input entries like
["Alice", "Math"]appearing twice are de-duplicated by the set, so the interest is counted only once per pair. - Case-sensitive lexicographic ordering. Python string comparison is used directly, so
"Bob" < "alice"(uppercase before lowercase).
Complexity
Let E = number of subscriptions, sᵢ = subscriber count for interest i, and P = number of distinct co-occurring pairs.
Time:
- Building the inverted index: O(E)
- Sorting subscriber lists: O(Σ sᵢ log sᵢ) ≤ O(E log U)
- Pair generation: O(Σ sᵢ²) — this term dominates
- Final sort: O(P log P), plus sorting each pair's interest list
Overall: O(E log U + Σ sᵢ² + P log P)
Space: O(E + Σ sᵢ²) for the inverted index and the shared-interest map.
When subscriber lists are small and sparse (the typical case), Σ sᵢ² stays close to linear in E — far better than all-pairs. When many users subscribe to almost all interests, the lists are large and Σ sᵢ² approaches M·U². In that dense regime, no algorithm improves the asymptotic bound because the output itself is O(U²) pairs each carrying O(M) items. Bitset intersection (representing subscriptions as M-bit integers and using popcount) can provide a large constant-factor improvement in that case.
Reference Solution
from collections import defaultdict
from typing import List
def find_shared_interests(subscriptions: List[List[str]], k: int) -> List[List]:
# Build inverted index: interest -> set of subscribing users
users_by_interest = defaultdict(set)
for user, interest in subscriptions:
users_by_interest[interest].add(user)
# Co-occurrence pass: for each interest, emit every user pair that shares it
shared = defaultdict(set)
for interest, users in users_by_interest.items():
ordered = sorted(users) # sort so that ordered[i] < ordered[j] for i < j
for i, user_a in enumerate(ordered):
for user_b in ordered[i + 1:]:
shared[(user_a, user_b)].add(interest)
# Collect pairs that meet the threshold
results = []
for (user_a, user_b), interests in shared.items():
if len(interests) >= k:
results.append([user_a, user_b, sorted(interests)])
results.sort(key=lambda item: (item[0], item[1]))
return results