KatInterview

Stable Softmax, Sliding Variance and Balanced Partition

Math & Bit ManipulationModel answer
MediumModel answerMath & Bit Manipulationsoftmaxnumerical-stabilitywelford

Last updated

Three short coding tasks: an overflow-safe softmax, an O(1) sliding-window variance with a ring buffer, and splitting positive integers into two groups with the smallest sum gap.

Solve the three small tasks below. For each one, explain why the obvious implementation breaks or is too slow, then give a correct version with its complexity.

Task 1: Overflow-safe softmax

Write softmax(x), which converts a list of real-valued scores into a probability distribution. It must give correct results even when the scores are very large or very negative.

def softmax(x: list[float]) -> list[float]:
    ...

Task 2: Variance of a sliding window

Write a class RollingVariance that receives numbers one at a time and reports the variance of the most recent k values (or of all values seen so far, if fewer than k have arrived). Each update call must run in O(1) time, the memory must be O(k), and the computation must be numerically stable. Welford-style updates or an equivalent technique are acceptable.

class RollingVariance:
    def __init__(self, k: int):
        ...
    def update(self, val: float) -> float:
        # add val to the stream, return the current window variance
        ...

Task 3: Balanced split of weights

You get a list of strictly positive integer weights. Divide them into two groups so that the absolute difference of the two group sums is as small as possible, and return that difference. Your algorithm must beat brute force over all 2^n splits.

def minimize_weight_diff(weights: list[int]) -> int:
    ...

Examples

  • softmax([1000, 1001]) should return [1/(1+e), e/(1+e)], not [NaN, NaN].
  • minimize_weight_diff([1, 2, 3, 9]) returns 3, from the groups {1, 2, 3} and {9}.

Constraints

  • Tasks 1 and 3: n is at most 1000.
  • Task 2: k is at most 10^5, and memory must be O(k).

State your assumptions about edge cases such as empty input, k = 1, and a first update on an empty window.

Hints

Hint 1

Softmax does not change if you subtract the same constant from every score. Which constant guarantees that no exponent is positive?

Hint 2

For the window, keep the running mean and the sum of squared deviations from the mean instead of the raw sum and sum of squares. When the window is full, the new value replaces the oldest one in a single combined update of both quantities.

Hint 3

If one group sums to s and the total is S, the gap is |S - 2s|. So you only need the achievable subset sum closest to S/2 from below. Track which sums are achievable, for example with a bitset.