File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
+ */
You can’t perform that action at this time.
0 commit comments