The median
- O(n log n) · Hard
- Full plan
- Python
- JavaScript
- lists
- sorting
- decimals
Problem
The average chases the extremes: one huge salary pulls it up.
The median doesn't: it's the value right in the middle once you line the numbers up from smallest to largest.
Write a function that takes a list of numbers and returns its median. With 3 numbers the median is the second one; with 5, the third one.
When the count is even there isn't a single one in the middle, so the median is the average of the middle two: with 1, 2, 3 and 4 it's 2.5. The list can arrive out of order, and it can bring repeated or negative numbers. With an empty list you return 0.
Examples
Three out of order
[5, 1, 3] → 3
An even count
[1, 2, 3, 4] → 2.5
Four out of order
[7, 2, 9, 4] → 5.5
With two digits
[2, 10, 9] → 9
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def median(numbers):
passJavaScript
function median(numbers) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.