DSA interview question
A latency dashboard receives response times one at a time and must show the running median after every new value, at any moment. Keeping a sorted array costs O(n) per insert. Instead, split the values into two halves. A max-heap holds the smaller half and a min-heap holds the larger half, with sizes kept equal or the lower half one larger. The median is then either the lower half's top or the average of the two tops, and each insert is O(log n).
Example: addNum(1), addNum(2), findMedian() → 1.5, addNum(3), findMedian() → 2.0.
class MedianFinder {
public:
void addNum(int num);
double findMedian(); // called only after at least one addNum
};
| Operations | Output | Explanation |
|---|---|---|
add 1, add 2, median, add 3, median | 1.5 2.0 | LeetCode's example |
add 5, median, add 15, median, add 1, median, add 3, median | 5.0 10.0 5.0 4.0 | |
add −1, −2, −3, −4, −5, median after each | -1.0 -1.5 -2.0 -2.5 -3.0 | Negative values |
(Confirm: the median of an even count is the average of the two middle values; values fit in 32-bit ints, but their sum may not, so add in floating point.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in