Most Stones Removed with Same Row or Column (LeetCode 947): Solution and Explanation
Stones sit at distinct integer points on a grid. You may remove a stone if another remaining stone shares its row or column. Return the maximum number of stones you can remove.
Watch it run step by step
Try your own input and write the code →Intuition
It looks like a search over removal orders, which would be hopeless. The breakthrough is to look at connected groups. Say two stones are linked if they share a row or column, and take the connected components of that relation. Within one component you can always remove all but one stone: pick any spanning tree and remove stones from the leaves inward, so each removed stone still has a linked neighbor left. And you can never empty a component completely, because its last stone has no partner. So the answer is the number of stones minus the number of components.
Now you only need to count components. Linking every pair of stones would be O(n²). Instead, notice that a row or a column acts like a hub: every stone in row 3 is connected to every other one. So treat each row and each column as a node and union the stone's row with its column. Two stones end up in the same set exactly when they are connected through shared rows and columns.
Rows and columns live in the same union-find, so they need distinct keys. The code uses x for a row and ~y (which equals -y - 1) for a column, so even when a row number equals a column number they never collide, since columns map to negative keys. The dictionary-based union-find creates nodes lazily, so coordinates up to 10,000 need no preallocated arrays.
Approach: Union-find on row and column keys
- Use a dictionary
parentso union-find nodes are created on first use. find(x)adds unseen keys as their own root, then follows and compresses the path to the root.union(x, y)links the roots ofxandywhen they differ.- For every stone
(x, y), callunion(x, ~y)to join its row and its column. - Collect
find(x)for each stone's row into a set; each distinct root is one component. - Return
len(stones) - len(roots).
Step-by-step example
stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
- Columns map to
~0 = -1,~1 = -2and~2 = -3. Stone (0,0) unions row 0 with -1, soparent[0] = -1. - Stone (0,1) unions row 0 with -2. The root of 0 is -1, so
parent[-1] = -2. Stone (1,0) joins row 1 to that set, soparent[1] = -2. - Stone (1,2) unions row 1 with -3, so
parent[-2] = -3. Stones (2,1) and (2,2) attach row 2 to the same root. - Every stone's row now finds root -3, so there is one component.
- The answer is 6 - 1 = 5: every stone except one can be removed.
Code: Python, Java, C++
1class Solution:
2 def removeStones(self, stones: List[List[int]]) -> int:
3 parent = {}
4
5 def find(x):
6 if x not in parent:
7 parent[x] = x
8 if parent[x] != x:
9 parent[x] = find(parent[x])
10 return parent[x]
11
12 def union(x, y):
13 px, py = find(x), find(y)
14 if px != py:
15 parent[px] = py
16
17 for x, y in stones:
18 union(x, ~y) # Use ~y to differentiate row and col
19
20 roots = set()
21 for x, y in stones:
22 roots.add(find(x))
23
24 return len(stones) - len(roots)1class Solution {
2 Map<Integer, Integer> parent = new HashMap<>();
3
4 public int removeStones(int[][] stones) {
5 for (int[] stone : stones) {
6 union(stone[0], ~stone[1]);
7 }
8
9 Set<Integer> roots = new HashSet<>();
10 for (int[] stone : stones) {
11 roots.add(find(stone[0]));
12 }
13
14 return stones.length - roots.size();
15 }
16
17 private int find(int x) {
18 if (!parent.containsKey(x)) parent.put(x, x);
19 if (parent.get(x) != x) {
20 parent.put(x, find(parent.get(x)));
21 }
22 return parent.get(x);
23 }
24
25 private void union(int x, int y) {
26 int px = find(x), py = find(y);
27 if (px != py) parent.put(px, py);
28 }
29}1class Solution {
2public:
3 unordered_map<int, int> parent;
4
5 int removeStones(vector<vector<int>>& stones) {
6 for (auto& stone : stones) {
7 unionNodes(stone[0], ~stone[1]);
8 }
9
10 unordered_set<int> roots;
11 for (auto& stone : stones) {
12 roots.insert(find(stone[0]));
13 }
14
15 return stones.size() - roots.size();
16 }
17
18 int find(int x) {
19 if (parent.find(x) == parent.end()) parent[x] = x;
20 if (parent[x] != x) {
21 parent[x] = find(parent[x]);
22 }
23 return parent[x];
24 }
25
26 void unionNodes(int x, int y) {
27 int px = find(x), py = find(y);
28 if (px != py) parent[px] = py;
29 }
30};Time and space complexity
O(n log n)
Each of the n stones performs a constant number of finds. With path compression alone (no union by rank), the amortized cost per find is O(log n), and in practice it is nearly constant.
O(n)
The dictionary holds at most one entry per distinct row and column, which is at most 2n keys.
Other approaches
DFS over stones (time O(n²), space O(n²))
Build a graph connecting stones that share a row or column, then count components with DFS. Comparing all pairs makes building the graph quadratic.
DFS with row and column buckets (time O(n), space O(n))
Group stones by row and by column in hash maps, then DFS from each unvisited stone through its row and column buckets, clearing each bucket after use. Linear and avoids union-find.
Common mistakes
- Using
ydirectly as the column key. Row 3 and column 3 would then merge, connecting stones that share nothing. - Unioning stones pairwise instead of rows and columns, which is O(n²) and unnecessary.
- Using
-yinstead of~yfor columns. Negating zero leaves it unchanged, so column 0 would collide with row 0 and merge unrelated stones. - Returning the number of components instead of
len(stones) - components. The question asks for removed stones, not survivors.
Frequently asked questions
Why is the answer stones minus components?
Inside a connected group you can always remove stones in an order that leaves exactly one, but the last stone has no partner and cannot go. Every component therefore keeps one stone.
Why use ~y for columns?
Row and column numbers share the same range, so they need different keys. ~y equals -y - 1, which is always negative for valid columns and cannot clash with any row.
What is the time complexity of Most Stones Removed?
With union-find over rows and columns it is near-linear, O(n log n) in the worst case with path compression only, and effectively O(n).
Can this be solved with DFS?
Yes. Build connections through row and column buckets, then count components with DFS; the answer is again the number of stones minus the number of components.