Skip to content

Commit 2f5ad9c

Browse files
authored
Update 0128-longest-consecutive-sequence.kt
1 parent aaa1281 commit 2f5ad9c

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed

kotlin/0128-longest-consecutive-sequence.kt

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,54 @@ class Solution {
2222
}
2323
return longestSize
2424
}
25-
}
25+
}
26+
27+
// Alternative solution using Union Find
28+
class Solution {
29+
30+
class DSU(val n: Int) {
31+
val parent = IntArray(n) { it }
32+
val size = IntArray(n) { 1 }
33+
34+
fun find(x: Int): Int {
35+
if (parent[x] != x)
36+
parent[x] = find(parent[x])
37+
return parent[x]
38+
}
39+
40+
fun union(x: Int, y: Int) {
41+
val px = find(x)
42+
val py = find(y)
43+
if (px != py) {
44+
parent[py] = px
45+
size[px] += size[py]
46+
}
47+
}
48+
49+
fun getLongest(): Int {
50+
var res = 0
51+
for (i in parent.indices) {
52+
if (parent[i] == i)
53+
res = maxOf(res, size[i])
54+
}
55+
return res
56+
}
57+
}
58+
59+
60+
fun longestConsecutive(nums: IntArray): Int {
61+
val hm = HashMap<Int, Int>()
62+
val dsu = DSU(nums.size)
63+
64+
for ((i,n) in nums.withIndex()) {
65+
if (n in hm) continue
66+
67+
hm[n - 1]?.let { dsu.union(i, it) }
68+
hm[n + 1]?.let { dsu.union(i, it) }
69+
70+
hm[n] = i
71+
}
72+
73+
return dsu.getLongest()
74+
}
75+
}

0 commit comments

Comments
 (0)