Coding questions · Shopify
Calculate Jaccard Similarity Score for Two String Lists
This question evaluates understanding of similarity metrics and competency in comparing string collections, reflecting knowledge of set-theoretic concepts and manipulation of collection data structures used in data processing.
Scenario
During pair programming, the interviewer asks you to compare two lists of merchant tags and quantify their similarity.
Question
Implement a Python function that takes two lists of strings and returns their Jaccard similarity score.
Hints
Convert both lists to sets, then compute |A ∩ B| ÷ |A ∪ B|.
Calculate Jaccard Similarity Score for Two String Lists
During pair programming, the interviewer asks you to compare two lists of merchant tags and quantify their similarity.
Implement a function jaccardSimilarity(listA, listB) that takes two lists of strings and returns their Jaccard similarity score: the size of the intersection of the two sets of tags divided by the size of their union.
Formally, for sets A and B derived from the input lists:
Jaccard(A, B) = |A ∩ B| / |A ∪ B|
Duplicate tags within a single list should be treated as one (the lists are converted to sets). If both lists are empty (the union is empty), return 0.0 to avoid dividing by zero.
Example:
listA = ["a", "b", "c"], listB = ["b", "c", "d"]
Intersection = {"b", "c"} (size 2), Union = {"a", "b", "c", "d"} (size 4)
Result = 2 / 4 = 0.5
Constraints
- 0 <= len(listA), len(listB) <= 10^5
- Each tag is a non-empty string of printable ASCII characters.
- Tags are case-sensitive ("Sale" and "sale" are distinct).
- Duplicate tags within the same list count once.
- If both lists are empty (union is empty), return 0.0.
Hints
- Convert both lists to sets to discard duplicates and enable fast membership tests.
- The intersection size is |A ∩ B| and the union size is |A ∪ B|; the score is their ratio.
- Guard against division by zero: when the union is empty (both lists empty), return 0.0.