Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

Spread m items to maximise the closest pair

Medium · Target 25 minutes · Binary search · Type asked atGoogleOptiver

There are slots at distinct positions position[i] on a line. Place m items in m different slots so that the smallest distance between any two placed items is as large as possible. Return that largest possible smallest distance.

Examples

InputOutputWhy
position = [1, 2, 3, 4, 7], m = 33Slots 1, 4 and 7: gaps of 3 and 3.
position = [5, 4, 3, 2, 1, 1000000000], m = 2999999999
position = [10, 20, 30, 40, 50], m = 410

Constraints

  • 2 ≤ n ≤ 10⁵
  • 1 ≤ position[i] ≤ 10⁹, all distinct
  • 2 ≤ m ≤ n

Hints

Hint 1

For a given distance d, can you decide quickly whether m items fit with every gap at least d?

Hint 2

Sort the positions. Put the first item in the leftmost slot, and each next item in the first slot at least d past the previous one. If that places m items, d is achievable.

Hint 3

If d is achievable, so is every smaller distance. Search for the largest achievable d, rounding the midpoint up.

Where people lose marks

  • Forgetting to sort the positions before the greedy pass.
  • Rounding the midpoint down while setting lo = mid: an infinite loop on the last two candidates.
  • Counting gaps instead of items: m items make m − 1 gaps.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.