Skip to content

Commit f634742

Browse files
committed
solve: longest consecutive sequence
1 parent 0a44499 commit f634742

File tree

1 file changed

+38
-0
lines changed
  • longest-consecutive-sequence

1 file changed

+38
-0
lines changed

longest-consecutive-sequence/evan.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var longestConsecutive = function (nums) {
6+
const set = new Set(nums);
7+
let longestStreak = 0;
8+
9+
for (const num of set) {
10+
// Check if it's the start of a sequence
11+
if (!set.has(num - 1)) {
12+
let currentNum = num;
13+
let currentStreak = 1;
14+
15+
// Find the length of the sequence
16+
while (set.has(currentNum + 1)) {
17+
currentNum += 1;
18+
currentStreak += 1;
19+
}
20+
21+
longestStreak = Math.max(longestStreak, currentStreak);
22+
}
23+
}
24+
25+
return longestStreak;
26+
};
27+
28+
/**
29+
* Time Complexity: O(n) where n is the length of the input array.
30+
* Reason:
31+
* Creating the Set: O(n)
32+
* Iterating Through the Set: O(n)
33+
* Checking for the Start of a Sequence: O(n)
34+
* Finding the Length of the Sequence: O(n) across all sequences
35+
* Tracking the Longest Sequence: O(n)
36+
*
37+
* Space Complexity: O(n) because of the additional space used by the set.
38+
*/

0 commit comments

Comments
 (0)