Code RoomGini impurity
MediumPrep Room Coding #1546

Gini impurity

CodingML systemsAlgorithms & data structuresMid–Senior~18 min

Compute the Gini impurity of a list of class labels (integers or strings). Gini impurity = 1 - sum over each class of (p_class)^2, where p_class is that class's fraction of the labels. A pure node (all one class) has impurity 0. The input list is non-empty. Round the result to 6 decimal places.

Implement
gini_impurity(labels: list[int]) → float
Examples
in[[0,0,1,1]]out0.5
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
[[0,0,1,1]]0.5not run yetsample