Skip to problem
←

Most Stones Removed with Same Row or Column

Medium 0 attempts

You're given a list of stones placed on a 2D grid, each described by its [x, y] coordinates. A stone can be removed as long as some other remaining stone still shares its row or its column. Determine the largest number of stones that can be removed this way.

The other stone must still be present at the moment of removal. Sharing a row or column does not require adjacent coordinates; diagonal contact alone does not count. Return the count, not a removal order.

For [[0,0],[0,1],[1,1]], remove (0,0) first using (0,1), then remove (0,1) using (1,1). Two removals are possible, leaving one stone.

Function contract

Implement removeStones(stones). Receive distinct [row, column] coordinate pairs.

Output: Return the maximum number of removable stones. Each removal requires another currently remaining stone in the same row or column.

Example 1

Input
stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
Output
5

Example 2

Input
stones = [[0,0]]
Output
0
Constraints
  • 1 <= stones.length <= 1000
  • 0 <= xi, yi <= 10^4
  • All stone coordinates are distinct

Union-Find (Count Components)

Connect stones that share a row or column. At least one stone must remain in each connected component. Conversely, remove leaves of a spanning tree one at a time while retaining their parents; this removes every stone except one. Therefore the maximum is total stones minus the component count.

The implementation unions row IDs with column IDs instead of comparing every stone pair. Nonnegative row IDs and negative column IDs (~c = -c - 1) occupy disjoint namespaces. This prevents a row numbered 1 from being confused with column 1. Every active component contains a row, so counting row roots counts all components.

javascript
function removeStones(stones) {
  const parent = new Map(), size = new Map();
  function find(x) { if(!parent.has(x)){parent.set(x,x);size.set(x,1);}let root=x;while(parent.get(root)!==root)root=parent.get(root);while(parent.get(x)!==x){const next=parent.get(x);parent.set(x,root);x=next;}return root; }
  function union(a, b) { a=find(a);b=find(b);if(a===b)return;if(size.get(a)<size.get(b))[a,b]=[b,a];parent.set(b,a);size.set(a,size.get(a)+size.get(b)); }
  for (const [r, c] of stones) union(r, ~c);
  const roots = new Set();
  for (const [r] of stones) roots.add(find(r));
  return stones.length - roots.size;
}

Time: O(n α(n)) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript