Problem Description
Determine if a given circle (defined by its radius and center coordinates) and an axis-aligned rectangle (defined by its bottom-left and top-right coordinates) overlap. In other words, check if there exists any point that lies inside both the circle and the rectangle.
Key Insights
- The circle and rectangle overlap if the shortest distance from the circle's center to the rectangle is less than or equal to the radius.
- The closest point on the rectangle to the circle's center can be found by "clamping" the circle's center coordinates to the rectangle’s bounds.
- Calculating the squared Euclidean distance between the circle's center and this closest point avoids unnecessary square root operations.
Space and Time Complexity
Time Complexity: O(1) Space Complexity: O(1)
Solution
The idea is to compute the closest point on the rectangle to the circle's center. For the x-coordinate, if the center is between x1 and x2, use the center’s x; otherwise, use the nearer boundary. Similarly, do this for the y-coordinate. Once the closest point is identified, calculate the squared distance between this point and the actual circle center. If this distance is less than or equal to the square of the radius, then the circle overlaps with the rectangle.