712208. Smallest Divisor

Medium

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:

  1. Calculate the sum total of all elements in the array.
  2. Initialize two pointers, low and high, to represent the range [0, total].
  3. Perform a binary search on the range to find the smallest divisor d.
  4. For each iteration of the binary search:
    • Calculate the mid value mid as (low + high) / 2.
    • Check if total / mid is an integer. If it's not, update high to mid - 1. Otherwise, update low to mid + 1.
  5. Once the binary search finds the smallest divisor d, check if d >= k. If it is, return d. 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

View on GeeksforGeeks
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;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.