You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Regarding consecutive numbers as a connected component, so we have to find the size of the largest component. 2 nodes are connected if they are consecutive. So, we union the indexes if the values of array are consecutive and keep a track of size. We return maximum value in size array.
4
+
T.C-> O(n)
5
+
*/
6
+
publicintlongestConsecutive(int[] nums) {
7
+
UnionFinduf = newUnionFind(nums.length);
8
+
HashMap<Integer, Integer> hm = newHashMap<>();
9
+
10
+
for (inti=0; i< nums.length; i++) {
11
+
if (hm.containsKey(nums[i])) {
12
+
continue; // not allowing duplicate values
13
+
}
14
+
15
+
if (hm.containsKey(nums[i] - 1)) {
16
+
uf.union(i, hm.get(nums[i] - 1)); // unioning the indexes of the array if the value contained is consecutive
17
+
}
18
+
19
+
if (hm.containsKey(nums[i] + 1)) {
20
+
uf.union(i, hm.get(nums[i] + 1));
21
+
}
22
+
hm.put(nums[i], i);
23
+
}
24
+
returnuf.getLargestComponentSize();
25
+
}
26
+
}
27
+
28
+
classUnionFind {
29
+
int[] parent;
30
+
int[] size;
31
+
32
+
publicUnionFind(intn) {
33
+
parent = newint[n];
34
+
size = newint[n];
35
+
for (inti=0; i<n; i++) {
36
+
parent[i] = i;
37
+
size[i] = 1;
38
+
}
39
+
}
40
+
41
+
publicvoidunion(intx, inty) {
42
+
intxParent = find(x);
43
+
intyParent = find(y);
44
+
45
+
if (xParent != yParent) {
46
+
parent[xParent] = yParent; // making one as parent of other
47
+
size[yParent] = size[yParent] + size[xParent]; // increasing the size array for it
0 commit comments