From 3fe3bd8074d23b232c032618fcbefd58447dd294 Mon Sep 17 00:00:00 2001 From: ThanhNIT Date: Tue, 15 Apr 2025 21:10:24 +0700 Subject: [PATCH] Added tasks 452-918 --- README.md | 13 +++ .../readme.md | 47 ++++++++++ .../solution.ts | 20 +++++ src/main/ts/g0501_0600/s0502_ipo/readme.md | 47 ++++++++++ src/main/ts/g0501_0600/s0502_ipo/solution.ts | 86 +++++++++++++++++++ .../readme.md | 28 ++++++ .../solution.ts | 37 ++++++++ .../readme.md | 26 ++++++ .../solution.ts | 44 ++++++++++ .../s0909_snakes_and_ladders/readme.md | 55 ++++++++++++ .../s0909_snakes_and_ladders/solution.ts | 44 ++++++++++ .../readme.md | 39 +++++++++ .../solution.ts | 25 ++++++ .../solution.test.ts | 36 ++++++++ .../ts/g0501_0600/s0502_ipo/solution.test.ts | 11 +++ .../solution.test.ts | 12 +++ .../solution.test.ts | 12 +++ .../s0909_snakes_and_ladders/solution.test.ts | 25 ++++++ .../solution.test.ts | 15 ++++ 19 files changed, 622 insertions(+) create mode 100644 src/main/ts/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/readme.md create mode 100644 src/main/ts/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/solution.ts create mode 100644 src/main/ts/g0501_0600/s0502_ipo/readme.md create mode 100644 src/main/ts/g0501_0600/s0502_ipo/solution.ts create mode 100644 src/main/ts/g0501_0600/s0530_minimum_absolute_difference_in_bst/readme.md create mode 100644 src/main/ts/g0501_0600/s0530_minimum_absolute_difference_in_bst/solution.ts create mode 100644 src/main/ts/g0601_0700/s0637_average_of_levels_in_binary_tree/readme.md create mode 100644 src/main/ts/g0601_0700/s0637_average_of_levels_in_binary_tree/solution.ts create mode 100644 src/main/ts/g0901_1000/s0909_snakes_and_ladders/readme.md create mode 100644 src/main/ts/g0901_1000/s0909_snakes_and_ladders/solution.ts create mode 100644 src/main/ts/g0901_1000/s0918_maximum_sum_circular_subarray/readme.md create mode 100644 src/main/ts/g0901_1000/s0918_maximum_sum_circular_subarray/solution.ts create mode 100644 src/test/ts/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/solution.test.ts create mode 100644 src/test/ts/g0501_0600/s0502_ipo/solution.test.ts create mode 100644 src/test/ts/g0501_0600/s0530_minimum_absolute_difference_in_bst/solution.test.ts create mode 100644 src/test/ts/g0601_0700/s0637_average_of_levels_in_binary_tree/solution.test.ts create mode 100644 src/test/ts/g0901_1000/s0909_snakes_and_ladders/solution.test.ts create mode 100644 src/test/ts/g0901_1000/s0918_maximum_sum_circular_subarray/solution.test.ts diff --git a/README.md b/README.md index ef5837c..c69e9aa 100644 --- a/README.md +++ b/README.md @@ -236,6 +236,7 @@ TypeScript-based LeetCode algorithm problem solutions, regularly updated. | | | | | | |-|-|-|-|-|- | 0053 |[Maximum Subarray](src/main/ts/g0001_0100/s0053_maximum_subarray/solution.ts)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer, Big_O_Time_O(n)_Space_O(1) | 0 | 100.00 +| 0918 |[Maximum Sum Circular Subarray](src/main/ts/g0901_1000/s0918_maximum_sum_circular_subarray/solution.ts)| Medium | Array, Dynamic_Programming, Divide_and_Conquer, Queue, Monotonic_Queue, Medium, Array, Dynamic_Programming, Divide_and_Conquer, Queue, Monotonic_Queue | 2 | 91.04 #### Day 6 @@ -1111,6 +1112,7 @@ TypeScript-based LeetCode algorithm problem solutions, regularly updated. | 0228 |[Summary Ranges](src/main/ts/g0201_0300/s0228_summary_ranges/solution.ts)| Easy | Array | 0 | 100.00 | 0056 |[Merge Intervals](src/main/ts/g0001_0100/s0056_merge_intervals/solution.ts)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Big_O_Time_O(n_log_n)_Space_O(n) | 7 | 87.99 | 0057 |[Insert Interval](src/main/ts/g0001_0100/s0057_insert_interval/solution.ts)| Medium | Array | 0 | 100.00 +| 0452 |[Minimum Number of Arrows to Burst Balloons](src/main/ts/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/solution.ts)| Medium | Array, Sorting, Greedy | 75 | 98.54 #### Top Interview 150 Stack @@ -1161,6 +1163,7 @@ TypeScript-based LeetCode algorithm problem solutions, regularly updated. | | | | | | |-|-|-|-|-|- | 0199 |[Binary Tree Right Side View](src/main/ts/g0101_0200/s0199_binary_tree_right_side_view/solution.ts)| Medium | Top_100_Liked_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 0 | 100.00 +| 0637 |[Average of Levels in Binary Tree](src/main/ts/g0601_0700/s0637_average_of_levels_in_binary_tree/solution.ts)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 0 | 100.00 | 0102 |[Binary Tree Level Order Traversal](src/main/ts/g0101_0200/s0102_binary_tree_level_order_traversal/solution.ts)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree, Big_O_Time_O(N)_Space_O(N) | 0 | 100.00 | 0103 |[Binary Tree Zigzag Level Order Traversal](src/main/ts/g0101_0200/s0103_binary_tree_zigzag_level_order_traversal/solution.ts)| Medium | Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 0 | 100.00 @@ -1168,6 +1171,7 @@ TypeScript-based LeetCode algorithm problem solutions, regularly updated. | | | | | | |-|-|-|-|-|- +| 0530 |[Minimum Absolute Difference in BST](src/main/ts/g0501_0600/s0530_minimum_absolute_difference_in_bst/solution.ts)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 0 | 100.00 | 0230 |[Kth Smallest Element in a BST](src/main/ts/g0201_0300/s0230_kth_smallest_element_in_a_bst/solution.ts)| Medium | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree, Big_O_Time_O(n)_Space_O(n) | 0 | 100.00 | 0098 |[Validate Binary Search Tree](src/main/ts/g0001_0100/s0098_validate_binary_search_tree/solution.ts)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree, Big_O_Time_O(N)_Space_O(log(N)) | 0 | 100.00 @@ -1183,6 +1187,7 @@ TypeScript-based LeetCode algorithm problem solutions, regularly updated. | | | | | | |-|-|-|-|-|- +| 0909 |[Snakes and Ladders](src/main/ts/g0901_1000/s0909_snakes_and_ladders/solution.ts)| Medium | Array, Breadth_First_Search, Matrix | 5 | 98.27 | 0433 |[Minimum Genetic Mutation](src/main/ts/g0401_0500/s0433_minimum_genetic_mutation/solution.ts)| Medium | String, Hash_Table, Breadth_First_Search | 0 | 100.00 | 0127 |[Word Ladder](src/main/ts/g0101_0200/s0127_word_ladder/solution.ts)| Hard | Top_Interview_Questions, String, Hash_Table, Breadth_First_Search | 41 | 95.63 @@ -1220,6 +1225,7 @@ TypeScript-based LeetCode algorithm problem solutions, regularly updated. | | | | | | |-|-|-|-|-|- | 0053 |[Maximum Subarray](src/main/ts/g0001_0100/s0053_maximum_subarray/solution.ts)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer, Big_O_Time_O(n)_Space_O(1) | 0 | 100.00 +| 0918 |[Maximum Sum Circular Subarray](src/main/ts/g0901_1000/s0918_maximum_sum_circular_subarray/solution.ts)| Medium | Array, Dynamic_Programming, Divide_and_Conquer, Queue, Monotonic_Queue, Medium, Array, Dynamic_Programming, Divide_and_Conquer, Queue, Monotonic_Queue | 2 | 91.04 #### Top Interview 150 Binary Search @@ -1238,6 +1244,7 @@ TypeScript-based LeetCode algorithm problem solutions, regularly updated. | | | | | | |-|-|-|-|-|- | 0215 |[Kth Largest Element in an Array](src/main/ts/g0201_0300/s0215_kth_largest_element_in_an_array/solution.ts)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Quickselect, Big_O_Time_O(n\*log(n))_Space_O(log(n)) | 4 | 99.64 +| 0502 |[IPO](src/main/ts/g0501_0600/s0502_ipo/solution.ts)| Hard | Array, Sorting, Greedy, Heap_Priority_Queue | 193 | 89.19 | 0373 |[Find K Pairs with Smallest Sums](src/main/ts/g0301_0400/s0373_find_k_pairs_with_smallest_sums/solution.ts)| Medium | Array, Heap_Priority_Queue | 42 | 85.15 | 0295 |[Find Median from Data Stream](src/main/ts/g0201_0300/s0295_find_median_from_data_stream/solution.ts)| Hard | Top_100_Liked_Questions, Sorting, Two_Pointers, Design, Heap_Priority_Queue, Data_Stream, Big_O_Time_O(n\*log_n)_Space_O(n) | 106 | 92.31 @@ -1743,12 +1750,18 @@ TypeScript-based LeetCode algorithm problem solutions, regularly updated. | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|--------- | 1143 |[Longest Common Subsequence](src/main/ts/g1101_1200/s1143_longest_common_subsequence/solution.ts)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming, Algorithm_II_Day_17_Dynamic_Programming, Dynamic_Programming_I_Day_19, Udemy_Dynamic_Programming, Big_O_Time_O(n\*m)_Space_O(n\*m) | 50 | 69.40 +| 0918 |[Maximum Sum Circular Subarray](src/main/ts/g0901_1000/s0918_maximum_sum_circular_subarray/solution.ts)| Medium | Array, Dynamic_Programming, Divide_and_Conquer, Queue, Monotonic_Queue, Medium, Array, Dynamic_Programming, Divide_and_Conquer, Queue, Monotonic_Queue, Dynamic_Programming_I_Day_5, Top_Interview_150_Kadane's_Algorithm | 2 | 91.04 +| 0909 |[Snakes and Ladders](src/main/ts/g0901_1000/s0909_snakes_and_ladders/solution.ts)| Medium | Array, Breadth_First_Search, Matrix, Top_Interview_150_Graph_BFS | 5 | 98.27 | 0763 |[Partition Labels](src/main/ts/g0701_0800/s0763_partition_labels/solution.ts)| Medium | String, Hash_Table, Greedy, Two_Pointers, Data_Structure_II_Day_7_String, Big_O_Time_O(n)_Space_O(1) | 4 | 86.89 | 0739 |[Daily Temperatures](src/main/ts/g0701_0800/s0739_daily_temperatures/solution.ts)| Medium | Top_100_Liked_Questions, Array, Stack, Monotonic_Stack, Programming_Skills_II_Day_6, Big_O_Time_O(n)_Space_O(n) | 18 | 80.57 | 0647 |[Palindromic Substrings](src/main/ts/g0601_0700/s0647_palindromic_substrings/solution.ts)| Medium | String, Dynamic_Programming, Big_O_Time_O(n^2)_Space_O(n) | 5 | 100.00 +| 0637 |[Average of Levels in Binary Tree](src/main/ts/g0601_0700/s0637_average_of_levels_in_binary_tree/solution.ts)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Top_Interview_150_Binary_Tree_BFS | 0 | 100.00 | 0560 |[Subarray Sum Equals K](src/main/ts/g0501_0600/s0560_subarray_sum_equals_k/solution.ts)| Medium | Top_100_Liked_Questions, Array, Hash_Table, Prefix_Sum, Data_Structure_II_Day_5_Array, Big_O_Time_O(n)_Space_O(n) | 14 | 87.34 | 0543 |[Diameter of Binary Tree](src/main/ts/g0501_0600/s0543_diameter_of_binary_tree/solution.ts)| Easy | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree, Level_2_Day_7_Tree, Udemy_Tree_Stack_Queue, Big_O_Time_O(n)_Space_O(n) | 1 | 87.16 +| 0530 |[Minimum Absolute Difference in BST](src/main/ts/g0501_0600/s0530_minimum_absolute_difference_in_bst/solution.ts)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Binary_Search_Tree, Top_Interview_150_Binary_Search_Tree | 0 | 100.00 +| 0502 |[IPO](src/main/ts/g0501_0600/s0502_ipo/solution.ts)| Hard | Array, Sorting, Greedy, Heap_Priority_Queue, Top_Interview_150_Heap | 193 | 89.19 | 0494 |[Target Sum](src/main/ts/g0401_0500/s0494_target_sum/solution.ts)| Medium | Array, Dynamic_Programming, Backtracking, Big_O_Time_O(n\*(sum+s))_Space_O(n\*(sum+s)) | 24 | 83.43 +| 0452 |[Minimum Number of Arrows to Burst Balloons](src/main/ts/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/solution.ts)| Medium | Array, Sorting, Greedy, Top_Interview_150_Intervals | 75 | 98.54 | 0438 |[Find All Anagrams in a String](src/main/ts/g0401_0500/s0438_find_all_anagrams_in_a_string/solution.ts)| Medium | Top_100_Liked_Questions, String, Hash_Table, Sliding_Window, Algorithm_II_Day_5_Sliding_Window, Programming_Skills_II_Day_12, Level_1_Day_12_Sliding_Window/Two_Pointer, Big_O_Time_O(n+m)_Space_O(1) | 8 | 97.80 | 0437 |[Path Sum III](src/main/ts/g0401_0500/s0437_path_sum_iii/solution.ts)| Medium | Depth_First_Search, Tree, Binary_Tree, Level_2_Day_7_Tree, Big_O_Time_O(n)_Space_O(n) | 3 | 86.41 | 0433 |[Minimum Genetic Mutation](src/main/ts/g0401_0500/s0433_minimum_genetic_mutation/solution.ts)| Medium | String, Hash_Table, Breadth_First_Search, Graph_Theory_I_Day_12_Breadth_First_Search, Top_Interview_150_Graph_BFS | 0 | 100.00 diff --git a/src/main/ts/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/readme.md b/src/main/ts/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/readme.md new file mode 100644 index 0000000..acd3967 --- /dev/null +++ b/src/main/ts/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/readme.md @@ -0,0 +1,47 @@ +452\. Minimum Number of Arrows to Burst Balloons + +Medium + +There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where points[i] = [xstart, xend] denotes a balloon whose **horizontal diameter** stretches between xstart and xend. You do not know the exact y-coordinates of the balloons. + +Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is **burst** by an arrow shot at `x` if xstart <= x <= xend. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. + +Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_. + +**Example 1:** + +**Input:** points = [[10,16],[2,8],[1,6],[7,12]] + +**Output:** 2 + +**Explanation:** The balloons can be burst by 2 arrows: + +- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. + +- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. + +**Example 2:** + +**Input:** points = [[1,2],[3,4],[5,6],[7,8]] + +**Output:** 4 + +**Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows. + +**Example 3:** + +**Input:** points = [[1,2],[2,3],[3,4],[4,5]] + +**Output:** 2 + +**Explanation:** The balloons can be burst by 2 arrows: + +- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. + +- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]. + +**Constraints:** + +* 1 <= points.length <= 105 +* `points[i].length == 2` +* -231 <= xstart < xend <= 231 - 1 diff --git a/src/main/ts/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/solution.ts b/src/main/ts/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/solution.ts new file mode 100644 index 0000000..208ddb1 --- /dev/null +++ b/src/main/ts/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/solution.ts @@ -0,0 +1,20 @@ +// #Medium #Array #Sorting #Greedy #Top_Interview_150_Intervals +// #2025_04_15_Time_75_ms_(98.54%)_Space_79.44_MB_(62.20%) + +function findMinArrowShots(points: number[][]): number { + if (points.length === 0) { + return 0 + } + points.sort((a, b) => a[1] - b[1]) + let minArrows = 1 + let end = points[0][1] + for (let i = 1; i < points.length; i++) { + if (points[i][0] > end) { + minArrows++ + end = points[i][1] + } + } + return minArrows +} + +export { findMinArrowShots } diff --git a/src/main/ts/g0501_0600/s0502_ipo/readme.md b/src/main/ts/g0501_0600/s0502_ipo/readme.md new file mode 100644 index 0000000..8e36db7 --- /dev/null +++ b/src/main/ts/g0501_0600/s0502_ipo/readme.md @@ -0,0 +1,47 @@ +502\. IPO + +Hard + +Suppose LeetCode will start its **IPO** soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the **IPO**. Since it has limited resources, it can only finish at most `k` distinct projects before the **IPO**. Help LeetCode design the best way to maximize its total capital after finishing at most `k` distinct projects. + +You are given `n` projects where the ith project has a pure profit `profits[i]` and a minimum capital of `capital[i]` is needed to start it. + +Initially, you have `w` capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. + +Pick a list of **at most** `k` distinct projects from given projects to **maximize your final capital**, and return _the final maximized capital_. + +The answer is guaranteed to fit in a 32-bit signed integer. + +**Example 1:** + +**Input:** k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] + +**Output:** 4 + +**Explanation:** + +Since your initial capital is 0, you can only start the project indexed 0. + +After finishing it you will obtain profit 1 and your capital becomes 1. + +With capital 1, you can either start the project indexed 1 or the project indexed 2. + +Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. + +Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. + +**Example 2:** + +**Input:** k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] + +**Output:** 6 + +**Constraints:** + +* 1 <= k <= 105 +* 0 <= w <= 109 +* `n == profits.length` +* `n == capital.length` +* 1 <= n <= 105 +* 0 <= profits[i] <= 104 +* 0 <= capital[i] <= 109 diff --git a/src/main/ts/g0501_0600/s0502_ipo/solution.ts b/src/main/ts/g0501_0600/s0502_ipo/solution.ts new file mode 100644 index 0000000..72cb0af --- /dev/null +++ b/src/main/ts/g0501_0600/s0502_ipo/solution.ts @@ -0,0 +1,86 @@ +// #Hard #Array #Sorting #Greedy #Heap_Priority_Queue #Top_Interview_150_Heap +// #2025_04_15_Time_193_ms_(89.19%)_Space_102.47_MB_(8.11%) + +class MaxHeap { + private heap: number[]; + + constructor() { + this.heap = []; + } + + push(value: number) { + this.heap.push(value); + this.heapifyUp(); + } + + pop(): number | undefined { + if (this.heap.length === 0) { + return undefined; + } + if (this.heap.length === 1) { + return this.heap.pop(); + } + const max = this.heap[0]; + this.heap[0] = this.heap.pop()!; + this.heapifyDown(); + return max; + } + + isEmpty(): boolean { + return this.heap.length === 0; + } + + private heapifyUp() { + let index = this.heap.length - 1; + while (index > 0) { + let parentIndex = Math.floor((index - 1) / 2); + if (this.heap[parentIndex] >= this.heap[index]) { + break; + } + [this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]]; + index = parentIndex; + } + } + + private heapifyDown() { + let index = 0; + while (true) { + let left = 2 * index + 1; + let right = 2 * index + 2; + let largest = index; + if (left < this.heap.length && this.heap[left] > this.heap[largest]) { + largest = left; + } + if (right < this.heap.length && this.heap[right] > this.heap[largest]) { + largest = right; + } + if (largest === index) break; + [this.heap[index], this.heap[largest]] = [this.heap[largest], this.heap[index]]; + index = largest; + } + } +} + +function findMaximizedCapital(k: number, w: number, profits: number[], capital: number[]): number { + let projects: [number, number][] = []; + const n = profits.length; + for (let i = 0; i < n; i++) { + projects.push([capital[i], profits[i]]); + } + projects.sort((a, b) => a[0] - b[0]); + const maxHeap = new MaxHeap(); + let i = 0; + while (k--) { + while (i < n && projects[i][0] <= w) { + maxHeap.push(projects[i][1]); + i++; + } + if (maxHeap.isEmpty()) { + break; + } + w += maxHeap.pop()!; + } + return w; +} + +export { findMaximizedCapital } diff --git a/src/main/ts/g0501_0600/s0530_minimum_absolute_difference_in_bst/readme.md b/src/main/ts/g0501_0600/s0530_minimum_absolute_difference_in_bst/readme.md new file mode 100644 index 0000000..64fdaa4 --- /dev/null +++ b/src/main/ts/g0501_0600/s0530_minimum_absolute_difference_in_bst/readme.md @@ -0,0 +1,28 @@ +530\. Minimum Absolute Difference in BST + +Easy + +Given the `root` of a Binary Search Tree (BST), return _the minimum absolute difference between the values of any two different nodes in the tree_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/05/bst1.jpg) + +**Input:** root = [4,2,6,1,3] + +**Output:** 1 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/02/05/bst2.jpg) + +**Input:** root = [1,0,48,null,null,12,49] + +**Output:** 1 + +**Constraints:** + +* The number of nodes in the tree is in the range [2, 104]. +* 0 <= Node.val <= 105 + +**Note:** This question is the same as 783: [https://leetcode.com/problems/minimum-distance-between-bst-nodes/](https://leetcode.com/problems/minimum-distance-between-bst-nodes/) diff --git a/src/main/ts/g0501_0600/s0530_minimum_absolute_difference_in_bst/solution.ts b/src/main/ts/g0501_0600/s0530_minimum_absolute_difference_in_bst/solution.ts new file mode 100644 index 0000000..e833b6d --- /dev/null +++ b/src/main/ts/g0501_0600/s0530_minimum_absolute_difference_in_bst/solution.ts @@ -0,0 +1,37 @@ +// #Easy #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree #Binary_Search_Tree +// #Top_Interview_150_Binary_Search_Tree #2025_04_15_Time_0_ms_(100.00%)_Space_61.15_MB_(83.13%) + +import { TreeNode } from '../../com_github_leetcode/treenode' + +/** + * Definition for a binary tree node. + * 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 getMinimumDifference(root: TreeNode | null): number { + let ans = Number.MAX_SAFE_INTEGER + let prev: number | null = null + function dfs(node: TreeNode | null) { + if (!node) { + return + } + dfs(node.left) + if (prev !== null) { + ans = Math.min(ans, Math.abs(node.val - prev)) + } + prev = node.val + dfs(node.right) + } + dfs(root) + return ans +} + +export { getMinimumDifference } diff --git a/src/main/ts/g0601_0700/s0637_average_of_levels_in_binary_tree/readme.md b/src/main/ts/g0601_0700/s0637_average_of_levels_in_binary_tree/readme.md new file mode 100644 index 0000000..5dac74e --- /dev/null +++ b/src/main/ts/g0601_0700/s0637_average_of_levels_in_binary_tree/readme.md @@ -0,0 +1,26 @@ +637\. Average of Levels in Binary Tree + +Easy + +Given the `root` of a binary tree, return _the average value of the nodes on each level in the form of an array_. Answers within 10-5 of the actual answer will be accepted. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/09/avg1-tree.jpg) + +**Input:** root = [3,9,20,null,null,15,7] + +**Output:** [3.00000,14.50000,11.00000] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/03/09/avg2-tree.jpg) + +**Input:** root = [3,9,20,15,7] + +**Output:** [3.00000,14.50000,11.00000] + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 104]. +* -231 <= Node.val <= 231 - 1 diff --git a/src/main/ts/g0601_0700/s0637_average_of_levels_in_binary_tree/solution.ts b/src/main/ts/g0601_0700/s0637_average_of_levels_in_binary_tree/solution.ts new file mode 100644 index 0000000..3bcaa8e --- /dev/null +++ b/src/main/ts/g0601_0700/s0637_average_of_levels_in_binary_tree/solution.ts @@ -0,0 +1,44 @@ +// #Easy #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree +// #Top_Interview_150_Binary_Tree_BFS #2025_04_15_Time_0_ms_(100.00%)_Space_61.24_MB_(69.52%) + +import { TreeNode } from '../../com_github_leetcode/treenode' + +/** + * Definition for a binary tree node. + * 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 averageOfLevels(root: TreeNode | null): number[] { + if (!root) { + return [] + } + let res = [] + let queue = [root] + while (queue.length) { + let len = queue.length + let sum = 0 + for (let i = 0; i < len; i++) { + let node = queue.shift() + sum += node.val + if (node.left) { + queue.push(node.left) + } + if (node.right) { + queue.push(node.right) + } + } + res.push(sum / len) + } + return res +} + +export { averageOfLevels } diff --git a/src/main/ts/g0901_1000/s0909_snakes_and_ladders/readme.md b/src/main/ts/g0901_1000/s0909_snakes_and_ladders/readme.md new file mode 100644 index 0000000..50734a0 --- /dev/null +++ b/src/main/ts/g0901_1000/s0909_snakes_and_ladders/readme.md @@ -0,0 +1,55 @@ +909\. Snakes and Ladders + +Medium + +You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to n2 in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row. + +You start on square `1` of the board. In each move, starting from square `curr`, do the following: + +* Choose a destination square `next` with a label in the range [curr + 1, min(curr + 6, n2)]. + * This choice simulates the result of a standard **6-sided die roll**: i.e., there are always at most 6 destinations, regardless of the size of the board. +* If `next` has a snake or ladder, you **must** move to the destination of that snake or ladder. Otherwise, you move to `next`. +* The game ends when you reach the square n2. + +A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and n2 do not have a snake or ladder. + +Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do **not** follow the subsequent snake or ladder. + +* For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do **not** follow the subsequent ladder to `4`. + +Return _the least number of moves required to reach the square_ n2_. If it is not possible to reach the square, return_ `-1`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2018/09/23/snakes.png) + +**Input:** board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]] + +**Output:** 4 + +**Explanation:** + +In the beginning, you start at square 1 (at row 5, column 0). + +You decide to move to square 2 and must take the ladder to square 15. + +You then decide to move to square 17 and must take the snake to square 13. + +You then decide to move to square 14 and must take the ladder to square 35. + +You then decide to move to square 36, ending the game. + +This is the lowest possible number of moves to reach the last square, so return 4. + +**Example 2:** + +**Input:** board = [[-1,-1],[-1,3]] + +**Output:** 1 + +**Constraints:** + +* `n == board.length == board[i].length` +* `2 <= n <= 20` +* `grid[i][j]` is either `-1` or in the range [1, n2]. +* The squares labeled `1` and n2 do not have any ladders or snakes. diff --git a/src/main/ts/g0901_1000/s0909_snakes_and_ladders/solution.ts b/src/main/ts/g0901_1000/s0909_snakes_and_ladders/solution.ts new file mode 100644 index 0000000..c711d28 --- /dev/null +++ b/src/main/ts/g0901_1000/s0909_snakes_and_ladders/solution.ts @@ -0,0 +1,44 @@ +// #Medium #Array #Breadth_First_Search #Matrix #Top_Interview_150_Graph_BFS +// #2025_04_15_Time_5_ms_(98.27%)_Space_59.74_MB_(65.90%) + +function snakesAndLadders(board: number[][]): number { + const size = board.length + const target = size * size + const visited: boolean[] = new Array(target).fill(false) + const queue: number[] = [] + queue.push(1) + visited[0] = true + let steps = 0 + while (queue.length > 0) { + const levelSize = queue.length + for (let i = 0; i < levelSize; i++) { + const current = queue.shift()! + if (current === target) { + return steps + } + for (let next = current + 1; next <= Math.min(current + 6, target); next++) { + if (visited[next - 1]) continue + visited[next - 1] = true + const [row, col] = indexToPosition(next, size) + const destination = board[row][col] === -1 ? next : board[row][col] + queue.push(destination) + } + } + steps++ + } + + return -1 +} + +function indexToPosition(index: number, size: number): [number, number] { + const row = size - 1 - Math.floor((index - 1) / size) + let col: number + if ((size - row) % 2 === 1) { + col = (index - 1) % size + } else { + col = size - 1 - ((index - 1) % size) + } + return [row, col] +} + +export { snakesAndLadders } diff --git a/src/main/ts/g0901_1000/s0918_maximum_sum_circular_subarray/readme.md b/src/main/ts/g0901_1000/s0918_maximum_sum_circular_subarray/readme.md new file mode 100644 index 0000000..60c43ad --- /dev/null +++ b/src/main/ts/g0901_1000/s0918_maximum_sum_circular_subarray/readme.md @@ -0,0 +1,39 @@ +918\. Maximum Sum Circular Subarray + +Medium + +Given a **circular integer array** `nums` of length `n`, return _the maximum possible sum of a non-empty **subarray** of_ `nums`. + +A **circular array** means the end of the array connects to the beginning of the array. Formally, the next element of `nums[i]` is `nums[(i + 1) % n]` and the previous element of `nums[i]` is `nums[(i - 1 + n) % n]`. + +A **subarray** may only include each element of the fixed buffer `nums` at most once. Formally, for a subarray `nums[i], nums[i + 1], ..., nums[j]`, there does not exist `i <= k1`, `k2 <= j` with `k1 % n == k2 % n`. + +**Example 1:** + +**Input:** nums = [1,-2,3,-2] + +**Output:** 3 + +**Explanation:** Subarray [3] has maximum sum 3. + +**Example 2:** + +**Input:** nums = [5,-3,5] + +**Output:** 10 + +**Explanation:** Subarray [5,5] has maximum sum 5 + 5 = 10. + +**Example 3:** + +**Input:** nums = [-3,-2,-3] + +**Output:** -2 + +**Explanation:** Subarray [-2] has maximum sum -2. + +**Constraints:** + +* `n == nums.length` +* 1 <= n <= 3 * 104 +* -3 * 104 <= nums[i] <= 3 * 104 diff --git a/src/main/ts/g0901_1000/s0918_maximum_sum_circular_subarray/solution.ts b/src/main/ts/g0901_1000/s0918_maximum_sum_circular_subarray/solution.ts new file mode 100644 index 0000000..8c446f8 --- /dev/null +++ b/src/main/ts/g0901_1000/s0918_maximum_sum_circular_subarray/solution.ts @@ -0,0 +1,25 @@ +// #Medium #Array #Dynamic_Programming #Divide_and_Conquer #Queue #Monotonic_Queue +// #Medium #Array #Dynamic_Programming #Divide_and_Conquer #Queue #Monotonic_Queue +// #Dynamic_Programming_I_Day_5 #Top_Interview_150_Kadane's_Algorithm +// #2025_04_15_Time_2_ms_(91.04%)_Space_61.54_MB_(85.07%) + +function maxSubarraySumCircular(nums: number[]): number { + let total = 0 + let maxSum = nums[0], + curMax = 0 + let minSum = nums[0], + curMin = 0 + for (let num of nums) { + curMax = Math.max(num, curMax + num) + maxSum = Math.max(maxSum, curMax) + curMin = Math.min(num, curMin + num) + minSum = Math.min(minSum, curMin) + total += num + } + if (maxSum < 0) { + return maxSum + } + return Math.max(maxSum, total - minSum) +} + +export { maxSubarraySumCircular } diff --git a/src/test/ts/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/solution.test.ts b/src/test/ts/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/solution.test.ts new file mode 100644 index 0000000..c9e97e6 --- /dev/null +++ b/src/test/ts/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/solution.test.ts @@ -0,0 +1,36 @@ +// tslint:disable:no-magic-numbers +import { findMinArrowShots } from 'src/main/ts/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/solution' +import { expect, test } from 'vitest' + +test('findMinArrowShots', () => { + expect( + findMinArrowShots([ + [10, 16], + [2, 8], + [1, 6], + [7, 12], + ]), + ).toEqual(2) +}) + +test('findMinArrowShots2', () => { + expect( + findMinArrowShots([ + [1, 2], + [3, 4], + [5, 6], + [7, 8], + ]), + ).toEqual(4) +}) + +test('findMinArrowShots3', () => { + expect( + findMinArrowShots([ + [1, 2], + [2, 3], + [3, 4], + [4, 5], + ]), + ).toEqual(2) +}) diff --git a/src/test/ts/g0501_0600/s0502_ipo/solution.test.ts b/src/test/ts/g0501_0600/s0502_ipo/solution.test.ts new file mode 100644 index 0000000..6423e12 --- /dev/null +++ b/src/test/ts/g0501_0600/s0502_ipo/solution.test.ts @@ -0,0 +1,11 @@ +// tslint:disable:no-magic-numbers +import { findMaximizedCapital } from 'src/main/ts/g0501_0600/s0502_ipo/solution' +import { expect, test } from 'vitest' + +test('findMaximizedCapital', () => { + expect(findMaximizedCapital(2, 0, [1, 2, 3], [0, 1, 1])).toEqual(4) +}) + +test('findMaximizedCapital2', () => { + expect(findMaximizedCapital(3, 0, [1, 2, 3], [0, 1, 2])).toEqual(6) +}) diff --git a/src/test/ts/g0501_0600/s0530_minimum_absolute_difference_in_bst/solution.test.ts b/src/test/ts/g0501_0600/s0530_minimum_absolute_difference_in_bst/solution.test.ts new file mode 100644 index 0000000..04a0a20 --- /dev/null +++ b/src/test/ts/g0501_0600/s0530_minimum_absolute_difference_in_bst/solution.test.ts @@ -0,0 +1,12 @@ +// tslint:disable:no-magic-numbers +import { createTreeNode } from 'src/main/ts/com_github_leetcode/treenode' +import { getMinimumDifference } from 'src/main/ts/g0501_0600/s0530_minimum_absolute_difference_in_bst/solution' +import { expect, test } from 'vitest' + +test('getMinimumDifference', () => { + expect(getMinimumDifference(createTreeNode([4, 2, 6, 1, 3]))).toEqual(1) +}) + +test('getMinimumDifference2', () => { + expect(getMinimumDifference(createTreeNode([1, 0, 48, null, null, 12, 49]))).toEqual(1) +}) diff --git a/src/test/ts/g0601_0700/s0637_average_of_levels_in_binary_tree/solution.test.ts b/src/test/ts/g0601_0700/s0637_average_of_levels_in_binary_tree/solution.test.ts new file mode 100644 index 0000000..3babc73 --- /dev/null +++ b/src/test/ts/g0601_0700/s0637_average_of_levels_in_binary_tree/solution.test.ts @@ -0,0 +1,12 @@ +// tslint:disable:no-magic-numbers +import { createTreeNode } from 'src/main/ts/com_github_leetcode/treenode' +import { averageOfLevels } from 'src/main/ts/g0601_0700/s0637_average_of_levels_in_binary_tree/solution' +import { expect, test } from 'vitest' + +test('averageOfLevels', () => { + expect(averageOfLevels(createTreeNode([3, 9, 20, null, null, 15, 7]))).toEqual([3.0, 14.5, 11.0]) +}) + +test('averageOfLevels2', () => { + expect(averageOfLevels(createTreeNode([3, 9, 20, 15, 7]))).toEqual([3.0, 14.5, 11.0]) +}) diff --git a/src/test/ts/g0901_1000/s0909_snakes_and_ladders/solution.test.ts b/src/test/ts/g0901_1000/s0909_snakes_and_ladders/solution.test.ts new file mode 100644 index 0000000..baf9e6d --- /dev/null +++ b/src/test/ts/g0901_1000/s0909_snakes_and_ladders/solution.test.ts @@ -0,0 +1,25 @@ +// tslint:disable:no-magic-numbers +import { snakesAndLadders } from 'src/main/ts/g0901_1000/s0909_snakes_and_ladders/solution' +import { expect, test } from 'vitest' + +test('snakesAndLadders', () => { + expect( + snakesAndLadders([ + [-1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1], + [-1, 35, -1, -1, 13, -1], + [-1, -1, -1, -1, -1, -1], + [-1, 15, -1, -1, -1, -1], + ]), + ).toEqual(4) +}) + +test('snakesAndLadders2', () => { + expect( + snakesAndLadders([ + [-1, -1], + [-1, 3], + ]), + ).toEqual(1) +}) diff --git a/src/test/ts/g0901_1000/s0918_maximum_sum_circular_subarray/solution.test.ts b/src/test/ts/g0901_1000/s0918_maximum_sum_circular_subarray/solution.test.ts new file mode 100644 index 0000000..90b10c6 --- /dev/null +++ b/src/test/ts/g0901_1000/s0918_maximum_sum_circular_subarray/solution.test.ts @@ -0,0 +1,15 @@ +// tslint:disable:no-magic-numbers +import { maxSubarraySumCircular } from 'src/main/ts/g0901_1000/s0918_maximum_sum_circular_subarray/solution' +import { expect, test } from 'vitest' + +test('maxSubarraySumCircular', () => { + expect(maxSubarraySumCircular([1, -2, 3, -2])).toEqual(3) +}) + +test('maxSubarraySumCircular2', () => { + expect(maxSubarraySumCircular([5, -3, 5])).toEqual(10) +}) + +test('maxSubarraySumCircular2', () => { + expect(maxSubarraySumCircular([-3, -2, -3])).toEqual(-2) +})