Incremental Entropy Tracker for Categorical Streams
Data Structure DesignAuto-graded · 24 test casesLast updated
Build a data structure that efficiently computes Shannon entropy after each new categorical observation arrives.
You are processing a stream of categorical observations that arrive one at a time. After receiving each observation, you must compute the Shannon entropy of the distribution formed by all observations seen so far.
Shannon entropy is defined as:
H = -Σ(p_i × ln(p_i))
where p_i represents the proportion of observations belonging to category i, and ln is the natural logarithm.
Write a function that accepts a list of categorical observations (represented as strings) and returns a list of entropy values, where the i-th value is the entropy after processing the first i observations.
Important details:
- When only one observation has been seen, all probability mass is on a single category, so the entropy is
0. - Categories are arbitrary strings and may appear in any order.
- Use the natural logarithm (base e).
- Your solution must not re-compute entropy from scratch after each observation; use incremental updates.
Constraints
- 1 ≤ len(observations) ≤ 10⁵
- Each observation is a non-empty string
- Categories are hashable identifiers
- Minor floating-point precision differences are acceptable
Examples
Example 1
Input: compute_streaming_entropy(['a'])
Output: [0]
Example 2
Input: compute_streaming_entropy(['a', 'a', 'b'])
Output: [0, 0, 0.636514168294813]
Example 3
Input: compute_streaming_entropy(['red', 'blue', 'red', 'green', 'blue'])
Output: [0, 0.6931471805599453, 0.636514168294813, 1.0397207708399179, 1.0549201679861442]
Example 4
Input: compute_streaming_entropy(['x', 'y', 'z', 'x', 'y', 'z'])
Output: [0, 0.6931471805599453, 1.0986122886681098, 1.0397207708399179, 1.0549201679861442, 1.0986122886681096]
Hints
Hint 1
Instead of storing probabilities, track integer counts for each category—they're easier to update incrementally.
Hint 2
Rewrite the entropy formula in terms of counts rather than probabilities: H = ln(n) - (1/n)×Σ(c_i × ln(c_i)), where n is the total count and c_i is the count for category i.
Hint 3
Maintain a running sum of c_i × ln(c_i) across all categories. When a category's count changes from c to c+1, subtract the old term and add the new term.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The naive approach would recompute entropy from scratch after each observation by iterating through all category counts, which takes O(k) time per observation where k is the number of distinct categories seen so far.
Instead, we derive an incremental update formula. Start with the standard entropy definition:
H = -Σ(p_i × ln(p_i))
where p_i = c_i / n, with c_i being the count of category i and n the total observations.
Substitute and rearrange:
H = -Σ((c_i / n) × ln(c_i / n))
= -Σ((c_i / n) × (ln(c_i) - ln(n)))
= -Σ((c_i / n) × ln(c_i)) + Σ((c_i / n) × ln(n))
= -(1/n) × Σ(c_i × ln(c_i)) + ln(n) × (Σc_i / n)
= ln(n) - (1/n) × Σ(c_i × ln(c_i))
This reformulation expresses entropy using only integer counts and a single sum term Σ(c_i × ln(c_i)).
Incremental update: Maintain a hash map of category counts and a running accumulator for Σ(c_i × ln(c_i)). When category x arrives:
- Look up its previous count
c_old(0 if new) - Increment to
c_new = c_old + 1 - Remove the old contribution: subtract
c_old × ln(c_old)from the sum (ifc_old > 0) - Add the new contribution: add
c_new × ln(c_new)to the sum - Increment the total count
n - Compute
H = ln(n) - sum / n
Each observation is processed in O(1) expected time (hash map lookup/update), giving O(m) total time for m observations.
Edge case: When only one observation exists, the formula yields ln(1) - (1 × ln(1)) / 1 = 0 - 0 = 0, which is correct (no uncertainty). We clamp negative values to 0 to handle floating-point rounding.
Complexity
- Time: O(m) for m observations, with O(1) expected time per observation
- Space: O(k) where k is the number of distinct categories
Solution
import math
from typing import List
def compute_streaming_entropy(observations: List[str]) -> List[float]:
category_counts = {}
total = 0
sum_c_ln_c = 0.0
entropies = []
for obs in observations:
prev_count = category_counts.get(obs, 0)
curr_count = prev_count + 1
category_counts[obs] = curr_count
total += 1
if prev_count > 0:
sum_c_ln_c -= prev_count * math.log(prev_count)
sum_c_ln_c += curr_count * math.log(curr_count)
h = math.log(total) - sum_c_ln_c / total
entropies.append(h if h > 0.0 else 0.0)
return entropies