Python coding

Remove stones sharing a row or column

Stones lie on a grid at the distinct points [x, y] of stones. One move removes a stone that shares its row or its column (the same x or the same y) with at least one other stone still on the grid. Return the largest number of stones you can remove, making the moves in the best order.

There is at least one stone, and coordinates are integers from 0 to 10⁴. Aim for near-linear time, not a comparison of every pair of stones.

Besides the tests, one large input (3,000 stones) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • max_removed([[0,0],[0,3],[2,3],[5,5],[5,1]]) → 3
  • max_removed([[1,1]]) → 0
  • max_removed([[0,0],[1,1],[2,2]]) → 0
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Link stones that share a row or a column, directly or through other stones, into groups. A group can lose every stone but one: remove them from the far end of a chain inward.

Hint 2

So the answer is stones minus groups. To build the groups without comparing pairs, make every row and every column a node and union each stone's row with its column.

Hint 3

Keep rows and columns apart, for example as ("row", x) and ("col", y): row 3 and column 3 are different lines.

Solution and why it works
pythonO(n · α(n)) · O(n)
def max_removed(stones: list[list[int]]) -> int:
    parent, size = {}, {}

    def find(x: tuple) -> tuple:
        while parent[x] != x:
            parent[x] = parent[parent[x]]        # path halving
            x = parent[x]
        return x

    for x, y in stones:
        a, b = ("row", x), ("col", y)            # rows and columns are separate nodes
        for line in (a, b):
            if line not in parent:
                parent[line], size[line] = line, 1
        ra, rb = find(a), find(b)
        if ra != rb:                             # the stone joins its row's group to its column's
            if size[ra] < size[rb]:
                ra, rb = rb, ra
            parent[rb] = ra
            size[ra] += size[rb]
    groups = {find(("row", x)) for x, _ in stones}
    return len(stones) - len(groups)             # each group can shed all its stones but one

Stones linked through shared lines form groups, and a group of k stones can always lose k − 1 of them (take the ends of a chain first) but never its last one, so the answer is stones minus groups. Unioning each stone's row node with its column node builds the groups with one union per stone instead of comparing pairs. The trap is giving rows and columns the same keys: then [1, 0] and [0, 1] look linked though they share no line.