geometry
algorithms
computer science
computational geometry
rectangles

Algorithm to take the union of rectangles and to see if the union is still a rectangle

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

In computational geometry and computer graphics, determining the union of rectangles is a common operation. This article delves into creating an algorithm to obtain the union of multiple rectangles and to determine whether the resulting union can be considered a single rectangle. We'll explore the steps involved, technical examples, and conditions necessary for the union to remain a rectangle.

Mathematical Representation of Rectangles

A rectangle in a 2D plane can be described using two defining points, typically the bottom-left corner ((x1, y1) ) and the top-right corner ((x2, y2) ). This convention simplifies calculations:

  • Width: x2x1x2 - x1
  • Height: y2y1y2 - y1

Union of Rectangles

The union of two or more rectangles involves identifying a new boundary that encompasses all input rectangles. Mathematically, this means:

  • The left edge of the union will be the minimum of all x1x1 values.
  • The right edge of the union will be the maximum of all x2x2 values.
  • The bottom edge of the union will be the minimum of all y1y1 values.
  • The top edge of the union will be the maximum of all y2y2 values.

This leads to the bounding rectangle that covers all given rectangles. Here’s a simple algorithmic representation:

Algorithm to Find the Union

  • Rectangle A: (1, 2, 4, 5)
  • Rectangle B: (3, 3, 6, 6)
  • x1=min(1,3)=1x1 = \min(1, 3) = 1
  • y1=min(2,3)=2y1 = \min(2, 3) = 2
  • x2=max(4,6)=6x2 = \max(4, 6) = 6
  • y2=max(5,6)=6y2 = \max(5, 6) = 6
  • No Spaces Between: Ensure that there are no spaces or gaps between rectangles.
  • Aligned Boundaries: All adjacent edges of rectangles must align exactly where overlap occurs.
  • Rectangle C: (1, 1, 3, 3)
  • Rectangle D: (3, 2, 5, 5)

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms