Most Stones Removed with Same Row or Column - Problem

Imagine you're playing a strategic stone removal game on an infinite 2D grid! You have n stones placed at various integer coordinates, with at most one stone per position.

The Rule: You can remove a stone if and only if there's at least one other stone that shares the same row OR the same column with it.

Your Goal: Remove as many stones as possible following this rule!

Given an array stones where stones[i] = [x_i, y_i] represents the coordinates of the i-th stone, return the maximum number of stones you can remove.

Key Insight: This isn't just about counting - it's about understanding connected components! Stones that can "reach" each other through shared rows/columns form groups, and from each group, you can remove all but one stone.

Input & Output

example_1.py โ€” Basic Connected Groups
$ Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
โ€บ Output: 5
๐Ÿ’ก Note: All stones are connected through shared rows/columns forming one component. We can remove 5 stones, leaving 1.
example_2.py โ€” Multiple Components
$ Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
โ€บ Output: 3
๐Ÿ’ก Note: Two connected components: {[0,0],[2,0],[0,2],[2,2]} and {[1,1]}. Remove 3 from first group, 0 from second.
example_3.py โ€” Single Stone
$ Input: stones = [[0,0]]
โ€บ Output: 0
๐Ÿ’ก Note: Cannot remove the only stone as there's no other stone sharing its row or column.

Constraints

  • 1 โ‰ค stones.length โ‰ค 1000
  • 0 โ‰ค xi, yi โ‰ค 104
  • No two stones are at the same coordinate point
  • All coordinates are integers

Visualization

Tap to expand
Stone Removal Game StrategyComponent 1: Connected Stones(0,0)(1,0)(0,2)(3,2)row 0col 0row 2Can remove 3 out of 4Component 2: Isolated Stone(5,5)Cannot remove (isolated)Final CalculationTotal Stones: 5Components: 2Removed: 5 - 2 = 3๐Ÿ’ก Key Insight: Each connected component must keep exactly one stone
Understanding the Visualization
1
Identify Connections
Two stones are connected if they share the same row OR column
2
Find Components
Group all connected stones into separate components
3
Apply Strategy
From each component of size k, we can remove k-1 stones
4
Calculate Result
Sum up all removals: total_stones - number_of_components
Key Takeaway
๐ŸŽฏ Key Insight: Transform the problem into finding connected components. The answer is always total_stones - number_of_components, because from each component we must keep exactly one stone.
Asked in
Google 42 Facebook 28 Amazon 31 Microsoft 19
48.0K Views
Medium Frequency
~25 min Avg. Time
2.1K 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