Circle and Rectangle Overlapping - Problem
Imagine you're designing a collision detection system for a 2D game! You need to determine if a circular object (like a ball) and a rectangular object (like a platform) are overlapping.
You are given:
- A circle represented as
(radius, xCenter, yCenter) - An axis-aligned rectangle represented as
(x1, y1, x2, y2), where(x1, y1)are the coordinates of the bottom-left corner, and(x2, y2)are the coordinates of the top-right corner
Goal: Return true if the circle and rectangle overlap (share at least one point), false otherwise.
Key insight: Two shapes overlap if there exists any point (xi, yi) that belongs to both the circle and the rectangle simultaneously.
Input & Output
example_1.py โ Basic Overlap
$
Input:
radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1
โบ
Output:
true
๐ก Note:
The circle centered at (0,0) with radius 1 overlaps with the rectangle. The closest point on rectangle to circle center is (1,0), and distance from (0,0) to (1,0) is 1, which equals the radius.
example_2.py โ No Overlap
$
Input:
radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1
โบ
Output:
false
๐ก Note:
The circle centered at (1,1) with radius 1 does not overlap with the rectangle. The closest point on rectangle to circle center is (1,-1), and distance from (1,1) to (1,-1) is 2, which is greater than the radius of 1.
example_3.py โ Circle Inside Rectangle
$
Input:
radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = -1, x2 = 1, y2 = 1
โบ
Output:
true
๐ก Note:
The circle is completely inside the rectangle. The closest point on rectangle to circle center is the center itself (0,0), so distance is 0, which is less than radius 1.
Visualization
Tap to expand
Understanding the Visualization
1
Setup Shapes
Position the circle and rectangle in coordinate space
2
Find Closest Point
Identify the point on rectangle closest to circle center
3
Measure Distance
Calculate distance from circle center to closest point
4
Compare with Radius
If distance โค radius, shapes overlap
Key Takeaway
๐ฏ Key Insight: Geometric optimization reduces an area-checking problem to a single point-distance calculation!
Time & Space Complexity
Time Complexity
O(1)
Only performs constant number of min/max operations and one distance calculation
โ Linear Growth
Space Complexity
O(1)
Uses only a few variables to store coordinates and distance
โ Linear Space
Constraints
- 1 โค radius โค 2000
- -1000 โค xCenter, yCenter โค 1000
- -1000 โค x1 < x2 โค 1000
- -1000 โค y1 < y2 โค 1000
- All values are integers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code