PracticeLevel 5: AlgorithmsEx 109. Running median
0/150 Solved(0%)
Level 5Exercise #109

Running median

Return the median after each streamed number using two heaps.

What you’ll practice

This Level 5 exercise focuses on two heaps in the Algorithms curriculum. Solve the challenge prompt above using clear, idiomatic Python and the relevant language or standard-library tools.

Relevant Python reference: heapq — Heap queue algorithm.

Sample Test Cases

Example #1
Input:running_medians([2,1,5])
Output:[2.0,1.5,2.0]

Further Reading

Reference Solution

Reveal Reference Solution
def running_medians(values: list[int]) -> list[float]:
import heapq
low, high, result = [], [], []
for value in values:
heapq.heappush(low, -value)
heapq.heappush(high, -heapq.heappop(low))
if len(high) > len(low): heapq.heappush(low, -heapq.heappop(high))
result.append(float(-low[0]) if len(low) > len(high) else (-low[0]+high[0])/2)
return result
Pro Tips & Keyboard Shortcuts
Color Theme
Ctrl + K then T

Open VS Code Color Theme Quick Pick to select from 20 dark and light themes.

Editor SettingsCtrl + K

Open practice settings drawer to toggle line numbers, indenting, font size & hints.

Search MenuCtrl + /

Expand sidebar menu, focus search bar, and highlight search text instantly.

Focus Code Editor
Esc or Ctrl + `

Instantly highlight and focus code editor from anywhere, restoring cursor right where you left off.

Normal ViewEsc

Collapse sidebar and close all popups or settings drawers for clean focus view.

solution.py· Python 3.11 WASM