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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code