Find the Smallest Divisor Given a Threshold — LeetCode 1283 Python Solution

MediumArrayBinary Search
Problem
#1283
Reading time
2 min

The problem

Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array 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.

Example

Input
nums = [1,2,5,9], threshold = 6
Output
5
Explanation
We can get a sum to 17 (1+2+5+9) if the divisor is 1.

Python solution

Python
class Solution:
    def smallestDivisor(self, nums: List[int], threshold: int) -> int:
        def f(v: int) -> bool:
            v += 1
            return sum((x + v - 1) // v for x in nums) <= threshold

        return bisect_left(range(max(nums)), True, key=f) + 1

Complexity

MeasureComplexity
TimeO(n \times \log M), where n is the length of the array nums and M is the maximum value in the array nums
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1283. Find the Smallest Divisor Given a Threshold is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1283. Find the Smallest Divisor Given a Threshold?
LeetCode 1283. Find the Smallest Divisor Given a Threshold is rated Medium on LeetCode.
What is the time complexity of LeetCode 1283. Find the Smallest Divisor Given a Threshold?
The Python solution on this page runs in O(n \times \log M), where n is the length of the array nums and M is the maximum value in the array nums.
What is the space complexity of LeetCode 1283. Find the Smallest Divisor Given a Threshold?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1283. Find the Smallest Divisor Given a Threshold cover?
LeetCode 1283. Find the Smallest Divisor Given a Threshold is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview