#492
Construct the Rectangle
EasyMathMathGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of checking all widths, we can start from the square root of the area and work downwards. This way, we find the closest dimensions with the smallest difference more efficiently.
⚙️
Algorithm
5 steps- 1Step 1: Calculate the integer square root of the area.
- 2Step 2: Loop from this square root down to 1.
- 3Step 3: For each width W, calculate L as area / W.
- 4Step 4: Check if L * W equals area and if L >= W.
- 5Step 5: Return the first valid pair [L, W] found.
solution.py7 lines
1import math
2
3def constructRectangle(area):
4 for W in range(int(math.sqrt(area)), 0, -1):
5 L = area // W
6 if L * W == area:
7 return [L, W]ℹ
Complexity note: The time complexity is O(n) in the worst case, but we usually find a solution much faster since we start from the square root.
- 1The optimal solution leverages the square root to minimize the number of checks.
- 2The conditions ensure that we only consider valid rectangles.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.