Skip to content

Commit 6e50eb8

Browse files
authored
Create most-stones-removed-with-same-row-or-column.py
1 parent 44add54 commit 6e50eb8

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
class UnionFind(object):
5+
def __init__(self, n):
6+
self.set = range(n)
7+
8+
def find_set(self, x):
9+
if self.set[x] != x:
10+
self.set[x] = self.find_set(self.set[x]) # path compression.
11+
return self.set[x]
12+
13+
def union_set(self, x, y):
14+
x_root, y_root = map(self.find_set, (x, y))
15+
if x_root == y_root:
16+
return False
17+
self.set[min(x_root, y_root)] = max(x_root, y_root)
18+
return True
19+
20+
21+
class Solution(object):
22+
def removeStones(self, stones):
23+
"""
24+
:type stones: List[List[int]]
25+
:rtype: int
26+
"""
27+
MAX_ROW = 10000
28+
union_find = UnionFind(2*MAX_ROW)
29+
for r, c in stones:
30+
union_find.union_set(r, c+MAX_ROW)
31+
return len(stones) - len({union_find.find_set(r) for r, _ in stones})

0 commit comments

Comments
 (0)