Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 9b40015

Browse files
committedMay 27, 2024·
Added cpp tasks 96-155
1 parent 57f259f commit 9b40015

File tree

21 files changed

+1882
-0
lines changed

21 files changed

+1882
-0
lines changed
 
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 96\. Unique Binary Search Trees
5+
6+
Medium
7+
8+
Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg)
13+
14+
**Input:** n = 3
15+
16+
**Output:** 5
17+
18+
**Example 2:**
19+
20+
**Input:** n = 1
21+
22+
**Output:** 1
23+
24+
**Constraints:**
25+
26+
* `1 <= n <= 19`
27+
28+
To solve the "Unique Binary Search Trees" problem in Java with the Solution class, follow these steps:
29+
30+
1. Define a method `numTrees` in the `Solution` class that takes an integer `n` as input and returns the number of structurally unique BSTs (binary search trees) with exactly `n` nodes.
31+
2. Implement a dynamic programming approach to solve the problem:
32+
- Create an array `dp` of size `n + 1` to store the number of unique BSTs for each number of nodes from 0 to `n`.
33+
- Initialize `dp[0] = 1` and `dp[1] = 1`, as there is only one unique BST for 0 and 1 node(s).
34+
- Use a nested loop to calculate `dp[i]` for each `i` from 2 to `n`.
35+
- For each `i`, calculate `dp[i]` by summing up the products of `dp[j]` and `dp[i - j - 1]` for all possible values of `j` from 0 to `i - 1`.
36+
- Return `dp[n]`, which represents the number of unique BSTs with `n` nodes.
37+
38+
Here's the implementation of the `numTrees` method in Java:
39+
40+
```java
41+
class Solution {
42+
public int numTrees(int n) {
43+
int[] dp = new int[n + 1];
44+
dp[0] = 1;
45+
dp[1] = 1;
46+
for (int i = 2; i <= n; i++) {
47+
for (int j = 0; j < i; j++) {
48+
dp[i] += dp[j] * dp[i - j - 1];
49+
}
50+
}
51+
return dp[n];
52+
}
53+
}
54+
```
55+
56+
This implementation uses dynamic programming to compute the number of structurally unique BSTs with `n` nodes in O(n^2) time complexity.
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 98\. Validate Binary Search Tree
5+
6+
Medium
7+
8+
Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_.
9+
10+
A **valid BST** is defined as follows:
11+
12+
* The left subtree of a node contains only nodes with keys **less than** the node's key.
13+
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
14+
* Both the left and right subtrees must also be binary search trees.
15+
16+
**Example 1:**
17+
18+
![](https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg)
19+
20+
**Input:** root = [2,1,3]
21+
22+
**Output:** true
23+
24+
**Example 2:**
25+
26+
![](https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg)
27+
28+
**Input:** root = [5,1,4,null,null,3,6]
29+
30+
**Output:** false
31+
32+
**Explanation:** The root node's value is 5 but its right child's value is 4.
33+
34+
**Constraints:**
35+
36+
* The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.
37+
* <code>-2<sup>31</sup> <= Node.val <= 2<sup>31</sup> - 1</code>
38+
39+
To solve the "Validate Binary Search Tree" problem in Java with the Solution class, follow these steps:
40+
41+
1. Define a method `isValidBST` in the `Solution` class that takes the root of a binary tree as input and returns true if the tree is a valid binary search tree (BST), and false otherwise.
42+
2. Implement a recursive approach to validate if the given binary tree is a valid BST:
43+
- Define a helper method `isValidBSTHelper` that takes the root node, a lower bound, and an upper bound as input parameters.
44+
- In the `isValidBSTHelper` method, recursively traverse the binary tree nodes.
45+
- At each node, check if its value is within the specified bounds (lower bound and upper bound) for a valid BST.
46+
- If the node's value violates the BST property, return false.
47+
- Otherwise, recursively validate the left and right subtrees by updating the bounds accordingly.
48+
- If both the left and right subtrees are valid BSTs, return true.
49+
3. Call the `isValidBSTHelper` method with the root node and appropriate initial bounds to start the validation process.
50+
51+
Here's the implementation of the `isValidBST` method in Java:
52+
53+
```java
54+
class Solution {
55+
public boolean isValidBST(TreeNode root) {
56+
return isValidBSTHelper(root, null, null);
57+
}
58+
59+
private boolean isValidBSTHelper(TreeNode node, Integer lower, Integer upper) {
60+
if (node == null) {
61+
return true;
62+
}
63+
64+
int val = node.val;
65+
if ((lower != null && val <= lower) || (upper != null && val >= upper)) {
66+
return false;
67+
}
68+
69+
return isValidBSTHelper(node.left, lower, val) && isValidBSTHelper(node.right, val, upper);
70+
}
71+
}
72+
```
73+
74+
This implementation recursively validates whether the given binary tree is a valid BST in O(n) time complexity, where n is the number of nodes in the tree.
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 101\. Symmetric Tree
5+
6+
Easy
7+
8+
Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center).
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg)
13+
14+
**Input:** root = [1,2,2,3,4,4,3]
15+
16+
**Output:** true
17+
18+
**Example 2:**
19+
20+
![](https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg)
21+
22+
**Input:** root = [1,2,2,null,3,null,3]
23+
24+
**Output:** false
25+
26+
**Constraints:**
27+
28+
* The number of nodes in the tree is in the range `[1, 1000]`.
29+
* `-100 <= Node.val <= 100`
30+
31+
**Follow up:** Could you solve it both recursively and iteratively?
32+
33+
To solve the "Symmetric Tree" problem in Java with the Solution class, follow these steps:
34+
35+
1. Define a method `isSymmetric` in the `Solution` class that takes the root of a binary tree as input and returns true if the tree is symmetric, and false otherwise.
36+
2. Implement a recursive approach to check if the given binary tree is symmetric:
37+
- Define a helper method `isMirror` that takes two tree nodes as input parameters.
38+
- In the `isMirror` method, recursively compare the left and right subtrees of the given nodes.
39+
- At each step, check if the values of the corresponding nodes are equal and if the left subtree of one node is a mirror image of the right subtree of the other node.
40+
- If both conditions are satisfied for all corresponding nodes, return true; otherwise, return false.
41+
3. Call the `isMirror` method with the root's left and right children to check if the entire tree is symmetric.
42+
43+
Here's the implementation of the `isSymmetric` method in Java:
44+
45+
```java
46+
class Solution {
47+
public boolean isSymmetric(TreeNode root) {
48+
if (root == null) {
49+
return true;
50+
}
51+
return isMirror(root.left, root.right);
52+
}
53+
54+
private boolean isMirror(TreeNode left, TreeNode right) {
55+
if (left == null && right == null) {
56+
return true;
57+
}
58+
if (left == null || right == null) {
59+
return false;
60+
}
61+
return (left.val == right.val) && isMirror(left.left, right.right) && isMirror(left.right, right.left);
62+
}
63+
}
64+
```
65+
66+
This implementation recursively checks whether the given binary tree is symmetric around its center in O(n) time complexity, where n is the number of nodes in the tree.
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 102\. Binary Tree Level Order Traversal
5+
6+
Medium
7+
8+
Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level).
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg)
13+
14+
**Input:** root = [3,9,20,null,null,15,7]
15+
16+
**Output:** [[3],[9,20],[15,7]]
17+
18+
**Example 2:**
19+
20+
**Input:** root = [1]
21+
22+
**Output:** [[1]]
23+
24+
**Example 3:**
25+
26+
**Input:** root = []
27+
28+
**Output:** []
29+
30+
**Constraints:**
31+
32+
* The number of nodes in the tree is in the range `[0, 2000]`.
33+
* `-1000 <= Node.val <= 1000`
34+
35+
To solve the "Binary Tree Level Order Traversal" problem in Java with a `Solution` class, we'll perform a breadth-first search (BFS) traversal of the binary tree. Below are the steps:
36+
37+
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
38+
39+
2. **Create a `levelOrder` method**: This method takes the root node of the binary tree as input and returns the level order traversal of its nodes' values.
40+
41+
3. **Initialize a queue**: Create a queue to store the nodes during BFS traversal.
42+
43+
4. **Check for null root**: Check if the root is null. If it is, return an empty list.
44+
45+
5. **Perform BFS traversal**: Enqueue the root node into the queue. While the queue is not empty:
46+
- Dequeue the front node from the queue.
47+
- Add the value of the dequeued node to the current level list.
48+
- Enqueue the left and right children of the dequeued node if they exist.
49+
- Move to the next level when all nodes in the current level are processed.
50+
51+
6. **Return the result**: After the BFS traversal is complete, return the list containing the level order traversal of the binary tree.
52+
53+
Here's the Java implementation:
54+
55+
```java
56+
import java.util.ArrayList;
57+
import java.util.LinkedList;
58+
import java.util.List;
59+
import java.util.Queue;
60+
61+
class Solution {
62+
public List<List<Integer>> levelOrder(TreeNode root) {
63+
List<List<Integer>> result = new ArrayList<>(); // Initialize list to store level order traversal
64+
if (root == null) return result; // Check for empty tree
65+
66+
Queue<TreeNode> queue = new LinkedList<>(); // Initialize queue for BFS traversal
67+
queue.offer(root); // Enqueue the root node
68+
69+
while (!queue.isEmpty()) {
70+
int levelSize = queue.size(); // Get the number of nodes in the current level
71+
List<Integer> level = new ArrayList<>(); // Initialize list for the current level
72+
73+
for (int i = 0; i < levelSize; i++) {
74+
TreeNode node = queue.poll(); // Dequeue the front node
75+
level.add(node.val); // Add node value to the current level list
76+
77+
// Enqueue the left and right children if they exist
78+
if (node.left != null) queue.offer(node.left);
79+
if (node.right != null) queue.offer(node.right);
80+
}
81+
82+
result.add(level); // Add the current level list to the result list
83+
}
84+
85+
return result; // Return the level order traversal
86+
}
87+
88+
// Definition for a TreeNode
89+
public class TreeNode {
90+
int val;
91+
TreeNode left;
92+
TreeNode right;
93+
94+
TreeNode() {}
95+
TreeNode(int val) { this.val = val; }
96+
TreeNode(int val, TreeNode left, TreeNode right) {
97+
this.val = val;
98+
this.left = left;
99+
this.right = right;
100+
}
101+
}
102+
}
103+
```
104+
105+
This implementation follows the steps outlined above and efficiently computes the level order traversal of the binary tree in Java using BFS.
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 104\. Maximum Depth of Binary Tree
5+
6+
Easy
7+
8+
Given the `root` of a binary tree, return _its maximum depth_.
9+
10+
A binary tree's **maximum depth** is the number of nodes along the longest path from the root node down to the farthest leaf node.
11+
12+
**Example 1:**
13+
14+
![](https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg)
15+
16+
**Input:** root = [3,9,20,null,null,15,7]
17+
18+
**Output:** 3
19+
20+
**Example 2:**
21+
22+
**Input:** root = [1,null,2]
23+
24+
**Output:** 2
25+
26+
**Example 3:**
27+
28+
**Input:** root = []
29+
30+
**Output:** 0
31+
32+
**Example 4:**
33+
34+
**Input:** root = [0]
35+
36+
**Output:** 1
37+
38+
**Constraints:**
39+
40+
* The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.
41+
* `-100 <= Node.val <= 100`
42+
43+
To solve the "Maximum Depth of Binary Tree" problem in Java with a `Solution` class, we'll perform a depth-first search (DFS) traversal of the binary tree. Below are the steps:
44+
45+
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
46+
47+
2. **Create a `maxDepth` method**: This method takes the root node of the binary tree as input and returns its maximum depth.
48+
49+
3. **Check for null root**: Check if the root is null. If it is, return 0 as the depth.
50+
51+
4. **Perform DFS traversal**: Recursively compute the depth of the left and right subtrees. The maximum depth of the binary tree is the maximum depth of its left and right subtrees, plus 1 for the current node.
52+
53+
5. **Return the result**: After the DFS traversal is complete, return the maximum depth of the binary tree.
54+
55+
Here's the Java implementation:
56+
57+
```java
58+
class Solution {
59+
public int maxDepth(TreeNode root) {
60+
if (root == null) return 0; // Check for empty tree
61+
int leftDepth = maxDepth(root.left); // Compute depth of left subtree
62+
int rightDepth = maxDepth(root.right); // Compute depth of right subtree
63+
return Math.max(leftDepth, rightDepth) + 1; // Return maximum depth of left and right subtrees, plus 1 for the current node
64+
}
65+
66+
// Definition for a TreeNode
67+
public class TreeNode {
68+
int val;
69+
TreeNode left;
70+
TreeNode right;
71+
72+
TreeNode() {}
73+
TreeNode(int val) { this.val = val; }
74+
TreeNode(int val, TreeNode left, TreeNode right) {
75+
this.val = val;
76+
this.left = left;
77+
this.right = right;
78+
}
79+
}
80+
}
81+
```
82+
83+
This implementation follows the steps outlined above and efficiently computes the maximum depth of the binary tree in Java using DFS traversal.
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 105\. Construct Binary Tree from Preorder and Inorder Traversal
5+
6+
Medium
7+
8+
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_.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2021/02/19/tree.jpg)
13+
14+
**Input:** preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
15+
16+
**Output:** [3,9,20,null,null,15,7]
17+
18+
**Example 2:**
19+
20+
**Input:** preorder = [-1], inorder = [-1]
21+
22+
**Output:** [-1]
23+
24+
**Constraints:**
25+
26+
* `1 <= preorder.length <= 3000`
27+
* `inorder.length == preorder.length`
28+
* `-3000 <= preorder[i], inorder[i] <= 3000`
29+
* `preorder` and `inorder` consist of **unique** values.
30+
* Each value of `inorder` also appears in `preorder`.
31+
* `preorder` is **guaranteed** to be the preorder traversal of the tree.
32+
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
33+
34+
To solve the "Construct Binary Tree from Preorder and Inorder Traversal" problem in Java with a `Solution` class, we'll use a recursive approach. Below are the steps:
35+
36+
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
37+
38+
2. **Create a `buildTree` method**: This method takes two integer arrays, `preorder` and `inorder`, as input and returns the constructed binary tree.
39+
40+
3. **Check for empty arrays**: Check if either of the arrays `preorder` or `inorder` is empty. If so, return null, as there's no tree to construct.
41+
42+
4. **Define a helper method**: Define a recursive helper method `build` to construct the binary tree.
43+
- The method should take the indices representing the current subtree in both `preorder` and `inorder`.
44+
- The start and end indices in `preorder` represent the current subtree's preorder traversal.
45+
- The start and end indices in `inorder` represent the current subtree's inorder traversal.
46+
47+
5. **Base case**: If the start index of `preorder` is greater than the end index or if the start index of `inorder` is greater than the end index, return null.
48+
49+
6. **Find the root node**: The root node is the first element in the `preorder` array.
50+
51+
7. **Find the root's position in `inorder`**: Iterate through the `inorder` array to find the root's position.
52+
53+
8. **Recursively build left and right subtrees**:
54+
- Recursively call the `build` method for the left subtree with updated indices.
55+
- Recursively call the `build` method for the right subtree with updated indices.
56+
57+
9. **Return the root node**: After constructing the left and right subtrees, return the root node.
58+
59+
Here's the Java implementation:
60+
61+
```java
62+
class Solution {
63+
public TreeNode buildTree(int[] preorder, int[] inorder) {
64+
if (preorder.length == 0 || inorder.length == 0) return null; // Check for empty arrays
65+
return build(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1); // Construct binary tree
66+
}
67+
68+
// Recursive helper method to construct binary tree
69+
private TreeNode build(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd) {
70+
if (preStart > preEnd || inStart > inEnd) return null; // Base case
71+
72+
int rootValue = preorder[preStart]; // Root node value
73+
TreeNode root = new TreeNode(rootValue); // Create root node
74+
75+
// Find root node's position in inorder array
76+
int rootIndex = 0;
77+
for (int i = inStart; i <= inEnd; i++) {
78+
if (inorder[i] == rootValue) {
79+
rootIndex = i;
80+
break;
81+
}
82+
}
83+
84+
// Recursively build left and right subtrees
85+
root.left = build(preorder, inorder, preStart + 1, preStart + rootIndex - inStart, inStart, rootIndex - 1);
86+
root.right = build(preorder, inorder, preStart + rootIndex - inStart + 1, preEnd, rootIndex + 1, inEnd);
87+
88+
return root; // Return root node
89+
}
90+
91+
// TreeNode definition
92+
public class TreeNode {
93+
int val;
94+
TreeNode left;
95+
TreeNode right;
96+
97+
TreeNode() {}
98+
TreeNode(int val) { this.val = val; }
99+
TreeNode(int val, TreeNode left, TreeNode right) {
100+
this.val = val;
101+
this.left = left;
102+
this.right = right;
103+
}
104+
}
105+
}
106+
```
107+
108+
This implementation follows the steps outlined above and efficiently constructs the binary tree from preorder and inorder traversals in Java.
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 114\. Flatten Binary Tree to Linked List
5+
6+
Medium
7+
8+
Given the `root` of a binary tree, flatten the tree into a "linked list":
9+
10+
* 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`.
11+
* 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.
12+
13+
**Example 1:**
14+
15+
![](https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg)
16+
17+
**Input:** root = [1,2,5,3,4,null,6]
18+
19+
**Output:** [1,null,2,null,3,null,4,null,5,null,6]
20+
21+
**Example 2:**
22+
23+
**Input:** root = []
24+
25+
**Output:** []
26+
27+
**Example 3:**
28+
29+
**Input:** root = [0]
30+
31+
**Output:** [0]
32+
33+
**Constraints:**
34+
35+
* The number of nodes in the tree is in the range `[0, 2000]`.
36+
* `-100 <= Node.val <= 100`
37+
38+
**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
39+
40+
To solve the "Flatten Binary Tree to Linked List" problem in Java with a `Solution` class, we'll use a recursive approach. Below are the steps:
41+
42+
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
43+
44+
2. **Create a `flatten` method**: This method takes the root node of the binary tree as input and flattens the tree into a linked list using preorder traversal.
45+
46+
3. **Check for null root**: Check if the root is null. If so, there's no tree to flatten, so return.
47+
48+
4. **Recursively flatten the tree**: Define a recursive helper method `flattenTree` to perform the flattening.
49+
- The method should take the current node as input.
50+
- Perform a preorder traversal of the tree.
51+
- For each node, if it has a left child:
52+
- Find the rightmost node in the left subtree.
53+
- Attach the right subtree of the current node to the right of the rightmost node.
54+
- Move the left subtree to the right subtree position.
55+
- Set the left child of the current node to null.
56+
- Recursively call the method for the right child.
57+
58+
5. **Call the helper method**: Call the `flattenTree` method with the root node.
59+
60+
Here's the Java implementation:
61+
62+
```java
63+
class Solution {
64+
public void flatten(TreeNode root) {
65+
if (root == null) return; // Check for empty tree
66+
flattenTree(root); // Flatten the tree
67+
}
68+
69+
// Recursive helper method to flatten the tree
70+
private void flattenTree(TreeNode node) {
71+
if (node == null) return;
72+
73+
// Flatten left subtree
74+
flattenTree(node.left);
75+
76+
// Flatten right subtree
77+
flattenTree(node.right);
78+
79+
// Save right subtree
80+
TreeNode rightSubtree = node.right;
81+
82+
// Attach left subtree to the right of the current node
83+
node.right = node.left;
84+
85+
// Set left child to null
86+
node.left = null;
87+
88+
// Move to the rightmost node of the flattened left subtree
89+
TreeNode current = node;
90+
while (current.right != null) {
91+
current = current.right;
92+
}
93+
94+
// Attach the saved right subtree to the right of the rightmost node
95+
current.right = rightSubtree;
96+
}
97+
98+
// TreeNode definition
99+
public class TreeNode {
100+
int val;
101+
TreeNode left;
102+
TreeNode right;
103+
104+
TreeNode() {}
105+
TreeNode(int val) { this.val = val; }
106+
TreeNode(int val, TreeNode left, TreeNode right) {
107+
this.val = val;
108+
this.left = left;
109+
this.right = right;
110+
}
111+
}
112+
}
113+
```
114+
115+
This implementation follows the steps outlined above and efficiently flattens the binary tree into a linked list using preorder traversal in Java.
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 121\. Best Time to Buy and Sell Stock
5+
6+
Easy
7+
8+
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
9+
10+
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.
11+
12+
Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`.
13+
14+
**Example 1:**
15+
16+
**Input:** prices = [7,1,5,3,6,4]
17+
18+
**Output:** 5
19+
20+
**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.
21+
22+
**Example 2:**
23+
24+
**Input:** prices = [7,6,4,3,1]
25+
26+
**Output:** 0
27+
28+
**Explanation:** In this case, no transactions are done and the max profit = 0.
29+
30+
**Constraints:**
31+
32+
* <code>1 <= prices.length <= 10<sup>5</sup></code>
33+
* <code>0 <= prices[i] <= 10<sup>4</sup></code>
34+
35+
To solve the "Best Time to Buy and Sell Stock" problem in Java with a `Solution` class, we'll use a greedy algorithm. Below are the steps:
36+
37+
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
38+
39+
2. **Create a `maxProfit` method**: This method takes an array `prices` as input and returns the maximum profit that can be achieved by buying and selling the stock.
40+
41+
3. **Initialize variables**: Initialize two variables, `minPrice` to store the minimum price seen so far and `maxProfit` to store the maximum profit seen so far. Initialize `maxProfit` to 0.
42+
43+
4. **Iterate through the prices array**:
44+
- For each price in the array:
45+
- Update `minPrice` to the minimum of the current price and `minPrice`.
46+
- Update `maxProfit` to the maximum of the current profit (price - `minPrice`) and `maxProfit`.
47+
48+
5. **Return the maximum profit**: After iterating through the entire array, return `maxProfit`.
49+
50+
Here's the Java implementation:
51+
52+
```java
53+
class Solution {
54+
public int maxProfit(int[] prices) {
55+
if (prices == null || prices.length <= 1) return 0; // Check for empty array or single element
56+
57+
int minPrice = prices[0]; // Initialize minPrice to the first price
58+
int maxProfit = 0; // Initialize maxProfit to 0
59+
60+
// Iterate through the prices array
61+
for (int i = 1; i < prices.length; i++) {
62+
minPrice = Math.min(minPrice, prices[i]); // Update minPrice
63+
maxProfit = Math.max(maxProfit, prices[i] - minPrice); // Update maxProfit
64+
}
65+
66+
return maxProfit; // Return the maximum profit
67+
}
68+
}
69+
```
70+
71+
This implementation follows the steps outlined above and efficiently calculates the maximum profit that can be achieved by buying and selling the stock in Java.
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 124\. Binary Tree Maximum Path Sum
5+
6+
Hard
7+
8+
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.
9+
10+
The **path sum** of a path is the sum of the node's values in the path.
11+
12+
Given the `root` of a binary tree, return _the maximum **path sum** of any **non-empty** path_.
13+
14+
**Example 1:**
15+
16+
![](https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg)
17+
18+
**Input:** root = [1,2,3]
19+
20+
**Output:** 6
21+
22+
**Explanation:** The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
23+
24+
**Example 2:**
25+
26+
![](https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg)
27+
28+
**Input:** root = [-10,9,20,null,null,15,7]
29+
30+
**Output:** 42
31+
32+
**Explanation:** The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
33+
34+
**Constraints:**
35+
36+
* The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.
37+
* `-1000 <= Node.val <= 1000`
38+
39+
To solve the "Binary Tree Maximum Path Sum" problem in Java with a `Solution` class, we'll use a recursive approach. Below are the steps:
40+
41+
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
42+
43+
2. **Create a `maxPathSum` method**: This method takes the root node of the binary tree as input and returns the maximum path sum.
44+
45+
3. **Define a recursive helper method**: Define a recursive helper method `maxSumPath` to compute the maximum path sum rooted at the current node.
46+
- The method should return the maximum path sum that can be obtained from the current node to any of its descendants.
47+
- We'll use a post-order traversal to traverse the tree.
48+
- For each node:
49+
- Compute the maximum path sum for the left and right subtrees recursively.
50+
- Update the maximum path sum by considering three cases:
51+
1. The current node itself.
52+
2. The current node plus the maximum path sum of the left subtree.
53+
3. The current node plus the maximum path sum of the right subtree.
54+
- Update the global maximum path sum if necessary by considering the sum of the current node, left subtree, and right subtree.
55+
56+
4. **Initialize a variable to store the maximum path sum**: Initialize a global variable `maxSum` to store the maximum path sum.
57+
58+
5. **Call the helper method**: Call the `maxSumPath` method with the root node.
59+
60+
6. **Return the maximum path sum**: After traversing the entire tree, return the `maxSum`.
61+
62+
Here's the Java implementation:
63+
64+
```java
65+
class Solution {
66+
int maxSum = Integer.MIN_VALUE; // Initialize global variable to store maximum path sum
67+
68+
public int maxPathSum(TreeNode root) {
69+
maxSumPath(root);
70+
return maxSum; // Return maximum path sum
71+
}
72+
73+
// Recursive helper method to compute maximum path sum rooted at current node
74+
private int maxSumPath(TreeNode node) {
75+
if (node == null) return 0; // Base case
76+
77+
// Compute maximum path sum for left and right subtrees recursively
78+
int leftSum = Math.max(maxSumPath(node.left), 0); // Ignore negative sums
79+
int rightSum = Math.max(maxSumPath(node.right), 0); // Ignore negative sums
80+
81+
// Update maximum path sum by considering three cases:
82+
// 1. Current node itself
83+
// 2. Current node + maximum path sum of left subtree
84+
// 3. Current node + maximum path sum of right subtree
85+
int currentSum = node.val + leftSum + rightSum;
86+
maxSum = Math.max(maxSum, currentSum); // Update global maximum path sum
87+
88+
// Return the maximum path sum that can be obtained from the current node to any of its descendants
89+
return node.val + Math.max(leftSum, rightSum);
90+
}
91+
92+
// Definition for a binary tree node
93+
public class TreeNode {
94+
int val;
95+
TreeNode left;
96+
TreeNode right;
97+
98+
TreeNode() {}
99+
TreeNode(int val) { this.val = val; }
100+
TreeNode(int val, TreeNode left, TreeNode right) {
101+
this.val = val;
102+
this.left = left;
103+
this.right = right;
104+
}
105+
}
106+
}
107+
```
108+
109+
This implementation follows the steps outlined above and efficiently computes the maximum path sum in a binary tree in Java.
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 128\. Longest Consecutive Sequence
5+
6+
Medium
7+
8+
Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
9+
10+
You must write an algorithm that runs in `O(n)` time.
11+
12+
**Example 1:**
13+
14+
**Input:** nums = [100,4,200,1,3,2]
15+
16+
**Output:** 4
17+
18+
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4.
19+
20+
**Example 2:**
21+
22+
**Input:** nums = [0,3,7,2,5,8,4,6,0,1]
23+
24+
**Output:** 9
25+
26+
**Constraints:**
27+
28+
* <code>0 <= nums.length <= 10<sup>5</sup></code>
29+
* <code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code>
30+
31+
To solve the "Longest Consecutive Sequence" problem in Java with a `Solution` class, we'll use a HashSet and a greedy approach. Below are the steps:
32+
33+
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
34+
35+
2. **Create a `longestConsecutive` method**: This method takes an array `nums` as input and returns the length of the longest consecutive elements sequence.
36+
37+
3. **Initialize a HashSet**: Create a HashSet named `numSet` to store all the numbers in the array `nums`.
38+
39+
4. **Iterate through the array**: Add all the numbers from the array `nums` to the `numSet`.
40+
41+
5. **Find the longest sequence**: Iterate through the array `nums` again. For each number `num` in the array:
42+
- Check if `num - 1` exists in the `numSet`. If it does not, `num` could be the start of a new sequence.
43+
- If `num - 1` does not exist, start a new sequence from `num`. Increment `currentNum` by 1 and check if `currentNum` exists in the `numSet`. Keep incrementing `currentNum` until it does not exist in the `numSet`. Update the maximum length of the sequence accordingly.
44+
45+
6. **Return the maximum length**: After iterating through the entire array, return the maximum length of the consecutive sequence.
46+
47+
Here's the Java implementation:
48+
49+
```java
50+
import java.util.HashSet;
51+
52+
class Solution {
53+
public int longestConsecutive(int[] nums) {
54+
HashSet<Integer> numSet = new HashSet<>();
55+
for (int num : nums) {
56+
numSet.add(num); // Add all numbers to HashSet
57+
}
58+
59+
int maxLength = 0;
60+
for (int num : nums) {
61+
if (!numSet.contains(num - 1)) { // Check if num - 1 exists in numSet
62+
int currentNum = num;
63+
int currentLength = 1;
64+
65+
while (numSet.contains(currentNum + 1)) { // Increment currentNum until it does not exist in numSet
66+
currentNum++;
67+
currentLength++;
68+
}
69+
70+
maxLength = Math.max(maxLength, currentLength); // Update maximum length
71+
}
72+
}
73+
74+
return maxLength; // Return the maximum length of the consecutive sequence
75+
}
76+
}
77+
```
78+
79+
This implementation follows the steps outlined above and efficiently calculates the length of the longest consecutive elements sequence in Java.
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 131\. Palindrome Partitioning
5+
6+
Medium
7+
8+
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return all possible palindrome partitioning of `s`.
9+
10+
A **palindrome** string is a string that reads the same backward as forward.
11+
12+
**Example 1:**
13+
14+
**Input:** s = "aab"
15+
16+
**Output:** [["a","a","b"],["aa","b"]]
17+
18+
**Example 2:**
19+
20+
**Input:** s = "a"
21+
22+
**Output:** [["a"]]
23+
24+
**Constraints:**
25+
26+
* `1 <= s.length <= 16`
27+
* `s` contains only lowercase English letters.
28+
29+
To solve the "Palindrome Partitioning" problem in Java with a `Solution` class, we'll use backtracking. Below are the steps:
30+
31+
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
32+
33+
2. **Create a `partition` method**: This method takes a string `s` as input and returns all possible palindrome partitioning of `s`.
34+
35+
3. **Define a recursive helper method**: Define a recursive helper method `backtrack` to find all possible palindrome partitions.
36+
- The method should take the current index `start`, the current partition `partition`, and the list to store all partitions `result`.
37+
- Base case: If `start` reaches the end of the string `s`, add the current partition to the result list and return.
38+
- Iterate from `start` to the end of the string:
39+
- Check if the substring from `start` to `i` is a palindrome.
40+
- If it is a palindrome, add the substring to the current partition and recursively call the `backtrack` method with the updated index and partition.
41+
- After the recursive call, remove the last substring added to the partition to backtrack and explore other partitions.
42+
43+
4. **Initialize a list to store all partitions**: Create an ArrayList named `result` to store all possible palindrome partitions.
44+
45+
5. **Call the helper method**: Call the `backtrack` method with the initial index, an empty partition list, and the result list.
46+
47+
6. **Return the result list**: After exploring all possible partitions, return the list containing all palindrome partitions.
48+
49+
Here's the Java implementation:
50+
51+
```java
52+
import java.util.ArrayList;
53+
import java.util.List;
54+
55+
class Solution {
56+
public List<List<String>> partition(String s) {
57+
List<List<String>> result = new ArrayList<>();
58+
backtrack(s, 0, new ArrayList<>(), result);
59+
return result;
60+
}
61+
62+
// Recursive helper method to find all possible palindrome partitions
63+
private void backtrack(String s, int start, List<String> partition, List<List<String>> result) {
64+
if (start == s.length()) {
65+
result.add(new ArrayList<>(partition));
66+
return;
67+
}
68+
69+
for (int i = start; i < s.length(); i++) {
70+
String substring = s.substring(start, i + 1);
71+
if (isPalindrome(substring)) {
72+
partition.add(substring);
73+
backtrack(s, i + 1, partition, result);
74+
partition.remove(partition.size() - 1); // Backtrack
75+
}
76+
}
77+
}
78+
79+
// Helper method to check if a string is a palindrome
80+
private boolean isPalindrome(String s) {
81+
int left = 0;
82+
int right = s.length() - 1;
83+
while (left < right) {
84+
if (s.charAt(left) != s.charAt(right)) {
85+
return false;
86+
}
87+
left++;
88+
right--;
89+
}
90+
return true;
91+
}
92+
}
93+
```
94+
95+
This implementation follows the steps outlined above and efficiently finds all possible palindrome partitions of the given string in Java.
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 136\. Single Number
5+
6+
Easy
7+
8+
Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one.
9+
10+
You must implement a solution with a linear runtime complexity and use only constant extra space.
11+
12+
**Example 1:**
13+
14+
**Input:** nums = [2,2,1]
15+
16+
**Output:** 1
17+
18+
**Example 2:**
19+
20+
**Input:** nums = [4,1,2,1,2]
21+
22+
**Output:** 4
23+
24+
**Example 3:**
25+
26+
**Input:** nums = [1]
27+
28+
**Output:** 1
29+
30+
**Constraints:**
31+
32+
* <code>1 <= nums.length <= 3 * 10<sup>4</sup></code>
33+
* <code>-3 * 10<sup>4</sup> <= nums[i] <= 3 * 10<sup>4</sup></code>
34+
* Each element in the array appears twice except for one element which appears only once.
35+
36+
To solve the "Single Number" problem in Java with a `Solution` class, we'll use bitwise XOR operation. Below are the steps:
37+
38+
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
39+
40+
2. **Create a `singleNumber` method**: This method takes an array `nums` as input and returns the single number that appears only once.
41+
42+
3. **Initialize a variable to store the result**: Initialize a variable `singleNumber` to 0.
43+
44+
4. **Iterate through the array and perform bitwise XOR operation**: Iterate through the array `nums`. For each number `num` in the array, perform bitwise XOR operation with the `singleNumber`.
45+
46+
5. **Return the result**: After iterating through the entire array, the `singleNumber` variable will store the single number that appears only once. Return `singleNumber`.
47+
48+
Here's the Java implementation:
49+
50+
```java
51+
class Solution {
52+
public int singleNumber(int[] nums) {
53+
int singleNumber = 0; // Initialize variable to store result
54+
55+
// Perform bitwise XOR operation on all elements in the array
56+
for (int num : nums) {
57+
singleNumber ^= num;
58+
}
59+
60+
return singleNumber; // Return the single number
61+
}
62+
}
63+
```
64+
65+
This implementation follows the steps outlined above and efficiently finds the single number that appears only once in the given array using bitwise XOR operation in Java.
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 138\. Copy List with Random Pointer
5+
6+
Medium
7+
8+
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`.
9+
10+
Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**.
11+
12+
For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`.
13+
14+
Return _the head of the copied linked list_.
15+
16+
The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where:
17+
18+
* `val`: an integer representing `Node.val`
19+
* `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node.
20+
21+
Your code will **only** be given the `head` of the original linked list.
22+
23+
**Example 1:**
24+
25+
![](https://assets.leetcode.com/uploads/2019/12/18/e1.png)
26+
27+
**Input:** head = \[\[7,null],[13,0],[11,4],[10,2],[1,0]]
28+
29+
**Output:** [[7,null],[13,0],[11,4],[10,2],[1,0]]
30+
31+
**Example 2:**
32+
33+
![](https://assets.leetcode.com/uploads/2019/12/18/e2.png)
34+
35+
**Input:** head = \[\[1,1],[2,1]]
36+
37+
**Output:** [[1,1],[2,1]]
38+
39+
**Example 3:**
40+
41+
**![](https://assets.leetcode.com/uploads/2019/12/18/e3.png)**
42+
43+
**Input:** head = \[\[3,null],[3,0],[3,null]]
44+
45+
**Output:** [[3,null],[3,0],[3,null]]
46+
47+
**Example 4:**
48+
49+
**Input:** head = []
50+
51+
**Output:** []
52+
53+
**Explanation:** The given linked list is empty (null pointer), so return null.
54+
55+
**Constraints:**
56+
57+
* `0 <= n <= 1000`
58+
* `-10000 <= Node.val <= 10000`
59+
* `Node.random` is `null` or is pointing to some node in the linked list.
60+
61+
To solve the "Copy List with Random Pointer" problem in Java with a `Solution` class, we'll use a HashMap to maintain a mapping between the original nodes and their corresponding copied nodes. Below are the steps:
62+
63+
1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods.
64+
65+
2. **Create a `copyRandomList` method**: This method takes the head node of the original linked list as input and returns the head node of the copied linked list.
66+
67+
3. **Initialize a HashMap**: Create a HashMap named `nodeMap` to store the mapping between original nodes and their corresponding copied nodes.
68+
69+
4. **Create a deep copy of the list**: Iterate through the original linked list and create a deep copy of each node. For each node `originalNode` in the original linked list:
70+
- Create a new node `copyNode` with the same value as `originalNode`.
71+
- Put the mapping between `originalNode` and `copyNode` in the `nodeMap`.
72+
- Set the `copyNode`'s `next` and `random` pointers accordingly.
73+
- Attach the `copyNode` to the copied linked list.
74+
75+
5. **Return the head of the copied linked list**: After creating the deep copy of the entire list, return the head node of the copied linked list.
76+
77+
Here's the Java implementation:
78+
79+
```java
80+
import java.util.HashMap;
81+
import java.util.Map;
82+
83+
class Solution {
84+
public Node copyRandomList(Node head) {
85+
if (head == null) return null; // Check for empty list
86+
87+
Map<Node, Node> nodeMap = new HashMap<>(); // Initialize HashMap to store mapping between original and copied nodes
88+
89+
// Create a deep copy of each node in the list
90+
Node current = head;
91+
while (current != null) {
92+
Node copyNode = new Node(current.val); // Create a new copy node
93+
nodeMap.put(current, copyNode); // Put mapping between original and copied nodes in the map
94+
current = current.next; // Move to the next node
95+
}
96+
97+
// Set the next and random pointers of copied nodes
98+
current = head;
99+
while (current != null) {
100+
Node copyNode = nodeMap.get(current); // Get copied node
101+
copyNode.next = nodeMap.getOrDefault(current.next, null); // Set next pointer
102+
copyNode.random = nodeMap.getOrDefault(current.random, null); // Set random pointer
103+
current = current.next; // Move to the next node
104+
}
105+
106+
return nodeMap.get(head); // Return the head of the copied linked list
107+
}
108+
109+
// Definition for a Node
110+
class Node {
111+
int val;
112+
Node next, random;
113+
114+
Node(int val) {
115+
this.val = val;
116+
this.next = null;
117+
this.random = null;
118+
}
119+
}
120+
}
121+
```
122+
123+
This implementation follows the steps outlined above and efficiently constructs a deep copy of the linked list with random pointers in Java.
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 139\. Word Break
5+
6+
Medium
7+
8+
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
9+
10+
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
11+
12+
**Example 1:**
13+
14+
**Input:** s = "leetcode", wordDict = ["leet","code"]
15+
16+
**Output:** true
17+
18+
**Explanation:** Return true because "leetcode" can be segmented as "leet code".
19+
20+
**Example 2:**
21+
22+
**Input:** s = "applepenapple", wordDict = ["apple","pen"]
23+
24+
**Output:** true
25+
26+
**Explanation:** Return true because "applepenapple" can be segmented as "apple pen apple". Note that you are allowed to reuse a dictionary word.
27+
28+
**Example 3:**
29+
30+
**Input:** s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
31+
32+
**Output:** false
33+
34+
**Constraints:**
35+
36+
* `1 <= s.length <= 300`
37+
* `1 <= wordDict.length <= 1000`
38+
* `1 <= wordDict[i].length <= 20`
39+
* `s` and `wordDict[i]` consist of only lowercase English letters.
40+
* All the strings of `wordDict` are **unique**.
41+
42+
## Solution
43+
44+
```cpp
45+
#include <string>
46+
#include <vector>
47+
#include <unordered_set>
48+
using namespace std;
49+
50+
class Solution {
51+
public:
52+
bool wordBreak(string s, vector<string>& wordDict) {
53+
unordered_set<string> set;
54+
int maxLen = 0;
55+
vector<bool> flag(s.length() + 1, false);
56+
57+
for (const string& word : wordDict) {
58+
set.insert(word);
59+
maxLen = max(maxLen, (int)word.length());
60+
}
61+
62+
for (int i = 1; i <= maxLen; ++i) {
63+
if (dfs(s, 0, i, maxLen, set, flag)) {
64+
return true;
65+
}
66+
}
67+
return false;
68+
}
69+
70+
private:
71+
bool dfs(const string& s, int start, int end, int maxLen, unordered_set<string>& set, vector<bool>& flag) {
72+
if (!flag[end] && set.count(s.substr(start, end - start))) {
73+
flag[end] = true;
74+
if (end == s.length()) {
75+
return true;
76+
}
77+
for (int i = 1; i <= maxLen; ++i) {
78+
if (end + i <= s.length() && dfs(s, end, end + i, maxLen, set, flag)) {
79+
return true;
80+
}
81+
}
82+
}
83+
return false;
84+
}
85+
};
86+
```
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 141\. Linked List Cycle
5+
6+
Easy
7+
8+
Given `head`, the head of a linked list, determine if the linked list has a cycle in it.
9+
10+
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**.
11+
12+
Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`.
13+
14+
**Example 1:**
15+
16+
![](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png)
17+
18+
**Input:** head = [3,2,0,-4], pos = 1
19+
20+
**Output:** true
21+
22+
**Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
23+
24+
**Example 2:**
25+
26+
![](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png)
27+
28+
**Input:** head = [1,2], pos = 0
29+
30+
**Output:** true
31+
32+
**Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node.
33+
34+
**Example 3:**
35+
36+
![](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png)
37+
38+
**Input:** head = [1], pos = -1
39+
40+
**Output:** false
41+
42+
**Explanation:** There is no cycle in the linked list.
43+
44+
**Constraints:**
45+
46+
* The number of the nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.
47+
* <code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code>
48+
* `pos` is `-1` or a **valid index** in the linked-list.
49+
50+
**Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
51+
52+
## Solution
53+
54+
```cpp
55+
/**
56+
* Definition for singly-linked list.
57+
* struct ListNode {
58+
* int val;
59+
* ListNode *next;
60+
* ListNode(int x) : val(x), next(NULL) {}
61+
* };
62+
*/
63+
class Solution {
64+
public:
65+
bool hasCycle(ListNode* head) {
66+
if (head == nullptr) {
67+
return false;
68+
}
69+
ListNode* fast = head->next;
70+
ListNode* slow = head;
71+
while (fast != nullptr && fast->next != nullptr) {
72+
if (fast == slow) {
73+
return true;
74+
}
75+
fast = fast->next->next;
76+
slow = slow->next;
77+
}
78+
return false;
79+
}
80+
};
81+
```
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 142\. Linked List Cycle II
5+
6+
Medium
7+
8+
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`.
9+
10+
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**.
11+
12+
**Do not modify** the linked list.
13+
14+
**Example 1:**
15+
16+
![](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png)
17+
18+
**Input:** head = [3,2,0,-4], pos = 1
19+
20+
**Output:** tail connects to node index 1
21+
22+
**Explanation:** There is a cycle in the linked list, where tail connects to the second node.
23+
24+
**Example 2:**
25+
26+
![](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png)
27+
28+
**Input:** head = [1,2], pos = 0
29+
30+
**Output:** tail connects to node index 0
31+
32+
**Explanation:** There is a cycle in the linked list, where tail connects to the first node.
33+
34+
**Example 3:**
35+
36+
![](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png)
37+
38+
**Input:** head = [1], pos = -1
39+
40+
**Output:** no cycle
41+
42+
**Explanation:** There is no cycle in the linked list.
43+
44+
**Constraints:**
45+
46+
* The number of the nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.
47+
* <code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code>
48+
* `pos` is `-1` or a **valid index** in the linked-list.
49+
50+
**Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
51+
52+
## Solution
53+
54+
```cpp
55+
class Solution {
56+
public:
57+
ListNode* detectCycle(ListNode* head) {
58+
if (head == nullptr || head->next == nullptr) {
59+
return nullptr;
60+
}
61+
ListNode* slow = head;
62+
ListNode* fast = head;
63+
while (fast != nullptr && fast->next != nullptr) {
64+
fast = fast->next->next;
65+
slow = slow->next;
66+
// Intersected inside the loop.
67+
if (slow == fast) {
68+
break;
69+
}
70+
}
71+
if (fast == nullptr || fast->next == nullptr) {
72+
return nullptr;
73+
}
74+
slow = head;
75+
while (slow != fast) {
76+
slow = slow->next;
77+
fast = fast->next;
78+
}
79+
return slow;
80+
}
81+
};
82+
```
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 146\. LRU Cache
5+
6+
Medium
7+
8+
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.
9+
10+
Implement the `LRUCache` class:
11+
12+
* `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`.
13+
* `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`.
14+
* `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key.
15+
16+
The functions `get` and `put` must each run in `O(1)` average time complexity.
17+
18+
**Example 1:**
19+
20+
**Input** ["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"] [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
21+
22+
**Output:** [null, null, null, 1, null, -1, null, -1, 3, 4]
23+
24+
**Explanation:**
25+
26+
LRUCache lRUCache = new LRUCache(2);
27+
lRUCache.put(1, 1); // cache is {1=1}
28+
lRUCache.put(2, 2); // cache is {1=1, 2=2}
29+
lRUCache.get(1); // return 1
30+
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
31+
lRUCache.get(2); // returns -1 (not found)
32+
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
33+
lRUCache.get(1); // return -1 (not found)
34+
lRUCache.get(3); // return 3
35+
lRUCache.get(4); // return 4
36+
37+
**Constraints:**
38+
39+
* `1 <= capacity <= 3000`
40+
* <code>0 <= key <= 10<sup>4</sup></code>
41+
* <code>0 <= value <= 10<sup>5</sup></code>
42+
* At most 2<code> * 10<sup>5</sup></code> calls will be made to `get` and `put`.
43+
44+
## Solution
45+
46+
```cpp
47+
#include <unordered_map>
48+
49+
class LRUCache {
50+
private:
51+
struct LruCacheNode {
52+
int key;
53+
int value;
54+
LruCacheNode* prev;
55+
LruCacheNode* next;
56+
57+
LruCacheNode(int k, int v) : key(k), value(v), prev(nullptr), next(nullptr) {}
58+
};
59+
60+
int capacity;
61+
std::unordered_map<int, LruCacheNode*> cacheMap;
62+
LruCacheNode* head;
63+
LruCacheNode* tail;
64+
65+
public:
66+
LRUCache(int cap) : capacity(cap), head(nullptr), tail(nullptr) {}
67+
68+
int get(int key) {
69+
auto it = cacheMap.find(key);
70+
if (it == cacheMap.end()) {
71+
return -1;
72+
}
73+
LruCacheNode* val = it->second;
74+
moveToHead(val);
75+
return val->value;
76+
}
77+
78+
void put(int key, int value) {
79+
auto it = cacheMap.find(key);
80+
if (it != cacheMap.end()) {
81+
LruCacheNode* valNode = it->second;
82+
valNode->value = value;
83+
moveToHead(valNode);
84+
} else {
85+
if (cacheMap.size() < capacity) {
86+
LruCacheNode* node = new LruCacheNode(key, value);
87+
cacheMap[key] = node;
88+
if (head == nullptr) {
89+
head = node;
90+
tail = node;
91+
} else {
92+
node->next = head;
93+
head->prev = node;
94+
head = node;
95+
}
96+
} else {
97+
// Remove from tail
98+
LruCacheNode* last = tail;
99+
tail = last->prev;
100+
if (tail != nullptr) {
101+
tail->next = nullptr;
102+
}
103+
cacheMap.erase(last->key);
104+
delete last;
105+
if (cacheMap.size() == 0) {
106+
head = nullptr;
107+
}
108+
// Call recursively
109+
put(key, value);
110+
}
111+
}
112+
}
113+
114+
private:
115+
void moveToHead(LruCacheNode* node) {
116+
if (node == head) {
117+
return;
118+
}
119+
if (node == tail) {
120+
tail = node->prev;
121+
}
122+
LruCacheNode* prev = node->prev;
123+
LruCacheNode* next = node->next;
124+
prev->next = next;
125+
if (next != nullptr) {
126+
next->prev = prev;
127+
}
128+
node->prev = nullptr;
129+
node->next = head;
130+
head->prev = node;
131+
head = node;
132+
}
133+
};
134+
135+
/**
136+
* Your LRUCache object will be instantiated and called as such:
137+
* LRUCache* obj = new LRUCache(capacity);
138+
* int param_1 = obj->get(key);
139+
* obj->put(key,value);
140+
*/
141+
```
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 148\. Sort List
5+
6+
Medium
7+
8+
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg)
13+
14+
**Input:** head = [4,2,1,3]
15+
16+
**Output:** [1,2,3,4]
17+
18+
**Example 2:**
19+
20+
![](https://assets.leetcode.com/uploads/2020/09/14/sort_list_2.jpg)
21+
22+
**Input:** head = [-1,5,3,4,0]
23+
24+
**Output:** [-1,0,3,4,5]
25+
26+
**Example 3:**
27+
28+
**Input:** head = []
29+
30+
**Output:** []
31+
32+
**Constraints:**
33+
34+
* The number of nodes in the list is in the range <code>[0, 5 * 10<sup>4</sup>]</code>.
35+
* <code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code>
36+
37+
**Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
38+
39+
## Solution
40+
41+
```cpp
42+
class Solution {
43+
public:
44+
ListNode* sortList(ListNode* head) {
45+
if (head == nullptr || head->next == nullptr) {
46+
return head;
47+
}
48+
ListNode* slow = head;
49+
ListNode* fast = head;
50+
ListNode* pre = slow;
51+
while (fast != nullptr && fast->next != nullptr) {
52+
pre = slow;
53+
slow = slow->next;
54+
fast = fast->next->next;
55+
}
56+
pre->next = nullptr;
57+
ListNode* first = sortList(head);
58+
ListNode* second = sortList(slow);
59+
ListNode* res = new ListNode(1);
60+
ListNode* cur = res;
61+
while (first != nullptr || second != nullptr) {
62+
if (first == nullptr) {
63+
cur->next = second;
64+
break;
65+
} else if (second == nullptr) {
66+
cur->next = first;
67+
break;
68+
} else if (first->val <= second->val) {
69+
cur->next = first;
70+
first = first->next;
71+
cur = cur->next;
72+
} else {
73+
cur->next = second;
74+
second = second->next;
75+
cur = cur->next;
76+
}
77+
}
78+
return res->next;
79+
}
80+
};
81+
```
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 152\. Maximum Product Subarray
5+
6+
Medium
7+
8+
Given an integer array `nums`, find a contiguous non-empty subarray within the array that has the largest product, and return _the product_.
9+
10+
It is **guaranteed** that the answer will fit in a **32-bit** integer.
11+
12+
A **subarray** is a contiguous subsequence of the array.
13+
14+
**Example 1:**
15+
16+
**Input:** nums = [2,3,-2,4]
17+
18+
**Output:** 6
19+
20+
**Explanation:** [2,3] has the largest product 6.
21+
22+
**Example 2:**
23+
24+
**Input:** nums = [-2,0,-1]
25+
26+
**Output:** 0
27+
28+
**Explanation:** The result cannot be 2, because [-2,-1] is not a subarray.
29+
30+
**Constraints:**
31+
32+
* <code>1 <= nums.length <= 2 * 10<sup>4</sup></code>
33+
* `-10 <= nums[i] <= 10`
34+
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
35+
36+
## Solution
37+
38+
```cpp
39+
#include <vector>
40+
#include <algorithm>
41+
42+
class Solution {
43+
public:
44+
int maxProduct(std::vector<int>& nums) {
45+
int ans = INT_MIN;
46+
int cprod = 1;
47+
for (int j : nums) {
48+
cprod *= j;
49+
ans = std::max(ans, cprod);
50+
if (cprod == 0) {
51+
cprod = 1;
52+
}
53+
}
54+
cprod = 1;
55+
for (int i = nums.size() - 1; i >= 0; i--) {
56+
cprod *= nums[i];
57+
ans = std::max(ans, cprod);
58+
if (cprod == 0) {
59+
cprod = 1;
60+
}
61+
}
62+
return ans;
63+
}
64+
};
65+
```
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 153\. Find Minimum in Rotated Sorted Array
5+
6+
Medium
7+
8+
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become:
9+
10+
* `[4,5,6,7,0,1,2]` if it was rotated `4` times.
11+
* `[0,1,2,4,5,6,7]` if it was rotated `7` times.
12+
13+
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
14+
15+
Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_.
16+
17+
You must write an algorithm that runs in `O(log n) time.`
18+
19+
**Example 1:**
20+
21+
**Input:** nums = [3,4,5,1,2]
22+
23+
**Output:** 1
24+
25+
**Explanation:** The original array was [1,2,3,4,5] rotated 3 times.
26+
27+
**Example 2:**
28+
29+
**Input:** nums = [4,5,6,7,0,1,2]
30+
31+
**Output:** 0
32+
33+
**Explanation:** The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.
34+
35+
**Example 3:**
36+
37+
**Input:** nums = [11,13,15,17]
38+
39+
**Output:** 11
40+
41+
**Explanation:** The original array was [11,13,15,17] and it was rotated 4 times.
42+
43+
**Constraints:**
44+
45+
* `n == nums.length`
46+
* `1 <= n <= 5000`
47+
* `-5000 <= nums[i] <= 5000`
48+
* All the integers of `nums` are **unique**.
49+
* `nums` is sorted and rotated between `1` and `n` times.
50+
51+
## Solution
52+
53+
```cpp
54+
#include <vector>
55+
56+
class Solution {
57+
private:
58+
int findMinUtil(std::vector<int>& nums, int l, int r) {
59+
if (l == r) {
60+
return nums[l];
61+
}
62+
int mid = (l + r) / 2;
63+
if (mid == l && nums[mid] < nums[r]) {
64+
return nums[l];
65+
}
66+
if (mid - 1 >= 0 && nums[mid - 1] > nums[mid]) {
67+
return nums[mid];
68+
}
69+
if (nums[mid] < nums[l]) {
70+
return findMinUtil(nums, l, mid - 1);
71+
} else if (nums[mid] > nums[r]) {
72+
return findMinUtil(nums, mid + 1, r);
73+
}
74+
return findMinUtil(nums, l, mid - 1);
75+
}
76+
77+
public:
78+
int findMin(std::vector<int>& nums) {
79+
int l = 0;
80+
int r = nums.size() - 1;
81+
return findMinUtil(nums, l, r);
82+
}
83+
};
84+
```
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 155\. Min Stack
5+
6+
Easy
7+
8+
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
9+
10+
Implement the `MinStack` class:
11+
12+
* `MinStack()` initializes the stack object.
13+
* `void push(int val)` pushes the element `val` onto the stack.
14+
* `void pop()` removes the element on the top of the stack.
15+
* `int top()` gets the top element of the stack.
16+
* `int getMin()` retrieves the minimum element in the stack.
17+
18+
**Example 1:**
19+
20+
**Input**
21+
22+
["MinStack","push","push","push","getMin","pop","top","getMin"]
23+
[[],[-2],[0],[-3],[],[],[],[]]
24+
25+
**Output:** [null,null,null,null,-3,null,0,-2]
26+
27+
**Explanation:**
28+
29+
MinStack minStack = new MinStack();
30+
minStack.push(-2);
31+
minStack.push(0);
32+
minStack.push(-3);
33+
minStack.getMin(); // return -3
34+
minStack.pop();
35+
minStack.top(); // return 0
36+
minStack.getMin(); // return -2
37+
38+
**Constraints:**
39+
40+
* <code>-2<sup>31</sup> <= val <= 2<sup>31</sup> - 1</code>
41+
* Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks.
42+
* At most <code>3 * 10<sup>4</sup></code> calls will be made to `push`, `pop`, `top`, and `getMin`.
43+
44+
## Solution
45+
46+
```cpp
47+
#include <stack>
48+
#include <algorithm>
49+
50+
class MinStack {
51+
private:
52+
struct Node {
53+
int min;
54+
int data;
55+
Node* nextNode;
56+
Node* previousNode;
57+
58+
Node(int min, int data, Node* previousNode, Node* nextNode)
59+
: min(min), data(data), previousNode(previousNode), nextNode(nextNode) {}
60+
};
61+
62+
Node* currentNode;
63+
64+
public:
65+
MinStack() : currentNode(nullptr) {}
66+
67+
void push(int val) {
68+
if (currentNode == nullptr) {
69+
currentNode = new Node(val, val, nullptr, nullptr);
70+
} else {
71+
currentNode->nextNode = new Node(std::min(currentNode->min, val), val, currentNode, nullptr);
72+
currentNode = currentNode->nextNode;
73+
}
74+
}
75+
76+
void pop() {
77+
if (currentNode != nullptr) {
78+
currentNode = currentNode->previousNode;
79+
}
80+
}
81+
82+
int top() {
83+
if (currentNode != nullptr) {
84+
return currentNode->data;
85+
}
86+
return -1;
87+
}
88+
89+
int getMin() {
90+
if (currentNode != nullptr) {
91+
return currentNode->min;
92+
}
93+
return -1;
94+
}
95+
96+
~MinStack() {
97+
while (currentNode != nullptr) {
98+
Node* temp = currentNode;
99+
currentNode = currentNode->previousNode;
100+
delete temp;
101+
}
102+
}
103+
};
104+
105+
/**
106+
* Your MinStack object will be instantiated and called as such:
107+
* MinStack* obj = new MinStack();
108+
* obj->push(val);
109+
* obj->pop();
110+
* int param_3 = obj->top();
111+
* int param_4 = obj->getMin();
112+
*/
113+
```

0 commit comments

Comments
 (0)
Please sign in to comment.