Code RoomShannon entropy
MediumPrep Room Coding #1547

Shannon entropy

CodingML systemsMid–Senior~18 min

Compute the Shannon entropy (in bits, base-2) of a list of class labels. Entropy = -sum over each class of p * log2(p), where p is the class's fraction. By convention a class contributing p = 0 adds nothing, and a pure single-class list has entropy 0. The input list is non-empty. Round the result to 6 decimal places.

Implement
entropy(labels: list[str]) → float
Examples
in[["a","a","b","b"]]out1
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

0:00 of about 18 min
InputExpectedGot
[["a","a","b","b"]]1not run yetsample