1. Problem Statement
Mental Model
Breaking down a complex problem into its most efficient algorithmic primitive.
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.
Implement the MedianFinder class:
void addNum(int num): adds the integernumfrom the data stream to the data structure.double findMedian(): returns the median of all elements so far.
Input: ["addNum", "addNum", "findMedian", "addNum", "findMedian"] [[1], [2], [], [3], []]
Output: [null, null, 1.5, null, 2.0]
2. The Mental Model: The "Center of Gravity"
Imagine a seesaw. We want to keep it balanced so that the "Center" is always where the median lives.
- We split the incoming numbers into two groups: Small Halves and Large Halves.
- To get the largest of the smalls instantly, we use a Max-Heap.
- To get the smallest of the larges instantly, we use a Min-Heap.
The median is always either the top of one of these heaps or the average of the two tops. By maintaining the size of these two heaps such that they never differ by more than 1, we find the median in $O(1)$ time.
3. Visual Execution (The Balancing Act)
graph LR
subgraph "Small Half (Max-Heap)"
Max[Top: Largest of Small]
end
subgraph "Large Half (Min-Heap)"
Min[Top: Smallest of Large]
end
Median{Running Median}
Max --- Median --- Min
4. Java Implementation
class MedianFinder {
private PriorityQueue<Integer> small; // Max-Heap for the smaller half
private PriorityQueue<Integer> large; // Min-Heap for the larger half
public MedianFinder() {
// Max-heap: Collections.reverseOrder() is crucial
small = new PriorityQueue<>(Collections.reverseOrder());
large = new PriorityQueue<>();
}
public void addNum(int num) {
// 1. Always add to small first to maintain sorted invariant
small.offer(num);
// 2. The Transfer: Move the largest of small to large
large.offer(small.poll());
// 3. The Balance: Ensure small.size >= large.size
// We want small to hold the extra element if the total count is odd
if (small.size() < large.size()) {
small.offer(large.poll());
}
}
public double findMedian() {
if (small.size() > large.size()) {
// Total count is odd, median is the top of the larger small-heap
return (double) small.peek();
}
// Total count is even, average of the two middle elements
return (small.peek() + large.peek()) / 2.0;
}
}
5. Verbal Interview Script (Staff Tier)
Interviewer: "Why not just use a sorted list and insert new elements in O(N)?"
You: "While a sorted list allows $O(1)$ median access, inserting a new element requires $O(N)$ shifting. In a high-velocity data stream (e.g., millions of events per second), $O(N)$ is unacceptable as it becomes slower as the dataset grows. The Two Heaps approach provides a logarithmic $O(\log N)$ insertion time and $O(1)$ lookup. This is the optimal trade-off for a real-time system. A key technical nuance in my implementation is the Double-Offer logic: by always pushing to the small heap and then immediately moving its largest element to the large heap, I guarantee that the 'Large' half truly contains only values $\ge$ the 'Small' half without needing manual comparison logic."
6. Staff-Level Follow-Ups
Follow-up 1: "What if the numbers are in a fixed range, say 0 to 100?"
- The Answer: "If the range is restricted, we can use a Frequency Array (Counting Sort style) of size 101. We track the total number of elements. Finding the median becomes an $O(101) \rightarrow O(1)$ scan of the frequencies to find the 50th percentile. This is faster and more memory-efficient than heaps."
Follow-up 2: "How would you find the median in a distributed stream (e.g., across 10 servers)?"
- The Answer: "For a distributed system, we would move from Heaps to Approximate Medians. I would use a T-Digest or a KLL Sketch. These probabilistic data structures can be merged across servers to give a median with a guaranteed error bound (e.g., 99% accuracy) while using significantly less network bandwidth than sending all raw data to a central aggregator."
7. Performance Nuances (The Java Perspective)
- Integer Overflow: When calculating
(a + b) / 2.0, ifaandbare nearInteger.MAX_VALUE, their sum will overflow before the division. A safer way isa + (b - a) / 2.0. - Heap Capacity: If we know the expected size of the stream, we should initialize the PriorityQueues with that capacity:
new PriorityQueue<>(expectedSize / 2). This prevents internal array resizing and copying during the stream.
Engineering Standard: The "Staff" Perspective
In high-throughput distributed systems, the code we write is often the easiest part. The difficulty lies in how that code interacts with other components in the stack.
1. Data Integrity and The "P" in CAP
Whenever you are dealing with state (Databases, Caches, or In-memory stores), you must account for Network Partitions. In a standard Java microservice, we often choose Availability (AP) by using Eventual Consistency patterns. However, for financial ledgers, we must enforce Strong Consistency (CP), which usually involves distributed locks (Redis Redlock or Zookeeper) or a strictly linearizable sequence.
2. The Observability Pillar
Writing logic without observability is like flying a plane without a dashboard. Every production service must implement:
- Tracing (OpenTelemetry): Track a single request across 50 microservices.
- Metrics (Prometheus): Monitor Heap usage, Thread saturation, and P99 latencies.
- Structured Logging (ELK/Splunk): Never log raw strings; use JSON so you can query logs like a database.
3. Production Incident Prevention
To survive a 3:00 AM incident, we use:
- Circuit Breakers: Stop the bleeding if a downstream service is down.
- Bulkheads: Isolate thread pools so one failing endpoint doesn't crash the entire app.
- Retries with Exponential Backoff: Avoid the "Thundering Herd" problem when a service comes back online.
Critical Interview Nuance
When an interviewer asks you about this topic, don't just explain the code. Explain the Trade-offs. A Staff Engineer is someone who knows that every architectural decision is a choice between two "bad" outcomes. You are picking the one that aligns with the business goal.
Performance Checklist for High-Load Systems:
- Minimize Object Creation: Use primitive arrays and reusable buffers.
- Batching: Group 1,000 small writes into 1 large batch to save I/O cycles.
- Async Processing: If the user doesn't need the result immediately, move it to a Message Queue (Kafka/SQS).
Key Takeaways
void addNum(int num): adds the integernumfrom the data stream to the data structure.double findMedian(): returns the median of all elements so far.- We split the incoming numbers into two groups: Small Halves and Large Halves.