File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {string } s
3+ * @param {number[][] } pairs
4+ * @return {string }
5+ */
6+ const smallestStringWithSwaps = function ( s , pairs ) {
7+ let set = Array ( s . length ) . fill ( - 1 )
8+ function union ( a , b ) {
9+ let root1 = find ( a )
10+ let root2 = find ( b )
11+ if ( root1 !== root2 ) {
12+ set [ root2 ] = root1
13+ }
14+ }
15+ function find ( a ) {
16+ if ( set [ a ] < 0 ) {
17+ return a
18+ } else {
19+ return ( set [ a ] = find ( set [ a ] ) )
20+ }
21+ }
22+ for ( let pair of pairs ) {
23+ union ( pair [ 0 ] , pair [ 1 ] )
24+ }
25+ let groups = [ ]
26+ for ( let i = 0 ; i < s . length ; i ++ ) {
27+ groups [ i ] = [ ]
28+ }
29+ for ( let i = 0 ; i < s . length ; i ++ ) {
30+ groups [ find ( i ) ] . push ( i )
31+ }
32+ let sArr = s . split ( '' )
33+ for ( let i = 0 ; i < s . length ; i ++ ) {
34+ if ( groups [ i ] . length > 1 ) {
35+ let chars = groups [ i ] . map ( idx => s [ idx ] )
36+ chars . sort ( )
37+ for ( let k = 0 ; k < groups [ i ] . length ; k ++ ) {
38+ sArr [ groups [ i ] [ k ] ] = chars [ k ]
39+ }
40+ }
41+ }
42+ return sArr . join ( '' )
43+ }
You can’t perform that action at this time.
0 commit comments