Problem solution · Python

Circle and Rectangle Overlapping

Circle and Rectangle Overlapping: a Python solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Direct simulation
Source
Kamyu LeetCode Solutions
Length
46 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Circle and Rectangle Overlapping, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 46 lines of Python from the credited upstream file circle-and-rectangle-overlapping.py.
  • The implementation keeps its working state in language-native values and containers.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeCircle and Rectangle Overlapping · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(1)# Space: O(1) class Solution(object):    def checkOverlap(self, radius, x_center, y_center, x1, y1, x2, y2):        """        :type radius: int        :type x_center: int        :type y_center: int        :type x1: int        :type y1: int        :type x2: int        :type y2: int        :rtype: bool        """        x1 -= x_center        y1 -= y_center        x2 -= x_center        y2 -= y_center        x = x1 if x1 > 0 else x2 if x2 < 0 else 0        y = y1 if y1 > 0 else y2 if y2 < 0 else 0        return x**2 + y**2 <= radius**2  # Time:  O(1)# Space: O(1)class Solution2(object):    def checkOverlap(self, radius, x_center, y_center, x1, y1, x2, y2):        """        :type radius: int        :type x_center: int        :type y_center: int        :type x1: int        :type y1: int        :type x2: int        :type y2: int        :rtype: bool        """        x1 -= x_center        y1 -= y_center        x2 -= x_center        y2 -= y_center                x = min(abs(x1), abs(x2)) if x1*x2 > 0 else 0        y = min(abs(y1), abs(y2)) if y1*y2 > 0 else 0        return x**2 + y**2 <= radius**2 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