sagelearnai

Most Stones Removed with Same Row or Column

Difficulty: Medium · Pattern: Union-Find · LeetCode #947

Stones lie on distinct points of a 2-D grid. You can remove a stone if another remaining stone shares its row or its column. Return the maximum number of stones that can be removed.

Examples

text
[[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]  →  5
[[0,0],[0,2],[1,1],[2,0],[2,2]]        →  3
[[0,0]]                                →  0

Hints

  1. Connect stones that share a row or a column. Within one connected component you can remove every stone but one (remove them leaf-first along a spanning tree).
  2. So the answer is #stones − #components.

Approach

Instead of comparing every pair of stones (O(n²)), union the row and the column: treat row r as node r and column c as node c + 10001, so the two kinds of node never collide, and union them for each stone. Each stone links its row and its column, and stones that share a row or a column end up in the same component.

Count the distinct roots among the nodes actually used, and the answer is n − components. That's O(n · α(n)).

Why can a component of k stones lose exactly k − 1? Take a spanning tree and repeatedly remove a leaf. Each leaf shares a line with its parent, which is still on the board.

Complexity

Time: O(n · α(n)). Space: O(n).

Python solution
def removeStones(stones):
    parent = {}
    def find(x):
        parent.setdefault(x, x)
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    for r, c in stones:
        ra, rb = find(r), find(c + 10001)
        if ra != rb:
            parent[ra] = rb
    roots = {find(x) for x in parent}
    return len(stones) - len(roots)
JavaScript solution
function removeStones(stones) {
  const parent = new Map();
  const find = (x) => {
    if (!parent.has(x)) parent.set(x, x);
    while (parent.get(x) !== x) { parent.set(x, parent.get(parent.get(x))); x = parent.get(x); }
    return x;
  };
  for (const [r, c] of stones) { const a = find(r), b = find(c + 10001); if (a !== b) parent.set(a, b); }
  const roots = new Set();
  for (const x of parent.keys()) roots.add(find(x));
  return stones.length - roots.size;
}