Most Stones Removed with Same Row or Column - Problem

On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone.

A stone can be removed if it shares either the same row or the same column as another stone that has not been removed.

Given an array stones of length n where stones[i] = [x_i, y_i] represents the location of the i-th stone, return the largest possible number of stones that can be removed.

Input & Output

Example 1 — Connected Stones
$ Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
Output: 5
💡 Note: We can remove stones at [0,1], [1,0], [1,2], [2,1], [2,2] because they each share a row or column with at least one other stone. The stone at [0,0] would be the last one remaining.
Example 2 — Two Groups
$ Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
Output: 3
💡 Note: Stones form two connected components: {[0,0],[2,0]} share column 0, and {[0,2],[2,2]} share column 2, while [1,1] is isolated. We can remove 3 stones total.
Example 3 — Single Stone
$ Input: stones = [[0,0]]
Output: 0
💡 Note: Cannot remove the only stone since it doesn't share a row or column with any other stone.

Constraints

  • 1 ≤ stones.length ≤ 1000
  • 0 ≤ xi, yi ≤ 104
  • No two stones are at the same coordinate point

Visualization

Tap to expand
Most Stones Removed: Row/Column ConnectionsStep 1: Input Grid(0,0)(0,1)(1,0)(2,1)4 stones on gridStep 2: Find ConnectionsGreen: connected groupPurple: isolatedSame row/column = connectedStep 3: Calculate ResultTotal stones: 4Components: 2(3 connected + 1 isolated)Removable: 4 - 2 = 2Keep 1 from each component🎯 Key Insight: Answer = Total Stones - Number of Connected Components
Understanding the Visualization
1
Input Grid
Stones placed at coordinate points
2
Find Connections
Identify stones sharing rows/columns
3
Count Removable
Total stones minus connected components
Key Takeaway
🎯 Key Insight: Stones sharing rows or columns form connected components - keep one stone per component, remove the rest
Asked in
Google 45 Facebook 32 Amazon 28 Microsoft 22
89.6K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen