Leetcode 1362: Closest Divisors

grid47
grid47
Exploring patterns and algorithms
Jun 23, 2024 4 min read

Given an integer num, find the closest two integers whose product is equal to either num + 1 or num + 2 and whose absolute difference is the smallest. You need to return these two integers in any order.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer `num` which represents the given number.
Example: num = 8
Constraints:
• 1 <= num <= 10^9
Output: The output should be a list of two integers that have the smallest absolute difference, whose product is equal to `num + 1` or `num + 2`.
Example: [3, 3]
Constraints:
• The output will always contain exactly two integers.
Goal: To find the two closest divisors of `num + 1` or `num + 2` whose absolute difference is the smallest.
Steps:
• For each possible divisor from `sqrt(num + 2)` down to 1, check if it divides `num + 1` or `num + 2`.
• Once a divisor is found, return the pair of divisors with the smallest difference.
Goal: Ensure that the value of `num` satisfies the given constraints.
Steps:
• The input `num` must be between 1 and 10^9.
Assumptions:
• The input `num` is always a positive integer.
Input: num = 8
Explanation: For `num + 1 = 9`, the closest divisors are `3` and `3`, and for `num + 2 = 10`, the closest divisors are `2` and `5`. The pair `[3, 3]` is returned as it has the smallest absolute difference.

Input: num = 25
Explanation: For `num + 1 = 26`, the closest divisors are `2` and `13`, and for `num + 2 = 27`, the closest divisors are `3` and `9`. The pair `[5, 6]` is returned because it forms the closest divisors.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus