Skip to content

Commit 286843d

Browse files
committed
unioning adjacent elements
1 parent f6aee9d commit 286843d

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

UnionFind/longestConsecutiveUF.java

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
class Solution {
2+
/*
3+
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+
public int longestConsecutive(int[] nums) {
7+
UnionFind uf = new UnionFind(nums.length);
8+
HashMap<Integer, Integer> hm = new HashMap<>();
9+
10+
for (int i=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+
return uf.getLargestComponentSize();
25+
}
26+
}
27+
28+
class UnionFind {
29+
int[] parent;
30+
int[] size;
31+
32+
public UnionFind(int n) {
33+
parent = new int[n];
34+
size = new int[n];
35+
for (int i=0; i<n; i++) {
36+
parent[i] = i;
37+
size[i] = 1;
38+
}
39+
}
40+
41+
public void union(int x, int y) {
42+
int xParent = find(x);
43+
int yParent = 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
48+
}
49+
}
50+
51+
public int find(int x) {
52+
while (parent[x] != x) {
53+
x = parent[x];
54+
}
55+
return x;
56+
}
57+
58+
public int getLargestComponentSize() {
59+
int maxSize = 0;
60+
for (int i=0; i<parent.length; i++) {
61+
if ((parent[i] == i)&&(size[i] > maxSize)) {
62+
maxSize = size[i];
63+
}
64+
}
65+
return maxSize;
66+
}
67+
}

0 commit comments

Comments
 (0)