Single-Split Piecewise Constant Step Fit
Medium · Machine Learning · Software Engineer · Technical Screen
Problem Statement
Given an ordered sequence data of n floating-point measurements, fit a two-piece constant step model by choosing a single cut index k (0 <= k <= n - 2) that partitions the sequence into two non-empty contiguous slices:
- Left slice:
data[0 .. k](inclusive), predicted by its arithmetic averageleft_mean. - Right slice:
data[k + 1 .. n - 1](inclusive), predicted by its arithmetic averageright_mean.
The fitting error of cut k is the combined sum of squared residuals across both slices:
error(k) = sum_{i = 0..k} (data[i] - left_mean)^2 + sum_{i = k+1..n-1} (data[i] - right_mean)^2
Implement find_optimal_split(data) to return (k, left_mean, right_mean) for the cut k that achieves the smallest total squared residual. Whenever two or more cut indices yield the exact same minimum error, return the smallest index k.
def find_optimal_split(data: List[float]) -> Tuple[int, float, float]:
Examples
Example 1
- Input:
data = [2.0, 2.4, 8.0, 8.6] - Output:
(1, 2.2, 8.3) - Explanation: Cutting at
k = 1forms[2.0, 2.4](mean2.2, squared residual0.04 + 0.04 = 0.08) and[8.0, 8.6](mean8.3, squared residual0.09 + 0.09 = 0.18), giving total error0.26— far lower thank = 0(23.3867) ork = 2(22.5067).
Example 2
- Input:
data = [-4.0, -2.0, -3.0, 5.0, 7.0] - Output:
(2, -3.0, 6.0) - Explanation: Cutting at
k = 2separates[-4.0, -2.0, -3.0](mean-3.0, squared residual1 + 1 + 0 = 2.0) from[5.0, 7.0](mean6.0, squared residual1 + 1 = 2.0), achieving the minimum total error4.0.
Example 3
- Input:
data = [4.5, 4.5, 4.5] - Output:
(0, 4.5, 4.5) - Explanation: Both valid cuts (
k = 0andk = 1) produce zero squared residual on both slices, so the tie-breaker selects the earlier indexk = 0.
Constraints
2 <= len(data) <= 10^5- Every entry in
datais a finite floating-point number (potentially negative or shifted by a large constant offset). - Both slices
[0 .. k]and[k + 1 .. n - 1]must contain at least one element (0 <= k <= len(data) - 2). - Break exact minimum-error ties in favor of the smallest
k.
Step-by-step walkthrough
Understand the piecewise constant model
Given a sequence
dataofnfloating-point measurements (2 <= n <= 10^5), we choose a single cut indexk(0 <= k <= n - 2) to dividedatainto two non-empty contiguous slices:- Left slice:
data[0 .. k](lengthk + 1), approximated by its meanleft_mean. - Right slice:
data[k + 1 .. n - 1](lengthn - k - 1), approximated by its meanright_mean.
data = [2.0, 2.4, 8.0, 8.6], cut after k = 1: value 8.6 | o --- right_mean = 8.3 --- 8.0 | o | | 2.4 | o | <-- split after k = 1 2.0 | o | --- left_mean = 2.2 --- +-------------------------- i=0 i=1 i=2 i=3Because neither slice may be empty,
kranges from0throughn - 2. We return(best_k, left_mean, right_mean)minimizing the total Sum of Squared Errors (SSE):SSE(k) = sum_{i = 0..k} (data[i] - left_mean)^2 + sum_{i = k+1..n-1} (data[i] - right_mean)^2Whenever multiple cuts tie for the exact minimum SSE (for instance
[4.5, 4.5, 4.5], where every cut gives SSE0), the smallestkwins.- Left slice:
Why recomputing each split from scratch is too slow
There are
n - 1candidate cut indicesk. Slicingdata[:k+1]anddata[k+1:], computing both averages, and looping across allnvalues for eachkspendsO(n)work per cut andO(n^2)overall.For
n = 10^5,O(n^2)performs around10^10operations. Yet advancingktok + 1transfers only one element (data[k]) from the right slice to the left slice!Derive the O(1) segment SSE formula step by step
Consider any slice of
mvaluesx_1, ..., x_mwith sumS = sum(x)and squared sumQ = sum(x^2). Its mean ismu = S / m. Expanding(x - mu)^2and summing across allmentries gives:sum( (x - mu)^2 ) = sum( x^2 - 2 * mu * x + mu^2 ) = sum(x^2) - 2 * mu * sum(x) + m * mu^2 (pull constants out; mu^2 added m times) = Q - 2 * (S / m) * S + m * (S / m)^2 (substitute sum(x^2) = Q, sum(x) = S, mu = S / m) = Q - 2 * S^2 / m + S^2 / m = Q - S^2 / mThat algebraic identity means a slice's SSE depends only on
(length, seg_sum, seg_sq_sum)— never on rescanning the individual elements!def segment_sse(seg_sum: float, seg_sq_sum: float, length: int) -> float: """Return sum((x - mean)^2) for a segment using sum(x^2) - sum(x)^2 / length.""" return seg_sq_sum - (seg_sum * seg_sum) / lengthKeep floating-point arithmetic accurate
Evaluating
Q - S^2 / mdirectly in 64-bit IEEEfloat(~15–17 decimal digits of precision) runs into two numerical hazards:- Large offsets cancel leading digits: if
data = [10^9 + 9, 10^9 + 8, 10^9 + 19, 10^9 + 6], eachx^2is near10^18. BothQandS^2 / magree in their top 16 digits, so subtracting them erases the small variations needed to pickbest_k! - Rounding dust perturbs exact ties: for
[0.1, 0.1, 0.1](0.1is repeating in binary) or[-1, 2, 1, 4](exact SSE42 / 9at bothk = 0andk = 2),Q - S^2 / mcan differ by~10^-16across tied cuts and trick a strict<check into picking a largerk.
Two lightweight safeguards eliminate both issues:
- Center around the global mean (
shift = sum(data) / n): subtracting a constantshiftfrom every point shifts each slice's mean by that exact sameshift, leaving every(x - mean)^2identical while keepingQsmall and accurate. - Require an error drop exceeding
tolerance = 1e-10 * total_sq_sum: differences at floating-point noise scale (~10^-15 * total_sq_sum) count as ties, keeping the smallestk.
# Shifting every observation by a constant leaves each segment's SSE unchanged, # and centering around the overall mean prevents precision loss in sum(x^2) - sum(x)^2 / m. shift = sum(data) / n # total_sum, total_sq_sum: sum and sum of squares of all centered values (x - shift). total_sum = 0.0 total_sq_sum = 0.0 for x in data: centered = x - shift total_sum += centered total_sq_sum += centered * centered # Treat SSE differences smaller than floating-point rounding noise as ties so smaller k wins. tolerance = 1e-10 * total_sq_sum- Large offsets cancel leading digits: if
Sweep all split points in O(n) time
Now sweep
kfrom0throughn - 2:centered values: [ v_0, v_1, ..., v_k | v_{k+1}, ..., v_{n-1} ] \___________________/ \_____________________/ left_sum, left_sq_sum right_sum = total_sum - left_sum left_len = k + 1 right_sq_sum = total_sq_sum - left_sq_sum right_len = n - left_lenAt step
k, incorporatingv_kinto the left slice takes two additions (left_sum += centered,left_sq_sum += centered * centered), and subtracting fromtotal_sumandtotal_sq_sumgives the right slice's totals inO(1)time. Afterward, we computeleft_meanandright_meandirectly from the original unshifteddata.best_k = 0 best_sse = None # left_sum, left_sq_sum: running sum and sum of squares of centered data[0..k]. left_sum = 0.0 left_sq_sum = 0.0 # Valid splits are k = 0 .. n - 2 so both [0..k] and [k+1..n-1] contain at least 1 element. for k in range(n - 1): centered = data[k] - shift left_sum += centered left_sq_sum += centered * centered left_len = k + 1 right_sum = total_sum - left_sum right_sq_sum = total_sq_sum - left_sq_sum right_len = n - left_len total_sse = ( segment_sse(left_sum, left_sq_sum, left_len) + segment_sse(right_sum, right_sq_sum, right_len) ) if best_sse is None or total_sse < best_sse - tolerance: best_sse = total_sse best_k = k # Recompute both segment means directly on the original unshifted values. left_raw_sum = 0.0 for i in range(best_k + 1): left_raw_sum += data[i] right_raw_sum = 0.0 for i in range(best_k + 1, n): right_raw_sum += data[i] left_mean = left_raw_sum / (best_k + 1) right_mean = right_raw_sum / (n - best_k - 1)Walk through Example 1 step by step
Trace
data = [2.0, 2.4, 8.0, 8.6](n = 4):shift = (2.0 + 2.4 + 8.0 + 8.6) / 4 = 5.25- Centered values:
[-3.25, -2.85, 2.75, 3.35] total_sum = 0.0,total_sq_sum = 10.5625 + 8.1225 + 7.5625 + 11.2225 = 37.47
k left (len, sum, sq_sum) left SSE right (len, sum, sq_sum) right SSE total_sse 0 (1, -3.25, 10.5625) 0.00 (3, 3.25, 26.9075) 23.3867 23.3867 1 (2, -6.10, 18.6850) 0.08 (2, 6.10, 18.7850) 0.18 0.2600 <-- best_k = 1 2 (3, -3.35, 26.2475) 22.5067 (1, 3.35, 11.2225) 0.00 22.5067At
best_k = 1, the original left slice[2.0, 2.4]averages to4.4 / 2 = 2.2and[8.0, 8.6]averages to16.6 / 2 = 8.3, returning(1, 2.2, 8.3).Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def segment_sse(seg_sum: float, seg_sq_sum: float, length: int) -> float: """Return sum((x - mean)^2) for a segment using sum(x^2) - sum(x)^2 / length.""" return seg_sq_sum - (seg_sum * seg_sum) / length def find_optimal_split(data: List[float]) -> Tuple[int, float, float]: n = len(data) # Shifting every observation by a constant leaves each segment's SSE unchanged, # and centering around the overall mean prevents precision loss in sum(x^2) - sum(x)^2 / m. shift = sum(data) / n # total_sum, total_sq_sum: sum and sum of squares of all centered values (x - shift). total_sum = 0.0 total_sq_sum = 0.0 for x in data: centered = x - shift total_sum += centered total_sq_sum += centered * centered # Treat SSE differences smaller than floating-point rounding noise as ties so smaller k wins. tolerance = 1e-10 * total_sq_sum best_k = 0 best_sse = None # left_sum, left_sq_sum: running sum and sum of squares of centered data[0..k]. left_sum = 0.0 left_sq_sum = 0.0 # Valid splits are k = 0 .. n - 2 so both [0..k] and [k+1..n-1] contain at least 1 element. for k in range(n - 1): centered = data[k] - shift left_sum += centered left_sq_sum += centered * centered left_len = k + 1 right_sum = total_sum - left_sum right_sq_sum = total_sq_sum - left_sq_sum right_len = n - left_len total_sse = ( segment_sse(left_sum, left_sq_sum, left_len) + segment_sse(right_sum, right_sq_sum, right_len) ) if best_sse is None or total_sse < best_sse - tolerance: best_sse = total_sse best_k = k # Recompute both segment means directly on the original unshifted values. left_raw_sum = 0.0 for i in range(best_k + 1): left_raw_sum += data[i] right_raw_sum = 0.0 for i in range(best_k + 1, n): right_raw_sum += data[i] left_mean = left_raw_sum / (best_k + 1) right_mean = right_raw_sum / (n - best_k - 1) return best_k, left_mean, right_mean✅ Submit now — all tests should pass.
Intuition & how it works
Think of piecewise constant regression (approximating a series with flat horizontal steps rather than a sloped line) as fitting a two-step staircase to noisy sensor readings: points 0 .. k rest on a left step of height left_mean, and points k + 1 .. n - 1 rest on a right step of height right_mean. We score each candidate cut k by its Sum of Squared Errors (SSE) — adding (reading - step_height)^2 across every point — and sweep k from left to right to locate the cut with the smallest total error.
Rescanning all n readings to compute both means and squared residuals at every one of the n - 1 cuts takes O(n^2) time (~10^10 operations when n = 10^5). Expanding (x - mean)^2 algebraically rewrites any slice's SSE as sum(x^2) - sum(x)^2 / length, letting us maintain running prefix sums (cumulative totals updated in O(1) as k steps right by 1) of the values and their squares so every cut is evaluated in O(1) time.
One floating-point pitfall must be handled: when readings hover around a large baseline (say 10^9), sum(x^2) and sum(x)^2 / length agree in almost every leading digit, and subtracting them causes catastrophic cancellation — wiping out the low-order digits where the real differences live. Subtracting the global average shift = sum(data) / n centers the values around 0 without changing any slice's SSE, while requiring an improvement past a tiny relative tolerance prevents rounding dust from breaking exact ties away from the smallest k.
Trace data = [2.0, 2.4, 8.0, 8.6] (shift = 5.25, centered [-3.25, -2.85, 2.75, 3.35], total_sq_sum = 37.47):
1. k = 0 ([-3.25] vs [-2.85, 2.75, 3.35]): left SSE is 10.5625 - 10.5625 / 1 = 0.0; right SSE is 26.9075 - 3.25^2 / 3 ≈ 23.3867; total ≈ 23.3867.
2. k = 1 ([-3.25, -2.85] vs [2.75, 3.35]): left SSE is 18.685 - (-6.10)^2 / 2 = 0.08; right SSE is 18.785 - 6.10^2 / 2 = 0.18; total 0.26 (new best!).
3. k = 2 ([-3.25, -2.85, 2.75] vs [3.35]): total SSE is ≈ 22.5067 + 0.0, so best_k = 1 wins with original slice means 2.2 and 8.3.
Complexity
- Time:
O(n), wheren = len(data). Computingshift, accumulatingtotal_sumandtotal_sq_sum, sweepingkacross0 .. n - 2inO(1)per cut, and summing the two winning slices each scan the array linearly once. - Space:
O(1)auxiliary space. Centering values on the fly and summing the final slices with plain index loops uses only a fixed handful of scalar variables regardless ofn.
Edge cases
- Minimum length (
n = 2, e.g.[5, -1]):k = 0is the sole valid cut, placing one element per slice with SSE0and returning(0, 5.0, -1.0). - Constant series (
[4.5, 4.5, 4.5]or[0.1, 0.1, 0.1]): all cuts have true SSE0; centering plustolerancekeeps binary rounding dust on0.1from drifting pastk = 0. - Exact ties across distinct cuts (
[1, 2, 1]or[-1, 2, 1, 4]): when two cuts have identical mathematical SSE,total_sse < best_sse - toleranceretains the smallerk. - Large baseline offset (
[1e9 + 9, 1e9 + 8, 1e9 + 19, 1e9 + 6]): centering strips out10^9before squaring sosum(x^2)remains small and accurate, while final means are computed on rawdata. - Single jump at index
0orn - 1: covered cleanly sincerange(n - 1)checks bothk = 0andk = n - 2.
Common mistakes
- Allowing
k == n - 1: leaves the right slice empty (right_len == 0) and raisesZeroDivisionError. - Computing
sum(x^2) - sum(x)^2 / mon uncentered values: loses precision silently whenevermean^2dwarfs the slice variance. - Comparing with strict
total_sse < best_sseand zero tolerance: 1-ULP rounding differences inS^2 / 3break exact ties toward largerk. - Returning centered means without restoring
shift: shifts both output averages down byshiftunless computed from rawdata. - Returning
k + 1instead ofk:kis the inclusive last index of the left slice[0 .. k].
Alternative approaches
- Two-way Welford updates: Welford's algorithm updates a running mean and running SSE incrementally (
delta = x - mean; mean += delta / count; sse += delta * (x - mean)) without squaring raw magnitudes. Storing suffix SSEs in anO(n)list and sweeping prefix SSEs forward avoidsQ - S^2 / mat the cost ofO(n)extra space. - Maximizing between-slice sum of squares (
left_sum^2 / left_len + right_sum^2 / right_len): sinceleft_sq_sum + right_sq_sum == total_sq_sumis invariant acrossk, minimizing total SSE is equivalent to maximizingS_L^2 / L + S_R^2 / Ron centered data.
Follow-up questions
- How do the time and space bounds change if we partition the series using two split indices (three constant segments) instead of one? Two cuts divide
datainto three non-empty slices[0..i],[i+1..j], and[j+1..n-1]. PrecomputingO(n)prefix arrays of centered sums and squared sums still evaluates any slice's SSE inO(1)time, so checking all(i, j)pairs runs inO(n^2)time andO(n)space. More generally,Kconstant segments (K - 1cuts) can be solved exactly via dynamic programming — building optimalc-segment prefixes from(c - 1)-segment prefixes — inO(K * n^2)time, or approximated faster via greedy binary segmentation (O(K * n)) or pruned algorithms like PELT. - What floating-point precision pitfalls arise when evaluating
sum(x^2) - sum(x)^2 / mon long or large-magnitude series, and how do you mitigate them? First, subtracting two huge nearly equal floats causes catastrophic cancellation whenever the mean vastly exceeds the standard deviation, sometimes even yielding tiny negative SSEs. Second, summing10^5or more floats sequentially accumulates rounding drift, and magnitudes above~1.34 * 10^154overflow IEEE-754 double precision upon squaring. Mitigate all three by centering around a reference mean (and scaling by the max centered magnitude when values are huge), summing withmath.fsumor Kahan compensated summation (carrying a running correction term for lost low-order bits), or tracking SSE via Welford's recurrence. - In an unbounded live data stream where retaining every past observation is infeasible, how could you approximate or track a good split point? Because each new observation changes the right-slice mean for every historical index
k, tracking the exact optimum across alltpast positions requiresO(t)memory (no better than keeping prefix sums per position). To cap memory at sublinear orO(1)space, aggregate historical arrivals intoBsummary buckets storing(count, sum, sq_sum)and evaluate cuts only at bucket boundaries (O(B)space and update work), maintain a sliding window of the most recentWpoints, or run an online change-point detector such as CUSUM (a constant-memory sequential statistic that accumulates deviations from a baseline mean to flag regime shifts in real time).
Follow-up questions
- How do the time and space bounds change if we partition the series using two split indices (three constant segments) instead of one?
- What floating-point precision pitfalls arise when evaluating `sum(x^2) - sum(x)^2 / m` on long or large-magnitude series, and how do you mitigate them?
- In an unbounded live data stream where retaining every past observation is infeasible, how could you approximate or track a good split point?
Similar questions
- Post-Hoc Confidence Calibration with Temperature Scaling
- End-to-End Modeling Strategy for Skewed Binary Labels
- Presenting Your Highest-Impact ML Project
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift