Python 0947.py
class Solution:
def removeStones(self, stones: List[List[int]]) -> int:
# all stones sharing a row or column create a subnet
# => count all distinct subnets
result = 0
# union-find, copied from problem 721, simplified
def find(x):
if parent[x] != x:
parent[x] = find(parent[x]) # path compression
return parent[x]
def union(x, y):
parent[find(x)] = find(y)
# identity
parent = { x : x for x, y in stones }
# group point into rows
rows = {} # just store the first point
for x, y in stones:
if y in rows:
union(rows[y], x)
else:
rows[y] = x
# find distinct groups
distinct = set([ find(rows[y]) for y in rows ])
return len(stones) - len(distinct)
Difficulty
and has an acceptance rate of about 63% (600k+ submissions).
Typical patterns to solve this problem:
- Depth First Search
- Graph Theory
- Hash Table
- Union Find
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the “remove stones” problem by modeling stones that share a row or a column as members of the same connected component. The core idea is to count how many distinct components exist and then subtract that number from the total stone count; the difference equals the maximum number of stones that can be removed. The algorithm relies on a union-find (disjoint-set) data structure with path compression to efficiently merge and query components.
Key Steps
1. Preparing the Union-Find Structure
A dictionary named parent is created where each stone’s x-coordinate is initially its own representative. This choice of using the x-coordinate as the identifier works because every stone is uniquely identified by its x value in the context of the union operations that follow.
parent = { x : x for x, y in stones }
2. Defining Find with Path Compression
The find function recursively climbs the parent links until it reaches the root of a component. While unwinding the recursion, it flattens the tree by assigning each visited node directly to the root, which speeds up subsequent queries.
def find(x):
if parent[x] != x:
parent[x] = find(parent[x]) # path compression
return parent[x]
3. Defining Union
The union function merges two components by linking the root of one directly to the root of the other. Because the algorithm does not maintain rank or size, the merge is performed in a single assignment.
def union(x, y):
parent[find(x)] = find(y)
4. Grouping Stones by Row
A dictionary called rows records the first stone encountered for each y-coordinate (row). When a subsequent stone shares the same row, the algorithm unites its x-coordinate with the stored representative of that row. This step ensures that all stones in the same row become part of a single component.
rows = {}
for x, y in stones:
if y in rows:
union(rows[y], x)
else:
rows[y] = x
5. Extracting Distinct Components
After processing all stones, the algorithm computes the set of unique component roots by applying find to the stored representative of each row. The size of this set equals the number of distinct subnets.
distinct = set([ find(rows[y]) for y in rows ])
6. Computing the Result
The final answer is the total number of stones minus the number of distinct components, reflecting the maximum removable stones.
return len(stones) - len(distinct)
Edge Cases Handled
When the input contains a single stone, the rows dictionary holds one entry, distinct becomes a set with a single root, and the returned value is zero, correctly indicating that no stone can be removed.
If multiple stones share the same row but have different columns, the union operation merges all of their x-identifiers into one component, and the distinct set still contains only one root for that row.
When stones are arranged such that each stone lies on a unique row and column, no union operations are triggered; each stone remains its own component, the distinct set size equals the number of stones, and the result is zero, which matches the expectation that no removal is possible.
The algorithm also gracefully handles cases where several rows intersect via columns. Because unions are performed whenever a row repeats, and the find function compresses paths, transitive connections across rows and columns are correctly collapsed into a single component.
Performance Optimizations
Path compression inside the find function reduces the depth of the union-find trees, ensuring that subsequent find calls execute in near-constant time.
Storing only the first stone per row in the rows dictionary avoids redundant union operations; each additional stone in the same row triggers a single union with the existing representative.
Using a dictionary for parent provides O(1) average-case access to representatives, which is faster than list-based indexing when the identifiers are not contiguous.
The final distinct component count is obtained with a set comprehension that directly applies find to each stored row representative, eliminating the need for an explicit loop and extra temporary structures.
Overall, the combination of these techniques yields an implementation that scales efficiently with the number of stones while keeping the code concise.
ELI5 - Simplified Explanation
Imagine you have a big collection of colorful building blocks scattered across a grid. Think of each block as a little friend. When two blocks are sitting in the same row or the same column, those two friends are holding hands in a line. Because they are holding hands, they belong to the same group. You can keep connecting friends until you have several different groups all over the board.
The code works by looking at every block to see if it can reach out and join a group. It uses a clever trick to remember who is connected to whom. First, it looks at the blocks in each row and makes sure they are all officially joined together as a team. Then, it does the same thing for all the columns.
Once all the lines are drawn and everyone is holding hands with their neighbors, the code counts how many separate groups, or teams, are left on the board. Each group is like a chain of friends. If you want to take away the most blocks possible while still leaving at least one friend behind in every group, you just count how many total blocks are on the board and subtract the number of groups you found. This tells you exactly how many extra blocks you can pick up.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | ||||||||
| leetcode.ca | C++ | Java | JS | Go | Python | TS | ||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| withaarzoo | C++ | |||||||||
| yuanliu666 | Kotlin | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Java | |||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| withaarzoo | C++ | |||||||||
| yuanliu666 | Kotlin |
Videos
Solved On The Same Day
- problem 640: Solve the Equation
- problem 898: Bitwise ORs of Subarrays
- problem 915: Partition Array into Disjoint Intervals
- problem 974: Subarray Sums Divisible by K
- problem 978: Longest Turbulent Subarray
- problem 1508: Range Sum of Sorted Subarray Sums
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality