We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent c8d7169 commit 84f9275Copy full SHA for 84f9275
longest-consecutive-sequence/nhistory.js
@@ -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