Find Most Similar Item Collections
SQL & DataAuto-graded · 15 test casesLast updated
Tests set operations, pairwise comparison, and tie-breaking logic to identify the pair of collections with maximum item overlap.
You are given two tables representing collections and their contents:
Schema:
lists: Contains columnslist_id(int),owner_id(int), andcreated_at(string in ISO date format "YYYY-MM-DD")list_items: Contains columnslist_id(int) anditem(string)
Your task is to find the pair of collections with the highest number of shared items, considering only collections created within a specific 7-day window.
Rules:
-
Time window: Only consider collections where
created_atis between2025-08-26and2025-09-01(inclusive on both ends). -
Deduplication: If a collection contains duplicate items, count each unique item only once.
-
Overlap calculation: For two collections A and B, the overlap count is the number of distinct items that appear in both collections.
-
Similarity metric: Calculate the Jaccard similarity coefficient as
overlap_count / union_size, whereunion_sizeis the total number of distinct items across both collections. If both collections are empty (union size is 0), the Jaccard coefficient is 0. -
Output format: Return a list
[list_id_small, list_id_large, overlap_count, jaccard]wherelist_id_small < list_id_large. -
Tie-breaking: If multiple pairs have the same overlap count, choose the pair with the higher Jaccard coefficient. If still tied, choose the pair with the smallest
list_id_small, then smallestlist_id_large. -
Edge cases: If fewer than two collections exist in the time window, return
None.
Constraints:
- 1 ≤ number of collections ≤ 1000
- 0 ≤ items per collection ≤ 1000
list_idvalues are positive integers- Item strings are non-empty and may contain any characters
- All dates in the input are valid ISO-format strings
Examples
Example 1
Input: find_most_similar_collections([[1, 10, '2025-08-30'], [2, 11, '2025-08-31'], [3, 12, '2025-09-01']], [[1, 'A'], [1, 'B'], [1, 'C'], [2, 'A'], [2, 'C'], [2, 'D'], [3, 'B'], [3, 'C'], [3, 'E']])
Output: [1, 2, 2, 0.5]
Hints
Hint 1
Treat each collection as a mathematical set—duplicates within a collection should be ignored.
Hint 2
Use set intersection to count shared items and set union to compute the denominator for Jaccard similarity.
Hint 3
When comparing pairs, iterate through all valid combinations systematically and track the best candidate based on the multi-level tie-breaking rules.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires comparing every valid pair of collections to find the one with maximum item overlap. The solution proceeds in four stages:
-
Filter by date range: Identify all collections whose creation date falls between August 26 and September 1, 2025 (inclusive).
-
Build deduplicated item sets: For each eligible collection, construct a set of its unique items. This automatically handles deduplication—if an item appears multiple times in a collection, the set contains it only once.
-
Compare all pairs: Generate every unordered pair of eligible collections. For each pair:
- Compute the intersection size (shared items) using set intersection
- Compute the union size (total distinct items) using set union
- Calculate the Jaccard coefficient as the ratio of intersection to union
-
Select the winner: Track the best pair using a comparison key that encodes the tie-breaking rules: prioritize higher overlap (negative to sort descending), then higher Jaccard (negative), then smaller list IDs (ascending).
Why It Works
The algorithm correctly implements set-based similarity:
-
Set operations ensure accuracy: Python's built-in set intersection (
&) and union (|) operators precisely count distinct shared and total items. -
Exhaustive comparison guarantees optimality: By examining all valid pairs through
combinations(), we never miss the true maximum. -
Tuple comparison implements tie-breaking: The comparison key
(-overlap, -jaccard, small, large)naturally sorts pairs by the specification's priority order. Python's tuple comparison evaluates elements left-to-right. -
Fraction arithmetic avoids precision issues: Using
Fractionfor Jaccard calculations ensures exact rational arithmetic during tie-breaking comparisons, only converting to float in the final output.
Complexity
Time complexity: O(E² × M) where E is the number of eligible collections and M is the average collection size. Building the item sets takes O(I) where I is the total number of item records. Comparing all pairs requires O(E²) iterations, and each set intersection/union operation costs O(M).
Space complexity: O(I) to store the deduplicated items across all eligible collections.
Full Solution
from datetime import date
from fractions import Fraction
from itertools import combinations
from typing import List, Optional
def find_most_similar_collections(lists: List[List], list_items: List[List]) -> Optional[List]:
start = date(2025, 8, 26)
end = date(2025, 9, 1)
eligible = {
row[0]
for row in lists
if start <= date.fromisoformat(row[2]) <= end
}
items_by_list = {list_id: set() for list_id in eligible}
for list_id, item in list_items:
if list_id in items_by_list:
items_by_list[list_id].add(item)
best = None
for small, large in combinations(sorted(eligible), 2):
overlap = len(items_by_list[small] & items_by_list[large])
union = len(items_by_list[small] | items_by_list[large])
jaccard = Fraction(overlap, union) if union else Fraction(0, 1)
key = (-overlap, -jaccard, small, large)
if best is None or key < best[0]:
best = (key, small, large, overlap, union, jaccard)
if best is None:
return None
_, small, large, overlap, union, jaccard = best
return [small, large, overlap, float(jaccard)]