Program to check two rectangular overlaps or not in Python

Suppose we have a rectangle that is represented as a list with four elements [x1, y1, x2, y2], where (x1, y1) is the coordinates of its bottom-left corner, and (x2, y2) is the coordinates of its top-right corner. Two rectangles overlap when the area of their intersection is positive. So, two rectangles that only touch at the corner or edges do not overlap.

So, if the input is like R1 = [0,0,2,2], R2 = [1,1,3,3], then the output will be True.

Visual Representation

R1 R2 Overlap X-axis Y-axis 0 1 2 3 0 1 2

Algorithm

To solve this, we will follow these steps ?

  • if R1[0]>=R2[2] or R1[2]<=R2[0] or R1[3]<=R2[1] or R1[1]>=R2[3], then
    • return False
  • otherwise,
    • return True

The logic checks for non-overlapping conditions: if any rectangle is completely to the left, right, above, or below the other, they don't overlap.

Example

Let us see the following implementation to get better understanding ?

class Solution:
    def solve(self, R1, R2):
        if (R1[0] >= R2[2]) or (R1[2] <= R2[0]) or (R1[3] <= R2[1]) or (R1[1] >= R2[3]):
            return False
        else:
            return True

ob = Solution()
print(ob.solve([0,0,3,3],[1,1,4,4]))
True

Method 2: Using Intersection Area

Alternative approach by calculating the intersection area directly ?

def rectangles_overlap(R1, R2):
    # Calculate intersection boundaries
    left = max(R1[0], R2[0])
    bottom = max(R1[1], R2[1])
    right = min(R1[2], R2[2])
    top = min(R1[3], R2[3])
    
    # Check if intersection has positive area
    if left < right and bottom < top:
        return True
    return False

# Test cases
print(rectangles_overlap([0,0,2,2], [1,1,3,3]))  # Overlapping
print(rectangles_overlap([0,0,1,1], [2,2,3,3]))  # Non-overlapping
print(rectangles_overlap([0,0,2,2], [2,2,3,3]))  # Only touching at corner
True
False
False

Comparison

Method Approach Time Complexity Best For
Non-overlap Check Check separation conditions O(1) Quick boolean result
Intersection Area Calculate overlap boundaries O(1) When you need overlap details

Conclusion

Both methods efficiently determine rectangle overlap in constant time. The first method uses separation logic, while the second calculates intersection boundaries. Use the first method for simple overlap detection and the second when you need intersection details.

Updated on: 2026-03-25T11:04:52+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements