Mid From PDF Coding C# Coding Interview

Find the median of a data stream?

Short answer: public class MedianFinder { private PriorityQueue<int, int> maxHeap; // lower half (max heap) Follow on: private PriorityQueue<int, int> minHeap; // upper half (min heap) public MedianFinder() { maxHeap = new PriorityQueue<int, int>(Comparer<int>.Create((a, b) => b.CompareTo(a))); minHeap = new PriorityQueue<int, int>(); } public void AddNum(int num) { maxHeap.Enqueue(num, num); minHeap.Enqueue(maxHeap.Dequeue(),…

Explain a bit more

maxHeap.Peek()); if (maxHeap.Count < minHeap.Count) maxHeap.Enqueue(minHeap.Dequeue(), minHeap.Peek()); } public double FindMedian() { if (maxHeap.Count > minHeap.Count) return maxHeap.Peek(); return (maxHeap.Peek() + minHeap.Peek()) / 2.0; } } Explanation: Maintain two heaps: maxHeap for lower half, minHeap for upper half. Balance their sizes.

Example code

public class MedianFinder {
private PriorityQueue<int, int> maxHeap; // lower half (max heap) Follow on: private PriorityQueue<int, int> minHeap; // upper half (min heap) public MedianFinder() { maxHeap = new PriorityQueue<int, int>(Comparer<int>.Create((a, b) => b.CompareTo(a)));
minHeap = new PriorityQueue<int, int>();
}
public void AddNum(int num) { maxHeap.Enqueue(num, num); minHeap.Enqueue(maxHeap.Dequeue(), maxHeap.Peek()); if (maxHeap.Count < minHeap.Count) maxHeap.Enqueue(minHeap.Dequeue(), minHeap.Peek()); }
public double FindMedian() {
if (maxHeap.Count > minHeap.Count)
return maxHeap.Peek();
return (maxHeap.Peek() + minHeap.Peek()) / 2.0;
}
} Explanation: Maintain two heaps: maxHeap for lower half, minHeap for upper half. Balance their sizes.

Real-world example (ShopNest)

In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).

Say this in the interview

  1. Define — one clear sentence (the short answer above).
  2. Example — relate it to a project like ShopNest or your real work.
  3. Trade-off — when you would not use it.
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details