Coding problem
The median of a growing list
The task
A latency monitor receives response times one by one and shows the median after each one.
Complete the class RunningMedian. Add(x) records a value. Median() returns the median of all the values so far: the middle value when the count is odd, or the average of the two middle values when it is even. Median() is only called after at least one Add. Values can be any int.
Signature
public sealed class RunningMedian public void Add(int x) public double Median()
Examples
Add(5),Add(1),Add(3), withMedian()after each →5, 3, 3. After 5 and 1 the two middle values are 1 and 5, average 3; with 1, 3, 5 the middle is 3.Add(4),Add(8), thenMedian()→6. The average of 4 and 8.
Limits: Up to 1,000,000 values, with a Median() call after each.
The tests check: one value, two values, equal values, negative values, two int.MaxValue values, int.MinValue with int.MaxValue (a median of −0.5), values added in falling order, low and high values in turn, and 1,000,000 falling values in time.
Hints
Your code
Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;
public sealed class RunningMedian
{
public void Add(int x)
{
throw new NotImplementedException();
}
// The median of all values added so far; only called after at least one Add.
public double Median()
{
throw new NotImplementedException();
}
}This problem comes with TechInterviewNotes Full Access
Unlock all paid content on TechInterviewNotes.