Best Single-Breakpoint Step-Function Fit
Arrays & HashingAuto-graded · 23 test casesLast updated
Tests whether a candidate can derive an O(n) prefix-aggregate sweep to find the one split index that minimizes total squared error for a two-segment constant model.
Problem
You have a sequence of n real-valued measurements stored in a list called readings. You want to approximate this sequence with the simplest possible step function: a constant value for every position up to and including some index, and a different constant value for every position after it.
Formally, pick a breakpoint index b in the range [0, n-2]. This divides readings into:
- a left segment
readings[0 … b](inclusive), represented by its mean, and - a right segment
readings[b+1 … n-1](inclusive), represented by its mean.
The quality of a fit is measured by the total sum of squared errors (SSE): for each position, square the difference between the measurement and its segment mean, then add those values up.
Your task is to return the breakpoint index b that produces the smallest total SSE, together with the left-segment mean and right-segment mean at that breakpoint.
If two breakpoints produce exactly the same SSE (within floating-point arithmetic), return the one with the smaller index.
Return value
A tuple (b, left_mean, right_mean) where:
bis the chosen breakpoint index (integer),left_meanis the mean ofreadings[0 … b](float),right_meanis the mean ofreadings[b+1 … n-1](float).
Constraints
2 <= n <= 10^5, wheren = len(readings)- Each element of
readingsis a finite floating-point or integer value. - The left segment always contains at least one element and the right segment always contains at least one element, so valid breakpoints run from index
0to indexn-2.
Examples
Example 1
Input: find_optimal_split([1, 1.2, 5, 5.2])
Output: [1, 1.1, 5.1]
Example 2
Input: find_optimal_split([10, 20, 30, 40])
Output: [1, 15, 35]
Example 3
Input: find_optimal_split([3, 3, 3, 3])
Output: [0, 3, 3]
Hints
Hint 1
Computing each segment's mean and SSE from scratch at every candidate breakpoint costs O(n) per breakpoint, giving O(n²) overall. Think about how to maintain running totals as you scan left to right so each breakpoint costs O(1).
Hint 2
For a segment with count c, element sum S, and sum of squares Q, the SSE equals Q − S²/c. You only need three numbers per segment to evaluate the fit without touching individual elements again.
Hint 3
Precompute the grand sum and grand sum of squares once. As you extend the left segment one element at a time, the right segment's sum and sum of squares are just the grand totals minus the left totals — no second pass or extra arrays needed.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
From O(n²) to O(n)
The naïve strategy recomputes both segment means and their SSEs from scratch at every candidate breakpoint. With up to n-1 breakpoints and O(n) work each, that is O(n²) — too slow for n = 10^5.
The key observation is that you do not need the raw values to evaluate a segment's SSE. Given three aggregates — element count c, sum S, and sum of squares Q — the SSE is:
SSE = Q − S² / c
This identity comes from expanding Σ(x − mean)² with mean = S/c:
Σ(x − S/c)² = Q − 2(S/c)·S + c·(S/c)² = Q − S²/c
Because the right segment's aggregates are just the grand totals minus the left totals, a single left-to-right sweep is enough:
- Precompute
total_sumandtotal_sqin one pass — O(n). - Walk through every valid breakpoint
kfrom0ton-2. At each step, addreadings[k]to runningleft_sumandleft_sq. Derive the right aggregates by subtraction. Evaluate both segment SSEs in O(1) and track the minimum.
Total time: O(n). Extra space: O(1) — no prefix arrays are stored.
Why this is correct
- The mean minimises squared error for any fixed set of points (its derivative is zero), so using the segment mean as the constant is always optimal for a given breakpoint.
- The algebraic identity is exact, so evaluating every breakpoint with it gives the true SSE for each split.
- The loop covers all valid breakpoints (
0ton-2), guaranteeing both segments are non-empty, so the global minimum is found. - Ties go to the earlier index because the update uses a strict
<comparison.
Edge cases
n = 2: Onlyk = 0is checked. Each segment has one element, so both SSEs are 0.- All identical values: Every breakpoint has SSE 0 (or a tiny floating-point residue). The first breakpoint wins due to the strict comparison.
- Integer input:
left_sumstarts as0.0and Python's/is true division, so means are always floats.
Complexity
| Time | O(n) |
| Space | O(1) extra |
Reference solution
from typing import List, Tuple
def find_optimal_split(readings: List[float]) -> Tuple[int, float, float]:
n = len(readings)
total_sum = sum(readings)
total_sq = sum(x * x for x in readings)
left_sum = 0.0
left_sq = 0.0
best_k = 0
best_sse = float("inf")
best_left_mean = 0.0
best_right_mean = 0.0
for k in range(n - 1):
value = readings[k]
left_sum += value
left_sq += value * value
left_count = k + 1
right_count = n - left_count
right_sum = total_sum - left_sum
right_sq = total_sq - left_sq
left_mean = left_sum / left_count
right_mean = right_sum / right_count
sse = (left_sq - left_sum * left_sum / left_count
+ right_sq - right_sum * right_sum / right_count)
if sse < best_sse:
best_sse = sse
best_k = k
best_left_mean = left_mean
best_right_mean = right_mean
return best_k, best_left_mean, best_right_mean