Skip to content
Problem 492 · LeetCode 492(opens in a new tab)

Construct the Rectangle

EasyMath

You need to lay out a rectangle with a given area. Its length L and width W are whole numbers, L × W must equal the area, and the width may not be more than the length.

Among all such shapes, pick the one where the length and width are as close together as possible. Return [L, W].

Example 1

Input:  area = 52
Output: [13, 4]
Why:    52 = 52×1 = 26×2 = 13×4; 13 − 4 is the smallest gap
2 more examples and the constraints

Example 2

Input:  area = 13
Output: [13, 1]
Why:    13 is prime, so 13×1 is the only shape

Example 3

Input:  area = 81
Output: [9, 9]
Why:    a perfect square makes a square

Constraints

  • 1 ≤ area ≤ 10,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every widthO(area)
  2. Walk down from the square rootO(√area)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for an area of 10,000,000Verdict
Try every widthO(area)
Correct, wastes most of its loop
Walk down from the square rootO(√area)
Best; stops at the first divisor

area = the target area.

Edge cases to test

  • Area 1. The only shape is [1, 1].
  • Prime area. 13 gives [13, 1]: the loop walks all the way down to W = 1.
  • Perfect square. 81 gives [9, 9]: the first width tried already divides.
  • Largest area. 10,000,000 gives [3200, 3125]; its square root is about 3162.

Common mistakes

  • Returning [W, L] instead of [L, W], with the larger number first.
  • Walking up from 1 and stopping at the first divisor, which is always 1.
  • Starting from a rounded-up square root, which can pick a width larger than the length.

How to talk through it

  1. 1Clarify. Must both sides be whole numbers? Which comes first in the answer, the length or the width?
  2. 2Give the scan. Try every width and keep the last one that divides with W ≤ L; say it is O(area).
  3. 3Bound the width. W ≤ L means W × W ≤ area, so W is at most the square root. Closer to the root means a smaller gap.
  4. 4Code the walk down. Start at the integer square root and step down to the first divisor.
  5. 5Test out loud. Run 1, a prime, and a perfect square before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?