Fix the median for a latency dashboard
Your task
Your metrics dashboard shows the median request latency. The first version returned the upper of the two middle values for an even number of samples, returned undefined for no samples, and sorted the caller's live buffer in place.
An assistant wrote median_latency_ms(samples) to replace it. It is in the editor. It has a bug. Find it and fix it.
Input and output:
samples: latencies in whole milliseconds, in any order.- Return the median as a number, or -1 when there are no samples.
Rules the tests check:
- An empty list returns -1.
- Sort the samples. With an odd count, the median is the middle value.
- With an even count, the median is the exact average of the two middle values, so it can end in
.5.
Examples
median_latency_ms(samples: list[int]) -> floatExample 1
Input
median_latency_ms([10, 20, 30, 40, 50])Output
30Example 2
Input
median_latency_ms([10, 20, 30, 40])Output
25Example 3
Input
median_latency_ms([])Output
-1