Minimize Max Distance to Gas Station, explained

Minimize Max Distance to Gas Station is solved by binary searching the answer as a real number: for a candidate distance d, a gap of length g needs ceil(g / d) - 1 new stations, and d is achievable if those needs add up to at most k. Shrink the range until it is tighter than the allowed error. A max-heap that always splits the currently longest piece is a correct but slower alternative.

By Published 8 min read

The problem, restated

You have gas stations at known positions along a straight road, listed in increasing order. You may build exactly k more stations at any real-valued positions, not just whole numbers. After building, measure every distance between neighboring stations and take the largest. Make that largest distance as small as possible and return it. Answers are usually accepted within a small tolerance, such as one millionth.

Examples worked out for this page
StationskAnswerHow
[0, 10]15One station in the middle
[0, 10]42Four stations cut the road into five pieces of 2
[1, 4, 13]14.5The gap of 9 is halved; the gap of 3 is left alone
[1, 4, 13]23The gap of 9 becomes three pieces of 3
[0, 2, 3, 9]32The gap of 6 gets two stations; the gap of 2 sets the floor
Examples worked out for this page. Scroll sideways on a small screen.

Only the gaps matter, not the absolute positions. A gap of length g that receives c new stations is best split evenly into c + 1 pieces of length g / (c + 1). The whole problem is deciding how many stations each gap gets.

A correct but slower idea: split the worst gap

Place stations one at a time, each in the gap whose current pieces are longest. Keep the gaps in a max-heap keyed by piece length, which is the gap divided by its number of pieces. Pop the top, add a piece, push it back. After k rounds, the top of the heap is the answer.

import heapq

def smallest_max_gap_heap(stations, k):
    heap = [(-(b - a), b - a, 1) for a, b in zip(stations, stations[1:])]
    heapq.heapify(heap)
    for _ in range(k):
        _, gap, parts = heapq.heappop(heap)
        parts += 1
        heapq.heappush(heap, (-gap / parts, gap, parts))
    return -heap[0][0]
Max-heap greedy: O(n + k log n) time, O(n) space.

This greedy is exact: a new station can only help the longest current piece, and giving it anywhere else leaves the maximum where it was. The trouble is k. If k is in the millions, k heap operations get slow, and the cost grows with k rather than with the size of the road. The naive version without a heap, scanning all gaps each round, is worse still at O(nk).

The main approach: binary search on the distance

Flip the question. Instead of asking how to spend k stations, ask: if I insist that no gap may exceed d, how many stations do I need? A gap of length g needs enough pieces that each is at most d, which is ceil(g / d) pieces and therefore ceil(g / d) - 1 new stations. Add that up over all gaps. If the total is at most k, then d is achievable; if not, d is too ambitious.

The total needed only goes down as d grows, so feasibility is monotone. Search d between 0 and the largest existing gap, which is always achievable with zero new stations. Because d is a real number there is no exact last step. Either loop until hi - lo drops below the tolerance, or run a fixed number of halvings. One hundred halvings shrink any realistic range far below one millionth and remove the risk of a loop that never ends because of floating-point rounding.

import math

def smallest_max_gap(stations, k):
    gaps = [b - a for a, b in zip(stations, stations[1:])]
    lo, hi = 0.0, float(max(gaps))
    for _ in range(100):
        d = (lo + hi) / 2
        needed = sum(math.ceil(g / d) - 1 for g in gaps)
        if needed <= k:
            hi = d
        else:
            lo = d
    return hi
Python: about 100 rounds, each O(n).
function smallestMaxGap(stations, k) {
  const gaps = [];
  for (let i = 1; i < stations.length; i++) {
    gaps.push(stations[i] - stations[i - 1]);
  }
  let lo = 0;
  let hi = gaps.reduce((a, b) => Math.max(a, b), 0);
  for (let round = 0; round < 100; round++) {
    const d = (lo + hi) / 2;
    let needed = 0;
    for (const g of gaps) needed += Math.ceil(g / d) - 1;
    if (needed <= k) hi = d;
    else lo = d;
  }
  return hi;
}
JavaScript: reduce avoids spreading a huge array into Math.max.

A common variant counts with floor(g / d) instead. That over-counts by one whenever g divides evenly by d, which makes a borderline d look infeasible. In a real-valued search the effect disappears in the limit, so both versions converge to the same answer within the tolerance, but ceil(g / d) - 1 is the exact count and easier to defend when an interviewer asks why.

Watching the search narrow

Take stations [1, 4, 13] with k = 1. The gaps are 3 and 9, so the range starts as 0 to 9. At d = 4.5, the gap of 3 needs 0 stations and the gap of 9 needs ceil(2) - 1 = 1, a total of 1, so 4.5 works and hi drops to 4.5. At d = 2.25, the needs are 1 and 3, too many, so lo rises to 2.25. Every later midpoint below 4.5 needs at least two stations for the gap of 9, so lo keeps creeping up toward 4.5 while hi stays put. The loop ends with hi equal to 4.5.

Complexity

n stations, k new ones, W = largest gap, e = tolerance
ApproachTimeSpaceDepends on k?
Scan for the worst gap each roundO(nk)O(n)Yes, linearly
Max-heap greedyO(n + k log n)O(n)Yes
Binary search on dO(n log(W / e))O(n) for gapsNo
n stations, k new ones, W = largest gap, e = tolerance. Scroll sideways on a small screen.

The binary search cost depends on the precision you want, not on k, which is why it is the preferred answer when k is large. With 100 fixed rounds it is simply 100 passes over the gaps.

Edge cases

  • k = 0: no new stations, so the answer is the largest existing gap, and the search converges to it.
  • Two stations: one gap, and the answer is that gap divided by k + 1.
  • Very uneven gaps, like [0, 1, 1000]: almost every new station goes into the big gap, and the small gap never matters.
  • Huge k: the heap version slows down while the binary search does not change.
  • Positions that are not sorted: the usual statement promises increasing order, but if it does not, sort first.

Where solutions go wrong

  • Searching over integers. The answer is real-valued; [1, 4, 13] with k = 1 needs 4.5.
  • A loop like `while hi - lo > 1e-6` with a tolerance below what floating point can represent at that scale. It can spin forever. A fixed round count is safer.
  • Testing d = 0. The range starts at 0, and g / 0 is infinite in JavaScript and an error in Python. Only test midpoints, which stay positive while hi is positive.
  • Spreading a big array into `Math.max`. Very long arrays can exceed the engine's argument limit; a reduce or a loop is safe.
  • Giving each new station to the longest original gap. The heap must track pieces, not original gaps, or a gap keeps receiving stations after it is no longer the worst.

Explaining it in an interview

Fictional example

Moving from the heap to the search
Candidate
A heap that always splits the longest current piece is correct, but it does k operations, and k may be huge.
Candidate
Instead I will guess the answer d. A gap g needs ceil of g over d, minus one, new stations to get every piece under d. If the total is at most k, d works, so I try smaller; otherwise I go larger.
Candidate
It is a real-valued search, so I will run a fixed hundred rounds rather than compare floats to a tolerance. That makes it O(n) per round, independent of k.

Other problems in this group

Magnetic Force Between Two Balls is the mirror image: it maximizes a minimum gap over integers with a greedy test. Single Element in a Sorted Array is a compact index search if you want a quick contrast. Median of a Row-Wise Sorted Matrix shows counting against a guessed value on a grid. See also the data structure interview questions for heap basics.

Rehearse with Natively

Natively can take a screenshot of a practice question like this and suggest a line of attack, which is a good cross-check once your own solution is down. It also transcribes mock interviews on your computer, so afterwards you can see whether you explained the ceil count and the stopping rule or glossed over them. Read about an AI interview assistant for Mac and Windows.

Questions people ask

How do you solve Minimize Max Distance to Gas Station?

Binary search on the answer d as a real number. A gap of length g needs ceil(g / d) - 1 new stations to keep every piece at most d; if the total over all gaps is at most k, d is achievable, so search lower.

Why not use a heap?

A max-heap that always splits the longest current piece is correct, but it performs k operations, so it slows down when k is large. The binary search cost depends on the precision, not on k.

How many iterations does the binary search need?

Enough to shrink the range below the allowed error. Running a fixed 100 halvings is a simple, safe choice that avoids floating-point loops that never end.

Should the count use floor(g / d) or ceil(g / d) - 1?

ceil(g / d) - 1 is the exact number of stations a gap needs. floor(g / d) over-counts by one when g divides evenly by d, but in a real-valued search both converge to the same answer within tolerance.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP