Drill

ProblemsTypeScript › reporting

The middle of a set of readings

mediumreportingTypeScript

A latency report quotes the median rather than the mean, because one slow request should not move the headline number.

medianValue(values: list<int>) → float

Solve it in the editor →

Where you start

function medianValue(values: number[]): number {
  
}

Worked examples

CallResult
medianValue([3,1,2])2
medianValue([1,2,3,4])2.5
medianValue([7])7
medianValue([])0

Hint

After sorting, the two middles for an even count sit at n/2 - 1 and n/2.

Reference solution in TypeScript
function medianValue(values: number[]): number {
  if (values.length === 0) return 0;
  const s = values.slice().sort((a, b) => a - b);
  const n = s.length;
  const mid = Math.floor(n / 2);
  return n % 2 === 1 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
}

The same problem in another language

More reporting problems in TypeScript