Skip to content

Commit f916b90

Browse files
authored
Merge pull request #870 from yoonthecoder/main
[yoonthecoder] Week 5
2 parents c37dddf + fd476db commit f916b90

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

3sum/yoonthecoder.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
var threeSum = function (nums) {
2+
nums.sort((a, b) => a - b);
3+
const results = [];
4+
for (let i = 0; i < nums.length - 2; i++) {
5+
if (i > 0 && nums[i] === nums[i - 1]) continue;
6+
let left = i + 1;
7+
let right = nums.length - 1;
8+
while (left < right) {
9+
const currSum = nums[i] + nums[left] + nums[right];
10+
11+
if (currSum == 0) {
12+
results.push([nums[i], nums[left], nums[right]]);
13+
left++;
14+
right--;
15+
// to avoid duplicates
16+
while (left < right && nums[left] === nums[left - 1]) left++;
17+
while (left < right && nums[right] === nums[right + 1]) right--;
18+
} else if (currSum < 0) {
19+
left++;
20+
} else right--;
21+
}
22+
}
23+
return results;
24+
};
25+
26+
// Time complexity: O(n^2);
27+
// Space complexity: O(n)
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
var maxProfit = function (prices) {
2+
// set the initial value to Infinity so that it can always return minimum value
3+
let minPrice = Infinity;
4+
let maxPrice = 0;
5+
for (i = 0; i < prices.length; i++) {
6+
minPrice = Math.min(prices[i], minPrice);
7+
maxPrice = Math.max(maxPrice, prices[i + 1] - minPrice);
8+
}
9+
return maxPrice;
10+
};
11+
12+
// Time complexity: O(n) - Iterating through the array
13+
// Space complexity: O(1)

group-anagrams/yoonthecoder.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
var groupAnagrams = function (strs) {
2+
const map = new Map();
3+
4+
for (const str of strs) {
5+
// split the string into each character (returns an array) => sort it => convert it to string
6+
const sortedStr = str.split('').sort().join('');
7+
// use the sorted Str as unique keys in the map
8+
if (map.has(sortedStr)) {
9+
map.get(sortedStr).push(str);
10+
} else map.set(sortedStr, [str]);
11+
}
12+
// convert values into an array
13+
return [...map.values()];
14+
};

0 commit comments

Comments
 (0)