Magnetic Force Between Two Balls

MediumBinary Searchbinary search on answer

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

There are n baskets placed along a line at the distinct integer coordinates in position (the array is **not** necessarily sorted). You must drop exactly m balls into m different baskets. The magnetic force between two balls at coordinates a and b is |a - b|. Choose the baskets so that the **smallest** force between any two of the placed balls is as large as possible, and return that largest achievable minimum force. Aim for O(n log n + n log(range)) time.

Examples

Input: position = [5,1,9,13], m = 2
Output: 12
Put the two balls at `1` and `13` for a force of `12`.
Input: position = [1,4,6,10,15], m = 3
Output: 5
Using baskets `1`, `6`, and `15` gives gaps `5` and `9`, so the minimum is `5`. No placement makes every gap at least `6`.

Constraints

  • 2 <= n <= 10^5
  • 1 <= position[i] <= 10^9
  • All values in `position` are distinct
  • 2 <= m <= n

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More binary search on answer problems