#1283
Find the Smallest Divisor Given a Threshold
MediumArrayBinary SearchBinary SearchGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n * m) | O(n log m) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log m)Space O(1)
Using binary search allows us to efficiently find the smallest divisor by narrowing down the range of possible divisors based on the sum of divisions. This is much faster than checking every divisor.
⚙️
Algorithm
5 steps- 1Step 1: Set the left boundary of the search to 1 and the right boundary to the maximum number in the array.
- 2Step 2: While left is less than or equal to right, calculate the middle divisor.
- 3Step 3: Calculate the total sum of divisions for the middle divisor.
- 4Step 4: If the sum is less than or equal to the threshold, move the right boundary to mid - 1 (to find a smaller divisor). Otherwise, move the left boundary to mid + 1.
- 5Step 5: The left boundary will converge to the smallest valid divisor.
solution.py11 lines
1def smallestDivisor(nums, threshold):
2 def total_division(divisor):
3 return sum(-(-num // divisor) for num in nums)
4 left, right = 1, max(nums)
5 while left < right:
6 mid = (left + right) // 2
7 if total_division(mid) > threshold:
8 left = mid + 1
9 else:
10 right = mid
11 return leftℹ
Complexity note: This complexity arises because we perform a binary search over the range of divisors (log m) and for each divisor, we compute the total sum (O(n)).
- 1Binary search significantly reduces the number of checks needed to find the smallest divisor.
- 2Understanding how to calculate the sum of divisions efficiently is crucial for optimizing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.