Skip to content

Commit e351218

Browse files
committed
Add week 5 solutions : longestConsecutiveSequence, 3Sum
1 parent e44814c commit e351218

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

3sum/yolophg.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Time Complexity: O(n^2)
2+
// Space Complexity: O(n)
3+
4+
// Time Complexity: O(n^2)
5+
// Space Complexity: O(n)
6+
7+
var threeSum = function(nums) {
8+
nums.sort((a, b) => a - b);
9+
// create a set to store triplets.
10+
const result = new Set();
11+
12+
// loop through the array, but stop 2 elements before the end.
13+
for (let i = 0; i < nums.length - 2; i++) {
14+
// if the current element is the same as the one before it, skip it to avoid duplicates.
15+
if (i > 0 && nums[i] === nums[i - 1]) continue;
16+
17+
// create a set to keep track of the complements.
18+
const complements = new Set();
19+
// start another loop from the next element.
20+
for (let j = i + 1; j < nums.length; j++) {
21+
const complement = -nums[i] - nums[j];
22+
// check if the current number is in the set.
23+
if (complements.has(nums[j])) {
24+
// if it is, found a triplet. Add it to the result set as a sorted string to avoid duplicates.
25+
result.add(JSON.stringify([nums[i], complement, nums[j]].sort((a, b) => a - b)));
26+
} else {
27+
complements.add(complement);
28+
}
29+
}
30+
}
31+
32+
// convert set of strings back to arrays.
33+
return Array.from(result).map(triplet => JSON.parse(triplet));
34+
};
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Time Complexity: O(n log n)
2+
// Space Complexity: O(n)
3+
4+
var longestConsecutive = function(nums) {
5+
if (nums.length === 0) return 0;
6+
7+
nums.sort((a, b) => a - b);
8+
9+
let longestStreak = 1;
10+
let currentStreak = 1;
11+
12+
// iterate through the sorted array.
13+
for (let i = 1; i < nums.length; i++) {
14+
// check for duplicates.
15+
if (nums[i] !== nums[i - 1]) {
16+
if (nums[i] === nums[i - 1] + 1) {
17+
// if current element is consecutive, increment current streak.
18+
currentStreak++;
19+
} else {
20+
// if not, update longest streak and reset current streak.
21+
longestStreak = Math.max(longestStreak, currentStreak);
22+
currentStreak = 1;
23+
}
24+
}
25+
}
26+
27+
// final comparison to ensure the longest streak is captured.
28+
longestStreak = Math.max(longestStreak, currentStreak);
29+
30+
return longestStreak;
31+
}

0 commit comments

Comments
 (0)