KatInterview

Find Most Similar Item Collections

SQL & DataAuto-graded · 15 test cases
MediumAuto-gradedSQL & Datasetssimilarity-metricsdata-manipulation

Last 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 columns list_id (int), owner_id (int), and created_at (string in ISO date format "YYYY-MM-DD")
  • list_items: Contains columns list_id (int) and item (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:

  1. Time window: Only consider collections where created_at is between 2025-08-26 and 2025-09-01 (inclusive on both ends).

  2. Deduplication: If a collection contains duplicate items, count each unique item only once.

  3. Overlap calculation: For two collections A and B, the overlap count is the number of distinct items that appear in both collections.

  4. Similarity metric: Calculate the Jaccard similarity coefficient as overlap_count / union_size, where union_size is the total number of distinct items across both collections. If both collections are empty (union size is 0), the Jaccard coefficient is 0.

  5. Output format: Return a list [list_id_small, list_id_large, overlap_count, jaccard] where list_id_small < list_id_large.

  6. 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 smallest list_id_large.

  7. 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_id values 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.