Skip to content

Commit ec37a17

Browse files
committed
Add 1061
1 parent 6438f2c commit ec37a17

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

Readme.md

+1
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@
115115
| 1032 | Stream of Characters | Hard | O(M) | O(M) | Trie | | |
116116
| 1035 | Uncrossed Lines | Medium | O(N^2) | O(N) | Array, Dynamic Programming | | |
117117
| 1060 | Missing Element in Sorted Array | Medium | O(logN) | O(1) | Binary Search | | 🔒 |
118+
| 1061 | Lexicographically Smallest Equivalent String | Medium | O(N) | O(N) | DFS, Union Find | | 🔒 |
118119
| 1094 | Car Pooling | Medium | O(N) | O(1) | Car Pooling | | |
119120
| 1232 | Check If It Is a Straight Line | Easy | O(N) | O(1) | Math, Pythonic, Geometry | | |
120121
| 1277 | Count Square Submatrices with All Ones | Medium | O(N * M) | O(1) | Array, Dynamic Programming | | |

src/1061.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# TAGS: DFS, Union Find
2+
# REVIEWME: Union Find
3+
class Solution:
4+
# 44 ms, 66.18%. Time and Space: O(N)
5+
def smallestEquivalentString(self, A: str, B: str, S: str) -> str:
6+
class UF:
7+
def __init__(self):
8+
self.array = list(range(26))
9+
10+
def union(self, parent, child):
11+
parent = self.find(parent)
12+
child = self.find(child)
13+
if parent > child:
14+
parent, child = child, parent
15+
self.array[child] = parent
16+
17+
def find(self, value): # find and assign parent
18+
if value != self.array[value]:
19+
parent = self.array[value]
20+
self.array[value] = self.find(parent)
21+
return self.array[value]
22+
23+
disjoint_set = UF()
24+
for c1, c2 in zip(A, B):
25+
c1 = ord(c1) - ord('a')
26+
c2 = ord(c2) - ord('a')
27+
disjoint_set.union(c1, c2)
28+
29+
ans = []
30+
for c in S:
31+
index = ord(c) - ord('a')
32+
parent = disjoint_set.find(index)
33+
ans.append(chr(parent + ord('a')))
34+
35+
return "".join(ans)

0 commit comments

Comments
 (0)