Skip to content

Commit 43e64ab

Browse files
committed
Longest Consecutive Sequence solution
1 parent 9fa5118 commit 43e64ab

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
var longestConsecutive = function (nums) { // sorting approach
2+
if (!nums.length) return 0;
3+
let set = new Set(nums);
4+
let sorted = [...set].sort((a, b) => a - b);
5+
let longestSeq = 0;
6+
let currSeq = 1;
7+
8+
for (let i = 1; i < sorted.length; i++) { // loop through sorted list to find sequence
9+
if (sorted[i - 1] + 1 === sorted[i]) {
10+
currSeq++;
11+
} else {
12+
longestSeq = Math.max(longestSeq, currSeq); // compare sequence to figure out the longest
13+
currSeq = 1;
14+
}
15+
}
16+
17+
return Math.max(longestSeq, currSeq);
18+
};
19+
20+
// time - O(nlong) using sort
21+
// space - O(n) store nums in set
22+
23+
24+
// TODO - try O(n) TC approach

0 commit comments

Comments
 (0)