Sorted-Order Best Decision Tree Split With Running Statistics
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement two functions that find the best decision tree split on a single continuous feature: `best_split_classification(x, y, criterion="gini", min_samples_leaf=1)` and `best_split_regression(x, y, min_samples_leaf=1)`. Each returns `(threshold, gain)` for the best split, with `x <= threshold` going to the left child and `x > threshold` going to the right. The search must run in $O(N \log N)$: sort once, then update the child statistics in $O(1)$ per candidate threshold.
Requirements:
- Candidate thresholds are midpoints between consecutive distinct sorted `x` values. Both children must contain at least `min_samples_leaf` samples.
- Gain is the parent impurity minus `(n_L * imp_L + n_R * imp_R) / n`. Classification supports `"gini"` and `"entropy"` (log base 2), and any other criterion raises `ValueError`. Regression uses population variance (`ddof=0`).
- When gains are equal within `1e-12`, choose the lowest threshold.
- When no split is valid (fewer than 2 samples, a constant feature, or a `min_samples_leaf` that is too large), return `(None, 0.0)`.
- Return Python `float`s, with the gain clamped to be at least 0. Class labels may be arbitrary values.
Example:
```python
best_split_classification([4., 1., 3., 2.], [1, 0, 1, 0], "gini") # (2.5, 0.5)
best_split_classification([4., 1., 3., 2.], [1, 0, 1, 0], "entropy") # (2.5, 1.0)
best_split_classification([1., 2., 3., 4.], [0, 1, 1, 1], min_samples_leaf=2) # (2.5, 0.125)
best_split_regression([6., 1., 5., 2., 4., 3.], [5., 1., 5., 1., 5., 1.]) # (3.5, 4.0)
```
```hint Carry statistics forward
Moving from one candidate threshold to the next in sorted order shifts a sample from the right child to the left. Decide which per-child quantities you can keep as running totals so each child's impurity comes out of a few arithmetic operations.
```
```hint Variance from sums
A child's variance can be written from its count, the sum of its targets and the sum of their squares. Check what that formula does in floating point when the targets have a large mean and a small spread.
```
```hint Duplicate values
Sorting puts equal `x` values next to each other, and no threshold can separate them. Work out how to skip those positions while keeping the sweep linear.
```
### Constraints & Assumptions
- n is between 1 and 200,000, and `x` and `y` have equal length. `x` may contain duplicates.
- All values are finite.
- Results must match a brute-force search (and, for regression, a scikit-learn depth-1 regressor) to about `1e-7` relative tolerance.
### What a Strong Answer Covers
- One sort followed by a linear sweep that updates the child statistics as each sample crosses from the right child to the left, with an honest total cost, including any dependence on the number of classes.
- Correct handling of duplicate `x` values, `min_samples_leaf`, and the no-valid-split return value.
- Gini, base-2 entropy and population variance computed from the running statistics, with `ValueError` for an unknown criterion.
- The `1e-12` tie rule, the clamped non-negative gain and Python `float` return types.
- Numerical stability of the variance formula for targets with a large mean.
### Follow-up Questions
- Running sums of `y` and `y²` can lose precision. How do you guard against it?
- How would you scale this to many features and millions of rows?
- How would you add sample weights?
Overview: Find the best decision tree threshold on one continuous feature in O(N log N) by sorting once and sweeping with running statistics, for Gini, entropy and variance criteria. It tests prefix-sum updates, handling of duplicate values and tie rules, and the numerical stability of variance computed from sums.