Most Stones Removed with Same Row or Column

Medium

Topics
Union FindGraphDFS

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 is still on the plane.

Given an array stones of length n where stones[i] = [x, y] represents the location of the i-th stone, return the largest possible number of stones that can be removed. On this judge the array is passed as a grid with two columns.

Example 1

0●●·1●·●2·●●012
Each dot is a stone at the given coordinate. A stone can go if another stone shares its row or column, so a whole connected group collapses to one survivor — and stones count as connected through intermediaries, not just directly. These 6 stones form 1 group, so 5 can be removed.
Input is a list of [row, col] stone coordinates, plotted here on the grid they span.
Input:  grid = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
Output: 5
Explanation: All six stones are connected, so all but one can be removed.

Example 2

0●·●1·●·2●·●012
Input:  grid = [[0,0],[0,2],[1,1],[2,0],[2,2]]
Output: 3

Example 3

0●0
Input:  grid = [[0,0]]
Output: 0
Explanation: A lone stone shares no row or column, so it cannot be removed.

Constraints

  • 1 <= stones.length <= 1000
  • 0 <= x, y <= 10^4
  • No two stones are at the same coordinate point
Editorial — intuition, approach, complexity and pitfalls

Intuition

Two stones that share a row or a column are linked, and linkage is transitive: if A links to B and B links to C, then removing stones in the right order lets you clear all of A, B, and C down to a single survivor. So group the stones into connected components. Within a component of size k you can always remove k - 1 stones - peel them off in reverse order of a spanning tree, so every stone you remove still has a neighbour present when you take it. The answer is therefore n - numberOfComponents.

The trick that makes this short is what you union. Do not union stone to stone, which needs an O(n2) scan. Union the row to the column of each stone, in one shared namespace. A stone is an edge between its row node and its column node, and two stones end up in the same component exactly when they are linked.

Approach

  1. Create a DSU over a namespace holding both rows and columns. Offset the column ids so they cannot collide with row ids - for example, use ~y or y + 10001 for column y.
  2. For each stone (x, y), call union(x, colId(y)).
  3. Count the distinct roots among only the nodes you actually touched. Untouched rows and columns are not components.
  4. Return n - distinctRoots.
class Solution:
    def removeStones(self, grid):
        parent = {}

        def find(x):
            parent.setdefault(x, x)
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x

        def union(a, b):
            ra, rb = find(a), find(b)
            if ra != rb:
                parent[rb] = ra

        for x, y in grid:
            union((0, x), (1, y))      # row node vs column node

        roots = {find(k) for k in parent}
        return len(grid) - len(roots)

Dry Run

stones [0,0] [0,1] [1,0] [1,2] [2,1] [2,2]
Two stones are connected when they share a row or a column, and this version
unions STONE INDICES pairwise -- so rows and columns never need a shared
namespace at all.
  0 [0,0] and 1 [0,1]  share row 0      merge, groups 5
  0 [0,0] and 2 [1,0]  share column 0   merge, groups 4
  1 [0,1] and 4 [2,1]  share column 1   merge, groups 3
  2 [1,0] and 3 [1,2]  share row 1      merge, groups 2
  3 [1,2] and 5 [2,2]  share column 2   merge, groups 1
  6 stones in 1 connected group
answer 6 - 1 = 5
The answer is stones minus GROUPS, not stones minus one. Each connected component
keeps exactly one survivor, which is why the second example -- [0,0] [0,2] [1,1]
[2,0] [2,2] -- answers 3 rather than 4: it has two components, and the isolated
[1,1] can never be removed at all.
Why k - 1 per component of size k is worth checking rather than assuming: build
any spanning tree of the component and remove leaves inward. Every leaf still
shares a line with its parent at the moment it goes, so the order always exists,
and the last stone standing has nothing left to share with.
The alternative formulation unions row ids with column ids directly, and there the
namespaces MUST be kept apart -- using the raw integer for both makes row 3 and
column 3 the same node and silently merges unrelated components. Pairing stone
indices avoids that question entirely at the cost of an O(n^2) scan.

Complexity

  • Time — O(n a(n)) where a is the inverse Ackermann function, so effectively O(n).
  • Space — O(n) for the DSU maps.

Common Pitfalls

  • Rows and columns must live in one namespace but must not collide. Using the raw integer for both makes row 3 and column 3 the same node, which silently merges unrelated components.
  • Count roots over the touched nodes only. Sizing the DSU to 10001 rows plus 10001 columns and counting all roots gives a wildly wrong component count.
  • The answer is not n - 1. Isolated stones and disconnected clusters each keep a survivor.
  • Verify the k - 1 claim rather than assuming it: build any spanning tree of the component and remove leaves inward.

Full Solution — all languages

class Solution:
    def removeStones(self, grid):
        n = len(grid)
        if n == 0:
            return 0
        parent = list(range(n))

        def find(x):
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x

        groups = n
        for i in range(n):
            for j in range(i + 1, n):
                if grid[i][0] == grid[j][0] or grid[i][1] == grid[j][1]:
                    a, b = find(i), find(j)
                    if a != b:
                        parent[a] = b
                        groups -= 1
        return n - groups
Asked at PhonePe
SensAI
Beta
Tap the mic to stop voice mode