LeetCode 1401 Elixir solution

LeetCode 1401 problem link: 1401. Circle and Rectangle Overlapping


Solution Description

For this solution I use Geometry and Clamping patterns. For each coordinate, min and max clamp the circle center to the rectangle boundaries to find the closest point on or inside the rectangle.
Then I calculate the horizontal and vertical distances from the circle center to this point. The circle overlaps the rectangle when the squared distance is less than or equal to radius * radius. Using squared distance avoids calculating a square root.


Time complexity: O(1)
Space complexity: O(1)


defmodule Solution do
  @spec check_overlap(
    radius :: integer,
    x_center :: integer,
    y_center :: integer,
    x1 :: integer,
    y1 :: integer,
    x2 :: integer,
    y2 :: integer
  ) :: boolean

  def check_overlap(radius, x_center, y_center, x1, y1, x2, y2) do
    closest_x = max(x1, min(x_center, x2))
    closest_y = max(y1, min(y_center, y2))

    dx = x_center - closest_x
    dy = y_center - closest_y

    dx * dx + dy * dy <= radius * radius
  end
end