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 average left_mean.
  • Right slice: data[k + 1 .. n - 1] (inclusive), predicted by its arithmetic average right_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 = 1 forms [2.0, 2.4] (mean 2.2, squared residual 0.04 + 0.04 = 0.08) and [8.0, 8.6] (mean 8.3, squared residual 0.09 + 0.09 = 0.18), giving total error 0.26 — far lower than k = 0 (23.3867) or k = 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 = 2 separates [-4.0, -2.0, -3.0] (mean -3.0, squared residual 1 + 1 + 0 = 2.0) from [5.0, 7.0] (mean 6.0, squared residual 1 + 1 = 2.0), achieving the minimum total error 4.0.

Example 3

  • Input: data = [4.5, 4.5, 4.5]
  • Output: (0, 4.5, 4.5)
  • Explanation: Both valid cuts (k = 0 and k = 1) produce zero squared residual on both slices, so the tie-breaker selects the earlier index k = 0.

Constraints

  • 2 <= len(data) <= 10^5
  • Every entry in data is 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

  1. Understand the piecewise constant model

    Given a sequence data of n floating-point measurements (2 <= n <= 10^5), we choose a single cut index k (0 <= k <= n - 2) to divide data into two non-empty contiguous slices:

    • Left slice: data[0 .. k] (length k + 1), approximated by its mean left_mean.
    • Right slice: data[k + 1 .. n - 1] (length n - k - 1), approximated by its mean right_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=3
    

    Because neither slice may be empty, k ranges from 0 through n - 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)^2
    

    Whenever multiple cuts tie for the exact minimum SSE (for instance [4.5, 4.5, 4.5], where every cut gives SSE 0), the smallest k wins.

  2. Why recomputing each split from scratch is too slow

    There are n - 1 candidate cut indices k. Slicing data[:k+1] and data[k+1:], computing both averages, and looping across all n values for each k spends O(n) work per cut and O(n^2) overall.

    For n = 10^5, O(n^2) performs around 10^10 operations. Yet advancing k to k + 1 transfers only one element (data[k]) from the right slice to the left slice!

  3. Derive the O(1) segment SSE formula step by step

    Consider any slice of m values x_1, ..., x_m with sum S = sum(x) and squared sum Q = sum(x^2). Its mean is mu = S / m. Expanding (x - mu)^2 and summing across all m entries 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 / m
    

    That 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) / length
    
  4. Keep floating-point arithmetic accurate

    Evaluating Q - S^2 / m directly in 64-bit IEEE float (~15–17 decimal digits of precision) runs into two numerical hazards:

    1. Large offsets cancel leading digits: if data = [10^9 + 9, 10^9 + 8, 10^9 + 19, 10^9 + 6], each x^2 is near 10^18. Both Q and S^2 / m agree in their top 16 digits, so subtracting them erases the small variations needed to pick best_k!
    2. Rounding dust perturbs exact ties: for [0.1, 0.1, 0.1] (0.1 is repeating in binary) or [-1, 2, 1, 4] (exact SSE 42 / 9 at both k = 0 and k = 2), Q - S^2 / m can differ by ~10^-16 across tied cuts and trick a strict < check into picking a larger k.

    Two lightweight safeguards eliminate both issues:

    • Center around the global mean (shift = sum(data) / n): subtracting a constant shift from every point shifts each slice's mean by that exact same shift, leaving every (x - mean)^2 identical while keeping Q small 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 smallest k.
        # 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
    
  5. Sweep all split points in O(n) time

    Now sweep k from 0 through n - 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_len
    

    At step k, incorporating v_k into the left slice takes two additions (left_sum += centered, left_sq_sum += centered * centered), and subtracting from total_sum and total_sq_sum gives the right slice's totals in O(1) time. Afterward, we compute left_mean and right_mean directly from the original unshifted data.

        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)
    
  6. 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.5067
    

    At best_k = 1, the original left slice [2.0, 2.4] averages to 4.4 / 2 = 2.2 and [8.0, 8.6] averages to 16.6 / 2 = 8.3, returning (1, 2.2, 8.3).

  7. 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), where n = len(data). Computing shift, accumulating total_sum and total_sq_sum, sweeping k across 0 .. n - 2 in O(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 of n.

Edge cases

  • Minimum length (n = 2, e.g. [5, -1]): k = 0 is the sole valid cut, placing one element per slice with SSE 0 and 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 SSE 0; centering plus tolerance keeps binary rounding dust on 0.1 from drifting past k = 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 - tolerance retains the smaller k.
  • Large baseline offset ([1e9 + 9, 1e9 + 8, 1e9 + 19, 1e9 + 6]): centering strips out 10^9 before squaring so sum(x^2) remains small and accurate, while final means are computed on raw data.
  • Single jump at index 0 or n - 1: covered cleanly since range(n - 1) checks both k = 0 and k = n - 2.

Common mistakes

  • Allowing k == n - 1: leaves the right slice empty (right_len == 0) and raises ZeroDivisionError.
  • Computing sum(x^2) - sum(x)^2 / m on uncentered values: loses precision silently whenever mean^2 dwarfs the slice variance.
  • Comparing with strict total_sse < best_sse and zero tolerance: 1-ULP rounding differences in S^2 / 3 break exact ties toward larger k.
  • Returning centered means without restoring shift: shifts both output averages down by shift unless computed from raw data.
  • Returning k + 1 instead of k: k is 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 an O(n) list and sweeping prefix SSEs forward avoids Q - S^2 / m at the cost of O(n) extra space.
  • Maximizing between-slice sum of squares (left_sum^2 / left_len + right_sum^2 / right_len): since left_sq_sum + right_sq_sum == total_sq_sum is invariant across k, minimizing total SSE is equivalent to maximizing S_L^2 / L + S_R^2 / R on 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 data into three non-empty slices [0..i], [i+1..j], and [j+1..n-1]. Precomputing O(n) prefix arrays of centered sums and squared sums still evaluates any slice's SSE in O(1) time, so checking all (i, j) pairs runs in O(n^2) time and O(n) space. More generally, K constant segments (K - 1 cuts) can be solved exactly via dynamic programming — building optimal c-segment prefixes from (c - 1)-segment prefixes — in O(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 / m on 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, summing 10^5 or more floats sequentially accumulates rounding drift, and magnitudes above ~1.34 * 10^154 overflow 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 with math.fsum or 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 all t past positions requires O(t) memory (no better than keeping prefix sums per position). To cap memory at sublinear or O(1) space, aggregate historical arrivals into B summary 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 recent W points, 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

Similar questions

More NewsBreak interview questions

All 4 NewsBreak questions →