Running Median of Live Heart Rate Readings on Apple Watch
Last updated: November 29, 2026
Quick Overview
Heart rate readings stream in one at a time. Implement add(bpm) and median(), where median returns the median of all readings so far (the mean of the two middle values for an even count), with O(log n) add and O(1) median.
Apple
November 29, 20260
0
0 solved
Heart rate readings stream in one at a time. Implement add(bpm) and median(), where median returns the median of all readings so far (the mean of the two middle values for an even count), with O(log n) add and O(1) median.
Robust statistics such as the median are used to smooth noisy optical heart rate sensors on Apple Watch. The interviewer checks the two-heap design, the rebalancing invariant, and whether you know how to bound memory with a sliding window.
What the Interviewer Expects
- Use a max-heap for the lower half and a min-heap for the upper half
- Keep sizes balanced so the lower heap has the same or one more element
- Route each new value to the correct heap and rebalance
- Compute the median from heap tops in O(1)
- Discuss sliding-window medians and approximate quantiles for bounded memory
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Compute the median over only the last 60 readings.
- Memory is extremely limited; what approximate method would you use?
- Readings are integers in 30 to 220 bpm; can you exploit that?
- Also report the 90th percentile.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
add(x) inserts a reading. median() returns a float, raising on no data. The structure must handle duplicates and arbitrary order. Target O(log n) per add and O(1) per median....
High-Level Design
low is a max-heap (stored as negatives) holding the smaller half and high is a min-heap holding the larger half. Invariant: every value in low is at most every value in high, and len(low) eq...