VOOZH about

URL: https://www.geeksforgeeks.org/dsa/perimeter-of-the-union-of-two-rectangles/

⇱ Perimeter of the Union of Two Rectangles - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Perimeter of the Union of Two Rectangles

Last Updated : 23 Jul, 2025

Given two arrays X[] and Y[], each of length 4, where (X[0], Y[0]) and (X[1], Y[1]) represents the bottom left and top right corners of one rectangle and (X[2], Y[2]) and (X[3], Y[3]) represents the bottom left and top right corners of the other rectangle, the task is to find the perimeter of the outer boundaries of the union of the two rectangles as shown below.

👁 Image

Examples:

Input: X[] = {-1, 2, 0, 4}, Y[] = {2, 5, -3, 3}
Output: 26
Explanation: Required Perimeter = 2 * ( (4 - (-1)) + (5 - (-3)) ) = 2*(8 + 5) = 26.

Input: X[] = {-3, 1, 1, 4}, Y[] = {-2, 3, 1, 5}
Output: 26
Explanation: Required Perimeter = 2 * ( (4 - (-3)) + (5 - (-2)) ) = 2*(7 + 7) = 28.

Approach: Follow the steps below to solve the problem:

  • Check if the rectangles formed by the given points intersect or not.
  • If found to be intersecting, then the perimeter can be calculated by the formula 2*((X[1] - X[0]) + (X[3] - X[2]) + (Y[1] - Y[0]) + (Y[3] - Y[2])).
  • Otherwise, print twice the sum of maximum differences between X and Y coordinates respectively, i.e. 2 * (max(X[]) - min(X[]) + max(Y[]) - min(Y[])).

Below is the implementation of the above approach:


Output: 
24

 

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment
Article Tags: