Find the Smallest Divisor Given a Threshold - Problem

Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array elements by it, and sum the division's result.

Find the smallest divisor such that the result mentioned above is less than or equal to threshold.

Each result of the division is rounded to the nearest integer greater than or equal to that element (ceiling function). For example: 7/3 = 3 and 10/2 = 5.

The test cases are generated so that there will be an answer.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,5,9], threshold = 6
Output: 5
💡 Note: With divisor 5: ceil(1/5) + ceil(2/5) + ceil(5/5) + ceil(9/5) = 1 + 1 + 1 + 2 = 5 ≤ 6. Smaller divisors give larger sums, so 5 is the answer.
Example 2 — Larger Threshold
$ Input: nums = [44,22,33,11,1], threshold = 5
Output: 44
💡 Note: With divisor 44: ceil(44/44) + ceil(22/44) + ceil(33/44) + ceil(11/44) + ceil(1/44) = 1 + 1 + 1 + 1 + 1 = 5 ≤ 5
Example 3 — Small Array
$ Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
💡 Note: With divisor 3: ceil(2/3) + ceil(3/3) + ceil(5/3) + ceil(7/3) + ceil(11/3) = 1 + 1 + 2 + 3 + 4 = 11 ≤ 11

Constraints

  • 1 ≤ nums.length ≤ 5 × 104
  • 1 ≤ nums[i] ≤ 106
  • nums.length ≤ threshold ≤ 106

Visualization

Tap to expand
Find the Smallest Divisor Given a Threshold INPUT Array: nums 1 2 5 9 [0] [1] [2] [3] threshold = 6 Search Range for Divisor: [1, max(nums)] = [1, 9] Ceiling Division: ceil(7/3) = 3 ceil(10/2) = 5 ceil(9/5) = 2 ALGORITHM STEPS 1 Binary Search Setup left=1, right=9 2 Calculate Mid mid = (left+right)/2 3 Compute Sum sum of ceil(nums[i]/mid) 4 Adjust Search sum <= threshold? go left Binary Search Trace mid sum action 5 5 5<=6 OK 3 7 7>6 go right 4 7 7>6 go right 5 5 ANSWER FINAL RESULT Smallest Valid Divisor: 5 Verification: ceil(1/5) = 1 ceil(2/5) = 1 ceil(5/5) = 1 ceil(9/5) = 2 Sum = 1+1+1+2 = 5 5 <= 6 [OK] Threshold satisfied! Key Insight: Binary search works because larger divisors always produce smaller or equal sums. If divisor d gives sum <= threshold, we try smaller divisors. If sum > threshold, we need larger divisors. This monotonic property allows O(n * log(max)) time complexity instead of brute force O(n * max). TutorialsPoint - Find the Smallest Divisor Given a Threshold | Optimal Binary Search Approach
Asked in
Amazon 15 Facebook 12 Google 8
87.4K Views
Medium Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen