Most Stones Removed with Same Row or Column solution explained
Most Stones Removed with Same Row or Column places stones on grid points and lets you remove a stone whenever another remaining stone shares its row or column; the task is to remove as many as possible. Stones linked through shared rows and columns form groups, and every group can be cleared down to exactly one stone, so the answer is the number of stones minus the number of groups. Union-find over rows and columns finds the groups in close to O(n) time.
By Evin JohnPublished 8 min read
The problem in plain words
Each stone sits on a different point [row, col] of an integer grid. You may take a stone away if at least one other stone still on the board has the same row or the same column. You can do this as many times as you like, choosing the order. Return the largest number of stones you can take away.
| Stones | Most removed | Why |
|---|---|---|
| [0,0], [0,3], [2,3], [5,5] | 2 | The first three are linked through row 0 and column 3, so two of them can go. [5,5] is alone |
| [1,1], [2,2], [3,3] | 0 | No two stones share a row or a column |
| [0,0], [0,1], [1,0], [1,1] | 3 | All four are one group, and only one stone has to stay |
| [0,0], [4,0], [4,9], [8,9], [8,1] | 4 | A zigzag: each stone shares a row or column with the next, so the whole chain is one group |
| [7,2] | 0 | A single stone can never be removed |
What the interviewer is checking
The removal game looks like it needs search or a clever greedy order. The interviewer wants to see you step back and spot the invariant: within a connected group, order can always be chosen to leave just one stone, and no order can do better. After that, the problem is plain component counting. The second thing they watch is how you build the graph. Comparing every pair of stones is O(n²); treating rows and columns as nodes gets it near linear.
Why n minus the number of groups
Take one group and pick any stone in it as the keeper. Build a spanning tree of the group, for example with a breadth-first search from the keeper, where each tree edge joins two stones that share a row or column. Remove stones from the leaves inward: a leaf always has its tree parent still on the board, sharing a row or column, so the removal is allowed. Eventually only the keeper remains. And the last stone of a group can never be removed, because every stone that ever shared its row or column was in the same group and is already gone. Removing stones never joins two groups, so the groups are independent.
Brute force: search every removal order
For a handful of stones, search the game directly. Describe the stones still on the board as a bitmask. From each state, try removing every stone that currently shares a row or column with another remaining stone, and take the best result. Memoizing on the mask keeps it to 2ⁿ states, each with O(n²) work. This proves nothing for large n but makes an honest checker for the formula.
from functools import lru_cache
def most_removed_slow(stones):
n = len(stones)
@lru_cache(maxsize=None)
def best(mask): # mask = stones still on the board
result = 0
for i in range(n):
if not mask >> i & 1:
continue
r, c = stones[i]
has_partner = any(j != i and mask >> j & 1 and
(stones[j][0] == r or stones[j][1] == c)
for j in range(n))
if has_partner:
result = max(result, 1 + best(mask & ~(1 << i)))
return result
return best((1 << n) - 1)Optimal: union-find over rows and columns
Instead of linking stones to stones, link each stone's row to its column. A stone at [r, c] says "row r and column c are in the same group". Two stones in one row then share the row node, and two stones in one column share the column node, so the stone groups match the row-and-column groups exactly. Count the groups that contain at least one row or column used by a stone, and subtract from n. Each stone is one union, so this is about O(n).
def most_removed(stones):
parent = {}
def find(key):
parent.setdefault(key, key)
root = key
while parent[root] != root:
root = parent[root]
while parent[key] != root: # compress the path just walked
parent[key], key = root, parent[key]
return root
for r, c in stones:
a, b = find(("row", r)), find(("col", c))
if a != b:
parent[a] = b
groups = sum(1 for key in parent if find(key) == key)
return len(stones) - groupsThe tags ("row", r) and ("col", c) keep row 3 and column 3 as different nodes. A common shortcut adds a fixed offset to column numbers, which works only while every row number stays below that offset. Tags remove that worry whatever the coordinates are. Every key in the dictionary belongs to some stone, so counting roots counts exactly the stone groups.
function mostRemoved(stones) {
const n = stones.length;
const parent = Array.from({ length: n }, (_, i) => i);
const find = (x) => {
while (parent[x] !== x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
};
let groups = n;
const union = (a, b) => {
const ra = find(a), rb = find(b);
if (ra !== rb) { parent[ra] = rb; groups--; }
};
const firstInRow = new Map();
const firstInCol = new Map();
stones.forEach(([r, c], i) => {
if (firstInRow.has(r)) union(i, firstInRow.get(r)); else firstInRow.set(r, i);
if (firstInCol.has(c)) union(i, firstInCol.get(c)); else firstInCol.set(c, i);
});
return n - groups;
}This version keeps stones as the nodes but avoids comparing every pair: each stone is joined only to the first stone met in its row and the first in its column. Two separate maps keep rows and columns apart, so there is no collision problem here either. Both approaches do O(n) unions.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Memoized search over removal orders | O(2ⁿ × n²) | O(2ⁿ) |
| Compare every pair, then count components | O(n²) | O(n) |
| Union-find over row and column keys | O(n α(n)) | O(n) |
| Union-find over stones with first-in-row and first-in-column maps | O(n α(n)) | O(n) |
Edge cases
- A single stone: nothing can be removed.
- All stones in one row: one group, so n - 1.
- No shared rows or columns: n groups, so 0.
- Large coordinates, or a row number that equals a column number: tagged keys or separate maps keep them apart.
- Stones that connect only through a long zigzag: union-find still joins them in one pass.
Common mistakes
- Trying a greedy removal order, such as removing the stone with the most neighbours first, which is hard to prove and easy to get wrong.
- Returning the number of groups instead of n minus the number of groups.
- Mixing row and column numbers in one key space, so row 2 and column 2 merge by accident.
- Using a column offset that is smaller than the largest coordinate.
- Counting roots over every possible row and column instead of only those that appear in some stone.
Follow-up questions
- Output a valid removal order. Run BFS from one stone in each group and remove stones in reverse BFS order, so each one still has its parent on the board.
- Stones are added and removed live, and you report the answer each time. Additions are easy with union-find. Deletions are hard, because union-find cannot split groups; mention offline techniques or rebuilding.
- A stone can also be removed if it shares a diagonal. Add diagonal keys (r - c and r + c) as extra node types and union them too.
How to explain it out loud
Fictional example
- Candidate
- If two stones share a row or column, I'll call them linked. Linked chains make groups.
- Candidate
- In a group I can always remove everything but one stone, by removing leaves of a spanning tree first. The last one can never go, since nothing else shares its row or column.
- Interviewer
- So what's the answer?
- Candidate
- Number of stones minus number of groups. To find groups fast, I union each stone's row with its column, using tagged keys so row 3 and column 3 stay different.
- Candidate
- That's one union per stone, so nearly linear.
Related problems
Number of Operations to Make Network Connected is another case where the answer falls out of a component count. Satisfiability of Equality Equations uses union-find on a fixed key space of letters. Regions Cut by Slashes shows another trick of choosing what the union-find nodes stand for.
Practicing it with Natively
This problem rewards the moment you stop simulating and say "it's just groups", so rehearse that reasoning aloud. On a Mac or Windows PC, Natively can read a stone layout from a screenshot, suggest the row-and-column union-find with tagged keys, and transcribe your mock explanation so you can check that you gave the spanning-tree argument. The page on how AI helps in coding interviews has more on that kind of practice.
Questions people ask
How do you solve Most Stones Removed with Same Row or Column?
Treat stones that share a row or column as linked and count the connected groups. Every group can be reduced to one stone, so the answer is the number of stones minus the number of groups.
Why can each group be reduced to exactly one stone?
Remove stones from the leaves of a spanning tree inward, so each removed stone still has its tree parent sharing a row or column. The last stone has no partner left, so it stays.
What is the time complexity?
O(n α(n)) with union-find over row and column keys, and O(n) space.
Why tag row and column keys?
Row 3 and column 3 are different nodes. Using raw numbers or a too-small column offset can merge them by accident.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
