Skip to content
ΣDSA Patterns
Menu
Language

Binary Search on Answer

Guide 5 of 6 · Path 5 of 6

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1
2
5
9

threshold = 6

Smallest divisor d such that Σ ceil(nums[i]/d) ≤ 6.

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Find the Smallest Divisor Given a Threshold

Problem (restated)

Find the smallest positive divisor such that the sum of ceil divisions of nums is ≤ threshold.

Intuition

Larger divisor → smaller sum; binary search the divisor.

Approaches

Binary search divisor

Unverified
Time O(n log M)Space O(1)

Idea. lo=1, hi=max(nums). mid ok if sum(ceil(x/mid)) ≤ threshold.

Walkthrough. [1,2,5,9], threshold=6 → divisor 5.

Trade-offs. Same pattern as Koko / ship capacity.

Solution
export function smallestDivisor(nums: number[], threshold: number): number {
  let lo = 1, hi = Math.max(...nums);
  const ok = (d: number) => {
    let s = 0;
    for (const x of nums) s += Math.ceil(x / d);
    return s <= threshold;
  };
  while (lo < hi) {
    const mid = lo + ((hi - lo) >> 1);
    if (ok(mid)) hi = mid; else lo = mid + 1;
  }
  return lo;
}
export function smallestDivisor(nums: number[], threshold: number): number {
  let lo = 1, hi = Math.max(...nums);
  const ok = (d: number) => {
    let s = 0;
    for (const x of nums) s += Math.ceil(x / d);
    return s <= threshold;
  };
  while (lo < hi) {
    const mid = lo + ((hi - lo) >> 1);
    if (ok(mid)) hi = mid; else lo = mid + 1;
  }
  return lo;
}

Template connection

Binary search on the divisor; sum of ceils is the feasibility check.

Reflection