223. Rectangle Area Leetcode Solution

Rectangle Area Leetcode Problem :

Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.

The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2).

The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2).

jump game leetcode

Rectangle Area Leetcode Solution :

Constraints :

  • -10^4 <= ax1 <= ax2 <= 10^4
  • -10^4 <= ay1 <= ay2 <= 10^4
  • -10^4 <= bx1 <= bx2 <= 10^4
  • -10^4 <= by1 <= by2 <= 10^4

Example 1:

  • Input: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
  • Output: 16

Intuition :

Intuition of this problem is simple. To calculate the common area between two rectangles,we use (area_1 + area_2 – common_area(between two rectangles)).

Approach :

Firstly,we will calculate the area1 and area2 by simple mathematics .i.e. length * width .Now our main task is compute the common area.There are few cases that can exist between two rectangles that are as follows:

Case 1: Rectangle 1 is enclosed in rectangle 2.

  • Condition: ax1>=bx1 && ax2<=bx2 && ay1>=by1 && ay2<=by2
  • Common Area:Area 1

Case 2: Rectangle 2 is enclosed in rectangle 1.

  • Condition: bx1>=ax1 && bx2<=ax2 && by1>=ay1 && by2<=ay2
  • Common Area:Area 2

Case 3: Rectangle 1 and rectangle 2 share some common area.

  • Condition: max(ax1,bx1)<= min(ax2,bx2) && max(ay1,by1)<= min(ay2,by2)
  • common_area= (max(ax1,bx1)- min(ax2,bx2))*(max(ay1,by1)- min(ay2,by2))

Case 4: Rectangle 1 and rectangle 2 has no common area.

  • Common area=0

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription