Find Most Overlapping Pair of Sets
Arrays & HashingAuto-graded · 21 test casesLast updated
Find the pair of set keys with the highest intersection size, using Jaccard similarity and lexicographical order as tie-breakers via an inverted index approach.
You are given a dictionary mapping dataset identifiers (strings) to collections of elements (lists of strings). Each collection should be treated as a set of unique elements (duplicates within the same collection are ignored).
Your goal is to find the pair of distinct dataset keys that share the highest number of common elements (intersection size).
Output Format
Return a 4-element list containing:
[key1, key2, intersection_size, jaccard_similarity]
Where:
key1andkey2are the two dataset keys forming the pair, ordered such thatkey1 < key2lexicographically.intersection_sizeis an integer representing $|A \cap B|$.jaccard_similarityis a float representing $\frac{|A \cap B|}{|A \cup B|}$.
Tie-Breaking Rules
If multiple pairs share the same maximum intersection_size, break ties by:
- Higher Jaccard similarity.
- Lexicographically smaller pair identifier, comparing
(key1, key2)as a tuple.
Edge Cases
- If there are fewer than 2 dataset keys in the input dictionary, return
None. - If no pair of datasets shares any common element (all intersections are 0), return
[smallest_key, second_smallest_key, 0, 0.0]according to the lexicographical sorting of all keys in the input dictionary.
Constraints
- $N$, the number of dataset keys: $0 \le N \le 200,000$.
- Total elements across all lists $\le 5,000,000$.
- Elements are case-sensitive strings.
Examples
Example 1
Input: find_max_overlap_pair({'L1': ['A', 'B', 'C'], 'L2': ['A', 'C', 'D'], 'L3': ['B', 'C', 'E'], 'L4': []})
Output: ['L1', 'L2', 2, 0.5]
Example 2
Input: find_max_overlap_pair({'a': ['x', 'x', 'y'], 'b': ['y', 'z'], 'c': ['q']})
Output: ['a', 'b', 1, 0.3333333333333333]
Example 3
Input: find_max_overlap_pair({'one': [], 'two': [], 'three': []})
Output: ['one', 'three', 0, 0]
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Checking all pairs of dataset keys takes $O(N^2)$ time, which is prohibitively expensive when $N$ is large. However, two datasets can only have a non-zero overlap if they share at least one common item. We can exploit this using an inverted index:
- Deduplicate and Index: Convert each input list into a set of unique items and record its cardinality. Construct an inverted index mapping each unique item to the list of dataset keys that contain it (the posting list).
- Count Overlaps: For every posting list, generate all pairwise combinations of keys $(A, B)$ with $A < B$. For each occurrence of a pair in a posting list, increment their intersection count in a hash map.
- Score and Select: For each candidate pair in the overlap map, compute the union size as $|A \cup B| = |A| + |B| - |A \cap B|$, and the Jaccard similarity as $|A \cap B| / |A \cup B|$. Track the best pair using the required tie-breaking logic (maximum overlap, then maximum Jaccard, then lexicographically smallest pair).
- Edge Cases:
- Return
Noneif $N < 2$. - If no pairs share any item, fall back to the first two lexicographically smallest dataset keys with overlap 0 and Jaccard similarity 0.0.
- Return
Complexity
- Time Complexity: $O(M \log N + \sum_{x} P_x^2)$, where $M$ is the total number of unique dataset-item memberships and $P_x$ is the number of datasets containing item $x$. In sparse datasets, this is significantly faster than $O(N^2)$.
- Space Complexity: $O(M + C)$, where $C$ is the number of pairs that share at least one common element.
Reference Solution
from collections import defaultdict
from itertools import combinations
from typing import Dict, List, Optional
def find_max_overlap_pair(lists: Dict[str, List[str]]) -> Optional[List]:
names = sorted(lists)
if len(names) < 2:
return None
sets = {name: set(items) for name, items in lists.items()}
sizes = {name: len(items) for name, items in sets.items()}
postings = defaultdict(list)
for name in names:
for item in sets[name]:
postings[item].append(name)
overlaps = defaultdict(int)
for item_names in postings.values():
item_names.sort()
for a, b in combinations(item_names, 2):
overlaps[(a, b)] += 1
if not overlaps:
return [names[0], names[1], 0, 0.0]
best_pair = None
best_overlap = -1
best_jaccard = -1.0
for (a, b), overlap in overlaps.items():
union_size = sizes[a] + sizes[b] - overlap
jaccard = overlap / union_size if union_size else 0.0
if (
overlap > best_overlap
or (overlap == best_overlap and jaccard > best_jaccard)
or (
overlap == best_overlap
and jaccard == best_jaccard
and (best_pair is None or (a, b) < best_pair)
)
):
best_pair = (a, b)
best_overlap = overlap
best_jaccard = jaccard
return [best_pair[0], best_pair[1], best_overlap, best_jaccard]