← Questions

Minimum triggers to clear linked balls on a grid

0
UberCodingLast asked Jun 2026

You are given n balls on a 2D grid. balls[i] = [x_i, y_i] is the position of ball i, and you are also given a non-negative integer d.

Two balls are linked when they lie on the same row (equal y) or the same column (equal x) and the distance between them along that line, |x_i - x_j| or |y_i - y_j|, is at most d. Balls on a diagonal are never linked directly.

When you trigger a ball, it is absorbed, and so is every ball linked to it. The effect spreads: each absorbed ball absorbs its own linked balls, and so on.

Implement:

def min_triggers(balls: list[list[int]], d: int) -> int

Return the minimum number of triggers needed to absorb every ball.

Constraints

  • 0 <= n <= 10^5
  • -10^9 <= x_i, y_i <= 10^9
  • 0 <= d <= 2 * 10^9
  • Two balls may share a position.

Example 1

balls = [[1, 1], [1, 4], [6, 4], [8, 8]], d = 5
output: 2

(1,1) and (1,4) share column 1 and are 3 apart. (1,4) and (6,4) share row 4 and are 5 apart. So one trigger clears those three balls, and (8,8) needs a second trigger.

Example 2

balls = [[0, 0], [0, 6], [0, 12], [3, 3]], d = 6
output: 2

(0,0) and (0,12) are 12 apart, but both link to (0,6), so one trigger clears all three. (3,3) shares no row or column with any other ball.

Reconstructed from the reported question; details may differ from what interviewers ask.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding