Programming & Development / April 10, 2025

🔢 Problem 223. Rectangle Area

Geometry Math

🧩 Problem Statement

Given the coordinates of two opposite corners of a rectangle, find the area of the rectangle.

The coordinates of the two opposite corners of the rectangle are given as (x1, y1) and (x2, y2).

📘 Example

go

Input: x1 = -3, y1 = -3, x2 = 3, y2 = 3
Output: 36

📝 Explanation:

  • The rectangle's width is |x2 - x1| = 6.
  • The rectangle's height is |y2 - y1| = 6.
  • The area is width * height = 6 * 6 = 36.

🧠 Approach

To compute the area of a rectangle given two opposite corners, you need to:

  1. Compute the width of the rectangle using the absolute difference between the x-coordinates: width = |x2 - x1|.
  2. Compute the height of the rectangle using the absolute difference between the y-coordinates: height = |y2 - y1|.
  3. The area of the rectangle is simply: area = width * height.

Steps:

  1. Calculate the width using abs(x2 - x1).
  2. Calculate the height using abs(y2 - y1).
  3. Multiply the width and height to find the area.

Go Implementation

go

package main

import "fmt"

// Function to compute the absolute value
func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}

// Function to compute the area of the rectangle
func computeArea(x1, y1, x2, y2 int) int {
    // Calculate width and height
    width := abs(x2 - x1)
    height := abs(y2 - y1)
    
    // Compute the area of the rectangle
    return width * height
}

func main() {
    // Test case
    x1, y1, x2, y2 := -3, -3, 3, 3
    fmt.Println(computeArea(x1, y1, x2, y2)) // Output: 36
}

📦 Example Usage

go

func main() {
    x1, y1, x2, y2 := -3, -3, 3, 3
    fmt.Println(computeArea(x1, y1, x2, y2)) // Output: 36
}

⏱️ Time & Space Complexity

  • Time Complexity: O(1), as the computation involves basic arithmetic operations and the absolute value function.
  • Space Complexity: O(1), since we are only using a constant amount of space for storing the coordinates and the computed result.

This approach ensures constant time complexity for computing the area of the rectangle with just a few arithmetic operations.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex