Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Real-Time Moving Median

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Real-Time Moving Median. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Google Pixel sensor services receive a continuous sequence of integer readings. For every complete sliding window of window_size consecutive readings, return its median as soon as the window is available.

Use two heaps to support insertion and deletion efficiently. If a window contains an even number of readings, define its median as the average of the two middle values. Return medians in the same order that the windows appear. Do not return a value until the first complete window has been received.

Formal Specification

Implement moving_median(readings, window_size).

  • Input: readings, a list of integers, and window_size, a positive integer.
  • Output: A list of numbers containing the median for every contiguous window of length window_size. Integer medians should remain integers; even-sized windows may produce floating-point values.

Constraints

  • 1 <= window_size <= len(readings) <= 10^5
  • -10^9 <= readings[i] <= 10^9
  • Duplicate readings are allowed.
  • Even-sized windows return the arithmetic average of the two middle values.

Function Signature

def moving_median(readings, window_size):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output