From c27a427a1f905abc5f2a5d74fd46095c1faddbc4 Mon Sep 17 00:00:00 2001 From: ThanhNIT Date: Tue, 28 Oct 2025 22:01:11 +0700 Subject: [PATCH 01/18] Update readme for tasks 23-49 --- .../s0023_merge_k_sorted_lists/readme.md | 105 +----------------- .../s0024_swap_nodes_in_pairs/readme.md | 69 +++--------- .../s0025_reverse_nodes_in_k_group/readme.md | 89 +-------------- .../readme.md | 18 +-- .../g0001_0100/s0027_remove_element/readme.md | 22 +--- .../readme.md | 32 ++---- .../readme.md | 30 +++-- .../s0031_next_permutation/readme.md | 81 ++------------ .../s0032_longest_valid_parentheses/readme.md | 51 +-------- .../readme.md | 58 +--------- .../readme.md | 70 +----------- .../s0035_search_insert_position/readme.md | 53 +-------- .../s0039_combination_sum/readme.md | 75 +------------ .../s0041_first_missing_positive/readme.md | 63 +++-------- .../s0042_trapping_rain_water/readme.md | 44 +------- .../g0001_0100/s0045_jump_game_ii/readme.md | 44 +------- .../g0001_0100/s0046_permutations/readme.md | 49 +------- .../g0001_0100/s0048_rotate_image/readme.md | 63 +---------- .../g0001_0100/s0049_group_anagrams/readme.md | 66 ++--------- 19 files changed, 122 insertions(+), 960 deletions(-) diff --git a/src/main/java/g0001_0100/s0023_merge_k_sorted_lists/readme.md b/src/main/java/g0001_0100/s0023_merge_k_sorted_lists/readme.md index 3d4409279..0e3754083 100644 --- a/src/main/java/g0001_0100/s0023_merge_k_sorted_lists/readme.md +++ b/src/main/java/g0001_0100/s0023_merge_k_sorted_lists/readme.md @@ -12,7 +12,7 @@ _Merge all the linked-lists into one sorted linked-list and return it._ **Output:** [1,1,2,3,4,4,5,6] -**Explanation:** The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted list: 1->1->2->3->4->4->5->6 +**Explanation:** The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted linked list: 1->1->2->3->4->4->5->6 **Example 2:** @@ -29,105 +29,8 @@ _Merge all the linked-lists into one sorted linked-list and return it._ **Constraints:** * `k == lists.length` -* `0 <= k <= 10^4` +* 0 <= k <= 104 * `0 <= lists[i].length <= 500` -* `-10^4 <= lists[i][j] <= 10^4` +* -104 <= lists[i][j] <= 104 * `lists[i]` is sorted in **ascending order**. -* The sum of `lists[i].length` won't exceed `10^4`. - -To solve the "Merge k Sorted Lists" problem in Java with a `Solution` class, we can use a priority queue (min-heap) to efficiently merge the lists. Here are the steps: - -1. Define a `Solution` class. -2. Define a method named `mergeKLists` that takes an array of linked lists `lists` as input and returns a single sorted linked list. -3. Create a priority queue of ListNode objects. We will use this priority queue to store the heads of each linked list. -4. Iterate through each linked list in the input array `lists` and add the head node of each list to the priority queue. -5. Create a dummy ListNode object to serve as the head of the merged sorted linked list. -6. Initialize a ListNode object named `current` to point to the dummy node. -7. While the priority queue is not empty: - - Remove the ListNode with the smallest value from the priority queue. - - Add this node to the merged linked list by setting the `next` pointer of the `current` node to this node. - - Move the `current` pointer to the next node in the merged linked list. - - If the removed node has a `next` pointer, add the next node from the same list to the priority queue. -8. Return the `next` pointer of the dummy node, which points to the head of the merged sorted linked list. - -Here's the implementation: - -```java -import java.util.PriorityQueue; - -public class Solution { - public ListNode mergeKLists(ListNode[] lists) { - PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a.val - b.val); - - // Add the heads of all lists to the priority queue - for (ListNode node : lists) { - if (node != null) { - minHeap.offer(node); - } - } - - // Create a dummy node to serve as the head of the merged list - ListNode dummy = new ListNode(0); - ListNode current = dummy; - - // Merge the lists - while (!minHeap.isEmpty()) { - ListNode minNode = minHeap.poll(); - current.next = minNode; - current = current.next; - - if (minNode.next != null) { - minHeap.offer(minNode.next); - } - } - - return dummy.next; - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test case - ListNode[] lists = new ListNode[] { - ListNode.createList(new int[] {1, 4, 5}), - ListNode.createList(new int[] {1, 3, 4}), - ListNode.createList(new int[] {2, 6}) - }; - System.out.println("Merged list:"); - ListNode.printList(solution.mergeKLists(lists)); - } -} - -class ListNode { - int val; - ListNode next; - - ListNode(int val) { - this.val = val; - } - - static ListNode createList(int[] arr) { - if (arr == null || arr.length == 0) { - return null; - } - - ListNode dummy = new ListNode(0); - ListNode current = dummy; - for (int num : arr) { - current.next = new ListNode(num); - current = current.next; - } - return dummy.next; - } - - static void printList(ListNode head) { - while (head != null) { - System.out.print(head.val + " "); - head = head.next; - } - System.out.println(); - } -} -``` - -This implementation provides a solution to the "Merge k Sorted Lists" problem in Java using a priority queue. \ No newline at end of file +* The sum of `lists[i].length` will not exceed 104. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0024_swap_nodes_in_pairs/readme.md b/src/main/java/g0001_0100/s0024_swap_nodes_in_pairs/readme.md index 3b760b9f3..e065a07a8 100644 --- a/src/main/java/g0001_0100/s0024_swap_nodes_in_pairs/readme.md +++ b/src/main/java/g0001_0100/s0024_swap_nodes_in_pairs/readme.md @@ -6,74 +6,33 @@ Given a linked list, swap every two adjacent nodes and return its head. You must **Example 1:** -![](https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg) - **Input:** head = [1,2,3,4] -**Output:** [2,1,4,3] +**Output:** [2,1,4,3] + +**Explanation:** + +![](https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg) **Example 2:** **Input:** head = [] -**Output:** [] +**Output:** [] **Example 3:** **Input:** head = [1] -**Output:** [1] +**Output:** [1] + +**Example 4:** + +**Input:** head = [1,2,3] + +**Output:** [2,1,3] **Constraints:** * The number of nodes in the list is in the range `[0, 100]`. -* `0 <= Node.val <= 100` - -To solve the "Swap Nodes in Pairs" problem in Java with a `Solution` class, we can traverse the linked list while swapping pairs of nodes. Here are the steps: - -1. Define a `Solution` class. -2. Define a method named `swapPairs` that takes the head of a linked list as input and returns the head of the modified list. -3. Create a dummy ListNode object and set its `next` pointer to the head of the input list. This dummy node will serve as the new head of the modified list. -4. Initialize three pointers: `prev`, `first`, and `second`. -5. Iterate through the list while `first` and `second` are not null: - - Assign `first` to the `next` pointer of `prev`. - - Assign `second` to the `next` pointer of `first`. - - Assign the `next` pointer of `prev` to the `next` pointer of `second`. - - Assign the `next` pointer of `second` to `first`. - - Move `prev` to `first`. - - Move `first` to `first.next` (which is the next pair of nodes). -6. Return the `next` pointer of the dummy node, which points to the head of the modified list. - -Here's the implementation: - -```java -public class Solution { - public ListNode swapPairs(ListNode head) { - // Create a dummy node and point its next to the head - ListNode dummy = new ListNode(0); - dummy.next = head; - - // Initialize pointers - ListNode prev = dummy; - ListNode first, second; - - // Swap pairs of nodes - while (prev.next != null && prev.next.next != null) { - first = prev.next; - second = first.next; - - // Swap nodes - prev.next = second; - first.next = second.next; - second.next = first; - - // Move prev to the next pair of nodes - prev = first; - } - - return dummy.next; - } -} -``` - -This implementation provides a solution to the "Swap Nodes in Pairs" problem in Java without modifying the values in the list's nodes. \ No newline at end of file +* `0 <= Node.val <= 100` \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0025_reverse_nodes_in_k_group/readme.md b/src/main/java/g0001_0100/s0025_reverse_nodes_in_k_group/readme.md index d20719d93..85c1581db 100644 --- a/src/main/java/g0001_0100/s0025_reverse_nodes_in_k_group/readme.md +++ b/src/main/java/g0001_0100/s0025_reverse_nodes_in_k_group/readme.md @@ -2,9 +2,9 @@ Hard -Given a linked list, reverse the nodes of a linked list _k_ at a time and return its modified list. +Given the `head` of a linked list, reverse the nodes of the list `k` at a time, and return _the modified list_. -_k_ is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of _k_ then left-out nodes, in the end, should remain as it is. +`k` is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of `k` then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed. @@ -24,89 +24,10 @@ You may not alter the values in the list's nodes, only nodes themselves may be c **Output:** [3,2,1,4,5] -**Example 3:** - -**Input:** head = [1,2,3,4,5], k = 1 - -**Output:** [1,2,3,4,5] - -**Example 4:** - -**Input:** head = [1], k = 1 - -**Output:** [1] - **Constraints:** -* The number of nodes in the list is in the range `sz`. -* `1 <= sz <= 5000` +* The number of nodes in the list is `n`. +* `1 <= k <= n <= 5000` * `0 <= Node.val <= 1000` -* `1 <= k <= sz` - -**Follow-up:** Can you solve the problem in O(1) extra memory space? - -To solve the "Reverse Nodes in k-Group" problem in Java with a `Solution` class, we can reverse the nodes in groups of k using a recursive approach. Here are the steps: - -1. Define a `Solution` class. -2. Define a method named `reverseKGroup` that takes the head of a linked list and an integer k as input and returns the head of the modified list. -3. Define a helper method named `reverse` that takes the head and tail of a sublist as input and reverses the sublist in place. This method returns the new head of the sublist. -4. Create a dummy ListNode object and set its `next` pointer to the head of the input list. This dummy node will serve as the new head of the modified list. -5. Initialize pointers `prev`, `curr`, `next`, and `tail`. Set `prev` and `tail` to the dummy node, and `curr` to the head of the input list. -6. Iterate through the list: - - Move `curr` k steps forward. If it's not possible (i.e., there are less than k nodes left), break the loop. - - Set `next` to the `next` pointer of `curr`. - - Reverse the sublist from `curr` to `next` using the `reverse` method. Update `prev` and `tail` accordingly. - - Move `prev` and `tail` k steps forward to the last node of the reversed sublist. - - Move `curr` to `next`. -7. Return the `next` pointer of the dummy node, which points to the head of the modified list. - -Here's the implementation: - -```java -public class Solution { - public ListNode reverseKGroup(ListNode head, int k) { - // Create a dummy node and point its next to the head - ListNode dummy = new ListNode(0); - dummy.next = head; - - // Initialize pointers - ListNode prev = dummy, curr = head, next, tail; - - // Iterate through the list and reverse in groups of k - while (true) { - // Move curr k steps forward - tail = prev; - for (int i = 0; i < k; i++) { - tail = tail.next; - if (tail == null) return dummy.next; // Less than k nodes left - } - - next = tail.next; // Save the next pointer of the sublist - tail.next = null; // Disconnect the sublist from the rest of the list - - // Reverse the sublist and update prev and tail pointers - prev.next = reverse(curr, tail); - tail.next = next; // Connect the reversed sublist back to the rest of the list - - // Move prev, tail, and curr to the next group - prev = curr; - curr = next; - } - } - - // Helper method to reverse a sublist from head to tail - private ListNode reverse(ListNode head, ListNode tail) { - ListNode prev = null, curr = head, next; - while (curr != null) { - next = curr.next; - curr.next = prev; - prev = curr; - curr = next; - if (prev == tail) break; - } - return prev; // Return the new head of the reversed sublist - } -} -``` -This implementation provides a solution to the "Reverse Nodes in k-Group" problem in Java without modifying the values in the list's nodes. It recursively reverses the nodes in groups of k. \ No newline at end of file +**Follow-up:** Can you solve the problem in `O(1)` extra memory space? \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0026_remove_duplicates_from_sorted_array/readme.md b/src/main/java/g0001_0100/s0026_remove_duplicates_from_sorted_array/readme.md index b4e776e2b..0d2adaa8c 100644 --- a/src/main/java/g0001_0100/s0026_remove_duplicates_from_sorted_array/readme.md +++ b/src/main/java/g0001_0100/s0026_remove_duplicates_from_sorted_array/readme.md @@ -4,25 +4,15 @@ Easy Given an integer array `nums` sorted in **non-decreasing order**, remove the duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears only **once**. The **relative order** of the elements should be kept the **same**. -Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements. +Consider the number of _unique elements_ in `nums` to be `k`. After removing duplicates, return the number of unique elements `k`. -Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`. - -Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory. +The first `k` elements of `nums` should contain the unique numbers in **sorted order**. The remaining elements beyond index `k - 1` can be ignored. **Custom Judge:** The judge will test your solution with the following code: - int[] nums = [...]; // Input array - int[] expectedNums = [...]; // The expected answer with correct length - - int k = removeDuplicates(nums); // Calls your implementation - - assert k == expectedNums.length; - for (int i = 0; i < k; i++) { - assert nums[i] == expectedNums[i]; - } +int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass, then your solution will be **accepted**. @@ -44,6 +34,6 @@ If all assertions pass, then your solution will be **accepted**. **Constraints:** -* 0 <= nums.length <= 3 * 104 +* 1 <= nums.length <= 3 * 104 * `-100 <= nums[i] <= 100` * `nums` is sorted in **non-decreasing** order. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0027_remove_element/readme.md b/src/main/java/g0001_0100/s0027_remove_element/readme.md index 027b058d6..a298be443 100644 --- a/src/main/java/g0001_0100/s0027_remove_element/readme.md +++ b/src/main/java/g0001_0100/s0027_remove_element/readme.md @@ -2,30 +2,18 @@ Easy -Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The relative order of the elements may be changed. +Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return _the number of elements in_ `nums` _which are not equal to_ `val`. -Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements. +Consider the number of elements in `nums` which are not equal to `val` be `k`, to get accepted, you need to do the following things: -Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`. - -Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory. +* Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. The remaining elements of `nums` are not important as well as the size of `nums`. +* Return `k`. **Custom Judge:** The judge will test your solution with the following code: - int[] nums = [...]; // Input array - int val = ...; // Value to remove - int[] expectedNums = [...]; // The expected answer with correct length. - // It is sorted with no values equaling val. - - int k = removeElement(nums, val); // Calls your implementation - - assert k == expectedNums.length; - sort(nums, 0, k); // Sort the first k elements of nums - for (int i = 0; i < actualLength; i++) { - assert nums[i] == expectedNums[i]; - } +int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass, then your solution will be **accepted**. diff --git a/src/main/java/g0001_0100/s0028_find_the_index_of_the_first_occurrence_in_a_string/readme.md b/src/main/java/g0001_0100/s0028_find_the_index_of_the_first_occurrence_in_a_string/readme.md index 098bd2485..16b5a75d9 100644 --- a/src/main/java/g0001_0100/s0028_find_the_index_of_the_first_occurrence_in_a_string/readme.md +++ b/src/main/java/g0001_0100/s0028_find_the_index_of_the_first_occurrence_in_a_string/readme.md @@ -1,36 +1,26 @@ -28\. Implement strStr() +28\. Find the Index of the First Occurrence in a String Easy -Implement [strStr()](http://www.cplusplus.com/reference/cstring/strstr/). - -Return the index of the first occurrence of needle in haystack, or `-1` if `needle` is not part of `haystack`. - -**Clarification:** - -What should we return when `needle` is an empty string? This is a great question to ask during an interview. - -For the purpose of this problem, we will return 0 when `needle` is an empty string. This is consistent to C's [strstr()](http://www.cplusplus.com/reference/cstring/strstr/) and Java's [indexOf()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String)). +Given two strings `needle` and `haystack`, return the index of the first occurrence of `needle` in `haystack`, or `-1` if `needle` is not part of `haystack`. **Example 1:** -**Input:** haystack = "hello", needle = "ll" +**Input:** haystack = "sadbutsad", needle = "sad" -**Output:** 2 +**Output:** 0 -**Example 2:** - -**Input:** haystack = "aaaaa", needle = "bba" +**Explanation:** "sad" occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. -**Output:** -1 +**Example 2:** -**Example 3:** +**Input:** haystack = "leetcode", needle = "leeto" -**Input:** haystack = "", needle = "" +**Output:** -1 -**Output:** 0 +**Explanation:** "leeto" did not occur in "leetcode", so we return -1. **Constraints:** -* 0 <= haystack.length, needle.length <= 5 * 104 -* `haystack` and `needle` consist of only lower-case English characters. \ No newline at end of file +* 1 <= haystack.length, needle.length <= 104 +* `haystack` and `needle` consist of only lowercase English characters. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0030_substring_with_concatenation_of_all_words/readme.md b/src/main/java/g0001_0100/s0030_substring_with_concatenation_of_all_words/readme.md index e4075f47a..a288f65e2 100644 --- a/src/main/java/g0001_0100/s0030_substring_with_concatenation_of_all_words/readme.md +++ b/src/main/java/g0001_0100/s0030_substring_with_concatenation_of_all_words/readme.md @@ -2,9 +2,13 @@ Hard -You are given a string `s` and an array of strings `words` of **the same length**. Return all starting indices of substring(s) in `s` that is a concatenation of each word in `words` **exactly once**, **in any order**, and **without any intervening characters**. +You are given a string `s` and an array of strings `words`. All the strings of `words` are of **the same length**. -You can return the answer in **any order**. +A **concatenated string** is a string that exactly contains all the strings of any permutation of `words` concatenated. + +* For example, if `words = ["ab","cd","ef"]`, then `"abcdef"`, `"abefcd"`, `"cdabef"`, `"cdefab"`, `"efabcd"`, and `"efcdab"` are all concatenated strings. `"acdbef"` is not a concatenated string because it is not the concatenation of any permutation of `words`. + +Return an array of _the starting indices_ of all the concatenated substrings in `s`. You can return the answer in **any order**. **Example 1:** @@ -12,24 +16,36 @@ You can return the answer in **any order**. **Output:** [0,9] -**Explanation:** Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively. The output order does not matter, returning [9,0] is fine too. +**Explanation:** + +The substring starting at 0 is `"barfoo"`. It is the concatenation of `["bar","foo"]` which is a permutation of `words`. + The substring starting at 9 is `"foobar"`. It is the concatenation of `["foo","bar"]` which is a permutation of `words`. **Example 2:** **Input:** s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"] -**Output:** [] +**Output:** [] + +**Explanation:** + +There is no concatenated substring. **Example 3:** **Input:** s = "barfoofoobarthefoobarman", words = ["bar","foo","the"] -**Output:** [6,9,12] +**Output:** [6,9,12] + +**Explanation:** + +The substring starting at 6 is `"foobarthe"`. It is the concatenation of `["foo","bar","the"]`. + The substring starting at 9 is `"barthefoo"`. It is the concatenation of `["bar","the","foo"]`. + The substring starting at 12 is `"thefoobar"`. It is the concatenation of `["the","foo","bar"]`. **Constraints:** * 1 <= s.length <= 104 -* `s` consists of lower-case English letters. * `1 <= words.length <= 5000` * `1 <= words[i].length <= 30` -* `words[i]` consists of lower-case English letters. \ No newline at end of file +* `s` and `words[i]` consist of lowercase English letters. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0031_next_permutation/readme.md b/src/main/java/g0001_0100/s0031_next_permutation/readme.md index 8dc4ea508..d375dfd93 100644 --- a/src/main/java/g0001_0100/s0031_next_permutation/readme.md +++ b/src/main/java/g0001_0100/s0031_next_permutation/readme.md @@ -2,9 +2,17 @@ Medium -Implement **next permutation**, which rearranges numbers into the lexicographically next greater permutation of numbers. +A **permutation** of an array of integers is an arrangement of its members into a sequence or linear order. -If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order). +* For example, for `arr = [1,2,3]`, the following are all the permutations of `arr`: `[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]`. + +The **next permutation** of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the **next permutation** of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). + +* For example, the next permutation of `arr = [1,2,3]` is `[1,3,2]`. +* Similarly, the next permutation of `arr = [2,3,1]` is `[3,1,2]`. +* While the next permutation of `arr = [3,2,1]` is `[1,2,3]` because `[3,2,1]` does not have a lexicographical larger rearrangement. + +Given an array of integers `nums`, _find the next permutation of_ `nums`. The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algorithm)** and use only constant extra memory. @@ -26,74 +34,7 @@ The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algor **Output:** [1,5,1] -**Example 4:** - -**Input:** nums = [1] - -**Output:** [1] - **Constraints:** * `1 <= nums.length <= 100` -* `0 <= nums[i] <= 100` - -To solve the "Next Permutation" problem in Java with a `Solution` class, we can follow these steps: - -1. Define a `Solution` class. -2. Define a method named `nextPermutation` that takes an integer array `nums` as input and modifies it to find the next permutation in lexicographic order. -3. Find the first index `i` from the right such that `nums[i] > nums[i - 1]`. If no such index exists, reverse the entire array, as it's already the last permutation. -4. Find the smallest index `j` from the right such that `nums[j] > nums[i - 1]`. -5. Swap `nums[i - 1]` with `nums[j]`. -6. Reverse the suffix of the array starting from index `i`. - -Here's the implementation: - -```java -public class Solution { - public void nextPermutation(int[] nums) { - int n = nums.length; - - // Step 1: Find the first index i from the right such that nums[i] > nums[i - 1] - int i = n - 1; - while (i > 0 && nums[i] <= nums[i - 1]) { - i--; - } - - // Step 2: If no such index exists, reverse the entire array - if (i == 0) { - reverse(nums, 0, n - 1); - return; - } - - // Step 3: Find the smallest index j from the right such that nums[j] > nums[i - 1] - int j = n - 1; - while (nums[j] <= nums[i - 1]) { - j--; - } - - // Step 4: Swap nums[i - 1] with nums[j] - swap(nums, i - 1, j); - - // Step 5: Reverse the suffix of the array starting from index i - reverse(nums, i, n - 1); - } - - // Helper method to reverse a portion of the array - private void reverse(int[] nums, int start, int end) { - while (start < end) { - swap(nums, start, end); - start++; - end--; - } - } - - // Helper method to swap two elements in the array - private void swap(int[] nums, int i, int j) { - int temp = nums[i]; - nums[i] = nums[j]; - nums[j] = temp; - } -} -``` - -This implementation provides a solution to the "Next Permutation" problem in Java. It finds the next lexicographically greater permutation of the given array `nums` and modifies it in place. \ No newline at end of file +* `0 <= nums[i] <= 100` \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0032_longest_valid_parentheses/readme.md b/src/main/java/g0001_0100/s0032_longest_valid_parentheses/readme.md index f39d676e5..ef219b09b 100644 --- a/src/main/java/g0001_0100/s0032_longest_valid_parentheses/readme.md +++ b/src/main/java/g0001_0100/s0032_longest_valid_parentheses/readme.md @@ -2,7 +2,7 @@ Hard -Given a string containing just the characters `'('` and `')'`, find the length of the longest valid (well-formed) parentheses substring. +Given a string containing just the characters `'('` and `')'`, return _the length of the longest valid (well-formed) parentheses_ **substring**. **Example 1:** @@ -29,51 +29,4 @@ Given a string containing just the characters `'('` and `')'`, find the length o **Constraints:** * 0 <= s.length <= 3 * 104 -* `s[i]` is `'('`, or `')'`. - -To solve the "Longest Valid Parentheses" problem in Java with a `Solution` class, we can follow these steps: - -1. Define a `Solution` class. -2. Define a method named `longestValidParentheses` that takes a string `s` as input and returns an integer representing the length of the longest valid parentheses substring. -3. Initialize a stack to store the indices of characters. -4. Initialize a variable `maxLen` to store the maximum length of valid parentheses found so far. -5. Push `-1` onto the stack to mark the starting point of a potential valid substring. -6. Iterate through each character of the string: - - If the character is `'('`, push its index onto the stack. - - If the character is `')'`: - - Pop the top index from the stack. - - If the stack is empty after popping, push the current index onto the stack to mark the starting point of the next potential valid substring. - - Otherwise, update `maxLen` with the maximum of the current `maxLen` and `i - stack.peek()`, where `i` is the current index and `stack.peek()` is the index at the top of the stack. -7. Return `maxLen`. - -Here's the implementation: - -```java -import java.util.Stack; - -public class Solution { - public int longestValidParentheses(String s) { - int maxLen = 0; - Stack stack = new Stack<>(); - stack.push(-1); // Mark the starting point of a potential valid substring - - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (c == '(') { - stack.push(i); - } else { // c == ')' - stack.pop(); - if (stack.isEmpty()) { - stack.push(i); // Mark the starting point of the next potential valid substring - } else { - maxLen = Math.max(maxLen, i - stack.peek()); - } - } - } - - return maxLen; - } -} -``` - -This implementation provides a solution to the "Longest Valid Parentheses" problem in Java. It finds the length of the longest valid parentheses substring in the given string `s`. \ No newline at end of file +* `s[i]` is `'('`, or `')'`. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0033_search_in_rotated_sorted_array/readme.md b/src/main/java/g0001_0100/s0033_search_in_rotated_sorted_array/readme.md index eddc18d75..b93cfed59 100644 --- a/src/main/java/g0001_0100/s0033_search_in_rotated_sorted_array/readme.md +++ b/src/main/java/g0001_0100/s0033_search_in_rotated_sorted_array/readme.md @@ -4,7 +4,7 @@ Medium There is an integer array `nums` sorted in ascending order (with **distinct** values). -Prior to being passed to your function, `nums` is **possibly rotated** at an unknown pivot index `k` (`1 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,5,6,7]` might be rotated at pivot index `3` and become `[4,5,6,7,0,1,2]`. +Prior to being passed to your function, `nums` is **possibly left rotated** at an unknown index `k` (`1 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,5,6,7]` might be left rotated by `3` indices and become `[4,5,6,7,0,1,2]`. Given the array `nums` **after** the possible rotation and an integer `target`, return _the index of_ `target` _if it is in_ `nums`_, or_ `-1` _if it is not in_ `nums`. @@ -34,58 +34,4 @@ You must write an algorithm with `O(log n)` runtime complexity. * -104 <= nums[i] <= 104 * All values of `nums` are **unique**. * `nums` is an ascending array that is possibly rotated. -* -104 <= target <= 104 - -To solve the "Search in Rotated Sorted Array" problem in Java with a `Solution` class, we can follow these steps: - -1. Define a `Solution` class. -2. Define a method named `search` that takes an integer array `nums` and an integer `target` as input and returns an integer representing the index of `target` in `nums`. If `target` is not found, return `-1`. -3. Implement the binary search algorithm to find the index of `target` in the rotated sorted array. -4. Set the left pointer `left` to 0 and the right pointer `right` to the length of `nums` minus 1. -5. While `left` is less than or equal to `right`: - - Calculate the middle index `mid` as `(left + right) / 2`. - - If `nums[mid]` is equal to `target`, return `mid`. - - Check if the left half of the array (`nums[left]` to `nums[mid]`) is sorted: - - If `nums[left] <= nums[mid]` and `nums[left] <= target < nums[mid]`, update `right = mid - 1`. - - Otherwise, update `left = mid + 1`. - - Otherwise, check if the right half of the array (`nums[mid]` to `nums[right]`) is sorted: - - If `nums[mid] <= nums[right]` and `nums[mid] < target <= nums[right]`, update `left = mid + 1`. - - Otherwise, update `right = mid - 1`. -6. If `target` is not found, return `-1`. - -Here's the implementation: - -```java -public class Solution { - public int search(int[] nums, int target) { - int left = 0; - int right = nums.length - 1; - - while (left <= right) { - int mid = left + (right - left) / 2; - - if (nums[mid] == target) { - return mid; - } - - if (nums[left] <= nums[mid]) { - if (nums[left] <= target && target < nums[mid]) { - right = mid - 1; - } else { - left = mid + 1; - } - } else { - if (nums[mid] < target && target <= nums[right]) { - left = mid + 1; - } else { - right = mid - 1; - } - } - } - - return -1; - } -} -``` - -This implementation provides a solution to the "Search in Rotated Sorted Array" problem in Java. It searches for the index of `target` in the rotated sorted array `nums`. The algorithm has a time complexity of O(log n). \ No newline at end of file +* -104 <= target <= 104 \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array/readme.md b/src/main/java/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array/readme.md index 16bdb69dc..7c04eb2ed 100644 --- a/src/main/java/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array/readme.md +++ b/src/main/java/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array/readme.md @@ -31,72 +31,4 @@ You must write an algorithm with `O(log n)` runtime complexity. * 0 <= nums.length <= 105 * -109 <= nums[i] <= 109 * `nums` is a non-decreasing array. -* -109 <= target <= 109 - -To solve the "Find First and Last Position of Element in Sorted Array" problem in Java with a `Solution` class, we can follow these steps: - -1. Define a `Solution` class. -2. Define a method named `searchRange` that takes an integer array `nums` and an integer `target` as input and returns an integer array representing the starting and ending positions of `target` in `nums`. If `target` is not found, return `[-1, -1]`. -3. Implement binary search to find the first and last occurrences of `target`. -4. Set the left pointer `left` to 0 and the right pointer `right` to the length of `nums` minus 1. -5. Initialize two variables `firstOccurrence` and `lastOccurrence` to -1. -6. Perform two binary search operations: - - First, find the first occurrence of `target`: - - While `left` is less than or equal to `right`: - - Calculate the middle index `mid` as `(left + right) / 2`. - - If `nums[mid]` is equal to `target`, update `firstOccurrence = mid` and continue searching on the left half by updating `right = mid - 1`. - - Otherwise, if `target` is less than `nums[mid]`, update `right = mid - 1`. - - Otherwise, update `left = mid + 1`. - - Second, find the last occurrence of `target`: - - Reset `left` to 0 and `right` to the length of `nums` minus 1. - - While `left` is less than or equal to `right`: - - Calculate the middle index `mid` as `(left + right) / 2`. - - If `nums[mid]` is equal to `target`, update `lastOccurrence = mid` and continue searching on the right half by updating `left = mid + 1`. - - Otherwise, if `target` is greater than `nums[mid]`, update `left = mid + 1`. - - Otherwise, update `right = mid - 1`. -7. Return the array `[firstOccurrence, lastOccurrence]`. - -Here's the implementation: - -```java -public class Solution { - public int[] searchRange(int[] nums, int target) { - int left = 0; - int right = nums.length - 1; - int firstOccurrence = -1; - int lastOccurrence = -1; - - // Find first occurrence - while (left <= right) { - int mid = left + (right - left) / 2; - if (nums[mid] == target) { - firstOccurrence = mid; - right = mid - 1; - } else if (target < nums[mid]) { - right = mid - 1; - } else { - left = mid + 1; - } - } - - // Find last occurrence - left = 0; - right = nums.length - 1; - while (left <= right) { - int mid = left + (right - left) / 2; - if (nums[mid] == target) { - lastOccurrence = mid; - left = mid + 1; - } else if (target < nums[mid]) { - right = mid - 1; - } else { - left = mid + 1; - } - } - - return new int[]{firstOccurrence, lastOccurrence}; - } -} -``` - -This implementation provides a solution to the "Find First and Last Position of Element in Sorted Array" problem in Java. It returns the starting and ending positions of `target` in `nums` using binary search, with a time complexity of O(log n). \ No newline at end of file +* -109 <= target <= 109 \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0035_search_insert_position/readme.md b/src/main/java/g0001_0100/s0035_search_insert_position/readme.md index 1de0a7a07..79f9ab2c2 100644 --- a/src/main/java/g0001_0100/s0035_search_insert_position/readme.md +++ b/src/main/java/g0001_0100/s0035_search_insert_position/readme.md @@ -24,60 +24,9 @@ You must write an algorithm with `O(log n)` runtime complexity. **Output:** 4 -**Example 4:** - -**Input:** nums = [1,3,5,6], target = 0 - -**Output:** 0 - -**Example 5:** - -**Input:** nums = [1], target = 0 - -**Output:** 0 - **Constraints:** * 1 <= nums.length <= 104 * -104 <= nums[i] <= 104 * `nums` contains **distinct** values sorted in **ascending** order. -* -104 <= target <= 104 - -To solve the "Search Insert Position" problem in Java with a `Solution` class, we can follow these steps: - -1. Define a `Solution` class. -2. Define a method named `searchInsert` that takes an integer array `nums` and an integer `target` as input and returns an integer representing the index where `target` would be inserted in order. -3. Implement binary search to find the insertion position of `target`. -4. Set the left pointer `left` to 0 and the right pointer `right` to the length of `nums` minus 1. -5. While `left` is less than or equal to `right`: - - Calculate the middle index `mid` as `(left + right) / 2`. - - If `nums[mid]` is equal to `target`, return `mid`. - - If `target` is less than `nums[mid]`, update `right = mid - 1`. - - If `target` is greater than `nums[mid]`, update `left = mid + 1`. -6. If `target` is not found in `nums`, return the value of `left`, which represents the index where `target` would be inserted in order. - -Here's the implementation: - -```java -public class Solution { - public int searchInsert(int[] nums, int target) { - int left = 0; - int right = nums.length - 1; - - while (left <= right) { - int mid = left + (right - left) / 2; - if (nums[mid] == target) { - return mid; - } else if (target < nums[mid]) { - right = mid - 1; - } else { - left = mid + 1; - } - } - - return left; - } -} -``` - -This implementation provides a solution to the "Search Insert Position" problem in Java. It returns the index where `target` would be inserted in `nums` using binary search, with a time complexity of O(log n). \ No newline at end of file +* -104 <= target <= 104 \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0039_combination_sum/readme.md b/src/main/java/g0001_0100/s0039_combination_sum/readme.md index 21570dc8f..c4c869610 100644 --- a/src/main/java/g0001_0100/s0039_combination_sum/readme.md +++ b/src/main/java/g0001_0100/s0039_combination_sum/readme.md @@ -6,7 +6,7 @@ Given an array of **distinct** integers `candidates` and a target integer `targe The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different. -It is **guaranteed** that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. +The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. **Example 1:** @@ -14,11 +14,7 @@ It is **guaranteed** that the number of unique combinations that sum up to `targ **Output:** [[2,2,3],[7]] -**Explanation:** - - 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. - 7 is a candidate, and 7 = 7. - These are the only two combinations. +**Explanation:** 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. **Example 2:** @@ -32,72 +28,9 @@ It is **guaranteed** that the number of unique combinations that sum up to `targ **Output:** [] -**Example 4:** - -**Input:** candidates = [1], target = 1 - -**Output:** [[1]] - -**Example 5:** - -**Input:** candidates = [1], target = 2 - -**Output:** [[1,1]] - **Constraints:** * `1 <= candidates.length <= 30` -* `1 <= candidates[i] <= 200` +* `2 <= candidates[i] <= 40` * All elements of `candidates` are **distinct**. -* `1 <= target <= 500` - -To solve the "Combination Sum" problem in Java with a `Solution` class, we can follow these steps: - -1. Define a `Solution` class. -2. Define a method named `combinationSum` that takes an array of integers `candidates` and an integer `target` as input and returns a list of lists containing all unique combinations of `candidates` where the chosen numbers sum to `target`. -3. Implement backtracking to explore all possible combinations of candidates. -4. Sort the `candidates` array to ensure that duplicates are grouped together. -5. Create a recursive helper method named `backtrack` that takes parameters: - - A list to store the current combination. - - An integer representing the starting index in the `candidates` array. - - The current sum of the combination. -6. In the `backtrack` method: - - If the current sum equals the target, add the current combination to the result list. - - Iterate over the candidates starting from the current index. - - Add the current candidate to the combination. - - Recursively call the `backtrack` method with the updated combination, index, and sum. - - Remove the last added candidate from the combination to backtrack. -7. Call the `backtrack` method with an empty combination list, starting index 0, and sum 0. -8. Return the result list containing all unique combinations. - -Here's the implementation: - -```java -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class Solution { - public List> combinationSum(int[] candidates, int target) { - List> result = new ArrayList<>(); - Arrays.sort(candidates); // Sort the candidates to ensure duplicates are grouped together - backtrack(result, new ArrayList<>(), candidates, target, 0); - return result; - } - - private void backtrack(List> result, List combination, int[] candidates, int target, int start) { - if (target == 0) { - result.add(new ArrayList<>(combination)); - return; - } - - for (int i = start; i < candidates.length && candidates[i] <= target; i++) { - combination.add(candidates[i]); - backtrack(result, combination, candidates, target - candidates[i], i); // Use the same candidate again - combination.remove(combination.size() - 1); // Backtrack by removing the last candidate - } - } -} -``` - -This implementation provides a solution to the "Combination Sum" problem in Java. It explores all possible combinations of candidates using backtracking and returns the unique combinations whose sum equals the target. \ No newline at end of file +* `1 <= target <= 40` \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0041_first_missing_positive/readme.md b/src/main/java/g0001_0100/s0041_first_missing_positive/readme.md index abfc2b245..c786c05c2 100644 --- a/src/main/java/g0001_0100/s0041_first_missing_positive/readme.md +++ b/src/main/java/g0001_0100/s0041_first_missing_positive/readme.md @@ -2,72 +2,35 @@ Hard -Given an unsorted integer array `nums`, return the smallest missing positive integer. +Given an unsorted integer array `nums`. Return the _smallest positive integer_ that is _not present_ in `nums`. -You must implement an algorithm that runs in `O(n)` time and uses constant extra space. +You must implement an algorithm that runs in `O(n)` time and uses `O(1)` auxiliary space. **Example 1:** **Input:** nums = [1,2,0] -**Output:** 3 +**Output:** 3 + +**Explanation:** The numbers in the range [1,2] are all in the array. **Example 2:** **Input:** nums = [3,4,-1,1] -**Output:** 2 +**Output:** 2 + +**Explanation:** 1 is in the array but 2 is missing. **Example 3:** **Input:** nums = [7,8,9,11,12] -**Output:** 1 +**Output:** 1 + +**Explanation:** The smallest positive integer 1 is missing. **Constraints:** -* 1 <= nums.length <= 5 * 105 -* -231 <= nums[i] <= 231 - 1 - -To solve the "First Missing Positive" problem in Java with a `Solution` class, we can follow these steps: - -1. Define a `Solution` class. -2. Define a method named `firstMissingPositive` that takes an array of integers `nums` as input and returns the smallest missing positive integer. -3. Iterate through the array and mark the positive integers found by negating the value at the corresponding index. -4. Iterate through the modified array again and return the index of the first positive number (which is the smallest missing positive integer). -5. If no positive number is found, return `nums.length + 1`. - -Here's the implementation: - -```java -public class Solution { - public int firstMissingPositive(int[] nums) { - int n = nums.length; - - // Mark positive integers found by negating the value at the corresponding index - for (int i = 0; i < n; i++) { - if (nums[i] > 0 && nums[i] <= n) { - int pos = nums[i] - 1; - if (nums[pos] != nums[i]) { - int temp = nums[pos]; - nums[pos] = nums[i]; - nums[i] = temp; - i--; // Revisit the swapped number - } - } - } - - // Find the first positive number (smallest missing positive integer) - for (int i = 0; i < n; i++) { - if (nums[i] != i + 1) { - return i + 1; - } - } - - // If no positive number is found, return nums.length + 1 - return n + 1; - } -} -``` - -This implementation provides a solution to the "First Missing Positive" problem in Java. It marks positive integers found by negating the value at the corresponding index and then iterates through the modified array to find the smallest missing positive integer. If no positive number is found, it returns `nums.length + 1`. \ No newline at end of file +* 1 <= nums.length <= 105 +* -231 <= nums[i] <= 231 - 1 \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0042_trapping_rain_water/readme.md b/src/main/java/g0001_0100/s0042_trapping_rain_water/readme.md index 2e839c06a..b57de86dd 100644 --- a/src/main/java/g0001_0100/s0042_trapping_rain_water/readme.md +++ b/src/main/java/g0001_0100/s0042_trapping_rain_water/readme.md @@ -24,46 +24,4 @@ Given `n` non-negative integers representing an elevation map where the width of * `n == height.length` * 1 <= n <= 2 * 104 -* 0 <= height[i] <= 105 - -To solve the "Trapping Rain Water" problem in Java with a `Solution` class, we can follow these steps: - -1. Define a `Solution` class. -2. Define a method named `trap` that takes an array of integers `height` as input and returns the amount of water it can trap after raining. -3. Initialize two pointers `left` and `right` at the beginning and end of the array respectively. -4. Initialize two variables `leftMax` and `rightMax` to keep track of the maximum height of bars encountered from the left and right directions respectively. -5. Iterate through the array using the two pointers: - - Update `leftMax` as the maximum of `leftMax` and `height[left]`. - - Update `rightMax` as the maximum of `rightMax` and `height[right]`. - - If `height[left] < height[right]`, calculate the water trapped at the current position using `leftMax` and subtract the height of the current bar. Move `left` pointer to the right. - - Otherwise, calculate the water trapped at the current position using `rightMax` and subtract the height of the current bar. Move `right` pointer to the left. -6. Continue this process until the two pointers meet. -7. Return the total amount of water trapped. - -Here's the implementation: - -```java -public class Solution { - public int trap(int[] height) { - int left = 0, right = height.length - 1; - int leftMax = 0, rightMax = 0; - int trappedWater = 0; - - while (left < right) { - if (height[left] < height[right]) { - leftMax = Math.max(leftMax, height[left]); - trappedWater += leftMax - height[left]; - left++; - } else { - rightMax = Math.max(rightMax, height[right]); - trappedWater += rightMax - height[right]; - right--; - } - } - - return trappedWater; - } -} -``` - -This implementation provides a solution to the "Trapping Rain Water" problem in Java. It calculates the amount of water that can be trapped between bars by using two pointers to track the left and right boundaries and two variables to track the maximum heights of bars encountered from the left and right directions. \ No newline at end of file +* 0 <= height[i] <= 105 \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0045_jump_game_ii/readme.md b/src/main/java/g0001_0100/s0045_jump_game_ii/readme.md index db8fa23af..e2c3be086 100644 --- a/src/main/java/g0001_0100/s0045_jump_game_ii/readme.md +++ b/src/main/java/g0001_0100/s0045_jump_game_ii/readme.md @@ -2,13 +2,14 @@ Medium -Given an array of non-negative integers `nums`, you are initially positioned at the first index of the array. +You are given a **0-indexed** array of integers `nums` of length `n`. You are initially positioned at index 0. -Each element in the array represents your maximum jump length at that position. +Each element `nums[i]` represents the maximum length of a forward jump from index `i`. In other words, if you are at index `i`, you can jump to any index `(i + j)` where: -Your goal is to reach the last index in the minimum number of jumps. +* `0 <= j <= nums[i]` and +* `i + j < n` -You can assume that you can always reach the last index. +Return _the minimum number of jumps to reach index_ `n - 1`. The test cases are generated such that you can reach index `n - 1`. **Example 1:** @@ -28,37 +29,4 @@ You can assume that you can always reach the last index. * 1 <= nums.length <= 104 * `0 <= nums[i] <= 1000` - -To solve the "Jump Game II" problem in Java with a `Solution` class, we can follow these steps: - -1. Define a `Solution` class. -2. Define a method named `jump` that takes an array of non-negative integers `nums` as input and returns the minimum number of jumps required to reach the last index. -3. Initialize variables `maxReach`, `steps`, and `end` to keep track of the maximum reachable position, the number of steps taken, and the end position respectively. Initialize `maxReach` to 0 and `end` to 0. -4. Iterate through the array from index 0 to `nums.length - 2`: - - Update `maxReach` as the maximum of `maxReach` and `i + nums[i]`. - - If the current index `i` equals `end`, update `end` to `maxReach` and increment `steps`. -5. Return `steps`. - -Here's the implementation: - -```java -public class Solution { - public int jump(int[] nums) { - int maxReach = 0; - int steps = 0; - int end = 0; - - for (int i = 0; i < nums.length - 1; i++) { - maxReach = Math.max(maxReach, i + nums[i]); - if (i == end) { - end = maxReach; - steps++; - } - } - - return steps; - } -} -``` - -This implementation provides a solution to the "Jump Game II" problem in Java. It calculates the minimum number of jumps required to reach the last index by iterating through the array and updating the maximum reachable position and the end position accordingly. \ No newline at end of file +* It's guaranteed that you can reach `nums[n - 1]`. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0046_permutations/readme.md b/src/main/java/g0001_0100/s0046_permutations/readme.md index 49b6db09a..f66dc4f2c 100644 --- a/src/main/java/g0001_0100/s0046_permutations/readme.md +++ b/src/main/java/g0001_0100/s0046_permutations/readme.md @@ -2,7 +2,7 @@ Medium -Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**. +Given an array `nums` of distinct integers, return all the possible permutations. You can return the answer in **any order**. **Example 1:** @@ -26,49 +26,4 @@ Given an array `nums` of distinct integers, return _all the possible permutation * `1 <= nums.length <= 6` * `-10 <= nums[i] <= 10` -* All the integers of `nums` are **unique**. - -To solve the "Permutations" problem in Java with a `Solution` class, we can follow these steps: - -1. Define a `Solution` class. -2. Define a method named `permute` that takes an array of distinct integers `nums` as input and returns a list of all possible permutations. -3. Create an empty list to store the result permutations. -4. Call a recursive helper function named `permuteHelper` to generate permutations. -5. Inside the `permuteHelper` function: - - If the current permutation size equals the length of the input array `nums`, add a copy of the current permutation to the result list. - - Otherwise, iterate through each element of `nums`: - - If the current element is not already in the permutation, add it to the current permutation, and recursively call `permuteHelper` with the updated permutation and the remaining elements of `nums`. - - After the recursive call, remove the last element from the permutation to backtrack. -6. Return the result list. - -Here's the implementation: - -```java -import java.util.ArrayList; -import java.util.List; - -public class Solution { - public List> permute(int[] nums) { - List> result = new ArrayList<>(); - permuteHelper(nums, new ArrayList<>(), result); - return result; - } - - private void permuteHelper(int[] nums, List current, List> result) { - if (current.size() == nums.length) { - result.add(new ArrayList<>(current)); - return; - } - - for (int num : nums) { - if (!current.contains(num)) { - current.add(num); - permuteHelper(nums, current, result); - current.remove(current.size() - 1); - } - } - } -} -``` - -This implementation provides a solution to the "Permutations" problem in Java. It generates all possible permutations of the given array of distinct integers using backtracking. \ No newline at end of file +* All the integers of `nums` are **unique**. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0048_rotate_image/readme.md b/src/main/java/g0001_0100/s0048_rotate_image/readme.md index 9c58ae342..3798319b9 100644 --- a/src/main/java/g0001_0100/s0048_rotate_image/readme.md +++ b/src/main/java/g0001_0100/s0048_rotate_image/readme.md @@ -22,67 +22,8 @@ You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-pla **Output:** [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] -**Example 3:** - -**Input:** matrix = [[1]] - -**Output:** [[1]] - -**Example 4:** - -**Input:** matrix = [[1,2],[3,4]] - -**Output:** [[3,1],[4,2]] - **Constraints:** -* `matrix.length == n` -* `matrix[i].length == n` +* `n == matrix.length == matrix[i].length` * `1 <= n <= 20` -* `-1000 <= matrix[i][j] <= 1000` - -To solve the "Rotate Image" problem in Java with a `Solution` class, we can follow these steps: - -1. Define a `Solution` class. -2. Define a method named `rotate` that takes a 2D array `matrix` representing an image as input and rotates the image by 90 degrees clockwise. -3. Determine the number of layers in the matrix, which is equal to half of the matrix's size. -4. Iterate through each layer from outer to inner layers. -5. For each layer: - - Iterate through each element in the current layer. - - Swap the elements of the current layer in a clockwise manner. -6. Return the rotated matrix. - -Here's the implementation: - -```java -public class Solution { - public void rotate(int[][] matrix) { - int n = matrix.length; - int layers = n / 2; - - for (int layer = 0; layer < layers; layer++) { - int first = layer; - int last = n - 1 - layer; - - for (int i = first; i < last; i++) { - int offset = i - first; - int top = matrix[first][i]; - - // Move left to top - matrix[first][i] = matrix[last - offset][first]; - - // Move bottom to left - matrix[last - offset][first] = matrix[last][last - offset]; - - // Move right to bottom - matrix[last][last - offset] = matrix[i][last]; - - // Move top to right - matrix[i][last] = top; - } - } - } -} -``` - -This implementation provides a solution to the "Rotate Image" problem in Java. It rotates the given 2D matrix representing an image by 90 degrees clockwise in-place. +* `-1000 <= matrix[i][j] <= 1000` \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0049_group_anagrams/readme.md b/src/main/java/g0001_0100/s0049_group_anagrams/readme.md index 163c68ac0..988d84dbb 100644 --- a/src/main/java/g0001_0100/s0049_group_anagrams/readme.md +++ b/src/main/java/g0001_0100/s0049_group_anagrams/readme.md @@ -2,78 +2,34 @@ Medium -Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**. - -An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. +Given an array of strings `strs`, group the anagrams together. You can return the answer in **any order**. **Example 1:** **Input:** strs = ["eat","tea","tan","ate","nat","bat"] -**Output:** [["bat"],["nat","tan"],["ate","eat","tea"]] +**Output:** [["bat"],["nat","tan"],["ate","eat","tea"]] + +**Explanation:** + +* There is no string in strs that can be rearranged to form `"bat"`. +* The strings `"nat"` and `"tan"` are anagrams as they can be rearranged to form each other. +* The strings `"ate"`, `"eat"`, and `"tea"` are anagrams as they can be rearranged to form each other. **Example 2:** **Input:** strs = [""] -**Output:** [[""]] +**Output:** [[""]] **Example 3:** **Input:** strs = ["a"] -**Output:** [["a"]] +**Output:** [["a"]] **Constraints:** * 1 <= strs.length <= 104 * `0 <= strs[i].length <= 100` -* `strs[i]` consists of lowercase English letters. - -To solve the "Group Anagrams" problem in Java with the Solution class, follow these steps: - -1. Define a method `groupAnagrams` in the `Solution` class that takes an array of strings `strs` as input and returns a list of lists of strings. -2. Initialize an empty HashMap to store the groups of anagrams. The key will be the sorted string, and the value will be a list of strings. -3. Iterate through each string `str` in the input array `strs`. -4. Sort the characters of the current string `str` to create a key for the HashMap. -5. Check if the sorted string exists as a key in the HashMap: - - If it does, add the original string `str` to the corresponding list of strings. - - If it doesn't, create a new entry in the HashMap with the sorted string as the key and a new list containing `str` as the value. -6. After iterating through all strings, return the values of the HashMap as the result. - -Here's the implementation of the `groupAnagrams` method in Java: - -```java -import java.util.*; - -class Solution { - public List> groupAnagrams(String[] strs) { - // Initialize a HashMap to store the groups of anagrams - Map> anagramGroups = new HashMap<>(); - - // Iterate through each string in the input array - for (String str : strs) { - // Sort the characters of the current string - char[] chars = str.toCharArray(); - Arrays.sort(chars); - String sortedStr = new String(chars); - - // Check if the sorted string exists as a key in the HashMap - if (anagramGroups.containsKey(sortedStr)) { - // If it does, add the original string to the corresponding list - anagramGroups.get(sortedStr).add(str); - } else { - // If it doesn't, create a new entry in the HashMap - List group = new ArrayList<>(); - group.add(str); - anagramGroups.put(sortedStr, group); - } - } - - // Return the values of the HashMap as the result - return new ArrayList<>(anagramGroups.values()); - } -} -``` - -This implementation ensures that all anagrams are grouped together efficiently using a HashMap. \ No newline at end of file +* `strs[i]` consists of lowercase English letters. \ No newline at end of file From 53b3ca025ba3c397172fe2b16105580dd9fea1e5 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:13:12 +0200 Subject: [PATCH 02/18] Update README with merge k sorted lists solution Added detailed explanation and implementation for merging k sorted lists using a priority queue. --- .../s0023_merge_k_sorted_lists/readme.md | 99 ++++++++++++++++++- 1 file changed, 98 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0023_merge_k_sorted_lists/readme.md b/src/main/java/g0001_0100/s0023_merge_k_sorted_lists/readme.md index 0e3754083..a96a7d090 100644 --- a/src/main/java/g0001_0100/s0023_merge_k_sorted_lists/readme.md +++ b/src/main/java/g0001_0100/s0023_merge_k_sorted_lists/readme.md @@ -33,4 +33,101 @@ _Merge all the linked-lists into one sorted linked-list and return it._ * `0 <= lists[i].length <= 500` * -104 <= lists[i][j] <= 104 * `lists[i]` is sorted in **ascending order**. -* The sum of `lists[i].length` will not exceed 104. \ No newline at end of file +* The sum of `lists[i].length` will not exceed 104. + +To solve the "Merge k Sorted Lists" problem in Java with a `Solution` class, we can use a priority queue (min-heap) to efficiently merge the lists. Here are the steps: + +1. Define a `Solution` class. +2. Define a method named `mergeKLists` that takes an array of linked lists `lists` as input and returns a single sorted linked list. +3. Create a priority queue of ListNode objects. We will use this priority queue to store the heads of each linked list. +4. Iterate through each linked list in the input array `lists` and add the head node of each list to the priority queue. +5. Create a dummy ListNode object to serve as the head of the merged sorted linked list. +6. Initialize a ListNode object named `current` to point to the dummy node. +7. While the priority queue is not empty: + - Remove the ListNode with the smallest value from the priority queue. + - Add this node to the merged linked list by setting the `next` pointer of the `current` node to this node. + - Move the `current` pointer to the next node in the merged linked list. + - If the removed node has a `next` pointer, add the next node from the same list to the priority queue. +8. Return the `next` pointer of the dummy node, which points to the head of the merged sorted linked list. + +Here's the implementation: + +```java +import java.util.PriorityQueue; + +public class Solution { + public ListNode mergeKLists(ListNode[] lists) { + PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a.val - b.val); + + // Add the heads of all lists to the priority queue + for (ListNode node : lists) { + if (node != null) { + minHeap.offer(node); + } + } + + // Create a dummy node to serve as the head of the merged list + ListNode dummy = new ListNode(0); + ListNode current = dummy; + + // Merge the lists + while (!minHeap.isEmpty()) { + ListNode minNode = minHeap.poll(); + current.next = minNode; + current = current.next; + + if (minNode.next != null) { + minHeap.offer(minNode.next); + } + } + + return dummy.next; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test case + ListNode[] lists = new ListNode[] { + ListNode.createList(new int[] {1, 4, 5}), + ListNode.createList(new int[] {1, 3, 4}), + ListNode.createList(new int[] {2, 6}) + }; + System.out.println("Merged list:"); + ListNode.printList(solution.mergeKLists(lists)); + } +} + +class ListNode { + int val; + ListNode next; + + ListNode(int val) { + this.val = val; + } + + static ListNode createList(int[] arr) { + if (arr == null || arr.length == 0) { + return null; + } + + ListNode dummy = new ListNode(0); + ListNode current = dummy; + for (int num : arr) { + current.next = new ListNode(num); + current = current.next; + } + return dummy.next; + } + + static void printList(ListNode head) { + while (head != null) { + System.out.print(head.val + " "); + head = head.next; + } + System.out.println(); + } +} +``` + +This implementation provides a solution to the "Merge k Sorted Lists" problem in Java using a priority queue. From a4c0dee02c26c01a8af59cfae09c5ef1cb6a68b4 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:14:25 +0200 Subject: [PATCH 03/18] Update README with 'Swap Nodes in Pairs' solution Added a detailed explanation and implementation for the 'Swap Nodes in Pairs' problem in Java to the README file. --- .../s0024_swap_nodes_in_pairs/readme.md | 51 ++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0024_swap_nodes_in_pairs/readme.md b/src/main/java/g0001_0100/s0024_swap_nodes_in_pairs/readme.md index e065a07a8..9a33becba 100644 --- a/src/main/java/g0001_0100/s0024_swap_nodes_in_pairs/readme.md +++ b/src/main/java/g0001_0100/s0024_swap_nodes_in_pairs/readme.md @@ -35,4 +35,53 @@ Given a linked list, swap every two adjacent nodes and return its head. You must **Constraints:** * The number of nodes in the list is in the range `[0, 100]`. -* `0 <= Node.val <= 100` \ No newline at end of file +* `0 <= Node.val <= 100` + +To solve the "Swap Nodes in Pairs" problem in Java with a `Solution` class, we can traverse the linked list while swapping pairs of nodes. Here are the steps: + +1. Define a `Solution` class. +2. Define a method named `swapPairs` that takes the head of a linked list as input and returns the head of the modified list. +3. Create a dummy ListNode object and set its `next` pointer to the head of the input list. This dummy node will serve as the new head of the modified list. +4. Initialize three pointers: `prev`, `first`, and `second`. +5. Iterate through the list while `first` and `second` are not null: + - Assign `first` to the `next` pointer of `prev`. + - Assign `second` to the `next` pointer of `first`. + - Assign the `next` pointer of `prev` to the `next` pointer of `second`. + - Assign the `next` pointer of `second` to `first`. + - Move `prev` to `first`. + - Move `first` to `first.next` (which is the next pair of nodes). +6. Return the `next` pointer of the dummy node, which points to the head of the modified list. + +Here's the implementation: + +```java +public class Solution { + public ListNode swapPairs(ListNode head) { + // Create a dummy node and point its next to the head + ListNode dummy = new ListNode(0); + dummy.next = head; + + // Initialize pointers + ListNode prev = dummy; + ListNode first, second; + + // Swap pairs of nodes + while (prev.next != null && prev.next.next != null) { + first = prev.next; + second = first.next; + + // Swap nodes + prev.next = second; + first.next = second.next; + second.next = first; + + // Move prev to the next pair of nodes + prev = first; + } + + return dummy.next; + } +} +``` + +This implementation provides a solution to the "Swap Nodes in Pairs" problem in Java without modifying the values in the list's nodes. From 6faa290aedefa69249e26969e48dbcdb45767518 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:16:51 +0200 Subject: [PATCH 04/18] Added task explanation --- .../s0025_reverse_nodes_in_k_group/readme.md | 68 ++++++++++++++++++- 1 file changed, 67 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0025_reverse_nodes_in_k_group/readme.md b/src/main/java/g0001_0100/s0025_reverse_nodes_in_k_group/readme.md index 85c1581db..5740b8cd6 100644 --- a/src/main/java/g0001_0100/s0025_reverse_nodes_in_k_group/readme.md +++ b/src/main/java/g0001_0100/s0025_reverse_nodes_in_k_group/readme.md @@ -30,4 +30,70 @@ You may not alter the values in the list's nodes, only nodes themselves may be c * `1 <= k <= n <= 5000` * `0 <= Node.val <= 1000` -**Follow-up:** Can you solve the problem in `O(1)` extra memory space? \ No newline at end of file +**Follow-up:** Can you solve the problem in `O(1)` extra memory space? + +To solve the "Reverse Nodes in k-Group" problem in Java with a `Solution` class, we can reverse the nodes in groups of k using a recursive approach. Here are the steps: + +1. Define a `Solution` class. +2. Define a method named `reverseKGroup` that takes the head of a linked list and an integer k as input and returns the head of the modified list. +3. Define a helper method named `reverse` that takes the head and tail of a sublist as input and reverses the sublist in place. This method returns the new head of the sublist. +4. Create a dummy ListNode object and set its `next` pointer to the head of the input list. This dummy node will serve as the new head of the modified list. +5. Initialize pointers `prev`, `curr`, `next`, and `tail`. Set `prev` and `tail` to the dummy node, and `curr` to the head of the input list. +6. Iterate through the list: + - Move `curr` k steps forward. If it's not possible (i.e., there are less than k nodes left), break the loop. + - Set `next` to the `next` pointer of `curr`. + - Reverse the sublist from `curr` to `next` using the `reverse` method. Update `prev` and `tail` accordingly. + - Move `prev` and `tail` k steps forward to the last node of the reversed sublist. + - Move `curr` to `next`. +7. Return the `next` pointer of the dummy node, which points to the head of the modified list. + +Here's the implementation: + +```java +public class Solution { + public ListNode reverseKGroup(ListNode head, int k) { + // Create a dummy node and point its next to the head + ListNode dummy = new ListNode(0); + dummy.next = head; + + // Initialize pointers + ListNode prev = dummy, curr = head, next, tail; + + // Iterate through the list and reverse in groups of k + while (true) { + // Move curr k steps forward + tail = prev; + for (int i = 0; i < k; i++) { + tail = tail.next; + if (tail == null) return dummy.next; // Less than k nodes left + } + + next = tail.next; // Save the next pointer of the sublist + tail.next = null; // Disconnect the sublist from the rest of the list + + // Reverse the sublist and update prev and tail pointers + prev.next = reverse(curr, tail); + tail.next = next; // Connect the reversed sublist back to the rest of the list + + // Move prev, tail, and curr to the next group + prev = curr; + curr = next; + } + } + + // Helper method to reverse a sublist from head to tail + private ListNode reverse(ListNode head, ListNode tail) { + ListNode prev = null, curr = head, next; + while (curr != null) { + next = curr.next; + curr.next = prev; + prev = curr; + curr = next; + if (prev == tail) break; + } + return prev; // Return the new head of the reversed sublist + } +} +``` + +This implementation provides a solution to the "Reverse Nodes in k-Group" problem in Java without modifying the values in the list's nodes. It recursively reverses the nodes in groups of k. From 2ca7d7549a202613e4629814be157944003eb5e4 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:18:04 +0200 Subject: [PATCH 05/18] Improve formatting of example code in readme Formatted the example code for better readability. --- .../g0001_0100/s0027_remove_element/readme.md | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/main/java/g0001_0100/s0027_remove_element/readme.md b/src/main/java/g0001_0100/s0027_remove_element/readme.md index a298be443..a0baa21ba 100644 --- a/src/main/java/g0001_0100/s0027_remove_element/readme.md +++ b/src/main/java/g0001_0100/s0027_remove_element/readme.md @@ -13,7 +13,18 @@ Consider the number of elements in `nums` which are not equal to `val` be `k`, t The judge will test your solution with the following code: -int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums[i] == expectedNums[i]; } + int[] nums = [...]; // Input array + int val = ...; // Value to remove + int[] expectedNums = [...]; // The expected answer with correct length. + // It is sorted with no values equaling val. + + int k = removeElement(nums, val); // Calls your implementation + + assert k == expectedNums.length; + sort(nums, 0, k); // Sort the first k elements of nums + for (int i = 0; i < actualLength; i++) { + assert nums[i] == expectedNums[i]; + } If all assertions pass, then your solution will be **accepted**. @@ -37,4 +48,4 @@ If all assertions pass, then your solution will be **accepted**. * `0 <= nums.length <= 100` * `0 <= nums[i] <= 50` -* `0 <= val <= 100` \ No newline at end of file +* `0 <= val <= 100` From bf2a2a516f6ae4e5582c904b0a8eb34fbc7b22b0 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:19:50 +0200 Subject: [PATCH 06/18] Update README with 'Next Permutation' solution Added detailed explanation and implementation for the 'Next Permutation' problem in Java. --- .../s0031_next_permutation/readme.md | 63 ++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0031_next_permutation/readme.md b/src/main/java/g0001_0100/s0031_next_permutation/readme.md index d375dfd93..ceb7d0b9a 100644 --- a/src/main/java/g0001_0100/s0031_next_permutation/readme.md +++ b/src/main/java/g0001_0100/s0031_next_permutation/readme.md @@ -37,4 +37,65 @@ The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algor **Constraints:** * `1 <= nums.length <= 100` -* `0 <= nums[i] <= 100` \ No newline at end of file +* `0 <= nums[i] <= 100` + +To solve the "Next Permutation" problem in Java with a `Solution` class, we can follow these steps: + +1. Define a `Solution` class. +2. Define a method named `nextPermutation` that takes an integer array `nums` as input and modifies it to find the next permutation in lexicographic order. +3. Find the first index `i` from the right such that `nums[i] > nums[i - 1]`. If no such index exists, reverse the entire array, as it's already the last permutation. +4. Find the smallest index `j` from the right such that `nums[j] > nums[i - 1]`. +5. Swap `nums[i - 1]` with `nums[j]`. +6. Reverse the suffix of the array starting from index `i`. + +Here's the implementation: + +```java +public class Solution { + public void nextPermutation(int[] nums) { + int n = nums.length; + + // Step 1: Find the first index i from the right such that nums[i] > nums[i - 1] + int i = n - 1; + while (i > 0 && nums[i] <= nums[i - 1]) { + i--; + } + + // Step 2: If no such index exists, reverse the entire array + if (i == 0) { + reverse(nums, 0, n - 1); + return; + } + + // Step 3: Find the smallest index j from the right such that nums[j] > nums[i - 1] + int j = n - 1; + while (nums[j] <= nums[i - 1]) { + j--; + } + + // Step 4: Swap nums[i - 1] with nums[j] + swap(nums, i - 1, j); + + // Step 5: Reverse the suffix of the array starting from index i + reverse(nums, i, n - 1); + } + + // Helper method to reverse a portion of the array + private void reverse(int[] nums, int start, int end) { + while (start < end) { + swap(nums, start, end); + start++; + end--; + } + } + + // Helper method to swap two elements in the array + private void swap(int[] nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} +``` + +This implementation provides a solution to the "Next Permutation" problem in Java. It finds the next lexicographically greater permutation of the given array `nums` and modifies it in place. From 36d276dc6c1c05f5d7d757ad2c98351ac6e184af Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:20:44 +0200 Subject: [PATCH 07/18] Update readme with Longest Valid Parentheses solution Added a detailed explanation and implementation for the Longest Valid Parentheses problem in Java. --- .../s0032_longest_valid_parentheses/readme.md | 49 ++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0032_longest_valid_parentheses/readme.md b/src/main/java/g0001_0100/s0032_longest_valid_parentheses/readme.md index ef219b09b..4f7ba516e 100644 --- a/src/main/java/g0001_0100/s0032_longest_valid_parentheses/readme.md +++ b/src/main/java/g0001_0100/s0032_longest_valid_parentheses/readme.md @@ -29,4 +29,51 @@ Given a string containing just the characters `'('` and `')'`, return _the lengt **Constraints:** * 0 <= s.length <= 3 * 104 -* `s[i]` is `'('`, or `')'`. \ No newline at end of file +* `s[i]` is `'('`, or `')'`. + +To solve the "Longest Valid Parentheses" problem in Java with a `Solution` class, we can follow these steps: + +1. Define a `Solution` class. +2. Define a method named `longestValidParentheses` that takes a string `s` as input and returns an integer representing the length of the longest valid parentheses substring. +3. Initialize a stack to store the indices of characters. +4. Initialize a variable `maxLen` to store the maximum length of valid parentheses found so far. +5. Push `-1` onto the stack to mark the starting point of a potential valid substring. +6. Iterate through each character of the string: + - If the character is `'('`, push its index onto the stack. + - If the character is `')'`: + - Pop the top index from the stack. + - If the stack is empty after popping, push the current index onto the stack to mark the starting point of the next potential valid substring. + - Otherwise, update `maxLen` with the maximum of the current `maxLen` and `i - stack.peek()`, where `i` is the current index and `stack.peek()` is the index at the top of the stack. +7. Return `maxLen`. + +Here's the implementation: + +```java +import java.util.Stack; + +public class Solution { + public int longestValidParentheses(String s) { + int maxLen = 0; + Stack stack = new Stack<>(); + stack.push(-1); // Mark the starting point of a potential valid substring + + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '(') { + stack.push(i); + } else { // c == ')' + stack.pop(); + if (stack.isEmpty()) { + stack.push(i); // Mark the starting point of the next potential valid substring + } else { + maxLen = Math.max(maxLen, i - stack.peek()); + } + } + } + + return maxLen; + } +} +``` + +This implementation provides a solution to the "Longest Valid Parentheses" problem in Java. It finds the length of the longest valid parentheses substring in the given string `s`. From f93253a890e28e32a6fa90b023283403bf55276b Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:21:48 +0200 Subject: [PATCH 08/18] Update README with solution steps and implementation Added detailed explanation and implementation for the Search in Rotated Sorted Array problem. --- .../readme.md | 56 ++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0033_search_in_rotated_sorted_array/readme.md b/src/main/java/g0001_0100/s0033_search_in_rotated_sorted_array/readme.md index b93cfed59..5ed3224c9 100644 --- a/src/main/java/g0001_0100/s0033_search_in_rotated_sorted_array/readme.md +++ b/src/main/java/g0001_0100/s0033_search_in_rotated_sorted_array/readme.md @@ -34,4 +34,58 @@ You must write an algorithm with `O(log n)` runtime complexity. * -104 <= nums[i] <= 104 * All values of `nums` are **unique**. * `nums` is an ascending array that is possibly rotated. -* -104 <= target <= 104 \ No newline at end of file +* -104 <= target <= 104 + +To solve the "Search in Rotated Sorted Array" problem in Java with a `Solution` class, we can follow these steps: + +1. Define a `Solution` class. +2. Define a method named `search` that takes an integer array `nums` and an integer `target` as input and returns an integer representing the index of `target` in `nums`. If `target` is not found, return `-1`. +3. Implement the binary search algorithm to find the index of `target` in the rotated sorted array. +4. Set the left pointer `left` to 0 and the right pointer `right` to the length of `nums` minus 1. +5. While `left` is less than or equal to `right`: + - Calculate the middle index `mid` as `(left + right) / 2`. + - If `nums[mid]` is equal to `target`, return `mid`. + - Check if the left half of the array (`nums[left]` to `nums[mid]`) is sorted: + - If `nums[left] <= nums[mid]` and `nums[left] <= target < nums[mid]`, update `right = mid - 1`. + - Otherwise, update `left = mid + 1`. + - Otherwise, check if the right half of the array (`nums[mid]` to `nums[right]`) is sorted: + - If `nums[mid] <= nums[right]` and `nums[mid] < target <= nums[right]`, update `left = mid + 1`. + - Otherwise, update `right = mid - 1`. +6. If `target` is not found, return `-1`. + +Here's the implementation: + +```java +public class Solution { + public int search(int[] nums, int target) { + int left = 0; + int right = nums.length - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; + + if (nums[mid] == target) { + return mid; + } + + if (nums[left] <= nums[mid]) { + if (nums[left] <= target && target < nums[mid]) { + right = mid - 1; + } else { + left = mid + 1; + } + } else { + if (nums[mid] < target && target <= nums[right]) { + left = mid + 1; + } else { + right = mid - 1; + } + } + } + + return -1; + } +} +``` + +This implementation provides a solution to the "Search in Rotated Sorted Array" problem in Java. It searches for the index of `target` in the rotated sorted array `nums`. The algorithm has a time complexity of O(log n). From ac00bfbb0ff7bfa0e79be028818e01359763258f Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:22:39 +0200 Subject: [PATCH 09/18] Update readme.md --- .../readme.md | 70 ++++++++++++++++++- 1 file changed, 69 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array/readme.md b/src/main/java/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array/readme.md index 7c04eb2ed..0e1036e1f 100644 --- a/src/main/java/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array/readme.md +++ b/src/main/java/g0001_0100/s0034_find_first_and_last_position_of_element_in_sorted_array/readme.md @@ -31,4 +31,72 @@ You must write an algorithm with `O(log n)` runtime complexity. * 0 <= nums.length <= 105 * -109 <= nums[i] <= 109 * `nums` is a non-decreasing array. -* -109 <= target <= 109 \ No newline at end of file +* -109 <= target <= 109 + +To solve the "Find First and Last Position of Element in Sorted Array" problem in Java with a `Solution` class, we can follow these steps: + +1. Define a `Solution` class. +2. Define a method named `searchRange` that takes an integer array `nums` and an integer `target` as input and returns an integer array representing the starting and ending positions of `target` in `nums`. If `target` is not found, return `[-1, -1]`. +3. Implement binary search to find the first and last occurrences of `target`. +4. Set the left pointer `left` to 0 and the right pointer `right` to the length of `nums` minus 1. +5. Initialize two variables `firstOccurrence` and `lastOccurrence` to -1. +6. Perform two binary search operations: + - First, find the first occurrence of `target`: + - While `left` is less than or equal to `right`: + - Calculate the middle index `mid` as `(left + right) / 2`. + - If `nums[mid]` is equal to `target`, update `firstOccurrence = mid` and continue searching on the left half by updating `right = mid - 1`. + - Otherwise, if `target` is less than `nums[mid]`, update `right = mid - 1`. + - Otherwise, update `left = mid + 1`. + - Second, find the last occurrence of `target`: + - Reset `left` to 0 and `right` to the length of `nums` minus 1. + - While `left` is less than or equal to `right`: + - Calculate the middle index `mid` as `(left + right) / 2`. + - If `nums[mid]` is equal to `target`, update `lastOccurrence = mid` and continue searching on the right half by updating `left = mid + 1`. + - Otherwise, if `target` is greater than `nums[mid]`, update `left = mid + 1`. + - Otherwise, update `right = mid - 1`. +7. Return the array `[firstOccurrence, lastOccurrence]`. + +Here's the implementation: + +```java +public class Solution { + public int[] searchRange(int[] nums, int target) { + int left = 0; + int right = nums.length - 1; + int firstOccurrence = -1; + int lastOccurrence = -1; + + // Find first occurrence + while (left <= right) { + int mid = left + (right - left) / 2; + if (nums[mid] == target) { + firstOccurrence = mid; + right = mid - 1; + } else if (target < nums[mid]) { + right = mid - 1; + } else { + left = mid + 1; + } + } + + // Find last occurrence + left = 0; + right = nums.length - 1; + while (left <= right) { + int mid = left + (right - left) / 2; + if (nums[mid] == target) { + lastOccurrence = mid; + left = mid + 1; + } else if (target < nums[mid]) { + right = mid - 1; + } else { + left = mid + 1; + } + } + + return new int[]{firstOccurrence, lastOccurrence}; + } +} +``` + +This implementation provides a solution to the "Find First and Last Position of Element in Sorted Array" problem in Java. It returns the starting and ending positions of `target` in `nums` using binary search, with a time complexity of O(log n). From cf86626d82dee7471163de887c74f67a474c3977 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:23:38 +0200 Subject: [PATCH 10/18] Update readme.md --- .../s0035_search_insert_position/readme.md | 41 ++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0035_search_insert_position/readme.md b/src/main/java/g0001_0100/s0035_search_insert_position/readme.md index 79f9ab2c2..b178a53bc 100644 --- a/src/main/java/g0001_0100/s0035_search_insert_position/readme.md +++ b/src/main/java/g0001_0100/s0035_search_insert_position/readme.md @@ -29,4 +29,43 @@ You must write an algorithm with `O(log n)` runtime complexity. * 1 <= nums.length <= 104 * -104 <= nums[i] <= 104 * `nums` contains **distinct** values sorted in **ascending** order. -* -104 <= target <= 104 \ No newline at end of file +* -104 <= target <= 104 + +To solve the "Search Insert Position" problem in Java with a `Solution` class, we can follow these steps: + +1. Define a `Solution` class. +2. Define a method named `searchInsert` that takes an integer array `nums` and an integer `target` as input and returns an integer representing the index where `target` would be inserted in order. +3. Implement binary search to find the insertion position of `target`. +4. Set the left pointer `left` to 0 and the right pointer `right` to the length of `nums` minus 1. +5. While `left` is less than or equal to `right`: + - Calculate the middle index `mid` as `(left + right) / 2`. + - If `nums[mid]` is equal to `target`, return `mid`. + - If `target` is less than `nums[mid]`, update `right = mid - 1`. + - If `target` is greater than `nums[mid]`, update `left = mid + 1`. +6. If `target` is not found in `nums`, return the value of `left`, which represents the index where `target` would be inserted in order. + +Here's the implementation: + +```java +public class Solution { + public int searchInsert(int[] nums, int target) { + int left = 0; + int right = nums.length - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; + if (nums[mid] == target) { + return mid; + } else if (target < nums[mid]) { + right = mid - 1; + } else { + left = mid + 1; + } + } + + return left; + } +} +``` + +This implementation provides a solution to the "Search Insert Position" problem in Java. It returns the index where `target` would be inserted in `nums` using binary search, with a time complexity of O(log n). From ff8e4bae3f55e4219453037109402cb43dd9385c Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:24:40 +0200 Subject: [PATCH 11/18] Update readme.md --- .../s0039_combination_sum/readme.md | 53 ++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0039_combination_sum/readme.md b/src/main/java/g0001_0100/s0039_combination_sum/readme.md index c4c869610..2130d52f7 100644 --- a/src/main/java/g0001_0100/s0039_combination_sum/readme.md +++ b/src/main/java/g0001_0100/s0039_combination_sum/readme.md @@ -33,4 +33,55 @@ The test cases are generated such that the number of unique combinations that su * `1 <= candidates.length <= 30` * `2 <= candidates[i] <= 40` * All elements of `candidates` are **distinct**. -* `1 <= target <= 40` \ No newline at end of file +* `1 <= target <= 40` + +To solve the "Combination Sum" problem in Java with a `Solution` class, we can follow these steps: + +1. Define a `Solution` class. +2. Define a method named `combinationSum` that takes an array of integers `candidates` and an integer `target` as input and returns a list of lists containing all unique combinations of `candidates` where the chosen numbers sum to `target`. +3. Implement backtracking to explore all possible combinations of candidates. +4. Sort the `candidates` array to ensure that duplicates are grouped together. +5. Create a recursive helper method named `backtrack` that takes parameters: + - A list to store the current combination. + - An integer representing the starting index in the `candidates` array. + - The current sum of the combination. +6. In the `backtrack` method: + - If the current sum equals the target, add the current combination to the result list. + - Iterate over the candidates starting from the current index. + - Add the current candidate to the combination. + - Recursively call the `backtrack` method with the updated combination, index, and sum. + - Remove the last added candidate from the combination to backtrack. +7. Call the `backtrack` method with an empty combination list, starting index 0, and sum 0. +8. Return the result list containing all unique combinations. + +Here's the implementation: + +```java +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Solution { + public List> combinationSum(int[] candidates, int target) { + List> result = new ArrayList<>(); + Arrays.sort(candidates); // Sort the candidates to ensure duplicates are grouped together + backtrack(result, new ArrayList<>(), candidates, target, 0); + return result; + } + + private void backtrack(List> result, List combination, int[] candidates, int target, int start) { + if (target == 0) { + result.add(new ArrayList<>(combination)); + return; + } + + for (int i = start; i < candidates.length && candidates[i] <= target; i++) { + combination.add(candidates[i]); + backtrack(result, combination, candidates, target - candidates[i], i); // Use the same candidate again + combination.remove(combination.size() - 1); // Backtrack by removing the last candidate + } + } +} +``` + +This implementation provides a solution to the "Combination Sum" problem in Java. It explores all possible combinations of candidates using backtracking and returns the unique combinations whose sum equals the target. From bb16cde52b2943e844c1a7ac8b730059eefe4454 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:25:36 +0200 Subject: [PATCH 12/18] Update readme.md --- .../s0041_first_missing_positive/readme.md | 45 ++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0041_first_missing_positive/readme.md b/src/main/java/g0001_0100/s0041_first_missing_positive/readme.md index c786c05c2..32df8d6ae 100644 --- a/src/main/java/g0001_0100/s0041_first_missing_positive/readme.md +++ b/src/main/java/g0001_0100/s0041_first_missing_positive/readme.md @@ -33,4 +33,47 @@ You must implement an algorithm that runs in `O(n)` time and uses `O(1)` auxilia **Constraints:** * 1 <= nums.length <= 105 -* -231 <= nums[i] <= 231 - 1 \ No newline at end of file +* -231 <= nums[i] <= 231 - 1 + +To solve the "First Missing Positive" problem in Java with a `Solution` class, we can follow these steps: + +1. Define a `Solution` class. +2. Define a method named `firstMissingPositive` that takes an array of integers `nums` as input and returns the smallest missing positive integer. +3. Iterate through the array and mark the positive integers found by negating the value at the corresponding index. +4. Iterate through the modified array again and return the index of the first positive number (which is the smallest missing positive integer). +5. If no positive number is found, return `nums.length + 1`. + +Here's the implementation: + +```java +public class Solution { + public int firstMissingPositive(int[] nums) { + int n = nums.length; + + // Mark positive integers found by negating the value at the corresponding index + for (int i = 0; i < n; i++) { + if (nums[i] > 0 && nums[i] <= n) { + int pos = nums[i] - 1; + if (nums[pos] != nums[i]) { + int temp = nums[pos]; + nums[pos] = nums[i]; + nums[i] = temp; + i--; // Revisit the swapped number + } + } + } + + // Find the first positive number (smallest missing positive integer) + for (int i = 0; i < n; i++) { + if (nums[i] != i + 1) { + return i + 1; + } + } + + // If no positive number is found, return nums.length + 1 + return n + 1; + } +} +``` + +This implementation provides a solution to the "First Missing Positive" problem in Java. It marks positive integers found by negating the value at the corresponding index and then iterates through the modified array to find the smallest missing positive integer. If no positive number is found, it returns `nums.length + 1`. From 607edf0fb4cbf4e1104df4e99f873e3c8db24954 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:26:19 +0200 Subject: [PATCH 13/18] Update readme.md --- .../s0042_trapping_rain_water/readme.md | 44 ++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0042_trapping_rain_water/readme.md b/src/main/java/g0001_0100/s0042_trapping_rain_water/readme.md index b57de86dd..d400d21b9 100644 --- a/src/main/java/g0001_0100/s0042_trapping_rain_water/readme.md +++ b/src/main/java/g0001_0100/s0042_trapping_rain_water/readme.md @@ -24,4 +24,46 @@ Given `n` non-negative integers representing an elevation map where the width of * `n == height.length` * 1 <= n <= 2 * 104 -* 0 <= height[i] <= 105 \ No newline at end of file +* 0 <= height[i] <= 105 + +To solve the "Trapping Rain Water" problem in Java with a `Solution` class, we can follow these steps: + +1. Define a `Solution` class. +2. Define a method named `trap` that takes an array of integers `height` as input and returns the amount of water it can trap after raining. +3. Initialize two pointers `left` and `right` at the beginning and end of the array respectively. +4. Initialize two variables `leftMax` and `rightMax` to keep track of the maximum height of bars encountered from the left and right directions respectively. +5. Iterate through the array using the two pointers: + - Update `leftMax` as the maximum of `leftMax` and `height[left]`. + - Update `rightMax` as the maximum of `rightMax` and `height[right]`. + - If `height[left] < height[right]`, calculate the water trapped at the current position using `leftMax` and subtract the height of the current bar. Move `left` pointer to the right. + - Otherwise, calculate the water trapped at the current position using `rightMax` and subtract the height of the current bar. Move `right` pointer to the left. +6. Continue this process until the two pointers meet. +7. Return the total amount of water trapped. + +Here's the implementation: + +```java +public class Solution { + public int trap(int[] height) { + int left = 0, right = height.length - 1; + int leftMax = 0, rightMax = 0; + int trappedWater = 0; + + while (left < right) { + if (height[left] < height[right]) { + leftMax = Math.max(leftMax, height[left]); + trappedWater += leftMax - height[left]; + left++; + } else { + rightMax = Math.max(rightMax, height[right]); + trappedWater += rightMax - height[right]; + right--; + } + } + + return trappedWater; + } +} +``` + +This implementation provides a solution to the "Trapping Rain Water" problem in Java. It calculates the amount of water that can be trapped between bars by using two pointers to track the left and right boundaries and two variables to track the maximum heights of bars encountered from the left and right directions. From 13623179781ed477205edea898ea05010d8aa0ff Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:27:06 +0200 Subject: [PATCH 14/18] Update readme.md --- .../g0001_0100/s0045_jump_game_ii/readme.md | 36 ++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0045_jump_game_ii/readme.md b/src/main/java/g0001_0100/s0045_jump_game_ii/readme.md index e2c3be086..1622fd539 100644 --- a/src/main/java/g0001_0100/s0045_jump_game_ii/readme.md +++ b/src/main/java/g0001_0100/s0045_jump_game_ii/readme.md @@ -29,4 +29,38 @@ Return _the minimum number of jumps to reach index_ `n - 1`. The test cases are * 1 <= nums.length <= 104 * `0 <= nums[i] <= 1000` -* It's guaranteed that you can reach `nums[n - 1]`. \ No newline at end of file +* It's guaranteed that you can reach `nums[n - 1]`. + +To solve the "Jump Game II" problem in Java with a `Solution` class, we can follow these steps: + +1. Define a `Solution` class. +2. Define a method named `jump` that takes an array of non-negative integers `nums` as input and returns the minimum number of jumps required to reach the last index. +3. Initialize variables `maxReach`, `steps`, and `end` to keep track of the maximum reachable position, the number of steps taken, and the end position respectively. Initialize `maxReach` to 0 and `end` to 0. +4. Iterate through the array from index 0 to `nums.length - 2`: + - Update `maxReach` as the maximum of `maxReach` and `i + nums[i]`. + - If the current index `i` equals `end`, update `end` to `maxReach` and increment `steps`. +5. Return `steps`. + +Here's the implementation: + +```java +public class Solution { + public int jump(int[] nums) { + int maxReach = 0; + int steps = 0; + int end = 0; + + for (int i = 0; i < nums.length - 1; i++) { + maxReach = Math.max(maxReach, i + nums[i]); + if (i == end) { + end = maxReach; + steps++; + } + } + + return steps; + } +} +``` + +This implementation provides a solution to the "Jump Game II" problem in Java. It calculates the minimum number of jumps required to reach the last index by iterating through the array and updating the maximum reachable position and the end position accordingly. From 67f3544082541cd07eda0613093a25c4d81ed016 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:28:08 +0200 Subject: [PATCH 15/18] Update readme.md --- .../g0001_0100/s0046_permutations/readme.md | 47 ++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0046_permutations/readme.md b/src/main/java/g0001_0100/s0046_permutations/readme.md index f66dc4f2c..31b15e6dd 100644 --- a/src/main/java/g0001_0100/s0046_permutations/readme.md +++ b/src/main/java/g0001_0100/s0046_permutations/readme.md @@ -26,4 +26,49 @@ Given an array `nums` of distinct integers, return all the possible permutations * `1 <= nums.length <= 6` * `-10 <= nums[i] <= 10` -* All the integers of `nums` are **unique**. \ No newline at end of file +* All the integers of `nums` are **unique**. + +To solve the "Permutations" problem in Java with a `Solution` class, we can follow these steps: + +1. Define a `Solution` class. +2. Define a method named `permute` that takes an array of distinct integers `nums` as input and returns a list of all possible permutations. +3. Create an empty list to store the result permutations. +4. Call a recursive helper function named `permuteHelper` to generate permutations. +5. Inside the `permuteHelper` function: + - If the current permutation size equals the length of the input array `nums`, add a copy of the current permutation to the result list. + - Otherwise, iterate through each element of `nums`: + - If the current element is not already in the permutation, add it to the current permutation, and recursively call `permuteHelper` with the updated permutation and the remaining elements of `nums`. + - After the recursive call, remove the last element from the permutation to backtrack. +6. Return the result list. + +Here's the implementation: + +```java +import java.util.ArrayList; +import java.util.List; + +public class Solution { + public List> permute(int[] nums) { + List> result = new ArrayList<>(); + permuteHelper(nums, new ArrayList<>(), result); + return result; + } + + private void permuteHelper(int[] nums, List current, List> result) { + if (current.size() == nums.length) { + result.add(new ArrayList<>(current)); + return; + } + + for (int num : nums) { + if (!current.contains(num)) { + current.add(num); + permuteHelper(nums, current, result); + current.remove(current.size() - 1); + } + } + } +} +``` + +This implementation provides a solution to the "Permutations" problem in Java. It generates all possible permutations of the given array of distinct integers using backtracking. From 1f2ffd243bbd7767cf2b082a1f2068a97c519f84 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:30:11 +0200 Subject: [PATCH 16/18] Update readme.md --- .../g0001_0100/s0048_rotate_image/readme.md | 48 ++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0048_rotate_image/readme.md b/src/main/java/g0001_0100/s0048_rotate_image/readme.md index 3798319b9..5077707b7 100644 --- a/src/main/java/g0001_0100/s0048_rotate_image/readme.md +++ b/src/main/java/g0001_0100/s0048_rotate_image/readme.md @@ -26,4 +26,50 @@ You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-pla * `n == matrix.length == matrix[i].length` * `1 <= n <= 20` -* `-1000 <= matrix[i][j] <= 1000` \ No newline at end of file +* `-1000 <= matrix[i][j] <= 1000` + +To solve the "Rotate Image" problem in Java with a `Solution` class, we can follow these steps: + +1. Define a `Solution` class. +2. Define a method named `rotate` that takes a 2D array `matrix` representing an image as input and rotates the image by 90 degrees clockwise. +3. Determine the number of layers in the matrix, which is equal to half of the matrix's size. +4. Iterate through each layer from outer to inner layers. +5. For each layer: + - Iterate through each element in the current layer. + - Swap the elements of the current layer in a clockwise manner. +6. Return the rotated matrix. + +Here's the implementation: + +```java +public class Solution { + public void rotate(int[][] matrix) { + int n = matrix.length; + int layers = n / 2; + + for (int layer = 0; layer < layers; layer++) { + int first = layer; + int last = n - 1 - layer; + + for (int i = first; i < last; i++) { + int offset = i - first; + int top = matrix[first][i]; + + // Move left to top + matrix[first][i] = matrix[last - offset][first]; + + // Move bottom to left + matrix[last - offset][first] = matrix[last][last - offset]; + + // Move right to bottom + matrix[last][last - offset] = matrix[i][last]; + + // Move top to right + matrix[i][last] = top; + } + } + } +} +``` + +This implementation provides a solution to the "Rotate Image" problem in Java. It rotates the given 2D matrix representing an image by 90 degrees clockwise in-place. From 47134c5102f0ded1284ff6df2bf4d9d659294f22 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:31:04 +0200 Subject: [PATCH 17/18] Update readme.md --- .../g0001_0100/s0049_group_anagrams/readme.md | 50 ++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0049_group_anagrams/readme.md b/src/main/java/g0001_0100/s0049_group_anagrams/readme.md index 988d84dbb..3d2d7723f 100644 --- a/src/main/java/g0001_0100/s0049_group_anagrams/readme.md +++ b/src/main/java/g0001_0100/s0049_group_anagrams/readme.md @@ -32,4 +32,52 @@ Given an array of strings `strs`, group the anagrams together. You can return th * 1 <= strs.length <= 104 * `0 <= strs[i].length <= 100` -* `strs[i]` consists of lowercase English letters. \ No newline at end of file +* `strs[i]` consists of lowercase English letters. + +To solve the "Group Anagrams" problem in Java with the Solution class, follow these steps: + +1. Define a method `groupAnagrams` in the `Solution` class that takes an array of strings `strs` as input and returns a list of lists of strings. +2. Initialize an empty HashMap to store the groups of anagrams. The key will be the sorted string, and the value will be a list of strings. +3. Iterate through each string `str` in the input array `strs`. +4. Sort the characters of the current string `str` to create a key for the HashMap. +5. Check if the sorted string exists as a key in the HashMap: + - If it does, add the original string `str` to the corresponding list of strings. + - If it doesn't, create a new entry in the HashMap with the sorted string as the key and a new list containing `str` as the value. +6. After iterating through all strings, return the values of the HashMap as the result. + +Here's the implementation of the `groupAnagrams` method in Java: + +```java +import java.util.*; + +class Solution { + public List> groupAnagrams(String[] strs) { + // Initialize a HashMap to store the groups of anagrams + Map> anagramGroups = new HashMap<>(); + + // Iterate through each string in the input array + for (String str : strs) { + // Sort the characters of the current string + char[] chars = str.toCharArray(); + Arrays.sort(chars); + String sortedStr = new String(chars); + + // Check if the sorted string exists as a key in the HashMap + if (anagramGroups.containsKey(sortedStr)) { + // If it does, add the original string to the corresponding list + anagramGroups.get(sortedStr).add(str); + } else { + // If it doesn't, create a new entry in the HashMap + List group = new ArrayList<>(); + group.add(str); + anagramGroups.put(sortedStr, group); + } + } + + // Return the values of the HashMap as the result + return new ArrayList<>(anagramGroups.values()); + } +} +``` + +This implementation ensures that all anagrams are grouped together efficiently using a HashMap. From 767822498e7daa46962dc36579a17974295dcb43 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 28 Oct 2025 17:33:47 +0200 Subject: [PATCH 18/18] Updated readme --- .../readme.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/java/g0001_0100/s0026_remove_duplicates_from_sorted_array/readme.md b/src/main/java/g0001_0100/s0026_remove_duplicates_from_sorted_array/readme.md index 0d2adaa8c..9df434879 100644 --- a/src/main/java/g0001_0100/s0026_remove_duplicates_from_sorted_array/readme.md +++ b/src/main/java/g0001_0100/s0026_remove_duplicates_from_sorted_array/readme.md @@ -12,7 +12,15 @@ The first `k` elements of `nums` should contain the unique numbers in **sorted o The judge will test your solution with the following code: -int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; } + int[] nums = [...]; // Input array + int[] expectedNums = [...]; // The expected answer with correct length + + int k = removeDuplicates(nums); // Calls your implementation + + assert k == expectedNums.length; + for (int i = 0; i < k; i++) { + assert nums[i] == expectedNums[i]; + } If all assertions pass, then your solution will be **accepted**. @@ -36,4 +44,4 @@ If all assertions pass, then your solution will be **accepted**. * 1 <= nums.length <= 3 * 104 * `-100 <= nums[i] <= 100` -* `nums` is sorted in **non-decreasing** order. \ No newline at end of file +* `nums` is sorted in **non-decreasing** order.