Skip to content

Commit 84f9275

Browse files
committed
Added longest consecutive solution
1 parent c8d7169 commit 84f9275

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
var longestConsecutive = function (nums) {
2+
// Return 0 if there are no elements in nums
3+
if (nums.length === 0) return 0;
4+
5+
// Create a set to find values efficiently
6+
const numSet = new Set(nums);
7+
let maxLength = 0;
8+
9+
for (let num of numSet) {
10+
// Check if this is the start of a sequence
11+
if (!numSet.has(num - 1)) {
12+
let currentNum = num;
13+
let currentLength = 1;
14+
15+
// Count the length of the sequence
16+
while (numSet.has(currentNum + 1)) {
17+
currentNum += 1;
18+
currentLength += 1;
19+
}
20+
21+
// Update the maximum length
22+
maxLength = Math.max(maxLength, currentLength);
23+
}
24+
}
25+
26+
return maxLength;
27+
};
28+
29+
// TC: O(n)
30+
// SC: O(n)

0 commit comments

Comments
 (0)