diff --git a/merge-intervals/gitsunmin.ts b/merge-intervals/gitsunmin.ts new file mode 100644 index 000000000..c5d1044c7 --- /dev/null +++ b/merge-intervals/gitsunmin.ts @@ -0,0 +1,18 @@ +/** + * https://leetcode.com/problems/merge-intervals/ + * time complexity : O(n) + * space complexity : O(n) + */ + +function merge(intervals: number[][]): number[][] { + if (intervals.length === 0) return []; + + intervals.sort((a, b) => a[0] - b[0]); + + const merged: number[][] = []; + for (const interval of intervals) { + if (merged.length === 0 || merged[merged.length - 1][1] < interval[0]) merged.push(interval); + else merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], interval[1]); + } + return merged; +}; diff --git a/remove-nth-node-from-end-of-list/gitsunmin.ts b/remove-nth-node-from-end-of-list/gitsunmin.ts new file mode 100644 index 000000000..0db7d792f --- /dev/null +++ b/remove-nth-node-from-end-of-list/gitsunmin.ts @@ -0,0 +1,33 @@ +/** + * https://leetcode.com/problems/remove-nth-node-from-end-of-list/ + * time complexity : O(n) + * space complexity : O(1) + */ + +class ListNode { + val: number + next: ListNode | null + constructor(val?: number, next?: ListNode | null) { + this.val = (val === undefined ? 0 : val) + this.next = (next === undefined ? null : next) + } +} + +function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { + const dummy = new ListNode(0, head); + let first: ListNode | null = dummy; + let second: ListNode | null = dummy; + + for (let i = 0; i <= n; i++) { + if (first !== null) first = first.next; + } + + while (first !== null) { + first = first.next; + second = second!.next; + } + + if (second !== null && second.next !== null) second.next = second.next.next; + + return dummy.next; +}; diff --git a/same-tree/gitsunmin.ts b/same-tree/gitsunmin.ts new file mode 100644 index 000000000..fb5fe098e --- /dev/null +++ b/same-tree/gitsunmin.ts @@ -0,0 +1,24 @@ +/** + * https://leetcode.com/problems/same-tree/ + * time complexity : O(n) + * space complexity : O(n) + */ + +class TreeNode { + val: number + left: TreeNode | null + right: TreeNode | null + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = (val === undefined ? 0 : val) + this.left = (left === undefined ? null : left) + this.right = (right === undefined ? null : right) + } +} + +function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { + if (p === null && q === null) return true; + if (p === null || q === null) return false; + if (p.val !== q.val) return false; + + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); +};