#1401

Circle and Rectangle Overlapping

Medium
MathGeometryGeometryDistance Calculation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

Instead of checking every point, we find the closest point on the rectangle to the circle's center and check if this point is within the circle. This reduces unnecessary calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Determine the closest point on the rectangle to the circle's center (xCenter, yCenter).
  2. 2Step 2: Clamp the circle's center coordinates to the rectangle's boundaries to find the closest point.
  3. 3Step 3: Calculate the distance from this closest point to the circle's center and compare it to the radius.
solution.py6 lines
1def checkOverlap(radius, xCenter, yCenter, x1, y1, x2, y2):
2    closestX = max(x1, min(xCenter, x2))
3    closestY = max(y1, min(yCenter, y2))
4    distanceX = closestX - xCenter
5    distanceY = closestY - yCenter
6    return (distanceX ** 2 + distanceY ** 2) <= radius ** 2

Complexity note: This solution runs in constant time since it only involves a few arithmetic operations regardless of the rectangle's size.

  • 1Finding the closest point on the rectangle to the circle's center is key to optimizing the solution.
  • 2Understanding the distance formula is crucial for determining overlap.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.