Python 0492.py
class Solution:
def constructRectangle(self, area: int) -> List[int]:
w = int(sqrt(area))
while area % w > 0:
w -= 1
return [ area // w, w ]
Difficulty
and has an acceptance rate of about 64% (200k+ 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 defines a method that, given a positive integer area, returns a pair of integers representing the length and width of a rectangle whose area equals the input. The rectangle is chosen so that the length is not smaller than the width and the difference between the two sides is minimized. The algorithm relies on elementary arithmetic and a simple search loop.
Key Steps
The method proceeds through three distinct phases, each illustrated by a concise code excerpt.
Determining the Starting Width
w = int(sqrt(area))
The integer part of the square root of area is taken as the initial candidate for the rectangle’s width. This choice positions the search at the point where the two sides would be equal if area were a perfect square, thereby providing a natural upper bound for the width.
Searching for a Divisor
while area % w > 0:
w -= 1
If the initial candidate does not divide area evenly, the loop decrements w one unit at a time until a divisor is found. Because the loop starts at the square-root boundary, the number of iterations is limited to the distance between the square root and the nearest lower divisor.
Computing the Complementary Length
return [area // w, w]
Once a suitable width w is identified, integer division yields the corresponding length. The result is returned as a two-element list with the larger dimension first, satisfying the requirement that length ≥ width.
Edge Cases Handled
When area is a perfect square, the initial width w already satisfies area % w == 0. The loop body is skipped entirely, and the method returns [w, w], delivering a square rectangle with zero side-difference.
If area is a prime number, the only divisors are 1 and the number itself. The loop will decrement w repeatedly until it reaches 1, at which point area % 1 is zero. The method then returns [area, 1], the only possible rectangle for a prime area.
For the smallest valid input, area = 1, the square root is 1, the loop does not execute, and the method returns [1, 1], correctly representing a unit square.
Performance Optimizations
The algorithm’s primary efficiency gain stems from initializing the search at the integer square root of area. By doing so, it avoids a naïve scan from area down to 1, which would be prohibitively expensive for large inputs. Starting at the square-root boundary ensures that the loop iterates at most sqrt(area) times in the worst case (e.g., when area is prime). Each iteration performs a single modulus operation and a decrement, both of constant cost.
Additionally, the use of integer division (area // w) to compute the complementary side eliminates any need for floating-point arithmetic after the divisor is found, preserving precision and avoiding unnecessary conversions.
Overall, the method delivers a concise solution that leverages mathematical properties to keep the search space minimal while handling all valid input values gracefully.
ELI5 - Simplified Explanation
Imagine you have a big pile of square blocks and you want to arrange them into a perfect rectangle. The size of the rectangle is decided by the number of blocks you have. To make the rectangle look nice and not too stretched out, you want the length and the width to be as close to each other as possible.
The code starts by guessing that the width should be about the same as the square root of the number of blocks. It checks to see if those blocks fit perfectly into a rectangle with that width. If they do not fit, it makes the width just a little bit smaller and checks again. It keeps making the width smaller until it finds a width that divides the total number of blocks perfectly. Once it finds the right number, it figures out what the length should be so that all the blocks are used.
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++ | Java | |||||||||
| leetcode.ca | C++ | Python | Java | Go | |||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
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