Skip to content

Commit ab5d9de

Browse files
committed
Add week 4 solutions: longest-consecutive-sequence
1 parent 6ef9db5 commit ab5d9de

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}

0 commit comments

Comments
 (0)