Fix the median for a latency dashboard

Review the AI's codeEasy10 min

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]) -> float
Example 1
Inputmedian_latency_ms([10, 20, 30, 40, 50])
Output30
Example 2
Inputmedian_latency_ms([10, 20, 30, 40])
Output25
Example 3
Inputmedian_latency_ms([])
Output-1