565. Array Nesting

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
class Solution {
private static class UnionFind {
private final int[] parent;

public UnionFind(int n) {
this.parent = new int[n];
for (int i = 0; i < parent.length; i++) {
parent[i] = i;
}
}

public void union(int x, int y) {
int xRoot = getRoot(x), yRoot = getRoot(y);
if (xRoot == yRoot) {
return;
}

parent[xRoot] = yRoot;
}

private int getRoot(int x) {
if (parent[x] != x) {
parent[x] = getRoot(parent[x]);
}
return parent[x];
}

}

public int arrayNesting(int[] nums) {
UnionFind unionFind = new UnionFind(nums.length);
for (int num : nums) {
unionFind.union(num, nums[num]);
}

int max = 0;
Map<Integer, Integer> rootToCountMap = new HashMap<>();
for (int num : nums) {
int root = unionFind.getRoot(num);
rootToCountMap.put(root, rootToCountMap.getOrDefault(root, 0) + 1);
max = Math.max(max, rootToCountMap.get(root));
}
return max;
}
}

References

565. Array Nesting