mediumUnion FindUnion Find

Most Stones Removed

mediumTime: O(n * α(n))Space: O(n)

Signals to notice

remove stones sharing row or columnconnected stones form groupsmaximize removals

Brute force first

Try all removal orders — factorial. The order matters for what's removable at each step. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Union-Find: stones sharing a row or column are connected. Each connected group of k stones allows k-1 removals (leave one). Answer = totalStones - numberOfGroups. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

What must stay true

Within a connected group (stones linked by shared rows/columns), you can always remove all but one stone. The maximum removals = total stones - number of connected groups. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Easy way to go wrong

Trying to simulate the removal process — you don't need to find the ORDER of removals, just the COUNT. Counting groups with Union-Find gives the answer directly. The fix is usually to return to the meaning of each move, not just the steps themselves.

Union Find Pattern