Skip to content

Commit b986020

Browse files
authored
Added tasks 105-141
1 parent 87d7c03 commit b986020

File tree

10 files changed

+754
-0
lines changed

10 files changed

+754
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
105\. Construct Binary Tree from Preorder and Inorder Traversal
2+
3+
Medium
4+
5+
Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_.
6+
7+
**Example 1:**
8+
9+
![](https://assets.leetcode.com/uploads/2021/02/19/tree.jpg)
10+
11+
**Input:** preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
12+
13+
**Output:** [3,9,20,null,null,15,7]
14+
15+
**Example 2:**
16+
17+
**Input:** preorder = [-1], inorder = [-1]
18+
19+
**Output:** [-1]
20+
21+
**Constraints:**
22+
23+
* `1 <= preorder.length <= 3000`
24+
* `inorder.length == preorder.length`
25+
* `-3000 <= preorder[i], inorder[i] <= 3000`
26+
* `preorder` and `inorder` consist of **unique** values.
27+
* Each value of `inorder` also appears in `preorder`.
28+
* `preorder` is **guaranteed** to be the preorder traversal of the tree.
29+
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
30+
31+
To solve this task, we can use a recursive approach to construct the binary tree. We'll define a `Solution` class with a method `buildTree` to perform this task. Here are the steps:
32+
33+
1. Define the `Solution` class.
34+
2. Define the `buildTree` method which takes `preorder` and `inorder` lists as input.
35+
3. Create a helper function, let's call it `buildTreeHelper`, that takes the indices representing the current subtree in preorder and inorder lists.
36+
4. In the `buildTreeHelper` function, if the `preorder` list is empty or the `inorder` list is empty, return `None`, indicating an empty subtree.
37+
5. Otherwise, the first element of the `preorder` list would be the root of the current subtree. Create a node for this root.
38+
6. Find the index of the root value in the `inorder` list. This index will partition the `inorder` list into left and right subtrees.
39+
7. Recursively call `buildTreeHelper` for the left subtree with appropriate indices.
40+
8. Recursively call `buildTreeHelper` for the right subtree with appropriate indices.
41+
9. Return the root node.
42+
10. Call `buildTreeHelper` from the `buildTree` method with initial indices for the entire preorder and inorder lists.
43+
11. Return the root node obtained from `buildTreeHelper`.
44+
45+
Here's the Python code implementing these steps:
46+
47+
```python
48+
class TreeNode:
49+
def __init__(self, val=0, left=None, right=None):
50+
self.val = val
51+
self.left = left
52+
self.right = right
53+
54+
class Solution:
55+
def buildTree(self, preorder, inorder):
56+
if not preorder or not inorder:
57+
return None
58+
59+
def buildTreeHelper(pre_start, pre_end, in_start, in_end):
60+
if pre_start > pre_end or in_start > in_end:
61+
return None
62+
63+
root_val = preorder[pre_start]
64+
root = TreeNode(root_val)
65+
66+
# Find index of root value in inorder list
67+
root_index = inorder.index(root_val)
68+
69+
# Calculate the number of nodes in the left subtree
70+
left_subtree_size = root_index - in_start
71+
72+
# Recursively build left subtree
73+
root.left = buildTreeHelper(pre_start + 1, pre_start + left_subtree_size, in_start, root_index - 1)
74+
75+
# Recursively build right subtree
76+
root.right = buildTreeHelper(pre_start + left_subtree_size + 1, pre_end, root_index + 1, in_end)
77+
78+
return root
79+
80+
return buildTreeHelper(0, len(preorder) - 1, 0, len(inorder) - 1)
81+
```
82+
83+
You can then use this `Solution` class to construct the binary tree from preorder and inorder traversal arrays.
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
114\. Flatten Binary Tree to Linked List
2+
3+
Medium
4+
5+
Given the `root` of a binary tree, flatten the tree into a "linked list":
6+
7+
* The "linked list" should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`.
8+
* The "linked list" should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg)
13+
14+
**Input:** root = [1,2,5,3,4,null,6]
15+
16+
**Output:** [1,null,2,null,3,null,4,null,5,null,6]
17+
18+
**Example 2:**
19+
20+
**Input:** root = []
21+
22+
**Output:** []
23+
24+
**Example 3:**
25+
26+
**Input:** root = [0]
27+
28+
**Output:** [0]
29+
30+
**Constraints:**
31+
32+
* The number of nodes in the tree is in the range `[0, 2000]`.
33+
* `-100 <= Node.val <= 100`
34+
35+
**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
36+
37+
To solve this task, we can use a recursive approach to flatten the binary tree. We'll define a `Solution` class with a method `flatten` to perform this task. Here are the steps:
38+
39+
1. Define the `Solution` class.
40+
2. Define the `flatten` method which takes `root` as input.
41+
3. Create a helper function, let's call it `flattenHelper`, that takes a node as input.
42+
4. In the `flattenHelper` function, if the current node is `None`, return `None`.
43+
5. Otherwise, recursively flatten the left subtree and right subtree.
44+
6. Once both subtrees are flattened, set the `right` child of the root to the flattened left subtree.
45+
7. Traverse to the end of the flattened left subtree and attach the flattened right subtree to its `right`.
46+
8. Set the `left` child of the root to `None`.
47+
9. Return the last node of the flattened tree (either the last node of the flattened right subtree or the last node of the flattened left subtree if the right subtree is `None`).
48+
10. Call `flattenHelper` from the `flatten` method with the root node.
49+
11. Return the root node.
50+
51+
Here's the Python code implementing these steps:
52+
53+
```python
54+
class TreeNode:
55+
def __init__(self, val=0, left=None, right=None):
56+
self.val = val
57+
self.left = left
58+
self.right = right
59+
60+
class Solution:
61+
def flatten(self, root):
62+
def flattenHelper(node):
63+
if not node:
64+
return None
65+
66+
left_last = flattenHelper(node.left)
67+
right_last = flattenHelper(node.right)
68+
69+
if left_last:
70+
left_last.right = node.right
71+
node.right = node.left
72+
node.left = None
73+
74+
return right_last if right_last else left_last if left_last else node
75+
76+
flattenHelper(root)
77+
return root
78+
```
79+
80+
You can then use this `Solution` class to flatten the binary tree into a linked list in pre-order traversal order.
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
121\. Best Time to Buy and Sell Stock
2+
3+
Easy
4+
5+
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
6+
7+
You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock.
8+
9+
Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`.
10+
11+
**Example 1:**
12+
13+
**Input:** prices = [7,1,5,3,6,4]
14+
15+
**Output:** 5
16+
17+
**Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
18+
19+
**Example 2:**
20+
21+
**Input:** prices = [7,6,4,3,1]
22+
23+
**Output:** 0
24+
25+
**Explanation:** In this case, no transactions are done and the max profit = 0.
26+
27+
**Constraints:**
28+
29+
* <code>1 <= prices.length <= 10<sup>5</sup></code>
30+
* <code>0 <= prices[i] <= 10<sup>4</sup></code>
31+
32+
To solve this task, we can use a greedy approach. We'll iterate through the prices array and keep track of the minimum price seen so far and the maximum profit we can achieve. Here are the steps:
33+
34+
1. Define the `Solution` class.
35+
2. Define the `maxProfit` method which takes `prices` as input.
36+
3. Initialize variables `min_price` to store the minimum price seen so far and `max_profit` to store the maximum profit.
37+
4. Iterate through the `prices` array.
38+
5. Update `min_price` to the minimum of the current price and `min_price`.
39+
6. Update `max_profit` to the maximum of the difference between the current price and `min_price`, and `max_profit`.
40+
7. After iterating through the array, return `max_profit`.
41+
42+
Here's the Python code implementing these steps:
43+
44+
```python
45+
class Solution:
46+
def maxProfit(self, prices):
47+
if not prices or len(prices) == 1:
48+
return 0
49+
50+
min_price = prices[0]
51+
max_profit = 0
52+
53+
for price in prices[1:]:
54+
min_price = min(min_price, price)
55+
max_profit = max(max_profit, price - min_price)
56+
57+
return max_profit
58+
```
59+
60+
You can then use this `Solution` class to find the maximum profit you can achieve by buying and selling stocks.
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
124\. Binary Tree Maximum Path Sum
2+
3+
Hard
4+
5+
A **path** in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence **at most once**. Note that the path does not need to pass through the root.
6+
7+
The **path sum** of a path is the sum of the node's values in the path.
8+
9+
Given the `root` of a binary tree, return _the maximum **path sum** of any **non-empty** path_.
10+
11+
**Example 1:**
12+
13+
![](https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg)
14+
15+
**Input:** root = [1,2,3]
16+
17+
**Output:** 6
18+
19+
**Explanation:** The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
20+
21+
**Example 2:**
22+
23+
![](https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg)
24+
25+
**Input:** root = [-10,9,20,null,null,15,7]
26+
27+
**Output:** 42
28+
29+
**Explanation:** The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
30+
31+
**Constraints:**
32+
33+
* The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.
34+
* `-1000 <= Node.val <= 1000`
35+
36+
To solve this task, we can use a recursive approach to traverse the binary tree and calculate the maximum path sum. We'll define a `Solution` class with a method `maxPathSum` to perform this task. Here are the steps:
37+
38+
1. Define the `Solution` class.
39+
2. Define the `maxPathSum` method which takes `root` as input.
40+
3. Create a helper function, let's call it `maxPathSumHelper`, that takes a node as input.
41+
4. In the `maxPathSumHelper` function, if the current node is `None`, return `0`.
42+
5. Recursively calculate the maximum path sum for the left and right subtrees using `maxPathSumHelper`.
43+
6. Calculate the maximum path sum passing through the current node, considering the possibility of including both left and right subtrees.
44+
7. Update a global variable `max_sum` to keep track of the maximum path sum encountered so far.
45+
8. Return the maximum path sum that includes either the current node or just one of its subtrees (if the sum with both subtrees is negative).
46+
9. Call `maxPathSumHelper` from the `maxPathSum` method with the root node.
47+
10. Return the global variable `max_sum`.
48+
49+
Here's the Python code implementing these steps:
50+
51+
```python
52+
class TreeNode:
53+
def __init__(self, val=0, left=None, right=None):
54+
self.val = val
55+
self.left = left
56+
self.right = right
57+
58+
class Solution:
59+
def maxPathSum(self, root):
60+
def maxPathSumHelper(node):
61+
if not node:
62+
return 0
63+
64+
left_sum = max(maxPathSumHelper(node.left), 0)
65+
right_sum = max(maxPathSumHelper(node.right), 0)
66+
67+
current_max = node.val + left_sum + right_sum
68+
69+
global max_sum
70+
max_sum = max(max_sum, current_max)
71+
72+
return node.val + max(left_sum, right_sum)
73+
74+
max_sum = float('-inf')
75+
maxPathSumHelper(root)
76+
return max_sum
77+
```
78+
79+
You can then use this `Solution` class to find the maximum path sum of any non-empty path in the binary tree.
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
128\. Longest Consecutive Sequence
2+
3+
Medium
4+
5+
Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
6+
7+
You must write an algorithm that runs in `O(n)` time.
8+
9+
**Example 1:**
10+
11+
**Input:** nums = [100,4,200,1,3,2]
12+
13+
**Output:** 4
14+
15+
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4.
16+
17+
**Example 2:**
18+
19+
**Input:** nums = [0,3,7,2,5,8,4,6,0,1]
20+
21+
**Output:** 9
22+
23+
**Constraints:**
24+
25+
* <code>0 <= nums.length <= 10<sup>5</sup></code>
26+
* <code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code>
27+
28+
To solve this task efficiently in O(n) time, we can use a HashSet to store all the elements of the array. Then, we can iterate through the array and for each element, check if the previous consecutive element (element - 1) exists in the set. If it does not exist, it means that the current element is the start of a new consecutive sequence. We can then keep track of the length of the consecutive sequence starting from the current element by continuously incrementing the current element until it no longer exists in the set. At each step, we update the maximum length of consecutive elements encountered so far. Here are the steps:
29+
30+
1. Define the `Solution` class.
31+
2. Define the `longestConsecutive` method which takes `nums` as input.
32+
3. Create a set `num_set` to store all elements of the array.
33+
4. Initialize a variable `max_length` to store the maximum length of consecutive sequence encountered so far.
34+
5. Iterate through the elements of the array.
35+
6. For each element `num`, check if `num - 1` exists in `num_set`. If it does not exist, it means that `num` is the start of a new consecutive sequence.
36+
7. Increment `current_length` by 1 and continuously increment `num` until it no longer exists in `num_set`.
37+
8. Update `max_length` with the maximum of `max_length` and `current_length`.
38+
9. After iterating through all elements, return `max_length`.
39+
40+
Here's the Python code implementing these steps:
41+
42+
```python
43+
class Solution:
44+
def longestConsecutive(self, nums):
45+
num_set = set(nums)
46+
max_length = 0
47+
48+
for num in nums:
49+
if num - 1 not in num_set:
50+
current_num = num
51+
current_length = 1
52+
53+
while current_num + 1 in num_set:
54+
current_num += 1
55+
current_length += 1
56+
57+
max_length = max(max_length, current_length)
58+
59+
return max_length
60+
```
61+
62+
You can then use this `Solution` class to find the length of the longest consecutive elements sequence in the given unsorted array.

0 commit comments

Comments
 (0)