KatInterview

Win Rate Between Two Weighted Dice

Heaps, Sorting & SearchAuto-graded · 20 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchsortingprobability

Last updated

Tests whether a candidate can count strict-win outcome pairs across two multi-faced dice efficiently using sorting and binary search instead of a brute-force double loop.

Win Rate Between Two Weighted Dice

You have two dice, a and b, each represented as a list of integers. Every element is one physical face of that die. Duplicate values are allowed and each duplicate counts as a separate, equally likely outcome. The two dice may have different numbers of faces.

When both dice are rolled simultaneously, what is the probability that the roll of a lands on a value strictly greater than the roll of b? A tie does not count as a win for either side.

Return that probability as a floating-point number.

Details

Every pair of faces (a[i], b[j]) is equally likely, so the answer is:

(number of pairs where a[i] > b[j]) / (len(a) * len(b))

Your solution must not enumerate all len(a) * len(b) pairs directly. For large inputs that approach is too slow; you need a more efficient strategy.

Constraints

  • Both lists are non-empty.
  • Face values are integers (negative, zero, or positive).
  • 1 <= len(a), len(b) <= 10^5
  • -10^9 <= a[i], b[j] <= 10^9
  • Do not deduplicate faces; each element is a distinct outcome regardless of its value.

Examples

Example 1

Input: win_probability([1, 2, 3], [1, 2, 3])

Output: 0.3333333333333333

Example 2

Input: win_probability([2, 2], [1, 2])

Output: 0.5

Hints

Hint 1

If you sort one of the lists, how quickly can you find how many of its values fall strictly below a given number?

Hint 2

bisect_left(sorted_b, x) returns the number of elements in sorted_b that are strictly less than x — which is exactly the win count for a single face x of a.

Hint 3

Keep the running win count as an integer and perform only one floating-point division at the very end to avoid accumulating rounding error.