↓Skip to main content
  1. LeetCode/

LeetCode 492: Construct the Rectangle

·2 mins· ·
LeetCode Easy Math
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

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, so area % 0 raised ZeroDivisionError.
  • range(1, area // 2) then had the wrong upper bound: area = 4 tried only 1, returning [4, 1] instead of [2, 2], and for area of 1, 2 or 3 the range was empty, leaving w at 0.
  • Bounding by √area passed. A rewrite that scans down from √area and returns the first divisor then had one version returning None and 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, not area // 2: for area = 4, range(1, 2) only tries 1.
  • Starting range at 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).

Related

LeetCode 415: Add Strings
·2 mins
LeetCode Easy Math String Simulation
LeetCode 415 note: add digit by digit from the ends with two pointers, tracking the carry, and append any leftover carry after the loop
LeetCode 441: Arranging Coins
·1 min
LeetCode Easy Math Binary-Search
LeetCode 441 note: find the largest k with k(k + 1) / 2 <= n; when moving right write l = mid + 1 or the search gets stuck
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 342: Power of Four
·1 min
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 note: confirm a power of two, then that the single 1 sits at an even position: n & 0x55555555 != 0, or n % 3 == 1
LeetCode 367: Valid Perfect Square
·1 min
LeetCode Easy Math Binary-Search
LeetCode 367 note: binary search [1, num] for mid² == num without using sqrt
LeetCode 405: Convert a Number to Hexadecimal
·2 mins
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 note: add 2^32 to a negative number to get its two’s complement, then take 4 bits at a time (% 16); handle 0 separately