From 9e1ff1ad9c263bf2cd489154f538ffa9ba3f5708 Mon Sep 17 00:00:00 2001 From: ThanhNIT Date: Mon, 27 Oct 2025 19:51:21 +0700 Subject: [PATCH 01/21] updated tasks 1-22 --- .../java/g0001_0100/s0001_two_sum/readme.md | 64 +------- .../s0002_add_two_numbers/readme.md | 100 +---------- .../readme.md | 75 +-------- .../readme.md | 88 +--------- .../readme.md | 83 +--------- .../s0006_zigzag_conversion/readme.md | 70 +------- .../s0007_reverse_integer/readme.md | 69 +------- .../s0008_string_to_integer_atoi/readme.md | 155 +++--------------- .../s0009_palindrome_number/readme.md | 75 +-------- .../readme.md | 81 +-------- .../s0011_container_with_most_water/readme.md | 76 +-------- .../s0012_integer_to_roman/readme.md | 75 +++++---- .../s0013_roman_to_integer/readme.md | 31 +--- .../s0014_longest_common_prefix/readme.md | 2 +- src/main/java/g0001_0100/s0015_3sum/readme.md | 99 ++--------- .../readme.md | 87 +--------- .../readme.md | 95 +---------- .../s0020_valid_parentheses/readme.md | 69 +------- .../s0021_merge_two_sorted_lists/readme.md | 81 +-------- .../s0022_generate_parentheses/readme.md | 59 +------ 20 files changed, 138 insertions(+), 1396 deletions(-) diff --git a/src/main/java/g0001_0100/s0001_two_sum/readme.md b/src/main/java/g0001_0100/s0001_two_sum/readme.md index 811079c85..d51bd7071 100644 --- a/src/main/java/g0001_0100/s0001_two_sum/readme.md +++ b/src/main/java/g0001_0100/s0001_two_sum/readme.md @@ -35,66 +35,4 @@ You can return the answer in any order. * -109 <= target <= 109 * **Only one valid answer exists.** -**Follow-up:** Can you come up with an algorithm that is less than O(n2) time complexity? - -To solve the Two Sum problem in Java using a `Solution` class, we'll follow these steps: - -1. Define a `Solution` class with a method named `twoSum`. -2. Inside the `twoSum` method, create a hashmap to store elements and their indices. -3. Iterate through the array: - - For each element, calculate the complement required to reach the target sum. - - Check if the complement exists in the hashmap. - - If found, return the indices of the current element and the complement. - - If not found, add the current element and its index to the hashmap. -4. Handle edge cases: - - If no solution is found, return an empty array or null (depending on the problem requirements). - -Here's the implementation: - -```java -import java.util.HashMap; - -public class Solution { - - public int[] twoSum(int[] nums, int target) { - // Create a hashmap to store elements and their indices - HashMap map = new HashMap<>(); - - // Iterate through the array - for (int i = 0; i < nums.length; i++) { - int complement = target - nums[i]; - // Check if the complement exists in the hashmap - if (map.containsKey(complement)) { - // Return the indices of the current element and the complement - return new int[]{map.get(complement), i}; - } - // Add the current element and its index to the hashmap - map.put(nums[i], i); - } - // If no solution is found, return an empty array or null - return new int[]{}; - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - int[] nums1 = {2, 7, 11, 15}; - int target1 = 9; - int[] result1 = solution.twoSum(nums1, target1); - System.out.println("Example 1 Output: [" + result1[0] + ", " + result1[1] + "]"); - - int[] nums2 = {3, 2, 4}; - int target2 = 6; - int[] result2 = solution.twoSum(nums2, target2); - System.out.println("Example 2 Output: [" + result2[0] + ", " + result2[1] + "]"); - - int[] nums3 = {3, 3}; - int target3 = 6; - int[] result3 = solution.twoSum(nums3, target3); - System.out.println("Example 3 Output: [" + result3[0] + ", " + result3[1] + "]"); - } -} -``` - -This implementation provides a solution to the Two Sum problem with a time complexity of O(n), where n is the number of elements in the input array. \ No newline at end of file +**Follow-up:** Can you come up with an algorithm that is less than O(n2) time complexity? \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0002_add_two_numbers/readme.md b/src/main/java/g0001_0100/s0002_add_two_numbers/readme.md index 77abd6701..6e67c194c 100644 --- a/src/main/java/g0001_0100/s0002_add_two_numbers/readme.md +++ b/src/main/java/g0001_0100/s0002_add_two_numbers/readme.md @@ -32,102 +32,4 @@ You may assume the two numbers do not contain any leading zero, except the numbe * The number of nodes in each linked list is in the range `[1, 100]`. * `0 <= Node.val <= 9` -* It is guaranteed that the list represents a number that does not have leading zeros. - -To solve the Add Two Numbers problem in Java using a `Solution` class, we'll follow these steps: - -1. Define a `ListNode` class to represent nodes in a linked list. -2. Define a `Solution` class with a method named `addTwoNumbers`. -3. Inside the `addTwoNumbers` method, traverse both input linked lists simultaneously: - - Keep track of a carry variable to handle cases where the sum of two digits exceeds 9. - - Calculate the sum of the current nodes' values along with the carry. - - Update the carry for the next iteration. - - Create a new node with the sum % 10 and attach it to the result linked list. - - Move to the next nodes in both input lists. -4. After finishing the traversal, check if there is any remaining carry. If so, add a new node with the carry to the result. -5. Return the head of the result linked list. - -Here's the implementation: - -```java -class ListNode { - int val; - ListNode next; - - ListNode() {} - - ListNode(int val) { - this.val = val; - } - - ListNode(int val, ListNode next) { - this.val = val; - this.next = next; - } -} - -public class Solution { - - public ListNode addTwoNumbers(ListNode l1, ListNode l2) { - ListNode dummyHead = new ListNode(); - ListNode curr = dummyHead; - int carry = 0; - - while (l1 != null || l2 != null) { - int sum = carry; - if (l1 != null) { - sum += l1.val; - l1 = l1.next; - } - if (l2 != null) { - sum += l2.val; - l2 = l2.next; - } - curr.next = new ListNode(sum % 10); - curr = curr.next; - carry = sum / 10; - } - - if (carry > 0) { - curr.next = new ListNode(carry); - } - - return dummyHead.next; - } - - // Helper method to print a linked list - public void printList(ListNode head) { - ListNode curr = head; - while (curr != null) { - System.out.print(curr.val + " "); - curr = curr.next; - } - System.out.println(); - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(3))); - ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4))); - ListNode result1 = solution.addTwoNumbers(l1, l2); - System.out.print("Example 1 Output: "); - solution.printList(result1); - - ListNode l3 = new ListNode(0); - ListNode l4 = new ListNode(0); - ListNode result2 = solution.addTwoNumbers(l3, l4); - System.out.print("Example 2 Output: "); - solution.printList(result2); - - ListNode l5 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))))))); - ListNode l6 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))); - ListNode result3 = solution.addTwoNumbers(l5, l6); - System.out.print("Example 3 Output: "); - solution.printList(result3); - } -} -``` - -This implementation provides a solution to the Add Two Numbers problem using linked lists in Java. \ No newline at end of file +* It is guaranteed that the list represents a number that does not have leading zeros. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0003_longest_substring_without_repeating_characters/readme.md b/src/main/java/g0001_0100/s0003_longest_substring_without_repeating_characters/readme.md index f4856aff1..1e1738446 100644 --- a/src/main/java/g0001_0100/s0003_longest_substring_without_repeating_characters/readme.md +++ b/src/main/java/g0001_0100/s0003_longest_substring_without_repeating_characters/readme.md @@ -2,7 +2,7 @@ Medium -Given a string `s`, find the length of the **longest substring** without repeating characters. +Given a string `s`, find the length of the **longest** **substring** without duplicate characters. **Example 1:** @@ -10,7 +10,7 @@ Given a string `s`, find the length of the **longest substring** without repeati **Output:** 3 -**Explanation:** The answer is "abc", with the length of 3. +**Explanation:** The answer is "abc", with the length of 3. Note that `"bca"` and `"cab"` are also correct answers. **Example 2:** @@ -28,76 +28,7 @@ Given a string `s`, find the length of the **longest substring** without repeati **Explanation:** The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. -**Example 4:** - -**Input:** s = "" - -**Output:** 0 - **Constraints:** * 0 <= s.length <= 5 * 104 -* `s` consists of English letters, digits, symbols and spaces. - -To solve the Longest Substring Without Repeating Characters problem in Java using a `Solution` class, we'll follow these steps: - -1. Define a `Solution` class with a method named `lengthOfLongestSubstring`. -2. Initialize variables to keep track of the starting index of the substring (`start`), the maximum length (`maxLen`), and a hashmap to store characters and their indices. -3. Iterate through the string `s`, and for each character: - - Check if the character exists in the hashmap and its index is greater than or equal to the `start` index. - - If found, update the `start` index to the index after the last occurrence of the character. - - Update the maximum length if necessary. - - Update the index of the current character in the hashmap. -4. Return the maximum length found. -5. Handle the edge case where the input string is empty. - -Here's the implementation: - -```java -import java.util.HashMap; - -public class Solution { - - public int lengthOfLongestSubstring(String s) { - // Initialize variables - int start = 0; - int maxLen = 0; - HashMap map = new HashMap<>(); - - // Iterate through the string - for (int end = 0; end < s.length(); end++) { - char ch = s.charAt(end); - // If the character exists in the hashmap and its index is greater than or equal to the start index - if (map.containsKey(ch) && map.get(ch) >= start) { - // Update the start index to the index after the last occurrence of the character - start = map.get(ch) + 1; - } - // Update the maximum length if necessary - maxLen = Math.max(maxLen, end - start + 1); - // Update the index of the current character in the hashmap - map.put(ch, end); - } - - return maxLen; - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - String s1 = "abcabcbb"; - System.out.println("Example 1 Output: " + solution.lengthOfLongestSubstring(s1)); - - String s2 = "bbbbb"; - System.out.println("Example 2 Output: " + solution.lengthOfLongestSubstring(s2)); - - String s3 = "pwwkew"; - System.out.println("Example 3 Output: " + solution.lengthOfLongestSubstring(s3)); - - String s4 = ""; - System.out.println("Example 4 Output: " + solution.lengthOfLongestSubstring(s4)); - } -} -``` - -This implementation provides a solution to the Longest Substring Without Repeating Characters problem in Java. \ No newline at end of file +* `s` consists of English letters, digits, symbols and spaces. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0004_median_of_two_sorted_arrays/readme.md b/src/main/java/g0001_0100/s0004_median_of_two_sorted_arrays/readme.md index 09e2fd08c..9482d8459 100644 --- a/src/main/java/g0001_0100/s0004_median_of_two_sorted_arrays/readme.md +++ b/src/main/java/g0001_0100/s0004_median_of_two_sorted_arrays/readme.md @@ -22,24 +22,6 @@ The overall run time complexity should be `O(log (m+n))`. **Explanation:** merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. -**Example 3:** - -**Input:** nums1 = [0,0], nums2 = [0,0] - -**Output:** 0.00000 - -**Example 4:** - -**Input:** nums1 = [], nums2 = [1] - -**Output:** 1.00000 - -**Example 5:** - -**Input:** nums1 = [2], nums2 = [] - -**Output:** 2.00000 - **Constraints:** * `nums1.length == m` @@ -47,72 +29,4 @@ The overall run time complexity should be `O(log (m+n))`. * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` -* -106 <= nums1[i], nums2[i] <= 106 - -To solve the Median of Two Sorted Arrays problem in Java using a `Solution` class, we'll follow these steps: - -1. Define a `Solution` class with a method named `findMedianSortedArrays`. -2. Calculate the total length of the combined array (m + n). -3. Determine the middle index or indices of the combined array based on its length (for both even and odd lengths). -4. Implement a binary search algorithm to find the correct position for partitioning the two arrays such that elements to the left are less than or equal to elements on the right. -5. Calculate the median based on the partitioned arrays. -6. Handle edge cases where one or both arrays are empty or where the combined length is odd or even. -7. Return the calculated median. - -Here's the implementation: - -```java -public class Solution { - - public double findMedianSortedArrays(int[] nums1, int[] nums2) { - int m = nums1.length; - int n = nums2.length; - int totalLength = m + n; - int left = (totalLength + 1) / 2; - int right = (totalLength + 2) / 2; - return (findKth(nums1, 0, nums2, 0, left) + findKth(nums1, 0, nums2, 0, right)) / 2.0; - } - - private int findKth(int[] nums1, int i, int[] nums2, int j, int k) { - if (i >= nums1.length) return nums2[j + k - 1]; - if (j >= nums2.length) return nums1[i + k - 1]; - if (k == 1) return Math.min(nums1[i], nums2[j]); - - int midVal1 = (i + k / 2 - 1 < nums1.length) ? nums1[i + k / 2 - 1] : Integer.MAX_VALUE; - int midVal2 = (j + k / 2 - 1 < nums2.length) ? nums2[j + k / 2 - 1] : Integer.MAX_VALUE; - - if (midVal1 < midVal2) { - return findKth(nums1, i + k / 2, nums2, j, k - k / 2); - } else { - return findKth(nums1, i, nums2, j + k / 2, k - k / 2); - } - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - int[] nums1_1 = {1, 3}; - int[] nums2_1 = {2}; - System.out.println("Example 1 Output: " + solution.findMedianSortedArrays(nums1_1, nums2_1)); - - int[] nums1_2 = {1, 2}; - int[] nums2_2 = {3, 4}; - System.out.println("Example 2 Output: " + solution.findMedianSortedArrays(nums1_2, nums2_2)); - - int[] nums1_3 = {0, 0}; - int[] nums2_3 = {0, 0}; - System.out.println("Example 3 Output: " + solution.findMedianSortedArrays(nums1_3, nums2_3)); - - int[] nums1_4 = {}; - int[] nums2_4 = {1}; - System.out.println("Example 4 Output: " + solution.findMedianSortedArrays(nums1_4, nums2_4)); - - int[] nums1_5 = {2}; - int[] nums2_5 = {}; - System.out.println("Example 5 Output: " + solution.findMedianSortedArrays(nums1_5, nums2_5)); - } -} -``` - -This implementation provides a solution to the Median of Two Sorted Arrays problem in Java with a runtime complexity of O(log(min(m, n))). \ No newline at end of file +* -106 <= nums1[i], nums2[i] <= 106 \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0005_longest_palindromic_substring/readme.md b/src/main/java/g0001_0100/s0005_longest_palindromic_substring/readme.md index aa6a60cf4..82ff4d567 100644 --- a/src/main/java/g0001_0100/s0005_longest_palindromic_substring/readme.md +++ b/src/main/java/g0001_0100/s0005_longest_palindromic_substring/readme.md @@ -2,13 +2,15 @@ Medium -Given a string `s`, return _the longest palindromic substring_ in `s`. +Given a string `s`, return _the longest_ _palindromic_ **substring** in `s`. **Example 1:** **Input:** s = "babad" -**Output:** "bab" **Note:** "aba" is also a valid answer. +**Output:** "bab" + +**Explanation:** "aba" is also a valid answer. **Example 2:** @@ -16,82 +18,7 @@ Given a string `s`, return _the longest palindromic substring_ in `s`. **Output:** "bb" -**Example 3:** - -**Input:** s = "a" - -**Output:** "a" - -**Example 4:** - -**Input:** s = "ac" - -**Output:** "a" - **Constraints:** * `1 <= s.length <= 1000` -* `s` consist of only digits and English letters. - -To solve the Longest Palindromic Substring problem in Java using a `Solution` class, we'll follow these steps: - -1. Define a `Solution` class with a method named `longestPalindrome`. -2. Initialize variables to keep track of the start and end indices of the longest palindromic substring found so far (`start` and `end`). -3. Iterate through the string `s`: - - For each character in the string, expand around it to check if it forms a palindrome. - - Handle both odd-length and even-length palindromes separately. - - Update `start` and `end` indices if a longer palindrome is found. -4. Return the substring from `start` to `end`. -5. Handle edge cases where the input string is empty or has a length of 1. - -Here's the implementation: - -```java -public class Solution { - - public String longestPalindrome(String s) { - if (s == null || s.length() < 1) return ""; - int start = 0; - int end = 0; - - for (int i = 0; i < s.length(); i++) { - int len1 = expandAroundCenter(s, i, i); - int len2 = expandAroundCenter(s, i, i + 1); - int len = Math.max(len1, len2); - if (len > end - start) { - start = i - (len - 1) / 2; - end = i + len / 2; - } - } - - return s.substring(start, end + 1); - } - - private int expandAroundCenter(String s, int left, int right) { - while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { - left--; - right++; - } - return right - left - 1; - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - String s1 = "babad"; - System.out.println("Example 1 Output: " + solution.longestPalindrome(s1)); - - String s2 = "cbbd"; - System.out.println("Example 2 Output: " + solution.longestPalindrome(s2)); - - String s3 = "a"; - System.out.println("Example 3 Output: " + solution.longestPalindrome(s3)); - - String s4 = "ac"; - System.out.println("Example 4 Output: " + solution.longestPalindrome(s4)); - } -} -``` - -This implementation provides a solution to the Longest Palindromic Substring problem in Java. \ No newline at end of file +* `s` consist of only digits and English letters. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0006_zigzag_conversion/readme.md b/src/main/java/g0001_0100/s0006_zigzag_conversion/readme.md index db1939f2a..4f55d57d3 100644 --- a/src/main/java/g0001_0100/s0006_zigzag_conversion/readme.md +++ b/src/main/java/g0001_0100/s0006_zigzag_conversion/readme.md @@ -36,72 +36,4 @@ string convert(string s, int numRows); * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. -* `1 <= numRows <= 1000` - -To solve the Zigzag Conversion problem in Java using a `Solution` class, we'll follow these steps: - -1. Define a `Solution` class with a method named `convert`. -2. Create an array of strings to represent each row of the zigzag pattern. -3. Initialize variables to keep track of the current row (`row`) and the direction of traversal (`down`). -4. Iterate through each character in the input string `s`. - - Append the current character to the string representing the current row. - - If we reach the first or last row, change the direction of traversal accordingly. - - Update the current row based on the direction of traversal. -5. Concatenate the strings representing each row to form the final zigzag conversion. -6. Return the concatenated string. -7. Handle edge cases where the number of rows is 1 or the input string is empty. - -Here's the implementation: - -```java -public class Solution { - - public String convert(String s, int numRows) { - if (numRows == 1 || s.length() <= numRows) { - return s; - } - - StringBuilder[] rows = new StringBuilder[numRows]; - for (int i = 0; i < numRows; i++) { - rows[i] = new StringBuilder(); - } - - int row = 0; - boolean down = false; - - for (char c : s.toCharArray()) { - rows[row].append(c); - if (row == 0 || row == numRows - 1) { - down = !down; - } - row += down ? 1 : -1; - } - - StringBuilder result = new StringBuilder(); - for (StringBuilder sb : rows) { - result.append(sb); - } - - return result.toString(); - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - String s1 = "PAYPALISHIRING"; - int numRows1 = 3; - System.out.println("Example 1 Output: " + solution.convert(s1, numRows1)); - - String s2 = "PAYPALISHIRING"; - int numRows2 = 4; - System.out.println("Example 2 Output: " + solution.convert(s2, numRows2)); - - String s3 = "A"; - int numRows3 = 1; - System.out.println("Example 3 Output: " + solution.convert(s3, numRows3)); - } -} -``` - -This implementation provides a solution to the Zigzag Conversion problem in Java. \ No newline at end of file +* `1 <= numRows <= 1000` \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0007_reverse_integer/readme.md b/src/main/java/g0001_0100/s0007_reverse_integer/readme.md index a49c7222c..a9974deb9 100644 --- a/src/main/java/g0001_0100/s0007_reverse_integer/readme.md +++ b/src/main/java/g0001_0100/s0007_reverse_integer/readme.md @@ -24,73 +24,6 @@ Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If rev **Output:** 21 -**Example 4:** - -**Input:** x = 0 - -**Output:** 0 - **Constraints:** -* -231 <= x <= 231 - 1 - -To solve the Reverse Integer problem in Java using a `Solution` class, we'll follow these steps: - -1. Define a `Solution` class with a method named `reverse`. -2. Initialize variables to keep track of the reversed integer (`rev`), the sign of the input integer (`sign`), and the absolute value of the input integer (`x`). -3. Iterate through each digit of the input integer `x`: - - Extract the least significant digit using the modulo operator. - - Update the reversed integer `rev` by multiplying it by 10 and adding the extracted digit. - - Update `x` by removing the least significant digit using integer division. -4. Check if the reversed integer `rev` overflows the signed 32-bit integer range. If so, return 0. -5. Return the reversed integer `rev` with the appropriate sign. - -Here's the implementation: - -```java -public class Solution { - - public int reverse(int x) { - int rev = 0; - int sign = (x < 0) ? -1 : 1; - int limit = Integer.MAX_VALUE / 10; - int absX = Math.abs(x); - - while (absX > 0) { - int digit = absX % 10; - absX /= 10; - - if (rev > limit || (rev == limit && digit > 7)) { - return 0; - } - - if (rev < -limit || (rev == -limit && digit < -8)) { - return 0; - } - - rev = rev * 10 + digit; - } - - return rev * sign; - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - int x1 = 123; - System.out.println("Example 1 Output: " + solution.reverse(x1)); - - int x2 = -123; - System.out.println("Example 2 Output: " + solution.reverse(x2)); - - int x3 = 120; - System.out.println("Example 3 Output: " + solution.reverse(x3)); - - int x4 = 0; - System.out.println("Example 4 Output: " + solution.reverse(x4)); - } -} -``` - -This implementation provides a solution to the Reverse Integer problem in Java. \ No newline at end of file +* -231 <= x <= 231 - 1 \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0008_string_to_integer_atoi/readme.md b/src/main/java/g0001_0100/s0008_string_to_integer_atoi/readme.md index 86bc9f4fd..8d0ab5062 100644 --- a/src/main/java/g0001_0100/s0008_string_to_integer_atoi/readme.md +++ b/src/main/java/g0001_0100/s0008_string_to_integer_atoi/readme.md @@ -2,21 +2,16 @@ Medium -Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer (similar to C/C++'s `atoi` function). +Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer. The algorithm for `myAtoi(string s)` is as follows: -1. Read in and ignore any leading whitespace. -2. Check if the next character (if not already at the end of the string) is `'-'` or `'+'`. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. -3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored. -4. Convert these digits into an integer (i.e. `"123" -> 123`, `"0032" -> 32`). If no digits were read, then the integer is `0`. Change the sign as necessary (from step 2). -5. If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1. -6. Return the integer as the final result. +1. **Whitespace**: Ignore any leading whitespace (`" "`). +2. **Signedness**: Determine the sign by checking if the next character is `'-'` or `'+'`, assuming positivity if neither present. +3. **Conversion**: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0. +4. **Rounding**: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1. -**Note:** - -* Only the space character `' '` is considered a whitespace character. -* **Do not ignore** any characters other than the leading whitespace or the rest of the string after the digits. +Return the integer as the final result. **Example 1:** @@ -24,161 +19,51 @@ The algorithm for `myAtoi(string s)` is as follows: **Output:** 42 -**Explanation:** The underlined characters are what is read in, the caret is the current reader position. - - Step 1: "42" (no characters read because there is no leading whitespace) - ^ - Step 2: "42" (no characters read because there is neither a '-' nor '+') - ^ - Step 3: "42" ("42" is read in) - ^ +**Explanation:** -The parsed integer is 42. Since 42 is in the range [-231, 231 - 1], the final result is 42. +The underlined characters are what is read in and the caret is the current reader position. Step 1: "42" (no characters read because there is no leading whitespace) ^ Step 2: "42" (no characters read because there is neither a '-' nor '+') ^ Step 3: "42" ("42" is read in) ^ **Example 2:** -**Input:** s = " -42" +**Input:** s = " -042" -**Output:** -42 +**Output:** \-42 **Explanation:** - Step 1: " -42" (leading whitespace is read and ignored) - ^ - Step 2: " -42" ('-' is read, so the result should be negative) - ^ - Step 3: " -42" ("42" is read in) - ^ - The parsed integer is -42. - -Since -42 is in the range [-231, 231 - 1], the final result is -42. +Step 1: " \-042" (leading whitespace is read and ignored) ^ Step 2: " \-042" ('-' is read, so the result should be negative) ^ Step 3: " -042" ("042" is read in, leading zeros ignored in the result) ^ **Example 3:** -**Input:** s = "4193 with words" +**Input:** s = "1337c0d3" -**Output:** 4193 +**Output:** 1337 **Explanation:** - Step 1: "4193 with words" (no characters read because there is no leading whitespace) - ^ - Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+') - ^ - Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit) - ^ - The parsed integer is 4193. - -Since 4193 is in the range [-231, 231 - 1], the final result is 4193. +Step 1: "1337c0d3" (no characters read because there is no leading whitespace) ^ Step 2: "1337c0d3" (no characters read because there is neither a '-' nor '+') ^ Step 3: "1337c0d3" ("1337" is read in; reading stops because the next character is a non-digit) ^ **Example 4:** -**Input:** s = "words and 987" +**Input:** s = "0-1" **Output:** 0 **Explanation:** - Step 1: "words and 987" (no characters read because there is no leading whitespace) - ^ - Step 2: "words and 987" (no characters read because there is neither a '-' nor '+') - ^ - Step 3: "words and 987" (reading stops immediately because there is a non-digit 'w') - ^ - The parsed integer is 0 because no digits were read. - -Since 0 is in the range [-231, 231 - 1], the final result is 0. +Step 1: "0-1" (no characters read because there is no leading whitespace) ^ Step 2: "0-1" (no characters read because there is neither a '-' nor '+') ^ Step 3: "0\-1" ("0" is read in; reading stops because the next character is a non-digit) ^ **Example 5:** -**Input:** s = "-91283472332" +**Input:** s = "words and 987" -**Output:** -2147483648 +**Output:** 0 **Explanation:** - Step 1: "-91283472332" (no characters read because there is no leading whitespace) - ^ - Step 2: "-91283472332" ('-' is read, so the result should be negative) - ^ - Step 3: "-91283472332" ("91283472332" is read in) - ^ - The parsed integer is -91283472332. - -Since -91283472332 is less than the lower bound of the range [-231, 231 - 1], the final result is clamped to -231 = -2147483648. +Reading stops at the first non-digit character 'w'. **Constraints:** * `0 <= s.length <= 200` -* `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`. - -To solve the String to Integer (atoi) problem in Java using a `Solution` class, we'll follow these steps: - -1. Define a `Solution` class with a method named `myAtoi`. -2. Trim leading whitespace from the input string `s`. -3. Check if the string is empty after trimming. If so, return 0. -4. Initialize variables to keep track of the sign of the integer (`sign`), the starting index of the numeric characters (`start`), and the result (`result`). -5. Check if the first character of the trimmed string is `'-'` or `'+'`. Update `sign` accordingly, and move the starting index accordingly. -6. Iterate through the characters of the trimmed string starting from the `start` index: - - Check if the current character is a digit. If not, break the loop. - - Convert the character to its numeric value and update the `result`. - - Check if the result exceeds the 32-bit integer range. If so, clamp it to the range and return. -7. Multiply the `result` by the sign and return the final value. -8. Handle edge cases where the input string is empty, consists of only whitespace, or contains non-numeric characters at the beginning. - -Here's the implementation: - -```java -public class Solution { - - public int myAtoi(String s) { - s = s.trim(); - if (s.isEmpty()) - return 0; - - int sign = 1; - int start = 0; - long result = 0; - - if (s.charAt(0) == '-' || s.charAt(0) == '+') { - sign = (s.charAt(0) == '-') ? -1 : 1; - start++; - } - - for (int i = start; i < s.length(); i++) { - char c = s.charAt(i); - if (!Character.isDigit(c)) - break; - result = result * 10 + (c - '0'); - if (result * sign > Integer.MAX_VALUE) - return Integer.MAX_VALUE; - if (result * sign < Integer.MIN_VALUE) - return Integer.MIN_VALUE; - } - - return (int) (result * sign); - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - String s1 = "42"; - System.out.println("Example 1 Output: " + solution.myAtoi(s1)); - - String s2 = " -42"; - System.out.println("Example 2 Output: " + solution.myAtoi(s2)); - - String s3 = "4193 with words"; - System.out.println("Example 3 Output: " + solution.myAtoi(s3)); - - String s4 = "words and 987"; - System.out.println("Example 4 Output: " + solution.myAtoi(s4)); - - String s5 = "-91283472332"; - System.out.println("Example 5 Output: " + solution.myAtoi(s5)); - } -} -``` - -This implementation provides a solution to the String to Integer (atoi) problem in Java. \ No newline at end of file +* `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0009_palindrome_number/readme.md b/src/main/java/g0001_0100/s0009_palindrome_number/readme.md index 464312411..efe0f5c0d 100644 --- a/src/main/java/g0001_0100/s0009_palindrome_number/readme.md +++ b/src/main/java/g0001_0100/s0009_palindrome_number/readme.md @@ -2,15 +2,15 @@ Easy -Given an integer `x`, return `true` if `x` is palindrome integer. - -An integer is a **palindrome** when it reads the same backward as forward. For example, `121` is palindrome while `123` is not. +Given an integer `x`, return `true` _if_ `x` _is a_ _**palindrome**__, and_ `false` _otherwise_. **Example 1:** **Input:** x = 121 -**Output:** true +**Output:** true + +**Explanation:** 121 reads as 121 from left to right and from right to left. **Example 2:** @@ -28,73 +28,8 @@ An integer is a **palindrome** when it reads the same backward as forward. For e **Explanation:** Reads 01 from right to left. Therefore it is not a palindrome. -**Example 4:** - -**Input:** x = -101 - -**Output:** false - **Constraints:** * -231 <= x <= 231 - 1 -**Follow up:** Could you solve it without converting the integer to a string? - -To solve the Palindrome Number problem in Java using a `Solution` class, we'll follow these steps: - -1. Define a `Solution` class with a method named `isPalindrome`. -2. Handle special cases where `x` is negative or divisible by 10 but not equal to zero, as they cannot be palindromes. -3. Initialize variables to keep track of the reversed number (`reversed`) and the original number (`original`). -4. Iterate through the digits of the original number `x`: - - Extract the least significant digit using the modulo operator and append it to the reversed number. - - Update `original` by removing the least significant digit using integer division. -5. Check if the reversed number is equal to the original number. If so, return `true`; otherwise, return `false`. - -Here's the implementation: - -```java -public class Solution { - - public boolean isPalindrome(int x) { - // Special cases: - // As discussed, negative numbers are not palindromes. - // Also, if the last digit of the number is 0, it can't be a palindrome unless the number is 0 itself. - if (x < 0 || (x % 10 == 0 && x != 0)) { - return false; - } - - int reversed = 0; - int original = x; - - while (original > reversed) { - int digit = original % 10; - reversed = reversed * 10 + digit; - original /= 10; - } - - // When the length is an odd number, we can get rid of the middle digit by reversed / 10 - // For example when the input is 12321, at the end of the while loop we get x = 12, reversed = 123, - // since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it. - return original == reversed || original == reversed / 10; - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - int x1 = 121; - System.out.println("Example 1 Output: " + solution.isPalindrome(x1)); - - int x2 = -121; - System.out.println("Example 2 Output: " + solution.isPalindrome(x2)); - - int x3 = 10; - System.out.println("Example 3 Output: " + solution.isPalindrome(x3)); - - int x4 = -101; - System.out.println("Example 4 Output: " + solution.isPalindrome(x4)); - } -} -``` - -This implementation provides a solution to the Palindrome Number problem in Java. \ No newline at end of file +**Follow up:** Could you solve it without converting the integer to a string? \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0010_regular_expression_matching/readme.md b/src/main/java/g0001_0100/s0010_regular_expression_matching/readme.md index f38de36c6..ed34a26ee 100644 --- a/src/main/java/g0001_0100/s0010_regular_expression_matching/readme.md +++ b/src/main/java/g0001_0100/s0010_regular_expression_matching/readme.md @@ -33,87 +33,10 @@ The matching should cover the **entire** input string (not partial). **Explanation:** ".\*" means "zero or more (\*) of any character (.)". -**Example 4:** - -**Input:** s = "aab", p = "c\*a\*b" - -**Output:** true - -**Explanation:** c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab". - -**Example 5:** - -**Input:** s = "mississippi", p = "mis\*is\*p\*." - -**Output:** false - **Constraints:** * `1 <= s.length <= 20` -* `1 <= p.length <= 30` +* `1 <= p.length <= 20` * `s` contains only lowercase English letters. * `p` contains only lowercase English letters, `'.'`, and `'*'`. -* It is guaranteed for each appearance of the character `'*'`, there will be a previous valid character to match. - -To solve the Regular Expression Matching problem in Java using a `Solution` class, we'll follow these steps: - -1. Define a `Solution` class with a method named `isMatch`. -2. Implement a recursive approach to check for pattern matching. -3. Base cases: - - If the pattern string is empty, return `s.isEmpty()`. - - If the pattern string's length is 1 or the next character after `*` is `.`: - - Check if the length of `s` is 1 and the characters match or the pattern is `.`. - - If so, return `true`; otherwise, return `false`. -4. If the second character of the pattern is not `*`, recursively call `isMatch` with the substring starting from the second character. -5. If the second character of the pattern is `*`, recursively check all possibilities: - - Zero occurrences of the preceding character (skipping `*` and the character before it). - - One or more occurrences of the preceding character (matching the first character and recursively calling `isMatch` for the remaining part of the string). -6. Return the result of the recursive checks. -7. Handle edge cases where the input strings are empty or the pattern contains invalid characters. - -Here's the implementation: - -```java -public class Solution { - - public boolean isMatch(String s, String p) { - if (p.isEmpty()) - return s.isEmpty(); - - boolean firstMatch = !s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.'); - - if (p.length() >= 2 && p.charAt(1) == '*') { - return isMatch(s, p.substring(2)) || (firstMatch && isMatch(s.substring(1), p)); - } else { - return firstMatch && isMatch(s.substring(1), p.substring(1)); - } - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - String s1 = "aa"; - String p1 = "a"; - System.out.println("Example 1 Output: " + solution.isMatch(s1, p1)); - - String s2 = "aa"; - String p2 = "a*"; - System.out.println("Example 2 Output: " + solution.isMatch(s2, p2)); - - String s3 = "ab"; - String p3 = ".*"; - System.out.println("Example 3 Output: " + solution.isMatch(s3, p3)); - - String s4 = "aab"; - String p4 = "c*a*b"; - System.out.println("Example 4 Output: " + solution.isMatch(s4, p4)); - - String s5 = "mississippi"; - String p5 = "mis*is*p*."; - System.out.println("Example 5 Output: " + solution.isMatch(s5, p5)); - } -} -``` - -This implementation provides a solution to the Regular Expression Matching problem in Java. \ No newline at end of file +* It is guaranteed for each appearance of the character `'*'`, there will be a previous valid character to match. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0011_container_with_most_water/readme.md b/src/main/java/g0001_0100/s0011_container_with_most_water/readme.md index 3f5f57efe..baa84ca0d 100644 --- a/src/main/java/g0001_0100/s0011_container_with_most_water/readme.md +++ b/src/main/java/g0001_0100/s0011_container_with_most_water/readme.md @@ -2,7 +2,11 @@ Medium -Given `n` non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). `n` vertical lines are drawn such that the two endpoints of the line `i` is at (i, ai) and `(i, 0)`. Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. +You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the ith line are `(i, 0)` and `(i, height[i])`. + +Find two lines that together with the x-axis form a container, such that the container contains the most water. + +Return _the maximum amount of water a container can store_. **Notice** that you may not slant the container. @@ -22,76 +26,8 @@ Given `n` non-negative integers a1, a2, ..., an **Output:** 1 -**Example 3:** - -**Input:** height = [4,3,2,1,4] - -**Output:** 16 - -**Example 4:** - -**Input:** height = [1,2,1] - -**Output:** 2 - **Constraints:** * `n == height.length` * 2 <= n <= 105 -* 0 <= height[i] <= 104 - -To solve the Container With Most Water problem in Java using a `Solution` class, we'll follow these steps: - -1. Define a `Solution` class with a method named `maxArea` that takes an array of integers `height` as input and returns the maximum area of water that can be contained. -2. Initialize two pointers, `left` pointing to the start of the array and `right` pointing to the end of the array. -3. Initialize a variable `maxArea` to store the maximum area encountered so far, initially set to 0. -4. Iterate while `left` is less than `right`. -5. Calculate the current area using the formula: `(right - left) * min(height[left], height[right])`. -6. Update `maxArea` if the current area is greater than `maxArea`. -7. Move the pointer pointing to the smaller height towards the other pointer. If `height[left] < height[right]`, increment `left`, otherwise decrement `right`. -8. Continue the iteration until `left` becomes greater than or equal to `right`. -9. Return `maxArea`. - -Here's the implementation: - -```java -public class Solution { - public int maxArea(int[] height) { - int left = 0; - int right = height.length - 1; - int maxArea = 0; - - while (left < right) { - int currentArea = (right - left) * Math.min(height[left], height[right]); - maxArea = Math.max(maxArea, currentArea); - - if (height[left] < height[right]) { - left++; - } else { - right--; - } - } - - return maxArea; - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - int[] height1 = {1, 8, 6, 2, 5, 4, 8, 3, 7}; - System.out.println("Example 1 Output: " + solution.maxArea(height1)); - - int[] height2 = {1, 1}; - System.out.println("Example 2 Output: " + solution.maxArea(height2)); - - int[] height3 = {4, 3, 2, 1, 4}; - System.out.println("Example 3 Output: " + solution.maxArea(height3)); - - int[] height4 = {1, 2, 1}; - System.out.println("Example 4 Output: " + solution.maxArea(height4)); - } -} -``` - -This implementation provides a solution to the Container With Most Water problem in Java. \ No newline at end of file +* 0 <= height[i] <= 104 \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0012_integer_to_roman/readme.md b/src/main/java/g0001_0100/s0012_integer_to_roman/readme.md index 456e0cfec..b411a2c09 100644 --- a/src/main/java/g0001_0100/s0012_integer_to_roman/readme.md +++ b/src/main/java/g0001_0100/s0012_integer_to_roman/readme.md @@ -2,61 +2,78 @@ Medium -Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. +Seven different symbols represent Roman numerals with the following values: - Symbol Value - I 1 - V 5 - X 10 - L 50 - C 100 - D 500 - M 1000 +Symbol -For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. +Value -Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: +I -* `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. -* `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. -* `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. +1 -Given an integer, convert it to a roman numeral. +V -**Example 1:** +5 -**Input:** num = 3 +X -**Output:** "III" +10 -**Example 2:** +L -**Input:** num = 4 +50 -**Output:** "IV" +C -**Example 3:** +100 + +D + +500 + +M + +1000 + +Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules: + +* If the value does not start with 4 or 9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral. +* If the value starts with 4 or 9 use the **subtractive form** representing one symbol subtracted from the following symbol, for example, 4 is 1 (`I`) less than 5 (`V`): `IV` and 9 is 1 (`I`) less than 10 (`X`): `IX`. Only the following subtractive forms are used: 4 (`IV`), 9 (`IX`), 40 (`XL`), 90 (`XC`), 400 (`CD`) and 900 (`CM`). +* Only powers of 10 (`I`, `X`, `C`, `M`) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5 (`V`), 50 (`L`), or 500 (`D`) multiple times. If you need to append a symbol 4 times use the **subtractive form**. -**Input:** num = 9 +Given an integer, convert it to a Roman numeral. -**Output:** "IX" +**Example 1:** + +**Input:** num = 3749 + +**Output:** "MMMDCCXLIX" -**Example 4:** +**Explanation:** + +3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) 700 = DCC as 500 (D) + 100 (C) + 100 (C) 40 = XL as 10 (X) less of 50 (L) 9 = IX as 1 (I) less of 10 (X) Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places + +**Example 2:** **Input:** num = 58 **Output:** "LVIII" -**Explanation:** L = 50, V = 5, III = 3. +**Explanation:** + +50 = L 8 = VIII -**Example 5:** +**Example 3:** **Input:** num = 1994 **Output:** "MCMXCIV" -**Explanation:** M = 1000, CM = 900, XC = 90 and IV = 4. +**Explanation:** + +1000 = M 900 = CM 90 = XC 4 = IV **Constraints:** -* `1 <= num <= 3999` +* `1 <= num <= 3999` \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0013_roman_to_integer/readme.md b/src/main/java/g0001_0100/s0013_roman_to_integer/readme.md index 14bbde8ed..c6b9a9850 100644 --- a/src/main/java/g0001_0100/s0013_roman_to_integer/readme.md +++ b/src/main/java/g0001_0100/s0013_roman_to_integer/readme.md @@ -4,16 +4,9 @@ Easy Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. - Symbol Value - I 1 - V 5 - X 10 - L 50 - C 100 - D 500 - M 1000 +**Symbol** **Value** I 1 V 5 X 10 L 50 C 100 D 500 M 1000 -For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. +For example, `2` is written as `II` in Roman numeral, just two ones added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: @@ -27,21 +20,11 @@ Given a roman numeral, convert it to an integer. **Input:** s = "III" -**Output:** 3 +**Output:** 3 -**Example 2:** - -**Input:** s = "IV" - -**Output:** 4 - -**Example 3:** +**Explanation:** III = 3. -**Input:** s = "IX" - -**Output:** 9 - -**Example 4:** +**Example 2:** **Input:** s = "LVIII" @@ -49,7 +32,7 @@ Given a roman numeral, convert it to an integer. **Explanation:** L = 50, V= 5, III = 3. -**Example 5:** +**Example 3:** **Input:** s = "MCMXCIV" @@ -61,4 +44,4 @@ Given a roman numeral, convert it to an integer. * `1 <= s.length <= 15` * `s` contains only the characters `('I', 'V', 'X', 'L', 'C', 'D', 'M')`. -* It is **guaranteed** that `s` is a valid roman numeral in the range `[1, 3999]`. +* It is **guaranteed** that `s` is a valid roman numeral in the range `[1, 3999]`. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0014_longest_common_prefix/readme.md b/src/main/java/g0001_0100/s0014_longest_common_prefix/readme.md index 3f23b8c72..f08c69449 100644 --- a/src/main/java/g0001_0100/s0014_longest_common_prefix/readme.md +++ b/src/main/java/g0001_0100/s0014_longest_common_prefix/readme.md @@ -24,4 +24,4 @@ If there is no common prefix, return an empty string `""`. * `1 <= strs.length <= 200` * `0 <= strs[i].length <= 200` -* `strs[i]` consists of only lower-case English letters. \ No newline at end of file +* `strs[i]` consists of only lowercase English letters if it is non-empty. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0015_3sum/readme.md b/src/main/java/g0001_0100/s0015_3sum/readme.md index 7d75ee60c..12aa783ee 100644 --- a/src/main/java/g0001_0100/s0015_3sum/readme.md +++ b/src/main/java/g0001_0100/s0015_3sum/readme.md @@ -10,100 +10,27 @@ Notice that the solution set must not contain duplicate triplets. **Input:** nums = [-1,0,1,2,-1,-4] -**Output:** [[-1,-1,2],[-1,0,1]] +**Output:** [[-1,-1,2],[-1,0,1]] + +**Explanation:** nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. **Example 2:** -**Input:** nums = [] +**Input:** nums = [0,1,1] + +**Output:** [] -**Output:** [] +**Explanation:** The only possible triplet does not sum up to 0. **Example 3:** -**Input:** nums = [0] +**Input:** nums = [0,0,0] + +**Output:** [[0,0,0]] -**Output:** [] +**Explanation:** The only possible triplet sums up to 0. **Constraints:** -* `0 <= nums.length <= 3000` -* -105 <= nums[i] <= 105 - -To solve the 3Sum problem in Java using a `Solution` class, we'll follow these steps: - -1. Define a `Solution` class with a method named `threeSum` that takes an array of integers `nums` as input and returns a list of lists representing the triplets that sum up to zero. -2. Sort the input array `nums` to ensure that duplicate triplets are avoided. -3. Initialize an empty list `result` to store the triplets. -4. Iterate over the elements of the sorted array `nums` up to the second to last element. -5. Within the outer loop, initialize two pointers, `left` and `right`, where `left` starts at the next element after the current element and `right` starts at the last element of the array. -6. While `left` is less than `right`, check if the sum of the current element (`nums[i]`), `nums[left]`, and `nums[right]` equals zero. -7. If the sum is zero, add `[nums[i], nums[left], nums[right]]` to the `result` list. -8. Move the `left` pointer to the right (increment `left`) and the `right` pointer to the left (decrement `right`). -9. If the sum is less than zero, increment `left`. -10. If the sum is greater than zero, decrement `right`. -11. After the inner loop finishes, increment the outer loop index while skipping duplicates. -12. Return the `result` list containing all the valid triplets. - -Here's the implementation: - -```java -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class Solution { - public List> threeSum(int[] nums) { - Arrays.sort(nums); - List> result = new ArrayList<>(); - - for (int i = 0; i < nums.length - 2; i++) { - if (i > 0 && nums[i] == nums[i - 1]) { - continue; // Skip duplicates - } - - int left = i + 1; - int right = nums.length - 1; - - while (left < right) { - int sum = nums[i] + nums[left] + nums[right]; - if (sum == 0) { - result.add(Arrays.asList(nums[i], nums[left], nums[right])); - - // Skip duplicates - while (left < right && nums[left] == nums[left + 1]) { - left++; - } - while (left < right && nums[right] == nums[right - 1]) { - right--; - } - - left++; - right--; - } else if (sum < 0) { - left++; - } else { - right--; - } - } - } - - return result; - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - int[] nums1 = {-1, 0, 1, 2, -1, -4}; - System.out.println("Example 1 Output: " + solution.threeSum(nums1)); - - int[] nums2 = {}; - System.out.println("Example 2 Output: " + solution.threeSum(nums2)); - - int[] nums3 = {0}; - System.out.println("Example 3 Output: " + solution.threeSum(nums3)); - } -} -``` - -This implementation provides a solution to the 3Sum problem in Java. \ No newline at end of file +* `3 <= nums.length <= 3000` +* -105 <= nums[i] <= 105 \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0017_letter_combinations_of_a_phone_number/readme.md b/src/main/java/g0001_0100/s0017_letter_combinations_of_a_phone_number/readme.md index ef64b4eaf..1c6fd79d3 100644 --- a/src/main/java/g0001_0100/s0017_letter_combinations_of_a_phone_number/readme.md +++ b/src/main/java/g0001_0100/s0017_letter_combinations_of_a_phone_number/readme.md @@ -4,9 +4,9 @@ Medium Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**. -A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. +A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. -![](https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png) +![](https://assets.leetcode.com/uploads/2022/03/15/1200px-telephone-keypad2svg.png) **Example 1:** @@ -16,90 +16,11 @@ A mapping of digit to letters (just like on the telephone buttons) is given belo **Example 2:** -**Input:** digits = "" - -**Output:** [] - -**Example 3:** - **Input:** digits = "2" **Output:** ["a","b","c"] **Constraints:** -* `0 <= digits.length <= 4` -* `digits[i]` is a digit in the range `['2', '9']`. - -To solve the Letter Combinations of a Phone Number problem in Java using a `Solution` class, we'll follow these steps: - -1. Define a `Solution` class with a method named `letterCombinations` that takes a string `digits` as input and returns a list of all possible letter combinations. -2. Create a mapping of digits to letters using a hashmap or an array. -3. Initialize an empty list `result` to store the combinations. -4. If the input string `digits` is empty, return an empty list `result`. -5. Call a recursive function `generateCombinations` to generate combinations for each digit. -6. Within the recursive function: - - Base case: If the current combination length equals the length of the input `digits`, add the combination to the `result` list. - - Recursive step: For the current digit, iterate over its corresponding letters and append each letter to the current combination, then recursively call the function with the next digit. -7. Return the `result` list containing all possible combinations. - -Here's the implementation: - -```java -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class Solution { - private static final Map digitToLetters = new HashMap<>(); - static { - digitToLetters.put('2', "abc"); - digitToLetters.put('3', "def"); - digitToLetters.put('4', "ghi"); - digitToLetters.put('5', "jkl"); - digitToLetters.put('6', "mno"); - digitToLetters.put('7', "pqrs"); - digitToLetters.put('8', "tuv"); - digitToLetters.put('9', "wxyz"); - } - - public List letterCombinations(String digits) { - List result = new ArrayList<>(); - if (digits.length() == 0) { - return result; - } - generateCombinations(result, digits, "", 0); - return result; - } - - private void generateCombinations(List result, String digits, String combination, int index) { - if (index == digits.length()) { - result.add(combination); - return; - } - - char digit = digits.charAt(index); - String letters = digitToLetters.get(digit); - for (char letter : letters.toCharArray()) { - generateCombinations(result, digits, combination + letter, index + 1); - } - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - String digits1 = "23"; - System.out.println("Example 1 Output: " + solution.letterCombinations(digits1)); - - String digits2 = ""; - System.out.println("Example 2 Output: " + solution.letterCombinations(digits2)); - - String digits3 = "2"; - System.out.println("Example 3 Output: " + solution.letterCombinations(digits3)); - } -} -``` - -This implementation provides a solution to the Letter Combinations of a Phone Number problem in Java. \ No newline at end of file +* `1 <= digits.length <= 4` +* `digits[i]` is a digit in the range `['2', '9']`. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0019_remove_nth_node_from_end_of_list/readme.md b/src/main/java/g0001_0100/s0019_remove_nth_node_from_end_of_list/readme.md index 0c5ecdd10..8e3684653 100644 --- a/src/main/java/g0001_0100/s0019_remove_nth_node_from_end_of_list/readme.md +++ b/src/main/java/g0001_0100/s0019_remove_nth_node_from_end_of_list/readme.md @@ -2,7 +2,7 @@ Medium -Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head. +Given the `head` of a linked list, remove the nth node from the end of the list and return its head. **Example 1:** @@ -31,95 +31,4 @@ Given the `head` of a linked list, remove the `nth` node from the end of the lis * `0 <= Node.val <= 100` * `1 <= n <= sz` -**Follow up:** Could you do this in one pass? - -To solve the Remove Nth Node From End of List problem in Java with a `Solution` class, we'll follow these steps: - -1. Define a `ListNode` class representing the nodes of the linked list. -2. Define a `Solution` class with a method named `removeNthFromEnd` that takes the head of the linked list and an integer `n` as input and returns the head of the modified list. -3. Create two pointers, `fast` and `slow`, and initialize them to point to the head of the list. -4. Move the `fast` pointer `n` steps forward in the list. -5. If the `fast` pointer reaches the end of the list (`fast == null`), it means that `n` is equal to the length of the list. In this case, remove the head node by returning `head.next`. -6. Move both `fast` and `slow` pointers simultaneously until the `fast` pointer reaches the end of the list. -7. At this point, the `slow` pointer will be pointing to the node just before the node to be removed. -8. Remove the `nth` node by updating the `next` reference of the node pointed to by the `slow` pointer to skip the `nth` node. -9. Return the head of the modified list. - -Here's the implementation: - -```java -public class ListNode { - int val; - ListNode next; - ListNode(int val) { this.val = val; } -} - -public class Solution { - public ListNode removeNthFromEnd(ListNode head, int n) { - ListNode dummy = new ListNode(0); - dummy.next = head; - ListNode fast = dummy; - ListNode slow = dummy; - - // Move the fast pointer n steps forward - for (int i = 0; i <= n; i++) { - fast = fast.next; - } - - // Move both pointers until the fast pointer reaches the end - while (fast != null) { - fast = fast.next; - slow = slow.next; - } - - // Remove the nth node - slow.next = slow.next.next; - - return dummy.next; - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Example 1 - ListNode head1 = new ListNode(1); - head1.next = new ListNode(2); - head1.next.next = new ListNode(3); - head1.next.next.next = new ListNode(4); - head1.next.next.next.next = new ListNode(5); - int n1 = 2; - ListNode result1 = solution.removeNthFromEnd(head1, n1); - printList(result1); // Output: [1,2,3,5] - - // Example 2 - ListNode head2 = new ListNode(1); - int n2 = 1; - ListNode result2 = solution.removeNthFromEnd(head2, n2); - printList(result2); // Output: [] - - // Example 3 - ListNode head3 = new ListNode(1); - head3.next = new ListNode(2); - int n3 = 1; - ListNode result3 = solution.removeNthFromEnd(head3, n3); - printList(result3); // Output: [1] - } - - private static void printList(ListNode head) { - if (head == null) { - System.out.println("[]"); - return; - } - StringBuilder sb = new StringBuilder("["); - while (head != null) { - sb.append(head.val).append(","); - head = head.next; - } - sb.setLength(sb.length() - 1); - sb.append("]"); - System.out.println(sb.toString()); - } -} -``` - -This implementation provides a solution to the Remove Nth Node From End of List problem in Java. \ No newline at end of file +**Follow up:** Could you do this in one pass? \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0020_valid_parentheses/readme.md b/src/main/java/g0001_0100/s0020_valid_parentheses/readme.md index e5f550055..d07dccb22 100644 --- a/src/main/java/g0001_0100/s0020_valid_parentheses/readme.md +++ b/src/main/java/g0001_0100/s0020_valid_parentheses/readme.md @@ -8,90 +8,39 @@ An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. +3. Every close bracket has a corresponding open bracket of the same type. **Example 1:** **Input:** s = "()" -**Output:** true +**Output:** true **Example 2:** **Input:** s = "()[]{}" -**Output:** true +**Output:** true **Example 3:** **Input:** s = "(]" -**Output:** false +**Output:** false **Example 4:** -**Input:** s = "([)]" +**Input:** s = "([])" -**Output:** false +**Output:** true **Example 5:** -**Input:** s = "{[]}" +**Input:** s = "([)]" -**Output:** true +**Output:** false **Constraints:** * 1 <= s.length <= 104 -* `s` consists of parentheses only `'()[]{}'`. - -To solve the Valid Parentheses problem in Java with a `Solution` class, we'll use a stack data structure. Here are the steps: - -1. Define a `Solution` class with a method named `isValid` that takes a string `s` as input and returns a boolean indicating whether the string contains valid parentheses. -2. Create a stack to store opening parentheses. -3. Iterate through each character in the input string `s`. -4. If the current character is an opening parenthesis (`'('`, `'{'`, or `'['`), push it onto the stack. -5. If the current character is a closing parenthesis (`')'`, `'}'`, or `']'`), check if the stack is empty. If it is, return `false` because there's no matching opening parenthesis for the current closing parenthesis. -6. If the stack is not empty, pop the top element from the stack and check if it matches the current closing parenthesis. If it doesn't match, return `false`. -7. After iterating through all characters in `s`, check if the stack is empty. If it's not empty, return `false` because there are unmatched opening parentheses remaining. -8. If the stack is empty after processing all characters, return `true` because all parentheses are valid. - -Here's the implementation: - -```java -import java.util.Stack; - -public class Solution { - public boolean isValid(String s) { - Stack stack = new Stack<>(); - - for (char c : s.toCharArray()) { - if (c == '(' || c == '{' || c == '[') { - stack.push(c); - } else { - if (stack.isEmpty()) { - return false; - } - char top = stack.pop(); - if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) { - return false; - } - } - } - - return stack.isEmpty(); - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - System.out.println(solution.isValid("()")); // true - System.out.println(solution.isValid("()[]{}")); // true - System.out.println(solution.isValid("(]")); // false - System.out.println(solution.isValid("([)]")); // false - System.out.println(solution.isValid("{[]}")); // true - } -} -``` - -This implementation provides a solution to the Valid Parentheses problem in Java using a stack data structure. \ No newline at end of file +* `s` consists of parentheses only `'()[]{}'`. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0021_merge_two_sorted_lists/readme.md b/src/main/java/g0001_0100/s0021_merge_two_sorted_lists/readme.md index 591a61c30..27127cdda 100644 --- a/src/main/java/g0001_0100/s0021_merge_two_sorted_lists/readme.md +++ b/src/main/java/g0001_0100/s0021_merge_two_sorted_lists/readme.md @@ -2,25 +2,29 @@ Easy -Merge two sorted linked lists and return it as a **sorted** list. The list should be made by splicing together the nodes of the first two lists. +You are given the heads of two sorted linked lists `list1` and `list2`. + +Merge the two lists into one **sorted** list. The list should be made by splicing together the nodes of the first two lists. + +Return _the head of the merged linked list_. **Example 1:** ![](https://assets.leetcode.com/uploads/2020/10/03/merge_ex1.jpg) -**Input:** l1 = [1,2,4], l2 = [1,3,4] +**Input:** list1 = [1,2,4], list2 = [1,3,4] **Output:** [1,1,2,3,4,4] **Example 2:** -**Input:** l1 = [], l2 = [] +**Input:** list1 = [], list2 = [] **Output:** [] **Example 3:** -**Input:** l1 = [], l2 = [0] +**Input:** list1 = [], list2 = [0] **Output:** [0] @@ -28,71 +32,4 @@ Merge two sorted linked lists and return it as a **sorted** list. The list shoul * The number of nodes in both lists is in the range `[0, 50]`. * `-100 <= Node.val <= 100` -* Both `l1` and `l2` are sorted in **non-decreasing** order. - -To solve the Merge Two Sorted Lists problem in Java with a `Solution` class, we'll implement a recursive approach. Here are the steps: - -1. Define a `ListNode` class to represent a node in the linked list. -2. Define a `Solution` class with a method named `mergeTwoLists` that takes two linked lists `l1` and `l2` as input and returns a merged sorted list. -3. The base case for the recursion is when either `l1` or `l2` is null. In this case, return the non-null list because it's already sorted. -4. Compare the values of the heads of `l1` and `l2`. Let `head` be the smaller value of the two heads. -5. Recursively call `mergeTwoLists` with the next node of the smaller head and the other list that remained unchanged. -6. Update the `next` pointer of the smaller head to point to the result of the recursive call. -7. Return the smaller head, which is the merged sorted list. - -Here's the implementation: - -```java -public class Solution { - static class ListNode { - int val; - ListNode next; - - ListNode(int val) { - this.val = val; - } - } - - public ListNode mergeTwoLists(ListNode l1, ListNode l2) { - if (l1 == null) { - return l2; - } - if (l2 == null) { - return l1; - } - - ListNode head; - if (l1.val < l2.val) { - head = l1; - head.next = mergeTwoLists(l1.next, l2); - } else { - head = l2; - head.next = mergeTwoLists(l1, l2.next); - } - - return head; - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - ListNode l1 = new ListNode(1); - l1.next = new ListNode(2); - l1.next.next = new ListNode(4); - - ListNode l2 = new ListNode(1); - l2.next = new ListNode(3); - l2.next.next = new ListNode(4); - - ListNode mergedList = solution.mergeTwoLists(l1, l2); - while (mergedList != null) { - System.out.print(mergedList.val + " "); - mergedList = mergedList.next; - } - System.out.println(); // newline - } -} -``` - -This implementation provides a solution to the Merge Two Sorted Lists problem in Java using a recursive approach. \ No newline at end of file +* Both `list1` and `list2` are sorted in **non-decreasing** order. \ No newline at end of file diff --git a/src/main/java/g0001_0100/s0022_generate_parentheses/readme.md b/src/main/java/g0001_0100/s0022_generate_parentheses/readme.md index 5c1679e59..72cab17b6 100644 --- a/src/main/java/g0001_0100/s0022_generate_parentheses/readme.md +++ b/src/main/java/g0001_0100/s0022_generate_parentheses/readme.md @@ -18,61 +18,4 @@ Given `n` pairs of parentheses, write a function to _generate all combinations o **Constraints:** -* `1 <= n <= 8` - -To solve the "Generate Parentheses" problem in Java with a `Solution` class, we can use a backtracking approach. Here are the steps: - -1. Define a `Solution` class. -2. Define a method named `generateParenthesis` that takes an integer `n` as input and returns a list of strings representing all combinations of well-formed parentheses. -3. Create an empty list to store the result. -4. Call the recursive helper function `generateParenthesisHelper` with the empty string `""`, counts of open and close parentheses set to `0`, the value of `n`, and the result list. -5. In the `generateParenthesisHelper` function: - - If the length of the current string is equal to `2 * n`, add it to the result list. - - If the count of open parentheses is less than `n`, append an open parenthesis to the current string and call the function recursively with increased open count. - - If the count of close parentheses is less than the count of open parentheses, append a close parenthesis to the current string and call the function recursively with increased close count. -6. Return the result list. - -Here's the implementation: - -```java -import java.util.ArrayList; -import java.util.List; - -public class Solution { - public List generateParenthesis(int n) { - List result = new ArrayList<>(); - generateParenthesisHelper("", 0, 0, n, result); - return result; - } - - private void generateParenthesisHelper(String current, int open, int close, int n, List result) { - if (current.length() == 2 * n) { - result.add(current); - return; - } - - if (open < n) { - generateParenthesisHelper(current + "(", open + 1, close, n, result); - } - - if (close < open) { - generateParenthesisHelper(current + ")", open, close + 1, n, result); - } - } - - public static void main(String[] args) { - Solution solution = new Solution(); - - // Test cases - int n1 = 3; - System.out.println("Parentheses combinations for n = " + n1 + ":"); - System.out.println(solution.generateParenthesis(n1)); - - int n2 = 1; - System.out.println("\nParentheses combinations for n = " + n2 + ":"); - System.out.println(solution.generateParenthesis(n2)); - } -} -``` - -This implementation provides a solution to the "Generate Parentheses" problem in Java using a backtracking approach. \ No newline at end of file +* `1 <= n <= 8` \ No newline at end of file From 3be15c5c1f32ef0d0b1ed829240b5a3e458aefff Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 15:44:45 +0200 Subject: [PATCH 02/21] Refactor readme for integer to Roman conversion Removed redundant table format for Roman numeral values and simplified the presentation. --- .../s0012_integer_to_roman/readme.md | 42 +++++-------------- 1 file changed, 10 insertions(+), 32 deletions(-) diff --git a/src/main/java/g0001_0100/s0012_integer_to_roman/readme.md b/src/main/java/g0001_0100/s0012_integer_to_roman/readme.md index b411a2c09..4e5d58c77 100644 --- a/src/main/java/g0001_0100/s0012_integer_to_roman/readme.md +++ b/src/main/java/g0001_0100/s0012_integer_to_roman/readme.md @@ -4,37 +4,15 @@ Medium Seven different symbols represent Roman numerals with the following values: -Symbol - -Value - -I - -1 - -V - -5 - -X - -10 - -L - -50 - -C - -100 - -D - -500 - -M - -1000 +| Symbol | Value | +|--------|-------| +| I | 1 | +| V | 5 | +| X | 10 | +| L | 50 | +| C | 100 | +| D | 500 | +| M | 1000 | Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules: @@ -76,4 +54,4 @@ Given an integer, convert it to a Roman numeral. **Constraints:** -* `1 <= num <= 3999` \ No newline at end of file +* `1 <= num <= 3999` From d9c850cbcbb67dc039e35246fc6b6d77a844af06 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 15:54:44 +0200 Subject: [PATCH 03/21] Improve readme formatting and explanations Updated explanations in the readme for clarity and formatting. --- .../s0008_string_to_integer_atoi/readme.md | 31 ++++++++++++++++--- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/src/main/java/g0001_0100/s0008_string_to_integer_atoi/readme.md b/src/main/java/g0001_0100/s0008_string_to_integer_atoi/readme.md index 8d0ab5062..cfb4bd447 100644 --- a/src/main/java/g0001_0100/s0008_string_to_integer_atoi/readme.md +++ b/src/main/java/g0001_0100/s0008_string_to_integer_atoi/readme.md @@ -21,7 +21,13 @@ Return the integer as the final result. **Explanation:** -The underlined characters are what is read in and the caret is the current reader position. Step 1: "42" (no characters read because there is no leading whitespace) ^ Step 2: "42" (no characters read because there is neither a '-' nor '+') ^ Step 3: "42" ("42" is read in) ^ + The underlined characters are what is read in and the caret is the current reader position. + Step 1: "42" (no characters read because there is no leading whitespace) + ^ + Step 2: "42" (no characters read because there is neither a '-' nor '+') + ^ + Step 3: "42" ("42" is read in) + ^ **Example 2:** @@ -31,7 +37,12 @@ The underlined characters are what is read in and the caret is the current reade **Explanation:** -Step 1: " \-042" (leading whitespace is read and ignored) ^ Step 2: " \-042" ('-' is read, so the result should be negative) ^ Step 3: " -042" ("042" is read in, leading zeros ignored in the result) ^ + Step 1: "___-042" (leading whitespace is read and ignored) + ^ + Step 2: " -042" ('-' is read, so the result should be negative) + ^ + Step 3: " -042" ("042" is read in, leading zeros ignored in the result) + ^ **Example 3:** @@ -41,7 +52,12 @@ Step 1: " \-042" (leading whitespace is read and ignored) ^ Step 2: " \-1337c0d3" ("1337" is read in; reading stops because the next character is a non-digit) ^ + Step 1: "1337c0d3" (no characters read because there is no leading whitespace) + ^ + Step 2: "1337c0d3" (no characters read because there is neither a '-' nor '+') + ^ + Step 3: "1337c0d3" ("1337" is read in; reading stops because the next character is a non-digit) + ^ **Example 4:** @@ -51,7 +67,12 @@ Step 1: "1337c0d3" (no characters read because there is no leading whitespace) ^ **Explanation:** -Step 1: "0-1" (no characters read because there is no leading whitespace) ^ Step 2: "0-1" (no characters read because there is neither a '-' nor '+') ^ Step 3: "0\-1" ("0" is read in; reading stops because the next character is a non-digit) ^ + Step 1: "0-1" (no characters read because there is no leading whitespace) + ^ + Step 2: "0-1" (no characters read because there is neither a '-' nor '+') + ^ + Step 3: "0-1" ("0" is read in; reading stops because the next character is a non-digit) + ^ **Example 5:** @@ -66,4 +87,4 @@ Reading stops at the first non-digit character 'w'. **Constraints:** * `0 <= s.length <= 200` -* `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`. \ No newline at end of file +* `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`. From 42231b08dbc6117874b34d480b58f0a3ab40b7a2 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 15:58:06 +0200 Subject: [PATCH 04/21] Format symbol-value table in readme Updated the readme to format the symbol-value table for better readability. --- .../java/g0001_0100/s0013_roman_to_integer/readme.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/java/g0001_0100/s0013_roman_to_integer/readme.md b/src/main/java/g0001_0100/s0013_roman_to_integer/readme.md index c6b9a9850..2afcaa520 100644 --- a/src/main/java/g0001_0100/s0013_roman_to_integer/readme.md +++ b/src/main/java/g0001_0100/s0013_roman_to_integer/readme.md @@ -4,7 +4,15 @@ Easy Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. -**Symbol** **Value** I 1 V 5 X 10 L 50 C 100 D 500 M 1000 +| Symbol | Value | +|--------|-------| +| I | 1 | +| V | 5 | +| X | 10 | +| L | 50 | +| C | 100 | +| D | 500 | +| M | 1000 | For example, `2` is written as `II` in Roman numeral, just two ones added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. @@ -44,4 +52,4 @@ Given a roman numeral, convert it to an integer. * `1 <= s.length <= 15` * `s` contains only the characters `('I', 'V', 'X', 'L', 'C', 'D', 'M')`. -* It is **guaranteed** that `s` is a valid roman numeral in the range `[1, 3999]`. \ No newline at end of file +* It is **guaranteed** that `s` is a valid roman numeral in the range `[1, 3999]`. From 3268a40990d4c40d121d6a189e1cdea670c6d2ab Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:39:05 +0200 Subject: [PATCH 05/21] Enhance readme with Two Sum problem solution Added a detailed explanation and implementation for the Two Sum problem in Java, including steps to solve it and example test cases. --- .../java/g0001_0100/s0001_two_sum/readme.md | 64 ++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0001_two_sum/readme.md b/src/main/java/g0001_0100/s0001_two_sum/readme.md index d51bd7071..c51a2d424 100644 --- a/src/main/java/g0001_0100/s0001_two_sum/readme.md +++ b/src/main/java/g0001_0100/s0001_two_sum/readme.md @@ -35,4 +35,66 @@ You can return the answer in any order. * -109 <= target <= 109 * **Only one valid answer exists.** -**Follow-up:** Can you come up with an algorithm that is less than O(n2) time complexity? \ No newline at end of file +**Follow-up:** Can you come up with an algorithm that is less than O(n2) time complexity? + +To solve the Two Sum problem in Java using a `Solution` class, we'll follow these steps: + +1. Define a `Solution` class with a method named `twoSum`. +2. Inside the `twoSum` method, create a hashmap to store elements and their indices. +3. Iterate through the array: + - For each element, calculate the complement required to reach the target sum. + - Check if the complement exists in the hashmap. + - If found, return the indices of the current element and the complement. + - If not found, add the current element and its index to the hashmap. +4. Handle edge cases: + - If no solution is found, return an empty array or null (depending on the problem requirements). + +Here's the implementation: + +```java +import java.util.HashMap; + +public class Solution { + + public int[] twoSum(int[] nums, int target) { + // Create a hashmap to store elements and their indices + HashMap map = new HashMap<>(); + + // Iterate through the array + for (int i = 0; i < nums.length; i++) { + int complement = target - nums[i]; + // Check if the complement exists in the hashmap + if (map.containsKey(complement)) { + // Return the indices of the current element and the complement + return new int[]{map.get(complement), i}; + } + // Add the current element and its index to the hashmap + map.put(nums[i], i); + } + // If no solution is found, return an empty array or null + return new int[]{}; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test cases + int[] nums1 = {2, 7, 11, 15}; + int target1 = 9; + int[] result1 = solution.twoSum(nums1, target1); + System.out.println("Example 1 Output: [" + result1[0] + ", " + result1[1] + "]"); + + int[] nums2 = {3, 2, 4}; + int target2 = 6; + int[] result2 = solution.twoSum(nums2, target2); + System.out.println("Example 2 Output: [" + result2[0] + ", " + result2[1] + "]"); + + int[] nums3 = {3, 3}; + int target3 = 6; + int[] result3 = solution.twoSum(nums3, target3); + System.out.println("Example 3 Output: [" + result3[0] + ", " + result3[1] + "]"); + } +} +``` + +This implementation provides a solution to the Two Sum problem with a time complexity of O(n), where n is the number of elements in the input array. From 091cbb3944bb550549d9827692fcaa24d15477a4 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:40:43 +0200 Subject: [PATCH 06/21] Enhance readme with problem explanation and code Added detailed explanation and implementation for the Add Two Numbers problem using linked lists in Java. --- .../s0002_add_two_numbers/readme.md | 100 +++++++++++++++++- 1 file changed, 99 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0002_add_two_numbers/readme.md b/src/main/java/g0001_0100/s0002_add_two_numbers/readme.md index 6e67c194c..82855a16b 100644 --- a/src/main/java/g0001_0100/s0002_add_two_numbers/readme.md +++ b/src/main/java/g0001_0100/s0002_add_two_numbers/readme.md @@ -32,4 +32,102 @@ You may assume the two numbers do not contain any leading zero, except the numbe * The number of nodes in each linked list is in the range `[1, 100]`. * `0 <= Node.val <= 9` -* It is guaranteed that the list represents a number that does not have leading zeros. \ No newline at end of file +* It is guaranteed that the list represents a number that does not have leading zeros. + +To solve the Add Two Numbers problem in Java using a `Solution` class, we'll follow these steps: + +1. Define a `ListNode` class to represent nodes in a linked list. +2. Define a `Solution` class with a method named `addTwoNumbers`. +3. Inside the `addTwoNumbers` method, traverse both input linked lists simultaneously: + - Keep track of a carry variable to handle cases where the sum of two digits exceeds 9. + - Calculate the sum of the current nodes' values along with the carry. + - Update the carry for the next iteration. + - Create a new node with the sum % 10 and attach it to the result linked list. + - Move to the next nodes in both input lists. +4. After finishing the traversal, check if there is any remaining carry. If so, add a new node with the carry to the result. +5. Return the head of the result linked list. + +Here's the implementation: + +```java +class ListNode { + int val; + ListNode next; + + ListNode() {} + + ListNode(int val) { + this.val = val; + } + + ListNode(int val, ListNode next) { + this.val = val; + this.next = next; + } +} + +public class Solution { + + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + ListNode dummyHead = new ListNode(); + ListNode curr = dummyHead; + int carry = 0; + + while (l1 != null || l2 != null) { + int sum = carry; + if (l1 != null) { + sum += l1.val; + l1 = l1.next; + } + if (l2 != null) { + sum += l2.val; + l2 = l2.next; + } + curr.next = new ListNode(sum % 10); + curr = curr.next; + carry = sum / 10; + } + + if (carry > 0) { + curr.next = new ListNode(carry); + } + + return dummyHead.next; + } + + // Helper method to print a linked list + public void printList(ListNode head) { + ListNode curr = head; + while (curr != null) { + System.out.print(curr.val + " "); + curr = curr.next; + } + System.out.println(); + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test cases + ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(3))); + ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4))); + ListNode result1 = solution.addTwoNumbers(l1, l2); + System.out.print("Example 1 Output: "); + solution.printList(result1); + + ListNode l3 = new ListNode(0); + ListNode l4 = new ListNode(0); + ListNode result2 = solution.addTwoNumbers(l3, l4); + System.out.print("Example 2 Output: "); + solution.printList(result2); + + ListNode l5 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))))))); + ListNode l6 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))); + ListNode result3 = solution.addTwoNumbers(l5, l6); + System.out.print("Example 3 Output: "); + solution.printList(result3); + } +} +``` + +This implementation provides a solution to the Add Two Numbers problem using linked lists in Java. From 94a3525fb66d6e9b216cfef5d2f652b84ee4fa79 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:41:51 +0200 Subject: [PATCH 07/21] Update README with problem explanation and solution Added a detailed explanation and implementation of the Longest Substring Without Repeating Characters problem in Java. --- .../readme.md | 65 ++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0003_longest_substring_without_repeating_characters/readme.md b/src/main/java/g0001_0100/s0003_longest_substring_without_repeating_characters/readme.md index 1e1738446..447d996d9 100644 --- a/src/main/java/g0001_0100/s0003_longest_substring_without_repeating_characters/readme.md +++ b/src/main/java/g0001_0100/s0003_longest_substring_without_repeating_characters/readme.md @@ -31,4 +31,67 @@ Given a string `s`, find the length of the **longest** **substring** without dup **Constraints:** * 0 <= s.length <= 5 * 104 -* `s` consists of English letters, digits, symbols and spaces. \ No newline at end of file +* `s` consists of English letters, digits, symbols and spaces. + +To solve the Longest Substring Without Repeating Characters problem in Java using a `Solution` class, we'll follow these steps: + +1. Define a `Solution` class with a method named `lengthOfLongestSubstring`. +2. Initialize variables to keep track of the starting index of the substring (`start`), the maximum length (`maxLen`), and a hashmap to store characters and their indices. +3. Iterate through the string `s`, and for each character: + - Check if the character exists in the hashmap and its index is greater than or equal to the `start` index. + - If found, update the `start` index to the index after the last occurrence of the character. + - Update the maximum length if necessary. + - Update the index of the current character in the hashmap. +4. Return the maximum length found. +5. Handle the edge case where the input string is empty. + +Here's the implementation: + +```java +import java.util.HashMap; + +public class Solution { + + public int lengthOfLongestSubstring(String s) { + // Initialize variables + int start = 0; + int maxLen = 0; + HashMap map = new HashMap<>(); + + // Iterate through the string + for (int end = 0; end < s.length(); end++) { + char ch = s.charAt(end); + // If the character exists in the hashmap and its index is greater than or equal to the start index + if (map.containsKey(ch) && map.get(ch) >= start) { + // Update the start index to the index after the last occurrence of the character + start = map.get(ch) + 1; + } + // Update the maximum length if necessary + maxLen = Math.max(maxLen, end - start + 1); + // Update the index of the current character in the hashmap + map.put(ch, end); + } + + return maxLen; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test cases + String s1 = "abcabcbb"; + System.out.println("Example 1 Output: " + solution.lengthOfLongestSubstring(s1)); + + String s2 = "bbbbb"; + System.out.println("Example 2 Output: " + solution.lengthOfLongestSubstring(s2)); + + String s3 = "pwwkew"; + System.out.println("Example 3 Output: " + solution.lengthOfLongestSubstring(s3)); + + String s4 = ""; + System.out.println("Example 4 Output: " + solution.lengthOfLongestSubstring(s4)); + } +} +``` + +This implementation provides a solution to the Longest Substring Without Repeating Characters problem in Java. From 0295b4d828c0088c752fa869bb27b17f8b45d7cc Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:42:51 +0200 Subject: [PATCH 08/21] Enhance README with solution steps and code example Added detailed steps and implementation for solving the Median of Two Sorted Arrays problem in Java. --- .../readme.md | 70 ++++++++++++++++++- 1 file changed, 69 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0004_median_of_two_sorted_arrays/readme.md b/src/main/java/g0001_0100/s0004_median_of_two_sorted_arrays/readme.md index 9482d8459..903c7dde0 100644 --- a/src/main/java/g0001_0100/s0004_median_of_two_sorted_arrays/readme.md +++ b/src/main/java/g0001_0100/s0004_median_of_two_sorted_arrays/readme.md @@ -29,4 +29,72 @@ The overall run time complexity should be `O(log (m+n))`. * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` -* -106 <= nums1[i], nums2[i] <= 106 \ No newline at end of file +* -106 <= nums1[i], nums2[i] <= 106 + +To solve the Median of Two Sorted Arrays problem in Java using a `Solution` class, we'll follow these steps: + +1. Define a `Solution` class with a method named `findMedianSortedArrays`. +2. Calculate the total length of the combined array (m + n). +3. Determine the middle index or indices of the combined array based on its length (for both even and odd lengths). +4. Implement a binary search algorithm to find the correct position for partitioning the two arrays such that elements to the left are less than or equal to elements on the right. +5. Calculate the median based on the partitioned arrays. +6. Handle edge cases where one or both arrays are empty or where the combined length is odd or even. +7. Return the calculated median. + +Here's the implementation: + +```java +public class Solution { + + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + int m = nums1.length; + int n = nums2.length; + int totalLength = m + n; + int left = (totalLength + 1) / 2; + int right = (totalLength + 2) / 2; + return (findKth(nums1, 0, nums2, 0, left) + findKth(nums1, 0, nums2, 0, right)) / 2.0; + } + + private int findKth(int[] nums1, int i, int[] nums2, int j, int k) { + if (i >= nums1.length) return nums2[j + k - 1]; + if (j >= nums2.length) return nums1[i + k - 1]; + if (k == 1) return Math.min(nums1[i], nums2[j]); + + int midVal1 = (i + k / 2 - 1 < nums1.length) ? nums1[i + k / 2 - 1] : Integer.MAX_VALUE; + int midVal2 = (j + k / 2 - 1 < nums2.length) ? nums2[j + k / 2 - 1] : Integer.MAX_VALUE; + + if (midVal1 < midVal2) { + return findKth(nums1, i + k / 2, nums2, j, k - k / 2); + } else { + return findKth(nums1, i, nums2, j + k / 2, k - k / 2); + } + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test cases + int[] nums1_1 = {1, 3}; + int[] nums2_1 = {2}; + System.out.println("Example 1 Output: " + solution.findMedianSortedArrays(nums1_1, nums2_1)); + + int[] nums1_2 = {1, 2}; + int[] nums2_2 = {3, 4}; + System.out.println("Example 2 Output: " + solution.findMedianSortedArrays(nums1_2, nums2_2)); + + int[] nums1_3 = {0, 0}; + int[] nums2_3 = {0, 0}; + System.out.println("Example 3 Output: " + solution.findMedianSortedArrays(nums1_3, nums2_3)); + + int[] nums1_4 = {}; + int[] nums2_4 = {1}; + System.out.println("Example 4 Output: " + solution.findMedianSortedArrays(nums1_4, nums2_4)); + + int[] nums1_5 = {2}; + int[] nums2_5 = {}; + System.out.println("Example 5 Output: " + solution.findMedianSortedArrays(nums1_5, nums2_5)); + } +} +``` + +This implementation provides a solution to the Median of Two Sorted Arrays problem in Java with a runtime complexity of O(log(min(m, n))). From 6927485afdfc5a84c94c2ce544f0bc26b08b776f Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:43:47 +0200 Subject: [PATCH 09/21] Enhance README with problem explanation and solution Added a detailed explanation of the Longest Palindromic Substring problem solution in Java, including constraints and implementation steps. --- .../readme.md | 65 ++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0005_longest_palindromic_substring/readme.md b/src/main/java/g0001_0100/s0005_longest_palindromic_substring/readme.md index 82ff4d567..5e3c1c6f4 100644 --- a/src/main/java/g0001_0100/s0005_longest_palindromic_substring/readme.md +++ b/src/main/java/g0001_0100/s0005_longest_palindromic_substring/readme.md @@ -21,4 +21,67 @@ Given a string `s`, return _the longest_ _palindromic_ **substring** in `s`. **Constraints:** * `1 <= s.length <= 1000` -* `s` consist of only digits and English letters. \ No newline at end of file +* `s` consist of only digits and English letters. + +To solve the Longest Palindromic Substring problem in Java using a `Solution` class, we'll follow these steps: + +1. Define a `Solution` class with a method named `longestPalindrome`. +2. Initialize variables to keep track of the start and end indices of the longest palindromic substring found so far (`start` and `end`). +3. Iterate through the string `s`: + - For each character in the string, expand around it to check if it forms a palindrome. + - Handle both odd-length and even-length palindromes separately. + - Update `start` and `end` indices if a longer palindrome is found. +4. Return the substring from `start` to `end`. +5. Handle edge cases where the input string is empty or has a length of 1. + +Here's the implementation: + +```java +public class Solution { + + public String longestPalindrome(String s) { + if (s == null || s.length() < 1) return ""; + int start = 0; + int end = 0; + + for (int i = 0; i < s.length(); i++) { + int len1 = expandAroundCenter(s, i, i); + int len2 = expandAroundCenter(s, i, i + 1); + int len = Math.max(len1, len2); + if (len > end - start) { + start = i - (len - 1) / 2; + end = i + len / 2; + } + } + + return s.substring(start, end + 1); + } + + private int expandAroundCenter(String s, int left, int right) { + while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { + left--; + right++; + } + return right - left - 1; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test cases + String s1 = "babad"; + System.out.println("Example 1 Output: " + solution.longestPalindrome(s1)); + + String s2 = "cbbd"; + System.out.println("Example 2 Output: " + solution.longestPalindrome(s2)); + + String s3 = "a"; + System.out.println("Example 3 Output: " + solution.longestPalindrome(s3)); + + String s4 = "ac"; + System.out.println("Example 4 Output: " + solution.longestPalindrome(s4)); + } +} +``` + +This implementation provides a solution to the Longest Palindromic Substring problem in Java. From 64b603d9d14e8724cb6a766c4c0c11e68fb29ed9 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:44:34 +0200 Subject: [PATCH 10/21] Update readme with Zigzag Conversion solution Added detailed explanation and implementation for Zigzag Conversion problem. --- .../s0006_zigzag_conversion/readme.md | 70 ++++++++++++++++++- 1 file changed, 69 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0006_zigzag_conversion/readme.md b/src/main/java/g0001_0100/s0006_zigzag_conversion/readme.md index 4f55d57d3..c0842869e 100644 --- a/src/main/java/g0001_0100/s0006_zigzag_conversion/readme.md +++ b/src/main/java/g0001_0100/s0006_zigzag_conversion/readme.md @@ -36,4 +36,72 @@ string convert(string s, int numRows); * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. -* `1 <= numRows <= 1000` \ No newline at end of file +* `1 <= numRows <= 1000` + +To solve the Zigzag Conversion problem in Java using a `Solution` class, we'll follow these steps: + +1. Define a `Solution` class with a method named `convert`. +2. Create an array of strings to represent each row of the zigzag pattern. +3. Initialize variables to keep track of the current row (`row`) and the direction of traversal (`down`). +4. Iterate through each character in the input string `s`. + - Append the current character to the string representing the current row. + - If we reach the first or last row, change the direction of traversal accordingly. + - Update the current row based on the direction of traversal. +5. Concatenate the strings representing each row to form the final zigzag conversion. +6. Return the concatenated string. +7. Handle edge cases where the number of rows is 1 or the input string is empty. + +Here's the implementation: + +```java +public class Solution { + + public String convert(String s, int numRows) { + if (numRows == 1 || s.length() <= numRows) { + return s; + } + + StringBuilder[] rows = new StringBuilder[numRows]; + for (int i = 0; i < numRows; i++) { + rows[i] = new StringBuilder(); + } + + int row = 0; + boolean down = false; + + for (char c : s.toCharArray()) { + rows[row].append(c); + if (row == 0 || row == numRows - 1) { + down = !down; + } + row += down ? 1 : -1; + } + + StringBuilder result = new StringBuilder(); + for (StringBuilder sb : rows) { + result.append(sb); + } + + return result.toString(); + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test cases + String s1 = "PAYPALISHIRING"; + int numRows1 = 3; + System.out.println("Example 1 Output: " + solution.convert(s1, numRows1)); + + String s2 = "PAYPALISHIRING"; + int numRows2 = 4; + System.out.println("Example 2 Output: " + solution.convert(s2, numRows2)); + + String s3 = "A"; + int numRows3 = 1; + System.out.println("Example 3 Output: " + solution.convert(s3, numRows3)); + } +} +``` + +This implementation provides a solution to the Zigzag Conversion problem in Java. From 37725d8fce05cf580354d36e736e87282f8a38a1 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:45:17 +0200 Subject: [PATCH 11/21] Enhance readme with Reverse Integer solution details Added detailed explanation and implementation for the Reverse Integer problem in Java. --- .../s0007_reverse_integer/readme.md | 63 ++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0007_reverse_integer/readme.md b/src/main/java/g0001_0100/s0007_reverse_integer/readme.md index a9974deb9..d2a1aae04 100644 --- a/src/main/java/g0001_0100/s0007_reverse_integer/readme.md +++ b/src/main/java/g0001_0100/s0007_reverse_integer/readme.md @@ -26,4 +26,65 @@ Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If rev **Constraints:** -* -231 <= x <= 231 - 1 \ No newline at end of file +* -231 <= x <= 231 - 1 + +To solve the Reverse Integer problem in Java using a `Solution` class, we'll follow these steps: + +1. Define a `Solution` class with a method named `reverse`. +2. Initialize variables to keep track of the reversed integer (`rev`), the sign of the input integer (`sign`), and the absolute value of the input integer (`x`). +3. Iterate through each digit of the input integer `x`: + - Extract the least significant digit using the modulo operator. + - Update the reversed integer `rev` by multiplying it by 10 and adding the extracted digit. + - Update `x` by removing the least significant digit using integer division. +4. Check if the reversed integer `rev` overflows the signed 32-bit integer range. If so, return 0. +5. Return the reversed integer `rev` with the appropriate sign. + +Here's the implementation: + +```java +public class Solution { + + public int reverse(int x) { + int rev = 0; + int sign = (x < 0) ? -1 : 1; + int limit = Integer.MAX_VALUE / 10; + int absX = Math.abs(x); + + while (absX > 0) { + int digit = absX % 10; + absX /= 10; + + if (rev > limit || (rev == limit && digit > 7)) { + return 0; + } + + if (rev < -limit || (rev == -limit && digit < -8)) { + return 0; + } + + rev = rev * 10 + digit; + } + + return rev * sign; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test cases + int x1 = 123; + System.out.println("Example 1 Output: " + solution.reverse(x1)); + + int x2 = -123; + System.out.println("Example 2 Output: " + solution.reverse(x2)); + + int x3 = 120; + System.out.println("Example 3 Output: " + solution.reverse(x3)); + + int x4 = 0; + System.out.println("Example 4 Output: " + solution.reverse(x4)); + } +} +``` + +This implementation provides a solution to the Reverse Integer problem in Java. From 60c174aa02a16c6e9db22fcca5dd3da9b8e989a9 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:46:30 +0200 Subject: [PATCH 12/21] Enhance readme with atoi problem solution Added a detailed explanation and implementation for the String to Integer (atoi) problem in Java. --- .../s0008_string_to_integer_atoi/readme.md | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/src/main/java/g0001_0100/s0008_string_to_integer_atoi/readme.md b/src/main/java/g0001_0100/s0008_string_to_integer_atoi/readme.md index cfb4bd447..743eb17cc 100644 --- a/src/main/java/g0001_0100/s0008_string_to_integer_atoi/readme.md +++ b/src/main/java/g0001_0100/s0008_string_to_integer_atoi/readme.md @@ -84,6 +84,77 @@ Return the integer as the final result. Reading stops at the first non-digit character 'w'. +To solve the String to Integer (atoi) problem in Java using a `Solution` class, we'll follow these steps: + +1. Define a `Solution` class with a method named `myAtoi`. +2. Trim leading whitespace from the input string `s`. +3. Check if the string is empty after trimming. If so, return 0. +4. Initialize variables to keep track of the sign of the integer (`sign`), the starting index of the numeric characters (`start`), and the result (`result`). +5. Check if the first character of the trimmed string is `'-'` or `'+'`. Update `sign` accordingly, and move the starting index accordingly. +6. Iterate through the characters of the trimmed string starting from the `start` index: + - Check if the current character is a digit. If not, break the loop. + - Convert the character to its numeric value and update the `result`. + - Check if the result exceeds the 32-bit integer range. If so, clamp it to the range and return. +7. Multiply the `result` by the sign and return the final value. +8. Handle edge cases where the input string is empty, consists of only whitespace, or contains non-numeric characters at the beginning. + +Here's the implementation: + +```java +public class Solution { + + public int myAtoi(String s) { + s = s.trim(); + if (s.isEmpty()) + return 0; + + int sign = 1; + int start = 0; + long result = 0; + + if (s.charAt(0) == '-' || s.charAt(0) == '+') { + sign = (s.charAt(0) == '-') ? -1 : 1; + start++; + } + + for (int i = start; i < s.length(); i++) { + char c = s.charAt(i); + if (!Character.isDigit(c)) + break; + result = result * 10 + (c - '0'); + if (result * sign > Integer.MAX_VALUE) + return Integer.MAX_VALUE; + if (result * sign < Integer.MIN_VALUE) + return Integer.MIN_VALUE; + } + + return (int) (result * sign); + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test cases + String s1 = "42"; + System.out.println("Example 1 Output: " + solution.myAtoi(s1)); + + String s2 = " -42"; + System.out.println("Example 2 Output: " + solution.myAtoi(s2)); + + String s3 = "4193 with words"; + System.out.println("Example 3 Output: " + solution.myAtoi(s3)); + + String s4 = "words and 987"; + System.out.println("Example 4 Output: " + solution.myAtoi(s4)); + + String s5 = "-91283472332"; + System.out.println("Example 5 Output: " + solution.myAtoi(s5)); + } +} +``` + +This implementation provides a solution to the String to Integer (atoi) problem in Java. + **Constraints:** * `0 <= s.length <= 200` From 48fe3c27fadf7fed24765536f8976cb30d1fd35f Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:47:25 +0200 Subject: [PATCH 13/21] Enhance readme with Palindrome Number solution details Added a detailed explanation and implementation for the Palindrome Number problem in Java, including constraints and follow-up considerations. --- .../s0009_palindrome_number/readme.md | 61 ++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0009_palindrome_number/readme.md b/src/main/java/g0001_0100/s0009_palindrome_number/readme.md index efe0f5c0d..232c883cf 100644 --- a/src/main/java/g0001_0100/s0009_palindrome_number/readme.md +++ b/src/main/java/g0001_0100/s0009_palindrome_number/readme.md @@ -32,4 +32,63 @@ Given an integer `x`, return `true` _if_ `x` _is a_ _**palindrome**__, and_ `fal * -231 <= x <= 231 - 1 -**Follow up:** Could you solve it without converting the integer to a string? \ No newline at end of file +**Follow up:** Could you solve it without converting the integer to a string? + +To solve the Palindrome Number problem in Java using a `Solution` class, we'll follow these steps: + +1. Define a `Solution` class with a method named `isPalindrome`. +2. Handle special cases where `x` is negative or divisible by 10 but not equal to zero, as they cannot be palindromes. +3. Initialize variables to keep track of the reversed number (`reversed`) and the original number (`original`). +4. Iterate through the digits of the original number `x`: + - Extract the least significant digit using the modulo operator and append it to the reversed number. + - Update `original` by removing the least significant digit using integer division. +5. Check if the reversed number is equal to the original number. If so, return `true`; otherwise, return `false`. + +Here's the implementation: + +```java +public class Solution { + + public boolean isPalindrome(int x) { + // Special cases: + // As discussed, negative numbers are not palindromes. + // Also, if the last digit of the number is 0, it can't be a palindrome unless the number is 0 itself. + if (x < 0 || (x % 10 == 0 && x != 0)) { + return false; + } + + int reversed = 0; + int original = x; + + while (original > reversed) { + int digit = original % 10; + reversed = reversed * 10 + digit; + original /= 10; + } + + // When the length is an odd number, we can get rid of the middle digit by reversed / 10 + // For example when the input is 12321, at the end of the while loop we get x = 12, reversed = 123, + // since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it. + return original == reversed || original == reversed / 10; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test cases + int x1 = 121; + System.out.println("Example 1 Output: " + solution.isPalindrome(x1)); + + int x2 = -121; + System.out.println("Example 2 Output: " + solution.isPalindrome(x2)); + + int x3 = 10; + System.out.println("Example 3 Output: " + solution.isPalindrome(x3)); + + int x4 = -101; + System.out.println("Example 4 Output: " + solution.isPalindrome(x4)); + } +} +``` + +This implementation provides a solution to the Palindrome Number problem in Java. From fbd0f5de546e6202db3e00803b0982a7dcdfa88c Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:48:16 +0200 Subject: [PATCH 14/21] Enhance README with solution steps and implementation Added detailed steps for solving the Regular Expression Matching problem in Java, including the implementation of the 'isMatch' method. --- .../readme.md | 65 ++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0010_regular_expression_matching/readme.md b/src/main/java/g0001_0100/s0010_regular_expression_matching/readme.md index ed34a26ee..2d99ab985 100644 --- a/src/main/java/g0001_0100/s0010_regular_expression_matching/readme.md +++ b/src/main/java/g0001_0100/s0010_regular_expression_matching/readme.md @@ -39,4 +39,67 @@ The matching should cover the **entire** input string (not partial). * `1 <= p.length <= 20` * `s` contains only lowercase English letters. * `p` contains only lowercase English letters, `'.'`, and `'*'`. -* It is guaranteed for each appearance of the character `'*'`, there will be a previous valid character to match. \ No newline at end of file +* It is guaranteed for each appearance of the character `'*'`, there will be a previous valid character to match. + +To solve the Regular Expression Matching problem in Java using a `Solution` class, we'll follow these steps: + +1. Define a `Solution` class with a method named `isMatch`. +2. Implement a recursive approach to check for pattern matching. +3. Base cases: + - If the pattern string is empty, return `s.isEmpty()`. + - If the pattern string's length is 1 or the next character after `*` is `.`: + - Check if the length of `s` is 1 and the characters match or the pattern is `.`. + - If so, return `true`; otherwise, return `false`. +4. If the second character of the pattern is not `*`, recursively call `isMatch` with the substring starting from the second character. +5. If the second character of the pattern is `*`, recursively check all possibilities: + - Zero occurrences of the preceding character (skipping `*` and the character before it). + - One or more occurrences of the preceding character (matching the first character and recursively calling `isMatch` for the remaining part of the string). +6. Return the result of the recursive checks. +7. Handle edge cases where the input strings are empty or the pattern contains invalid characters. + +Here's the implementation: + +```java +public class Solution { + + public boolean isMatch(String s, String p) { + if (p.isEmpty()) + return s.isEmpty(); + + boolean firstMatch = !s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.'); + + if (p.length() >= 2 && p.charAt(1) == '*') { + return isMatch(s, p.substring(2)) || (firstMatch && isMatch(s.substring(1), p)); + } else { + return firstMatch && isMatch(s.substring(1), p.substring(1)); + } + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test cases + String s1 = "aa"; + String p1 = "a"; + System.out.println("Example 1 Output: " + solution.isMatch(s1, p1)); + + String s2 = "aa"; + String p2 = "a*"; + System.out.println("Example 2 Output: " + solution.isMatch(s2, p2)); + + String s3 = "ab"; + String p3 = ".*"; + System.out.println("Example 3 Output: " + solution.isMatch(s3, p3)); + + String s4 = "aab"; + String p4 = "c*a*b"; + System.out.println("Example 4 Output: " + solution.isMatch(s4, p4)); + + String s5 = "mississippi"; + String p5 = "mis*is*p*."; + System.out.println("Example 5 Output: " + solution.isMatch(s5, p5)); + } +} +``` + +This implementation provides a solution to the Regular Expression Matching problem in Java. From 9f5fddce13953f2473b30eacf89d58e1a78b8528 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:49:41 +0200 Subject: [PATCH 15/21] Update readme with solution details for Container With Most Water Added a detailed explanation and implementation for the Container With Most Water problem. --- .../s0011_container_with_most_water/readme.md | 58 ++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0011_container_with_most_water/readme.md b/src/main/java/g0001_0100/s0011_container_with_most_water/readme.md index baa84ca0d..f22e18f7b 100644 --- a/src/main/java/g0001_0100/s0011_container_with_most_water/readme.md +++ b/src/main/java/g0001_0100/s0011_container_with_most_water/readme.md @@ -30,4 +30,60 @@ Return _the maximum amount of water a container can store_. * `n == height.length` * 2 <= n <= 105 -* 0 <= height[i] <= 104 \ No newline at end of file +* 0 <= height[i] <= 104 Date: Mon, 27 Oct 2025 17:51:03 +0200 Subject: [PATCH 16/21] Enhance README with 3Sum problem solution Added detailed explanation and implementation for the 3Sum problem in Java, including constraints and step-by-step approach. --- src/main/java/g0001_0100/s0015_3sum/readme.md | 81 ++++++++++++++++++- 1 file changed, 80 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0015_3sum/readme.md b/src/main/java/g0001_0100/s0015_3sum/readme.md index 12aa783ee..4fdae92ce 100644 --- a/src/main/java/g0001_0100/s0015_3sum/readme.md +++ b/src/main/java/g0001_0100/s0015_3sum/readme.md @@ -33,4 +33,83 @@ Notice that the solution set must not contain duplicate triplets. **Constraints:** * `3 <= nums.length <= 3000` -* -105 <= nums[i] <= 105 \ No newline at end of file +* -105 <= nums[i] <= 105 + +To solve the 3Sum problem in Java using a `Solution` class, we'll follow these steps: + +1. Define a `Solution` class with a method named `threeSum` that takes an array of integers `nums` as input and returns a list of lists representing the triplets that sum up to zero. +2. Sort the input array `nums` to ensure that duplicate triplets are avoided. +3. Initialize an empty list `result` to store the triplets. +4. Iterate over the elements of the sorted array `nums` up to the second to last element. +5. Within the outer loop, initialize two pointers, `left` and `right`, where `left` starts at the next element after the current element and `right` starts at the last element of the array. +6. While `left` is less than `right`, check if the sum of the current element (`nums[i]`), `nums[left]`, and `nums[right]` equals zero. +7. If the sum is zero, add `[nums[i], nums[left], nums[right]]` to the `result` list. +8. Move the `left` pointer to the right (increment `left`) and the `right` pointer to the left (decrement `right`). +9. If the sum is less than zero, increment `left`. +10. If the sum is greater than zero, decrement `right`. +11. After the inner loop finishes, increment the outer loop index while skipping duplicates. +12. Return the `result` list containing all the valid triplets. + +Here's the implementation: + +```java +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Solution { + public List> threeSum(int[] nums) { + Arrays.sort(nums); + List> result = new ArrayList<>(); + + for (int i = 0; i < nums.length - 2; i++) { + if (i > 0 && nums[i] == nums[i - 1]) { + continue; // Skip duplicates + } + + int left = i + 1; + int right = nums.length - 1; + + while (left < right) { + int sum = nums[i] + nums[left] + nums[right]; + if (sum == 0) { + result.add(Arrays.asList(nums[i], nums[left], nums[right])); + + // Skip duplicates + while (left < right && nums[left] == nums[left + 1]) { + left++; + } + while (left < right && nums[right] == nums[right - 1]) { + right--; + } + + left++; + right--; + } else if (sum < 0) { + left++; + } else { + right--; + } + } + } + + return result; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test cases + int[] nums1 = {-1, 0, 1, 2, -1, -4}; + System.out.println("Example 1 Output: " + solution.threeSum(nums1)); + + int[] nums2 = {}; + System.out.println("Example 2 Output: " + solution.threeSum(nums2)); + + int[] nums3 = {0}; + System.out.println("Example 3 Output: " + solution.threeSum(nums3)); + } +} +``` + +This implementation provides a solution to the 3Sum problem in Java. From 788a822e1acf361124398f662aabc5c8394bcadf Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:52:01 +0200 Subject: [PATCH 17/21] Update readme.md --- .../readme.md | 75 ++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0017_letter_combinations_of_a_phone_number/readme.md b/src/main/java/g0001_0100/s0017_letter_combinations_of_a_phone_number/readme.md index 1c6fd79d3..7525b8dff 100644 --- a/src/main/java/g0001_0100/s0017_letter_combinations_of_a_phone_number/readme.md +++ b/src/main/java/g0001_0100/s0017_letter_combinations_of_a_phone_number/readme.md @@ -23,4 +23,77 @@ A mapping of digits to letters (just like on the telephone buttons) is given bel **Constraints:** * `1 <= digits.length <= 4` -* `digits[i]` is a digit in the range `['2', '9']`. \ No newline at end of file +* `digits[i]` is a digit in the range `['2', '9']`. + +To solve the Letter Combinations of a Phone Number problem in Java using a `Solution` class, we'll follow these steps: + +1. Define a `Solution` class with a method named `letterCombinations` that takes a string `digits` as input and returns a list of all possible letter combinations. +2. Create a mapping of digits to letters using a hashmap or an array. +3. Initialize an empty list `result` to store the combinations. +4. If the input string `digits` is empty, return an empty list `result`. +5. Call a recursive function `generateCombinations` to generate combinations for each digit. +6. Within the recursive function: + - Base case: If the current combination length equals the length of the input `digits`, add the combination to the `result` list. + - Recursive step: For the current digit, iterate over its corresponding letters and append each letter to the current combination, then recursively call the function with the next digit. +7. Return the `result` list containing all possible combinations. + +Here's the implementation: + +```java +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Solution { + private static final Map digitToLetters = new HashMap<>(); + static { + digitToLetters.put('2', "abc"); + digitToLetters.put('3', "def"); + digitToLetters.put('4', "ghi"); + digitToLetters.put('5', "jkl"); + digitToLetters.put('6', "mno"); + digitToLetters.put('7', "pqrs"); + digitToLetters.put('8', "tuv"); + digitToLetters.put('9', "wxyz"); + } + + public List letterCombinations(String digits) { + List result = new ArrayList<>(); + if (digits.length() == 0) { + return result; + } + generateCombinations(result, digits, "", 0); + return result; + } + + private void generateCombinations(List result, String digits, String combination, int index) { + if (index == digits.length()) { + result.add(combination); + return; + } + + char digit = digits.charAt(index); + String letters = digitToLetters.get(digit); + for (char letter : letters.toCharArray()) { + generateCombinations(result, digits, combination + letter, index + 1); + } + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test cases + String digits1 = "23"; + System.out.println("Example 1 Output: " + solution.letterCombinations(digits1)); + + String digits2 = ""; + System.out.println("Example 2 Output: " + solution.letterCombinations(digits2)); + + String digits3 = "2"; + System.out.println("Example 3 Output: " + solution.letterCombinations(digits3)); + } +} +``` + +This implementation provides a solution to the Letter Combinations of a Phone Number problem in Java. From 03b002d495caa7fc500c741cc48c3cac565dfac6 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:52:54 +0200 Subject: [PATCH 18/21] Update README with solution for nth node removal Added detailed explanation and implementation for removing the nth node from the end of a linked list. --- .../readme.md | 93 ++++++++++++++++++- 1 file changed, 92 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0019_remove_nth_node_from_end_of_list/readme.md b/src/main/java/g0001_0100/s0019_remove_nth_node_from_end_of_list/readme.md index 8e3684653..c9562bcbb 100644 --- a/src/main/java/g0001_0100/s0019_remove_nth_node_from_end_of_list/readme.md +++ b/src/main/java/g0001_0100/s0019_remove_nth_node_from_end_of_list/readme.md @@ -31,4 +31,95 @@ Given the `head` of a linked list, remove the nth node f * `0 <= Node.val <= 100` * `1 <= n <= sz` -**Follow up:** Could you do this in one pass? \ No newline at end of file +**Follow up:** Could you do this in one pass? + +To solve the Remove Nth Node From End of List problem in Java with a `Solution` class, we'll follow these steps: + +1. Define a `ListNode` class representing the nodes of the linked list. +2. Define a `Solution` class with a method named `removeNthFromEnd` that takes the head of the linked list and an integer `n` as input and returns the head of the modified list. +3. Create two pointers, `fast` and `slow`, and initialize them to point to the head of the list. +4. Move the `fast` pointer `n` steps forward in the list. +5. If the `fast` pointer reaches the end of the list (`fast == null`), it means that `n` is equal to the length of the list. In this case, remove the head node by returning `head.next`. +6. Move both `fast` and `slow` pointers simultaneously until the `fast` pointer reaches the end of the list. +7. At this point, the `slow` pointer will be pointing to the node just before the node to be removed. +8. Remove the `nth` node by updating the `next` reference of the node pointed to by the `slow` pointer to skip the `nth` node. +9. Return the head of the modified list. + +Here's the implementation: + +```java +public class ListNode { + int val; + ListNode next; + ListNode(int val) { this.val = val; } +} + +public class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode dummy = new ListNode(0); + dummy.next = head; + ListNode fast = dummy; + ListNode slow = dummy; + + // Move the fast pointer n steps forward + for (int i = 0; i <= n; i++) { + fast = fast.next; + } + + // Move both pointers until the fast pointer reaches the end + while (fast != null) { + fast = fast.next; + slow = slow.next; + } + + // Remove the nth node + slow.next = slow.next.next; + + return dummy.next; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Example 1 + ListNode head1 = new ListNode(1); + head1.next = new ListNode(2); + head1.next.next = new ListNode(3); + head1.next.next.next = new ListNode(4); + head1.next.next.next.next = new ListNode(5); + int n1 = 2; + ListNode result1 = solution.removeNthFromEnd(head1, n1); + printList(result1); // Output: [1,2,3,5] + + // Example 2 + ListNode head2 = new ListNode(1); + int n2 = 1; + ListNode result2 = solution.removeNthFromEnd(head2, n2); + printList(result2); // Output: [] + + // Example 3 + ListNode head3 = new ListNode(1); + head3.next = new ListNode(2); + int n3 = 1; + ListNode result3 = solution.removeNthFromEnd(head3, n3); + printList(result3); // Output: [1] + } + + private static void printList(ListNode head) { + if (head == null) { + System.out.println("[]"); + return; + } + StringBuilder sb = new StringBuilder("["); + while (head != null) { + sb.append(head.val).append(","); + head = head.next; + } + sb.setLength(sb.length() - 1); + sb.append("]"); + System.out.println(sb.toString()); + } +} +``` + +This implementation provides a solution to the Remove Nth Node From End of List problem in Java. From 5b3a17c5bdd9a270278a582f4fcbf8bd89e3de21 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:53:50 +0200 Subject: [PATCH 19/21] Document Valid Parentheses solution in readme Added implementation details for Valid Parentheses problem using a stack in Java. --- .../s0020_valid_parentheses/readme.md | 54 ++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0020_valid_parentheses/readme.md b/src/main/java/g0001_0100/s0020_valid_parentheses/readme.md index d07dccb22..e0ace3610 100644 --- a/src/main/java/g0001_0100/s0020_valid_parentheses/readme.md +++ b/src/main/java/g0001_0100/s0020_valid_parentheses/readme.md @@ -43,4 +43,56 @@ An input string is valid if: **Constraints:** * 1 <= s.length <= 104 -* `s` consists of parentheses only `'()[]{}'`. \ No newline at end of file +* `s` consists of parentheses only `'()[]{}'`. + +To solve the Valid Parentheses problem in Java with a `Solution` class, we'll use a stack data structure. Here are the steps: + +1. Define a `Solution` class with a method named `isValid` that takes a string `s` as input and returns a boolean indicating whether the string contains valid parentheses. +2. Create a stack to store opening parentheses. +3. Iterate through each character in the input string `s`. +4. If the current character is an opening parenthesis (`'('`, `'{'`, or `'['`), push it onto the stack. +5. If the current character is a closing parenthesis (`')'`, `'}'`, or `']'`), check if the stack is empty. If it is, return `false` because there's no matching opening parenthesis for the current closing parenthesis. +6. If the stack is not empty, pop the top element from the stack and check if it matches the current closing parenthesis. If it doesn't match, return `false`. +7. After iterating through all characters in `s`, check if the stack is empty. If it's not empty, return `false` because there are unmatched opening parentheses remaining. +8. If the stack is empty after processing all characters, return `true` because all parentheses are valid. + +Here's the implementation: + +```java +import java.util.Stack; + +public class Solution { + public boolean isValid(String s) { + Stack stack = new Stack<>(); + + for (char c : s.toCharArray()) { + if (c == '(' || c == '{' || c == '[') { + stack.push(c); + } else { + if (stack.isEmpty()) { + return false; + } + char top = stack.pop(); + if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) { + return false; + } + } + } + + return stack.isEmpty(); + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test cases + System.out.println(solution.isValid("()")); // true + System.out.println(solution.isValid("()[]{}")); // true + System.out.println(solution.isValid("(]")); // false + System.out.println(solution.isValid("([)]")); // false + System.out.println(solution.isValid("{[]}")); // true + } +} +``` + +This implementation provides a solution to the Valid Parentheses problem in Java using a stack data structure. From 15641902acc539beb8031eb5fea887eae0a98f40 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:55:03 +0200 Subject: [PATCH 20/21] Enhance README with mergeTwoLists explanation Added a detailed explanation and implementation for merging two sorted linked lists using recursion. --- .../s0021_merge_two_sorted_lists/readme.md | 69 ++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0021_merge_two_sorted_lists/readme.md b/src/main/java/g0001_0100/s0021_merge_two_sorted_lists/readme.md index 27127cdda..699679b01 100644 --- a/src/main/java/g0001_0100/s0021_merge_two_sorted_lists/readme.md +++ b/src/main/java/g0001_0100/s0021_merge_two_sorted_lists/readme.md @@ -32,4 +32,71 @@ Return _the head of the merged linked list_. * The number of nodes in both lists is in the range `[0, 50]`. * `-100 <= Node.val <= 100` -* Both `list1` and `list2` are sorted in **non-decreasing** order. \ No newline at end of file +* Both `list1` and `list2` are sorted in **non-decreasing** order. + +To solve the Merge Two Sorted Lists problem in Java with a `Solution` class, we'll implement a recursive approach. Here are the steps: + +1. Define a `ListNode` class to represent a node in the linked list. +2. Define a `Solution` class with a method named `mergeTwoLists` that takes two linked lists `l1` and `l2` as input and returns a merged sorted list. +3. The base case for the recursion is when either `l1` or `l2` is null. In this case, return the non-null list because it's already sorted. +4. Compare the values of the heads of `l1` and `l2`. Let `head` be the smaller value of the two heads. +5. Recursively call `mergeTwoLists` with the next node of the smaller head and the other list that remained unchanged. +6. Update the `next` pointer of the smaller head to point to the result of the recursive call. +7. Return the smaller head, which is the merged sorted list. + +Here's the implementation: + +```java +public class Solution { + static class ListNode { + int val; + ListNode next; + + ListNode(int val) { + this.val = val; + } + } + + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + if (l1 == null) { + return l2; + } + if (l2 == null) { + return l1; + } + + ListNode head; + if (l1.val < l2.val) { + head = l1; + head.next = mergeTwoLists(l1.next, l2); + } else { + head = l2; + head.next = mergeTwoLists(l1, l2.next); + } + + return head; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test cases + ListNode l1 = new ListNode(1); + l1.next = new ListNode(2); + l1.next.next = new ListNode(4); + + ListNode l2 = new ListNode(1); + l2.next = new ListNode(3); + l2.next.next = new ListNode(4); + + ListNode mergedList = solution.mergeTwoLists(l1, l2); + while (mergedList != null) { + System.out.print(mergedList.val + " "); + mergedList = mergedList.next; + } + System.out.println(); // newline + } +} +``` + +This implementation provides a solution to the Merge Two Sorted Lists problem in Java using a recursive approach. From 448f37bf28e05d4b1d74dbda0a4d119ff1b6f635 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 27 Oct 2025 17:55:49 +0200 Subject: [PATCH 21/21] Enhance readme with generate parentheses solution Added detailed explanation and implementation for generating parentheses using backtracking in Java. --- .../s0022_generate_parentheses/readme.md | 59 ++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/src/main/java/g0001_0100/s0022_generate_parentheses/readme.md b/src/main/java/g0001_0100/s0022_generate_parentheses/readme.md index 72cab17b6..82fb8c528 100644 --- a/src/main/java/g0001_0100/s0022_generate_parentheses/readme.md +++ b/src/main/java/g0001_0100/s0022_generate_parentheses/readme.md @@ -18,4 +18,61 @@ Given `n` pairs of parentheses, write a function to _generate all combinations o **Constraints:** -* `1 <= n <= 8` \ No newline at end of file +* `1 <= n <= 8` + +To solve the "Generate Parentheses" problem in Java with a `Solution` class, we can use a backtracking approach. Here are the steps: + +1. Define a `Solution` class. +2. Define a method named `generateParenthesis` that takes an integer `n` as input and returns a list of strings representing all combinations of well-formed parentheses. +3. Create an empty list to store the result. +4. Call the recursive helper function `generateParenthesisHelper` with the empty string `""`, counts of open and close parentheses set to `0`, the value of `n`, and the result list. +5. In the `generateParenthesisHelper` function: + - If the length of the current string is equal to `2 * n`, add it to the result list. + - If the count of open parentheses is less than `n`, append an open parenthesis to the current string and call the function recursively with increased open count. + - If the count of close parentheses is less than the count of open parentheses, append a close parenthesis to the current string and call the function recursively with increased close count. +6. Return the result list. + +Here's the implementation: + +```java +import java.util.ArrayList; +import java.util.List; + +public class Solution { + public List generateParenthesis(int n) { + List result = new ArrayList<>(); + generateParenthesisHelper("", 0, 0, n, result); + return result; + } + + private void generateParenthesisHelper(String current, int open, int close, int n, List result) { + if (current.length() == 2 * n) { + result.add(current); + return; + } + + if (open < n) { + generateParenthesisHelper(current + "(", open + 1, close, n, result); + } + + if (close < open) { + generateParenthesisHelper(current + ")", open, close + 1, n, result); + } + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + // Test cases + int n1 = 3; + System.out.println("Parentheses combinations for n = " + n1 + ":"); + System.out.println(solution.generateParenthesis(n1)); + + int n2 = 1; + System.out.println("\nParentheses combinations for n = " + n2 + ":"); + System.out.println(solution.generateParenthesis(n2)); + } +} +``` + +This implementation provides a solution to the "Generate Parentheses" problem in Java using a backtracking approach.