Classify Pairwise Circle Boundary Relationships
Medium · Coding & Algorithms · Data Scientist · Technical Screen
Problem Statement
A 2D vector rendering pipeline inspects pairs of circular outlines in the Cartesian plane so downstream passes know whether two boundaries cross, meet at a single point, or never touch.
Implement two functions:
classify_pair(x1: float, y1: float, r1: float, x2: float, y2: float, r2: float) -> strclassify_pairs(pairs: List[Sequence[float]]) -> List[str]
Each 6-element record (x1, y1, r1, x2, y2, r2) specifies the center (x1, y1) and radius r1 of the first circle followed by the center (x2, y2) and radius r2 of the second circle. Let d = sqrt((x2 - x1)^2 + (y2 - y1)^2) denote the Euclidean distance between the two centers. Classify the boundary curves (outlines, not filled disks) of each pair as one of three lowercase strings:
"separate"— the two outlines share zero points: either the circles lie strictly outside one another (d > r1 + r2), or one circle sits strictly inside the other without reaching its boundary (d < |r1 - r2|)."touch"— the two outlines share exactly one point: external tangency (d == r1 + r2), internal tangency (d == |r1 - r2|withr1 != r2), or two coincident zero-radius points (d == 0andr1 == r2 == 0)."intersect"— the two outlines cross at two distinct points (|r1 - r2| < d < r1 + r2), or both circles share the exact same center and positive radius (d == 0andr1 == r2 > 0, overlapping everywhere along their circumference).
classify_pairs evaluates every (x1, y1, r1, x2, y2, r2) item in pairs and returns the list of status labels in the same order.
Examples
Example 1
Input:
pairs = [
(1, 2, 3, 5, 5, 2),
(0, 0, 4, 5, 0, 3),
(2, -1, 6, 3, -1, 2),
(-3, 0, 2, 4, 0, 3),
]
classify_pairs(pairs)
Output:
["touch", "intersect", "separate", "separate"]
Explanation:
(1, 2, 3)and(5, 5, 2)have center offsetsdx = 4, dy = 3, givingd = 5 == 3 + 2, so their rims meet externally at one point ("touch").(0, 0, 4)and(5, 0, 3)haved = 5, which lies strictly between|4 - 3| = 1and4 + 3 = 7, so their rims cross twice ("intersect").(2, -1, 6)and(3, -1, 2)haved = 1 < |6 - 2| = 4, so the radius-2 circle sits strictly inside the radius-6 circle without contacting its rim ("separate").(-3, 0, 2)and(4, 0, 3)haved = 7 > 2 + 3 = 5, so the two circles lie completely apart ("separate").
Example 2
Input:
pairs = [
(0, 0, 5, 3, 0, 2),
(4, -2, 3, 4, -2, 3),
(-1, 5, 0, -1, 5, 0),
]
classify_pairs(pairs)
Output:
["touch", "intersect", "touch"]
Explanation:
(0, 0, 5)and(3, 0, 2)haved = 3 == |5 - 2| > 0, so the smaller circle kisses the inner wall of the larger circle at(5, 0)("touch").(4, -2, 3)and(4, -2, 3)have identical centers and positive radius3, sharing infinitely many boundary points ("intersect").(-1, 5, 0)and(-1, 5, 0)are two degenerate points at(-1, 5), sharing that single point ("touch").
Example 3
Input:
classify_pair(0.0, 0.0, 0.15, 0.45, 0.0, 0.30)
Output:
"touch"
Explanation:
In binary floating-point arithmetic, 0.15 + 0.30 evaluates to 0.44999999999999996, which matches d = 0.45 within relative floating-point tolerance, so the two circles are classified as externally tangent ("touch").
Constraints
0 <= len(pairs) <= 10^5- Coordinates and radii may be Python
intorfloatvalues;boolvalues are not treated as exact integers. - When all six numbers in a pair are plain
intvalues, comparisons must be exact without floating-point rounding loss (even for coordinates and radii up to10^9or larger). - When any input in a pair is a
float, boundary equality atr1 + r2and|r1 - r2|uses a small relative tolerance (1e-9 * max(d, r1 + r2)) and must not overflow on large finite magnitudes (such as1e200). r1 >= 0andr2 >= 0for valid circles (0represents a degenerate point). RaiseValueErrorifr1 < 0,r2 < 0, or any coordinate or radius is non-finite (NaN,inf,-inf).
Step-by-step walkthrough
Understand the inputs, outputs, and outline rules
We are given a list of circle pairs, where each element
(x1, y1, r1, x2, y2, r2)describes Circle 1 with center(x1, y1)and radiusr1, and Circle 2 with center(x2, y2)and radiusr2. For every pair in order, we must return"intersect","touch", or"separate".Before writing any math, we need to be clear about what part of the circle we are comparing. Comparing
d(the distance between the two centers) with bothr1 + r2and|r1 - r2|classifies the circles' outlines (their boundary curves, not filled disks):"separate"(0 shared points): either the circles sit completely outside each other, or the smaller circle sits strictly inside the larger one without touching its rim."touch"(1 shared point): the two outlines kiss at a single point, either from the outside or from the inside."intersect"(2 or infinitely many shared points): the two outlines cross at two points, or both circles have the exact same center and positive radius so their outlines overlap completely.- Degenerate and invalid inputs: a radius of
0represents a single point ((x, y, 0)), so two identical points share 1 point ("touch"). A negative radius or non-finite float (NaNorinf) is invalid geometry and raisesValueError.
Slide two circles together to see all five geometric cases
Imagine fixing Circle 1 at
(0, 0)with radiusr1 = 3and sliding Circle 2 with radiusr2 = 1from far away on the right all the way to(0, 0). Herer1 + r2 = 4(the outer touch distance) and|r1 - r2| = 2(the inner touch distance).As the center-to-center distance
dshrinks from5down to1, the outlines pass through five distinct regimes:Circle 1: r1 = 3, Circle 2: r2 = 1 --> outer = r1 + r2 = 4, inner = |r1 - r2| = 2 Case 1: d = 5 (d > 4) ( C1 ) (C2) 0 shared points -> "separate" Case 2: d = 4 (d == 4) ( C1 )(C2) 1 shared point -> "touch" (external) Case 3: d = 3 (2 < d < 4) ( C1 ( )C2) 2 shared points -> "intersect" Case 4: d = 2 (d == 2, r1 != r2) ( C1 (C2) ) 1 shared point -> "touch" (internal) Case 5: d = 1 (d < 2) ( C1 (C2) ) 0 shared points -> "separate" (inside)Notice the one special case on the
d == |r1 - r2|boundary: whenr1 == r2 > 0,|r1 - r2|is0, sod == 0means both circles have the exact same center and positive radius. Instead of touching at one point, they are the exact same circle and return"intersect".Keep integer inputs exact by comparing squared distances
A naive implementation computes
d = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)and checksd == r1 + r2. Even when every input is an integer,math.sqrtconverts the answer to a 64-bit floating-point number, which only stores 53 bits of precision (about 15–17 decimal digits).Because
d,r1 + r2, and|r1 - r2|are all non-negative (>= 0), squaring both sides preserves<,==, and>without ever taking a square root:d > r1 + r2 <==> dx^2 + dy^2 > (r1 + r2)^2 d == r1 + r2 <==> dx^2 + dy^2 == (r1 + r2)^2 d < |r1 - r2| <==> dx^2 + dy^2 < (r1 - r2)^2Why this matters in practice: consider Circle 1
(0, 0, 600_000_000)and Circle 2(1_000_000_000, 1, 400_000_000):dx = 10^9, dy = 1 --> d^2 = 10^18 + 1 r1 + r2 = 10^9 --> (r1 + r2)^2 = 10^18Because
10^18 + 1 > 10^18, the circles are strictly"separate". Yet near10^18, consecutive 64-bit floats are128apart, sofloat(10**18 + 1)rounds straight to1e18andmath.sqrtfalsely reports"touch". Python integers have arbitrary precision, so comparing integer squares stays 100% exact at every scale.Handle floating-point inputs safely with hypot and relative tolerance
When inputs are floats, they arrive already rounded. For example, Circle 1
(0.0, 0.0, 0.15)and Circle 2(0.45, 0.0, 0.30)are meant to touch externally (0.15 + 0.30 = 0.45), but in binary floating-point0.15 + 0.30evaluates to0.44999999999999996, which would falsely look like"separate"under exact comparison.For float inputs, squaring no longer gives exactness, and comparing plain lengths is better for two reasons:
- No overflow on large floats:
math.hypot(dx, dy)rescales internally before squaring, so coordinates like1e200will not overflowdx * dxtoinf. - Consistent tolerance at both boundaries: We treat two lengths as equal when they differ by at most
tol = 1e-9 * max(d, r1 + r2), a small fraction of the overall configuration size. If we put1e-9 * (r1 + r2)^2on squared values instead, then near internal tangency (d ≈ |r1 - r2|) with nearly equal radii (r1 = 1.0,r2 = 1.0001), the algebraic identityd^2 - (r1 - r2)^2 = (d - |r1 - r2|) * (d + |r1 - r2|)shrinks the squared gap byd + |r1 - r2| ≈ 10^-4, making a squared tolerance accept length errors10,000times too large!
- No overflow on large floats:
Write the single-pair classifier
Both the exact-integer branch and the float branch produce four numbers in the same order:
center_gap,outer_limit,inner_limit, andtol(0for exact integers). That lets a single top-down chain ofifchecks test each boundary from largestddown to0:from typing import Sequence import math SEPARATE = "separate" TOUCH = "touch" INTERSECT = "intersect" REL_TOL = 1e-9 def _all_exact_ints(values: Sequence[float]) -> bool: """Return True when every value is a plain Python int (excluding bool).""" for value in values: # In Python, bool is a subclass of int, so exclude booleans explicitly. if not isinstance(value, int) or isinstance(value, bool): return False return True def classify_pair(x1: float, y1: float, r1: float, x2: float, y2: float, r2: float) -> str: """Return "intersect", "touch" or "separate" for the two circles' outlines.""" # Phase 1: Validate that all inputs are finite numbers and radii are non-negative. for value in (x1, y1, r1, x2, y2, r2): if isinstance(value, float) and not math.isfinite(value): raise ValueError("coordinates and radii must be finite numbers") if r1 < 0 or r2 < 0: raise ValueError("a radius must not be negative") dx = x2 - x1 dy = y2 - y1 # Phase 2: Compute (center_gap, outer_limit, inner_limit, tol) in exact squared # units for integers, or plain length units with relative tolerance for floats. if _all_exact_ints((x1, y1, r1, x2, y2, r2)): # Squaring avoids math.sqrt so integer comparisons stay 100% exact. center_gap = dx * dx + dy * dy outer_limit = (r1 + r2) * (r1 + r2) inner_limit = (r1 - r2) * (r1 - r2) tol = 0 else: # math.hypot avoids dx*dx overflow on huge floats like 1e200, and keeping # plain lengths makes tol represent the same physical gap at both boundaries. center_gap = math.hypot(dx, dy) outer_limit = r1 + r2 inner_limit = abs(r1 - r2) tol = REL_TOL * max(center_gap, outer_limit) # Phase 3: Sweep from farthest apart down to concentric circles. if center_gap > outer_limit + tol: # d > r1 + r2: circles lie completely outside each other. return SEPARATE if center_gap >= outer_limit - tol: # d == r1 + r2 (within tol): outlines kiss at one external point. # Two identical r = 0 points also land here (center_gap == outer_limit == 0). return TOUCH if center_gap > inner_limit + tol: # |r1 - r2| < d < r1 + r2: outlines cross at two distinct points. return INTERSECT if center_gap >= inner_limit - tol: # d == |r1 - r2| (within tol): either identical circles or internal tangency. # Since r1 = r2 = 0 already returned TOUCH above, inner_limit <= tol here # means two positive-radius circles share the same center and radius. if inner_limit <= tol: return INTERSECT return TOUCH # d < |r1 - r2|: smaller circle sits strictly inside the larger one without touching. return SEPARATENotice how cleanly the two zero-distance edge cases separate: - Two identical points (
r1 = 0,r2 = 0,d = 0) havecenter_gap == outer_limit == 0, so the secondifimmediately returns"touch". - Two identical positive-radius circles (r1 = r2 = 2,d = 0) skipouter_limit(0 < 16) and reachcenter_gap >= inner_limit - tolwithinner_limit == 0 <= tol, returning"intersect".Trace a batch of four circle pairs
classify_pairssimply iterates through the input sequence in order and collects each pair's label:from typing import List, Sequence def classify_pairs(pairs: List[Sequence[float]]) -> List[str]: """Classify every (x1, y1, r1, x2, y2, r2) entry, keeping the input order.""" # labels: list of status strings ("separate" | "touch" | "intersect"), one per input tuple. labels: List[str] = [] for x1, y1, r1, x2, y2, r2 in pairs: labels.append(classify_pair(x1, y1, r1, x2, y2, r2)) return labelsLet's trace
classify_pairson the four integer tuples from Example 1:Input pair center_gap (d^2) outer ((r1+r2)^2) inner ((r1-r2)^2) Matched branch & result ---------------------- ---------------- ----------------- ----------------- -------------------------------- (1, 2, 3, 5, 5, 2) 25 25 1 center_gap >= outer -> "touch" (0, 0, 4, 5, 0, 3) 25 49 1 25 > inner (1) -> "intersect" (2, -1, 6, 3, -1, 2) 1 64 16 1 < inner (16) -> "separate" (-3, 0, 2, 4, 0, 3) 49 25 1 49 > outer (25) -> "separate"The returned list is
["touch", "intersect", "separate", "separate"].Complete solution
from typing import List, Sequence import math SEPARATE = "separate" TOUCH = "touch" INTERSECT = "intersect" REL_TOL = 1e-9 def _all_exact_ints(values: Sequence[float]) -> bool: """Return True when every value is a plain Python int (excluding bool).""" for value in values: # In Python, bool is a subclass of int, so exclude booleans explicitly. if not isinstance(value, int) or isinstance(value, bool): return False return True def classify_pair(x1: float, y1: float, r1: float, x2: float, y2: float, r2: float) -> str: """Return "intersect", "touch" or "separate" for the two circles' outlines.""" # Phase 1: Validate that all inputs are finite numbers and radii are non-negative. for value in (x1, y1, r1, x2, y2, r2): if isinstance(value, float) and not math.isfinite(value): raise ValueError("coordinates and radii must be finite numbers") if r1 < 0 or r2 < 0: raise ValueError("a radius must not be negative") dx = x2 - x1 dy = y2 - y1 # Phase 2: Compute (center_gap, outer_limit, inner_limit, tol) in exact squared # units for integers, or plain length units with relative tolerance for floats. if _all_exact_ints((x1, y1, r1, x2, y2, r2)): # Squaring avoids math.sqrt so integer comparisons stay 100% exact. center_gap = dx * dx + dy * dy outer_limit = (r1 + r2) * (r1 + r2) inner_limit = (r1 - r2) * (r1 - r2) tol = 0 else: # math.hypot avoids dx*dx overflow on huge floats like 1e200, and keeping # plain lengths makes tol represent the same physical gap at both boundaries. center_gap = math.hypot(dx, dy) outer_limit = r1 + r2 inner_limit = abs(r1 - r2) tol = REL_TOL * max(center_gap, outer_limit) # Phase 3: Sweep from farthest apart down to concentric circles. if center_gap > outer_limit + tol: # d > r1 + r2: circles lie completely outside each other. return SEPARATE if center_gap >= outer_limit - tol: # d == r1 + r2 (within tol): outlines kiss at one external point. # Two identical r = 0 points also land here (center_gap == outer_limit == 0). return TOUCH if center_gap > inner_limit + tol: # |r1 - r2| < d < r1 + r2: outlines cross at two distinct points. return INTERSECT if center_gap >= inner_limit - tol: # d == |r1 - r2| (within tol): either identical circles or internal tangency. # Since r1 = r2 = 0 already returned TOUCH above, inner_limit <= tol here # means two positive-radius circles share the same center and radius. if inner_limit <= tol: return INTERSECT return TOUCH # d < |r1 - r2|: smaller circle sits strictly inside the larger one without touching. return SEPARATE def classify_pairs(pairs: List[Sequence[float]]) -> List[str]: """Classify every (x1, y1, r1, x2, y2, r2) entry, keeping the input order.""" # labels: list of status strings ("separate" | "touch" | "intersect"), one per input tuple. labels: List[str] = [] for x1, y1, r1, x2, y2, r2 in pairs: labels.append(classify_pair(x1, y1, r1, x2, y2, r2)) return labels✅ Submit now — all tests should pass.
Intuition & how it works
Picture sliding a small hula hoop across the floor toward a larger hula hoop lying flat on the ground, and counting how many points their plastic rims share. When the hoops are far apart, their rims share zero points ("separate"). As they slide closer, the outer edges kiss at one point ("touch"), then cross at two points ("intersect"), then kiss at one point on the inside of the larger hoop ("touch"), and finally sit one inside the other with open space all around ("separate"). Everything depends on comparing d — the Euclidean distance (straight-line distance) between the two centers — against two landmarks: the sum of radii r1 + r2 and the absolute difference of radii |r1 - r2|.
A naive implementation computes d = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) and tests d < r1 + r2 or d == r1 + r2. That approach breaks in two ways: first, checking only r1 + r2 forgets that a tiny hoop strictly inside a giant hoop (d < |r1 - r2|) never touches the giant hoop's rim; second, floating-point rounding corrupts exact tangency (meeting at a single point without crossing). On integers near 10^9, math.sqrt loses precision and turns d^2 = 10^18 + 1 into 10^18, while on floats, 0.15 + 0.30 becomes 0.44999999999999996 and misses a real tangency at d = 0.45. We avoid both traps by comparing exact squared integers (dx^2 + dy^2 against (r1 + r2)^2 and (r1 - r2)^2) when all inputs are integers, and comparing plain lengths (math.hypot(dx, dy)) with a relative tolerance (a small allowed error margin scaled to the size of the numbers being compared, 1e-9 * max(d, r1 + r2)) when any input is a float.
Walk through four quick examples from the sample cases to see how the boundaries work:
- (1, 2, 3) and (5, 5, 2) (integers): d^2 = 4^2 + 3^2 = 25, (r1 + r2)^2 = 25, (r1 - r2)^2 = 1 -> d^2 == (r1 + r2)^2, so "touch".
- (0, 0, 4) and (5, 0, 3) (integers): d^2 = 25 sits strictly between 1 and 49 -> "intersect".
- (2, -1, 6) and (3, -1, 2) (integers): d^2 = 1 < (6 - 2)^2 = 16 -> the small circle is strictly inside the big one, so "separate".
- (0.0, 0.0, 0.15) and (0.45, 0.0, 0.30) (floats): d = 0.45, r1 + r2 = 0.44999999999999996, and their gap 5.55e-17 is well inside tol = 4.5e-10 -> "touch".
Complexity
- Time: O(n) for
ncircle pairs, because we loop through theninput tuples once and perform a constant number of arithmetic operations, comparisons, and at most onemath.hypotcall per pair. - Space: O(n) to store the output list of
nclassification strings, using O(1) extra working memory per pair becauseclassify_paironly keeps a handful of scalar variables.
Edge cases
- External and internal tangency (
d == r1 + r2andd == |r1 - r2| > 0): Both are single-point contacts that require exact integer squares (for integers) or relative length tolerance (for floats) so rounding does not flip"touch"into"intersect"or"separate". - Nested and concentric circles (
d < |r1 - r2|): Concentric circles (circles that share the exact same center,d = 0) with different radii never meet along their outlines, so they return"separate". - Identical circles vs identical points: Two circles with the same center and the same positive radius (
d = 0,r1 = r2 > 0) share infinitely many outline points and return"intersect", whereas two identical zero-radius points (d = 0,r1 = r2 = 0) share a single point and return"touch". - Large integer and huge float coordinates: Python integers never overflow (
d^2 = 10^18 + 1stays distinct from10^18; in 64-bit integer languages, coordinates and radii up to10^9keepd^2 <= 8 * 10^18 < 2^63 - 1), andmath.hypothandles float coordinates like1e200without overflowingdx * dxto infinity. - Invalid inputs and empty batches: Negative radii or non-finite floats (
NaN,inf,-inf) raiseValueError, booleans are not treated as integers, and an empty input list[]returns[].
Common mistakes
- Taking
math.sqrton integer inputs and testingd == r1 + r2: Floating-point rounding loses the low bits of large squared distances and misclassifies near-tangent integer circles. - Forgetting the inner boundary
|r1 - r2|: Checking onlyd < r1 + r2labels a small circle nested inside a large circle as"intersect", which is right for filled disks but wrong for circle outlines. - Misclassifying identical circles (
d = 0,r1 = r2 > 0) as"touch": Identical circles land ond == |r1 - r2| == 0, so you must explicitly check whether|r1 - r2| == 0(within tolerance) before returning"touch". - Applying relative tolerance to squared floats: Because
d^2 - (r1 - r2)^2 = (d - |r1 - r2|) * (d + |r1 - r2|), a tolerance of1e-9 * (r1 + r2)^2becomes thousands of times too loose whenr1andr2are nearly equal anddis tiny, falsely merging distinct crossing or concentric circles.
Follow-up questions
- How would you find all overlapping pairs among n standalone circles in better than O(n^2) expected time? Wrap each circle in an axis-aligned bounding box (the tightest rectangle
[x - r, x + r] × [y - r, y + r]enclosing the circle) and insert those boxes into a uniform spatial grid (a checkerboard of square cells sized to the typical circle diameter) or a sweep-line algorithm (sorting left and right box edges alongxwhile tracking activeyintervals). You then runclassify_paironly on pairs whose bounding boxes share a grid cell or overlap in both axes. When circles are reasonably spread out withktrue overlaps, expected runtime drops fromO(n^2)to roughlyO(n + k), while the worst case where every circle overlaps every other remainsO(n^2)just to list the output. - How does a 2D renderer convert pairwise circle overlap information into a valid back-to-front draw order? First confirm whether the renderer draws hollow outlines (where only
"touch"and"intersect"pairs can occlude each other) or filled disks (where overlap isd < r1 + r2, because an interior circle also covers pixels of the outer disk). Build a directed graph where an edgeA -> Bmeans circleAmust be drawn before circleBsoBpaints on top — known as the painter's algorithm (drawing back-to-front so nearer objects overwrite farther ones) — and run a topological sort (an ordering of nodes where every directed edge points forward). If three circles overlap in a cycle (AoverB,BoverC,CoverA), no whole-circle drawing order exists and the renderer must break the cycle with per-pixel depth values (a z-buffer) or split one circle into arcs. - When two circles return "intersect" with centers at distinct positions, how do you calculate the exact (x, y) coordinates of both crossing points? Let
u = ((x2 - x1) / d, (y2 - y1) / d)be the unit vector (a direction arrow of length1) pointing from Center 1 to Center 2, and letv = (-u_y, u_x)beurotated 90 degrees counterclockwise. By the law of cosines on the triangle formed by the two centers and a crossing point, the distance alongufrom Center 1 to the midpoint between the two crossings isa = (d^2 + r1^2 - r2^2) / (2 * d), and the perpendicular half-chord length ish = sqrt(max(0.0, r1^2 - a^2)). The two crossing points areC1 + a * u + h * vandC1 + a * u - h * v; for example,(0, 0, 5)and(6, 0, 5)gived = 6,a = 3,h = 4, yielding(3, 4)and(3, -4).
Follow-up questions
- How would you find all overlapping pairs among n standalone circles in better than O(n^2) expected time?
- How does a 2D renderer convert pairwise circle overlap information into a valid back-to-front draw order?
- When two circles return "intersect" with centers at distinct positions, how do you calculate the exact (x, y) coordinates of both crossing points?
Similar questions
- Classify Pairwise Circle Geometry
- K-th Absent Positive and Windowed Repeat Count
- Smallest Element in a Cyclically Shifted Array
- Minimal String After One Alphabetical Left-Shift
- Function Pipeline Composer and JSON Serialization Mixin
- State Vote Podium Query and Transfer Analytics
More Point72 interview questions
- Format Numeric Dates as Quarter Labels Medium
- Presenting and Defending a Quantitative Alpha Signal Study Medium
- Optimal Bidding in Two-Bidder Second- and First-Price Auctions Hard Pro
- Principles and Core Families of Ensemble Models Medium Pro
- CART Mechanics, Pruning, and Scalable Tree Tuning Hard Pro
- K-th Absent Positive and Windowed Repeat Count Easy Pro
- Smallest Element in a Cyclically Shifted Array Medium Pro
- Minimal String After One Alphabetical Left-Shift Medium Pro
- Optimal Pairwise Weighings for Top Two Items Hard Pro
- Optimal Non-Overlapping Stock Trades Hard Pro