Construct the Rectangle - Problem
Design the Perfect Rectangle

As a web developer, you need to design a rectangular web page with specific dimensions. Given the total area of the page, find the length L and width W that create the most square-like rectangle possible.

Requirements:
• The area must exactly equal the given target area
• Width W ≤ Length L (width cannot exceed length)
• The difference |L - W| should be minimized

Goal: Return [L, W] where L and W are the optimal dimensions.

Example: For area = 4, return [2, 2] (a perfect square). For area = 6, return [3, 2] (closest to square while satisfying L ≥ W).

Input & Output

example_1.py — Basic Square
$ Input: area = 4
Output: [2, 2]
💡 Note: Area 4 can form a perfect square 2×2. Since L=W=2, this satisfies L≥W and minimizes |L-W|=0.
example_2.py — Near-Square Rectangle
$ Input: area = 6
Output: [3, 2]
💡 Note: Area 6 has factors: 1×6 and 2×3. Between [6,1] (diff=5) and [3,2] (diff=1), we choose [3,2] as it's closest to square.
example_3.py — Prime Number
$ Input: area = 7
Output: [7, 1]
💡 Note: Area 7 is prime, so only factors are 1×7. Result is [7,1] - the only valid rectangle.

Constraints

  • 1 ≤ area ≤ 107
  • area is always a positive integer
  • The returned length L must be ≥ width W

Visualization

Tap to expand
Finding Optimal Rectangle for Area = 12√12 ≈ 3.46 → Start checking from width = 3Perfect Square3.46 × 3.46Not Integer!Width = 312 ÷ 3 = 4 ✓FOUND!Alternative: W=2L=6, Diff=4Alternative: W=1, L=12Diff=11 (worst)OptimalResult: [4, 3]Length = 4, Width = 3Difference = |4 - 3| = 1 (minimal)Area = 4 × 3 = 12 ✓
Understanding the Visualization
1
Calculate Target
Find √area as our ideal starting point for a square
2
Test Divisibility
Check if current width divides area evenly
3
Adjust if Needed
If not divisible, decrease width by 1 and try again
4
Found Solution
First valid width gives us the optimal rectangle
Key Takeaway
🎯 Key Insight: The optimal rectangle always has its width as the largest factor ≤ √area, making the search efficient and the result closest to a square.
Asked in
Google 23 Amazon 18 Meta 15 Apple 12
28.4K Views
Medium Frequency
~12 min Avg. Time
886 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