🧠
Binary Search on Answer Space with Greedy Check
💡 This approach uses binary search on the minimum distance (answer space) and a greedy check to verify feasibility, drastically improving efficiency.
Intuition
Instead of checking all distances, use binary search between 1 and max distance. For each mid distance, greedily check if m balls can be placed with at least mid distance apart.
Algorithm
- Sort the positions array.
- Set low = 1 and high = max distance between first and last position.
- While low <= high:
- Calculate mid = (low + high) // 2.
- Check if it is possible to place m balls with minimum distance mid.
- If possible, update result = mid and set low = mid + 1 to try larger distances.
- Else, set high = mid - 1 to try smaller distances.
- Return result.
💡 Binary search narrows down the answer space efficiently, and greedy check quickly verifies feasibility.
def maxDistanceBinarySearch(position, m):
position.sort()
def can_place(distance):
count = 1
last_pos = position[0]
for pos in position[1:]:
if pos - last_pos >= distance:
count += 1
last_pos = pos
if count == m:
return True
return False
low, high = 1, position[-1] - position[0]
result = 0
while low <= high:
mid = (low + high) // 2
if can_place(mid):
result = mid
low = mid + 1
else:
high = mid - 1
return result
# Driver code
if __name__ == '__main__':
pos = [1,2,3,4,7]
m = 3
print(maxDistanceBinarySearch(pos, m)) # Output: 3
Line Notes
position.sort()Sort positions to enable greedy placement in order
def can_place(distance):Helper function to check feasibility of placing balls with given minimum distance
for pos in position[1:]:Iterate through positions to greedily place balls
if pos - last_pos >= distance:Place ball only if distance condition is met to maintain minimum spacing
if count == m:Return True early if all balls have been placed successfully
low, high = 1, position[-1] - position[0]Initialize binary search boundaries for minimum distance
while low <= high:Binary search loop over possible minimum distances
mid = (low + high) // 2Calculate mid distance to check feasibility
if can_place(mid):If placement is possible, try larger distances
else:If placement is not possible, try smaller distances
import java.util.*;
public class Solution {
public static boolean canPlace(int[] position, int m, int distance) {
int count = 1, lastPos = position[0];
for (int i = 1; i < position.length; i++) {
if (position[i] - lastPos >= distance) {
count++;
lastPos = position[i];
if (count == m) return true;
}
}
return false;
}
public static int maxDistanceBinarySearch(int[] position, int m) {
Arrays.sort(position);
int low = 1, high = position[position.length - 1] - position[0];
int result = 0;
while (low <= high) {
int mid = low + (high - low) / 2;
if (canPlace(position, m, mid)) {
result = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return result;
}
public static void main(String[] args) {
int[] pos = {1,2,3,4,7};
int m = 3;
System.out.println(maxDistanceBinarySearch(pos, m)); // Output: 3
}
}
Line Notes
Arrays.sort(position);Sort positions to enable greedy placement in order
int low = 1, high = position[position.length - 1] - position[0];Initialize binary search boundaries for minimum distance
while (low <= high)Binary search loop over possible minimum distances
int mid = low + (high - low) / 2;Calculate mid distance safely to avoid overflow
if (canPlace(position, m, mid))If placement is feasible, try larger distances
elseIf placement is not feasible, try smaller distances
return result;Return the maximum feasible minimum distance
#include <bits/stdc++.h>
using namespace std;
bool canPlace(vector<int>& position, int m, int distance) {
int count = 1, lastPos = position[0];
for (int i = 1; i < (int)position.size(); i++) {
if (position[i] - lastPos >= distance) {
count++;
lastPos = position[i];
if (count == m) return true;
}
}
return false;
}
int maxDistanceBinarySearch(vector<int>& position, int m) {
sort(position.begin(), position.end());
int low = 1, high = position.back() - position.front();
int result = 0;
while (low <= high) {
int mid = low + (high - low) / 2;
if (canPlace(position, m, mid)) {
result = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return result;
}
int main() {
vector<int> pos = {1,2,3,4,7};
int m = 3;
cout << maxDistanceBinarySearch(pos, m) << "\n"; // Output: 3
return 0;
}
Line Notes
sort(position.begin(), position.end());Sort positions to enable greedy placement in order
int low = 1, high = position.back() - position.front();Initialize binary search boundaries for minimum distance
while (low <= high)Binary search loop over possible minimum distances
int mid = low + (high - low) / 2;Calculate mid distance safely to avoid overflow
if (canPlace(position, m, mid))If placement is feasible, try larger distances
elseIf placement is not feasible, try smaller distances
return result;Return the maximum feasible minimum distance
function canPlace(position, m, distance) {
let count = 1;
let lastPos = position[0];
for (let i = 1; i < position.length; i++) {
if (position[i] - lastPos >= distance) {
count++;
lastPos = position[i];
if (count === m) return true;
}
}
return false;
}
function maxDistanceBinarySearch(position, m) {
position.sort((a,b) => a - b);
let low = 1;
let high = position[position.length - 1] - position[0];
let result = 0;
while (low <= high) {
let mid = Math.floor((low + high) / 2);
if (canPlace(position, m, mid)) {
result = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return result;
}
// Test
const pos = [1,2,3,4,7];
const m = 3;
console.log(maxDistanceBinarySearch(pos, m)); // Output: 3
Line Notes
position.sort((a,b) => a - b);Sort positions to enable greedy placement in order
let low = 1;Initialize lower bound for binary search
let high = position[position.length - 1] - position[0];Initialize upper bound for binary search
while (low <= high)Binary search loop over possible minimum distances
let mid = Math.floor((low + high) / 2);Calculate mid distance to check feasibility
if (canPlace(position, m, mid))If placement is feasible, try larger distances
elseIf placement is not feasible, try smaller distances
TimeO(n log d) where d is max distance between positions
SpaceO(1) additional space
Binary search runs in log d iterations, each checking feasibility in O(n) time.
💡 For n=10^5 and maxDist=10^9, this approach is efficient and practical.
Interview Verdict: Accepted
This is the optimal approach for this problem and is expected in interviews.