Problem 1362

Abstract / Summary

Given a number n, find two integers whose product is either n+1 or n+2 and whose difference is as small as possible.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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 ]
15 lines | 420 bytes | submitted November 9, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 61% (40k+ submissions).

Typical patterns to solve this problem:
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.74 | σ = 1.38

Complexity Analysis

Time: sublinear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
20 links | 10 authors | 6 languages

Videos

These are a few popular YouTube videos for this problem:
1 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

11 solutions   November 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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