Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

ML coding · Classic algorithms

Best decision-tree split by Gini impurity

Medium · Target 25 minutes · Python and NumPy

Given features X (n × d) and class labels y, find the split "xf ≤ t goes left" with the lowest weighted Gini impurity (nLGL + nRGR)/n, where G = 1 − Σc pc².

  • Candidate thresholds for a feature are the midpoints between consecutive distinct values of that feature.
  • Treat impurities within 10⁻¹² as equal. On a tie, prefer the lower feature index, then the lower threshold.
  • Return [feature, threshold, impurity]. If no feature has two distinct values, return [-1, 0.0, G] with G the impurity of the whole set.

Examples

Input X = [[1], [2], [3], [4]], y = [0, 0, 1, 1]

Output [0, 2.5, 0]

A perfect split at 2.5: both children are pure.

Input X = [[1, 5], [2, 5], [3, 6], [4, 6]], y = [0, 1, 0, 1]

Output [0, 1.5, 0.3333]

Nothing separates the classes. Thresholds 1.5 and 3.5 on feature 0 both give 1/3; the lower one wins.

Input X = [[7], [7], [7]], y = [0, 1, 1]

Output [-1, 0, 0.4444]

No threshold exists. Return −1 and the impurity of the whole set, 4/9.

Constraints

  • 1 ≤ n ≤ 10⁴, 1 ≤ d ≤ 50
  • Labels are integers
  • Threshold and impurity checked to 10⁻⁹

Hints

Hint 1

For one feature, sort the points by that feature. A threshold between positions i and i + 1 puts the first i + 1 points on the left.

Hint 2

Keep class counts for the left side and subtract from the totals for the right. Moving one point across is an O(1) update.

Hint 3

Skip positions where the next value is equal to the current one: no threshold separates equal values.

Where candidates go wrong

  • Using the data values themselves as thresholds, so that "≤ t" puts a shared value on one side or the other depending on how you wrote it.
  • Recomputing the class counts from scratch for every threshold: O(n²) per feature.
  • Weighting the children's impurities equally instead of by size.
  • Comparing impurities with a strict < and no tolerance, so that rounding decides the tie rule.
Console⌘/Ctrl + Enter runs

Python runs in your browser with NumPy. The first run downloads the runtime, which takes a few seconds.


Why interviewers ask it

Gradient-boosted trees still win most tabular problems, and quant research runs on tabular data. Interviewers ask for the split function because it is the whole tree in miniature, and because the efficient sweep separates candidates who think about complexity from those who do not.

The theory behind it is in the lesson k-means, kNN, PCA and decision trees from scratch.


Keep going