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 with Same Row or Column INPUT 0 1 2 0 1 2 0 1 2 3 4 5 stones = [ [0,0],[0,1],[1,0], [1,2],[2,1],[2,2] ] n = 6 stones on 3x3 grid Index shown in circles UNION-FIND ALGORITHM 1 Initialize DSU Each stone is its own parent 2 Union by Row/Col Connect stones sharing row/col Row 0: stone 0 -- stone 2 Col 0: stone 0 -- stone 1 Col 1: stone 1 -- stone 4 Row 2: stone 4 -- stone 5 Col 2: stone 3 -- stone 5 Row 1: stone 2 -- stone 3 3 Count Components All 6 stones in 1 component 4 Calculate Result n - components = 6 - 1 = 5 Components = 1 FINAL RESULT 0 = Remaining = Removed Output: 5 stones removed OK - Verified 6 - 1 = 5 max Key Insight: Stones sharing a row or column form connected components. Using Union-Find, we group all connected stones. For each component of size k, we can remove k-1 stones (keeping one). Max removable = n - (number of components). Time: O(n * alpha(n)), Space: O(n) TutorialsPoint - Most Stones Removed with Same Row or Column | Union-Find (Disjoint Set) Approach
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