File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Finds the length of the longest consecutive elements sequence.
3+ * Eliminates duplicates using a Set and only starts counting when the current number is the beginning of a sequence.
4+ *
5+ * @param nums - An array of integers.
6+ * @returns The length of the longest consecutive sequence.
7+ *
8+ * Time Complexity: O(n)
9+ * Space Complexity: O(n)
10+ */
11+ function longestConsecutive ( nums : number [ ] ) : number {
12+ let longest = 0 ;
13+ const numSet = new Set ( nums ) ;
14+
15+ for ( const num of numSet ) {
16+ if ( ! numSet . has ( num - 1 ) ) {
17+ let length = 1 ;
18+ while ( numSet . has ( num + length ) ) {
19+ length ++ ;
20+ }
21+ longest = Math . max ( length , longest ) ;
22+ }
23+ }
24+
25+ return longest ;
26+ }
You can’t perform that action at this time.
0 commit comments