KatInterview

Overlap Ratio of Two Token Lists

Arrays & HashingAuto-graded · 22 test cases
EasyAuto-gradedArrays & Hashinghash-setsetsstrings

Last updated

Compute the overlap ratio between the distinct strings of two lists using hash sets, with exact string matching and a defined result when both lists are empty.

Overlap Ratio of Two Token Lists

You are given two lists of strings, first and second. Measure how much their contents overlap by computing the ratio of shared distinct strings to all distinct strings that appear in either list.

Task

Write a function that returns this ratio as a float:

(number of distinct strings present in both lists) / (number of distinct strings present in at least one list)

Rules

  • Only distinct strings matter. If a string appears several times in one list, it counts once for that list.
  • Strings are compared exactly. Uppercase and lowercase letters are different, and spaces (leading, trailing, or inside) are part of the string. Do not trim or change the case of anything.
  • The empty string "" is an ordinary string value. A list containing only "" is not an empty list.
  • If both lists are empty, return 1.0.
  • If exactly one list is empty, return 0.0.
  • Do not use third-party libraries.
  • Aim for time proportional to the total size of the two inputs.

Constraints

  • first and second each contain zero or more strings.
  • Every element is a Python str, possibly empty.
  • The return value is a float.

Examples

Example 1

Input: overlap_ratio(['red', 'blue', 'blue'], ['blue', 'green'])

Output: 0.3333333333333333

Example 2

Input: overlap_ratio(['a', 'b'], ['a', 'b'])

Output: 1

Example 3

Input: overlap_ratio([], ['a'])

Output: 0

Example 4

Input: overlap_ratio([], [])

Output: 1

Hints

Hint 1

Collapse each list into a set first. That handles repeated strings and gives fast membership checks.

Hint 2

You do not need to build the union explicitly: its size equals |A| + |B| - |A ∩ B|.

Hint 3

Division by zero can only happen when both sets are empty, which the statement defines as 1.0. Check emptiness by size, not by whether elements are truthy, since [""] is non-empty.