File tree 2 files changed +36
-0
lines changed
2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change 115
115
| 1032 | Stream of Characters | Hard | O(M) | O(M) | Trie | | |
116
116
| 1035 | Uncrossed Lines | Medium | O(N^2) | O(N) | Array, Dynamic Programming | | |
117
117
| 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 | | 🔒 |
118
119
| 1094 | Car Pooling | Medium | O(N) | O(1) | Car Pooling | | |
119
120
| 1232 | Check If It Is a Straight Line | Easy | O(N) | O(1) | Math, Pythonic, Geometry | | |
120
121
| 1277 | Count Square Submatrices with All Ones | Medium | O(N * M) | O(1) | Array, Dynamic Programming | | |
Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments