KatInterview

Best Single-Breakpoint Step-Function Fit

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingarraysmathprefix-sums

Last 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:

  • b is the chosen breakpoint index (integer),
  • left_mean is the mean of readings[0 … b] (float),
  • right_mean is the mean of readings[b+1 … n-1] (float).

Constraints

  • 2 <= n <= 10^5, where n = len(readings)
  • Each element of readings is 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 0 to index n-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.