Construct the Rectangle — LeetCode 492 Python Solution
- Problem
- #492
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: The area of the rectangular web page you designed must equal to the given target area.
Example
- Input
- area = 4
- Output
- [2,2]
- Explanation
- The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
Python solution
class Solution:
def constructRectangle(self, area: int) -> List[int]:
w = int(sqrt(area))
while area % w != 0:
w -= 1
return [area // w, w]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) or O(1) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 492. Construct the Rectangle is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 492. Construct the Rectangle?
- LeetCode 492. Construct the Rectangle is rated Easy on LeetCode.
- What topics does LeetCode 492. Construct the Rectangle cover?
- LeetCode 492. Construct the Rectangle is tagged Math on LeetCode.