Solving Leetcode Interviews in Seconds with AI: Circle and Rectangle Overlapping
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1401" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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
Explanation
Here's a breakdown of the solution:
- Find the Closest Point: Determine the point on the rectangle closest to the circle's center.
- Distance Check: Calculate the distance between the circle's center and this closest point. If the distance is less than or equal to the radius, the circle and rectangle overlap.
Handle Overlap: The logic automatically handles cases where the circle's center is inside the rectangle, as the closest point will be the center itself, and the distance will be 0.
Runtime Complexity: O(1), Storage Complexity: O(1)
Code
def checkOverlap(radius: int, xCenter: int, yCenter: int, x1: int, y1: int, x2: int, y2: int) -> bool:
"""
Checks if a circle and a rectangle overlap.
Args:
radius: The radius of the circle.
xCenter: The x-coordinate of the center of the circle.
yCenter: The y-coordinate of the center of the circle.
x1: The x-coordinate of the bottom-left corner of the rectangle.
y1: The y-coordinate of the bottom-left corner of the rectangle.
x2: The x-coordinate of the top-right corner of the rectangle.
y2: The y-coordinate of the top-right corner of the rectangle.
Returns:
True if the circle and rectangle overlap, False otherwise.
"""
closestX = max(x1, min(xCenter, x2))
closestY = max(y1, min(yCenter, y2))
distanceX = xCenter - closestX
distanceY = yCenter - closestY
distanceSquared = distanceX * distanceX + distanceY * distanceY
return distanceSquared <= radius * radius