Find the Smallest Divisor Given a Threshold (LeetCode 1283): Solution and Explanation

Medium
Array
Binary Search

Pick a positive divisor, divide every number in nums by it rounding up, and add the results. Return the smallest divisor whose sum is at most threshold.

Intuition

Think of each number x as a stick of length x, and the divisor d as a saw that cuts it into pieces of length d. The stick produces ceil(x / d) pieces, because a short leftover still counts as one piece. The sum is the total number of pieces across all sticks.

Longer pieces mean fewer pieces. If d works, any larger d produces the same or fewer pieces, so it works too. If d fails, every smaller d fails. The valid divisors form one contiguous block at the top of the range.

The top of the range is max(nums): at that length every stick is a single piece, the sum is nums.length, and the constraints promise that is within the threshold. So the answer lies in [1, max(nums)], and a monotone yes/no test over a range is exactly what binary search finds the edge of.

Approach: Binary search on the answer

  1. Set lo = 1 and hi = max(nums). hi always holds a divisor known to work.
  2. While lo < hi, take mid = (lo + hi) // 2 and add up (x + mid - 1) // mid over every x.
  3. If the sum is at most threshold, mid works and might be the answer, so set hi = mid.
  4. Otherwise mid and everything below it fail, so set lo = mid + 1.
  5. When lo == hi, return it: it is the smallest divisor that works.

Step-by-step example

nums = [1,2,5,9], threshold = 6
  1. Range [1, 9]. mid = 5: pieces 1 + 1 + 1 + 2 = 5, which is at most 6. hi = 5.
  2. Range [1, 5]. mid = 3: pieces 1 + 1 + 2 + 3 = 7, which is more than 6. lo = 4.
  3. Range [4, 5]. mid = 4: pieces 1 + 1 + 2 + 3 = 7, still too many. lo = 5.
  4. lo = hi = 5, so the loop stops and the answer is 5.

Code: Python, Java, C++

1class Solution:
2    def smallestDivisor(self, nums: List[int], threshold: int) -> int:
3        lo, hi = 1, max(nums)
4        while lo < hi:
5            mid = (lo + hi) // 2
6            total = 0
7            for x in nums:
8                total += (x + mid - 1) // mid
9            if total <= threshold:
10                hi = mid
11            else:
12                lo = mid + 1
13        return lo
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log M)

M is max(nums). The binary search runs about log2(M) rounds, about 20 for M = 10^6, and each round sums over all n numbers.

Space

O(1)

Only lo, hi, mid and the running sum are stored.

Other approaches

Linear scan from 1 (time O(n M), space O(1))

Try d = 1, 2, 3, ... and stop at the first divisor whose sum fits. Correct, but it can take up to 10^6 rounds of n work each, which times out on the largest inputs.

Tighter starting bounds (time O(n log M), space O(1))

Start lo at ceil(sum(nums) / threshold), since the rounded sum is at least sum / d. It saves a few rounds but does not change the complexity.

Common mistakes

  • Using floor division. The problem rounds up, so 7 / 3 must count as 3, not 2. Use (x + d - 1) // d or Math.ceil.
  • Starting lo at 0. Division by zero crashes, and the divisor must be positive anyway.
  • Mixing loop styles: with hi = mid the loop must be while lo < hi, or it never ends when lo == hi and mid works.
  • Returning mid from the last round instead of lo. The final mid may be a failed divisor.

Frequently asked questions

Why is binary search allowed when nums is not sorted?

The search is over the divisor, not over nums. What has to be sorted is the yes/no answer for each divisor, and it is: all failing divisors come before all working ones.

Can the answer be larger than max(nums)?

No. At d = max(nums) every term is already 1, and a larger divisor cannot make a term smaller than 1. Since threshold >= nums.length, max(nums) always works.

Can the sum overflow a 32-bit int?

Not in practice. Every mid tried is at least about half of hi, a divisor whose sum is already within the threshold, so each term is at most about twice that divisor's term plus one. The sum stays within a few million, far below 2^31.

How is this related to Koko Eating Bananas?

It is the same problem in different words. Koko's eating speed is the divisor, the piles are nums, and the hours are the threshold.