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.
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:
- Height:
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 values.
- The right edge of the union will be the maximum of all values.
- The bottom edge of the union will be the minimum of all values.
- The top edge of the union will be the maximum of all 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) - 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
- Algorithm to tell if two arrays have identical members
- algorithm to trace border in 2D array
- Algorithm to transfer water from a set of bottles to another one metaphorically speaking
- Algorithm to transform a workflow DAG into parallel resource allocation?
- Algorithms based on number base systems?
- Algorithms for Deducing a Timeline / Chronology
- Algorithm to transform one word to another through valid words
- algorithm used to calculate 5 star ratings

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 courseTrack 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.