1401. Circle and Rectangle Overlapping LeetCode Solution

In this guide, you will get 1401. Circle and Rectangle Overlapping LeetCode Solution with the best time and space complexity. The solution to Circle and Rectangle Overlapping problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Circle and Rectangle Overlapping solution in C++
  4. Circle and Rectangle Overlapping solution in Java
  5. Circle and Rectangle Overlapping solution in Python
  6. Additional Resources
1401. Circle and Rectangle Overlapping LeetCode Solution image

Problem Statement of Circle and Rectangle Overlapping

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.

Example 1:

Input: radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1
Output: true
Explanation: Circle and rectangle share the point (1,0).

Example 2:

Input: radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1
Output: false

Example 3:

Input: radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1
Output: true

Constraints:

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

Complexity Analysis

  • Time Complexity: O(1)
  • Space Complexity: O(1)

1401. Circle and Rectangle Overlapping LeetCode Solution in C++

class Solution {
 public:
  bool checkOverlap(int radius, int x_center, int y_center, int x1, int y1,
                    int x2, int y2) {
    auto clamp = [&](int center, int mn, int mx) {
      return max(mn, min(mx, center));
    };

    // the closest point to the circle within the rectangle
    int closestX = clamp(x_center, x1, x2);
    int closestY = clamp(y_center, y1, y2);

    // the distance between the circle's center and its closest point
    int distanceX = x_center - closestX;
    int distanceY = y_center - closestY;

    // If the distance < the circle's radius, an intersection occurs.
    return (distanceX * distanceX) + (distanceY * distanceY) <=
           (radius * radius);
  }
};
/* code provided by PROGIEZ */

1401. Circle and Rectangle Overlapping LeetCode Solution in Java

N/A
// code provided by PROGIEZ

1401. Circle and Rectangle Overlapping LeetCode Solution in Python

N/A
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.