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) -> str
  • classify_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| with r1 != r2), or two coincident zero-radius points (d == 0 and r1 == 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 == 0 and r1 == 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. (1, 2, 3) and (5, 5, 2) have center offsets dx = 4, dy = 3, giving d = 5 == 3 + 2, so their rims meet externally at one point ("touch").
  2. (0, 0, 4) and (5, 0, 3) have d = 5, which lies strictly between |4 - 3| = 1 and 4 + 3 = 7, so their rims cross twice ("intersect").
  3. (2, -1, 6) and (3, -1, 2) have d = 1 < |6 - 2| = 4, so the radius-2 circle sits strictly inside the radius-6 circle without contacting its rim ("separate").
  4. (-3, 0, 2) and (4, 0, 3) have d = 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:

  1. (0, 0, 5) and (3, 0, 2) have d = 3 == |5 - 2| > 0, so the smaller circle kisses the inner wall of the larger circle at (5, 0) ("touch").
  2. (4, -2, 3) and (4, -2, 3) have identical centers and positive radius 3, sharing infinitely many boundary points ("intersect").
  3. (-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 int or float values; bool values are not treated as exact integers.
  • When all six numbers in a pair are plain int values, comparisons must be exact without floating-point rounding loss (even for coordinates and radii up to 10^9 or larger).
  • When any input in a pair is a float, boundary equality at r1 + r2 and |r1 - r2| uses a small relative tolerance (1e-9 * max(d, r1 + r2)) and must not overflow on large finite magnitudes (such as 1e200).
  • r1 >= 0 and r2 >= 0 for valid circles (0 represents a degenerate point). Raise ValueError if r1 < 0, r2 < 0, or any coordinate or radius is non-finite (NaN, inf, -inf).

Step-by-step walkthrough

  1. 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 radius r1, and Circle 2 with center (x2, y2) and radius r2. 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 both r1 + r2 and |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 0 represents a single point ((x, y, 0)), so two identical points share 1 point ("touch"). A negative radius or non-finite float (NaN or inf) is invalid geometry and raises ValueError.
  2. Slide two circles together to see all five geometric cases

    Imagine fixing Circle 1 at (0, 0) with radius r1 = 3 and sliding Circle 2 with radius r2 = 1 from far away on the right all the way to (0, 0). Here r1 + r2 = 4 (the outer touch distance) and |r1 - r2| = 2 (the inner touch distance).

    As the center-to-center distance d shrinks from 5 down to 1, 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: when r1 == r2 > 0, |r1 - r2| is 0, so d == 0 means 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".

  3. Keep integer inputs exact by comparing squared distances

    A naive implementation computes d = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) and checks d == r1 + r2. Even when every input is an integer, math.sqrt converts 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)^2
    

    Why 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^18
    

    Because 10^18 + 1 > 10^18, the circles are strictly "separate". Yet near 10^18, consecutive 64-bit floats are 128 apart, so float(10**18 + 1) rounds straight to 1e18 and math.sqrt falsely reports "touch". Python integers have arbitrary precision, so comparing integer squares stays 100% exact at every scale.

  4. 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-point 0.15 + 0.30 evaluates to 0.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:

    1. No overflow on large floats: math.hypot(dx, dy) rescales internally before squaring, so coordinates like 1e200 will not overflow dx * dx to inf.
    2. 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 put 1e-9 * (r1 + r2)^2 on squared values instead, then near internal tangency (d ≈ |r1 - r2|) with nearly equal radii (r1 = 1.0, r2 = 1.0001), the algebraic identity d^2 - (r1 - r2)^2 = (d - |r1 - r2|) * (d + |r1 - r2|) shrinks the squared gap by d + |r1 - r2| ≈ 10^-4, making a squared tolerance accept length errors 10,000 times too large!
  5. 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, and tol (0 for exact integers). That lets a single top-down chain of if checks test each boundary from largest d down to 0:

    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 SEPARATE
    

    Notice how cleanly the two zero-distance edge cases separate: - Two identical points (r1 = 0, r2 = 0, d = 0) have center_gap == outer_limit == 0, so the second if immediately returns "touch". - Two identical positive-radius circles (r1 = r2 = 2, d = 0) skip outer_limit (0 < 16) and reach center_gap >= inner_limit - tol with inner_limit == 0 <= tol, returning "intersect".

  6. Trace a batch of four circle pairs

    classify_pairs simply 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 labels
    

    Let's trace classify_pairs on 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"].

  7. 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 n circle pairs, because we loop through the n input tuples once and perform a constant number of arithmetic operations, comparisons, and at most one math.hypot call per pair.
  • Space: O(n) to store the output list of n classification strings, using O(1) extra working memory per pair because classify_pair only keeps a handful of scalar variables.

Edge cases

  • External and internal tangency (d == r1 + r2 and d == |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 + 1 stays distinct from 10^18; in 64-bit integer languages, coordinates and radii up to 10^9 keep d^2 <= 8 * 10^18 < 2^63 - 1), and math.hypot handles float coordinates like 1e200 without overflowing dx * dx to infinity.
  • Invalid inputs and empty batches: Negative radii or non-finite floats (NaN, inf, -inf) raise ValueError, booleans are not treated as integers, and an empty input list [] returns [].

Common mistakes

  • Taking math.sqrt on integer inputs and testing d == 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 only d < r1 + r2 labels 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 on d == |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 of 1e-9 * (r1 + r2)^2 becomes thousands of times too loose when r1 and r2 are nearly equal and d is 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 along x while tracking active y intervals). You then run classify_pair only on pairs whose bounding boxes share a grid cell or overlap in both axes. When circles are reasonably spread out with k true overlaps, expected runtime drops from O(n^2) to roughly O(n + k), while the worst case where every circle overlaps every other remains O(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 is d < r1 + r2, because an interior circle also covers pixels of the outer disk). Build a directed graph where an edge A -> B means circle A must be drawn before circle B so B paints 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 (A over B, B over C, C over A), 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 length 1) pointing from Center 1 to Center 2, and let v = (-u_y, u_x) be u rotated 90 degrees counterclockwise. By the law of cosines on the triangle formed by the two centers and a crossing point, the distance along u from Center 1 to the midpoint between the two crossings is a = (d^2 + r1^2 - r2^2) / (2 * d), and the perpendicular half-chord length is h = sqrt(max(0.0, r1^2 - a^2)). The two crossing points are C1 + a * u + h * v and C1 + a * u - h * v; for example, (0, 0, 5) and (6, 0, 5) give d = 6, a = 3, h = 4, yielding (3, 4) and (3, -4).

Follow-up questions

Similar questions

More Point72 interview questions

All 41 Point72 questions →