1362. Closest Divisors LeetCode Solution

In this guide, you will get 1362. Closest Divisors LeetCode Solution with the best time and space complexity. The solution to Closest Divisors problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Closest Divisors solution in C++
  4. Closest Divisors solution in Java
  5. Closest Divisors solution in Python
  6. Additional Resources
1362. Closest Divisors LeetCode Solution image

Problem Statement of Closest Divisors

Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2.
Return the two integers in any order.

Example 1:

Input: num = 8
Output: [3,3]
Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.

Example 2:

Input: num = 123
Output: [5,25]

Example 3:

Input: num = 999
Output: [40,25]

Constraints:

1 <= num <= 10^9

Complexity Analysis

  • Time Complexity:
  • Space Complexity:

1362. Closest Divisors LeetCode Solution in C++

class Solution {
 public:
  vector<int> closestDivisors(int num) {
    for (int root = sqrt(num + 2); root > 0; --root)
      for (int cand : {num + 1, num + 2})
        if (cand % root == 0)
          return {root, cand / root};

    throw;
  }
};
/* code provided by PROGIEZ */

1362. Closest Divisors LeetCode Solution in Java

class Solution {
  public int[] closestDivisors(int num) {
    for (int root = (int) Math.sqrt(num + 2); root > 0; --root)
      for (int cand : new int[] {num + 1, num + 2})
        if (cand % root == 0)
          return new int[] {root, cand / root};

    throw new IllegalArgumentException();
  }
}
// code provided by PROGIEZ

1362. Closest Divisors LeetCode Solution in Python

class Solution:
  def closestDivisors(self, num: int) -> list[int]:
    for root in reversed(range(math.isqrt(num + 2) + 1)):
      for cand in [num + 1, num + 2]:
        if cand % root == 0:
          return [root, cand // root]
# code by PROGIEZ

Additional Resources

See also  3419. Minimize the Maximum Edge Weight of Graph LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.