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
Rectangle ARectangle BOverlap AreaKey Insight:Rectangles overlap โ†”NOT separated in ANY directionABโ† SeparatedABโ† Overlapping
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!
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
28.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen