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.
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.
Input: stones = [[0,0],[1,1],[2,2]] Output: 0 No two share a row or column; each is isolated.
- 0 <= stones.length <= 1000 - 0 <= r, c <= 10^4 - no two stones at the same coordinate
Two stones in the same row or column are connected, and connectivity is transitive — so the stones split into connected components. Within a component of k stones, you can always remove k-1 of them (remove them in an order that keeps a shared partner until the end, leaving exactly one). So the answer is simply:
max removed = (total stones) - (number of connected components).
Build the components by connecting stones that share a row or column. Union-Find does it slickly: keep a row → first stone and column → first stone map, and union each new stone with the first stone that already occupies its row and its column. Then the answer is n - #roots. O(n·α).
“What makes a stone removable?”
Sharing a row or column with another remaining stone.
“How many remain?”
One per connected component.
Stones sharing a row or column form components; I can remove all but one from each.
So the answer is total stones minus the number of components — I count those with union-find.
Worked example — stones = [[0,0],[0,1],[1,0],[1,1]]
all four share rows/columns -> one component of 4 removable = 4 - 1 = 3
Components form under this relation.
Remove size - 1 from each.
Sum of (size - 1) over components.
| DFS on stone graph | Union-Find | |
|---|---|---|
| Connect via | group by row/col, build edges | row/col first-owner maps |
| Time | O(n + edges) | O(n·α) |
| Answer | n - components | n - roots |
Both count the same components. Full code is in the Approaches selector below.
Key takeaway
Stones sharing a row or column form components; you can remove all but one from each, so the answer is n minus the number of components. Union-find via row/column first-owner maps computes it in O(n·α).
union each stone with the first stone in its row and its column answer = n - number of distinct roots