Best single location on a line to minimize total distance
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Meta. It tests median, sorting and quickselect.
You are choosing one location on a number line to serve a set of sites. You are given a non-empty integer array nums. Each value is the coordinate of a site (values may repeat and may be negative).
Pick a point x that is one of the values in nums so that the total distance
total = sum(|x - nums[i]| for every index i)
is as small as possible. Return [x, total]. If several values of x give the same minimum total, return the smallest such x.
Implement:
def min_total_distance(nums: list[int]) -> list[int]: ...
Constraints
1 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9- The total can exceed 32-bit range.
Example 1
nums = [7, 1, 4]
output: [4, 6]
Choosing 4 costs 3 + 3 + 0 = 6. Choosing 1 costs 9 and choosing 7 costs 9.
Example 2
nums = [-6, 0, 12, 2]
output: [0, 20]
Choosing 0 or 2 both cost 20; return the smaller one, 0.
Aim for better than O(n^2). Be ready to discuss an expected O(n) approach.
Clarifying questions
- Must
xbe one of the values innums, even when a point between two values would tie? (Yes.) - On a tie, is the smallest such
xreturned? (Yes.) - Can the total overflow 64 bits? (Up to about
2 * 10^14, so no.) - Can we change
numsin place?
What a strong answer covers
- Knows that the sum of distances is smallest at a median. With an even count, every point between the two middle values ties, so the lower median is the smallest best
xand is innums. - Sorts and takes
sorted[(n - 1) // 2], then computes the total in one pass. That is O(n log n). - Or uses quickselect for expected O(n) time, and explains the worst case.
- Tests both examples, one value, repeated values, negative values, and an even count with a wide middle gap.
Follow-ups
- Each site has a weight: the weighted median.
- Sites on a 2D grid with Manhattan distance: the axes are independent.
- Sites stream in, and the best location is asked at any time: two heaps.
- Place
klocations instead of one.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
