Python 1283.py
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
# range of potential divisors
left = 1
right = max(nums)
# binary search
while left != right:
# mid => divisor
mid = (left + right) // 2
# note: problem asks for rounding up
total = sum(int(ceil(n / mid)) for n in nums)
if total > threshold:
left = mid + 1
else:
right = mid
return left # == right
Difficulty
and has an acceptance rate of about 66% (700k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the “smallest divisor” problem by searching for the minimal integer divisor that reduces the sum of rounded-up quotients of an input array nums to be less than or equal to a given threshold. The algorithm employs a classic binary search over the range of possible divisor values, leveraging the monotonic relationship between the divisor size and the resulting sum.
Key Steps
Defining the Search Interval
left = 1
right = max(nums)
The lower bound is fixed at 1 because any divisor must be a positive integer. The upper bound is set to the maximum element of nums; a divisor equal to this maximum yields a sum of at most the length of nums, guaranteeing that the threshold condition can be satisfied.
Binary Search Loop
while left != right:
mid = (left + right) // 2
total = sum(int(ceil(n / mid)) for n in nums)
if total > threshold:
left = mid + 1
else:
right = mid
Inside the loop, the midpoint mid acts as the candidate divisor. The code computes the total of the rounded-up division results for all elements in nums. If this total exceeds the threshold, the divisor is too small, so the search moves to the right half by setting left to mid + 1. Otherwise, the divisor is sufficient, and the search narrows to the left half by assigning right to mid. The loop terminates when left and right converge on the smallest viable divisor.
Returning the Result
return left # == right
At termination, both pointers reference the minimal divisor that satisfies the condition, and the method returns this value.
Edge Cases Handled
When the input array contains a single element, the search interval collapses to [1, max(nums)], and the binary search still correctly identifies the smallest divisor because the monotonic property holds for any array length.
If the threshold is larger than the sum obtained with divisor 1 (the worst-case sum), the condition is already satisfied at the lower bound. The binary search quickly converges to left = 1 because the else branch repeatedly moves right leftward until both pointers meet.
Conversely, if the threshold is smaller than the sum achievable with divisor equal to max(nums), the algorithm will push left upward until it reaches max(nums). This scenario is safe because the divisor cannot exceed max(nums) without producing a sum larger than the array length, which would still be greater than the threshold, and the loop logic ensures convergence at the correct upper bound.
The use of ceil guarantees that each division result is rounded up, matching the problem’s specification even when numbers divide evenly; in that case ceil returns the exact quotient, preserving correctness.
Performance Optimizations
The binary search reduces the number of divisor candidates from a linear scan of the entire range to a logarithmic number of iterations, dramatically cutting the number of total sum calculations.
The sum computation employs a generator expression inside sum, which avoids constructing an intermediate list and thus minimizes memory overhead.
Casting the result of ceil to int eliminates the need for floating-point storage beyond the temporary division, keeping the inner loop lightweight.
By updating the search bounds (left and right) directly based on the comparison with threshold, the algorithm avoids unnecessary recomputation of the midpoint for already-discarded portions of the search space.
Overall, the combination of binary search and in-place aggregation yields an efficient solution that scales well with both the size of nums and the magnitude of its elements.
ELI5 - Simplified Explanation
Imagine a big box of scattered blocks that needs to be packed into smaller bags. Each bag has a limit on how many blocks it can hold, and this limit is like the threshold. The goal is to find the smallest number, which acts as a special size for the bags, so that when every block is packed, the total number of bags used is not more than the limit.
To solve this, start by thinking of the smallest possible bag size, which is one, and the largest possible bag size, which is the same as the biggest pile of blocks currently in the box. Instead of checking every single number one by one, pick the middle number between the smallest and largest guesses.
Calculate how many bags are needed with that middle number as the size. If the number of bags is too high, it means the bag size is too small, so move the smallest guess up to make the bags bigger. If the number of bags is just right or even lower, it means a bigger bag size might be okay, but it is also possible that a smaller size works too. In this case, move the largest guess down to the current size to keep looking for a smaller one. Keep repeating this process by cutting the range of guesses in half until only one choice remains. That final number is the perfect size for the bags.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | Python | C++ | Java | TS | ||||
| WalkCCC | Python | C++ | Java | ||||||
| leetcode.ca | Python | C++ | JS | Java | Go | C# | Rust | TS | |
| Progiez | Python | C++ | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 2529: Maximum Count of Positive Integer and Negative Integer
- problem 532: K-diff Pairs in an Array
- problem 718: Maximum Length of Repeated Subarray
- problem 826: Most Profit Assigning Work
- problem 1237: Find Positive Integer Solution for a Given Equation
- problem 1552: Magnetic Force Between Two Balls
- problem 1561: Maximum Number of Coins You Can Get
- problem 1760: Minimum Limit of Balls in a Bag
- problem 1870: Minimum Speed to Arrive on Time
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality