Visualize LeetCode 774 step by step. Watch binary search narrow the maximum gap, with a linear feasibility pass counting how many extra stations keep all gaps below the candidate threshold.
About this algorithm
Gas stations stand at given positions along a road and you may build k more anywhere. Place them so the largest gap between neighbouring stations is as small as possible, and report that gap. The page solves it by guessing the answer and checking each guess, halving the range of possible answers every time.
This page sits with the sliding window pages, but the method is binary search on the answer. It fits when you can easily check whether a value D is achievable and the checks are monotone: if a gap limit D works, every larger limit works too. Other problems of the same shape are Koko eating bananas, splitting an array into k parts with the smallest largest sum, and shipping packages within d days. Use a real sliding window, as on the max ones page, when the answer is a stretch of the array rather than a number you can test.
The answer is above 0 and no more than the largest existing gap, since that is the result of building nothing. This page searches from 0 to the largest gap.
Take mid = (lo + hi) / 2 as a candidate for the largest allowed gap.
A gap of length g needs ceil(g / mid) - 1 new stations to cut it into pieces no longer than mid. Add this up over all gaps.
If the count is at most k, the guess works, so try smaller: hi = mid. If it is more than k, the guess is too tight: lo = mid. Repeat until the range is tiny.
The gaps are 6, 4 and 10, so the search runs from 0 to 10. Guess 5: the gaps need 1, 0 and 1 stations, 2 in all, which fits, so hi = 5. Guess 2.5: 2 + 1 + 3 = 6, too many, so lo = 2.5. Guess 3.75: 1 + 1 + 2 = 4, fits, hi = 3.75. Guess 3.125: 1 + 1 + 3 = 5, too many, lo = 3.125. The guesses keep closing in on 10 / 3, about 3.333: one station splits the 6 gap into two 3s, one splits the 4 gap into two 2s, and two split the 10 gap into three pieces of 3.333. After its 14 halvings the page reports 3.33313, which is within 0.0003 of that.
The code listing starts hi at the full road length (20 here) and stops when the range is under 0.000001. The page starts hi at the largest gap, which is enough, and stops after 14 halvings so the run stays watchable, which is why its answer is close to 10 / 3 rather than exact.
Time: each check walks the N - 1 gaps once, and halving a range of width W down to a precision ε takes about log2(W / ε) checks. Space: the check keeps a running count; lo, hi and mid are the only other values.