Skip to content

Commit 94473f0

Browse files
authored
Merge pull request #2479 from reeseo3o/main
[reeseo3o] WEEK 04 Solutions
2 parents e976c4c + fde6a4a commit 94473f0

2 files changed

Lines changed: 81 additions & 0 deletions

File tree

maximum-subarray/reeseo3o.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* DFS
3+
* Time complexity: O(n)
4+
* Space complexity: O(h) - h is the height of the tree, worst case O(n)
5+
*/
6+
const maxDepth = (root) => {
7+
if (root === null) return 0;
8+
9+
const leftDepth = maxDepth(root.left);
10+
const rightDepth = maxDepth(root.right);
11+
12+
return 1 + Math.max(leftDepth, rightDepth);
13+
};
14+
15+
/**
16+
* BFS
17+
* Time complexity: O(n)
18+
* Space complexity: O(n)
19+
*/
20+
const maxDepthBFS = (root) => {
21+
if (root === null) return 0;
22+
23+
const queue = [root];
24+
let depth = 0;
25+
26+
while (queue.length > 0) {
27+
const levelSize = queue.length;
28+
29+
for (let i = 0; i < levelSize; i++) {
30+
const node = queue.shift();
31+
if (node.left) queue.push(node.left);
32+
if (node.right) queue.push(node.right);
33+
}
34+
35+
depth++;
36+
}
37+
38+
return depth;
39+
};

merge-two-sorted-lists/reeseo3o.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 1. Recursive approach
3+
* Time complexity: O(n + m)
4+
* Space complexity: O(n + m)
5+
*/
6+
// const mergeTwoLists = (list1, list2) => {
7+
// if (!list1) return list2;
8+
// if (!list2) return list1;
9+
//
10+
// if (list1.val <= list2.val) {
11+
// list1.next = mergeTwoLists(list1.next, list2);
12+
// return list1;
13+
// } else {
14+
// list2.next = mergeTwoLists(list1, list2.next);
15+
// return list2;
16+
// }
17+
// };
18+
19+
/**
20+
* 2. Iterative approach + Dummy Node
21+
* Time complexity: O(n + m)
22+
* Space complexity: O(1)
23+
*/
24+
const mergeTwoLists = (list1, list2) => {
25+
const dummy = new ListNode(-1);
26+
let current = dummy;
27+
28+
while (list1 !== null && list2 !== null) {
29+
if (list1.val <= list2.val) {
30+
current.next = list1;
31+
list1 = list1.next;
32+
} else {
33+
current.next = list2;
34+
list2 = list2.next;
35+
}
36+
current = current.next;
37+
}
38+
39+
current.next = list1 ?? list2;
40+
41+
return dummy.next;
42+
};

0 commit comments

Comments
 (0)