diff --git a/src/main/java/g0101_0200/s0102_binary_tree_level_order_traversal/readme.md b/src/main/java/g0101_0200/s0102_binary_tree_level_order_traversal/readme.md index 92fe4a4e3..509970383 100644 --- a/src/main/java/g0101_0200/s0102_binary_tree_level_order_traversal/readme.md +++ b/src/main/java/g0101_0200/s0102_binary_tree_level_order_traversal/readme.md @@ -27,4 +27,76 @@ Given the `root` of a binary tree, return _the level order traversal of its node **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. -* `-1000 <= Node.val <= 1000` \ No newline at end of file +* `-1000 <= Node.val <= 1000` + +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: + +1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods. + +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. + +3. **Initialize a queue**: Create a queue to store the nodes during BFS traversal. + +4. **Check for null root**: Check if the root is null. If it is, return an empty list. + +5. **Perform BFS traversal**: Enqueue the root node into the queue. While the queue is not empty: + - Dequeue the front node from the queue. + - Add the value of the dequeued node to the current level list. + - Enqueue the left and right children of the dequeued node if they exist. + - Move to the next level when all nodes in the current level are processed. + +6. **Return the result**: After the BFS traversal is complete, return the list containing the level order traversal of the binary tree. + +Here's the Java implementation: + +```java +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +class Solution { + public List> levelOrder(TreeNode root) { + List> result = new ArrayList<>(); // Initialize list to store level order traversal + if (root == null) return result; // Check for empty tree + + Queue queue = new LinkedList<>(); // Initialize queue for BFS traversal + queue.offer(root); // Enqueue the root node + + while (!queue.isEmpty()) { + int levelSize = queue.size(); // Get the number of nodes in the current level + List level = new ArrayList<>(); // Initialize list for the current level + + for (int i = 0; i < levelSize; i++) { + TreeNode node = queue.poll(); // Dequeue the front node + level.add(node.val); // Add node value to the current level list + + // Enqueue the left and right children if they exist + if (node.left != null) queue.offer(node.left); + if (node.right != null) queue.offer(node.right); + } + + result.add(level); // Add the current level list to the result list + } + + return result; // Return the level order traversal + } + + // Definition for a TreeNode + public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode() {} + TreeNode(int val) { this.val = val; } + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } + } +} +``` + +This implementation follows the steps outlined above and efficiently computes the level order traversal of the binary tree in Java using BFS. \ No newline at end of file diff --git a/src/main/java/g0101_0200/s0104_maximum_depth_of_binary_tree/readme.md b/src/main/java/g0101_0200/s0104_maximum_depth_of_binary_tree/readme.md index 052ac0151..aadf2c137 100644 --- a/src/main/java/g0101_0200/s0104_maximum_depth_of_binary_tree/readme.md +++ b/src/main/java/g0101_0200/s0104_maximum_depth_of_binary_tree/readme.md @@ -35,4 +35,46 @@ A binary tree's **maximum depth** is the number of nodes along the longest path **Constraints:** * The number of nodes in the tree is in the range [0, 104]. -* `-100 <= Node.val <= 100` \ No newline at end of file +* `-100 <= Node.val <= 100` + +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: + +1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods. + +2. **Create a `maxDepth` method**: This method takes the root node of the binary tree as input and returns its maximum depth. + +3. **Check for null root**: Check if the root is null. If it is, return 0 as the depth. + +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. + +5. **Return the result**: After the DFS traversal is complete, return the maximum depth of the binary tree. + +Here's the Java implementation: + +```java +class Solution { + public int maxDepth(TreeNode root) { + if (root == null) return 0; // Check for empty tree + int leftDepth = maxDepth(root.left); // Compute depth of left subtree + int rightDepth = maxDepth(root.right); // Compute depth of right subtree + return Math.max(leftDepth, rightDepth) + 1; // Return maximum depth of left and right subtrees, plus 1 for the current node + } + + // Definition for a TreeNode + public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode() {} + TreeNode(int val) { this.val = val; } + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } + } +} +``` + +This implementation follows the steps outlined above and efficiently computes the maximum depth of the binary tree in Java using DFS traversal. \ No newline at end of file diff --git a/src/main/java/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md b/src/main/java/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md index fa4a8b4dc..006bfdd1b 100644 --- a/src/main/java/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md +++ b/src/main/java/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md @@ -26,4 +26,80 @@ Given two integer arrays `preorder` and `inorder` where `preorder` is the preord * `preorder` and `inorder` consist of **unique** values. * Each value of `inorder` also appears in `preorder`. * `preorder` is **guaranteed** to be the preorder traversal of the tree. -* `inorder` is **guaranteed** to be the inorder traversal of the tree. \ No newline at end of file +* `inorder` is **guaranteed** to be the inorder traversal of the tree. + +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: + +1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods. + +2. **Create a `buildTree` method**: This method takes two integer arrays, `preorder` and `inorder`, as input and returns the constructed binary tree. + +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. + +4. **Define a helper method**: Define a recursive helper method `build` to construct the binary tree. + - The method should take the indices representing the current subtree in both `preorder` and `inorder`. + - The start and end indices in `preorder` represent the current subtree's preorder traversal. + - The start and end indices in `inorder` represent the current subtree's inorder traversal. + +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. + +6. **Find the root node**: The root node is the first element in the `preorder` array. + +7. **Find the root's position in `inorder`**: Iterate through the `inorder` array to find the root's position. + +8. **Recursively build left and right subtrees**: + - Recursively call the `build` method for the left subtree with updated indices. + - Recursively call the `build` method for the right subtree with updated indices. + +9. **Return the root node**: After constructing the left and right subtrees, return the root node. + +Here's the Java implementation: + +```java +class Solution { + public TreeNode buildTree(int[] preorder, int[] inorder) { + if (preorder.length == 0 || inorder.length == 0) return null; // Check for empty arrays + return build(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1); // Construct binary tree + } + + // Recursive helper method to construct binary tree + private TreeNode build(int[] preorder, int[] inorder, int preStart, preEnd, int inStart, int inEnd) { + if (preStart > preEnd || inStart > inEnd) return null; // Base case + + int rootValue = preorder[preStart]; // Root node value + TreeNode root = new TreeNode(rootValue); // Create root node + + // Find root node's position in inorder array + int rootIndex = 0; + for (int i = inStart; i <= inEnd; i++) { + if (inorder[i] == rootValue) { + rootIndex = i; + break; + } + } + + // Recursively build left and right subtrees + root.left = build(preorder, inorder, preStart + 1, preStart + rootIndex - inStart, inStart, rootIndex - 1); + root.right = build(preorder, inorder, preStart + rootIndex - inStart + 1, preEnd, rootIndex + 1, inEnd); + + return root; // Return root node + } + + // TreeNode definition + public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode() {} + TreeNode(int val) { this.val = val; } + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } + } +} +``` + +This implementation follows the steps outlined above and efficiently constructs the binary tree from preorder and inorder traversals in Java. \ No newline at end of file diff --git a/src/main/java/g0101_0200/s0114_flatten_binary_tree_to_linked_list/readme.md b/src/main/java/g0101_0200/s0114_flatten_binary_tree_to_linked_list/readme.md index ea101ac1f..1cc08892d 100644 --- a/src/main/java/g0101_0200/s0114_flatten_binary_tree_to_linked_list/readme.md +++ b/src/main/java/g0101_0200/s0114_flatten_binary_tree_to_linked_list/readme.md @@ -32,4 +32,81 @@ Given the `root` of a binary tree, flatten the tree into a "linked list": * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100` -**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)? \ No newline at end of file +**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)? + +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: + +1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods. + +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. + +3. **Check for null root**: Check if the root is null. If so, there's no tree to flatten, so return. + +4. **Recursively flatten the tree**: Define a recursive helper method `flattenTree` to perform the flattening. + - The method should take the current node as input. + - Perform a preorder traversal of the tree. + - For each node, if it has a left child: + - Find the rightmost node in the left subtree. + - Attach the right subtree of the current node to the right of the rightmost node. + - Move the left subtree to the right subtree position. + - Set the left child of the current node to null. + - Recursively call the method for the right child. + +5. **Call the helper method**: Call the `flattenTree` method with the root node. + +Here's the Java implementation: + +```java +class Solution { + public void flatten(TreeNode root) { + if (root == null) return; // Check for empty tree + flattenTree(root); // Flatten the tree + } + + // Recursive helper method to flatten the tree + private void flattenTree(TreeNode node) { + if (node == null) return; + + // Flatten left subtree + flattenTree(node.left); + + // Flatten right subtree + flattenTree(node.right); + + // Save right subtree + TreeNode rightSubtree = node.right; + + // Attach left subtree to the right of the current node + node.right = node.left; + + // Set left child to null + node.left = null; + + // Move to the rightmost node of the flattened left subtree + TreeNode current = node; + while (current.right != null) { + current = current.right; + } + + // Attach the saved right subtree to the right of the rightmost node + current.right = rightSubtree; + } + + // TreeNode definition + public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode() {} + TreeNode(int val) { this.val = val; } + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } + } +} +``` + +This implementation follows the steps outlined above and efficiently flattens the binary tree into a linked list using preorder traversal in Java. \ No newline at end of file diff --git a/src/main/java/g0101_0200/s0121_best_time_to_buy_and_sell_stock/readme.md b/src/main/java/g0101_0200/s0121_best_time_to_buy_and_sell_stock/readme.md index 6e22ccf57..1f99587fe 100644 --- a/src/main/java/g0101_0200/s0121_best_time_to_buy_and_sell_stock/readme.md +++ b/src/main/java/g0101_0200/s0121_best_time_to_buy_and_sell_stock/readme.md @@ -27,4 +27,42 @@ Return _the maximum profit you can achieve from this transaction_. If you cannot **Constraints:** * 1 <= prices.length <= 105 -* 0 <= prices[i] <= 104 \ No newline at end of file +* 0 <= prices[i] <= 104 + +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: + +1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods. + +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. + +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. + +4. **Iterate through the prices array**: + - For each price in the array: + - Update `minPrice` to the minimum of the current price and `minPrice`. + - Update `maxProfit` to the maximum of the current profit (price - `minPrice`) and `maxProfit`. + +5. **Return the maximum profit**: After iterating through the entire array, return `maxProfit`. + +Here's the Java implementation: + +```java +class Solution { + public int maxProfit(int[] prices) { + if (prices == null || prices.length <= 1) return 0; // Check for empty array or single element + + int minPrice = prices[0]; // Initialize minPrice to the first price + int maxProfit = 0; // Initialize maxProfit to 0 + + // Iterate through the prices array + for (int i = 1; i < prices.length; i++) { + minPrice = Math.min(minPrice, prices[i]); // Update minPrice + maxProfit = Math.max(maxProfit, prices[i] - minPrice); // Update maxProfit + } + + return maxProfit; // Return the maximum profit + } +} +``` + +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. \ No newline at end of file diff --git a/src/main/java/g0101_0200/s0124_binary_tree_maximum_path_sum/readme.md b/src/main/java/g0101_0200/s0124_binary_tree_maximum_path_sum/readme.md index 29f9180b2..15f9fe527 100644 --- a/src/main/java/g0101_0200/s0124_binary_tree_maximum_path_sum/readme.md +++ b/src/main/java/g0101_0200/s0124_binary_tree_maximum_path_sum/readme.md @@ -31,4 +31,76 @@ Given the `root` of a binary tree, return _the maximum **path sum** of any **non **Constraints:** * The number of nodes in the tree is in the range [1, 3 * 104]. -* `-1000 <= Node.val <= 1000` \ No newline at end of file +* `-1000 <= Node.val <= 1000` + +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: + +1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods. + +2. **Create a `maxPathSum` method**: This method takes the root node of the binary tree as input and returns the maximum path sum. + +3. **Define a recursive helper method**: Define a recursive helper method `maxSumPath` to compute the maximum path sum rooted at the current node. + - The method should return the maximum path sum that can be obtained from the current node to any of its descendants. + - We'll use a post-order traversal to traverse the tree. + - For each node: + - Compute the maximum path sum for the left and right subtrees recursively. + - Update the maximum path sum by considering three cases: + 1. The current node itself. + 2. The current node plus the maximum path sum of the left subtree. + 3. The current node plus the maximum path sum of the right subtree. + - Update the global maximum path sum if necessary by considering the sum of the current node, left subtree, and right subtree. + +4. **Initialize a variable to store the maximum path sum**: Initialize a global variable `maxSum` to store the maximum path sum. + +5. **Call the helper method**: Call the `maxSumPath` method with the root node. + +6. **Return the maximum path sum**: After traversing the entire tree, return the `maxSum`. + +Here's the Java implementation: + +```java +class Solution { + int maxSum = Integer.MIN_VALUE; // Initialize global variable to store maximum path sum + + public int maxPathSum(TreeNode root) { + maxSumPath(root); + return maxSum; // Return maximum path sum + } + + // Recursive helper method to compute maximum path sum rooted at current node + private int maxSumPath(TreeNode node) { + if (node == null) return 0; // Base case + + // Compute maximum path sum for left and right subtrees recursively + int leftSum = Math.max(maxSumPath(node.left), 0); // Ignore negative sums + int rightSum = Math.max(maxSumPath(node.right), 0); // Ignore negative sums + + // Update maximum path sum by considering three cases: + // 1. Current node itself + // 2. Current node + maximum path sum of left subtree + // 3. Current node + maximum path sum of right subtree + int currentSum = node.val + leftSum + rightSum; + maxSum = Math.max(maxSum, currentSum); // Update global maximum path sum + + // Return the maximum path sum that can be obtained from the current node to any of its descendants + return node.val + Math.max(leftSum, rightSum); + } + + // Definition for a binary tree node + public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode() {} + TreeNode(int val) { this.val = val; } + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } + } +} +``` + +This implementation follows the steps outlined above and efficiently computes the maximum path sum in a binary tree in Java. \ No newline at end of file diff --git a/src/main/java/g0101_0200/s0128_longest_consecutive_sequence/readme.md b/src/main/java/g0101_0200/s0128_longest_consecutive_sequence/readme.md index b5169398a..b22df106c 100644 --- a/src/main/java/g0101_0200/s0128_longest_consecutive_sequence/readme.md +++ b/src/main/java/g0101_0200/s0128_longest_consecutive_sequence/readme.md @@ -23,4 +23,54 @@ You must write an algorithm that runs in `O(n)` time. **Constraints:** * 0 <= nums.length <= 105 -* -109 <= nums[i] <= 109 \ No newline at end of file +* -109 <= nums[i] <= 109 + +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: + +1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods. + +2. **Create a `longestConsecutive` method**: This method takes an array `nums` as input and returns the length of the longest consecutive elements sequence. + +3. **Initialize a HashSet**: Create a HashSet named `numSet` to store all the numbers in the array `nums`. + +4. **Iterate through the array**: Add all the numbers from the array `nums` to the `numSet`. + +5. **Find the longest sequence**: Iterate through the array `nums` again. For each number `num` in the array: + - Check if `num - 1` exists in the `numSet`. If it does not, `num` could be the start of a new sequence. + - 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. + +6. **Return the maximum length**: After iterating through the entire array, return the maximum length of the consecutive sequence. + +Here's the Java implementation: + +```java +import java.util.HashSet; + +class Solution { + public int longestConsecutive(int[] nums) { + HashSet numSet = new HashSet<>(); + for (int num : nums) { + numSet.add(num); // Add all numbers to HashSet + } + + int maxLength = 0; + for (int num : nums) { + if (!numSet.contains(num - 1)) { // Check if num - 1 exists in numSet + int currentNum = num; + int currentLength = 1; + + while (numSet.contains(currentNum + 1)) { // Increment currentNum until it does not exist in numSet + currentNum++; + currentLength++; + } + + maxLength = Math.max(maxLength, currentLength); // Update maximum length + } + } + + return maxLength; // Return the maximum length of the consecutive sequence + } +} +``` + +This implementation follows the steps outlined above and efficiently calculates the length of the longest consecutive elements sequence in Java. \ No newline at end of file diff --git a/src/main/java/g0101_0200/s0131_palindrome_partitioning/readme.md b/src/main/java/g0101_0200/s0131_palindrome_partitioning/readme.md index 450d8798f..7da870e7b 100644 --- a/src/main/java/g0101_0200/s0131_palindrome_partitioning/readme.md +++ b/src/main/java/g0101_0200/s0131_palindrome_partitioning/readme.md @@ -21,4 +21,72 @@ A **palindrome** string is a string that reads the same backward as forward. **Constraints:** * `1 <= s.length <= 16` -* `s` contains only lowercase English letters. \ No newline at end of file +* `s` contains only lowercase English letters. + +To solve the "Palindrome Partitioning" problem in Java with a `Solution` class, we'll use backtracking. Below are the steps: + +1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods. + +2. **Create a `partition` method**: This method takes a string `s` as input and returns all possible palindrome partitioning of `s`. + +3. **Define a recursive helper method**: Define a recursive helper method `backtrack` to find all possible palindrome partitions. + - The method should take the current index `start`, the current partition `partition`, and the list to store all partitions `result`. + - Base case: If `start` reaches the end of the string `s`, add the current partition to the result list and return. + - Iterate from `start` to the end of the string: + - Check if the substring from `start` to `i` is a palindrome. + - If it is a palindrome, add the substring to the current partition and recursively call the `backtrack` method with the updated index and partition. + - After the recursive call, remove the last substring added to the partition to backtrack and explore other partitions. + +4. **Initialize a list to store all partitions**: Create an ArrayList named `result` to store all possible palindrome partitions. + +5. **Call the helper method**: Call the `backtrack` method with the initial index, an empty partition list, and the result list. + +6. **Return the result list**: After exploring all possible partitions, return the list containing all palindrome partitions. + +Here's the Java implementation: + +```java +import java.util.ArrayList; +import java.util.List; + +class Solution { + public List> partition(String s) { + List> result = new ArrayList<>(); + backtrack(s, 0, new ArrayList<>(), result); + return result; + } + + // Recursive helper method to find all possible palindrome partitions + private void backtrack(String s, int start, List partition, List> result) { + if (start == s.length()) { + result.add(new ArrayList<>(partition)); + return; + } + + for (int i = start; i < s.length(); i++) { + String substring = s.substring(start, i + 1); + if (isPalindrome(substring)) { + partition.add(substring); + backtrack(s, i + 1, partition, result); + partition.remove(partition.size() - 1); // Backtrack + } + } + } + + // Helper method to check if a string is a palindrome + private boolean isPalindrome(String s) { + int left = 0; + int right = s.length() - 1; + while (left < right) { + if (s.charAt(left) != s.charAt(right)) { + return false; + } + left++; + right--; + } + return true; + } +} +``` + +This implementation follows the steps outlined above and efficiently finds all possible palindrome partitions of the given string in Java. \ No newline at end of file diff --git a/src/main/java/g0101_0200/s0136_single_number/readme.md b/src/main/java/g0101_0200/s0136_single_number/readme.md index 5f9d3dfca..c8d377bc7 100644 --- a/src/main/java/g0101_0200/s0136_single_number/readme.md +++ b/src/main/java/g0101_0200/s0136_single_number/readme.md @@ -28,4 +28,35 @@ You must implement a solution with a linear runtime complexity and use only cons * 1 <= nums.length <= 3 * 104 * -3 * 104 <= nums[i] <= 3 * 104 -* Each element in the array appears twice except for one element which appears only once. \ No newline at end of file +* Each element in the array appears twice except for one element which appears only once. + +To solve the "Single Number" problem in Java with a `Solution` class, we'll use bitwise XOR operation. Below are the steps: + +1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods. + +2. **Create a `singleNumber` method**: This method takes an array `nums` as input and returns the single number that appears only once. + +3. **Initialize a variable to store the result**: Initialize a variable `singleNumber` to 0. + +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`. + +5. **Return the result**: After iterating through the entire array, the `singleNumber` variable will store the single number that appears only once. Return `singleNumber`. + +Here's the Java implementation: + +```java +class Solution { + public int singleNumber(int[] nums) { + int singleNumber = 0; // Initialize variable to store result + + // Perform bitwise XOR operation on all elements in the array + for (int num : nums) { + singleNumber ^= num; + } + + return singleNumber; // Return the single number + } +} +``` + +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. \ No newline at end of file diff --git a/src/main/java/g0101_0200/s0138_copy_list_with_random_pointer/readme.md b/src/main/java/g0101_0200/s0138_copy_list_with_random_pointer/readme.md index 9e2f93921..4a2316baa 100644 --- a/src/main/java/g0101_0200/s0138_copy_list_with_random_pointer/readme.md +++ b/src/main/java/g0101_0200/s0138_copy_list_with_random_pointer/readme.md @@ -53,4 +53,68 @@ Your code will **only** be given the `head` of the original linked list. * `0 <= n <= 1000` * `-10000 <= Node.val <= 10000` -* `Node.random` is `null` or is pointing to some node in the linked list. \ No newline at end of file +* `Node.random` is `null` or is pointing to some node in the linked list. + +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: + +1. **Create a `Solution` class**: Define a class named `Solution` to encapsulate our solution methods. + +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. + +3. **Initialize a HashMap**: Create a HashMap named `nodeMap` to store the mapping between original nodes and their corresponding copied nodes. + +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: + - Create a new node `copyNode` with the same value as `originalNode`. + - Put the mapping between `originalNode` and `copyNode` in the `nodeMap`. + - Set the `copyNode`'s `next` and `random` pointers accordingly. + - Attach the `copyNode` to the copied linked list. + +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. + +Here's the Java implementation: + +```java +import java.util.HashMap; +import java.util.Map; + +class Solution { + public Node copyRandomList(Node head) { + if (head == null) return null; // Check for empty list + + Map nodeMap = new HashMap<>(); // Initialize HashMap to store mapping between original and copied nodes + + // Create a deep copy of each node in the list + Node current = head; + while (current != null) { + Node copyNode = new Node(current.val); // Create a new copy node + nodeMap.put(current, copyNode); // Put mapping between original and copied nodes in the map + current = current.next; // Move to the next node + } + + // Set the next and random pointers of copied nodes + current = head; + while (current != null) { + Node copyNode = nodeMap.get(current); // Get copied node + copyNode.next = nodeMap.getOrDefault(current.next, null); // Set next pointer + copyNode.random = nodeMap.getOrDefault(current.random, null); // Set random pointer + current = current.next; // Move to the next node + } + + return nodeMap.get(head); // Return the head of the copied linked list + } + + // Definition for a Node + class Node { + int val; + Node next, random; + + Node(int val) { + this.val = val; + this.next = null; + this.random = null; + } + } +} +``` + +This implementation follows the steps outlined above and efficiently constructs a deep copy of the linked list with random pointers in Java. \ No newline at end of file