Rectangle Overlap - Problem
Imagine you're designing a collision detection system for a 2D game! ๐ฎ
You have two axis-aligned rectangles represented as lists [x1, y1, x2, y2], where:
(x1, y1)is the bottom-left corner(x2, y2)is the top-right corner- All edges are parallel to the X and Y axes
Your task is to determine if these rectangles overlap - meaning they share some positive area in common. Two rectangles that only touch at corners or edges do not count as overlapping!
Goal: Return true if the rectangles overlap, false otherwise.
Example: Rectangle A: [0,0,2,2] and Rectangle B: [1,1,3,3] โ They overlap in the area from (1,1) to (2,2) โ Return true
Input & Output
example_1.py โ Basic Overlap
$
Input:
rec1 = [0,0,2,2], rec2 = [1,1,3,3]
โบ
Output:
true
๐ก Note:
The rectangles overlap in the area from (1,1) to (2,2), which has positive area.
example_2.py โ No Overlap (Separated)
$
Input:
rec1 = [0,0,1,1], rec2 = [2,2,3,3]
โบ
Output:
false
๐ก Note:
Rectangle 1 is completely separated from Rectangle 2 (both horizontally and vertically), so no overlap.
example_3.py โ Edge Touch (No Overlap)
$
Input:
rec1 = [0,0,1,1], rec2 = [1,0,2,1]
โบ
Output:
false
๐ก Note:
The rectangles only touch along the edge x=1, but don't share any positive area, so no overlap.
Constraints
-
Each rectangle
rec[i] = [xi1, yi1, xi2, yi2]where(xi1, yi1)is the bottom-left corner and(xi2, yi2)is the top-right corner -
-109 โค xi1 < xi2 โค 109 -
-109 โค yi1 < yi2 โค 109 - Both rectangles are guaranteed to be valid (bottom-left coordinates are less than top-right coordinates)
Visualization
Tap to expand
Understanding the Visualization
1
Parse Coordinates
Extract x1,y1,x2,y2 for both rectangles
2
Check Left Separation
Is rect1 completely left of rect2? (x2 <= x3)
3
Check Right Separation
Is rect1 completely right of rect2? (x1 >= x4)
4
Check Vertical Separation
Is rect1 completely above/below rect2?
5
Determine Overlap
If no separation exists, rectangles must overlap!
Key Takeaway
๐ฏ Key Insight: Instead of checking all possible overlap scenarios, simply verify that the rectangles are NOT completely separated in any direction (left, right, above, below). If they're not separated, they must overlap!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code