Stable Softmax, Sliding Variance and Balanced Partition
Math & Bit ManipulationModel answerLast 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])returns3, from the groups{1, 2, 3}and{9}.
Constraints
- Tasks 1 and 3:
nis at most 1000. - Task 2:
kis 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Task 1: Stable softmax
Problem with the naive version. Computing exp(x_i) / sum(exp(x_j)) overflows to inf for scores around 710 and above in float64. The result is then inf/inf = NaN. Very negative scores can instead underflow every term to 0, giving 0/0.
Fix. Softmax is unchanged when every score is shifted by the same constant c:
softmax(x)_i = exp(x_i - c) / sum_j exp(x_j - c)
Choose c = max(x). All exponents are then at most 0, so nothing overflows. The largest term is exactly exp(0) = 1, so the denominator is at least 1 and never zero. Terms that underflow to 0 are correct, since their true probability is below float resolution.
For [1000, 1001] the shifted values are [-1, 0], giving [e^-1, 1] / (1 + e^-1) = [1/(1+e), e/(1+e)].
Edge cases. Empty input returns []. A single element returns [1.0]. If all values are -inf, then -inf - (-inf) is NaN, so choose a policy (uniform output or raise an error). Inputs containing +inf or NaN are invalid.
import math
def softmax(x):
if not x:
return []
m = max(x)
if m == -math.inf:
return [1.0 / len(x)] * len(x)
exps = [math.exp(v - m) for v in x]
total = sum(exps)
return [e / total for e in exps]
Complexity is O(n) time and O(n) output space. The same shift gives a stable log-softmax: x_i - (m + log(sum exp(x_j - m))). This is the log-sum-exp trick, and it avoids log(0) in cross-entropy. For a 2D array, subtract the maximum per row (with keepdims=True). A single global maximum would make rows with low scores underflow completely.
Task 2: Rolling variance
Problem with the naive version. Maintaining sum and sum_sq and returning sum_sq/k - (sum/k)^2 is algebraically correct but subtracts two huge, nearly equal numbers when the mean is large relative to the spread. For values near 10^9 with a spread of about 1, almost all significant digits cancel, and the result can even be negative.
Approach. Keep a circular buffer of the last k values (O(k) memory), plus the window mean and M2, the sum of squared deviations from the mean. Both are updated from deviations only, so the error depends on the spread and not on the magnitude of the data.
- Window not full (Welford add):
n += 1; d = x - mean; mean += d / n; M2 += d * (x - mean). - Window full (swap oldest
ofor newx):mean' = mean + (x - o) / kM2' = M2 + (x - o) * (x + o - mean' - mean)
The swap formula comes from M2 = sum(v^2) - k*mean^2. The change in sum(v^2) is (x-o)(x+o), and the change in k*mean^2 is (x-o)(mean'+mean). Subtracting gives the formula above.
The returned value is the population variance M2 / n, where n = min(count, k).
class RollingVariance:
def __init__(self, k):
if k <= 0:
raise ValueError("k must be positive")
self.k = k
self.buf = [0.0] * k
self.head = 0
self.n = 0
self.mean = 0.0
self.m2 = 0.0
def update(self, val):
if self.n < self.k:
self.n += 1
d = val - self.mean
self.mean += d / self.n
self.m2 += d * (val - self.mean)
else:
old = self.buf[self.head]
old_mean = self.mean
self.mean += (val - old) / self.k
self.m2 += (val - old) * (val + old - self.mean - old_mean)
self.buf[self.head] = val
self.head = (self.head + 1) % self.k
if self.m2 < 0.0: # rounding guard
self.m2 = 0.0
return self.m2 / self.n
Each update is O(1) time, and memory is O(k). Edge cases: k = 1 always gives 0, the first update gives 0, and k <= 0 is an error. Over very long streams, rounding errors in M2 can slowly accumulate. If that matters, recompute from the buffer every so often (amortised O(1)) or use a two-stack scheme that merges partial statistics.
Task 3: Balanced partition
Reduction. Let S be the total. If one group sums to s, the other sums to S - s, and the gap is |S - 2s|. So we need the achievable subset sum s <= S/2 that is largest. This is subset-sum, solved by DP over reachable sums.
Bitset DP. Store the set of reachable sums as the bits of an integer, with bit i meaning "some subset sums to i". Start with reach = 1 (only sum 0). For each weight w, do reach |= reach << w, which means each item is either skipped or taken. At the end, scan downward from S // 2 for the first set bit s and return S - 2*s.
def minimize_weight_diff(weights):
total = sum(weights)
reach = 1
for w in weights:
reach |= reach << w
for s in range(total // 2, -1, -1):
if (reach >> s) & 1:
return total - 2 * s
return total
Check on [1, 2, 3, 9]: S = 15, the reachable sums up to 7 include 6, so the answer is 15 - 12 = 3.
Complexity. The time is O(n * S) bit operations, which in practice is about O(n * S / 64) word operations, and the space is O(S) bits. This is pseudo-polynomial: much better than 2^n when the weights are moderate, but not polynomial in the input size, so the problem is still NP-hard in general. A plain boolean-array DP over 0..S//2 has the same logic and is easier to write on a whiteboard. Mention the bitset as an optimisation.
Edge cases. An empty list gives 0. A single weight w gives w. If all weights are equal, the answer is 0 for even n and w for odd n.
Common mistakes.
- Using a greedy "put the next largest item in the lighter group" rule. It is not optimal, for example on
[3, 3, 2, 2, 2], where greedy gives 2 but the best split is 0. - Looping the 0/1 knapsack forward in a boolean array, which reuses an item several times.
- Subtracting an unstable formula for variance, or applying a single global max to a batch of softmax rows.