Construct the Rectangle - 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.
  • The width W should not be larger than the length L, which means L >= W.
  • The difference between length L and width W should be as small as possible.

Return an array [L, W] where L and W are the length and width of the web page you designed in sequence.

Input & Output

Example 1 — Perfect Square Area
$ Input: area = 4
Output: [2,2]
💡 Note: Area 4 can form a 2×2 square, which has the minimum possible difference of 0
Example 2 — Non-Square Area
$ Input: area = 6
Output: [3,2]
💡 Note: Area 6 has factors: 1×6 (diff=5) and 2×3 (diff=1). The 3×2 rectangle has minimum difference
Example 3 — Prime Number Area
$ Input: area = 7
Output: [7,1]
💡 Note: Area 7 is prime, so only possible rectangle is 7×1

Constraints

  • 1 ≤ area ≤ 107

Visualization

Tap to expand
Construct the Rectangle INPUT Target Area 4 square units Possible as: 4 x 1 2 x 2 Input: area = 4 ALGORITHM STEPS (Square Root Approach) 1 Calculate sqrt(area) sqrt(4) = 2 2 Start W from floor(sqrt) W starts at 2 3 Check divisibility 4 % 2 == 0? Yes! 4 Calculate L = area/W L = 4/2 = 2 Iteration Process: W = 2: 4 % 2 = 0 OK Found! L = 4 / 2 = 2 L >= W: 2 >= 2 OK Valid! Return [2, 2] FINAL RESULT L = 2 W = 2 Area = 4 (2 x 2) Output: [2, 2] OK Verified! L >= W, Min difference Key Insight: Starting from sqrt(area) and decrementing W ensures we find the pair with minimum difference first. For a perfect square like 4, sqrt gives the exact answer immediately. Time: O(sqrt(n)), Space: O(1). The closer W is to sqrt(area), the smaller |L - W| becomes, making the rectangle closer to a square. TutorialsPoint - Construct the Rectangle | Square Root Approach
Asked in
Google 15 Amazon 12
23.0K Views
Medium Frequency
~15 min Avg. Time
680 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen