Circle and Rectangle Overlapping - Problem

You are given a circle represented as (radius, xCenter, yCenter) and 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 of the rectangle.

Return true if the circle and rectangle are overlapped otherwise return false. In other words, check if there is any point (xi, yi) that belongs to the circle and the rectangle at the same time.

Input & Output

Example 1 — Circle Overlapping Rectangle
$ Input: radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1
Output: true
💡 Note: Circle at (0,0) with radius 1 overlaps the rectangle. The closest point on rectangle to circle center is (1,0), and distance = 1 which equals the radius, so they overlap.
Example 2 — Circle Not Overlapping Rectangle
$ Input: radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1
Output: false
💡 Note: Circle at (1,1) with radius 1 does not reach the rectangle. The closest point on rectangle is (1,-1), distance = 2 > radius 1, so no overlap.
Example 3 — Circle Contains Rectangle
$ Input: radius = 5, xCenter = 0, yCenter = 0, x1 = -1, y1 = -1, x2 = 1, y2 = 1
Output: true
💡 Note: Large circle with radius 5 completely contains the small rectangle, so they definitely overlap.

Constraints

  • 1 ≤ radius ≤ 2000
  • -104 ≤ xCenter, yCenter ≤ 104
  • -104 ≤ x1 < x2 ≤ 104
  • -104 ≤ y1 < y2 ≤ 104

Visualization

Tap to expand
Circle and Rectangle Overlapping INPUT (0,0) (1,-1) to (3,1) Contact! Circle: radius = 1 xCenter = 0 yCenter = 0 Rectangle: x1=1, y1=-1 x2=3, y2=1 ALGORITHM STEPS 1 Find Closest Point Clamp center to rect bounds closestX = clamp(0, 1, 3) = 1 closestY = clamp(0, -1, 1) = 0 2 Calculate Distance From center to closest point dx = 0 - 1 = -1 dy = 0 - 0 = 0 dist^2 = 1 + 0 = 1 3 Compare with Radius Check if dist^2 <= r^2 1 <= 1*1 = 1 (TRUE!) 4 Return Result Circle touches rectangle edge Point (1,0) is ON both circle and rectangle! FINAL RESULT Circle Rectangle Touching Point: (1, 0) Output: true Shapes overlap: OK Key Insight: The optimal approach finds the closest point on the rectangle to the circle's center by clamping the center coordinates to the rectangle's bounds. If the distance from the center to this closest point is less than or equal to the radius, the shapes overlap. Time: O(1), Space: O(1). TutorialsPoint - Circle and Rectangle Overlapping | Optimal Solution
Asked in
Google 15 Apple 12 Microsoft 8
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