KatInterview

Find Most Overlapping Pair of Sets

Arrays & HashingAuto-graded · 21 test cases
MediumAuto-gradedArrays & Hashinginverted-indexhash-tablearrays

Last 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:

  • key1 and key2 are the two dataset keys forming the pair, ordered such that key1 < key2 lexicographically.
  • intersection_size is an integer representing $|A \cap B|$.
  • jaccard_similarity is 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:

  1. Higher Jaccard similarity.
  2. 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]