LeetCode 492: Construct the Rectangle Solution

Master LeetCode problem 492 (Construct the Rectangle), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

492. Construct the Rectangle

Easy

Problem Explanation

Explanation

To solve this problem, we need to find the dimensions of a rectangle with a given area such that the difference between the length and width is minimized. We can start by iterating from the square root of the given area down to 1 and checking if the current number is a valid width for the given area. If we find a valid width, we can calculate the corresponding length and return the result.

  • Start iterating from the square root of the given area down to 1
  • Check if the current number is a valid width by dividing the area by the current number and checking if the remainder is 0
  • If a valid width is found, calculate the length and return the result

Time complexity: O(sqrt(area)) Space complexity: O(1)

Solution Code

class Solution {
    public int[] constructRectangle(int area) {
        int width = (int) Math.sqrt(area);
        while (area % width != 0) {
            width--;
        }
        return new int[]{area / width, width};
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 492 (Construct the Rectangle)?

This page provides optimized solutions for LeetCode problem 492 (Construct the Rectangle) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 492 (Construct the Rectangle)?

The time complexity for LeetCode 492 (Construct the Rectangle) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 492 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 492 in Java, C++, or Python.

Back to LeetCode Solutions