Problems
Loading...
1 / 1

Jaccard Similarity

Recommender Systems
Easy

Jaccard similarity measures the overlap between two sets as the ratio of their intersection to their union. In recommender systems, it is used to compare users by their item interaction histories (purchases, likes, views) without needing explicit ratings. Two users who bought many of the same products will have a high Jaccard similarity.

Given two lists of items, compute the Jaccard similarity coefficient. Duplicate items in the input should be treated as a single item (convert to sets first).

Algorithm

J(A,B)=ABABJ(A, B) = \frac{|A \cap B|}{|A \cup B|}

If both sets are empty, return 0.0.

Loading visualization...

Examples

Input:

set_a = [1, 2, 3], set_b = [2, 3, 4]

Output:

0.5

Intersection = {2, 3} (size 2), union = {1, 2, 3, 4} (size 4). Jaccard = 2/4 = 0.5.

Input:

set_a = [1, 2, 3], set_b = [4, 5, 6]

Output:

0.0

No items in common. Intersection is empty, so Jaccard = 0/6 = 0.0.

Hint 1

Convert both lists to Python sets using set(). Then use set intersection (&) and set union (|) operators. The Jaccard similarity is len(intersection) / len(union).

Hint 2

Handle the edge case where both sets are empty (union has size 0) by returning 0.0 before dividing.

Requirements

  • Convert both input lists to sets (remove duplicates)
  • Compute the intersection and union of the two sets
  • Return 0.0 if both sets are empty
  • Return a float between 0.0 and 1.0

Constraints

  • Input lists may contain duplicates (treat as sets)
  • Items are integers
  • Return a float
  • Time limit: 300 ms
Try Similar Problems