712208. Smallest Divisor
Here is the blog post for the Smallest Divisor problem:
Smallest Divisor
Slug: smallest-divisor
Difficulty: Medium
Id: 712208
Topic Tags: Binary Search, Arrays, Algorithms
Company Tags: None
Summary
Given an array of integers arr and a target integer k, find the smallest divisor d such that d is greater than or equal to k and the sum of all elements in the array divided by d is an integer. The problem requires us to use binary search to efficiently solve this problem.
Detailed Explanation
To solve this problem, we can start by iterating through the array and calculating the sum of all elements. Then, we can use binary search to find the smallest divisor that satisfies the condition. Here's a step-by-step breakdown:
- Calculate the sum
totalof all elements in the array. - Initialize two pointers,
lowandhigh, to represent the range [0, total]. - Perform a binary search on the range to find the smallest divisor
d. - For each iteration of the binary search:
- Calculate the mid value
midas(low + high) / 2. - Check if
total / midis an integer. If it's not, updatehightomid - 1. Otherwise, updatelowtomid + 1.
- Calculate the mid value
- Once the binary search finds the smallest divisor
d, check ifd >= k. If it is, returnd. Otherwise, return-1.
The time complexity of this solution is O(log total), where total is the sum of all elements in the array. The space complexity is O(1), as we only use a few extra variables to store the intermediate results.
Optimized Solutions
Java
public int smallestDivisor(int[] arr, int k) {
int total = 0;
for (int num : arr) {
total += num;
}
int low = 1;
int high = total;
while (low <= high) {
int mid = (low + high) / 2;
if (total % mid == 0) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return total / low >= k ? low : -1;
}