Problem 492

Abstract / Summary

Given a number of small squares, create a rectangle with area equal to that number and dimensions as close as possible.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0492.py

class Solution:
    def constructRectangle(self, area: int) -> List[int]:
        w = int(sqrt(area))
        while area % w > 0:
            w -= 1
        return [ area // w, w ]
6 lines | 187 bytes | submitted August 23, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 64% (200k+ submissions).

Typical patterns to solve this problem:
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method that, given a positive integer area, returns a pair of integers representing the length and width of a rectangle whose area equals the input. The rectangle is chosen so that the length is not smaller than the width and the difference between the two sides is minimized. The algorithm relies on elementary arithmetic and a simple search loop.

Key Steps

The method proceeds through three distinct phases, each illustrated by a concise code excerpt.

Determining the Starting Width

w = int(sqrt(area))

The integer part of the square root of area is taken as the initial candidate for the rectangle’s width. This choice positions the search at the point where the two sides would be equal if area were a perfect square, thereby providing a natural upper bound for the width.

Searching for a Divisor

while area % w > 0:
    w -= 1

If the initial candidate does not divide area evenly, the loop decrements w one unit at a time until a divisor is found. Because the loop starts at the square-root boundary, the number of iterations is limited to the distance between the square root and the nearest lower divisor.

Computing the Complementary Length

return [area // w, w]

Once a suitable width w is identified, integer division yields the corresponding length. The result is returned as a two-element list with the larger dimension first, satisfying the requirement that length ≥ width.

Edge Cases Handled

When area is a perfect square, the initial width w already satisfies area % w == 0. The loop body is skipped entirely, and the method returns [w, w], delivering a square rectangle with zero side-difference.

If area is a prime number, the only divisors are 1 and the number itself. The loop will decrement w repeatedly until it reaches 1, at which point area % 1 is zero. The method then returns [area, 1], the only possible rectangle for a prime area.

For the smallest valid input, area = 1, the square root is 1, the loop does not execute, and the method returns [1, 1], correctly representing a unit square.

Performance Optimizations

The algorithm’s primary efficiency gain stems from initializing the search at the integer square root of area. By doing so, it avoids a naïve scan from area down to 1, which would be prohibitively expensive for large inputs. Starting at the square-root boundary ensures that the loop iterates at most sqrt(area) times in the worst case (e.g., when area is prime). Each iteration performs a single modulus operation and a decrement, both of constant cost.

Additionally, the use of integer division (area // w) to compute the complementary side eliminates any need for floating-point arithmetic after the divisor is found, preserving precision and avoiding unnecessary conversions.

Overall, the method delivers a concise solution that leverages mathematical properties to keep the search space minimal while handling all valid input values gracefully.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of square blocks and you want to arrange them into a perfect rectangle. The size of the rectangle is decided by the number of blocks you have. To make the rectangle look nice and not too stretched out, you want the length and the width to be as close to each other as possible.

The code starts by guessing that the width should be about the same as the square root of the number of blocks. It checks to see if those blocks fit perfectly into a rectangle with that width. If they do not fit, it makes the width just a little bit smaller and checks again. It keeps making the width smaller until it finds a width that divides the total number of blocks perfectly. Once it finds the right number, it figures out what the length should be so that all the blocks are used.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.12 | σ = 1.89

Complexity Analysis

Time: sublinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python Java Go
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
everthis JS
fartem Ruby
halfrost Go
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
varunu28 Java
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
everthis JavaScript
fartem Ruby
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
varunu28 Java
yuanliu666 Kotlin
zfang399 C++
33 links | 22 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 easy 1 medium
3 solutions   August 23, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality