#1362
Closest Divisors
MediumMathMathTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(sqrt(n)) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(sqrt(n))Space O(1)
The optimal approach leverages the fact that we only need to check divisors up to the square root of the numbers. This significantly reduces the number of checks needed to find the closest divisors.
⚙️
Algorithm
3 steps- 1Step 1: Calculate num + 1 and num + 2.
- 2Step 2: For each of these two values, iterate from 1 to the square root of the number to find divisors.
- 3Step 3: For each divisor found, calculate its pair and track the pair with the smallest absolute difference.
solution.py13 lines
1import math
2
3def closestDivisors(num):
4 def findClosestDivisors(n):
5 closest = (1, n)
6 for i in range(1, int(math.sqrt(n)) + 1):
7 if n % i == 0:
8 j = n // i
9 if abs(i - j) < abs(closest[0] - closest[1]):
10 closest = (i, j)
11 return closest
12
13 return findClosestDivisors(num + 1) if findClosestDivisors(num + 1)[0] <= findClosestDivisors(num + 2)[0] else findClosestDivisors(num + 2)ℹ
Complexity note: This complexity is much better because we only check divisors up to the square root of the numbers, which drastically reduces the number of iterations needed.
- 1Divisors can be found efficiently by only checking up to the square root of the number.
- 2The closest divisors will have the smallest absolute difference, which can be tracked during the search.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.