logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›take u forward›binary search›faqs

Minimise Max Distance to Gas Stations

# Question

Given a sorted integer array arr representing positions of NNN existing gas stations on the X-axis, and an integer KKK, place KKK new gas stations anywhere on the X-axis. Find the minimum possible value of the maximum distance between adjacent gas stations after all KKK new stations are added. Your answer must be within 10−610^{-6}10−6 of the true value.

# Solution

# Pattern

Floating-Point Binary Search on Answer We cannot efficiently compute the exact optimal placements iteratively if KKK is massive. However, we know the optimal maximum distance lies somewhere between 0.00.00.0 and the maximum current gap. We binary search this continuous floating-point range. For a "guessed" maximum distance, we greedily calculate how many new stations are required to break up all existing gaps to be ≤\le≤ our guess.

# How to Identify

  • The problem asks to minimize a maximum (minimize the maximum gap).
  • The solution requires high precision (e.g., 10−610^{-6}10−6), dictating a continuous floating-point search space rather than discrete integers.
  • The constraint on KKK can be extremely large, rendering O(Klog⁡N)O(K \log N)O(KlogN) Priority Queue (Max-Heap) approaches unviable.

# Description

Step-by-step explanation:

  1. Establish Bounds: - Lower Bound (left): 0.00.00.0. The distance can theoretically be infinitesimal.
    • Upper Bound (right): The maximum distance between any two adjacent stations in the given array.
  2. Floating-Point Loop: Loop while the difference between right and left is strictly greater than the requested precision (1e-6).
  3. Calculate Midpoint: mid = left + (right - left) / 2.0. This represents our guessed optimal maximum gap.
  4. Greedy Validation (canPlaceStations):
    • Iterate through every adjacent pair of stations.
    • Calculate the distance between them: dist = arr[i] - arr[i-1].
    • The number of new stations required to ensure no resulting segment is larger than mid is determined by: (int)((dist - 1e-9) / mid). The - 1e-9 is crucial for exact divisions (e.g., gap of 2 divided by max limit of 1 should require 1 internal station, not 2).
    • Sum these required stations across all gaps.
    • If total required stations >K> K>K, our guess mid was too strict. Return false.
  5. Adjust Bounds (CRITICAL):
    • Because the search space is continuous, do not use mid + 1 or mid - epsilon.
    • If valid: right = mid.
    • If invalid: left = mid.
  6. Return: When the gap closes to < 10^{-6}, right holds the precise minimized maximum distance.

# The Intuition

Imagine you have a highway with several very long stretches without gas stations. You are given a budget of KKK new stations to place. Your goal is to ensure drivers never drive more than XXX miles between stations. You guess X=50.0X = 50.0X=50.0 miles. You inspect a 120-mile stretch. To break it into pieces of 50 or less, you must place 2 stations (creating 3 pieces of 40 miles). You repeat this math for every gap on the highway. If you used 101010 stations but your budget was only 555, your guess of 50.050.050.0 was too small. You need to allow a larger gap. If you only used 333 stations, your guess worked! But maybe you can squeeze it even tighter, so you try 40.040.040.0 miles. You halve the guess repeatedly until converging on the exact decimal value that perfectly utilizes your budget.

# Complexity

LabelWorstAverage
Time ComplexityO(Nlog⁡Mϵ)O(N \log \frac{M}{\epsilon})O(NlogϵM​)O(Nlog⁡Mϵ)O(N \log \frac{M}{\epsilon})O(NlogϵM​)
Space ComplexityO(1)O(1)O(1)O(1)O(1)O(1)

# Time Complexity

Let MMM be the maximum initial distance between any two stations, and ϵ\epsilonϵ be the precision tolerance 10−610^{-6}10−6. The search space halves in a continuous domain. It takes exactly ≈log⁡2(M10−6)\approx \log_2(\frac{M}{10^{-6}})≈log2​(10−6M​) steps to converge. Inside the loop, we execute a linear O(N)O(N)O(N) scan. Total time is O(Nlog⁡Mϵ)O(N \log \frac{M}{\epsilon})O(NlogϵM​). Given constraints, this is roughly 50 iterations, making it highly efficient.

# Space Complexity

We only allocate primitive variables (left, right, mid, requiredStations). Auxiliary space is strictly O(1)O(1)O(1).

# Code

