The problem of constructing a rectangle is a popular coding interview question. Here you will be given the area of a rectangle, and you need to return the height and width of the rectangle to solve this problem. So if you want to know how to solve this problem, this article is for you. This article will take you through how to construct a rectangle using Python.
Construct the Rectangle Problem
In the constructing rectangle problem, we need to return the dimensions of a rectangle with its given area such that its width and height differ by the smallest possible number. For example, look at the input and output of this problem shown below:
- Input: 24 | Output: [6, 4]
In the above example, the input area is 24. So the dimensions of the rectangle can be 6×4, and the difference between 6 and 4 is 2 (smallest possible number).
Construct the Rectangle using Python
I hope you have now understood what the problem of constructing the rectangle means. Below is how you can solve this problem using the Python programming language:
import math def constructRectangle(area): w = int(math.sqrt(area)) while area % w != 0: w -= 1 return [area // w, w] area = 24 print(constructRectangle(area))
Output: [6, 4]
So this is how you can solve the constructing rectangle problem using Python. You can find many more practice questions for coding interviews solved and explained using Python here.
Summary
In the constructing rectangle problem, we need to return the dimensions of a rectangle with its given area such that its width and height differ by the smallest possible number. I hope you liked this article on how to solve the problem of constructing a rectangle using Python. Feel free to ask valuable questions in the comments section below.