Skip to content

Commit 3818661

Browse files
Merge pull request #603 from harshitpandey-26/patch-4
Create LongestConsecutiveSequence.java
2 parents 93149ef + f3cd824 commit 3818661

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Author: HarshitKumarPandey
2+
// Date: 2025-10-09
3+
// Description: Find the length of the longest consecutive sequence using HashSet in O(n) time.
4+
5+
import java.util.HashSet;
6+
7+
public class LongestConsecutiveSequence {
8+
9+
public static int longestConsecutive(int[] nums) {
10+
if (nums.length == 0) return 0;
11+
12+
HashSet<Integer> set = new HashSet<>();
13+
for (int num : nums) set.add(num);
14+
15+
int longestStreak = 0;
16+
17+
for (int num : set) {
18+
// Only start counting when it's the beginning of a sequence
19+
if (!set.contains(num - 1)) {
20+
int currentNum = num;
21+
int currentStreak = 1;
22+
23+
// Count consecutive numbers
24+
while (set.contains(currentNum + 1)) {
25+
currentNum++;
26+
currentStreak++;
27+
}
28+
29+
longestStreak = Math.max(longestStreak, currentStreak);
30+
}
31+
}
32+
return longestStreak;
33+
}
34+
35+
public static void main(String[] args) {
36+
int[] nums = {100, 4, 200, 1, 3, 2};
37+
System.out.println("Longest consecutive sequence length: " + longestConsecutive(nums));
38+
}
39+
}

0 commit comments

Comments
 (0)