The most typical satellite
- O(n) · Medium
- Full plan
- Python
- JavaScript
- lists
- indexes
- comparisons
Problem
"I want to study the most ordinary satellite in the constellation," the mission chief said. To the agency, the most ordinary one is the one flying at the height closest to the average of them all.
Write a function that takes a list of heights in kilometers (positive whole numbers, never empty) and returns the position, counting from 0, of the satellite whose height is closest to the average. Above or below doesn't matter: only the distance counts. With [700, 350, 500, 480] the average is 2030 / 4 = 507.5; 500 is 7.5 away and it's the closest, so you return 2.
The average can have decimals and match none of the heights. If two satellites are the same distance away, you return the one that comes earlier in the list.
Examples
The average is one of the heights
[400, 600, 500] → 2
An average with decimals
[300, 800, 550, 420] → 2
The closest one is below
[410, 490, 515, 380, 705] → 1
A single satellite
[550] → 0
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def typical_satellite(heights):
passJavaScript
function typicalSatellite(heights) {
}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.