KatInterview

Circle Pair Relationship Labeler

Math & Bit ManipulationAuto-graded · 17 test cases
EasyAuto-gradedMath & Bit Manipulationgeometryinteger-arithmeticcase-analysis

Last updated

Label each pair of circles by their geometric relationship using exact integer squared-distance comparisons and a strict rule order, including degenerate radius-zero cases.

You are given a list of N circle pairs. Each circle is described by three integers [x, y, r]: the center (x, y) and the radius r. Label how the two circles in each pair relate to each other and return the labels in input order.

Let d be the distance between the two centers, and let r1, r2 be the radii.

Labels

Apply the rules below in this exact order. The first rule that matches decides the label.

  1. IDENTICAL: the centers coincide and r1 == r2.
  2. CONCENTRIC: the centers coincide and r1 != r2.
  3. TOUCHING_EXTERNALLY: d == r1 + r2.
  4. TOUCHING_INTERNALLY: d == |r1 - r2|.
  5. INTERSECTING: |r1 - r2| < d < r1 + r2.
  6. DISJOINT: every other case. This covers circles that are fully apart (d > r1 + r2). It also covers the case where one circle lies strictly inside the other without touching it and the centers differ (0 < d < |r1 - r2|).

Notes

  • A radius of 0 is allowed and represents a single point. Because of the rule order, a point lying exactly on a circle is TOUCHING_EXTERNALLY.
  • Equal radii with different centers can never be TOUCHING_INTERNALLY, because |r1 - r2| = 0 while d > 0.
  • Coordinates may be negative. If any radius in the input is negative, raise a ValueError.
  • Avoid floating point. Compare squared quantities instead: d² against (r1 + r2)² and (r1 - r2)². All of these are non-negative, so squaring preserves the ordering.

Input / Output

  • Input: pairs, a list of N items, each of the form [[x1, y1, r1], [x2, y2, r2]].
  • Output: a list of N strings, one label per pair, in the same order.

Constraints

  • 0 <= N <= 2 * 10^5
  • |x|, |y| <= 10^9 and 0 <= r <= 10^9 for valid input
  • All values are integers
  • A negative radius must raise ValueError
  • The target is linear time in N

Examples

Example 1

Input: classify_circle_relations([[[0, 0, 2], [3, 0, 1]], [[0, 0, 1], [0, 0, 1]], [[0, 0, 3], [0, 0, 1]], [[0, 0, 2], [5, 0, 2]]])

Output: ['TOUCHING_EXTERNALLY', 'IDENTICAL', 'CONCENTRIC', 'DISJOINT']

Hints

Hint 1

Never take a square root. Compute dx*dx + dy*dy once and compare it with (r1+r2)^2 and (r1-r2)^2; both are non-negative, so the order is preserved.

Hint 2

Handle the coincident-centers case first, since it decides IDENTICAL versus CONCENTRIC before any distance comparison is meaningful.

Hint 3

Follow the stated rule order exactly: check external tangency before internal tangency, then intersecting, and let everything left over fall into DISJOINT.