Community JavaScript Snippet

Binary Search on the Answer Space

I had to bin-pack 5M jobs across N machines under a wall-time budget; sort-and-greedy timed out. The fix was binary searching the makespan: a `feasible(m)` predicate plus the standard lo/hi loop turns an NP-hard scheduler into O(N log range).

Binary Search on the Answer Space

I had to bin-pack 5M jobs across N machines under a wall-time budget; sort-and-greedy timed out. The fix was binary searching the makespan: a `feasible(m)` predicate plus the standard lo/hi loop turns an NP-hard scheduler into O(N log range).

JavaScript
Frontend
3 snippets
binary-search
problem-solving
code-template
rohaneriksson

By @rohaneriksson

January 12, 2026

·

Updated May 18, 2026

647 views

21

4.4 (13)

The template is the reason this pattern is in my permanent toolkit. The outer loop is the standard lo < hi binary search; the only project-specific logic is feasible(capacity), which decides whether the candidate answer is achievable. For makespan the predicate is greedy first-fit: walk jobs in order, push onto the current machine if it fits, otherwise start a new one. Because feasible is monotonic (if m works, every m+1 also works), binary search converges in log(sum - max) iterations. The bounds are deliberate: lo starts at the largest single job (you can never go below it) and hi starts at the sum (one machine taking everything is always feasible).