Construct the Rectangle — LeetCode 492 Python Solution

EasyMath
Problem
#492
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

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

Complexity

MeasureComplexity
TimeO(n) or O(1)
SpaceO(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.

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.

Get Stealth Interview