KatInterview

Incremental Entropy Tracker for Categorical Streams

Data Structure DesignAuto-graded · 24 test cases
MediumAuto-gradedData Structure Designstreamingentropyincremental-computation

Last 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.