Most Stones Removed with Same Row or Column

medium

On a 2D plane, stones[i] = [r, c] places a stone at row r, column c. A stone can be removed if it shares its row or column with another stone still on the plane. Return the maximum number of stones you can remove.

Hints

Stones sharing a row or column are connected, and this relation is transitive.
From a component of k stones you can remove k-1, leaving one.
So the answer is (number of stones) - (number of connected components).

Common doubts

As long as a component has more than one stone, some stone shares a line with another and can be removed; peel until one remains.
Mapping each row and column to its first stone lets you union new stones with existing ones directly, no explicit edges.
You union stones that share a row OR a column, so you key by row and by column separately.

Interview follow-ups

Yes — treat 'row r' and 'col c' as nodes and union them per stone; components of the stones follow.
Add a diagonal key; the component structure changes accordingly.

Fun facts

  • LeetCode 947 — a components problem where the answer is n minus the component count.
  • The row/column first-owner trick is a compact way to union by a shared attribute.

Asked at

AmazonGoogleFacebook
Frequently Sometimes Occasionally
Example 1
Input: stones = [[0,0],[0,1],[1,0],[1,1]]
Output: 3
All four are connected via shared rows/columns — one component, so remove 3.
Example 2
Input: stones = [[0,0],[1,1],[2,2]]
Output: 0
No two share a row or column; each is isolated.
Constraints

- 0 <= stones.length <= 1000 - 0 <= r, c <= 10^4 - no two stones at the same coordinate

Solve this problem →