[Leetcode] Problem 1202 - Smallest String With Swaps

You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.

You can swap the characters at any pair of indices in the given pairs any number of times.

Return the lexicographically smallest string that s can be changed to after using the swaps.

Example

No.1

Input: s = “dcab”, pairs = [[0,3],[1,2]]

Output: “bacd”

Explaination:
Swap s[0] and s[3], s = “bcad”
Swap s[1] and s[2], s = “bacd”

No.2

Input: s = “dcab”, pairs = [[0,3],[1,2],[0,2]]

Output: “abcd”

Explaination:
Swap s[0] and s[3], s = “bcad”
Swap s[0] and s[2], s = “acbd”
Swap s[1] and s[2], s = “abcd”

No.3

Input: s = “cba”, pairs = [[0,1],[1,2]]

Output: “abc”

Explaination:
Swap s[0] and s[1], s = “bca”
Swap s[1] and s[2], s = “bac”
Swap s[0] and s[1], s = “abc”

Constraints

  • 1 <= s.length <= 10^5
  • 0 <= pairs.length <= 10^5
  • 0 <= pairs[i][0], pairs[i][1] < s.length
  • s only contains lower case English letters.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public class UnionFind {
private int[] id;
private int[] size;

public UnionFind(int n) {
this.id = new int[n];
this.size = new int[n];

for (int i = 0; i < n; i++) {
id[i] = i;
size[i] = 1;
}
}

public boolean union(int p, int q) {
int pRoot = find(p);
int qRoot = find(q);

if (pRoot == qRoot)
return false;

if (size[pRoot] < size[qRoot]) {
id[pRoot] = qRoot;
size[qRoot] += size[pRoot];
} else {
id[qRoot] = pRoot;
size[pRoot] += size[qRoot];
}

return true;
}

public int find(int p) {
while (p != id[p])
p = id[p];

return p;
}
}

public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
char[] result = s.toCharArray();
UnionFind uf = new UnionFind(s.length());
Map<Integer, List<Integer>> map = new HashMap<>();

for (List<Integer> pair : pairs)
uf.union(pair.get(0), pair.get(1));

for (int i = 0; i < s.length(); i++) {
int root = uf.find(i);
map.putIfAbsent(root, new ArrayList<>());
map.get(root).add(i);
}

for (Map.Entry<Integer, List<Integer>> entry : map.entrySet()) {
List<Integer> index = entry.getValue();
List<Character> chars = new ArrayList<>();

for (int idx : index)
chars.add(result[idx]);

Collections.sort(chars);

for (int i = 0; i < index.size(); i++)
result[index.get(i)] = chars.get(i);
}

return String.valueOf(result);
}