KatInterview

Running Bit-Entropy of a Token Feed with Stable Updates

Data Structure DesignAuto-graded · 22 test cases
HardAuto-gradedData Structure Designstreamingnumerical-stabilityhash-map

Last 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 is None.
    • for "get_entropy" it is []. The result is the entropy, as a float in bits, of all tokens added so far.
  • Any other operation name must raise ValueError.
  • The returned list has the same length as operations.

Accuracy and cost requirements

  • Each add and each get_entropy must take O(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.9999999999999999 versus 1.0) are fine.

Constraints

  • The total number of tokens N may exceed 10^7.
  • The number of distinct tokens K may be up to 10^5.
  • Memory beyond the returned list must be O(K).
  • Tokens are arbitrary strings compared by exact equality.
  • get_entropy on an empty stream returns 0.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.