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 ProblemRectangle (1,-1) to (3,1)Circle: center(0,0), radius=1Circle CenterClosest Pointdistance ≤ radius?Algorithm:1. Find closest point on rectangle2. Calculate distance to circle center3. Compare distance with radiusResult: OVERLAP!Output: true (shapes overlap)
Understanding the Visualization
1
Input
Circle (center, radius) and Rectangle (bottom-left, top-right)
2
Process
Find closest point on rectangle to circle center
3
Output
Return true if distance ≤ radius, false otherwise
Key Takeaway
🎯 Key Insight: The optimal solution uses coordinate clamping to find the closest rectangle point to the circle center in O(1) time
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