KatInterview

Overflow-Safe Probability Normalization of Raw Scores

Math & Bit ManipulationAuto-graded · 23 test cases
MediumAuto-gradedMath & Bit Manipulationnumerical-stabilitymathfloating-point

Last updated

Convert a list of real scores into a probability distribution via exponentiation and normalization, without overflow or division-by-zero for extreme input values.

Overflow-Safe Probability Normalization

You are given a list of real-valued scores. Turn it into a probability distribution in which larger scores receive larger probabilities. The probability assigned to position i is

p[i] = exp(scores[i]) / (exp(scores[0]) + exp(scores[1]) + ... + exp(scores[n-1]))

Evaluating this formula literally breaks down for extreme inputs. For large scores, exp exceeds the range of a double-precision float (in Python, math.exp(1000.0) raises an OverflowError; in other environments it yields inf, which leads to NaN after division). For very negative scores, every exp term can underflow to 0.0, producing a 0 / 0 division.

Write a function that returns the correct distribution for every valid input, including those extreme cases.

Requirements

  • Return a list of floats the same length as the input, where entry i is the probability for scores[i].
  • The result must equal the mathematical definition above (to normal double-precision accuracy), not an approximation.
  • Your function must never raise an overflow error and must never return NaN or inf for inputs within the constraints.
  • A probability that is too small to represent in a double should come out as 0.0.
  • Equal scores must receive equal probabilities. A one-element input yields [1.0].

Constraints

  • 1 <= len(scores) <= 10^5
  • -10^4 <= scores[i] <= 10^4
  • Values may be given as integers or floats.

Examples

Example 1

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

Output: [0.09003057317038046, 0.24472847105479764, 0.6652409557748218]

Example 2

Input: scores_to_probabilities([1000, 1000])

Output: [0.5, 0.5]

Hints

Hint 1

Adding or subtracting the same constant from every score leaves the final probabilities unchanged, because the constant's factor cancels between numerator and denominator.

Hint 2

Pick the constant so that the largest shifted score is exactly 0. Then every exponent argument is at most 0, so no term can overflow.

Hint 3

After the shift, the largest element contributes exactly 1 to the denominator, so the denominator is at least 1 and you never divide by zero, even when the other terms underflow.