Running Bit-Entropy of a Token Feed with Stable Updates
Data Structure DesignAuto-graded · 22 test casesLast updated
Maintain Shannon entropy of a growing token stream with constant-time updates and queries, avoiding catastrophic cancellation when one token dominates.
Running Bit-Entropy of a Token Feed
A monitoring service watches a feed of string tokens, such as predicted labels or category IDs, and reports how spread out the observed distribution is. The spread is measured by the Shannon entropy in bits.
After N tokens have arrived, with c_i occurrences of the i-th distinct token, the entropy is
H = - sum over distinct tokens of (c_i / N) * log2(c_i / N)
If no token has arrived yet (N = 0), the entropy is 0.0.
Task
Implement track_entropy(operations, arguments). It replays a list of operations, in order, against one fresh tracker and returns one result per operation.
operations[i]is either"add"or"get_entropy".arguments[i]is the argument list for that operation:- for
"add"it is[token], a single string token. The token is recorded and the result for this operation isNone. - for
"get_entropy"it is[]. The result is the entropy, as a float in bits, of all tokens added so far.
- for
- Any other operation name must raise
ValueError. - The returned list has the same length as
operations.
Accuracy and cost requirements
- Each
addand eachget_entropymust takeO(1)amortized time. Do not rescan all distinct tokens on every operation. - The result must stay accurate over very long streams and highly skewed ones. When a single token makes up almost the whole stream, the entropy is tiny, and the formula
log2(N) - (1/N) * sum(c_i * log2(c_i))loses nearly all its significant digits to cancellation. Your method must avoid this. - If only one distinct token has been seen, the entropy must be exactly
0.0, not a tiny non-zero value. - Floating-point results are compared with a small tolerance, so tiny last-digit differences (such as
0.9999999999999999versus1.0) are fine.
Constraints
- The total number of tokens
Nmay exceed10^7. - The number of distinct tokens
Kmay be up to10^5. - Memory beyond the returned list must be
O(K). - Tokens are arbitrary strings compared by exact equality.
get_entropyon an empty stream returns0.0.
Examples
Example 1
Input: track_entropy(['add', 'get_entropy', 'add', 'get_entropy', 'add', 'add', 'get_entropy'], [['A'], [], ['B'], [], ['A'], ['B'], []])
Output: [None, 0, None, 1, None, None, 0.9999999999999999]
Example 2
Input: track_entropy(['add', 'add', 'add', 'add', 'get_entropy'], [['A'], ['A'], ['A'], ['B'], []])
Output: [None, None, None, None, 0.8112781244591328]
Hints
Hint 1
Instead of recomputing from all counts, ask how the quantity N*H changes when one token's count goes from c to c+1 and the total goes from N to N+1.
Hint 2
Store the entropy H itself rather than the large running sum of c*log(c). Then every update is a weighted average of non-negative numbers, so nothing large is ever subtracted from something nearly equal.
Hint 3
The change in N*H involves (N+1)log(N+1) - N log N - ((c+1)log(c+1) - c log c). Rewrite log(x+1) as log(x) + log1p(1/x) so the large terms cancel analytically, and treat the cases N = 0, c = N, and c = 0 separately.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep a dictionary of token counts, the total n, and the current entropy H in bits. Never store the large sum sum(c_i * ln c_i). Update H directly on each add, and return the stored H on each get_entropy.
Deriving the update
Let T = n * H, measured in nats for now, so T = n ln n - sum(c_i ln c_i). When a token with current count c arrives, n becomes n + 1 and c becomes c + 1. Define
f(x) = (x+1) ln(x+1) - x ln x, with f(0) = 0.
Then T grows by delta = f(n) - f(c), and the new entropy is
H_new = (n * H + delta) / (n + 1)
Dividing delta by ln 2 converts it to bits.
Stable evaluation of delta
Computing f(n) - f(c) directly subtracts numbers of size about n ln n. When c is close to n, almost all digits cancel. Using ln(x+1) = ln x + log1p(1/x), we get
f(x) = ln x + (x+1) * log1p(1/x)
and therefore
delta = log1p((n - c) / c) + (n+1) * log1p(1/n) - (c+1) * log1p(1/c)
The first term is ln(n/c), computed accurately even when n/c is near 1. The other two terms lie between 1 and 2 ln 2, so they are small and their difference is accurate to about machine epsilon.
Special cases:
n == 0: the first token, soH = 0.c == n: only one distinct token has been seen, sodelta = 0exactly andHstays exactly0.0.c == 0: a new token, sodelta = f(n) = ln n + (n+1) * log1p(1/n).
Why it is correct
- The formula for
deltais an exact algebraic identity for hown * Hchanges, and thelog1prewrite is also an identity. - Since
fis increasing andc <= n,delta >= 0. The update is a weighted average of non-negative values, so there is no cancellation in it. His bounded bylog2 K, so its magnitude never grows withn, and precision does not degrade for streams beyond10^7tokens.
Complexity
- Time:
O(1)amortized per operation (one dictionary lookup or insert and a fewlog1pcalls).get_entropyisO(1). - Space:
O(K)for the counts, plusO(1)scalars (and the output list).
Reference solution
import math
from typing import List, Optional
def track_entropy(operations: List[str], arguments: List[List[str]]) -> List[Optional[float]]:
counts = {}
n = 0
entropy = 0.0
result = []
ln2 = math.log(2.0)
for operation, args in zip(operations, arguments):
if operation == "add":
token = args[0]
old_count = counts.get(token, 0)
if n == 0:
counts[token] = 1
n = 1
entropy = 0.0
result.append(None)
continue
if old_count == n:
# Only one distinct token so far: entropy stays exactly 0.
increment = 0.0
elif old_count == 0:
# New token: f(n) - f(0) with f(0) = 0.
increment = (
math.log(n)
+ (n + 1) * math.log1p(1.0 / n)
) / ln2
else:
# f(n) - f(c) where f(x) = (x+1)ln(x+1) - x ln(x),
# evaluated without subtracting huge, nearly equal values.
gap = n - old_count
increment = (
math.log1p(gap / old_count)
+ (n + 1) * math.log1p(1.0 / n)
- (old_count + 1) * math.log1p(1.0 / old_count)
) / ln2
entropy = (n * entropy + increment) / (n + 1)
counts[token] = old_count + 1
n += 1
result.append(None)
elif operation == "get_entropy":
result.append(float(entropy))
else:
raise ValueError(f"unknown operation: {operation}")
return result