Visualize

Pattern visualizer

Find the Smallest Divisor Given a Threshold

The array is not sorted and never gets sorted — what is sorted is the RANGE OF ANSWERS. Divide by a bigger number and every rounded-up quotient falls or stays put, so the total cost slides downward as the divisor grows. That one-directional slide is the only thing binary search ever needed, so the search runs over candidate divisors 1..max(nums) with 'is this divisor cheap enough?' standing in for 'is this the target?'. Animated on: nums = [9,3,5,44,6,2], threshold = 12 — find the smallest divisor d such that the sum of every nums[i] / d, each rounded up, stays at or below 12..

Binary search the answer, not the array

time O(n log(max(nums)))space O(1)step 1 / 9
9
[0]
3
[1]
5
[2]
44
[3]
6
[4]
2
[5]
line 2

nums=[9,3,5,44,6,2], threshold=12. With divisor 1 nothing shrinks, so the cost is the whole sum 69 — way over 12. The divisor has to grow.

Pseudocode
1FUNCTION smallestDivisor(nums, threshold)
2 low <- 1
3 high <- MAX(nums)
4 WHILE low <= high
5 mid <- FLOOR((low + high) / 2)
6 total <- SUM(CEIL(nums[i] / mid))
7 IF total <= threshold
8 high <- mid - 1
9 ELSE
10 low <- mid + 1
11 RETURN low

← / → step · space play · Home restart

Where to practice Binary Search