Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions maximum-subarray/reeseo3o.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* DFS
* Time complexity: O(n)
* Space complexity: O(h) - h is the height of the tree, worst case O(n)
*/
const maxDepth = (root) => {
if (root === null) return 0;

const leftDepth = maxDepth(root.left);
const rightDepth = maxDepth(root.right);

return 1 + Math.max(leftDepth, rightDepth);
};

/**
* BFS
* Time complexity: O(n)
* Space complexity: O(n)
*/
const maxDepthBFS = (root) => {
if (root === null) return 0;

const queue = [root];
let depth = 0;

while (queue.length > 0) {
const levelSize = queue.length;

for (let i = 0; i < levelSize; i++) {
const node = queue.shift();
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}

depth++;
}

return depth;
};
42 changes: 42 additions & 0 deletions merge-two-sorted-lists/reeseo3o.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* 1. Recursive approach
* Time complexity: O(n + m)
* Space complexity: O(n + m)
*/
// const mergeTwoLists = (list1, list2) => {
// if (!list1) return list2;
// if (!list2) return list1;
//
// if (list1.val <= list2.val) {
// list1.next = mergeTwoLists(list1.next, list2);
// return list1;
// } else {
// list2.next = mergeTwoLists(list1, list2.next);
// return list2;
// }
// };

/**
* 2. Iterative approach + Dummy Node
* Time complexity: O(n + m)
* Space complexity: O(1)
*/
const mergeTwoLists = (list1, list2) => {
const dummy = new ListNode(-1);
let current = dummy;

while (list1 !== null && list2 !== null) {
if (list1.val <= list2.val) {
current.next = list1;
list1 = list1.next;
} else {
current.next = list2;
list2 = list2.next;
}
current = current.next;
}

current.next = list1 ?? list2;

return dummy.next;
};
Loading