class Solution {
    public double minimiseMaxDistance(int[] arr, int k) {
        if (arr == null || arr.length < 2) return 0.0;
 
        double left = 0;
        double right = 0;
 
        // Establish the upper bound (maximum initial gap)
        for (int i = 1; i < arr.length; i++) {
            right = Math.max(right, arr[i] - arr[i - 1]);
        }
 
        // Search space is continuous; define precision threshold (10^-6 precision)
        double diff = 1e-6;
 
        while (right - left &gt; diff) {
            double mid = left + (right - left) / 2.0;
 
            if (canPlaceStations(arr, k, mid)) {
                // mid is valid, attempt to find a smaller maximum distance
                right = mid;
            } else {
                // mid is too small, requires more stations than k
                left = mid;
            }
        }
 
        return right;
    }
 
    private boolean canPlaceStations(int[] arr, int targetStations, double maxDistance) {
        int requiredStations = 0;
        double epsilon = 1e-9;
        
        for (int i = 1; i &lt; arr.length; i++) {
            double gap = arr[i] - arr[i - 1];
            
            // The -epsilon handles perfectly divisible gaps.
            // E.g., gap 2.0 / maxDist 1.0 requires 1 station, not 2.
            // (2.0 - 1e-9) / 1.0 = 1.999999999 -&gt; truncates to 1.
            requiredStations += (int) ((gap - epsilon) / maxDistance);
            
            // Fast fail
            if (requiredStations &gt; targetStations) return false;
        }
 
        return true;
    }
}

# Caveats

  • Floating-Point Boundaries: A fatal mistake in floating-point binary searches is treating them like integer array indices (e.g., left = mid + 0.0001). If the optimal answer is 3.141592 and mid is 3.1415, adding 0.0001 forces left to 3.1416, permanently skipping over the true answer. Always use strict left = mid and right = mid.
  • IEEE 754 Precision Errors: Using Math.ceil(dist / maxDist) - 1 seems mathematically perfect. However, due to binary representation artifacts, 2.0/1.02.0 / 1.02.0/1.0 might evaluate to 2.0000000000000004. Math.ceil bumps this to 333, causing the required stations to overestimate and erroneously fail the validation. Using (int) truncation safely sidesteps this.
  • Modulo Operator: Never use % on double values to check divisibility; it is unreliable.
  • Scale of K: If kkk is small, a Max-Heap approach O(klog⁡N)O(k \log N)O(klogN) is faster, but Binary Search is the general-purpose solution for large kkk
  • Exact Division Trap: On paper, an exact integer division (e.g., Gap is 2.0, maxDistance is 1.0) mathematically returns 2. However, to break a gap of 2 into pieces of 1, you only need to place 1 internal station. Subtracting an infinitesimally small epsilon from the gap (gap - 1e-9) before integer truncation elegantly fixes this.

# Concepts to Think About

  • The Priority Queue (Max-Heap) Alternative: You can solve this by pushing all initial gaps into a Max-Heap. You pop the largest gap, increment its internal station count, recalculate its new split gap size, and push it back, repeating KKK times. While conceptually intuitive, the time complexity is O(Klog⁡N)O(K \log N)O(KlogN). If K=109K = 10^9K=109, this approach will Time Limit Exceed (TLE). Binary search is universally superior here because its runtime is decoupled from KKK's magnitude.
  • Numerical Stability: Dealing with floating-point underflow/overflow.
  • Fixed Iterations vs. Epsilon Loop: Trade-offs in termination conditions.
  • Greedy vs. BS: When to use a Priority Queue vs. Binary Search on Answer.
  • NP-Hardness: How "contiguous" requirements (like in Book Allocation) simplify problems that would otherwise be NP-hard (like Partition).

# Logical Follow-up

Question: If we use (int)(gap / maxDistance), won't it fail if the gap is exactly divisible? (e.g., Gap is 2, maxDistance is 1. (int)(2/1) = 2, but we only need 1 station!) Solution: On paper, exact integer division fails this truncation check. However, because we are executing a continuous binary search with a tolerance of 10−610^{-6}10−6, the algorithm naturally tests values infinitesimally larger than the integer (e.g., mid = 1.0000001). When it evaluates (int)(2.0 / 1.0000001), it safely truncates to 1, which correctly satisfies the budget constraint. The continuous nature of the binary search automatically "saves" the division from its exact-integer flaw, rendering the algorithm perfectly accurate within the accepted tolerance.

Question: If you were given a very small kkk (e.g., k=10k=10k=10) but n=1,000,000n=1,000,000n=1,000,000, would this approach still be the best? Solution: No. In that case, an O(klog⁡n)O(k \log n)O(klogn) approach using a Max-Heap would be faster. You would store all current gaps in the heap and repeatedly split the largest one.

Question: Can we parallelize this? Solution: Yes. The predicate function getRequiredStations is a simple summation over an array, which can be easily distributed across multiple cores or even using MapReduce for massive datasets.

PreviousKth Element Of 2 Sorted ArraysNextSplit Array - Largest Sum
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up