EasyNo. 0492

Construct the Rectangle — LeetCode 492 Python Solution

Topics
Math
Reading time
2 min

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

PythonSolution
class Solution:
    def constructRectangle(self, area: int) -> List[int]:
        w = int(sqrt(area))
        while area % w != 0:
            w -= 1
        return [area // w, w]

Complexity

Time
O(n) or O(1)
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0002Add Two NumbersMedium
0007Reverse IntegerMedium
0009Palindrome NumberEasy
0043Multiply StringsMedium
0048Rotate ImageMedium
0050Pow(x, n)Medium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.