← Questions

Best single location on a line to minimize total distance

0
MetaCoding

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 x be one of the values in nums, even when a point between two values would tie? (Yes.)
  • On a tie, is the smallest such x returned? (Yes.)
  • Can the total overflow 64 bits? (Up to about 2 * 10^14, so no.)
  • Can we change nums in 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 x and is in nums.
  • 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 k locations instead of one.

Where it's asked

What it tests

median · sorting · quickselect · math

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding