File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * requirement: return result in linear time (O(n))
3
+ */
4
+ function longestConsecutive ( nums : number [ ] ) : number {
5
+ if ( nums . length === 0 ) return 0 ;
6
+
7
+ const numSet = new Set ( nums ) ; // O(1) lookups
8
+ let maxLength = 0 ;
9
+
10
+ for ( const num of numSet ) {
11
+ // key: determine the "start" of a consecutive sequence.
12
+ // approach: if num - 1 doesn't exist in the set → num is the start of a sequence.
13
+ if ( ! numSet . has ( num - 1 ) ) {
14
+ let currentNum = num ;
15
+ let currentLength = 1 ;
16
+
17
+ // count consecutive numbers
18
+ while ( numSet . has ( currentNum + 1 ) ) {
19
+ currentNum ++ ;
20
+ currentLength ++ ;
21
+ }
22
+
23
+ maxLength = Math . max ( maxLength , currentLength ) ;
24
+ }
25
+ }
26
+ return maxLength ;
27
+ }
You can’t perform that action at this time.
0 commit comments