File: construct-the-rectangle/solution.py

Date: 2026-06-06

Time: 15:50

Purpose

This file solves LeetCode #492 — Construct the Rectangle. Given an integer area, find dimensions [L, W] of a rectangle such that L * W == area, L >= W, and the difference L - W is minimized. It's a self-contained module: solution function + unit tests in one file.

Key Components

constructRectangle(area: int) -> list[int]

The sole public function. Contract:

TestConstructRectangle

Six test cases covering the key partitions: perfect squares (4, 1000000), primes (37), composites (12), edge case (1), and a larger composite (122122).

Patterns

Search downward from the square root. The optimal width is the largest factor of area that is ≤ sqrt(area). The code starts at isqrt(area) and decrements until it finds a divisor. This is the canonical approach — math.isqrt gives the integer square root (floor), and since we're searching for the largest factor ≤ sqrt, decrementing from there hits it first.

Inline tests. Solution and tests co-located in one file, runnable via python solution.py. Standard pattern across all ~500 problems in this repo.

Dependencies

Imports: math (for isqrt) and unittest (test harness). No project-internal imports.

Imported by: The "Imported By" list is misleading — those 400+ test files don't actually import *this* file. They share the same structural pattern (each problem's testsolution.py imports its sibling solution.py). The construct-the-rectangle/testsolution.py is the only real consumer.

Flow

1. Compute w = isqrt(area) — the largest integer whose square ≤ area.

2. While area % w != 0, decrement w. This walks down from sqrt until hitting a factor.

3. Return [area // w, w]. Since w ≤ sqrt(area), area // w ≥ sqrt(area), so L ≥ W is guaranteed.

Worst case: area is prime → the loop walks from isqrt(area) all the way down to 1. That's O(sqrt(area)) iterations, which for area = 10^7 is ~3162 steps — trivial.

Invariants

Error Handling

None — the function assumes valid input per the LeetCode constraint (1 <= area <= 10^7). No bounds checking, no exceptions. The unittest runner surfaces test failures.

Topics to Explore

Beliefs