Sliding Window Median
Real-world version: Rolling Frame MiddleThe statement here is our own: the same inputs, outputs and technique.
A monitor logs one integer per tick into readings. A frame of span consecutive readings
starts at the left end and slides right one tick at a time, so the first frame covers
positions 0 through span - 1, the next covers 1 through span, and so on until the
frame reaches the right end.
The middle value of a frame is defined on the frame's readings put in sorted order. When
span is odd it is the single reading in the centre. When span is even it is the mean of
the two central readings, so it can land halfway between two integers and must be reported
that way, for example 5.5.
Return the middle value of every frame, in the order the frames appear.
Examples
Example 1
- Input
- readings = [4,1,7,1,8], span = 3
- Output
- [4.0,1.0,7.0]
The three frames sort to [1,4,7], [1,1,7] and [1,7,8], and the centre entry of each is 4, 1 and 7.
Example 2
- Input
- readings = [6,2,9,4], span = 2
- Output
- [4.0,5.5,6.5]
Every frame holds two readings, so each answer is their mean: 4 for 6 and 2, 5.5 for 2 and 9, and 6.5 for 9 and 4.
Constraints
- 1 <= span <= readings.length <= 10^5
- -2^31 <= readings[i] <= 2^31 - 1
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def rolling_medians(readings: list[int], span: int) -> list[float]:public double[] rollingMedians(int[] readings, int span)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 2 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Find X-Sum of All K-Long Subarrays IReal-world version: The Loudest Tracks in Every StretchEasy
- Smallest Range Covering Elements from K ListsReal-world version: Tightest Gauge BandHard
- Contains Duplicate IIReal-world version: Nearby Repeat TrimEasy
- Longest Harmonious SubsequenceReal-world version: Widest One-Degree SampleEasy