Classifying Circle Pair Relationships
Math & Bit ManipulationModel answerLast updated
Determine whether two circles intersect at two points, are tangent at one point, or have no boundary contact.
You're building a graphics layer that needs to understand how circles relate to each other spatially.
Write a function that takes pairs of circles and classifies each pair's relationship. Each circle is defined by its center coordinates and radius: (x1, y1, r1, x2, y2, r2).
Input: A list of tuples, where each tuple contains six numbers representing two circles.
Output: A list of strings in corresponding order. Each string must be one of:
"intersect"— the circle boundaries cross at two distinct points"touch"— the circle boundaries meet at exactly one point (externally or internally tangent)"separate"— the circle boundaries never meet (completely disjoint or one entirely inside the other)
Special case: When two circles are identical (same center, same radius), classify as "intersect".
Constraints:
- Radii are non-negative
- Coordinates can be integers or floats
- For floating-point inputs, use appropriate tolerance when checking equality
Example:
Input: [(0, 0, 1, 3, 0, 1), (0, 0, 2, 2, 0, 1), (0, 0, 5, 1, 0, 1)]
Output: ["separate", "intersect", "separate"]
The first pair is too far apart, the second pair crosses at two points, and the third has one circle completely inside the other.
Hints
Hint 1
Calculate the distance between centers and compare it to the sum and difference of the radii
Hint 2
Work with squared distances to avoid square root calculations and improve numerical accuracy
Hint 3
Handle the coincident circle case (same center and radius) separately before checking other conditions
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Understanding the Problem
Before writing code, I need to clarify what "intersection" means for this problem. The key insight is that we're checking whether the boundaries (perimeters) of the circles interact, not whether the circular regions overlap.
Classification rules:
- Intersect: Boundaries cross at two points, or circles are identical
- Touch: Boundaries meet at exactly one point (tangent)
- Separate: Boundaries don't meet at all (either far apart or one contained inside the other with no contact)
A common mistake is assuming a small circle inside a large circle should be "intersect" because their areas overlap. For boundary-based classification, that's actually "separate" unless the boundaries touch.
Approach
The solution relies on comparing the center-to-center distance with the sum and difference of radii.
Let:
d= distance between centersS= r1 + r2 (sum of radii)D= |r1 - r2| (absolute difference of radii)
Geometric analysis:
d > S: Circles are too far apart → separated = S: Circles touch externally → touchD < d < S: Boundaries cross at two points → intersectd = D: One circle touches the other internally → touchd < D: One circle is strictly inside the other → separated = 0andr1 = r2: Identical circles → intersect
Key optimization: Compare squared distances instead of taking square roots. Since all values are non-negative, d² vs S² gives the same ordering as d vs S, but avoids floating-point error from sqrt and is exact for integer inputs.
Handling Edge Cases
Floating-point tolerance: When checking equality (for "touch"), exact comparison fails due to rounding. Use a relative tolerance: two values are equal if their difference is small relative to their magnitude.
Coincident circles: When centers match and radii match, the circles are identical. This is a special case with infinitely many intersection points.
Zero radius: A point on another circle's boundary should be "touch". Two identical points are coincident circles, so "intersect".
Concentric circles: Different radii with the same center gives d = 0 < D, correctly classified as "separate".
Complexity
Time: O(1) per pair, O(n) for n pairs Space: O(n) for output, O(1) auxiliary space
Implementation
from typing import List, Tuple
def classify_circle_pair(x1: float, y1: float, r1: float,
x2: float, y2: float, r2: float) -> str:
"""Classify the relationship between two circles."""
if r1 < 0 or r2 < 0:
raise ValueError("Radii must be non-negative")
# Use exact comparison for integers, tolerance for floats
is_integer = all(isinstance(v, int) for v in [x1, y1, r1, x2, y2, r2])
epsilon = 0 if is_integer else 1e-9
def approx_equal(a: float, b: float) -> bool:
if is_integer:
return a == b
tolerance = epsilon * max(1.0, abs(a), abs(b))
return abs(a - b) <= tolerance
# Compute squared distance to avoid sqrt
dx, dy = x2 - x1, y2 - y1
dist_sq = dx * dx + dy * dy
sum_radii_sq = (r1 + r2) ** 2
diff_radii_sq = (r1 - r2) ** 2
# Special case: identical circles
if approx_equal(dist_sq, 0) and approx_equal(diff_radii_sq, 0):
return "intersect"
# Check against sum of radii
if dist_sq > sum_radii_sq and not approx_equal(dist_sq, sum_radii_sq):
return "separate" # Too far apart
if approx_equal(dist_sq, sum_radii_sq):
return "touch" # External tangency
# Now we know dist_sq < sum_radii_sq
# Check against difference of radii
if dist_sq > diff_radii_sq and not approx_equal(dist_sq, diff_radii_sq):
return "intersect" # Two crossing points
if approx_equal(dist_sq, diff_radii_sq):
return "touch" # Internal tangency
return "separate" # One strictly inside the other
def classify_circles(pairs: List[Tuple[float, float, float,
float, float, float]]) -> List[str]:
"""Classify multiple circle pairs."""
return [classify_circle_pair(*pair) for pair in pairs]
# Test cases
test_pairs = [
(0, 0, 1, 3, 0, 1), # separate (far apart)
(0, 0, 1, 2, 0, 1), # touch (external)
(0, 0, 2, 2, 0, 1), # intersect (cross)
(0, 0, 3, 1, 0, 2), # touch (internal)
(0, 0, 5, 1, 0, 1), # separate (contained, no contact)
(0, 0, 2, 0, 0, 2), # intersect (identical)
(0, 0, 2, 0, 0, 1), # separate (concentric)
]
print(classify_circles(test_pairs))
# Output: ['separate', 'touch', 'intersect', 'touch', 'separate', 'intersect', 'separate']
Common Mistakes
- Using
sqrtunnecessarily: Introduces rounding error and is slower - Exact equality on floats:
d == r1 + r2fails for tangent circles with floating-point coordinates - Forgetting containment: Assuming any overlap means "intersect", when one circle inside another is "separate"
- Missing the coincident case: Identical circles should be handled explicitly
- Wrong tolerance: Using absolute tolerance fails for very large or very small coordinates
Follow-up Questions
An interviewer might ask:
-
"What if we care about area overlap instead of boundary contact?" Change the contained case to return "intersect" instead of "separate".
-
"Can you vectorize this for many pairs at once?" With NumPy, compute all distances and thresholds as arrays and apply the same comparisons element-wise.
-
"What about 3D spheres?" The same logic applies—just compute distance in 3D space.