Sliding Window Median of Mid Prices With Lazy Deletion

Last updated: November 29, 2026

Quick Overview

Implement a streaming structure that receives mid prices one at a time and, once k prices have arrived, returns the median of the last k on every update in O(log k) amortized time.

Trexquant
Coding & Algorithms
Software Engineer
Trexquant
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Implement a streaming structure that receives mid prices one at a time and, once k prices have arrived, returns the median of the last k on every update in O(log k) amortized time.

A rolling median is a robust filter for noisy quotes and bad ticks in market data pipelines. The interviewer wants a two-heap design with correct removal of expired elements and a clear invariant, since this is where most candidates break.

What the Interviewer Expects
  • Uses a max-heap and min-heap with a stated size invariant
  • Explains why heaps cannot delete arbitrary items and uses lazy deletion
  • Keeps logical sizes separate from physical heap sizes
  • Prunes heap tops after every removal or rebalance
  • Verifies against a brute-force median on random input
Key Topics to Cover
two heaps
lazy deletion
sliding window
streaming statistics
invariants
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would an order-statistics tree or sorted list with bisect compare?
  • How would you make the memory bounded since the delayed map can grow?
  • What if you need the 10th and 90th percentiles too?
  • How does this behave with many duplicate prices?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

push(x) returns None until k values have arrived, then the median of the last k values (mean of the middle two when k is even). Target O(log k) amortized per call....

High-Level Design

lo is a max-heap of the smaller half, hi a min-heap of the larger half. Invariant on logical sizes: lo_size == hi_size or lo_size == hi_size + 1, so the median is lo's top or the average of ...


Submit Your Answer
Markdown supported

Related Questions