LeetCode 1401: Circle and Rectangle Overlapping Solution

Master LeetCode problem 1401 (Circle and Rectangle Overlapping), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1401. Circle and Rectangle Overlapping

Problem Explanation

Explanation

To determine if a circle and a rectangle overlap, we need to consider all possible scenarios where the circle and the rectangle intersect. The key idea is to find the closest point on the rectangle to the center of the circle and then check if that point lies within the circle. If it does, then the circle and rectangle overlap.

  1. Find the closest point on the rectangle to the center of the circle. This point may be inside the rectangle or on its boundary.
  2. Check if the closest point lies within the circle by calculating the distance between the center of the circle and the closest point.

Time complexity: O(1) as we are just performing some mathematical calculations. Space complexity: O(1) as we are using constant extra space.

Solution Code

class Solution {
    public boolean checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) {
        int closestX = Math.max(x1, Math.min(xCenter, x2));
        int closestY = Math.max(y1, Math.min(yCenter, y2));
        
        int distanceX = xCenter - closestX;
        int distanceY = yCenter - closestY;
        
        return (distanceX * distanceX + distanceY * distanceY) <= radius * radius;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1401 (Circle and Rectangle Overlapping)?

This page provides optimized solutions for LeetCode problem 1401 (Circle and Rectangle Overlapping) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1401 (Circle and Rectangle Overlapping)?

The time complexity for LeetCode 1401 (Circle and Rectangle Overlapping) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1401 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1401 in Java, C++, or Python.

Back to LeetCode Solutions