Python 1362.py
class Solution:
def closestDivisors(self, num: int) -> List[int]:
def factor(n):
high = int(sqrt(n))
for i in range(high, 0, -1):
if n % i == 0:
return i
a = factor(num + 1)
b = (num + 1) // a
x = factor(num + 2)
y = (num + 2) // x
return [ a, b ] if abs(a - b) <= abs(x - y) else [ x, y ]
Difficulty
and has an acceptance rate of about 61% (40k+ submissions).
Typical patterns to solve this problem:
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the “closest divisors” problem by examining the two numbers that are one and two greater than the input num. For each of these candidates it finds a pair of divisors whose product equals the candidate and whose absolute difference is as small as possible. The final result is the pair with the smaller difference between the two candidates.
Core Components
Factor Helper
def factor(n):
high = int(sqrt(n))
for i in range(high, 0, -1):
if n % i == 0:
return i
The helper factor receives an integer n and searches for the greatest divisor not exceeding the square-root of n. By starting the loop at high and moving downward, the first divisor encountered is the one that yields the pair of factors closest to each other. The function returns only the smaller factor; the larger factor is derived by integer division.
Computing Divisor Pairs
a = factor(num + 1)
b = (num + 1) // a
x = factor(num + 2)
y = (num + 2) // x
Two separate calls to factor are made: one for num + 1 and another for num + 2. The corresponding larger factors b and y are obtained by dividing the candidate numbers by the returned smaller factors a and x. At this point the algorithm has two candidate pairs: [a, b] for num + 1 and [x, y] for num + 2.
Selecting the Closest Pair
return [ a, b ] if abs(a - b) <= abs(x - y) else [ x, y ]
The final step compares the absolute differences of the two pairs. The pair with the smaller (or equal) difference is returned. The use of <= ensures that when both differences are identical, the pair derived from num + 1 is preferred.
Edge Cases Handled
When num is very small, such as 0 or 1, the candidates become 1, 2, 3, or 4. The factor function correctly handles these values because the loop includes i = 1, guaranteeing a divisor is always found. For a perfect square (e.g., num = 8 leading to num + 1 = 9), the square root itself is a divisor, so factor returns 3 and the pair [3, 3] is produced, achieving a difference of zero. For prime numbers, the only divisors are 1 and the number itself; the downward search quickly reaches 1, resulting in pairs like [1, prime]. The selection logic still works because the difference is computed correctly.
Performance Optimizations
The algorithm avoids exhaustive divisor enumeration by limiting the search range to the integer square root of each candidate. Starting the loop from this upper bound and moving downward means the first divisor found is the one that yields the most balanced factor pair, eliminating the need to examine smaller divisors. The early return inside the loop provides an immediate exit once the optimal divisor is identified, preventing unnecessary iterations. Using integer division to compute the complementary factor avoids floating-point operations, keeping the computation fast and memory-light. The overall structure performs only two bounded scans, one for each of the two candidate numbers, which makes the solution efficient even for large inputs.
ELI5 - Simplified Explanation
Imagine you have a big pile of building blocks and you want to arrange them into a perfect rectangle. Sometimes the blocks fit into a nice shape where the sides are almost the same length, and other times they make a long, skinny shape. This code is like a little helper that looks at a number and tries to find two side lengths that make a rectangle using that many blocks.
First, the code looks at the number you have plus one. It starts by picking a side length that is near the middle of that number and checks if it can divide the total blocks evenly. Once it finds a length that fits perfecty, it calculates the other side so you know exactly how wide and how tall your rectangle will be.
Next, the code repeats the same steps but uses your number plus two instead. It finds the side lengths for this new pile of blocks just like before.
Finally, the code compares the two rectangles you made. It checks which one is more like a square by looking at how close the two side lengths are to each other. It picks the set of sides that are closest together so you have the neatest looking rectangle possible.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||
|---|---|---|---|---|---|---|---|
| author | solutions | ||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||
| WalkCCC | C++ | Python | Java | ||||
| leetcode.ca | C++ | Python | Java | Go | |||
| Progiez | C++ | Python | Java | ||||
| github | black-shadows | C++ | |||||
| charles-wangkai | Java | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JS | ||||||
| keineahnung2345 | C++ | ||||||
| lkwq007 | Python | ||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||
| WalkCCC | C++, Python, Java | ||||||
| leetcode.ca | C++, Go, Java, Python | ||||||
| Progiez | C++, Java, Python | ||||||
| black-shadows | C++, C++ | ||||||
| charles-wangkai | Java | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JavaScript | ||||||
| keineahnung2345 | C++ | ||||||
| lkwq007 | Python |
Videos
Similar Problems
- problem 2521: Distinct Prime Factors of Product of Array
Solved On The Same Day
- problem 1365: How Many Numbers Are Smaller Than the Current Number
- problem 1389: Create Target Array in the Given Order
- problem 1394: Find Lucky Integer in an Array
- problem 1758: Minimum Changes To Make Alternating Binary String
- problem 1357: Apply Discount Every n Orders
- problem 1367: Linked List in Binary Tree
- problem 1386: Cinema Seat Allocation
- problem 1390: Four Divisors
- problem 1395: Count Number of Teams
- problem 1759: Count Number of Homogenous Substrings
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality