File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * https://leetcode.com/problems/longest-consecutive-sequence
3+ * time complexity : O(n)
4+ * space complexity : O(n)
5+ */
6+ const findStreak = ( set : Set < number > ) => ( num : number ) : number => {
7+ if ( ! set . has ( num - 1 ) ) return takeWhile ( num , currentNum => set . has ( currentNum ) ) . length ;
8+ return 0 ;
9+ } ;
10+
11+ const takeWhile = ( start : number , predicate : ( value : number ) => boolean ) : number [ ] => {
12+ const result : number [ ] = [ ] ;
13+ let currentNum = start ;
14+ while ( predicate ( currentNum ) ) {
15+ result . push ( currentNum ) ;
16+ currentNum += 1 ;
17+ }
18+ return result ;
19+ }
20+
21+ const max = ( maxStreak : number , currentStreak : number ) : number => Math . max ( maxStreak , currentStreak ) ;
22+
23+ function longestConsecutive ( nums : number [ ] ) : number {
24+ const numSet = new Set ( nums ) ;
25+
26+ return [ ...numSet ]
27+ . map ( findStreak ( numSet ) )
28+ . reduce ( max , 0 ) ;
29+ }
You can’t perform that action at this time.
0 commit comments