Meta Data#
Difficulty: easy First Attempt: 2022-08-24
- Submissions: Runtime Error → Wrong Answer ×3 → Accepted ×3 → Wrong Answer → Runtime Error → Accepted
Approach#
L >= W with L - W minimal means W should be as large as possible without exceeding √area (Math Template 4). Scan down from int(√area); the first W dividing area is the answer with L = area // W. W = 1 always divides, so the search always succeeds.
My Attempts#
This took 10 submissions:
- Attempt 1’s
range(area // 2)started at 0, soarea % 0raised ZeroDivisionError. range(1, area // 2)then had the wrong upper bound:area = 4tried only 1, returning[4, 1]instead of[2, 2], and forareaof 1, 2 or 3 the range was empty, leavingwat 0.- Bounding by
√areapassed. A rewrite that scans down from√areaand returns the first divisor then had one version returningNoneand one misnamed variable before passing on the third try.
Solution#
class Solution:
def constructRectangle(self, area: int) -> List[int]:
w = isqrt(area)
while area % w:
w -= 1
return [area // w, w]
Complexity#
Time O(√area), space O(1).
Mistakes to Avoid#
- The width’s upper bound is
√area, notarea // 2: forarea = 4,range(1, 2)only tries 1. - Starting
rangeat 0 divides by zero.
Interview Explanation#
With L at least W and the gap minimal, W should be as close to √area as possible, so I scan down from √area for the first divisor and set L = area / W. Time O(√area).
