KatInterview

Maximum Pebble Removals on a Coordinate Board

Trees & GraphsAuto-graded · 15 test cases
MediumAuto-gradedTrees & Graphsunion-findconnected-componentsgraph-modeling

Last updated

Compute how many pebbles can be taken off a board when each removal needs another remaining pebble in the same row or column, using connected components.

Pebble Removal Game

A board contains n pebbles, each on its own cell. The i-th pebble sits at the integer coordinate pebbles[i] = [row, col], and no two pebbles occupy the same cell.

You may repeatedly take a pebble off the board, but only under this rule: at the moment of removal, at least one other pebble still on the board must lie in the same row or in the same column as the pebble being removed.

Return the largest possible number of pebbles that can be removed by a sequence of legal moves.

Input

  • pebbles: a list of n pairs [row, col] of non-negative integers (0-indexed coordinates).

Output

  • A single integer: the maximum number of pebbles that can be removed.

Notes

  • A pebble alone in both its row and its column (with respect to the pebbles currently on the board) cannot be removed.
  • If there is only one pebble, the answer is 0.

Constraints

  • 1 <= len(pebbles) <= 1000
  • 0 <= row, col <= 10000
  • All coordinates in pebbles are distinct.

Examples

Example 1

Input: max_pebble_removals([[0, 0], [0, 1], [1, 0], [1, 2], [2, 1], [2, 2]])

Output: 5

Example 2

Input: max_pebble_removals([[0, 0], [0, 2], [1, 1], [2, 0], [2, 2]])

Output: 3

Example 3

Input: max_pebble_removals([[0, 0]])

Output: 0

Hints

Hint 1

Think of each pebble as a node, and link two pebbles whenever they share a row or a column. What does a legal removal look like in this graph?

Hint 2

A pebble that is the last one left in its group of linked pebbles can never be removed. Conversely, show that a group of size k can always be reduced to a single pebble.

Hint 3

The answer is n minus the number of connected groups. To count groups in linear time, union each pebble with the first pebble seen in its row and the first seen in its column (or union row-nodes with column-nodes).