From fc307310f68b22e452a441b7076d860aaab708d8 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 17 Nov 2026 22:17:46 +0200 Subject: [PATCH 1/4] Added tasks 3993-4009 --- .../Solution.java | 13 +++ .../readme.md | 44 ++++++++++ .../Solution.java | 23 +++++ .../readme.md | 61 +++++++++++++ .../Solution.java | 78 ++++++++++++++++ .../readme.md | 74 ++++++++++++++++ .../Solution.java | 10 +++ .../readme.md | 38 ++++++++ .../Solution.java | 48 ++++++++++ .../readme.md | 43 +++++++++ .../Solution.java | 88 +++++++++++++++++++ .../readme.md | 69 +++++++++++++++ .../Solution.java | 73 +++++++++++++++ .../readme.md | 73 +++++++++++++++ .../Solution.java | 22 +++++ .../readme.md | 42 +++++++++ .../Solution.java | 43 +++++++++ .../s4001_aggregate_two_time_series/readme.md | 69 +++++++++++++++ .../s4002_count_valid_sequences/Solution.java | 40 +++++++++ .../s4002_count_valid_sequences/readme.md | 67 ++++++++++++++ .../Solution.java | 61 +++++++++++++ .../readme.md | 82 +++++++++++++++++ .../s4006_count_valid_prefixes/Solution.java | 25 ++++++ .../s4006_count_valid_prefixes/readme.md | 42 +++++++++ .../s4007_widest_possible_fence/Solution.java | 48 ++++++++++ .../s4007_widest_possible_fence/readme.md | 45 ++++++++++ .../Solution.java | 31 +++++++ .../readme.md | 60 +++++++++++++ .../Solution.java | 60 +++++++++++++ .../readme.md | 74 ++++++++++++++++ .../SolutionTest.java | 23 +++++ .../SolutionTest.java | 23 +++++ .../SolutionTest.java | 43 +++++++++ .../SolutionTest.java | 18 ++++ .../SolutionTest.java | 22 +++++ .../SolutionTest.java | 29 ++++++ .../SolutionTest.java | 30 +++++++ .../SolutionTest.java | 23 +++++ .../SolutionTest.java | 34 +++++++ .../SolutionTest.java | 23 +++++ .../SolutionTest.java | 23 +++++ .../SolutionTest.java | 18 ++++ .../SolutionTest.java | 18 ++++ .../SolutionTest.java | 24 +++++ .../SolutionTest.java | 28 ++++++ 45 files changed, 1925 insertions(+) create mode 100644 src/main/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/Solution.java create mode 100644 src/main/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/readme.md create mode 100644 src/main/java/g3901_4000/s3994_minimum_adjacent_swaps_to_partition_array/Solution.java create mode 100644 src/main/java/g3901_4000/s3994_minimum_adjacent_swaps_to_partition_array/readme.md create mode 100644 src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/Solution.java create mode 100644 src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/readme.md create mode 100644 src/main/java/g3901_4000/s3996_even_number_of_knight_moves/Solution.java create mode 100644 src/main/java/g3901_4000/s3996_even_number_of_knight_moves/readme.md create mode 100644 src/main/java/g3901_4000/s3997_count_dominant_nodes_in_a_binary_tree/Solution.java create mode 100644 src/main/java/g3901_4000/s3997_count_dominant_nodes_in_a_binary_tree/readme.md create mode 100644 src/main/java/g3901_4000/s3998_transform_binary_string_using_subsequence_sort/Solution.java create mode 100644 src/main/java/g3901_4000/s3998_transform_binary_string_using_subsequence_sort/readme.md create mode 100644 src/main/java/g3901_4000/s3999_minimum_number_of_string_groups_through_transformations/Solution.java create mode 100644 src/main/java/g3901_4000/s3999_minimum_number_of_string_groups_through_transformations/readme.md create mode 100644 src/main/java/g3901_4000/s4000_largest_integer_with_given_digit_sum/Solution.java create mode 100644 src/main/java/g3901_4000/s4000_largest_integer_with_given_digit_sum/readme.md create mode 100644 src/main/java/g4001_4100/s4001_aggregate_two_time_series/Solution.java create mode 100644 src/main/java/g4001_4100/s4001_aggregate_two_time_series/readme.md create mode 100644 src/main/java/g4001_4100/s4002_count_valid_sequences/Solution.java create mode 100644 src/main/java/g4001_4100/s4002_count_valid_sequences/readme.md create mode 100644 src/main/java/g4001_4100/s4003_minimum_cost_path_with_alternating_directions_iii/Solution.java create mode 100644 src/main/java/g4001_4100/s4003_minimum_cost_path_with_alternating_directions_iii/readme.md create mode 100644 src/main/java/g4001_4100/s4006_count_valid_prefixes/Solution.java create mode 100644 src/main/java/g4001_4100/s4006_count_valid_prefixes/readme.md create mode 100644 src/main/java/g4001_4100/s4007_widest_possible_fence/Solution.java create mode 100644 src/main/java/g4001_4100/s4007_widest_possible_fence/readme.md create mode 100644 src/main/java/g4001_4100/s4008_minimum_initial_strength_to_defeat_all_monsters/Solution.java create mode 100644 src/main/java/g4001_4100/s4008_minimum_initial_strength_to_defeat_all_monsters/readme.md create mode 100644 src/main/java/g4001_4100/s4009_minimum_possible_maximum_waiting_time/Solution.java create mode 100644 src/main/java/g4001_4100/s4009_minimum_possible_maximum_waiting_time/readme.md create mode 100644 src/test/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3994_minimum_adjacent_swaps_to_partition_array/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3996_even_number_of_knight_moves/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3997_count_dominant_nodes_in_a_binary_tree/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3998_transform_binary_string_using_subsequence_sort/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3999_minimum_number_of_string_groups_through_transformations/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s4000_largest_integer_with_given_digit_sum/SolutionTest.java create mode 100644 src/test/java/g4001_4100/s4001_aggregate_two_time_series/SolutionTest.java create mode 100644 src/test/java/g4001_4100/s4002_count_valid_sequences/SolutionTest.java create mode 100644 src/test/java/g4001_4100/s4003_minimum_cost_path_with_alternating_directions_iii/SolutionTest.java create mode 100644 src/test/java/g4001_4100/s4006_count_valid_prefixes/SolutionTest.java create mode 100644 src/test/java/g4001_4100/s4007_widest_possible_fence/SolutionTest.java create mode 100644 src/test/java/g4001_4100/s4008_minimum_initial_strength_to_defeat_all_monsters/SolutionTest.java create mode 100644 src/test/java/g4001_4100/s4009_minimum_possible_maximum_waiting_time/SolutionTest.java diff --git a/src/main/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/Solution.java b/src/main/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/Solution.java new file mode 100644 index 000000000..a38805242 --- /dev/null +++ b/src/main/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/Solution.java @@ -0,0 +1,13 @@ +package g3901_4000.s3993_maximum_value_of_an_alternating_sequence; + +// #Medium #Math #Greedy #Senior #Biweekly_Contest_187 +// #2026_11_17_Time_1_ms_(96.70%)_Space_42.16_MB_(87.91%) + +public class Solution { + public long maximumValue(int n, int s, int m) { + if (n == 1) { + return s; + } + return (long) s + (long) (n / 2) * (m - 1) + 1; + } +} diff --git a/src/main/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/readme.md b/src/main/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/readme.md new file mode 100644 index 000000000..3e574b0cd --- /dev/null +++ b/src/main/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/readme.md @@ -0,0 +1,44 @@ +3993\. Maximum Value of an Alternating Sequence + +Medium + +You are given three integers `n`, `s`, and `m`. + +A sequence `seq` of integers of length `n` is considered **valid** if: + +* `seq[0] = s`. +* The sequence is **alternating**, meaning that either: + * `seq[0] > seq[1] < seq[2] > ...`, or + * `seq[0] < seq[1] > seq[2] < ...`. +* For every adjacent pair, `|seq[i] - seq[i - 1]| <= m`. + +A sequence of length 1 is considered alternating. + +Return the **maximum** possible element that can appear in any valid sequence. + +OriginalJava**Example 1:** + +**Input:** n = 4, s = 3, m = 5 + +**Output:** 12 + +**Explanation:** + +* One valid sequence is `[3, 8, 7, 12]`. +* The maximum element in the sequence is 12. + +**Example 2:** + +**Input:** n = 2, s = 4, m = 3 + +**Output:** 7 + +**Explanation:** + +* One valid sequence is `[4, 7]`. +* The maximum element in the sequence is 7. + +**Constraints:** + +* 1 <= n, s <= 109 +* 1 <= m <= 105 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3994_minimum_adjacent_swaps_to_partition_array/Solution.java b/src/main/java/g3901_4000/s3994_minimum_adjacent_swaps_to_partition_array/Solution.java new file mode 100644 index 000000000..ecfde4efb --- /dev/null +++ b/src/main/java/g3901_4000/s3994_minimum_adjacent_swaps_to_partition_array/Solution.java @@ -0,0 +1,23 @@ +package g3901_4000.s3994_minimum_adjacent_swaps_to_partition_array; + +// #Medium #Array #Greedy #Staff #Biweekly_Contest_187 +// #2026_11_17_Time_6_ms_(80.28%)_Space_101.87_MB_(61.97%) + +public class Solution { + public int minAdjacentSwaps(int[] nums, int a, int b) { + long ans = 0; + long c1 = 0; + long c2 = 0; + for (int v : nums) { + if (v < a) { + ans += c1 + c2; + } else if (v <= b) { + c1++; + ans += c2; + } else { + c2++; + } + } + return (int) (ans % 1000000007); + } +} diff --git a/src/main/java/g3901_4000/s3994_minimum_adjacent_swaps_to_partition_array/readme.md b/src/main/java/g3901_4000/s3994_minimum_adjacent_swaps_to_partition_array/readme.md new file mode 100644 index 000000000..c1e5d3588 --- /dev/null +++ b/src/main/java/g3901_4000/s3994_minimum_adjacent_swaps_to_partition_array/readme.md @@ -0,0 +1,61 @@ +3994\. Minimum Adjacent Swaps to Partition Array + +Medium + +You are given an integer array `nums` and two integers `a` and `b` such that `a < b`. + +An array is called **good** if it can be split into three **contiguous** parts, in this order, such that: + +* Every element in the first part is **less than** `a`. +* Every element in the second part is **in** the range `[a, b]` inclusive. +* Every element in the third part is **greater than** `b`. + +Any of the three parts **may be** empty. + +In one **adjacent swap**, you may swap two **neighboring** elements of `nums`. + +Return the **minimum number** of adjacent swaps required to make `nums` good. Since the answer may be very large, return it **modulo** 109 + 7. + +OriginalJava**Example 1:** + +**Input:** nums = [1,3,2,4,5,6], a = 3, b = 4 + +**Output:** 1 + +**Explanation:** + +* Swap `nums[1]` and `nums[2]`. The array becomes `[1, 2, 3, 4, 5, 6]`. +* This array is good because it can be split into `[1, 2]`, `[3, 4]`, and `[5, 6]`. + +**Example 2:** + +**Input:** nums = [9,7,5,3], a = 4, b = 8 + +**Output:** 5 + +**Explanation:** + +One sequence of optimal swaps is as follows: + +* Swap `nums[2]` and `nums[3]`. The array becomes `[9, 7, 3, 5]`. +* Swap `nums[1]` and `nums[2]`. The array becomes `[9, 3, 7, 5]`. +* Swap `nums[0]` and `nums[1]`. The array becomes `[3, 9, 7, 5]`. +* Swap `nums[1]` and `nums[2]`. The array becomes `[3, 7, 9, 5]`. +* Swap `nums[2]` and `nums[3]`. The array becomes `[3, 7, 5, 9]`. +* This array is good because it can be split into `[3]`, `[7, 5]`, and `[9]`. + +**Example 3:** + +**Input:** nums = [3,7,5,9], a = 4, b = 8 + +**Output:** 0 + +**Explanation:** + +The array is already good. No swaps are needed. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 109 +* 1 <= a < b <= 109 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/Solution.java b/src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/Solution.java new file mode 100644 index 000000000..198c7d95b --- /dev/null +++ b/src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/Solution.java @@ -0,0 +1,78 @@ +package g3901_4000.s3995_minimum_cost_to_convert_string_iii; + +// #Hard #Array #String #Dynamic_Programming #Senior_Staff #Biweekly_Contest_187 +// #2026_11_17_Time_10_ms_(100.00%)_Space_47.23_MB_(68.97%) + +import java.util.Arrays; +import java.util.List; + +public class Solution { + public int minCost(String source, String target, List> rules, int[] costs) { + int n = source.length(); + if (n != target.length()) { + return -1; + } + if (source.equals(target)) { + return 0; + } + int m = rules.size(); + int[] len = new int[m]; + String[] pat = new String[m]; + String[] rep = new String[m]; + int[] rulesCost = new int[m]; + for (int i = 0; i < m; i++) { + String p = rules.get(i).get(0); + String r = rules.get(i).get(1); + pat[i] = p; + rep[i] = r; + len[i] = p.length(); + int wild = 0; + for (char c : p.toCharArray()) { + if (c == '*') { + wild++; + } + } + rulesCost[i] = costs[i] + wild; + } + int in = Integer.MAX_VALUE / 2; + int[] dp = new int[n + 1]; + Arrays.fill(dp, in); + dp[0] = 0; + for (int i = 0; i < n; i++) { + if (dp[i] == in) { + continue; + } + if (source.charAt(i) == target.charAt(i)) { + if (dp[i] < dp[i + 1]) { + dp[i + 1] = dp[i]; + } + } + for (int k = 0; k < m; k++) { + int l = len[k]; + if (i + l > n) { + continue; + } + boolean match = true; + for (int j = 0; j < l; j++) { + char pc = pat[k].charAt(j); + char sc = source.charAt(i + j); + if (pc != '*' && pc != sc) { + match = false; + break; + } + } + if (!match) { + continue; + } + if (!target.substring(i, i + l).equals(rep[k])) { + continue; + } + int nd = dp[i] + rulesCost[k]; + if (nd < dp[i + l]) { + dp[i + l] = nd; + } + } + } + return dp[n] >= in ? -1 : dp[n]; + } +} diff --git a/src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/readme.md b/src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/readme.md new file mode 100644 index 000000000..9949eafbd --- /dev/null +++ b/src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/readme.md @@ -0,0 +1,74 @@ +3995\. Minimum Cost to Convert String III + +Hard + +You are given two strings, `source` and `target`. + +You are also given a 2D string array `rules`, where rules[i] = [patterni, replacementi], and an integer array `costs`, where `costs[i]` is the base cost of applying `rules[i]`. Both arrays have the same length. Additionally, patterni and replacementi have the same length. + +You may apply **any** rule **any** number of times. Each rule application works as follows: + +* Choose an index `l` such that the range of positions from `l` to l + patterni.length - 1 exists in the current string and **none** of these positions has been used in a previous rule application. +* For each index `j`, the character patterni[j] must either be **equal** to the current character at position `l + j`, or be `'*'`. +* Replace the characters in this range with replacementi. The replacement is used **exactly** as given and does not contain wildcards. +* The cost of this rule application is `costs[i]` **plus** the number of `'*'` characters in patterni. +* Once a character position has been used in a rule application, it **cannot** be used in any **later** rule application. + +Since every patterni and replacementi have the same length, character positions are preserved after every rule application. + +Return the **minimum** total cost required to transform `source` into `target`. If it is impossible, return -1. + +OriginalJava**Example 1:** + +**Input:** source = "hello", target = "world", rules = [["he","wo"],["llo","rld"]], costs = [3,4] + +**Output:** 7 + +**Explanation:** + +* Apply `rules[0]` to replace `"he"` with `"wo"` at cost 3, so the string becomes `"wollo"`. +* Apply `rules[1]` to replace `"llo"` with `"rld"` at cost 4, so the string becomes `"world"`. +* The total cost is `3 + 4 = 7`. + +**Example 2:** + +**Input:** source = "cat", target = "dog", rules = [["c\*t","dog"]], costs = [2] + +**Output:** 3 + +**Explanation:** + +* Apply `rules[0]` to replace `"cat"` with `"dog"`. The wildcard `'*'` matches `'a'`, adding 1 to the base cost 2. +* The total cost is `2 + 1 = 3`. + +**Example 3:** + +**Input:** source = "test", target = "next", rules = [["\*e\*t","next"]], costs = [4] + +**Output:** 6 + +**Explanation:** + +* Apply `rules[0]` to replace `"test"` with `"next"`. The first wildcard matches `'t'` and the second wildcard matches `'s'`, adding 2 to the base cost 4. +* The total cost is `4 + 2 = 6`. + +**Example 4:** + +**Input:** source = "ab", target = "bc", rules = [["a\*","bd"]], costs = [9] + +**Output:** \-1 + +**Explanation:** + +No sequence of rule applications can transform `source` into `target`, so the answer is -1. + +**Constraints:** + +* `1 <= source.length == target.length <= 5000` +* `source` and `target` consist of lowercase English letters. +* `1 <= rules.length == costs.length <= 200` +* rules[i] = [patterni, replacementi] +* 1 <= patterni.length == replacementi.length <= 20 +* patterni contains at least one lowercase English letter and at most 5 `'*'` characters. +* replacementi contains only lowercase English letters. +* `1 <= costs[i] <= 1000` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3996_even_number_of_knight_moves/Solution.java b/src/main/java/g3901_4000/s3996_even_number_of_knight_moves/Solution.java new file mode 100644 index 000000000..7defb621c --- /dev/null +++ b/src/main/java/g3901_4000/s3996_even_number_of_knight_moves/Solution.java @@ -0,0 +1,10 @@ +package g3901_4000.s3996_even_number_of_knight_moves; + +// #Easy #Array #Math #Mid_Level #Weekly_Contest_511 +// #2026_11_17_Time_1_ms_(88.64%)_Space_43.26_MB_(96.70%) + +public class Solution { + public boolean canReach(int[] start, int[] target) { + return (start[0] + start[1]) % 2 == (target[0] + target[1]) % 2; + } +} diff --git a/src/main/java/g3901_4000/s3996_even_number_of_knight_moves/readme.md b/src/main/java/g3901_4000/s3996_even_number_of_knight_moves/readme.md new file mode 100644 index 000000000..5b04c9abc --- /dev/null +++ b/src/main/java/g3901_4000/s3996_even_number_of_knight_moves/readme.md @@ -0,0 +1,38 @@ +3996\. Even Number of Knight Moves + +Easy + +You are given two integer arrays `start` and `target`, where each array is of the form `[x, y]` representing a cell on a standard 8 x 8 chessboard. + +Return `true` if a knight can move from `start` to `target` in an **even** number of moves. Otherwise, return `false`. + +**Note:** A valid knight move consists of moving two squares in one direction and one square perpendicular to it. The figure below illustrates all eight possible moves from a cell. + +![](https://assets.leetcode.com/uploads/2018/10/12/knight.png) + +OriginalJava**Example 1:** + +**Input:** start = [1,1], target = [2,2] + +**Output:** true + +**Explanation:** + +One possible sequence of moves is `(1, 1) -> (3, 2) -> (2, 4) -> (4, 3) -> (2, 2)`. + +The knight reaches the target in 4 moves, which is even. Thus, the answer is `true`. + +**Example 2:** + +**Input:** start = [4,5], target = [6,6] + +**Output:** false + +**Explanation:** + +It is impossible to reach `target = [6, 6]` from `start = [4, 5]` in an even number of moves. Thus, the answer is `false`. + +**Constraints:** + +* `start.length == target.length == 2` +* `0 <= start[i], target[i] <= 7` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3997_count_dominant_nodes_in_a_binary_tree/Solution.java b/src/main/java/g3901_4000/s3997_count_dominant_nodes_in_a_binary_tree/Solution.java new file mode 100644 index 000000000..5f03cc4e4 --- /dev/null +++ b/src/main/java/g3901_4000/s3997_count_dominant_nodes_in_a_binary_tree/Solution.java @@ -0,0 +1,48 @@ +package g3901_4000.s3997_count_dominant_nodes_in_a_binary_tree; + +// #Medium #Tree #Binary_Tree #Senior #Weekly_Contest_511 #Depth_First_Search +// #2026_11_17_Time_7_ms_(95.22%)_Space_172.70_MB_(86.01%) + +import com_github_leetcode.TreeNode; + +/* + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + private int dominantNode; + + public int countDominantNodes(TreeNode root) { + dominantNode = 0; + dfs(root); + return dominantNode; + } + + private int dfs(TreeNode root) { + if (root == null) { + return Integer.MIN_VALUE; + } + if (root.left == null && root.right == null) { + dominantNode++; + return root.val; + } + int left = dfs(root.left); + int right = dfs(root.right); + int max = Math.max(left, right); + if (root.val >= max) { + dominantNode++; + } + return Math.max(max, root.val); + } +} diff --git a/src/main/java/g3901_4000/s3997_count_dominant_nodes_in_a_binary_tree/readme.md b/src/main/java/g3901_4000/s3997_count_dominant_nodes_in_a_binary_tree/readme.md new file mode 100644 index 000000000..cadb15884 --- /dev/null +++ b/src/main/java/g3901_4000/s3997_count_dominant_nodes_in_a_binary_tree/readme.md @@ -0,0 +1,43 @@ +3997\. Count Dominant Nodes in a Binary Tree + +Medium + +You are given the `root` of a complete binary tree. + +A node `x` is called **dominant** if its value is equal to the maximum value among all nodes in the subtree rooted at `x`. + +Return the number of dominant nodes in the tree. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2026/06/13/tnew.png) + +**Input:** root = [5,3,8,2,4,7,1] + +**Output:** 5 + +**Explanation:** + +* The leaf nodes with values 2, 4, 7, and 1 are dominant. +* The node with value 8 is dominant because its value is the maximum value in its subtree `[8, 7, 1]`. +* Thus, the answer is 5. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2026/06/15/t9.png) + +**Input:** root = [1,2,3,1,2] + +**Output:** 4 + +**Explanation:** + +* The leaf nodes with values 1, 2, and 3 are dominant. +* The node with value 2 whose subtree is `[2, 1, 2]` is dominant because its value is the maximum value in its subtree. +* Thus, the answer is 4. + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 105]. +* 1 <= Node.val <= 109 +* The tree is guaranteed to be a complete binary tree. \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3998_transform_binary_string_using_subsequence_sort/Solution.java b/src/main/java/g3901_4000/s3998_transform_binary_string_using_subsequence_sort/Solution.java new file mode 100644 index 000000000..ad813c4b5 --- /dev/null +++ b/src/main/java/g3901_4000/s3998_transform_binary_string_using_subsequence_sort/Solution.java @@ -0,0 +1,88 @@ +package g3901_4000.s3998_transform_binary_string_using_subsequence_sort; + +// #Medium #Array #String #Greedy #Two_Pointers #Staff #Weekly_Contest_511 +// #2026_11_17_Time_25_ms_(100.00%)_Space_85.98_MB_(6.45%) + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +public class Solution { + public boolean[] transformStr(String s, String[] strs) { + int len = strs.length; + int[] count = new int[2]; + for (char ch : s.toCharArray()) { + count[ch - '0']++; + } + // create lists of all those tasks, which are no blocking main thread + List> listOfFutureTasks = new ArrayList<>(); + for (String target : strs) { + listOfFutureTasks.add(canConvert(s, target, count)); + } + // allOf will make sure all things are running concurrently/parallely while .join() can be + // used to complete em all + CompletableFuture allDone = + CompletableFuture.allOf(listOfFutureTasks.toArray(new CompletableFuture[0])); + // collect results when allDone is complete + boolean[] res = new boolean[len]; + allDone.thenRun( + () -> { + for (int i = 0; i < len; i++) { + res[i] = listOfFutureTasks.get(i).join(); + } + }) + .join(); + return res; + } + + private CompletableFuture canConvert(String src, String target, int[] count) { + // first check there should be equal or less number of 1's and 0's + return CompletableFuture.supplyAsync(() -> validateBalance(target, count)) + .thenApply(dst -> dst != null && isPossibleToConvert(src, dst)); + } + + private boolean isPossibleToConvert(String src, String dst) { + int n = src.length(); + int zero = 0; + for (int i = 0; i < n; i++) { + if (src.charAt(i) == '0') { + zero++; + } + if (dst.charAt(i) == '0') { + zero--; + } + if (zero > 0) { + return false; + } + } + return true; + } + + private String validateBalance(String s, int[] count) { + int[] local = new int[2]; + for (char ch : s.toCharArray()) { + if (ch == '?') { + continue; + } + local[ch - '0']++; + } + if (local[0] > count[0] || local[1] > count[1]) { + return null; + } + int diff0 = count[0] - local[0]; + int diff1 = count[1] - local[1]; + StringBuilder sb = new StringBuilder(); + for (char c : s.toCharArray()) { + if (c == '?') { + if (diff0-- > 0) { + sb.append('0'); + } else if (diff1-- > 0) { + sb.append('1'); + } + } else { + sb.append(c); + } + } + return sb.toString(); + } +} diff --git a/src/main/java/g3901_4000/s3998_transform_binary_string_using_subsequence_sort/readme.md b/src/main/java/g3901_4000/s3998_transform_binary_string_using_subsequence_sort/readme.md new file mode 100644 index 000000000..6b1510fdd --- /dev/null +++ b/src/main/java/g3901_4000/s3998_transform_binary_string_using_subsequence_sort/readme.md @@ -0,0 +1,69 @@ +3998\. Transform Binary String Using Subsequence Sort + +Medium + +You are given a binary string `s`. + +You are also given an array of strings `strs`, where each `strs[i]` has the **same** length as `s` and consists of characters `'0'`, `'1'`, and `'?'`. Each `'?'` can be replaced by either `'0'` or `'1'`. + +You may perform the following operation any number of times (including zero): + +* Choose any subsequence `sub` of `s`. +* Sort `sub` in **non-decreasing** order. +* Replace the chosen **subsequence** in `s` with the sorted `sub`, keeping all other characters unchanged. + +Return a boolean array `ans`, where `ans[i]` is `true` if it's possible to replace all `'?'` in `strs[i]` with `'0'` or `'1'` and transform `s` into the resulting string using the allowed operation above, otherwise return `false`. + +OriginalJava**Example 1:** + +**Input:** s = "101", strs = ["1?1","0?1","0?0"] + +**Output:** [true,true,false] + +**Explanation:** + +| `i` | `strs[i]` | Replacement | Result `strs[i]` | Operation(s) | Result | +| --- | --- | --- | --- | --- | --- | +| 0 | `"1?1"` | `? → 0` | `"101"` | Matches `s`. | `true` | +| 1 | `"0?1"` | `? → 1` | `"011"` | Select the subsequence at indices `[0..2]` of `s` → `"101"`.
Sort `"101"` to get `"011" = strs[i]`. | `true` | +| 2 | `"0?0"` | `? → 0` or `1` | `"000"` or `"010"` | Not feasible. | `false` | + +Thus, `ans = [true, true, false]`. + +**Example 2:** + +**Input:** s = "1100", strs = ["0011","11?1","1?1?"] + +**Output:** [true,false,true] + +**Explanation:** + +| `i` | `strs[i]` | Replacement | Result `strs[i]` | Operation(s) | Result | +| --- | --- | --- | --- | --- | --- | +| 0 | `"0011"` | \- | `"0011"` | Select the subsequence at indices `[0..3]` of `s` → `"1100"`.
Sort `"1100"` to get `"0011" = strs[i]`. | `true` | +| 1 | `"11?1"` | `? → 0` | `"1101"` | Not feasible. | `false` | +| 2 | `"1?1?"` | First `? → 0`
Second `? → 0` | `"1010"` | Select the subsequence at indices `[1, 2]` of `s` → `"10"`.
Sort `"10"` to get `"01"`, so s = "1010". | `true` | + +Thus, `ans = [true, false, true]`. + +**Example 3:** + +**Input:** s = "1010", strs = ["0011"] + +**Output:** [true] + +**Explanation:** + +| `i` | `strs[i]` | Replacement | Result `strs[i]` | Operation(s) | Result | +| --- | --- | --- | --- | --- | --- | +| 0 | `"0011"` | \- | `"0011"` | Select the subsequence at indices `[0, 2, 3]` of `s` → `"110"`.
Sort `"110"` to get `"011"`, so s = "0011" = strs[i]. | `true` | + +Thus, `ans = [true]`. + +**Constraints:** + +* `1 <= n == s.length <= 2000` +* `s[i]` is either `'0'` or `'1'`. +* `1 <= strs.length <= 2000` +* `strs[i].length == n` +* `strs[i]` is either `'0'`, `'1'`, or `'?'`. \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3999_minimum_number_of_string_groups_through_transformations/Solution.java b/src/main/java/g3901_4000/s3999_minimum_number_of_string_groups_through_transformations/Solution.java new file mode 100644 index 000000000..a07dff57f --- /dev/null +++ b/src/main/java/g3901_4000/s3999_minimum_number_of_string_groups_through_transformations/Solution.java @@ -0,0 +1,73 @@ +package g3901_4000.s3999_minimum_number_of_string_groups_through_transformations; + +// #Hard #String #Hash_Table #Two_Pointers #Senior_Staff #Weekly_Contest_511 +// #2026_11_17_Time_83_ms_(100.00%)_Space_60.37_MB_(97.83%) + +import java.util.HashSet; + +public class Solution { + public int minimumGroups(String[] words) { + HashSet set = new HashSet<>(); + for (String w : words) { + int n = w.length(); + int evenLen = (n + 1) >> 1; + int oddLen = n >> 1; + char[] even = new char[evenLen]; + char[] odd = new char[oddLen]; + int ei = 0; + int oi = 0; + for (int i = 0; i < n; i++) { + if ((i & 1) == 0) { + even[ei++] = w.charAt(i); + } else { + odd[oi++] = w.charAt(i); + } + } + int eStart = booth(even); + int oStart = booth(odd); + long h1 = hash(even, eStart); + long h2 = hash(odd, oStart); + long key = h1 * 1000003L + h2; + set.add(key); + } + return set.size(); + } + + private int booth(char[] s) { + int n = s.length; + if (n <= 1) { + return 0; + } + int i = 0; + int j = 1; + int k = 0; + while (i < n && j < n && k < n) { + char a = s[(i + k) % n]; + char b = s[(j + k) % n]; + if (a == b) { + k++; + } else if (a > b) { + i += k + 1; + if (i <= j) { + i = j + 1; + } + k = 0; + } else { + j += k + 1; + if (j <= i) { + j = i + 1; + } + k = 0; + } + } + return Math.min(i, j); + } + + private long hash(char[] s, int start) { + long h = 0; + for (int i = 0; i < s.length; i++) { + h = h * 131 + s[(start + i) % s.length]; + } + return h; + } +} diff --git a/src/main/java/g3901_4000/s3999_minimum_number_of_string_groups_through_transformations/readme.md b/src/main/java/g3901_4000/s3999_minimum_number_of_string_groups_through_transformations/readme.md new file mode 100644 index 000000000..0f3a98f17 --- /dev/null +++ b/src/main/java/g3901_4000/s3999_minimum_number_of_string_groups_through_transformations/readme.md @@ -0,0 +1,73 @@ +3999\. Minimum Number of String Groups Through Transformations + +Hard + +You are given an array of strings `words`. + +Define a **transformation** on a string `s` as follows: + +* Let `E` be the subsequence of characters at even indices of `s`. +* Let `O` be the **subsequence** of characters at odd indices of `s`. +* **Independently** cyclically shift `E` and `O` by **any** number of positions to the right, possibly zero. +* Reconstruct the string by placing the shifted `E` characters back into even indices and the shifted `O` characters back into odd indices. + +Two strings are **equivalent** if one can be transformed into the other by a **single** transformation. + +Partition `words` into the **minimum** number of groups such that: + +* Every string belongs to **exactly** one group. +* Every pair of strings in the same group are **equivalent**. + +Return an integer denoting the **minimum** number of groups. + +OriginalJava**Example 1:** + +**Input:** words = ["ntgwz","zwntg"] + +**Output:** 1 + +**Explanation:** + +* For `"ntgwz"`, the even-index subsequence is `"ngz"` and the odd-index subsequence is `"tw"`. +* Shift `"ngz"` right by `1` position to obtain `"zng"`, and shift `"tw"` right by `1` position to obtain `"wt"`. +* After reconstructing the string, we obtain `"zwntg"`. +* Therefore, both strings are equivalent and belong to the same group. + +**Example 2:** + +**Input:** words = ["abc","cab","bac","acb","bca","cba"] + +**Output:** 3 + +**Explanation:** + +The strings can be partitioned into the following groups: + +* `["abc","cba"]` +* `["cab","bac"]` +* `["acb","bca"]` + +**Example 3:** + +**Input:** words = ["leet","abb","bab","deed","edde","code","bba"] + +**Output:** 5 + +**Explanation:** + +The strings can be partitioned into the following groups: + +* `["abb","bba"]` +* `["deed","edde"]` +* `["leet"]` +* `["bab"]` +* `["code"]` + +All pairs of strings in each group are equivalent. + +**Constraints:** + +* 1 <= words.length <= 105 +* 1 <= words[i].length <= 5 * 105 +* The sum of `words[i].length` does not exceed 5 * 105. +* `words[i]` consist of lowercase English letters. \ No newline at end of file diff --git a/src/main/java/g3901_4000/s4000_largest_integer_with_given_digit_sum/Solution.java b/src/main/java/g3901_4000/s4000_largest_integer_with_given_digit_sum/Solution.java new file mode 100644 index 000000000..d1bf524c4 --- /dev/null +++ b/src/main/java/g3901_4000/s4000_largest_integer_with_given_digit_sum/Solution.java @@ -0,0 +1,22 @@ +package g3901_4000.s4000_largest_integer_with_given_digit_sum; + +// #Easy #Math #Greedy #Mid_Level #Weekly_Contest_512 +// #2026_11_17_Time_1_ms_(68.99%)_Space_42.00_MB_(64.02%) + +public class Solution { + public int largestInteger(int n, int s) { + if (9 * n < s) { + return -1; + } + if (s == 0) { + return 0; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < n; i++) { + int d = Math.min(9, s); + sb.append(d); + s -= d; + } + return Integer.parseInt(sb.toString()); + } +} diff --git a/src/main/java/g3901_4000/s4000_largest_integer_with_given_digit_sum/readme.md b/src/main/java/g3901_4000/s4000_largest_integer_with_given_digit_sum/readme.md new file mode 100644 index 000000000..4bb61d987 --- /dev/null +++ b/src/main/java/g3901_4000/s4000_largest_integer_with_given_digit_sum/readme.md @@ -0,0 +1,42 @@ +4000\. Largest Integer With Given Digit Sum + +Easy + +You are given two non-negative integers `n` and `s`. + +Return the **largest** integer that has **at most** `n` digits and whose sum of digits is `s`. If no such integer exists, return -1. + +OriginalJava**Example 1:** + +**Input:** n = 2, s = 9 + +**Output:** 90 + +**Explanation:** + +The largest integer with at most 2 digits that has a sum of digits of 9 is 90. + +**Example 2:** + +**Input:** n = 2, s = 19 + +**Output:** \-1 + +**Explanation:** + +There is no integer with at most 2 digits that has a sum of digits of 19, so the answer is -1. + +**Example 3:** + +**Input:** n = 5, s = 0 + +**Output:** 0 + +**Explanation:** + +The only non-negative integer whose digits sum to 0 is 0. + +**Constraints:** + +* `1 <= n <= 5` +* `0 <= s <= 100` \ No newline at end of file diff --git a/src/main/java/g4001_4100/s4001_aggregate_two_time_series/Solution.java b/src/main/java/g4001_4100/s4001_aggregate_two_time_series/Solution.java new file mode 100644 index 000000000..956cfc276 --- /dev/null +++ b/src/main/java/g4001_4100/s4001_aggregate_two_time_series/Solution.java @@ -0,0 +1,43 @@ +package g4001_4100.s4001_aggregate_two_time_series; + +// #Medium #Array #Two_Pointers #Senior #Weekly_Contest_512 +// #2026_11_17_Time_9_ms_(100.00%)_Space_167.92_MB_(85.71%) + +import java.util.ArrayList; +import java.util.List; + +public class Solution { + public List> aggregateTimeSeries(int[][] left, int[][] right) { + int n = left.length; + int m = right.length; + List> result = new ArrayList<>(left.length + m); + int i = 0; + int j = 0; + while (i < n && j < m) { + int[] lp = left[i]; + int[] rp = right[j]; + int cmp = Integer.compare(lp[0], rp[0]); + int value = lp[1] + rp[1]; + if (cmp < 0) { + result.add(List.of(lp[0], value)); + i++; + } else if (cmp > 0) { + result.add(List.of(rp[0], value)); + j++; + } else { + result.add(List.of(rp[0], value)); + i++; + j++; + } + } + while (i < n) { + result.add(List.of(left[i][0], left[i][1])); + i++; + } + while (j < m) { + result.add(List.of(right[j][0], right[j][1])); + j++; + } + return result; + } +} diff --git a/src/main/java/g4001_4100/s4001_aggregate_two_time_series/readme.md b/src/main/java/g4001_4100/s4001_aggregate_two_time_series/readme.md new file mode 100644 index 000000000..120ce6661 --- /dev/null +++ b/src/main/java/g4001_4100/s4001_aggregate_two_time_series/readme.md @@ -0,0 +1,69 @@ +4001\. Aggregate Two Time Series + +Medium + +You are given two 2D integer arrays `series1` and `series2`. + +Each element in both series is of the form `[timestamp, value]`, where: + +* `timestamp` is an integer representing the time. +* `value` is an integer representing the value at that timestamp. + +Each array is sorted in strictly increasing order of `timestamp`. + +For any timestamp **not present** in a series, its value is taken from the **next available timestamp** in the same series if one exists. Otherwise, its value is considered 0. + +The **aggregated series** is formed by summing the corresponding values from both series at every timestamp that appears in either series. + +Return the **aggregated series** as a 2D integer array of `[timestamp, summedValue]` pairs, sorted in **strictly increasing** order of timestamp. + +OriginalJava**Example 1:** + +**Input:** series1 = [[1,3],[4,1]], series2 = [[2,2],[5,2]] + +**Output:** [[1,5],[2,3],[4,3],[5,2]] + +**Explanation:** + +| Timestamp | `series1` | `series2` | `summedValue` | +| --- | --- | --- | --- | +| 1 | 3 | 2 | 5 | +| 2 | 1 | 2 | 3 | +| 4 | 1 | 2 | 3 | +| 5 | 0 | 2 | 2 | + +Thus, the aggregated series is `[[1, 5], [2, 3], [4, 3], [5, 2]]`. + +**Example 2:** + +**Input:** series1 = [[1,5],[3,1]], series2 = [[2,2]] + +**Output:** [[1,7],[2,3],[3,1]] + +**Explanation:** + +| Timestamp | `series1` | `series2` | `summedValue` | +| --- | --- | --- | --- | +| 1 | 5 | 2 | 7 | +| 2 | 1 | 2 | 3 | +| 3 | 1 | 0 | 1 | + +Thus, the aggregated series is `[[1, 7], [2, 3], [3, 1]]`. + +**Example 3:** + +**Input:** series1 = [[1,5]], series2 = [[1000000000,2]] + +**Output:** [[1,7],[1000000000,2]] + +**Explanation:** + +At timestamp 1, the next available value in `series2` is 2 at timestamp 1000000000. At timestamp 1000000000, there is no later timestamp in `series1`, so its value is 0. Only timestamps that appear in at least one of the two series are included. + +**Constraints:** + +* 1 <= series1.length, series2.length <= 105 +* `series1[i].length == series2[i].length == 2` +* 1 <= series1[i][0], series2[i][0] <= 109 +* 1 <= series1[i][1], series2[i][1] <= 109 +* Each series is sorted in strictly increasing order of `timestamp`. \ No newline at end of file diff --git a/src/main/java/g4001_4100/s4002_count_valid_sequences/Solution.java b/src/main/java/g4001_4100/s4002_count_valid_sequences/Solution.java new file mode 100644 index 000000000..64e32d19f --- /dev/null +++ b/src/main/java/g4001_4100/s4002_count_valid_sequences/Solution.java @@ -0,0 +1,40 @@ +package g4001_4100.s4002_count_valid_sequences; + +// #Medium #Math #Combinatorics #Staff #Weekly_Contest_512 +// #2026_11_17_Time_8_ms_(96.61%)_Space_42.35_MB_(61.02%) + +public class Solution { + private static final int MOD = 1000000007; + + private long power(long b, long e) { + long r = 1; + for (; e > 0; e >>= 1, b = b * b % MOD) { + if ((e & 1) == 1) { + r = r * b % MOD; + } + } + return r; + } + + private long comb(int n, int k) { + if (k < 0 || k > n) { + return 0; + } + k = Math.min(k, n - k); + long res = 1; + long den = 1; + for (int i = 1; i <= k; ++i) { + res = res * (n - i + 1) % MOD; + den = den * i % MOD; + } + return res * power(den, MOD - 2) % MOD; + } + + public int countValidSequences(int n, int k) { + long res = comb(n - 1, k - 1); + if (n % 2 == k % 2) { + res = (res - comb((n + k) / 2 - 1, k - 1) + MOD) % MOD; + } + return (int) res; + } +} diff --git a/src/main/java/g4001_4100/s4002_count_valid_sequences/readme.md b/src/main/java/g4001_4100/s4002_count_valid_sequences/readme.md new file mode 100644 index 000000000..a200cd57f --- /dev/null +++ b/src/main/java/g4001_4100/s4002_count_valid_sequences/readme.md @@ -0,0 +1,67 @@ +4002\. Count Valid Sequences + +Medium + +You are given two **positive** integers `n` and `k`. + +A **valid sequence** is a sequence of `k` positive integers such that: + +* The **sum** of all integers in the sequence is equal to `n`. +* The **product** of all integers in the sequence is **even**. + +Return the number of valid sequences. Since the answer may be very large, return it **modulo** 109 + 7. + +Two sequences are considered **different** if they differ at any index. For example, `[1, 1, 2]` and `[1, 2, 1]` are considered different sequences. + +OriginalJava**Example 1:** + +**Input:** n = 5, k = 3 + +**Output:** 3 + +**Explanation:** + +The sequences of length `k = 3` whose sum is 5 are: + +| Sequence | Product | Parity | +| --- | --- | --- | +| `[1, 1, 3]` | `1 * 1 * 3 = 3` | Odd | +| `[1, 2, 2]` | `1 * 2 * 2 = 4` | Even | +| `[2, 1, 2]` | `2 * 1 * 2 = 4` | Even | +| `[2, 2, 1]` | `2 * 2 * 1 = 4` | Even | +| `[1, 3, 1]` | `1 * 3 * 1 = 3` | Odd | +| `[3, 1, 1]` | `3 * 1 * 1 = 3` | Odd | + +There are 3 sequences with an even product, thus the answer is 3. + +**Example 2:** + +**Input:** n = 3, k = 2 + +**Output:** 2 + +**Explanation:** + +The sequences of length `k = 2` whose sum is 3 are: + +| Sequence | Product | Parity | +| --- | --- | --- | +| `[1, 2]` | `1 * 2 = 2` | Even | +| `[2, 1]` | `2 * 1 = 2` | Even | + +There are 2 sequences with an even product, thus the answer is 2. + +**Example 3:** + +**Input:** n = 5, k = 5 + +**Output:** 0 + +**Explanation:** + +The only possible sequence of length `k = 5` whose sum is 5 is `[1, 1, 1, 1, 1]`, which has an odd product. Thus, the answer is 0. + +**Constraints:** + +* 1 <= n <= 5 * 105 +* `1 <= k <= n` \ No newline at end of file diff --git a/src/main/java/g4001_4100/s4003_minimum_cost_path_with_alternating_directions_iii/Solution.java b/src/main/java/g4001_4100/s4003_minimum_cost_path_with_alternating_directions_iii/Solution.java new file mode 100644 index 000000000..037b6d26b --- /dev/null +++ b/src/main/java/g4001_4100/s4003_minimum_cost_path_with_alternating_directions_iii/Solution.java @@ -0,0 +1,61 @@ +package g4001_4100.s4003_minimum_cost_path_with_alternating_directions_iii; + +// #Hard #Array #Matrix #Heap_Priority_Queue #Shortest_Path #Graph_Theory #Senior_Staff +// #Weekly_Contest_512 #2026_11_17_Time_349_ms_(100.00%)_Space_139.73_MB_(84.00%) + +import java.util.Arrays; +import java.util.Comparator; +import java.util.PriorityQueue; + +public class Solution { + public long minCost(int m, int n, int[][] penalty) { + long inf = Long.MAX_VALUE / 4; + long[] dist = new long[m * n * 2]; + Arrays.fill(dist, inf); + PriorityQueue pq = new PriorityQueue<>(Comparator.comparingLong(a -> a[0])); + dist[0] = 1; + pq.add(new long[] {1, 0}); + int[] dx = {1, 0, -1, 0}; + int[] dy = {0, 1, 0, -1}; + while (!pq.isEmpty()) { + long[] top = pq.poll(); + int state = (int) top[1]; + if (top[0] > dist[state]) { + continue; + } + int parity = state & 1; + int cell = state >> 1; + int i = cell / n; + int j = cell % n; + if (i == m - 1 && j == n - 1) { + return top[0]; + } + int np = parity ^ 1; + // wait + long wait = top[0] + penalty[i][j]; + int ws = (cell << 1) | np; + if (wait < dist[ws]) { + dist[ws] = wait; + pq.add(new long[] {wait, ws}); + } + for (int d = 0; d < 4; d++) { + int x = i + dx[d]; + int y = j + dy[d]; + if (x < 0 || y < 0 || x >= m || y >= n) { + continue; + } + // right/down + boolean forward = d < 2; + // parity 0: next action is odd-numbered + boolean follows = (parity == 0) == forward; + long c = top[0] + (long) (x + 1) * (y + 1) + (follows ? 0 : penalty[i][j]); + int ns = ((x * n + y) << 1) | np; + if (c < dist[ns]) { + dist[ns] = c; + pq.add(new long[] {c, ns}); + } + } + } + return -1; + } +} diff --git a/src/main/java/g4001_4100/s4003_minimum_cost_path_with_alternating_directions_iii/readme.md b/src/main/java/g4001_4100/s4003_minimum_cost_path_with_alternating_directions_iii/readme.md new file mode 100644 index 000000000..a1ca2230f --- /dev/null +++ b/src/main/java/g4001_4100/s4003_minimum_cost_path_with_alternating_directions_iii/readme.md @@ -0,0 +1,82 @@ +4003\. Minimum Cost Path with Alternating Directions III + +Hard + +You are given two integers `m` and `n` representing the number of rows and columns of a grid. Your goal is to reach cell `(m - 1, n - 1)`. You are also given a 2D integer array `penalty`. + +The cost to enter cell `(i, j)` is `(i + 1) * (j + 1)`. + +You begin at cell `(0, 0)` and initially pay its entrance cost. Actions performed after entering `(0, 0)` are numbered starting from 1. + +On each action, you may move to an **adjacent** cell or wait in the current cell. A move follows the parity rule if: + +* On an **odd-numbered** action, you move **right** or **down**. +* On an **even-numbered** action, you move **left** or **up**. + +The cost of an action is determined as follows: + +* If you move according to the parity rule, pay only the entrance cost of the destination cell. +* If you move in a direction that **violates** the parity rule, pay the entrance cost of the destination cell plus `penalty[i][j]`, where `(i, j)` is the cell you move from. +* If you **wait** in cell `(i, j)`, pay `penalty[i][j]`. + +After every move or wait, the action number increases by 1. Therefore, the required parity alternates after every action, regardless of whether a penalty was paid. + +Return the **minimum** total cost required to reach `(m - 1, n - 1)`. + +OriginalJava**Example 1:** + +**Input:** m = 2, n = 2, penalty = [[5,3],[1,4]] + +**Output:** 8 + +**Explanation:** + +The optimal path is: + +* Start at cell `(0, 0)` with entry cost `(0 + 1) * (0 + 1) = 1`. +* **Move 1**: Move down to cell `(1, 0)` with entry cost `(1 + 1) * (0 + 1) = 2`. +* **Move 2**: Move right to cell `(1, 1)` with entry cost `(1 + 1) * (1 + 1) = 4` and an extra cost of `penalty[1][0] = 1` for violating the even parity rule. + +Thus, the total cost is `1 + 2 + 4 + 1 = 8`. + +**Example 2:** + +**Input:** m = 2, n = 2, penalty = [[0,7],[3,2]] + +**Output:** 7 + +**Explanation:** + +The optimal path is: + +* Start at cell `(0, 0)` with entry cost `(0 + 1) * (0 + 1) = 1`. +* **Move 1**: Wait at cell `(0, 0)` with an extra cost of `penalty[0][0] = 0` to flip to even parity. +* **Move 2**: Move right to cell `(0, 1)` with entry cost `(0 + 1) * (1 + 1) = 2` and an extra cost of `penalty[0][0] = 0` for violating the even parity rule. +* **Move 3**: Move down to cell `(1, 1)` with entry cost `(1 + 1) * (1 + 1) = 4`. + +Thus, the total cost is `1 + 0 + 2 + 0 + 4 = 7`. + +**Example 3:** + +**Input:** m = 2, n = 3, penalty = [[8,0,9],[7,4,1]] + +**Output:** 12 + +**Explanation:** + +The optimal path is: + +* Start at cell `(0, 0)` with entry cost `(0 + 1) * (0 + 1) = 1`. +* **Move 1**: Move right to cell `(0, 1)` with entry cost `(0 + 1) * (1 + 1) = 2`. +* **Move 2**: Move right to cell `(0, 2)` with entry cost `(0 + 1) * (2 + 1) = 3` and an extra cost of `penalty[0][1] = 0` for violating the even parity rule. +* **Move 3**: Move down to cell `(1, 2)` with entry cost `(1 + 1) * (2 + 1) = 6`. + +Thus, the total cost is `1 + 2 + 3 + 0 + 6 = 12`. + +**Constraints:** + +* 1 <= m, n <= 105 +* 2 <= m * n <= 105 +* `penalty.length == m` +* `penalty[i].length == n` +* 0 <= penalty[i][j] <= 105 \ No newline at end of file diff --git a/src/main/java/g4001_4100/s4006_count_valid_prefixes/Solution.java b/src/main/java/g4001_4100/s4006_count_valid_prefixes/Solution.java new file mode 100644 index 000000000..14948cb29 --- /dev/null +++ b/src/main/java/g4001_4100/s4006_count_valid_prefixes/Solution.java @@ -0,0 +1,25 @@ +package g4001_4100.s4006_count_valid_prefixes; + +// #Easy #String #Counting #Mid_Level #Biweekly_Contest_188 +// #2026_11_17_Time_2_ms_(55.11%)_Space_43.18_MB_(90.05%) + +public class Solution { + public int countValidPrefixes(String s) { + int one = 0; + int zero = 0; + int ans = 0; + + for (char c : s.toCharArray()) { + if (c == '1') { + one++; + } else { + zero++; + } + + if (Math.abs(one - zero) <= 1) { + ans++; + } + } + return ans; + } +} diff --git a/src/main/java/g4001_4100/s4006_count_valid_prefixes/readme.md b/src/main/java/g4001_4100/s4006_count_valid_prefixes/readme.md new file mode 100644 index 000000000..337b0288f --- /dev/null +++ b/src/main/java/g4001_4100/s4006_count_valid_prefixes/readme.md @@ -0,0 +1,42 @@ +4006\. Count Valid Prefixes + +Easy + +You are given a binary string `s`. + +A prefix of `s` is considered **valid** if its characters can be rearranged to form an **alternating** string. + +Return the number of valid prefixes of `s`. + +A string is considered **alternating** if no two adjacent characters are equal. + +OriginalJava**Example 1:** + +**Input:** s = "00101" + +**Output:** 3 + +**Explanation:** + +The valid prefixes are: + +* `"0"`: It is already an alternating string. +* `"001"`: It can be rearranged into `"010"`, which is an alternating string. +* `"00101"`: It can be rearranged into `"01010"`, which is an alternating string. + +Thus, the answer is 3. + +**Example 2:** + +**Input:** s = "101" + +**Output:** 3 + +**Explanation:** + +All prefixes of `s = "101"` are already alternating strings. Thus, the answer is 3. + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` consists only of `'0'` and `'1'`. \ No newline at end of file diff --git a/src/main/java/g4001_4100/s4007_widest_possible_fence/Solution.java b/src/main/java/g4001_4100/s4007_widest_possible_fence/Solution.java new file mode 100644 index 000000000..8894e98a8 --- /dev/null +++ b/src/main/java/g4001_4100/s4007_widest_possible_fence/Solution.java @@ -0,0 +1,48 @@ +package g4001_4100.s4007_widest_possible_fence; + +// #Hard #Array #Hash_Table #Counting #Enumeration #Senior #Biweekly_Contest_188 +// #2026_11_17_Time_214_ms_(100.00%)_Space_240.96_MB_(90.41%) + +import java.util.HashMap; +import java.util.Map; + +public class Solution { + public int maximumWidth(int[] planks) { + Map freqMap = new HashMap<>(); + for (int plank : planks) { + freqMap.merge(plank, 1, Integer::sum); + } + int n = freqMap.size(); + int i = 0; + int[] nums = new int[n]; + int[] freq = new int[n]; + for (Map.Entry entry : freqMap.entrySet()) { + nums[i] = entry.getKey(); + freq[i++] = entry.getValue(); + } + return getMax(n, nums, freq); + } + + private static int getMax(int n, int[] nums, int[] freq) { + Map fence = new HashMap<>(n * n); + int max = 1; + for (int right = 0; right < n; ++right) { + int curr = nums[right]; + int count = freq[right]; + max = Math.max(max, fence.merge(curr, count, Integer::sum)); + if (count > 1) { + max = Math.max(max, fence.merge(curr << 1, count >> 1, Integer::sum)); + } + for (int left = right + 1; left < n; ++left) { + max = + Math.max( + max, + fence.merge( + curr + nums[left], + Math.min(count, freq[left]), + Integer::sum)); + } + } + return max; + } +} diff --git a/src/main/java/g4001_4100/s4007_widest_possible_fence/readme.md b/src/main/java/g4001_4100/s4007_widest_possible_fence/readme.md new file mode 100644 index 000000000..1fce09468 --- /dev/null +++ b/src/main/java/g4001_4100/s4007_widest_possible_fence/readme.md @@ -0,0 +1,45 @@ +4007\. Widest Possible Fence + +Hard + +You are given an integer array `planks`, where `planks[i]` represents the height of the ith wooden plank. Each plank has a width of 1 unit. + +You want to build a fence consisting of planks that all have the **same** height. + +You may either use a plank as is, or combine **exactly** two distinct original planks into a single plank whose height **equals** the sum of their heights. Each original plank can be used **at most** once, and not all original planks need to be used. + +Return the **maximum possible width** of the fence that can be built. + +OriginalJava**Example 1:** + +**Input:** planks = [1,3,2,5,7,5,4,2,1] + +**Output:** 4 + +**Explanation:** + +We can have four planks of height 5. + +* `planks[3] = 5` +* `planks[5] = 5` +* `planks[0] + planks[6] = 1 + 4 = 5` +* `planks[1] + planks[2] = 3 + 2 = 5` + +Hence, the maximum width is 4. + +**Example 2:** + +**Input:** planks = [2,3,7] + +**Output:** 1 + +**Explanation:** + +* It is impossible to form two planks of the same height, even after combining two distinct original planks. +* Since not all original planks need to be used, we can choose any one plank as the fence. +* Therefore, the maximum possible width is 1. + +**Constraints:** + +* `1 <= planks.length <= 1000` +* 1 <= planks[i] <= 109 \ No newline at end of file diff --git a/src/main/java/g4001_4100/s4008_minimum_initial_strength_to_defeat_all_monsters/Solution.java b/src/main/java/g4001_4100/s4008_minimum_initial_strength_to_defeat_all_monsters/Solution.java new file mode 100644 index 000000000..55a0060b3 --- /dev/null +++ b/src/main/java/g4001_4100/s4008_minimum_initial_strength_to_defeat_all_monsters/Solution.java @@ -0,0 +1,31 @@ +package g4001_4100.s4008_minimum_initial_strength_to_defeat_all_monsters; + +// #Medium #Array #Greedy #Binary_Search #Prefix_Sum #Staff #Biweekly_Contest_188 +// #2026_11_17_Time_3_ms_(97.92%)_Space_161.18_MB_(66.67%) + +public class Solution { + public long minInitialStrength(int[] monsters, int[][] boosts) { + int n = monsters.length; + long[] diff = new long[n]; + for (int[] boost : boosts) { + int l = boost[0]; + int r = boost[1]; + int v = boost[2]; + diff[r] += v; + if (l > 0) { + diff[l - 1] -= v; + } + } + long res = 0; + long bonus = 0; + for (int i = n - 1; i >= 0; i--) { + bonus += diff[i]; + if (res > 0) { + res += monsters[i]; + } else { + res = Math.max(0L, monsters[i] - bonus); + } + } + return res; + } +} diff --git a/src/main/java/g4001_4100/s4008_minimum_initial_strength_to_defeat_all_monsters/readme.md b/src/main/java/g4001_4100/s4008_minimum_initial_strength_to_defeat_all_monsters/readme.md new file mode 100644 index 000000000..4d9dc3b57 --- /dev/null +++ b/src/main/java/g4001_4100/s4008_minimum_initial_strength_to_defeat_all_monsters/readme.md @@ -0,0 +1,60 @@ +4008\. Minimum Initial Strength to Defeat All Monsters + +Medium + +You are given an integer array `monsters`, where `monsters[i]` represents the strength of the ith monster. + +You are also given a 2D integer array `boosts`, where boosts[i] = [li, ri, vi] indicates that vi is added to your **temporary bonus** while fighting any monster whose index lies in [li, ri]. Boost ranges may overlap, and the values of all applicable boosts are added together. + +You start with a **non-negative** initial strength and fight the monsters from left to right. + +For each monster at index `i`: + +* Let `bonus` be the **sum** of the values of all boosts that apply to monster `i`. +* You can defeat the monster only if your current strength plus `bonus` is **at least** `monsters[i]`. +* After defeating the monster, only your current strength decreases by `monsters[i]`. If it becomes **negative**, it is set to 0. + +Return the **minimum** initial strength required to defeat all monsters. + +Note: The temporary bonus is used only to determine whether the current monster can be defeated. It does not otherwise change your current strength. + +OriginalJava**Example 1:** + +**Input:** monsters = [5,10,15], boosts = [[1,1,10]] + +**Output:** 30 + +**Explanation:** + +Let's start with an initial strength of 30. + +* `monsters[0] = 5`: At index 0, the bonus is 0. Since `30 + 0 >= 5`, this monster can be defeated. The strength becomes `30 - 5 = 25`. +* `monsters[1] = 10`: At index 1, the bonus is 10. Since `25 + 10 >= 10`, this monster can be defeated. The strength becomes `25 - 10 = 15`. +* `monsters[2] = 15`: At index 2, the bonus is 0. Since `15 + 0 >= 15`, this monster can be defeated. The strength becomes `15 - 15 = 0`. + +Thus, the minimum initial strength required is 30. + +**Example 2:** + +**Input:** monsters = [5,10,15], boosts = [[1,2,10],[1,2,5]] + +**Output:** 5 + +**Explanation:** + +Let's start with an initial strength of 5. + +* `monsters[0] = 5`: The bonus is 0. Since `5 + 0 >= 5`, the monster can be defeated. The strength becomes `5 - 5 = 0`. +* `monsters[1] = 10`: The two overlapping boosts provide `bonus = 10 + 5 = 15`. Since `0 + 15 >= 10`, the monster can be defeated. The strength remains 0. +* `monsters[2] = 15`: The two overlapping boosts again provide `bonus = 15`. Since `0 + 15 >= 15`, the monster can be defeated. The strength remains 0. + +Thus, the minimum initial strength required is 5. + +**Constraints:** + +* 1 <= monsters.length <= 5 * 104 +* 1 <= monsters[i] <= 109 +* 0 <= boosts.length <= 5 * 104 +* boosts[i] == [li, ri, vi] +* 0 <= li <= ri < monsters.length +* 1 <= vi <= 109 \ No newline at end of file diff --git a/src/main/java/g4001_4100/s4009_minimum_possible_maximum_waiting_time/Solution.java b/src/main/java/g4001_4100/s4009_minimum_possible_maximum_waiting_time/Solution.java new file mode 100644 index 000000000..23fec55e6 --- /dev/null +++ b/src/main/java/g4001_4100/s4009_minimum_possible_maximum_waiting_time/Solution.java @@ -0,0 +1,60 @@ +package g4001_4100.s4009_minimum_possible_maximum_waiting_time; + +public class Solution { + public int minMaxWaitingTime(int[] demand, int[] fuel) { + int result = solve(0, fuel[0], fuel[1], 0, 0, demand, new java.util.HashMap<>()); + return (result >>> 5) == 0 ? -1 : result & 31; + } + + private int solve( + int index, + int fuel0, + int fuel1, + int busy0, + int busy1, + int[] demand, + java.util.HashMap memo) { + if (index == demand.length) { + return 0; + } + int key = (index << 22) | (fuel0 << 16) | (fuel1 << 10) | (busy0 << 5) | busy1; + Integer cached = memo.get(key); + if (cached != null) { + return cached; + } + int best = 0; + int required = demand[index]; + if (fuel0 >= required) { + int wait = busy0; + int child = + solve( + index + 1, + fuel0 - required, + fuel1, + required, + Math.max(0, busy1 - wait), + demand, + memo); + best = (1 + (child >>> 5)) * 32 + Math.max(wait, child & 31); + } + if (fuel1 >= required) { + int wait = busy1; + int child = + solve( + index + 1, + fuel0, + fuel1 - required, + Math.max(0, busy0 - wait), + required, + demand, + memo); + int candidate = (1 + (child >>> 5)) * 32 + Math.max(wait, child & 31); + if ((candidate >>> 5) > (best >>> 5) + || ((candidate >>> 5) == (best >>> 5) && (candidate & 31) < (best & 31))) { + best = candidate; + } + } + memo.put(key, best); + return best; + } +} diff --git a/src/main/java/g4001_4100/s4009_minimum_possible_maximum_waiting_time/readme.md b/src/main/java/g4001_4100/s4009_minimum_possible_maximum_waiting_time/readme.md new file mode 100644 index 000000000..1b8e082f1 --- /dev/null +++ b/src/main/java/g4001_4100/s4009_minimum_possible_maximum_waiting_time/readme.md @@ -0,0 +1,74 @@ +4009\. Minimum Possible Maximum Waiting Time + +Hard + +You are given an integer array `demand`, where `demand[i]` is the amount of fuel required by the ith car. + +You are also given an integer array `fuel` of length 2. There are **exactly** two fuel dispensers, numbered 0 and 1, where `fuel[j]` is the initial amount of fuel available in dispenser `j`. + +Cars are allowed to start refueling in **increasing** index order. Car 0 becomes allowed at time 0, and for each `i > 0`, car `i` becomes allowed **exactly** when car `i - 1` starts refueling. + +The refueling process follows these rules: + +* Each dispenser can serve **at most** one car at a time. +* When a car becomes allowed, you must choose a dispenser with **at least** `demand[i]` fuel remaining. If both dispensers have enough fuel remaining, you may choose **either** of them, regardless of when they become free. +* The car waits until the chosen dispenser becomes free and starts refueling **immediately**. It cannot switch dispensers or intentionally wait after the chosen dispenser becomes free. +* When a car starts refueling, the remaining fuel in the chosen dispenser decreases by `demand[i]`, and the dispenser remains occupied for `demand[i]` seconds. +* Once started, refueling cannot be interrupted. +* If neither dispenser has at least `demand[i]` fuel remaining when car `i` becomes allowed, the process terminates and no further cars can be served. + +The **waiting time** of a car is the time between when it becomes allowed to start refueling and when it actually starts. + +Return the **minimum** possible value of the **maximum** waiting time among all served cars over all assignments that **maximize** the number of served cars. If no car can be served, return -1. + +OriginalJava**Example 1:** + +**Input:** demand = [6,8,4,6,5], fuel = [16,13] + +**Output:** 6 + +**Explanation:** + +The following assignment serves all five cars: + +| Car | Becomes allowed at | Starts refueling at | Dispenser used | Remaining fuel before start
(dispenser 0, dispenser 1) | Waiting time | +| --- | --- | --- | --- | --- | --- | +| 0 | 0 | 0 | 0 | (16, 13) | 0 | +| 1 | 0 | 0 | 1 | (10, 13) | 0 | +| 2 | 0 | 6 | 0 | (10, 5) | 6 | +| 3 | 6 | 10 | 0 | (6, 5) | 4 | +| 4 | 10 | 10 | 1 | (0, 5) | 0 | + +Thus, all five cars are served, and the maximum waiting time is 6. + +To serve all five cars, dispenser 0 must serve the cars with demands 6, 4, and 6, while dispenser 1 must serve the cars with demands 8 and 5. Therefore, car 2 must wait until time 6 for dispenser 0 to become free, so no assignment serving all five cars can have a maximum waiting time less than 6. + +**Example 2:** + +**Input:** demand = [10,15], fuel = [12,17] + +**Output:** 0 + +**Explanation:** + +* At time 0, Car 0 becomes allowed and starts refuelling using dispenser 0. +* Car 1 becomes allowed at time 0 (when Car 0 starts) and immediately starts refuelling using dispenser 1. +* Both cars start without waiting, so the maximum waiting time is 0. + +**Example 3:** + +**Input:** demand = [10,5], fuel = [8,8] + +**Output:** \-1 + +**Explanation:** + +* At time 0, Car 0 becomes allowed. However, neither dispenser has enough fuel to serve it, so the process terminates immediately. +* No car is served, so the answer is -1. + +**Constraints:** + +* `1 <= demand.length <= 50` +* `1 <= demand[i] <= 20` +* `fuel.length == 2` +* `1 <= fuel[i] <= 50` \ No newline at end of file diff --git a/src/test/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/SolutionTest.java b/src/test/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/SolutionTest.java new file mode 100644 index 000000000..77f9cd410 --- /dev/null +++ b/src/test/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3993_maximum_value_of_an_alternating_sequence; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maximumValue() { + assertThat(new Solution().maximumValue(4, 3, 5), equalTo(12L)); + } + + @Test + void maximumValue2() { + assertThat(new Solution().maximumValue(2, 4, 3), equalTo(7L)); + } + + @Test + void maximumValue3() { + assertThat(new Solution().maximumValue(1, 5, 3), equalTo(5L)); + } +} diff --git a/src/test/java/g3901_4000/s3994_minimum_adjacent_swaps_to_partition_array/SolutionTest.java b/src/test/java/g3901_4000/s3994_minimum_adjacent_swaps_to_partition_array/SolutionTest.java new file mode 100644 index 000000000..90f4f84ee --- /dev/null +++ b/src/test/java/g3901_4000/s3994_minimum_adjacent_swaps_to_partition_array/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3994_minimum_adjacent_swaps_to_partition_array; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minAdjacentSwaps() { + assertThat(new Solution().minAdjacentSwaps(new int[] {1, 3, 2, 4, 5, 6}, 3, 4), equalTo(1)); + } + + @Test + void minAdjacentSwaps2() { + assertThat(new Solution().minAdjacentSwaps(new int[] {9, 7, 5, 3}, 4, 8), equalTo(5)); + } + + @Test + void minAdjacentSwaps3() { + assertThat(new Solution().minAdjacentSwaps(new int[] {3, 7, 5, 9}, 4, 8), equalTo(0)); + } +} diff --git a/src/test/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/SolutionTest.java b/src/test/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/SolutionTest.java new file mode 100644 index 000000000..18980758c --- /dev/null +++ b/src/test/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/SolutionTest.java @@ -0,0 +1,43 @@ +package g3901_4000.s3995_minimum_cost_to_convert_string_iii; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.util.List; +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minCost() { + assertThat( + new Solution() + .minCost( + "hello", + "world", + List.of(List.of("he", "wo"), List.of("llo", "rld")), + new int[] {3, 4}), + equalTo(7)); + } + + @Test + void minCost2() { + assertThat( + new Solution().minCost("cat", "dog", List.of(List.of("c*t", "dog")), new int[] {2}), + equalTo(3)); + } + + @Test + void minCost3() { + assertThat( + new Solution() + .minCost("test", "next", List.of(List.of("*e*t", "next")), new int[] {4}), + equalTo(6)); + } + + @Test + void minCost4() { + assertThat( + new Solution().minCost("ab", "bc", List.of(List.of("a*", "bd")), new int[] {9}), + equalTo(-1)); + } +} diff --git a/src/test/java/g3901_4000/s3996_even_number_of_knight_moves/SolutionTest.java b/src/test/java/g3901_4000/s3996_even_number_of_knight_moves/SolutionTest.java new file mode 100644 index 000000000..453b52e1c --- /dev/null +++ b/src/test/java/g3901_4000/s3996_even_number_of_knight_moves/SolutionTest.java @@ -0,0 +1,18 @@ +package g3901_4000.s3996_even_number_of_knight_moves; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void canReach() { + assertThat(new Solution().canReach(new int[] {1, 1}, new int[] {2, 2}), equalTo(true)); + } + + @Test + void canReach2() { + assertThat(new Solution().canReach(new int[] {4, 5}, new int[] {6, 6}), equalTo(false)); + } +} diff --git a/src/test/java/g3901_4000/s3997_count_dominant_nodes_in_a_binary_tree/SolutionTest.java b/src/test/java/g3901_4000/s3997_count_dominant_nodes_in_a_binary_tree/SolutionTest.java new file mode 100644 index 000000000..a57286dec --- /dev/null +++ b/src/test/java/g3901_4000/s3997_count_dominant_nodes_in_a_binary_tree/SolutionTest.java @@ -0,0 +1,22 @@ +package g3901_4000.s3997_count_dominant_nodes_in_a_binary_tree; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import com_github_leetcode.TreeNode; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void countDominantNodes() { + TreeNode root = TreeNode.create(Arrays.asList(5, 3, 8, 2, 4, 7, 1)); + assertThat(new Solution().countDominantNodes(root), equalTo(5)); + } + + @Test + void countDominantNodes2() { + TreeNode root = TreeNode.create(Arrays.asList(1, 2, 3, 1, 2)); + assertThat(new Solution().countDominantNodes(root), equalTo(4)); + } +} diff --git a/src/test/java/g3901_4000/s3998_transform_binary_string_using_subsequence_sort/SolutionTest.java b/src/test/java/g3901_4000/s3998_transform_binary_string_using_subsequence_sort/SolutionTest.java new file mode 100644 index 000000000..0de30d9d8 --- /dev/null +++ b/src/test/java/g3901_4000/s3998_transform_binary_string_using_subsequence_sort/SolutionTest.java @@ -0,0 +1,29 @@ +package g3901_4000.s3998_transform_binary_string_using_subsequence_sort; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void transformStr() { + assertThat( + new Solution().transformStr("101", new String[] {"1?1", "0?1", "0?0"}), + equalTo(new boolean[] {true, true, false})); + } + + @Test + void transformStr2() { + assertThat( + new Solution().transformStr("1100", new String[] {"0011", "11?1", "1?1?"}), + equalTo(new boolean[] {true, false, true})); + } + + @Test + void transformStr3() { + assertThat( + new Solution().transformStr("1010", new String[] {"0011"}), + equalTo(new boolean[] {true})); + } +} diff --git a/src/test/java/g3901_4000/s3999_minimum_number_of_string_groups_through_transformations/SolutionTest.java b/src/test/java/g3901_4000/s3999_minimum_number_of_string_groups_through_transformations/SolutionTest.java new file mode 100644 index 000000000..de26ac844 --- /dev/null +++ b/src/test/java/g3901_4000/s3999_minimum_number_of_string_groups_through_transformations/SolutionTest.java @@ -0,0 +1,30 @@ +package g3901_4000.s3999_minimum_number_of_string_groups_through_transformations; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minimumGroups() { + assertThat(new Solution().minimumGroups(new String[] {"ntgwz", "zwntg"}), equalTo(1)); + } + + @Test + void minimumGroups2() { + assertThat( + new Solution() + .minimumGroups(new String[] {"abc", "cab", "bac", "acb", "bca", "cba"}), + equalTo(3)); + } + + @Test + void minimumGroups3() { + assertThat( + new Solution() + .minimumGroups( + new String[] {"leet", "abb", "bab", "deed", "edde", "code", "bba"}), + equalTo(5)); + } +} diff --git a/src/test/java/g3901_4000/s4000_largest_integer_with_given_digit_sum/SolutionTest.java b/src/test/java/g3901_4000/s4000_largest_integer_with_given_digit_sum/SolutionTest.java new file mode 100644 index 000000000..4722c38ff --- /dev/null +++ b/src/test/java/g3901_4000/s4000_largest_integer_with_given_digit_sum/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s4000_largest_integer_with_given_digit_sum; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void largestInteger() { + assertThat(new Solution().largestInteger(2, 9), equalTo(90)); + } + + @Test + void largestInteger2() { + assertThat(new Solution().largestInteger(2, 19), equalTo(-1)); + } + + @Test + void largestInteger3() { + assertThat(new Solution().largestInteger(5, 0), equalTo(0)); + } +} diff --git a/src/test/java/g4001_4100/s4001_aggregate_two_time_series/SolutionTest.java b/src/test/java/g4001_4100/s4001_aggregate_two_time_series/SolutionTest.java new file mode 100644 index 000000000..c4300091c --- /dev/null +++ b/src/test/java/g4001_4100/s4001_aggregate_two_time_series/SolutionTest.java @@ -0,0 +1,34 @@ +package g4001_4100.s4001_aggregate_two_time_series; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import com_github_leetcode.ArrayUtils; +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void aggregateTimeSeries() { + assertThat( + new Solution() + .aggregateTimeSeries( + new int[][] {{1, 3}, {4, 1}}, new int[][] {{2, 2}, {5, 2}}), + equalTo(ArrayUtils.getLists(new int[][] {{1, 5}, {2, 3}, {4, 3}, {5, 2}}))); + } + + @Test + void aggregateTimeSeries2() { + assertThat( + new Solution() + .aggregateTimeSeries(new int[][] {{1, 5}, {3, 1}}, new int[][] {{2, 2}}), + equalTo(ArrayUtils.getLists(new int[][] {{1, 7}, {2, 3}, {3, 1}}))); + } + + @Test + void aggregateTimeSeries3() { + assertThat( + new Solution() + .aggregateTimeSeries(new int[][] {{1, 5}}, new int[][] {{1000000000, 2}}), + equalTo(ArrayUtils.getLists(new int[][] {{1, 7}, {1000000000, 2}}))); + } +} diff --git a/src/test/java/g4001_4100/s4002_count_valid_sequences/SolutionTest.java b/src/test/java/g4001_4100/s4002_count_valid_sequences/SolutionTest.java new file mode 100644 index 000000000..b61e0cfef --- /dev/null +++ b/src/test/java/g4001_4100/s4002_count_valid_sequences/SolutionTest.java @@ -0,0 +1,23 @@ +package g4001_4100.s4002_count_valid_sequences; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void countValidSequences() { + assertThat(new Solution().countValidSequences(5, 3), equalTo(3)); + } + + @Test + void countValidSequences2() { + assertThat(new Solution().countValidSequences(3, 2), equalTo(2)); + } + + @Test + void countValidSequences3() { + assertThat(new Solution().countValidSequences(5, 5), equalTo(0)); + } +} diff --git a/src/test/java/g4001_4100/s4003_minimum_cost_path_with_alternating_directions_iii/SolutionTest.java b/src/test/java/g4001_4100/s4003_minimum_cost_path_with_alternating_directions_iii/SolutionTest.java new file mode 100644 index 000000000..8cfb5c7c3 --- /dev/null +++ b/src/test/java/g4001_4100/s4003_minimum_cost_path_with_alternating_directions_iii/SolutionTest.java @@ -0,0 +1,23 @@ +package g4001_4100.s4003_minimum_cost_path_with_alternating_directions_iii; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minCost() { + assertThat(new Solution().minCost(2, 2, new int[][] {{5, 3}, {1, 4}}), equalTo(8L)); + } + + @Test + void minCost2() { + assertThat(new Solution().minCost(2, 2, new int[][] {{0, 7}, {3, 2}}), equalTo(7L)); + } + + @Test + void minCost3() { + assertThat(new Solution().minCost(2, 3, new int[][] {{8, 0, 9}, {7, 4, 1}}), equalTo(12L)); + } +} diff --git a/src/test/java/g4001_4100/s4006_count_valid_prefixes/SolutionTest.java b/src/test/java/g4001_4100/s4006_count_valid_prefixes/SolutionTest.java new file mode 100644 index 000000000..47fe3ea69 --- /dev/null +++ b/src/test/java/g4001_4100/s4006_count_valid_prefixes/SolutionTest.java @@ -0,0 +1,18 @@ +package g4001_4100.s4006_count_valid_prefixes; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void countValidPrefixes() { + assertThat(new Solution().countValidPrefixes("00101"), equalTo(3)); + } + + @Test + void countValidPrefixes2() { + assertThat(new Solution().countValidPrefixes("101"), equalTo(3)); + } +} diff --git a/src/test/java/g4001_4100/s4007_widest_possible_fence/SolutionTest.java b/src/test/java/g4001_4100/s4007_widest_possible_fence/SolutionTest.java new file mode 100644 index 000000000..9f7b1c392 --- /dev/null +++ b/src/test/java/g4001_4100/s4007_widest_possible_fence/SolutionTest.java @@ -0,0 +1,18 @@ +package g4001_4100.s4007_widest_possible_fence; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maximumWidth() { + assertThat(new Solution().maximumWidth(new int[] {1, 3, 2, 5, 7, 5, 4, 2, 1}), equalTo(4)); + } + + @Test + void maximumWidth2() { + assertThat(new Solution().maximumWidth(new int[] {2, 3, 7}), equalTo(1)); + } +} diff --git a/src/test/java/g4001_4100/s4008_minimum_initial_strength_to_defeat_all_monsters/SolutionTest.java b/src/test/java/g4001_4100/s4008_minimum_initial_strength_to_defeat_all_monsters/SolutionTest.java new file mode 100644 index 000000000..fc50b2154 --- /dev/null +++ b/src/test/java/g4001_4100/s4008_minimum_initial_strength_to_defeat_all_monsters/SolutionTest.java @@ -0,0 +1,24 @@ +package g4001_4100.s4008_minimum_initial_strength_to_defeat_all_monsters; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minInitialStrength() { + assertThat( + new Solution().minInitialStrength(new int[] {5, 10, 15}, new int[][] {{1, 1, 10}}), + equalTo(30L)); + } + + @Test + void minInitialStrength2() { + assertThat( + new Solution() + .minInitialStrength( + new int[] {5, 10, 15}, new int[][] {{1, 2, 10}, {1, 2, 5}}), + equalTo(5L)); + } +} diff --git a/src/test/java/g4001_4100/s4009_minimum_possible_maximum_waiting_time/SolutionTest.java b/src/test/java/g4001_4100/s4009_minimum_possible_maximum_waiting_time/SolutionTest.java new file mode 100644 index 000000000..7d2c1ad8b --- /dev/null +++ b/src/test/java/g4001_4100/s4009_minimum_possible_maximum_waiting_time/SolutionTest.java @@ -0,0 +1,28 @@ +package g4001_4100.s4009_minimum_possible_maximum_waiting_time; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minMaxWaitingTime() { + assertThat( + new Solution().minMaxWaitingTime(new int[] {6, 8, 4, 6, 5}, new int[] {16, 13}), + equalTo(6)); + } + + @Test + void minMaxWaitingTime2() { + assertThat( + new Solution().minMaxWaitingTime(new int[] {10, 15}, new int[] {12, 17}), + equalTo(0)); + } + + @Test + void minMaxWaitingTime3() { + assertThat( + new Solution().minMaxWaitingTime(new int[] {10, 5}, new int[] {8, 8}), equalTo(-1)); + } +} From 233206b57e6740fb1449f73dbff715f46fc3c47b Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 17 Nov 2026 22:21:22 +0200 Subject: [PATCH 2/4] Refactor countValidPrefixes method formatting Adjust the formatting and remove unnecessary lines. --- .../java/g4001_4100/s4006_count_valid_prefixes/Solution.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/g4001_4100/s4006_count_valid_prefixes/Solution.java b/src/main/java/g4001_4100/s4006_count_valid_prefixes/Solution.java index 14948cb29..31b02d8ec 100644 --- a/src/main/java/g4001_4100/s4006_count_valid_prefixes/Solution.java +++ b/src/main/java/g4001_4100/s4006_count_valid_prefixes/Solution.java @@ -8,14 +8,12 @@ public int countValidPrefixes(String s) { int one = 0; int zero = 0; int ans = 0; - for (char c : s.toCharArray()) { if (c == '1') { one++; } else { zero++; } - if (Math.abs(one - zero) <= 1) { ans++; } From 31b2a6043a923b056c2480cec776282da80a7308 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 17 Nov 2026 22:26:06 +0200 Subject: [PATCH 3/4] Fixed sonar --- .../Solution.java | 2 +- .../s3995_minimum_cost_to_convert_string_iii/Solution.java | 6 ++---- .../g4001_4100/s4002_count_valid_sequences/Solution.java | 2 +- .../g4001_4100/s4007_widest_possible_fence/Solution.java | 2 +- 4 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/main/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/Solution.java b/src/main/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/Solution.java index a38805242..40875b0c7 100644 --- a/src/main/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/Solution.java +++ b/src/main/java/g3901_4000/s3993_maximum_value_of_an_alternating_sequence/Solution.java @@ -8,6 +8,6 @@ public long maximumValue(int n, int s, int m) { if (n == 1) { return s; } - return (long) s + (long) (n / 2) * (m - 1) + 1; + return s + (long) (n / 2) * (m - 1) + 1; } } diff --git a/src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/Solution.java b/src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/Solution.java index 198c7d95b..8054b7688 100644 --- a/src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/Solution.java +++ b/src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/Solution.java @@ -42,10 +42,8 @@ public int minCost(String source, String target, List> rules, int[] if (dp[i] == in) { continue; } - if (source.charAt(i) == target.charAt(i)) { - if (dp[i] < dp[i + 1]) { - dp[i + 1] = dp[i]; - } + if (source.charAt(i) == target.charAt(i) && dp[i] < dp[i + 1]) { + dp[i + 1] = dp[i]; } for (int k = 0; k < m; k++) { int l = len[k]; diff --git a/src/main/java/g4001_4100/s4002_count_valid_sequences/Solution.java b/src/main/java/g4001_4100/s4002_count_valid_sequences/Solution.java index 64e32d19f..b084a51a3 100644 --- a/src/main/java/g4001_4100/s4002_count_valid_sequences/Solution.java +++ b/src/main/java/g4001_4100/s4002_count_valid_sequences/Solution.java @@ -27,7 +27,7 @@ private long comb(int n, int k) { res = res * (n - i + 1) % MOD; den = den * i % MOD; } - return res * power(den, MOD - 2) % MOD; + return res * power(den, MOD - 2L) % MOD; } public int countValidSequences(int n, int k) { diff --git a/src/main/java/g4001_4100/s4007_widest_possible_fence/Solution.java b/src/main/java/g4001_4100/s4007_widest_possible_fence/Solution.java index 8894e98a8..6bd6f9f9b 100644 --- a/src/main/java/g4001_4100/s4007_widest_possible_fence/Solution.java +++ b/src/main/java/g4001_4100/s4007_widest_possible_fence/Solution.java @@ -24,7 +24,7 @@ public int maximumWidth(int[] planks) { } private static int getMax(int n, int[] nums, int[] freq) { - Map fence = new HashMap<>(n * n); + Map fence = HashMap.newHashMap(n * n); int max = 1; for (int right = 0; right < n; ++right) { int curr = nums[right]; From 22a1f10b73734b7120bb70a7b12dd111db51f5b8 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 17 Nov 2026 22:35:28 +0200 Subject: [PATCH 4/4] Add suppression for Java code quality warning --- .../s3995_minimum_cost_to_convert_string_iii/Solution.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/Solution.java b/src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/Solution.java index 8054b7688..114e9d9c0 100644 --- a/src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/Solution.java +++ b/src/main/java/g3901_4000/s3995_minimum_cost_to_convert_string_iii/Solution.java @@ -6,6 +6,7 @@ import java.util.Arrays; import java.util.List; +@SuppressWarnings("java:S135") public class Solution { public int minCost(String source, String target, List> rules, int[] costs) { int n = source.length();