Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Implement a Data Structure or Algorithm

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

Your question is Implement a Data Structure or Algorithm. 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

Rain processes a stream of transfer amounts and needs the median amount for every consecutive window of size k. Implement an efficient algorithm that supports both adding the newest amount and removing the amount that leaves the window.

Formal Specification

Given an integer array amounts and an integer k, return an array containing the median of every contiguous subarray of length k. For an odd-sized window, the median is its middle value after sorting. For an even-sized window, return the arithmetic mean of the two middle values. Results may contain integers or floating-point values.

Your solution should avoid sorting every window independently.

Constraints

  • 1 <= k <= len(amounts) <= 10^5
  • -10^9 <= amounts[i] <= 10^9
  • Duplicate amounts are allowed.
  • Return exactly len(amounts) - k + 1 medians.

Function Signature

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