From 16a948d888eb7c63bec2ca6edb353ea801741f08 Mon Sep 17 00:00:00 2001 From: ThanhNIT Date: Tue, 3 Nov 2026 23:46:28 +0700 Subject: [PATCH 01/12] Added tasks 3969-3992 --- .../Solution.java | 74 ++++++++++ .../readme.md | 47 +++++++ .../Solution.java | 67 +++++++++ .../readme.md | 59 ++++++++ .../s3971_maximum_total_value/Solution.java | 63 +++++++++ .../s3971_maximum_total_value/readme.md | 67 +++++++++ .../Solution.java | 43 ++++++ .../readme.md | 68 ++++++++++ .../Solution.java | 50 +++++++ .../s3975_filter_occupied_intervals/readme.md | 42 ++++++ .../Solution.java | 21 +++ .../readme.md | 46 +++++++ .../Solution.java | 128 ++++++++++++++++++ .../readme.md | 79 +++++++++++ .../s3978_unique_middle_element/Solution.java | 18 +++ .../s3978_unique_middle_element/readme.md | 37 +++++ .../Solution.java | 17 +++ .../s3979_maximum_valid_pair_sum/readme.md | 49 +++++++ .../Solution.java | 32 +++++ .../readme.md | 50 +++++++ .../Solution.java | 112 +++++++++++++++ .../readme.md | 81 +++++++++++ .../Solution.java | 32 +++++ .../readme.md | 47 +++++++ .../Solution.java | 34 +++++ .../readme.md | 36 +++++ .../s3984_divisible_game/Solution.java | 49 +++++++ .../g3901_4000/s3984_divisible_game/readme.md | 67 +++++++++ .../Solution.java | 88 ++++++++++++ .../s3985_palindromic_subarray_sum/readme.md | 62 +++++++++ .../Solution.java | 29 ++++ .../readme.md | 37 +++++ .../Solution.java | 30 ++++ .../readme.md | 59 ++++++++ .../Solution.java | 106 +++++++++++++++ .../readme.md | 67 +++++++++ .../Solution.java | 31 +++++ .../readme.md | 53 ++++++++ .../Solution.java | 21 +++ .../readme.md | 49 +++++++ .../SolutionTest.java | 23 ++++ .../SolutionTest.java | 31 +++++ .../SolutionTest.java | 27 ++++ .../SolutionTest.java | 23 ++++ .../SolutionTest.java | 32 +++++ .../SolutionTest.java | 23 ++++ .../SolutionTest.java | 50 +++++++ .../SolutionTest.java | 23 ++++ .../SolutionTest.java | 23 ++++ .../SolutionTest.java | 23 ++++ .../SolutionTest.java | 28 ++++ .../SolutionTest.java | 23 ++++ .../SolutionTest.java | 23 ++++ .../s3984_divisible_game/SolutionTest.java | 23 ++++ .../SolutionTest.java | 33 +++++ .../SolutionTest.java | 23 ++++ .../SolutionTest.java | 23 ++++ .../SolutionTest.java | 28 ++++ .../SolutionTest.java | 25 ++++ .../SolutionTest.java | 23 ++++ 60 files changed, 2677 insertions(+) create mode 100644 src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/Solution.java create mode 100644 src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/readme.md create mode 100644 src/main/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/Solution.java create mode 100644 src/main/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/readme.md create mode 100644 src/main/java/g3901_4000/s3971_maximum_total_value/Solution.java create mode 100644 src/main/java/g3901_4000/s3971_maximum_total_value/readme.md create mode 100644 src/main/java/g3901_4000/s3974_maximum_total_sum_of_k_selected_elements/Solution.java create mode 100644 src/main/java/g3901_4000/s3974_maximum_total_sum_of_k_selected_elements/readme.md create mode 100644 src/main/java/g3901_4000/s3975_filter_occupied_intervals/Solution.java create mode 100644 src/main/java/g3901_4000/s3975_filter_occupied_intervals/readme.md create mode 100644 src/main/java/g3901_4000/s3976_maximum_subarray_sum_after_multiplier/Solution.java create mode 100644 src/main/java/g3901_4000/s3976_maximum_subarray_sum_after_multiplier/readme.md create mode 100644 src/main/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/Solution.java create mode 100644 src/main/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/readme.md create mode 100644 src/main/java/g3901_4000/s3978_unique_middle_element/Solution.java create mode 100644 src/main/java/g3901_4000/s3978_unique_middle_element/readme.md create mode 100644 src/main/java/g3901_4000/s3979_maximum_valid_pair_sum/Solution.java create mode 100644 src/main/java/g3901_4000/s3979_maximum_valid_pair_sum/readme.md create mode 100644 src/main/java/g3901_4000/s3980_minimum_operations_to_transform_binary_string/Solution.java create mode 100644 src/main/java/g3901_4000/s3980_minimum_operations_to_transform_binary_string/readme.md create mode 100644 src/main/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/Solution.java create mode 100644 src/main/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/readme.md create mode 100644 src/main/java/g3901_4000/s3982_sum_of_integers_with_maximum_digit_range/Solution.java create mode 100644 src/main/java/g3901_4000/s3982_sum_of_integers_with_maximum_digit_range/readme.md create mode 100644 src/main/java/g3901_4000/s3983_subsequence_after_one_replacement/Solution.java create mode 100644 src/main/java/g3901_4000/s3983_subsequence_after_one_replacement/readme.md create mode 100644 src/main/java/g3901_4000/s3984_divisible_game/Solution.java create mode 100644 src/main/java/g3901_4000/s3984_divisible_game/readme.md create mode 100644 src/main/java/g3901_4000/s3985_palindromic_subarray_sum/Solution.java create mode 100644 src/main/java/g3901_4000/s3985_palindromic_subarray_sum/readme.md create mode 100644 src/main/java/g3901_4000/s3986_number_of_elapsed_seconds_between_two_times/Solution.java create mode 100644 src/main/java/g3901_4000/s3986_number_of_elapsed_seconds_between_two_times/readme.md create mode 100644 src/main/java/g3901_4000/s3987_minimum_total_cost_to_process_all_elements/Solution.java create mode 100644 src/main/java/g3901_4000/s3987_minimum_total_cost_to_process_all_elements/readme.md create mode 100644 src/main/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/Solution.java create mode 100644 src/main/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/readme.md create mode 100644 src/main/java/g3901_4000/s3989_maximum_consistent_columns_in_a_grid/Solution.java create mode 100644 src/main/java/g3901_4000/s3989_maximum_consistent_columns_in_a_grid/readme.md create mode 100644 src/main/java/g3901_4000/s3992_rearrange_string_to_avoid_character_pair/Solution.java create mode 100644 src/main/java/g3901_4000/s3992_rearrange_string_to_avoid_character_pair/readme.md create mode 100644 src/test/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3971_maximum_total_value/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3974_maximum_total_sum_of_k_selected_elements/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3975_filter_occupied_intervals/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3976_maximum_subarray_sum_after_multiplier/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3978_unique_middle_element/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3979_maximum_valid_pair_sum/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3980_minimum_operations_to_transform_binary_string/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3982_sum_of_integers_with_maximum_digit_range/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3983_subsequence_after_one_replacement/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3984_divisible_game/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3985_palindromic_subarray_sum/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3986_number_of_elapsed_seconds_between_two_times/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3987_minimum_total_cost_to_process_all_elements/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3989_maximum_consistent_columns_in_a_grid/SolutionTest.java create mode 100644 src/test/java/g3901_4000/s3992_rearrange_string_to_avoid_character_pair/SolutionTest.java diff --git a/src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/Solution.java b/src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/Solution.java new file mode 100644 index 000000000..e67477989 --- /dev/null +++ b/src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/Solution.java @@ -0,0 +1,74 @@ +package g3901_4000.s3969_valid_subarrays_with_matching_sum_digits_i; + +// #Medium #Array #Hash_Table #Prefix_Sum #Sliding_Window #Enumeration #Senior #Weekly_Contest_507 +// #2026_11_03_Time_50_ms_(98.27%)_Space_46.22_MB_(95.95%) + +import java.util.ArrayList; +import java.util.List; + +public class Solution { + public int countValidSubarrays(int[] nums, int x) { + int n = nums.length; + long[] pre = new long[n + 1]; + for (int i = 0; i < n; i++) { + pre[i + 1] = pre[i] + nums[i]; + } + if (x == 0) { + return 0; + } + List interval = new ArrayList<>(); + for (long p = 1; p <= pre[n]; p *= 10) { + interval.add(new long[] {p * x, p * x + p - 1}); + } + List[] isit = new List[10]; + for (int r = 0; r < 10; r++) { + isit[r] = new ArrayList<>(); + } + long sum = 0; + for (int i = 0; i <= n; i++) { + if (i > 0) { + long k = pre[i]; + int r = (int) (((k - x) % 10 + 10) % 10); + List list = isit[r]; + for (long[] j : interval) { + long a = k - j[1]; + long b = k - j[0]; + if (b < 0) { + continue; + } + int high = upper(list, b); + int low = lower(list, a); + sum += high - low; + } + } + isit[(int) (pre[i] % 10)].add(pre[i]); + } + return (int) sum; + } + + private int lower(List list, long k) { + int l = 0; + int h = list.size(); + while (l < h) { + int m = (l + h) >>> 1; + if (list.get(m) < k) { + l = m + 1; + } else h = m; + } + return l; + } + + private int upper(List list, long k) { + int l = 0; + int h = list.size(); + while (l < h) { + int m = (l + h) >>> 1; + if (list.get(m) <= k) { + l = m + 1; + } else { + h = m; + } + } + return l; + } +} diff --git a/src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/readme.md b/src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/readme.md new file mode 100644 index 000000000..ae7b8cf82 --- /dev/null +++ b/src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/readme.md @@ -0,0 +1,47 @@ +3969\. Valid Subarrays With Matching Sum Digits I + +Medium + +You are given an integer array `nums` and an integer digit `x`. + +A non-empty subarrays `nums[l..r]` is considered **valid** if the sum of its elements satisfies both of the following conditions: + +* The first digit of the sum is equal to `x`. +* The last digit of the sum is equal to `x`. + +Return the number of valid subarrays. + +**Example 1:** + +**Input:** nums = [1,100,1], x = 1 + +**Output:** 4 + +**Explanation:** + +The valid subarrays are: + +* `nums[0..0]`: `sum = 1` +* `nums[0..1]`: `sum = 1 + 100 = 101` +* `nums[1..2]`: `sum = 100 + 1 = 101` +* `nums[2..2]`: `sum = 1` + +Thus, the answer is 4. + +**Example 2:** + +**Input:** nums = [1], x = 2 + +**Output:** 0 + +**Explanation:** + +The only subarray is `nums[0..0]` with a sum of 1, which does not satisfy the conditions. + +Thus, the answer is 0. + +**Constraints:** + +* `1 <= nums.length <= 1500` +* 1 <= nums[i] <= 109 +* `1 <= x <= 9` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/Solution.java b/src/main/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/Solution.java new file mode 100644 index 000000000..8b8b0bb1d --- /dev/null +++ b/src/main/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/Solution.java @@ -0,0 +1,67 @@ +package g3901_4000.s3970_shortest_path_with_at_most_k_consecutive_identical_characters; + +// #Medium #String #Heap_Priority_Queue #Shortest_Path #Graph_Theory #Staff #Weekly_Contest_507 +// #2026_11_03_Time_40_ms_(97.73%)_Space_198.21_MB_(98.49%) + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.PriorityQueue; + +public class Solution { + private static class Node { + long w; + int ch; + int city; + + public Node(int city, long w, int ch) { + this.city = city; + this.w = w; + this.ch = ch; + } + } + + public int shortestPath(int n, int[][] edges, String labelschars, int k) { + int[] chars = new int[n]; + char[] labels = labelschars.toCharArray(); + Arrays.fill(chars, Integer.MAX_VALUE); + List> adj = new ArrayList<>(); + for (int i = 0; i < n; i++) { + adj.add(new ArrayList<>()); + } + for (int[] edge : edges) { + adj.get(edge[0]).add(new int[] {edge[1], edge[2]}); + } + PriorityQueue pq = new PriorityQueue<>((a, b) -> Long.compare(a.w, b.w)); + pq.add(new Node(0, 0, 1)); + while (!pq.isEmpty()) { + Node nd = pq.poll(); + if (nd.ch >= chars[nd.city]) { + continue; + } + chars[nd.city] = nd.ch; + if (nd.city == n - 1) { + return (int) nd.w; + } + addNeighbors(nd, adj, labels, k, pq); + } + return -1; + } + + private void addNeighbors( + Node nd, List> adj, char[] labels, int k, PriorityQueue pq) { + for (int[] nbr : adj.get(nd.city)) { + int nextCity = nbr[0]; + int totalCh = getNextCharCount(nd.ch, labels[nd.city], labels[nextCity]); + if (nd.city != nextCity && totalCh <= k) { + long totalWeight = nd.w + nbr[1]; + + pq.add(new Node(nextCity, totalWeight, totalCh)); + } + } + } + + private int getNextCharCount(int ch, char current, char next) { + return current == next ? ch + 1 : 1; + } +} diff --git a/src/main/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/readme.md b/src/main/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/readme.md new file mode 100644 index 000000000..28bd987c3 --- /dev/null +++ b/src/main/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/readme.md @@ -0,0 +1,59 @@ +3970\. Shortest Path With At Most K Consecutive Identical Characters + +Medium + +You are given an integer `n` representing the number of nodes in a **directed weighted** graph, numbered from 0 to `n - 1`. This is represented by a 2D integer array `edges`, where edges[i] = [ui, vi, wi] represents a directed edge from node ui to node vi with weight wi. + +You are also given a string `labels` of length `n`, where `labels[i]` is the character assigned to node `i`, and an integer `k`. + +Return the **minimum** **total** edge weight of a path from node 0 to node `n - 1` such that the concatenation of the labels of the nodes along the path contains **at most** `k` **consecutive** **identical** characters. If no valid path exists, return -1. + +**Example 1:** + +**Input:** n = 3, edges = [[0,1,1],[1,2,1],[0,2,3]], labels = "aab", k = 1 + +**Output:** 3 + +**Explanation:** + +The optimal valid path from node 0 to node 2 is as follows: + +* Use `edges[2] = [0, 2, 3]` to reach node 2 with a weight wi = 3. + +The corresponding concatenation of labels is `"ab"`, which satisfies at most `k = 1` consecutive identical characters. Thus, the answer is 3. + +**Example 2:** + +**Input:** n = 3, edges = [[0,1,1],[1,2,1],[0,2,3]], labels = "aab", k = 2 + +**Output:** 2 + +**Explanation:** + +The optimal valid path from node 0 to node 2 is as follows: + +* Use `edges[0] = [0, 1, 1]` to reach node 1 with weight wi = 1. +* Use `edges[1] = [1, 2, 1]` to reach node 2 with weight wi = 1. + +The corresponding concatenation of labels is `"aab"`, which satisfies at most `k = 2` consecutive identical characters. Thus, the answer is 2. + +**Example 3:** + +**Input:** n = 3, edges = [[0,1,1],[1,2,1]], labels = "aaa", k = 2 + +**Output:** \-1 + +**Explanation:** + +There is no valid path from node 0 to node 2 that satisfies at most `k = 2` consecutive identical characters. Thus, the answer is -1. + +**Constraints:** + +* 1 <= n == labels.length <= 5 * 104 +* 0 <= edges.length <= 5 * 104 +* edges[i] == [ui, vi, wi] +* 0 <= ui, vi <= n - 1 +* ui != vi +* 1 <= wi <= 104 +* `labels` consists of lowercase English letters +* `1 <= k <= 50` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3971_maximum_total_value/Solution.java b/src/main/java/g3901_4000/s3971_maximum_total_value/Solution.java new file mode 100644 index 000000000..6f00bcd6c --- /dev/null +++ b/src/main/java/g3901_4000/s3971_maximum_total_value/Solution.java @@ -0,0 +1,63 @@ +package g3901_4000.s3971_maximum_total_value; + +// #Hard #Array #Math #Greedy #Binary_Search #Senior_Staff #Weekly_Contest_507 +// #2026_11_03_Time_19_ms_(100.00%)_Space_106.00_MB_(7.14%) + +public class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int maxTotalValue(int[] value, int[] decay, int m) { + if (getCount(value, decay, m, 0) < m) { + return getSum(value, decay, m, 0); + } + int max = 0; + for (int x : value) { + max = Math.max(max, x); + } + int left = 1; + int right = max; + while (left <= right) { + int mid = left + right >> 1; + if (getCount(value, decay, m, mid) >= m) { + left = mid + 1; + } else { + right = mid - 1; + } + } + return getSum(value, decay, m, right); + } + + private long getCount(int[] value, int[] decay, int m, int limit) { + int n = value.length; + long count = 0; + for (int i = 0; i < n; ++i) { + int x = value[i]; + int d = decay[i]; + if (x >= limit) { + count += (x - limit) / d + 1; + } + if (count >= m) { + break; + } + } + return count; + } + + private int getSum(int[] value, int[] decay, long m, int limit) { + int n = value.length; + long sum = 0; + for (int i = 0; i < n; ++i) { + int x = value[i]; + int d = decay[i]; + if (x <= limit) { + continue; + } + long c = (x - limit - 1) / d + 1L; + sum += c * (x + x - (c - 1) * d); + m -= c; + } + sum >>= 1; + sum += m * limit; + return (int) (sum % MOD); + } +} diff --git a/src/main/java/g3901_4000/s3971_maximum_total_value/readme.md b/src/main/java/g3901_4000/s3971_maximum_total_value/readme.md new file mode 100644 index 000000000..494f3a255 --- /dev/null +++ b/src/main/java/g3901_4000/s3971_maximum_total_value/readme.md @@ -0,0 +1,67 @@ +3971\. Maximum Total Value + +Hard + +You are given two integer arrays `value` and `decay`, and an integer `m`. + +* `value[i]` represents the initial value at index `i`. +* `decay[i]` represents how much the value decreases after each selection of index `i`. + +You may select any index **multiple** times. The total number of selections across all indices must not exceed `m`. + +If you select index `i` for the tth time, where `t` is 1-indexed, the value gained is `value[i] - decay[i] * (t - 1)`. + +Return the **maximum** total value you can obtain. Since the answer may be large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** value = [6,5,4], decay = [2,1,1], m = 4 + +**Output:** 19 + +**Explanation:** + +One optimal sequence of selections is as follows: + +* By selecting index 0, the value gained is 6. +* By selecting index 1, the value gained is 5. +* By selecting index 2, the value gained is 4. +* By selecting index 0 again, the value gained is `6 - 2 = 4`. + +The total value is `6 + 5 + 4 + 4 = 19`. No other sequence of at most 4 selections gives a higher total value. + +**Example 2:** + +**Input:** value = [7,2,2], decay = [3,2,1], m = 2 + +**Output:** 11 + +**Explanation:** + +One optimal sequence of selections is as follows: + +* By selecting index 0, the value gained is 7. +* By selecting index 0 again, the value gained is `7 - 3 = 4`. + +The total value is `7 + 4 = 11`. + +**Example 3:** + +**Input:** value = [4,3], decay = [5,4], m = 5 + +**Output:** 7 + +**Explanation:** + +One optimal sequence of selections is as follows: + +* By selecting index 0, the value gained is 4. +* By selecting index 1, the value gained is 3. + +The total value is `4 + 3 = 7`. + +**Constraints:** + +* 1 <= value.length == decay.length <= 105 +* 1 <= value[i], decay[i] <= 109 +* 1 <= m <= 109 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3974_maximum_total_sum_of_k_selected_elements/Solution.java b/src/main/java/g3901_4000/s3974_maximum_total_sum_of_k_selected_elements/Solution.java new file mode 100644 index 000000000..79b6e3bb5 --- /dev/null +++ b/src/main/java/g3901_4000/s3974_maximum_total_sum_of_k_selected_elements/Solution.java @@ -0,0 +1,43 @@ +package g3901_4000.s3974_maximum_total_sum_of_k_selected_elements; + +// #Medium #Array #Sorting #Greedy #Senior #Weekly_Contest_508 +// #2026_11_03_Time_18_ms_(98.38%)_Space_143.14_MB_(97.84%) + +public class Solution { + private static final int MAX = 100_000 + 1; + + public long maxSum(int[] nums, int k, int mul) { + int[] count = new int[MAX]; + int max = nums[0]; + long sum = 0; + for (int n : nums) { + max = Math.max(max, n); + count[n]++; + } + while (max >= 0 && k > 0) { + if (count[max] != 0) { + int min = Math.min(mul, count[max]); + min = Math.min(k, min); + k -= min; + mul -= min; + long local = + ((long) (mul + min) * (mul + min + 1)) / 2 - ((long) mul * (mul + 1)) / 2; + sum += local * max; + if (mul == 0) { + count[max] -= min; + break; + } + } + max--; + } + while (max >= 0 && k > 0) { + if (count[max] != 0) { + int min = Math.min(k, count[max]); + k -= min; + sum += (long) max * min; + } + max--; + } + return sum; + } +} diff --git a/src/main/java/g3901_4000/s3974_maximum_total_sum_of_k_selected_elements/readme.md b/src/main/java/g3901_4000/s3974_maximum_total_sum_of_k_selected_elements/readme.md new file mode 100644 index 000000000..7f5cb05bf --- /dev/null +++ b/src/main/java/g3901_4000/s3974_maximum_total_sum_of_k_selected_elements/readme.md @@ -0,0 +1,68 @@ +3974\. Maximum Total Sum of K Selected Elements + +Medium + +You are given an integer array `nums` and two integers `k` and `mul`. + +Select **exactly** `k` elements from `nums`. Process these elements one by one in any order you choose. + +For each selected element, **independently** choose one of the following: + +* **Add** the element's value to the total sum, or +* **Multiply** the element by the **current** value of `mul` and **add** the result to the total sum. + +After processing each selected element, `mul` **decreases** by 1, regardless of which option was chosen. The current value of `mul` may become 0 or negative. + +Return an integer denoting the **maximum** possible total sum. + +**Example 1:** + +**Input:** nums = [6,1,2,9], k = 3, mul = 2 + +**Output:** 26 + +**Explanation:** + +One optimal way: + +* One optimal selection is `nums[3] = 9`, `nums[0] = 6`, and `nums[2] = 2`. +* Process `nums[3] = 9` first: choose multiplication, so it contributes `9 * 2 = 18`. Now, `mul` becomes 1. +* Process `nums[0] = 6` next: choose multiplication, so it contributes `6 * 1 = 6`. Now, `mul` becomes 0. +* Process `nums[2] = 2` last: choose addition, so it contributes 2. +* The total sum is `18 + 6 + 2 = 26`. + +**Example 2:** + +**Input:** nums = [3,7,5,2], k = 2, mul = 4 + +**Output:** 43 + +**Explanation:** + +One optimal way: + +* One optimal selection is `nums[1] = 7` and `nums[2] = 5`. +* Process `nums[1] = 7` first: choose multiplication, so it contributes `7 * 4 = 28`. Now, `mul` becomes 3. +* Process `nums[2] = 5` next: choose multiplication, so it contributes `5 * 3 = 15`. +* The total sum is `28 + 15 = 43`. + +**Example 3:** + +**Input:** nums = [4,4], k = 1, mul = 1 + +**Output:** 4 + +**Explanation:** + +One optimal way: + +* One optimal selection is `nums[0] = 4`. +* Process `nums[0] = 4`: choose multiplication, so it contributes `4 * 1 = 4`. +* The total sum is 4. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 105 +* `1 <= k <= nums.length` +* 1 <= mul <= 105 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3975_filter_occupied_intervals/Solution.java b/src/main/java/g3901_4000/s3975_filter_occupied_intervals/Solution.java new file mode 100644 index 000000000..cfc49a648 --- /dev/null +++ b/src/main/java/g3901_4000/s3975_filter_occupied_intervals/Solution.java @@ -0,0 +1,50 @@ +package g3901_4000.s3975_filter_occupied_intervals; + +// #Medium #Array #Sorting #Senior #Weekly_Contest_508 +// #2026_11_03_Time_63_ms_(99.08%)_Space_149.43_MB_(90.83%) + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; + +public class Solution { + public List> filterOccupiedIntervals( + int[][] occupiedIntervals, int freeStart, int freeEnd) { + List intervals = new ArrayList<>(); + for (int[] occupiedInterval : occupiedIntervals) { + int first = occupiedInterval[0]; + int second = occupiedInterval[1]; + if (second < freeStart || first > freeEnd) { + intervals.add(new int[] {first, second}); + } else { + if (first < freeStart) { + intervals.add(new int[] {first, freeStart - 1}); + } + + if (second > freeEnd) { + intervals.add(new int[] {freeEnd + 1, second}); + } + } + } + intervals.sort(Comparator.comparingInt(a -> a[0])); + return getLists(intervals); + } + + private static List> getLists(List intervals) { + int index = 0; + List> res = new ArrayList<>(); + while (index < intervals.size()) { + int first = intervals.get(index)[0]; + int second = intervals.get(index)[1]; + while (index + 1 < intervals.size() && second + 1 >= intervals.get(index + 1)[0]) { + index++; + second = Math.max(second, intervals.get(index)[1]); + } + List temp = Arrays.asList(first, second); + res.add(temp); + index++; + } + return res; + } +} diff --git a/src/main/java/g3901_4000/s3975_filter_occupied_intervals/readme.md b/src/main/java/g3901_4000/s3975_filter_occupied_intervals/readme.md new file mode 100644 index 000000000..b21c3df24 --- /dev/null +++ b/src/main/java/g3901_4000/s3975_filter_occupied_intervals/readme.md @@ -0,0 +1,42 @@ +3975\. Filter Occupied Intervals + +Medium + +You are given a 2D integer array `occupiedIntervals`, where occupiedIntervals[i] = [starti, endi] represents a time interval during which you are occupied. Each interval starts at starti and ends at endi, **inclusive**. These intervals may **overlap**. + +You are also given two integers `freeStart` and `freeEnd`, which define a free time interval from `freeStart` to `freeEnd`, inclusive. + +Your task is to merge **all** occupied intervals that overlap or touch, then remove **all** integer points in the free interval from the merged occupied intervals. + +Two intervals touch if the second interval starts **immediately after** the first one ends. For example, `[1, 1]` and `[2, 2]` touch and should be merged into `[1, 2]`. + +Return the **remaining** occupied intervals in **sorted** order. The returned intervals must be **non-overlapping** and must contain the **minimum** number of intervals possible. If there are no remaining occupied points, return an empty list. + +**Example 1:** + +**Input:** occupiedIntervals = [[2,6],[4,8],[10,10],[10,12],[14,16]], freeStart = 7, freeEnd = 11 + +**Output:** [[2,6],[12,12],[14,16]] + +**Explanation:** + +* After merging, the occupied intervals are `[2, 8]`, `[10, 12]`, and `[14, 16]`. +* Excluding the free interval `[7, 11]` results in `[2, 6]`, `[12, 12]`, and `[14, 16]`. + +**Example 2:** + +**Input:** occupiedIntervals = [[1,5],[2,3]], freeStart = 3, freeEnd = 8 + +**Output:** [[1,2]] + +**Explanation:** + +* After merging, the occupied interval is `[1, 5]`. +* Excluding the free interval `[3, 8]` results in `[1, 2]`. + +**Constraints:** + +* 1 <= occupiedIntervals.length <= 5 * 104 +* `occupiedIntervals[i].length == 2` +* 1 <= starti <= endi <= 109 +* 1 <= freeStart <= freeEnd <= 109 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3976_maximum_subarray_sum_after_multiplier/Solution.java b/src/main/java/g3901_4000/s3976_maximum_subarray_sum_after_multiplier/Solution.java new file mode 100644 index 000000000..7728a7100 --- /dev/null +++ b/src/main/java/g3901_4000/s3976_maximum_subarray_sum_after_multiplier/Solution.java @@ -0,0 +1,21 @@ +package g3901_4000.s3976_maximum_subarray_sum_after_multiplier; + +// #Medium #Array #Dynamic_Programming #Staff #Weekly_Contest_508 +// #2026_11_03_Time_5_ms_(100.00%)_Space_113.06_MB_(81.25%) + +public class Solution { + public long maxSubarraySum(int[] nums, int k) { + long max = Long.MIN_VALUE; + long used = 0; + long div = 0; + long sum = 0; + for (int x : nums) { + used = Math.max(used, div) + x; + div = Math.max(sum, div) + x / k; + sum += x; + max = Math.max(Math.max(max, sum * k), Math.max(used, div)); + sum = Math.max(sum, 0); + } + return max; + } +} diff --git a/src/main/java/g3901_4000/s3976_maximum_subarray_sum_after_multiplier/readme.md b/src/main/java/g3901_4000/s3976_maximum_subarray_sum_after_multiplier/readme.md new file mode 100644 index 000000000..55ebcf724 --- /dev/null +++ b/src/main/java/g3901_4000/s3976_maximum_subarray_sum_after_multiplier/readme.md @@ -0,0 +1,46 @@ +3976\. Maximum Subarray Sum After Multiplier + +Medium + +You are given an integer array `nums` and a positive integer `k`. + +You must choose **exactly** one non-empty subarrays of `nums` and perform **exactly** one of the following operations: + +1. Multiply each number in the chosen subarray by `k`. +2. Divide each number in the chosen subarray by `k`. + * When dividing a positive number by `k`, use the **floor** value of the division result. + * When dividing a negative number by `k`, use the **ceiling** value of the division result. + +Return the **maximum** possible sum of a **non-empty** subarray in the resulting array. + +Note that the subarray chosen for the operation and the subarray chosen for the sum may be **different**. + +**Example 1:** + +**Input:** nums = [1,-2,3,4,-5], k = 2 + +**Output:** 14 + +**Explanation:** + +* Multiply each number in the subarray `[3, 4]` by 2. +* This results in `nums = [1, -2, 6, 8, -5]`. +* The subarray with the largest sum is `[6, 8]`, so the output is `6 + 8 = 14`. + +**Example 2:** + +**Input:** nums = [-5,-4,-3], k = 2 + +**Output:** \-1 + +**Explanation:** + +* Divide each number in the subarray `[-3]` by 2. +* This results in `nums = [-5, -4, -1]`. +* The subarray with the largest sum is `[-1]`, so the output is -1. + +**Constraints:** + +* 1 <= nums.length <= 105 +* -105 <= nums[i] <= 105 +* 1 <= k <= 105 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/Solution.java b/src/main/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/Solution.java new file mode 100644 index 000000000..e8e4c6f8c --- /dev/null +++ b/src/main/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/Solution.java @@ -0,0 +1,128 @@ +package g3901_4000.s3977_minimum_time_to_reach_target_with_limited_power; + +// #Hard #Array #Dynamic_Programming #Heap_Priority_Queue #Shortest_Path #Graph_Theory #Senior_Staff +// #Weekly_Contest_508 #2026_11_03_Time_7_ms_(98.67%)_Space_47.66_MB_(96.00%) + +import java.util.Arrays; + +public class Solution { + private static class Graph { + int[] head; + int[] next; + int[] to; + int[] time; + + Graph(int n, int[][] edges) { + int m = edges.length; + + head = new int[n]; + next = new int[m + 1]; + to = new int[m + 1]; + time = new int[m + 1]; + + for (int i = 0; i < m; i++) { + int u = edges[i][0]; + + to[i + 1] = edges[i][1]; + time[i + 1] = edges[i][2]; + next[i + 1] = head[u]; + head[u] = i + 1; + } + } + } + + private static class MinHeap { + long[] heap = new long[2048]; + int size; + + void push(long value) { + if (++size == heap.length) { + heap = Arrays.copyOf(heap, heap.length << 1); + } + + int j = size; + + while (j > 1) { + int p = j >>> 1; + + if (heap[p] <= value) { + break; + } + + heap[j] = heap[p]; + j = p; + } + + heap[j] = value; + } + + long pop() { + long result = heap[1]; + long val = heap[size--]; + + int i = 1; + + while ((i << 1) <= size) { + int left = i << 1; + int right = left + 1; + + int min = right <= size && heap[right] < heap[left] ? right : left; + + if (val <= heap[min]) { + break; + } + + heap[i] = heap[min]; + i = min; + } + + if (size > 0) { + heap[i] = val; + } + + return result; + } + + boolean isEmpty() { + return size == 0; + } + } + + public long[] minTimeMaxPower( + int n, int[][] edges, int power, int[] cost, int source, int target) { + Graph graph = new Graph(n, edges); + int[] bestPower = new int[n]; + Arrays.fill(bestPower, -1); + MinHeap pq = new MinHeap(); + long startPowerComp = 1024L - power; + pq.push((startPowerComp << 11) | source); + while (!pq.isEmpty()) { + long curr = pq.pop(); + long currTime = curr >>> 22; + int currPower = 1024 - (int) ((curr >>> 11) & 0x7FF); + int u = (int) (curr & 0x7FF); + if (u == target) { + return new long[] {currTime, currPower}; + } + if (currPower > bestPower[u]) { + bestPower[u] = currPower; + if (currPower >= cost[u]) { + addNeighbors(pq, currTime, currPower, u, graph, cost); + } + } + } + return new long[] {-1, -1}; + } + + private void addNeighbors( + MinHeap pq, long currTime, int currPower, int u, Graph graph, int[] cost) { + int nextPower = currPower - cost[u]; + long nextPowerComp = 1024L - nextPower; + for (int e = graph.head[u]; e != 0; e = graph.next[e]) { + long nextPacked = + ((currTime + graph.time[e]) << 22) | (nextPowerComp << 11) | graph.to[e]; + + pq.push(nextPacked); + } + } +} diff --git a/src/main/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/readme.md b/src/main/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/readme.md new file mode 100644 index 000000000..9c2a83ca1 --- /dev/null +++ b/src/main/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/readme.md @@ -0,0 +1,79 @@ +3977\. Minimum Time to Reach Target With Limited Power + +Hard + +You are given a **directed** weighted graph with `n` nodes labeled from 0 to `n - 1`. + +The graph is represented by a 2D integer array `edges`, where edges[i] = [ui, vi, ti] indicates a directed edge from node ui to node vi that takes ti seconds to traverse. + +You are also given an integer `power` representing the initial available power, and an integer array `cost` of length `n`, where `cost[u]` represents the power required to forward the signal from node `u` through **any** one of its outgoing edges. + +You are given two integers `source` and `target`. + +The signal starts at `source` at time 0 with `power` units of power and follows these rules: + +* The signal may traverse a directed edge from node `u` only if the remaining power is **at least** `cost[u]`. +* No power is consumed when the signal arrives at a node, unless it later leaves that node by traversing another edge. +* When the signal is forwarded from node `u`, the remaining power is **decreased** by `cost[u]` units. +* Traversing an edge edges[i] = [ui, vi, ti] **increases** the total time by ti seconds. + +Return an integer array `answer` of size 2, where: + +* `answer[0]` is the **minimum** time required for the signal to reach node `target`. +* `answer[1]` is the **maximum** remaining power among all paths that achieve `answer[0]`. + +If the signal cannot reach `target`, return `[-1, -1]`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2026/02/09/g1.png) + +**Input:** n = 5, edges = [[0,1,1],[1,4,1],[0,2,1],[2,3,1],[3,4,1]], power = 4, cost = [2,3,1,1,1], source = 0, target = 4 + +**Output:** [3,0] + +**Explanation:** + +* The signal starts at node 0 with 4 units of power. +* The path `0 -> 1 -> 4` is not valid, because after leaving node 0, the signal has 2 units of power remaining, which is less than `cost[1] = 3`. +* The valid path `0 -> 2 -> 3 -> 4` takes a total time of 3. +* The total power consumed along this path is `cost[0] + cost[2] + cost[3] = 4`, leaving 0 remaining power. +* Hence, the answer is `[3, 0]`. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2026/02/09/g22.png) + +**Input:** n = 3, edges = [[0,1,2],[1,2,2],[2,0,2]], power = 3, cost = [1,1,1], source = 1, target = 1 + +**Output:** [0,3] + +**Explanation:** + +* Since the `source` and `target` are the same node, no traversal is required. +* Hence, the minimum total time taken is 0, and no power is consumed. +* Therefore, the answer is `[0, 3]`. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2026/02/09/g23.png) + +**Input:** n = 4, edges = [[0,1,3],[2,3,4]], power = 3, cost = [1,1,1,1], source = 0, target = 3 + +**Output:** [-1,-1] + +**Explanation:** + +There is no valid path from `source` to `target`, therefore return `[-1, -1]`. + +**Constraints:** + +* `1 <= n <= 1000` +* `0 <= edges.length <= 1000` +* edges[i] = [ui, vi, ti] +* 0 <= ui, vi <= n - 1 +* 1 <= ti <= 109 +* `1 <= power <= 1000` +* `cost.length == n` +* `1 <= cost[i] <= 2000` +* `0 <= source, target <= n - 1` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3978_unique_middle_element/Solution.java b/src/main/java/g3901_4000/s3978_unique_middle_element/Solution.java new file mode 100644 index 000000000..e93ebd8ec --- /dev/null +++ b/src/main/java/g3901_4000/s3978_unique_middle_element/Solution.java @@ -0,0 +1,18 @@ +package g3901_4000.s3978_unique_middle_element; + +// #Easy #Array #Counting #Mid_Level #Biweekly_Contest_186 +// #2026_11_03_Time_1_ms_(94.19%)_Space_45.62_MB_(97.22%) + +public class Solution { + public boolean isMiddleElementUnique(int[] nums) { + int mid = nums.length / 2; + int key = nums[mid]; + int freq = 0; + for (int ele : nums) { + if (ele == key) { + freq++; + } + } + return (freq == 1); + } +} diff --git a/src/main/java/g3901_4000/s3978_unique_middle_element/readme.md b/src/main/java/g3901_4000/s3978_unique_middle_element/readme.md new file mode 100644 index 000000000..717faf9c5 --- /dev/null +++ b/src/main/java/g3901_4000/s3978_unique_middle_element/readme.md @@ -0,0 +1,37 @@ +3978\. Unique Middle Element + +Easy + +You are given an integer array `nums` of odd length `n`. + +Return `true` if the middle element of `nums` appears **exactly** once in the array. Otherwise return `false`. + +**Example 1:** + +**Input:** nums = [1,2,3] + +**Output:** true + +**Explanation:** + +The middle element of `nums` is 2, which appears exactly once. + +Thus, the answer is `true`. + +**Example 2:** + +**Input:** nums = [1,2,2] + +**Output:** false + +**Explanation:** + +The middle element of `nums` is 2, which appears twice. + +Thus, the answer is `false`. + +**Constraints:** + +* `1 <= n == nums.length <= 100` +* `n` is odd. +* `1 <= nums[i] <= 100` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3979_maximum_valid_pair_sum/Solution.java b/src/main/java/g3901_4000/s3979_maximum_valid_pair_sum/Solution.java new file mode 100644 index 000000000..7e0df2d78 --- /dev/null +++ b/src/main/java/g3901_4000/s3979_maximum_valid_pair_sum/Solution.java @@ -0,0 +1,17 @@ +package g3901_4000.s3979_maximum_valid_pair_sum; + +// #Medium #Array #Enumeration #Senior #Biweekly_Contest_186 +// #2026_11_03_Time_2_ms_(59.68%)_Space_118.86_MB_(52.57%) + +public class Solution { + public int maxValidPairSum(int[] nums, int k) { + int res = 0; + int pre = 0; + int n = nums.length; + for (int i = 0; i < n - k; i++) { + pre = Math.max(pre, nums[i]); + res = Math.max(res, pre + nums[i + k]); + } + return res; + } +} diff --git a/src/main/java/g3901_4000/s3979_maximum_valid_pair_sum/readme.md b/src/main/java/g3901_4000/s3979_maximum_valid_pair_sum/readme.md new file mode 100644 index 000000000..a9926d20a --- /dev/null +++ b/src/main/java/g3901_4000/s3979_maximum_valid_pair_sum/readme.md @@ -0,0 +1,49 @@ +3979\. Maximum Valid Pair Sum + +Medium + +You are given an integer array `nums` of length `n` and an integer `k`. + +A pair of indices `(i, j)` is called **valid** if: + +* `0 <= i < j < n` +* `j - i >= k` + +Return the **maximum** value of `nums[i] + nums[j]` among all valid pairs. + +**Example 1:** + +**Input:** nums = [1,3,5,2,8], k = 2 + +**Output:** 13 + +**Explanation:** + +The valid pairs are: + +* `(0, 2)`: `nums[0] + nums[2] = 6` +* `(0, 3)`: `nums[0] + nums[3] = 3` +* `(0, 4)`: `nums[0] + nums[4] = 9` +* `(1, 3)`: `nums[1] + nums[3] = 5` +* `(1, 4)`: `nums[1] + nums[4] = 11` +* `(2, 4)`: `nums[2] + nums[4] = 13` + +Thus, the answer is 13. + +**Example 2:** + +**Input:** nums = [5,1,9], k = 1 + +**Output:** 14 + +**Explanation:** + +* Since `k = 1`, every pair is valid. +* The maximum value is obtained from a pair `(0, 2)`, which is `nums[0] + nums[2] = 5 + 9 = 14`. +* Thus, the answer is 14. + +**Constraints:** + +* 2 <= n == nums.length <= 105 +* 1 <= nums[i] <= 109 +* `1 <= k <= n - 1` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3980_minimum_operations_to_transform_binary_string/Solution.java b/src/main/java/g3901_4000/s3980_minimum_operations_to_transform_binary_string/Solution.java new file mode 100644 index 000000000..b78b56fd4 --- /dev/null +++ b/src/main/java/g3901_4000/s3980_minimum_operations_to_transform_binary_string/Solution.java @@ -0,0 +1,32 @@ +package g3901_4000.s3980_minimum_operations_to_transform_binary_string; + +// #Medium #String #Dynamic_Programming #Greedy #Staff #Biweekly_Contest_186 +// #2026_11_03_Time_10_ms_(100.00%)_Space_47.23_MB_(95.24%) + +public class Solution { + public int minOperations(String s1, String s2) { + int n = s1.length(); + int sumDiff = 0; + int pairs = 0; + boolean isCovered = false; + for (int i = 0; i < n; i++) { + int diff = s1.charAt(i) - s2.charAt(i); + sumDiff += diff; + if (diff == 1 && !isCovered) { + if (i + 1 < n) { + pairs++; + isCovered = true; + } else { + if (i > 0) { + pairs++; + } else { + return -1; + } + } + } else { + isCovered = false; + } + } + return 3 * pairs - sumDiff; + } +} diff --git a/src/main/java/g3901_4000/s3980_minimum_operations_to_transform_binary_string/readme.md b/src/main/java/g3901_4000/s3980_minimum_operations_to_transform_binary_string/readme.md new file mode 100644 index 000000000..0ac8ccd54 --- /dev/null +++ b/src/main/java/g3901_4000/s3980_minimum_operations_to_transform_binary_string/readme.md @@ -0,0 +1,50 @@ +3980\. Minimum Operations to Transform Binary String + +Medium + +You are given two binary strings `s1` and `s2` of the same length `n`. + +You can perform the following operations on `s1` any number of times, in any order: + +* Choose an index `i` such that `s1[i] == '0'`, and change it to `'1'`. +* Choose an index `i` such that `0 <= i < n - 1`, and both `s1[i]` and `s1[i + 1]` are `'1'`. Change both characters to `'0'`. + +Return the **minimum** number of operations required to make `s1` equal to `s2`. If it is impossible, return -1. + +**Example 1:** + +**Input:** s1 = "11", s2 = "00" + +**Output:** 1 + +**Explanation:** + +Change indices 0 and 1 from `'1'` to `'0'` in one operation, so `"11"` becomes `"00"`. Thus, the answer is 1. + +**Example 2:** + +**Input:** s1 = "01", s2 = "10" + +**Output:** 3 + +**Explanation:** + +* Change index 0 from `'0'` to `'1'`, so `"01"` becomes `"11"`. +* Change indices 0 and 1 from `'1'` to `'0'`, so `"11"` becomes `"00"`. +* Change index 0 from `'0'` to `'1'`, so `"00"` becomes `"10"`. +* Thus, the answer is 3. + +**Example 3:** + +**Input:** s1 = "1", s2 = "0" + +**Output:** \-1 + +**Explanation:** + +The first operation cannot change `'1'` to `'0'`, and the second operation requires two adjacent characters. Therefore, it is impossible. + +**Constraints:** + +* 1 <= n == s1.length == s2.length <= 105 +* `s1` and `s2` consist only of `'0'` and `'1'`. \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/Solution.java b/src/main/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/Solution.java new file mode 100644 index 000000000..fdd2279b5 --- /dev/null +++ b/src/main/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/Solution.java @@ -0,0 +1,112 @@ +package g3901_4000.s3981_count_distinct_ways_to_form_target_from_two_strings; + +// #Hard #String #Dynamic_Programming #Prefix_Sum #Senior_Staff #Biweekly_Contest_186 +// #2026_11_03_Time_28_ms_(100.00%)_Space_45.96_MB_(95.35%) + +import java.util.Arrays; + +public class Solution { + private static final int MOD = 1_000_000_007; + + public int interleaveCharacters(String word1, String word2, String target) { + int wl1 = word1.length(); + int wl2 = word2.length(); + int tl = target.length(); + int[][] dp = initializeDP(wl1, wl2); + int[][] nextDp = new int[wl1 + 1][wl2 + 1]; + int[][] s1 = new int[wl1 + 1][wl2 + 1]; + int[][] s2 = new int[wl1 + 1][wl2 + 1]; + boolean[] m1 = new boolean[wl1]; + boolean[] m2 = new boolean[wl2]; + for (int i = tl - 1; i >= 0; i--) { + char tc = target.charAt(i); + updateMatches(word1, m1, tc); + updateMatches(word2, m2, tc); + calculateS1(s1, dp, m1, wl1, wl2); + calculateS2(s2, s1, nextDp, dp, m2, wl1, wl2); + + int[][] temp = dp; + dp = nextDp; + nextDp = temp; + } + long[] dp1 = helper(word1, target, tl, wl1); + long[] dp2 = helper(word2, target, tl, wl2); + long ans = (dp[0][0] - dp1[0] - dp2[0]) % MOD; + return (int) ((ans + MOD) % MOD); + } + + private int[][] initializeDP(int wl1, int wl2) { + int[][] dp = new int[wl1 + 1][wl2 + 1]; + for (int i = 0; i <= wl1; i++) { + Arrays.fill(dp[i], 1); + } + return dp; + } + + private void updateMatches(String word, boolean[] matches, char targetChar) { + for (int i = 0; i < word.length(); i++) { + matches[i] = word.charAt(i) == targetChar; + } + } + + private void calculateS1(int[][] s1, int[][] dp, boolean[] m1, int wl1, int wl2) { + Arrays.fill(s1[wl1], 0); + for (int j = wl1 - 1; j >= 0; j--) { + int[] current = s1[j]; + int[] next = s1[j + 1]; + if (m1[j]) { + calculateS1Row(current, next, dp[j + 1], wl2); + } else { + System.arraycopy(next, 0, current, 0, wl2 + 1); + } + } + } + + private void calculateS1Row(int[] current, int[] next, int[] dpNext, int wl2) { + for (int k = wl2; k >= 0; k--) { + current[k] = (next[k] + dpNext[k]) % MOD; + } + } + + private void calculateS2( + int[][] s2, int[][] s1, int[][] nextDp, int[][] dp, boolean[] m2, int wl1, int wl2) { + for (int j = 0; j <= wl1; j++) { + calculateS2Row(s2[j], s1[j], nextDp[j], dp[j], m2, wl2); + } + } + + private void calculateS2Row( + int[] s2Row, int[] s1Row, int[] nextDpRow, int[] dpRow, boolean[] m2, int wl2) { + s2Row[wl2] = 0; + for (int k = wl2 - 1; k >= 0; k--) { + int val = s2Row[k + 1]; + if (m2[k]) { + val = (val + dpRow[k + 1]) % MOD; + } + s2Row[k] = val; + nextDpRow[k] = (s1Row[k] + val) % MOD; + } + nextDpRow[wl2] = s1Row[wl2]; + } + + private long[] helper(String word1, String target, int tl, int wl1) { + long[] ans = new long[wl1 + 1]; + Arrays.fill(ans, 1); + for (int i = tl - 1; i >= 0; i--) { + ans = calculateHelperRow(word1, target.charAt(i), ans, wl1); + } + return ans; + } + + private long[] calculateHelperRow(String word, char targetChar, long[] ans, int length) { + long[] next = new long[length + 1]; + long sum = 0; + for (int j = length - 1; j >= 0; j--) { + if (word.charAt(j) == targetChar) { + sum = (sum + ans[j + 1]) % MOD; + } + next[j] = sum; + } + return next; + } +} diff --git a/src/main/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/readme.md b/src/main/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/readme.md new file mode 100644 index 000000000..d5ac981ad --- /dev/null +++ b/src/main/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/readme.md @@ -0,0 +1,81 @@ +3981\. Count Distinct Ways to Form Target from Two Strings + +Hard + +You are given three strings `word1`, `word2`, and `target`. + +Your task is to count the number of ways to form `target` by choosing characters from `word1` and `word2` under the following conditions: + +* For each character of `target`, choose one matching character from either `word1` or `word2`. +* The chosen indices from `word1` must be **strictly** increasing. +* The chosen indices from `word2` must be **strictly** increasing. +* **At least** one character must be chosen from **both** `word1` and `word2`. + +Two ways are considered different if, for **at least** one position in `target`, the chosen character comes from a different string or a different index. + +Return the number of ways. Since the answer may be very large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** word1 = "abc", word2 = "bac", target = "abc" + +**Output:** 5 + +**Explanation:** + +There are 5 ways to form `target`: + +* `word1[0] = 'a'`, `word1[1] = 'b'`, `word2[2] = 'c'` +* `word1[0] = 'a'`, `word2[0] = 'b'`, `word1[2] = 'c'` +* `word1[0] = 'a'`, `word2[0] = 'b'`, `word2[2] = 'c'` +* `word2[1] = 'a'`, `word1[1] = 'b'`, `word1[2] = 'c'` +* `word2[1] = 'a'`, `word1[1] = 'b'`, `word2[2] = 'c'` + +All ways preserve the increasing index order inside each string and choose at least one character from each string. + +**Example 2:** + +**Input:** word1 = "cd", word2 = "cd", target = "ccd" + +**Output:** 4 + +**Explanation:** + +There are 4 ways to form `target`: + +* `word1[0] = 'c'`, `word2[0] = 'c'`, `word1[1] = 'd'` +* `word1[0] = 'c'`, `word2[0] = 'c'`, `word2[1] = 'd'` +* `word2[0] = 'c'`, `word1[0] = 'c'`, `word1[1] = 'd'` +* `word2[0] = 'c'`, `word1[0] = 'c'`, `word2[1] = 'd'` + +The first two `'c'` characters in `target` must come one from each string. The final `'d'` can be chosen from either string. + +**Example 3:** + +**Input:** word1 = "xy", word2 = "xy", target = "xyxy" + +**Output:** 2 + +**Explanation:** + +There are 2 ways to form `target`: + +* `word1[0] = 'x'`, `word1[1] = 'y'`, `word2[0] = 'x'`, `word2[1] = 'y'` +* `word2[0] = 'x'`, `word2[1] = 'y'`, `word1[0] = 'x'`, `word1[1] = 'y'` + +Each `"xy"` part in `target` comes entirely from one string. + +**Example 4:** + +**Input:** word1 = "ab", word2 = "cde", target = "ace" + +**Output:** 1 + +**Explanation:** + +The only way is to choose `word1[0] = 'a'`, `word2[0] = 'c'`, and `word2[2] = 'e'`. Thus, the answer is 1. + +**Constraints:** + +* `1 <= word1.length, word2.length, target.length <= 100` +* `word1`, `word2`, and `target` consist of lowercase English letters only. \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3982_sum_of_integers_with_maximum_digit_range/Solution.java b/src/main/java/g3901_4000/s3982_sum_of_integers_with_maximum_digit_range/Solution.java new file mode 100644 index 000000000..97278be42 --- /dev/null +++ b/src/main/java/g3901_4000/s3982_sum_of_integers_with_maximum_digit_range/Solution.java @@ -0,0 +1,32 @@ +package g3901_4000.s3982_sum_of_integers_with_maximum_digit_range; + +// #Easy #Array #Math #Mid_Level #Weekly_Contest_509 +// #2026_11_03_Time_2_ms_(57.34%)_Space_44.91_MB_(80.07%) + +public class Solution { + public int maxDigitRange(int[] nums) { + int n = nums.length; + int[] range = nums.clone(); + int maxRange = Integer.MIN_VALUE; + for (int i = 0; i < n; i++) { + int x = range[i]; + int mn = Integer.MAX_VALUE; + int mx = Integer.MIN_VALUE; + while (x > 0) { + int d = x % 10; + mn = Math.min(mn, d); + mx = Math.max(mx, d); + x /= 10; + } + range[i] = mx - mn; + maxRange = Math.max(maxRange, range[i]); + } + int ans = 0; + for (int i = 0; i < n; i++) { + if (range[i] == maxRange) { + ans += nums[i]; + } + } + return ans; + } +} diff --git a/src/main/java/g3901_4000/s3982_sum_of_integers_with_maximum_digit_range/readme.md b/src/main/java/g3901_4000/s3982_sum_of_integers_with_maximum_digit_range/readme.md new file mode 100644 index 000000000..2753cc899 --- /dev/null +++ b/src/main/java/g3901_4000/s3982_sum_of_integers_with_maximum_digit_range/readme.md @@ -0,0 +1,47 @@ +3982\. Sum of Integers with Maximum Digit Range + +Easy + +You are given an integer array `nums`. + +The **digit range** of an integer is defined as the difference between its **largest** digit and **smallest** digit. + +For example, the digit range of 5724 is `7 - 2 = 5`. + +Return the sum of all integers in `nums` whose **digit range** is equal to the **maximum digit range** among all integers in the array. + +**Example 1:** + +**Input:** nums = [5724,111,350] + +**Output:** 6074 + +**Explanation:** + +| `i` | `nums[i]` | Largest | Smallest | Digit Range | +| --- | --- | --- | --- | --- | +| 0 | 5724 | 7 | 2 | 5 | +| 1 | 111 | 1 | 1 | 0 | +| 2 | 350 | 5 | 0 | 5 | + +The maximum digit range is 5. The integers with this digit range are 5724 and 350, so the answer is `5724 + 350 = 6074`. + +**Example 2:** + +**Input:** nums = [90,900] + +**Output:** 990 + +**Explanation:** + +| `i` | `nums[i]` | Largest | Smallest | Digit Range | +| --- | --- | --- | --- | --- | +| 0 | 90 | 9 | 0 | 9 | +| 1 | 900 | 9 | 0 | 9 | + +The maximum digit range is 9. Both integers have this digit range, so the answer is `90 + 900 = 990`. + +**Constraints:** + +* `1 <= nums.length <= 100` +* 10 <= nums[i] <= 105 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3983_subsequence_after_one_replacement/Solution.java b/src/main/java/g3901_4000/s3983_subsequence_after_one_replacement/Solution.java new file mode 100644 index 000000000..2a8894ab7 --- /dev/null +++ b/src/main/java/g3901_4000/s3983_subsequence_after_one_replacement/Solution.java @@ -0,0 +1,34 @@ +package g3901_4000.s3983_subsequence_after_one_replacement; + +// #Medium #String #Two_Pointers #Staff #Weekly_Contest_509 +// #2026_11_03_Time_11_ms_(98.90%)_Space_47.84_MB_(67.03%) + +public class Solution { + public boolean canMakeSubsequence(String t, String s) { + char[] arrS = s.toCharArray(); + char[] arrT = t.toCharArray(); + if (arrS.length < arrT.length) { + return false; + } + int idx1 = 0; + int idx2 = 0; + int n = arrT.length; + for (char curr : arrS) { + int nextIdx1 = idx1; + int nextIdx2 = idx2; + if (idx2 < n && arrT[idx2] == curr) { + nextIdx2 = Math.max(nextIdx2, idx2 + 1); + } + if (idx1 < n) { + nextIdx2 = Math.max(nextIdx2, idx1 + 1); + } + if (idx1 < n && arrT[idx1] == curr) { + nextIdx1 = idx1 + 1; + } + nextIdx2 = Math.max(nextIdx2, nextIdx1); + idx1 = nextIdx1; + idx2 = nextIdx2; + } + return idx1 == n || idx2 == n; + } +} diff --git a/src/main/java/g3901_4000/s3983_subsequence_after_one_replacement/readme.md b/src/main/java/g3901_4000/s3983_subsequence_after_one_replacement/readme.md new file mode 100644 index 000000000..25b1fe428 --- /dev/null +++ b/src/main/java/g3901_4000/s3983_subsequence_after_one_replacement/readme.md @@ -0,0 +1,36 @@ +3983\. Subsequence After One Replacement + +Medium + +You are given two strings `s` and `t` consisting of lowercase English letters. + +You may choose **at most** one index in `s` and replace the character at that index with any lowercase English letter. + +Return `true` if it is possible to make `s` a subsequence of `t`; otherwise, return `false`. + +**Example 1:** + +**Input:** s = "cat", t = "chat" + +**Output:** true + +**Explanation:** + +* Replace `s[1]` from `'a'` to `'h'`. The resulting string is `"cht"`. +* `"cht"` is a subsequence of `"chat"` because we can match `'c'`, `'h'`, and `'t'` in order. + +**Example 2:** + +**Input:** s = "plane", t = "apple" + +**Output:** false + +**Explanation:** + +* The characters `'p'`, `'l'`, and `'e'` can be matched in `t`, but the remaining characters cannot be matched while preserving the required order. +* Even after replacing any one character in `s`, it is impossible to make `s` a subsequence of `t`. + +**Constraints:** + +* 1 <= s.length, t.length <= 105 +* `s` and `t` consist only of lowercase English letters. \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3984_divisible_game/Solution.java b/src/main/java/g3901_4000/s3984_divisible_game/Solution.java new file mode 100644 index 000000000..ce7bfdbb5 --- /dev/null +++ b/src/main/java/g3901_4000/s3984_divisible_game/Solution.java @@ -0,0 +1,49 @@ +package g3901_4000.s3984_divisible_game; + +// #Medium #Array #Dynamic_Programming #Math #Enumeration #Number_Theory #Staff #Weekly_Contest_509 +// #2026_11_03_Time_22_ms_(93.00%)_Space_46.30_MB_(94.00%) + +import java.util.HashSet; + +public class Solution { + public int divisibleGame(int[] nums) { + HashSet prime = new HashSet<>(); + int mod = (int) 1e9 + 7; + long bestscore = nums[0]; + for (int i : nums) { + bestscore = Math.min(bestscore, i); + } + bestscore = -bestscore; + long bestprime = 2; + for (int i : nums) { + for (int j = 2; j * j <= i; j++) { + if (i % j == 0) { + prime.add(j); + while (i % j == 0) { + i = i / j; + } + } + } + if (i > 1) { + prime.add(i); + } + } + for (int p : prime) { + long curr = 0; + long maxi = Long.MIN_VALUE; + for (int i : nums) { + long val = (i % p == 0) ? i : -i; + curr = Math.max(0, curr + val); + maxi = Math.max(maxi, curr); + } + if (maxi > bestscore) { + bestscore = maxi; + bestprime = p; + } else if (maxi == bestscore && p < bestprime) { + bestprime = p; + } + } + bestscore = ((bestscore % mod) + mod) % mod; + return (int) ((bestscore * (bestprime % mod)) % mod); + } +} diff --git a/src/main/java/g3901_4000/s3984_divisible_game/readme.md b/src/main/java/g3901_4000/s3984_divisible_game/readme.md new file mode 100644 index 000000000..548306066 --- /dev/null +++ b/src/main/java/g3901_4000/s3984_divisible_game/readme.md @@ -0,0 +1,67 @@ +3984\. Divisible Game + +Medium + +You are given an integer array `nums` of length `n`. + +Alice and Bob are playing a game. Alice chooses: + +* An integer `k` such that `k > 1`. +* Two integers `l` and `r` such that `0 <= l <= r < n`. + +Initially, both Alice's and Bob's scores are 0. + +For each index `i` in the range `[l, r]` (inclusive): + +* If `nums[i]` is divisible by `k`, Alice's score **increases** by `nums[i]`. +* Otherwise, Bob's score **increases** by `nums[i]`. + +The **score difference** is Alice's score **minus** Bob's score. + +Alice wants to **maximize** the score difference. If there are multiple values of `k` that achieve the **maximum** score difference, she chooses the **smallest** such `k`. + +Return the **product** of the **maximum** score difference and the chosen value of `k`. Since the result can be large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** nums = [1,4,6,8] + +**Output:** 36 + +**Explanation:** + +* Alice can choose `k = 2`, `l = 1`, and `r = 3`. +* All values in `nums[1..3]` are divisible by 2, so Alice's score is `4 + 6 + 8 = 18`, while Bob's score is 0. +* The score difference is 18, which is the maximum possible. Among all values of `k` that achieve this score difference, the smallest is 2. +* Therefore, the answer is `18 * 2 = 36`. + +**Example 2:** + +**Input:** nums = [2,1,2] + +**Output:** 6 + +**Explanation:** + +* Alice can choose `k = 2`, `l = 0`, and `r = 2`. +* The values `nums[0]` and `nums[2]` are divisible by 2, so Alice's score is `2 + 2 = 4`. The value `nums[1]` is not divisible by 2, so Bob's score is 1. +* The score difference is `4 - 1 = 3`, which is the maximum possible. Among all values of `k` that achieve this score difference, the smallest is 2. +* Therefore, the answer is `3 * 2 = 6`. + +**Example 3:** + +**Input:** nums = [1] + +**Output:** 1000000005 + +**Explanation:** + +* Alice must choose some `k > 1`. The smallest possible choice is `k = 2`. +* Since `nums[0]` is not divisible by 2, Alice's score is 0, while Bob's score is 1. +* The score difference is -1, which is the maximum possible. +* Therefore, the answer is `-1 * 2 = -2`. Modulo 109 + 7, this equals 1000000005. + +**Constraints:** + +* `1 <= nums.length <= 1000` +* 1 <= nums[i] <= 106 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3985_palindromic_subarray_sum/Solution.java b/src/main/java/g3901_4000/s3985_palindromic_subarray_sum/Solution.java new file mode 100644 index 000000000..7e38d0fc1 --- /dev/null +++ b/src/main/java/g3901_4000/s3985_palindromic_subarray_sum/Solution.java @@ -0,0 +1,88 @@ +package g3901_4000.s3985_palindromic_subarray_sum; + +// #Hard #Array #Binary_Search #Prefix_Sum #Hash_Function #Senior_Staff #Weekly_Contest_509 +// #2026_11_03_Time_13_ms_(100.00%)_Space_141.97_MB_(58.82%) + +public class Solution { + public long getSum(int[] nums) { + long[] prefix = buildPrefixSum(nums); + long oddMax = calculateOdd(nums, prefix); + long evenMax = calculateEven(nums, prefix); + return Math.max(oddMax, evenMax); + } + + private long[] buildPrefixSum(int[] nums) { + int n = nums.length; + long[] prefix = new long[n + 1]; + for (int i = 0; i < n; i++) { + prefix[i + 1] = prefix[i] + nums[i]; + } + return prefix; + } + + private long calculateOdd(int[] nums, long[] prefix) { + int n = nums.length; + int[] d1 = new int[n]; + int l = 0; + int r = -1; + long ans = 0; + for (int i = 0; i < n; i++) { + int k = (i > r) ? 1 : Math.min(d1[l + r - i], r - i + 1); + k = expandOdd(nums, i, k); + d1[i] = k; + int left = i - k + 1; + int right = i + k - 1; + ans = Math.max(ans, getRangeSum(prefix, left, right)); + if (right > r) { + l = left; + r = right; + } + } + + return ans; + } + + private int expandOdd(int[] nums, int i, int k) { + int n = nums.length; + while (i - k >= 0 && i + k < n && nums[i - k] == nums[i + k]) { + k++; + } + return k; + } + + private long calculateEven(int[] nums, long[] prefix) { + int n = nums.length; + int[] d2 = new int[n]; + int l = 0; + int r = -1; + long ans = 0; + for (int i = 0; i < n; i++) { + int k = (i > r) ? 0 : Math.min(d2[l + r - i + 1], r - i + 1); + k = expandEven(nums, i, k); + d2[i] = k; + if (k > 0) { + int left = i - k; + int right = i + k - 1; + ans = Math.max(ans, getRangeSum(prefix, left, right)); + if (right > r) { + l = left; + r = right; + } + } + } + + return ans; + } + + private int expandEven(int[] nums, int i, int k) { + while (i - k - 1 >= 0 && i + k < nums.length && nums[i - k - 1] == nums[i + k]) { + k++; + } + + return k; + } + + private long getRangeSum(long[] prefix, int left, int right) { + return prefix[right + 1] - prefix[left]; + } +} diff --git a/src/main/java/g3901_4000/s3985_palindromic_subarray_sum/readme.md b/src/main/java/g3901_4000/s3985_palindromic_subarray_sum/readme.md new file mode 100644 index 000000000..1d3c3dcd6 --- /dev/null +++ b/src/main/java/g3901_4000/s3985_palindromic_subarray_sum/readme.md @@ -0,0 +1,62 @@ +3985\. Palindromic Subarray Sum + +Hard + +You are given an integer array `nums`. + +Return the maximum possible sum of a non-empty subarrays of `nums` that is a palindrome. + +**Example 1:** + +**Input:** nums = [10,10] + +**Output:** 20 + +**Explanation:** + +The whole array `[10,10]` is a palindrome. Therefore, the maximum sum is `10 + 10 = 20`. + +**Example 2:** + +**Input:** nums = [1,2,3,2,1,5,6] + +**Output:** 9 + +**Explanation:** + +The contiguous subarray `[1,2,3,2,1]` is a palindrome. Its sum is `1 + 2 + 3 + 2 + 1 = 9` and it is the maximum sum. + +**Example 3:** + +**Input:** nums = [7,1,2,1,7,3,4,3,4] + +**Output:** 18 + +**Explanation:** + +The contiguous subarray `[7,1,2,1,7]` is a palindrome. Its sum is `7 + 1 + 2 + 1 + 7 = 18` and it is the maximum sum. + +**Example 4:** + +**Input:** nums = [1,2,3,4,5] + +**Output:** 5 + +**Explanation:** + +No subarray with length greater than 1 is a palindrome. The largest element in the array is 5. Therefore, the answer is 5. + +**Example 5:** + +**Input:** nums = [1000] + +**Output:** 1000 + +**Explanation:** + +The subarray with only one element is a palindrome. Therefore, the answer is 1000. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 109 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3986_number_of_elapsed_seconds_between_two_times/Solution.java b/src/main/java/g3901_4000/s3986_number_of_elapsed_seconds_between_two_times/Solution.java new file mode 100644 index 000000000..2cf901bf7 --- /dev/null +++ b/src/main/java/g3901_4000/s3986_number_of_elapsed_seconds_between_two_times/Solution.java @@ -0,0 +1,29 @@ +package g3901_4000.s3986_number_of_elapsed_seconds_between_two_times; + +// #Easy #String #Math #Mid_Level #Weekly_Contest_510 +// #2026_11_03_Time_2_ms_(72.94%)_Space_43.63_MB_(98.57%) + +public class Solution { + public int secondsBetweenTimes(String startTime, String endTime) { + int startSec = 0; + int endSec = 0; + int sSec = 0; + int eSec = 0; + int colon = 2; + for (int i = 0; i < 8; i++) { + if (startTime.charAt(i) == ':') { + startSec = (int) (startSec + sSec * Math.pow(60, colon)); + endSec = (int) (endSec + eSec * Math.pow(60, colon)); + colon--; + sSec = 0; + eSec = 0; + continue; + } + sSec = sSec * 10 + (startTime.charAt(i) - '0'); + eSec = eSec * 10 + (endTime.charAt(i) - '0'); + } + startSec = (int) (startSec + sSec * Math.pow(60, colon)); + endSec = (int) (endSec + eSec * Math.pow(60, colon)); + return endSec - startSec; + } +} diff --git a/src/main/java/g3901_4000/s3986_number_of_elapsed_seconds_between_two_times/readme.md b/src/main/java/g3901_4000/s3986_number_of_elapsed_seconds_between_two_times/readme.md new file mode 100644 index 000000000..2fe426586 --- /dev/null +++ b/src/main/java/g3901_4000/s3986_number_of_elapsed_seconds_between_two_times/readme.md @@ -0,0 +1,37 @@ +3986\. Number of Elapsed Seconds Between Two Times + +Easy + +You are given two valid times `startTime` and `endTime`, each represented as a string in the format `"HH:MM:SS"`. + +Return the number of seconds that have elapsed from `startTime` to `endTime`. + +**Example 1:** + +**Input:** startTime = "01:00:00", endTime = "01:00:25" + +**Output:** 25 + +**Explanation:** + +`endTime` is 25 seconds ahead of `startTime`. + +**Example 2:** + +**Input:** startTime = "12:34:56", endTime = "13:00:00" + +**Output:** 1504 + +**Explanation:** + +`endTime` is 25 minutes and 4 seconds ahead of `startTime`, which equals 1504 seconds. + +**Constraints:** + +* `startTime.length == 8` +* `endTime.length == 8` +* `startTime` and `endTime` are valid times in the format `"HH:MM:SS"` +* `00 <= HH <= 23` +* `00 <= MM <= 59` +* `00 <= SS <= 59` +* `endTime` is not earlier than `startTime` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3987_minimum_total_cost_to_process_all_elements/Solution.java b/src/main/java/g3901_4000/s3987_minimum_total_cost_to_process_all_elements/Solution.java new file mode 100644 index 000000000..34dd050e4 --- /dev/null +++ b/src/main/java/g3901_4000/s3987_minimum_total_cost_to_process_all_elements/Solution.java @@ -0,0 +1,30 @@ +package g3901_4000.s3987_minimum_total_cost_to_process_all_elements; + +// #Medium #Array #Math #Simulation #Senior #Weekly_Contest_510 +// #2026_11_03_Time_2_ms_(94.04%)_Space_136.23_MB_(77.48%) + +public class Solution { + public int minimumCost(int[] nums, int k) { + long sum = 0L; + int mod = 1000000007; + for (int num : nums) { + sum = sum + num; + } + if (sum < k) { + return 0; + } + long kRequired; + if (sum % k == 0) { + kRequired = sum / k; + } else { + kRequired = sum / k + 1; + } + return (int) func(kRequired - 1, mod); + } + + private long func(long n, int mod) { + long ans = ((n % mod) * ((n + 1) % mod)) % mod; + ans = (ans * 500000004) % mod; + return ans; + } +} diff --git a/src/main/java/g3901_4000/s3987_minimum_total_cost_to_process_all_elements/readme.md b/src/main/java/g3901_4000/s3987_minimum_total_cost_to_process_all_elements/readme.md new file mode 100644 index 000000000..e8aa164ec --- /dev/null +++ b/src/main/java/g3901_4000/s3987_minimum_total_cost_to_process_all_elements/readme.md @@ -0,0 +1,59 @@ +3987\. Minimum Total Cost to Process All Elements + +Medium + +You are given an integer array `nums` and an integer `k`. + +Initially, you have `k` units of resources. + +You must process the elements of `nums` from left to right. To process the ith element, you need `nums[i]` resources. + +If your available resources are less than `nums[i]`, you may perform an operation that increases your available resources by `k`. The value of `k` is fixed and does not change throughout the process. The first such operation incurs a cost of 1, the second incurs a cost of 2, and so on. + +After processing the ith element, your available resources decrease by `nums[i]`. + +Return an integer denoting the **minimum total cost** required to process all elements. Since the answer may be very large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** nums = [1,2,3,4], k = 4 + +**Output:** 3 + +**Explanation:** + +* After processing `nums[0]`, we have `4 - 1 = 3` units of resources left. +* After processing `nums[1]`, we have `3 - 2 = 1` unit of resources left. +* Since `nums[2] = 3` and only 1 unit of resources is available, we perform the first operation costing 1. After processing `nums[2]`, we have `1 + 4 - 3 = 2` units of resources left. +* Since `nums[3] = 4` and only 2 units of resources are available, we perform the second operation costing 2, to have `2 + 4 = 6` units of resources, which is enough to process `nums[3]`. +* Thus, the total cost is `1 + 2 = 3`. + +**Example 2:** + +**Input:** nums = [1,1,7,14], k = 4 + +**Output:** 15 + +**Explanation:** + +* After processing `nums[0]`, we have `4 - 1 = 3` units of resources left. +* After processing `nums[1]`, we have `3 - 1 = 2` units of resources left. +* Since `nums[2] = 7` and only 2 units of resources are available, we perform two operations costing `1 + 2 = 3`. After processing `nums[2]`, we have `2 + 4 + 4 - 7 = 3` units of resources left. +* Since `nums[3] = 14` and only 3 units of resources are available, we perform three operations costing `3 + 4 + 5 = 12`, to have `3 + 4 + 4 + 4 = 15` units of resources, which is enough to process `nums[3]`. +* Thus, the total cost is `3 + 12 = 15`. + +**Example 3:** + +**Input:** nums = [1,2,3,4], k = 10 + +**Output:** 0 + +**Explanation:** + +To process all elements, we can use the initial 10 units of resources without performing any operations. Thus, the total cost required is 0. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 109 +* 1 <= k <= 109 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/Solution.java b/src/main/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/Solution.java new file mode 100644 index 000000000..fa86751cd --- /dev/null +++ b/src/main/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/Solution.java @@ -0,0 +1,106 @@ +package g3901_4000.s3988_create_grid_with_exactly_k_paths_i; + +// #Medium #Array #Math #Matrix #Combinatorics #Staff #Weekly_Contest_510 +// #2026_11_03_Time_1_ms_(100.00%)_Space_43.92_MB_(68.14%) + +import java.util.Arrays; + +public class Solution { + + public String[] createGrid(int m, int n, int k) { + int[] dimensions = getDimensions(m, n, k); + if (dimensions.length == 0) { + return new String[] {}; + } + int dm = dimensions[0]; + int dn = dimensions[1]; + char[][] grid = initializeGrid(m, n); + + createRequiredPaths(grid, dm, dn); + addObstacles(grid, dm, dn, k); + connectRemainingGrid(grid, m, n, dm, dn); + return convertToStrings(grid, m); + } + + private int[] getDimensions(int m, int n, int k) { + if (k == 1) { + return new int[] {0, 0}; + } + if (k == 2 && m >= 2 && n >= 2) { + return new int[] {1, 1}; + } + if (k == 3) { + if (m >= 3 && n >= 2) { + return new int[] {2, 1}; + } + if (m >= 2 && n >= 3) { + return new int[] {1, 2}; + } + } + if (k == 4) { + return getFourPathDimensions(m, n); + } + return new int[0]; + } + + private int[] getFourPathDimensions(int m, int n) { + if (m >= 4 && n >= 2) { + return new int[] {3, 1}; + } + if (m >= 2 && n >= 4) { + return new int[] {1, 3}; + } + if (m >= 3 && n >= 3) { + return new int[] {2, 2}; + } + return new int[0]; + } + + private char[][] initializeGrid(int m, int n) { + char[][] grid = new char[m][n]; + for (char[] row : grid) { + Arrays.fill(row, '#'); + } + return grid; + } + + private void createRequiredPaths(char[][] grid, int dm, int dn) { + for (int i = 0; i <= dm; i++) { + for (int j = 0; j <= dn; j++) { + grid[i][j] = '.'; + } + } + } + + private void addObstacles(char[][] grid, int dm, int dn, int k) { + if (dm == 2 && dn == 2 && k == 4) { + grid[0][2] = '#'; + grid[2][0] = '#'; + } + } + + private void connectRemainingGrid(char[][] grid, int m, int n, int dm, int dn) { + connectVertically(grid, dm, dn, m); + connectHorizontally(grid, m, dn, n); + } + + private void connectVertically(char[][] grid, int dm, int dn, int m) { + for (int i = dm + 1; i < m; i++) { + grid[i][dn] = '.'; + } + } + + private void connectHorizontally(char[][] grid, int m, int dn, int n) { + for (int j = dn + 1; j < n; j++) { + grid[m - 1][j] = '.'; + } + } + + private String[] convertToStrings(char[][] grid, int m) { + String[] ans = new String[m]; + for (int i = 0; i < m; i++) { + ans[i] = new String(grid[i]); + } + return ans; + } +} diff --git a/src/main/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/readme.md b/src/main/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/readme.md new file mode 100644 index 000000000..17609fb76 --- /dev/null +++ b/src/main/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/readme.md @@ -0,0 +1,67 @@ +3988\. Create Grid With Exactly K Paths I + +Medium + +You are given three integers `m`, `n`, and `k`. + +Construct **any** `m x n` grid consisting only of the characters `'.'` and `'#'`, where: + +* `'.'` represents a free cell. +* `'#'` represents an obstacle cell. + +A **valid path** is a sequence of free cells that: + +* Starts at the top-left cell `(0, 0)`. +* Ends at the bottom-right cell `(m - 1, n - 1)`. +* Moves only: + * Right, from `(i, j)` to `(i, j + 1)`, or + * Down, from `(i, j)` to `(i + 1, j)`. + +Return any grid such that there are **exactly** `k` **valid paths** from the top-left cell to the bottom-right cell. If no such grid exists, return an empty array. + +**Example 1:** + +**Input:** m = 2, n = 3, k = 2 + +**Output:** ["...","#.."] + +**Explanation:** + +![](https://assets.leetcode.com/uploads/2026/05/26/screenshot-2026-05-27-at-113554am.png) + +There are exactly `k = 2` valid paths from `(0, 0)` to `(1, 2)`: + +* `(0, 0) → (0, 1) → (0, 2) → (1, 2)` +* `(0, 0) → (0, 1) → (1, 1) → (1, 2)` + +**Example 2:** + +**Input:** m = 3, n = 3, k = 4 + +**Output:** ["..#","...","#.."] + +**Explanation:** + +![](https://assets.leetcode.com/uploads/2026/05/26/screenshot-2026-05-27-at-113452am.png) + +There are exactly `k = 4` valid paths from `(0, 0)` to `(2, 2)`: + +* `(0, 0) → (0, 1) → (1, 1) → (1, 2) → (2, 2)` +* `(0, 0) → (0, 1) → (1, 1) → (2, 1) → (2, 2)` +* `(0, 0) → (1, 0) → (1, 1) → (1, 2) → (2, 2)` +* `(0, 0) → (1, 0) → (1, 1) → (2, 1) → (2, 2)` + +**Example 3:** + +**Input:** m = 1, n = 4, k = 2 + +**Output:** [] + +**Explanation:** + +No grid exists with exactly `k = 2` valid paths for a `1 x 4` grid, so the answer is an empty array. + +**Constraints:** + +* `1 <= m, n <= 10` +* `1 <= k <= 4` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3989_maximum_consistent_columns_in_a_grid/Solution.java b/src/main/java/g3901_4000/s3989_maximum_consistent_columns_in_a_grid/Solution.java new file mode 100644 index 000000000..73b89c566 --- /dev/null +++ b/src/main/java/g3901_4000/s3989_maximum_consistent_columns_in_a_grid/Solution.java @@ -0,0 +1,31 @@ +package g3901_4000.s3989_maximum_consistent_columns_in_a_grid; + +// #Hard #Array #Dynamic_Programming #Matrix #Senior_Staff #Weekly_Contest_510 +// #2026_11_03_Time_10_ms_(94.64%)_Space_61.08_MB_(87.50%) + +public class Solution { + public int maxConsistentColumns(int[][] grid, int limit) { + int n = grid[0].length; + int max = 1; + int[] dp = new int[n]; + for (int col = 0; col < n; ++col) { + dp[col] = 1; + for (int p = col - 1; p >= 0; --p) { + if (dp[p] + 1 >= dp[col] && areColumnsConsistent(grid, col, p, limit)) { + dp[col] = dp[p] + 1; + } + } + max = Math.max(max, dp[col]); + } + return max; + } + + private boolean areColumnsConsistent(int[][] grid, int col, int previousCol, int limit) { + for (int[] row : grid) { + if (Math.abs(row[col] - row[previousCol]) > limit) { + return false; + } + } + return true; + } +} diff --git a/src/main/java/g3901_4000/s3989_maximum_consistent_columns_in_a_grid/readme.md b/src/main/java/g3901_4000/s3989_maximum_consistent_columns_in_a_grid/readme.md new file mode 100644 index 000000000..32e6cfbb6 --- /dev/null +++ b/src/main/java/g3901_4000/s3989_maximum_consistent_columns_in_a_grid/readme.md @@ -0,0 +1,53 @@ +3989\. Maximum Consistent Columns in a Grid + +Hard + +You are given a 2D integer array `grid` of size `m x n`, and an integer `limit`. + +You may remove zero or more columns from the grid, but at least one column must remain. The **relative** order of the remaining columns must be preserved. + +A grid is called **consistent** if for every row `i`, and for every pair of adjacent remaining columns `a` and `b` with `a < b`, the following holds: `|grid[i][b] - grid[i][a]| <= limit`. + +Return the **maximum** number of columns that can remain such that the resulting grid is **consistent**. + +**Example 1:** + +**Input:** grid = [[-2,0,3]], limit = 2 + +**Output:** 2 + +**Explanation:** + +* Remove column 2 and keep columns 0 and 1, which gives `|grid[0][1] − grid[0][0]| = |0 − (−2)| = 2 <= limit`. +* Thus, the maximum number of columns that can remain is 2. + +**Example 2:** + +**Input:** grid = [[1,-1,1],[2,2,2]], limit = 1 + +**Output:** 2 + +**Explanation:** + +* Remove column 1 and keep columns 0 and 2, which gives + * `|grid[0][2] − grid[0][0]| = |1 − 1| = 0 <= limit` and + * `|grid[1][2] − grid[1][0]| = |2 − 2| = 0 <= limit`. +* Thus, the maximum number of columns that can remain is 2. + +**Example 3:** + +**Input:** grid = [[-5,5]], limit = 9 + +**Output:** 1 + +**Explanation:** + +* Remove either column 0 or column 1, since `|grid[0][1] − grid[0][0]| = |5 − (−5)| = 10 > limit`. +* Thus, the maximum number of columns that can remain is 1. + +**Constraints:** + +* `1 <= m == grid.length <= 250` +* `1 <= n == grid[i].length <= 250` +* -105 <= grid[i][j] <= 105 +* 0 <= limit <= 105 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3992_rearrange_string_to_avoid_character_pair/Solution.java b/src/main/java/g3901_4000/s3992_rearrange_string_to_avoid_character_pair/Solution.java new file mode 100644 index 000000000..946fa2f26 --- /dev/null +++ b/src/main/java/g3901_4000/s3992_rearrange_string_to_avoid_character_pair/Solution.java @@ -0,0 +1,21 @@ +package g3901_4000.s3992_rearrange_string_to_avoid_character_pair; + +// #Easy #String #Sorting #Two_Pointers #Mid_Level #Biweekly_Contest_187 +// #2026_11_03_Time_2_ms_(78.07%)_Space_44.54_MB_(91.27%) + +@SuppressWarnings("java:S1172") +public class Solution { + public String rearrangeString(String s, char x, char y) { + char[] arr = s.toCharArray(); + int i = 0; + for (int j = 0; j < arr.length; j++) { + if (arr[j] == y) { + char temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + i++; + } + } + return new String(arr); + } +} diff --git a/src/main/java/g3901_4000/s3992_rearrange_string_to_avoid_character_pair/readme.md b/src/main/java/g3901_4000/s3992_rearrange_string_to_avoid_character_pair/readme.md new file mode 100644 index 000000000..4603d4fd0 --- /dev/null +++ b/src/main/java/g3901_4000/s3992_rearrange_string_to_avoid_character_pair/readme.md @@ -0,0 +1,49 @@ +3992\. Rearrange String to Avoid Character Pair + +Easy + +You are given a string `s` and two distinct lowercase English letters `x` and `y`. + +Rearrange the characters of `s` to construct a new string `t` such that: + +* `t` is a permutation of `s`. +* Every occurrence of `y` appears before every occurrence of `x` in `t`. + +Return any valid string `t`. + +**Example 1:** + +**Input:** s = "aabc", x = "a", y = "c" + +**Output:** "cbaa" + +**Explanation:** + +The string `"cbaa"` is a permutation of `"aabc"`, and every occurrence of `'c'` appears before every occurrence of `'a'`. + +**Example 2:** + +**Input:** s = "dcab", x = "d", y = "b" + +**Output:** "cabd" + +**Explanation:** + +The string `"cabd"` is a permutation of `"dcab"`, and every occurrence of `'b'` appears before every occurrence of `'d'`. + +**Example 3:** + +**Input:** s = "axe", x = "o", y = "x" + +**Output:** "axe" + +**Explanation:** + +The string `"axe"` is already valid. Since `'o'` does not occur in the string, the required condition is automatically satisfied. + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` consists of lowercase English letters. +* `x` and `y` are lowercase English letters. +* `x != y` \ No newline at end of file diff --git a/src/test/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/SolutionTest.java b/src/test/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/SolutionTest.java new file mode 100644 index 000000000..14e0ac03e --- /dev/null +++ b/src/test/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3969_valid_subarrays_with_matching_sum_digits_i; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void countValidSubarrays() { + assertThat(new Solution().countValidSubarrays(new int[] {1, 100, 1}, 1), equalTo(4)); + } + + @Test + void countValidSubarrays2() { + assertThat(new Solution().countValidSubarrays(new int[] {1}, 2), equalTo(0)); + } + + @Test + void countValidSubarrays3() { + assertThat(new Solution().countValidSubarrays(new int[] {2, 20, 2}, 2), equalTo(4)); + } +} diff --git a/src/test/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/SolutionTest.java b/src/test/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/SolutionTest.java new file mode 100644 index 000000000..412604a66 --- /dev/null +++ b/src/test/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/SolutionTest.java @@ -0,0 +1,31 @@ +package g3901_4000.s3970_shortest_path_with_at_most_k_consecutive_identical_characters; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void shortestPath() { + assertThat( + new Solution() + .shortestPath(3, new int[][] {{0, 1, 1}, {1, 2, 1}, {0, 2, 3}}, "aab", 1), + equalTo(3)); + } + + @Test + void shortestPath2() { + assertThat( + new Solution() + .shortestPath(3, new int[][] {{0, 1, 1}, {1, 2, 1}, {0, 2, 3}}, "aab", 2), + equalTo(2)); + } + + @Test + void shortestPath3() { + assertThat( + new Solution().shortestPath(3, new int[][] {{0, 1, 1}, {1, 2, 1}}, "aaa", 2), + equalTo(-1)); + } +} diff --git a/src/test/java/g3901_4000/s3971_maximum_total_value/SolutionTest.java b/src/test/java/g3901_4000/s3971_maximum_total_value/SolutionTest.java new file mode 100644 index 000000000..091978c80 --- /dev/null +++ b/src/test/java/g3901_4000/s3971_maximum_total_value/SolutionTest.java @@ -0,0 +1,27 @@ +package g3901_4000.s3971_maximum_total_value; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maxTotalValue() { + assertThat( + new Solution().maxTotalValue(new int[] {6, 5, 4}, new int[] {2, 1, 1}, 4), + equalTo(19)); + } + + @Test + void maxTotalValue2() { + assertThat( + new Solution().maxTotalValue(new int[] {7, 2, 2}, new int[] {3, 2, 1}, 2), + equalTo(11)); + } + + @Test + void maxTotalValue3() { + assertThat(new Solution().maxTotalValue(new int[] {4, 3}, new int[] {5, 4}, 5), equalTo(7)); + } +} diff --git a/src/test/java/g3901_4000/s3974_maximum_total_sum_of_k_selected_elements/SolutionTest.java b/src/test/java/g3901_4000/s3974_maximum_total_sum_of_k_selected_elements/SolutionTest.java new file mode 100644 index 000000000..217ce8e10 --- /dev/null +++ b/src/test/java/g3901_4000/s3974_maximum_total_sum_of_k_selected_elements/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3974_maximum_total_sum_of_k_selected_elements; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maxSum() { + assertThat(new Solution().maxSum(new int[] {6, 1, 2, 9}, 3, 2), equalTo(26L)); + } + + @Test + void maxSum2() { + assertThat(new Solution().maxSum(new int[] {3, 7, 5, 2}, 2, 4), equalTo(43L)); + } + + @Test + void maxSum3() { + assertThat(new Solution().maxSum(new int[] {4, 4}, 1, 1), equalTo(4L)); + } +} diff --git a/src/test/java/g3901_4000/s3975_filter_occupied_intervals/SolutionTest.java b/src/test/java/g3901_4000/s3975_filter_occupied_intervals/SolutionTest.java new file mode 100644 index 000000000..f1fe0bd81 --- /dev/null +++ b/src/test/java/g3901_4000/s3975_filter_occupied_intervals/SolutionTest.java @@ -0,0 +1,32 @@ +package g3901_4000.s3975_filter_occupied_intervals; + +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 filterOccupiedIntervals() { + assertThat( + new Solution() + .filterOccupiedIntervals( + new int[][] {{2, 6}, {4, 8}, {10, 10}, {10, 12}, {14, 16}}, 7, 11), + equalTo(List.of(List.of(2, 6), List.of(12, 12), List.of(14, 16)))); + } + + @Test + void filterOccupiedIntervals2() { + assertThat( + new Solution().filterOccupiedIntervals(new int[][] {{1, 5}, {2, 3}}, 3, 8), + equalTo(List.of(List.of(1, 2)))); + } + + @Test + void filterOccupiedIntervals3() { + assertThat( + new Solution().filterOccupiedIntervals(new int[][] {{1, 2}, {4, 5}}, 1, 5), + equalTo(List.of())); + } +} diff --git a/src/test/java/g3901_4000/s3976_maximum_subarray_sum_after_multiplier/SolutionTest.java b/src/test/java/g3901_4000/s3976_maximum_subarray_sum_after_multiplier/SolutionTest.java new file mode 100644 index 000000000..d17ed08c8 --- /dev/null +++ b/src/test/java/g3901_4000/s3976_maximum_subarray_sum_after_multiplier/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3976_maximum_subarray_sum_after_multiplier; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maxSubarraySum() { + assertThat(new Solution().maxSubarraySum(new int[] {1, -2, 3, 4, -5}, 2), equalTo(14L)); + } + + @Test + void maxSubarraySum2() { + assertThat(new Solution().maxSubarraySum(new int[] {-5, -4, -3}, 2), equalTo(-1L)); + } + + @Test + void maxSubarraySum3() { + assertThat(new Solution().maxSubarraySum(new int[] {1, 2, 3}, 2), equalTo(12L)); + } +} diff --git a/src/test/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/SolutionTest.java b/src/test/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/SolutionTest.java new file mode 100644 index 000000000..88789cc6e --- /dev/null +++ b/src/test/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/SolutionTest.java @@ -0,0 +1,50 @@ +package g3901_4000.s3977_minimum_time_to_reach_target_with_limited_power; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minTimeMaxPower() { + assertThat( + new Solution() + .minTimeMaxPower( + 5, + new int[][] {{0, 1, 1}, {1, 4, 1}, {0, 2, 1}, {2, 3, 1}, {3, 4, 1}}, + 4, + new int[] {2, 3, 1, 1, 1}, + 0, + 4), + equalTo(new long[] {3, 0})); + } + + @Test + void minTimeMaxPower2() { + assertThat( + new Solution() + .minTimeMaxPower( + 3, + new int[][] {{0, 1, 2}, {1, 2, 2}, {2, 0, 2}}, + 3, + new int[] {1, 1, 1}, + 1, + 1), + equalTo(new long[] {0, 3})); + } + + @Test + void minTimeMaxPower3() { + assertThat( + new Solution() + .minTimeMaxPower( + 4, + new int[][] {{0, 1, 3}, {2, 3, 4}}, + 3, + new int[] {1, 1, 1, 1}, + 0, + 3), + equalTo(new long[] {-1, -1})); + } +} diff --git a/src/test/java/g3901_4000/s3978_unique_middle_element/SolutionTest.java b/src/test/java/g3901_4000/s3978_unique_middle_element/SolutionTest.java new file mode 100644 index 000000000..4e98189f4 --- /dev/null +++ b/src/test/java/g3901_4000/s3978_unique_middle_element/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3978_unique_middle_element; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void isMiddleElementUnique() { + assertThat(new Solution().isMiddleElementUnique(new int[] {1, 2, 3}), equalTo(true)); + } + + @Test + void isMiddleElementUnique2() { + assertThat(new Solution().isMiddleElementUnique(new int[] {1, 2, 2}), equalTo(false)); + } + + @Test + void isMiddleElementUnique3() { + assertThat(new Solution().isMiddleElementUnique(new int[] {7}), equalTo(true)); + } +} diff --git a/src/test/java/g3901_4000/s3979_maximum_valid_pair_sum/SolutionTest.java b/src/test/java/g3901_4000/s3979_maximum_valid_pair_sum/SolutionTest.java new file mode 100644 index 000000000..ff381f229 --- /dev/null +++ b/src/test/java/g3901_4000/s3979_maximum_valid_pair_sum/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3979_maximum_valid_pair_sum; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maxValidPairSum() { + assertThat(new Solution().maxValidPairSum(new int[] {1, 3, 5, 2, 8}, 2), equalTo(13)); + } + + @Test + void maxValidPairSum2() { + assertThat(new Solution().maxValidPairSum(new int[] {5, 1, 9}, 1), equalTo(14)); + } + + @Test + void maxValidPairSum3() { + assertThat(new Solution().maxValidPairSum(new int[] {9, 1, 1, 8}, 3), equalTo(17)); + } +} diff --git a/src/test/java/g3901_4000/s3980_minimum_operations_to_transform_binary_string/SolutionTest.java b/src/test/java/g3901_4000/s3980_minimum_operations_to_transform_binary_string/SolutionTest.java new file mode 100644 index 000000000..517748423 --- /dev/null +++ b/src/test/java/g3901_4000/s3980_minimum_operations_to_transform_binary_string/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3980_minimum_operations_to_transform_binary_string; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minOperations() { + assertThat(new Solution().minOperations("11", "00"), equalTo(1)); + } + + @Test + void minOperations2() { + assertThat(new Solution().minOperations("01", "10"), equalTo(3)); + } + + @Test + void minOperations3() { + assertThat(new Solution().minOperations("1", "0"), equalTo(-1)); + } +} diff --git a/src/test/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/SolutionTest.java b/src/test/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/SolutionTest.java new file mode 100644 index 000000000..ecd58feb1 --- /dev/null +++ b/src/test/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/SolutionTest.java @@ -0,0 +1,28 @@ +package g3901_4000.s3981_count_distinct_ways_to_form_target_from_two_strings; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void interleaveCharacters() { + assertThat(new Solution().interleaveCharacters("abc", "bac", "abc"), equalTo(5)); + } + + @Test + void interleaveCharacters2() { + assertThat(new Solution().interleaveCharacters("cd", "cd", "ccd"), equalTo(4)); + } + + @Test + void interleaveCharacters3() { + assertThat(new Solution().interleaveCharacters("xy", "xy", "xyxy"), equalTo(2)); + } + + @Test + void interleaveCharacters4() { + assertThat(new Solution().interleaveCharacters("ab", "cde", "ace"), equalTo(1)); + } +} diff --git a/src/test/java/g3901_4000/s3982_sum_of_integers_with_maximum_digit_range/SolutionTest.java b/src/test/java/g3901_4000/s3982_sum_of_integers_with_maximum_digit_range/SolutionTest.java new file mode 100644 index 000000000..dbf50c71f --- /dev/null +++ b/src/test/java/g3901_4000/s3982_sum_of_integers_with_maximum_digit_range/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3982_sum_of_integers_with_maximum_digit_range; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maxDigitRange() { + assertThat(new Solution().maxDigitRange(new int[] {5724, 111, 350}), equalTo(6074)); + } + + @Test + void maxDigitRange2() { + assertThat(new Solution().maxDigitRange(new int[] {90, 900}), equalTo(990)); + } + + @Test + void maxDigitRange3() { + assertThat(new Solution().maxDigitRange(new int[] {11, 22, 33}), equalTo(66)); + } +} diff --git a/src/test/java/g3901_4000/s3983_subsequence_after_one_replacement/SolutionTest.java b/src/test/java/g3901_4000/s3983_subsequence_after_one_replacement/SolutionTest.java new file mode 100644 index 000000000..81fbaf0b2 --- /dev/null +++ b/src/test/java/g3901_4000/s3983_subsequence_after_one_replacement/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3983_subsequence_after_one_replacement; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void canMakeSubsequence() { + assertThat(new Solution().canMakeSubsequence("cat", "chat"), equalTo(true)); + } + + @Test + void canMakeSubsequence2() { + assertThat(new Solution().canMakeSubsequence("plane", "apple"), equalTo(false)); + } + + @Test + void canMakeSubsequence3() { + assertThat(new Solution().canMakeSubsequence("abc", "abc"), equalTo(true)); + } +} diff --git a/src/test/java/g3901_4000/s3984_divisible_game/SolutionTest.java b/src/test/java/g3901_4000/s3984_divisible_game/SolutionTest.java new file mode 100644 index 000000000..21d0277ed --- /dev/null +++ b/src/test/java/g3901_4000/s3984_divisible_game/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3984_divisible_game; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void divisibleGame() { + assertThat(new Solution().divisibleGame(new int[] {1, 4, 6, 8}), equalTo(36)); + } + + @Test + void divisibleGame2() { + assertThat(new Solution().divisibleGame(new int[] {2, 1, 2}), equalTo(6)); + } + + @Test + void divisibleGame3() { + assertThat(new Solution().divisibleGame(new int[] {1}), equalTo(1000000005)); + } +} diff --git a/src/test/java/g3901_4000/s3985_palindromic_subarray_sum/SolutionTest.java b/src/test/java/g3901_4000/s3985_palindromic_subarray_sum/SolutionTest.java new file mode 100644 index 000000000..b2d66faf0 --- /dev/null +++ b/src/test/java/g3901_4000/s3985_palindromic_subarray_sum/SolutionTest.java @@ -0,0 +1,33 @@ +package g3901_4000.s3985_palindromic_subarray_sum; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void getSum() { + assertThat(new Solution().getSum(new int[] {10, 10}), equalTo(20L)); + } + + @Test + void getSum2() { + assertThat(new Solution().getSum(new int[] {1, 2, 3, 2, 1, 5, 6}), equalTo(9L)); + } + + @Test + void getSum3() { + assertThat(new Solution().getSum(new int[] {7, 1, 2, 1, 7, 3, 4, 3, 4}), equalTo(18L)); + } + + @Test + void getSum4() { + assertThat(new Solution().getSum(new int[] {1, 2, 3, 4, 5}), equalTo(5L)); + } + + @Test + void getSum5() { + assertThat(new Solution().getSum(new int[] {1000}), equalTo(1000L)); + } +} diff --git a/src/test/java/g3901_4000/s3986_number_of_elapsed_seconds_between_two_times/SolutionTest.java b/src/test/java/g3901_4000/s3986_number_of_elapsed_seconds_between_two_times/SolutionTest.java new file mode 100644 index 000000000..9905cca68 --- /dev/null +++ b/src/test/java/g3901_4000/s3986_number_of_elapsed_seconds_between_two_times/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3986_number_of_elapsed_seconds_between_two_times; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void secondsBetweenTimes() { + assertThat(new Solution().secondsBetweenTimes("01:00:00", "01:00:25"), equalTo(25)); + } + + @Test + void secondsBetweenTimes2() { + assertThat(new Solution().secondsBetweenTimes("12:34:56", "13:00:00"), equalTo(1504)); + } + + @Test + void secondsBetweenTimes3() { + assertThat(new Solution().secondsBetweenTimes("00:00:00", "00:00:00"), equalTo(0)); + } +} diff --git a/src/test/java/g3901_4000/s3987_minimum_total_cost_to_process_all_elements/SolutionTest.java b/src/test/java/g3901_4000/s3987_minimum_total_cost_to_process_all_elements/SolutionTest.java new file mode 100644 index 000000000..214001e91 --- /dev/null +++ b/src/test/java/g3901_4000/s3987_minimum_total_cost_to_process_all_elements/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3987_minimum_total_cost_to_process_all_elements; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minimumCost() { + assertThat(new Solution().minimumCost(new int[] {1, 2, 3, 4}, 4), equalTo(3)); + } + + @Test + void minimumCost2() { + assertThat(new Solution().minimumCost(new int[] {1, 1, 7, 14}, 4), equalTo(15)); + } + + @Test + void minimumCost3() { + assertThat(new Solution().minimumCost(new int[] {1, 2, 3, 4}, 10), equalTo(0)); + } +} diff --git a/src/test/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/SolutionTest.java b/src/test/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/SolutionTest.java new file mode 100644 index 000000000..67dc11ade --- /dev/null +++ b/src/test/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/SolutionTest.java @@ -0,0 +1,28 @@ +package g3901_4000.s3988_create_grid_with_exactly_k_paths_i; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void createGrid() { + assertThat(new Solution().createGrid(2, 3, 2), equalTo(new String[] {"..#", "..."})); + } + + @Test + void createGrid2() { + assertThat(new Solution().createGrid(3, 3, 4), equalTo(new String[] {"..#", "...", "#.."})); + } + + @Test + void createGrid3() { + assertThat(new Solution().createGrid(1, 4, 2), equalTo(new String[] {})); + } + + @Test + void createGrid4() { + assertThat(new Solution().createGrid(2, 3, 1), equalTo(new String[] {".##", "..."})); + } +} diff --git a/src/test/java/g3901_4000/s3989_maximum_consistent_columns_in_a_grid/SolutionTest.java b/src/test/java/g3901_4000/s3989_maximum_consistent_columns_in_a_grid/SolutionTest.java new file mode 100644 index 000000000..4e1c7666d --- /dev/null +++ b/src/test/java/g3901_4000/s3989_maximum_consistent_columns_in_a_grid/SolutionTest.java @@ -0,0 +1,25 @@ +package g3901_4000.s3989_maximum_consistent_columns_in_a_grid; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maxConsistentColumns() { + assertThat(new Solution().maxConsistentColumns(new int[][] {{-2, 0, 3}}, 2), equalTo(2)); + } + + @Test + void maxConsistentColumns2() { + assertThat( + new Solution().maxConsistentColumns(new int[][] {{1, -1, 1}, {2, 2, 2}}, 1), + equalTo(2)); + } + + @Test + void maxConsistentColumns3() { + assertThat(new Solution().maxConsistentColumns(new int[][] {{-5, 5}}, 9), equalTo(1)); + } +} diff --git a/src/test/java/g3901_4000/s3992_rearrange_string_to_avoid_character_pair/SolutionTest.java b/src/test/java/g3901_4000/s3992_rearrange_string_to_avoid_character_pair/SolutionTest.java new file mode 100644 index 000000000..d19937bf6 --- /dev/null +++ b/src/test/java/g3901_4000/s3992_rearrange_string_to_avoid_character_pair/SolutionTest.java @@ -0,0 +1,23 @@ +package g3901_4000.s3992_rearrange_string_to_avoid_character_pair; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void rearrangeString() { + assertThat(new Solution().rearrangeString("aabc", 'a', 'c'), equalTo("caba")); + } + + @Test + void rearrangeString2() { + assertThat(new Solution().rearrangeString("dcab", 'd', 'b'), equalTo("bcad")); + } + + @Test + void rearrangeString3() { + assertThat(new Solution().rearrangeString("axe", 'o', 'x'), equalTo("xae")); + } +} From c04f7a4a05d71294a19d8d6ebb7ce8e7a2a2b38d Mon Sep 17 00:00:00 2001 From: ThanhNIT Date: Wed, 4 Nov 2026 00:04:44 +0700 Subject: [PATCH 02/12] Update Solution.java --- .../Solution.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/Solution.java b/src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/Solution.java index e67477989..50de98b82 100644 --- a/src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/Solution.java +++ b/src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/Solution.java @@ -29,7 +29,7 @@ public int countValidSubarrays(int[] nums, int x) { if (i > 0) { long k = pre[i]; int r = (int) (((k - x) % 10 + 10) % 10); - List list = isit[r]; + List list = isit[r]; for (long[] j : interval) { long a = k - j[1]; long b = k - j[0]; @@ -53,7 +53,9 @@ private int lower(List list, long k) { int m = (l + h) >>> 1; if (list.get(m) < k) { l = m + 1; - } else h = m; + } else { + h = m; + } } return l; } From c1c44b8c18e8343de43ff98535140a96d3baf6bc Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 3 Nov 2026 19:16:44 +0200 Subject: [PATCH 03/12] Refactor graph and heap logic in Solution.java --- .../Solution.java | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/src/main/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/Solution.java b/src/main/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/Solution.java index e8e4c6f8c..c7c593eb7 100644 --- a/src/main/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/Solution.java +++ b/src/main/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/Solution.java @@ -14,15 +14,12 @@ private static class Graph { Graph(int n, int[][] edges) { int m = edges.length; - head = new int[n]; next = new int[m + 1]; to = new int[m + 1]; time = new int[m + 1]; - for (int i = 0; i < m; i++) { int u = edges[i][0]; - to[i + 1] = edges[i][1]; time[i + 1] = edges[i][2]; next[i + 1] = head[u]; @@ -39,47 +36,35 @@ void push(long value) { if (++size == heap.length) { heap = Arrays.copyOf(heap, heap.length << 1); } - int j = size; - while (j > 1) { int p = j >>> 1; - if (heap[p] <= value) { break; } - heap[j] = heap[p]; j = p; } - heap[j] = value; } long pop() { long result = heap[1]; long val = heap[size--]; - int i = 1; - while ((i << 1) <= size) { int left = i << 1; int right = left + 1; - int min = right <= size && heap[right] < heap[left] ? right : left; - if (val <= heap[min]) { break; } - heap[i] = heap[min]; i = min; } - if (size > 0) { heap[i] = val; } - return result; } @@ -121,7 +106,6 @@ private void addNeighbors( for (int e = graph.head[u]; e != 0; e = graph.next[e]) { long nextPacked = ((currTime + graph.time[e]) << 22) | (nextPowerComp << 11) | graph.to[e]; - pq.push(nextPacked); } } From 97510cc5313e3797879f83e48e0c39b3211c75df Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 3 Nov 2026 19:19:31 +0200 Subject: [PATCH 04/12] Refactor expandOdd and expandEven methods --- .../g3901_4000/s3985_palindromic_subarray_sum/Solution.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/g3901_4000/s3985_palindromic_subarray_sum/Solution.java b/src/main/java/g3901_4000/s3985_palindromic_subarray_sum/Solution.java index 7e38d0fc1..ed864ad3e 100644 --- a/src/main/java/g3901_4000/s3985_palindromic_subarray_sum/Solution.java +++ b/src/main/java/g3901_4000/s3985_palindromic_subarray_sum/Solution.java @@ -38,7 +38,6 @@ private long calculateOdd(int[] nums, long[] prefix) { r = right; } } - return ans; } @@ -70,7 +69,6 @@ private long calculateEven(int[] nums, long[] prefix) { } } } - return ans; } @@ -78,7 +76,6 @@ private int expandEven(int[] nums, int i, int k) { while (i - k - 1 >= 0 && i + k < nums.length && nums[i - k - 1] == nums[i + k]) { k++; } - return k; } From 7a32c0d164196703404170e292be0bb44876cbd4 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 3 Nov 2026 19:22:17 +0200 Subject: [PATCH 05/12] Fix condition check for adding next city to priority queue --- .../Solution.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/Solution.java b/src/main/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/Solution.java index 8b8b0bb1d..791ad1b55 100644 --- a/src/main/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/Solution.java +++ b/src/main/java/g3901_4000/s3970_shortest_path_with_at_most_k_consecutive_identical_characters/Solution.java @@ -55,7 +55,6 @@ private void addNeighbors( int totalCh = getNextCharCount(nd.ch, labels[nd.city], labels[nextCity]); if (nd.city != nextCity && totalCh <= k) { long totalWeight = nd.w + nbr[1]; - pq.add(new Node(nextCity, totalWeight, totalCh)); } } From ce06d78252fa996572bafed9227c51250015683c Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 3 Nov 2026 19:24:58 +0200 Subject: [PATCH 06/12] Fix logic for adding free intervals in Solution.java --- .../g3901_4000/s3975_filter_occupied_intervals/Solution.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/g3901_4000/s3975_filter_occupied_intervals/Solution.java b/src/main/java/g3901_4000/s3975_filter_occupied_intervals/Solution.java index cfc49a648..8ed7dccc2 100644 --- a/src/main/java/g3901_4000/s3975_filter_occupied_intervals/Solution.java +++ b/src/main/java/g3901_4000/s3975_filter_occupied_intervals/Solution.java @@ -21,7 +21,6 @@ public List> filterOccupiedIntervals( if (first < freeStart) { intervals.add(new int[] {first, freeStart - 1}); } - if (second > freeEnd) { intervals.add(new int[] {freeEnd + 1, second}); } From 0271a40b9f8b6d39c18d777c218daf7823cf42bd Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 3 Nov 2026 19:27:15 +0200 Subject: [PATCH 07/12] Refactor DP array swapping in Solution.java --- .../Solution.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/Solution.java b/src/main/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/Solution.java index fdd2279b5..edc7fe381 100644 --- a/src/main/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/Solution.java +++ b/src/main/java/g3901_4000/s3981_count_distinct_ways_to_form_target_from_two_strings/Solution.java @@ -24,7 +24,6 @@ public int interleaveCharacters(String word1, String word2, String target) { updateMatches(word2, m2, tc); calculateS1(s1, dp, m1, wl1, wl2); calculateS2(s2, s1, nextDp, dp, m2, wl1, wl2); - int[][] temp = dp; dp = nextDp; nextDp = temp; From 2df3a4646a5913b5552f54c4f2d596bc422d6361 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 3 Nov 2026 19:29:36 +0200 Subject: [PATCH 08/12] Refactor createGrid method in Solution class --- .../s3988_create_grid_with_exactly_k_paths_i/Solution.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/Solution.java b/src/main/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/Solution.java index fa86751cd..8efec2c94 100644 --- a/src/main/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/Solution.java +++ b/src/main/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/Solution.java @@ -6,7 +6,6 @@ import java.util.Arrays; public class Solution { - public String[] createGrid(int m, int n, int k) { int[] dimensions = getDimensions(m, n, k); if (dimensions.length == 0) { @@ -15,7 +14,6 @@ public String[] createGrid(int m, int n, int k) { int dm = dimensions[0]; int dn = dimensions[1]; char[][] grid = initializeGrid(m, n); - createRequiredPaths(grid, dm, dn); addObstacles(grid, dm, dn, k); connectRemainingGrid(grid, m, n, dm, dn); From 1ed624592c5ff2e68e1acd0c956b3b8b8bcc9a54 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Wed, 4 Nov 2026 00:23:40 +0200 Subject: [PATCH 09/12] Add SuppressWarnings annotation to Solution class --- .../Solution.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/Solution.java b/src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/Solution.java index 50de98b82..6de2ad683 100644 --- a/src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/Solution.java +++ b/src/main/java/g3901_4000/s3969_valid_subarrays_with_matching_sum_digits_i/Solution.java @@ -6,6 +6,7 @@ import java.util.ArrayList; import java.util.List; +@SuppressWarnings("unchecked") public class Solution { public int countValidSubarrays(int[] nums, int x) { int n = nums.length; From 00aa151fe57050397c84b2104de94180ba02f08f Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Wed, 4 Nov 2026 11:08:11 +0200 Subject: [PATCH 10/12] Added tests --- .../SolutionTest.java | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) diff --git a/src/test/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/SolutionTest.java b/src/test/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/SolutionTest.java index 67dc11ade..c7b064875 100644 --- a/src/test/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/SolutionTest.java +++ b/src/test/java/g3901_4000/s3988_create_grid_with_exactly_k_paths_i/SolutionTest.java @@ -25,4 +25,102 @@ void createGrid3() { void createGrid4() { assertThat(new Solution().createGrid(2, 3, 1), equalTo(new String[] {".##", "..."})); } + + @Test + void createGrid5() { + // Single cell, k = 1 + assertThat(new Solution().createGrid(1, 1, 1), equalTo(new String[] {"."})); + } + + @Test + void createGrid6() { + // Single row, k = 1 -> only horizontal connection + assertThat(new Solution().createGrid(1, 5, 1), equalTo(new String[] {"....."})); + } + + @Test + void createGrid7() { + // Single column, k = 1 -> only vertical connection + assertThat(new Solution().createGrid(4, 1, 1), equalTo(new String[] {".", ".", ".", "."})); + } + + @Test + void createGrid8() { + // k = 3, m >= 3 && n >= 2 -> dimensions {2, 1}, whole grid open + assertThat(new Solution().createGrid(3, 2, 3), equalTo(new String[] {"..", "..", ".."})); + } + + @Test + void createGrid9() { + // k = 3, m < 3 but n >= 3 -> dimensions {1, 2}, whole grid open + assertThat(new Solution().createGrid(2, 3, 3), equalTo(new String[] {"...", "..."})); + } + + @Test + void createGrid10() { + // k = 3 on larger grid -> dimensions {2, 1} plus connection to bottom-right + assertThat( + new Solution().createGrid(4, 4, 3), + equalTo(new String[] {"..##", "..##", "..##", "#..."})); + } + + @Test + void createGrid11() { + // k = 3 impossible on 2x2 grid + assertThat(new Solution().createGrid(2, 2, 3), equalTo(new String[] {})); + } + + @Test + void createGrid12() { + // k = 4, m >= 4 && n >= 2 -> dimensions {3, 1} + assertThat( + new Solution().createGrid(4, 2, 4), equalTo(new String[] {"..", "..", "..", ".."})); + } + + @Test + void createGrid13() { + // k = 4, m < 4 but n >= 4 -> dimensions {1, 3} + assertThat(new Solution().createGrid(2, 4, 4), equalTo(new String[] {"....", "...."})); + } + + @Test + void createGrid14() { + // k = 4 on 5x5 grid -> dimensions {3, 1} plus connection + assertThat( + new Solution().createGrid(5, 5, 4), + equalTo(new String[] {"..###", "..###", "..###", "..###", "#...."})); + } + + @Test + void createGrid15() { + // k = 4 with dimensions {1, 3} and a vertical connection + assertThat( + new Solution().createGrid(3, 4, 4), equalTo(new String[] {"....", "....", "###."})); + } + + @Test + void createGrid16() { + // k = 4 impossible on 2x2 grid + assertThat(new Solution().createGrid(2, 2, 4), equalTo(new String[] {})); + } + + @Test + void createGrid17() { + // k = 2 on 3x5 grid -> dimensions {1, 1} plus connection + assertThat( + new Solution().createGrid(3, 5, 2), + equalTo(new String[] {"..###", "..###", "#...."})); + } + + @Test + void createGrid18() { + // Unsupported k (> 4) + assertThat(new Solution().createGrid(3, 3, 5), equalTo(new String[] {})); + } + + @Test + void createGrid19() { + // Unsupported k (0) + assertThat(new Solution().createGrid(3, 3, 0), equalTo(new String[] {})); + } } From 124c4a3611efacb235c1a6926ecf375410122caa Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Wed, 4 Nov 2026 17:10:28 +0200 Subject: [PATCH 11/12] Added tests --- .../SolutionTest.java | 117 ++++++++++++++++++ 1 file changed, 117 insertions(+) diff --git a/src/test/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/SolutionTest.java b/src/test/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/SolutionTest.java index 88789cc6e..9339855ce 100644 --- a/src/test/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/SolutionTest.java +++ b/src/test/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/SolutionTest.java @@ -47,4 +47,121 @@ void minTimeMaxPower3() { 3), equalTo(new long[] {-1, -1})); } + + @Test + void minTimeMaxPower4() { + // Single node, source == target, cost of source is never paid + assertThat( + new Solution().minTimeMaxPower(1, new int[][] {}, 5, new int[] {10}, 0, 0), + equalTo(new long[] {0, 5})); + } + + @Test + void minTimeMaxPower5() { + // Simple chain 0 -> 1 -> 2, costs paid at 0 and 1 + assertThat( + new Solution() + .minTimeMaxPower( + 3, + new int[][] {{0, 1, 2}, {1, 2, 3}}, + 10, + new int[] {3, 4, 100}, + 0, + 2), + equalTo(new long[] {5, 3})); + } + + @Test + void minTimeMaxPower6() { + // Not enough power to leave the source + assertThat( + new Solution() + .minTimeMaxPower(2, new int[][] {{0, 1, 1}}, 1, new int[] {2, 0}, 0, 1), + equalTo(new long[] {-1, -1})); + } + + @Test + void minTimeMaxPower7() { + // Two paths with equal time, the one with more remaining power wins + assertThat( + new Solution() + .minTimeMaxPower( + 4, + new int[][] {{0, 1, 1}, {0, 2, 1}, {1, 3, 1}, {2, 3, 1}}, + 10, + new int[] {1, 5, 2, 0}, + 0, + 3), + equalTo(new long[] {2, 7})); + } + + @Test + void minTimeMaxPower8() { + // Faster path is blocked by a high cost node, slower path is used + assertThat( + new Solution() + .minTimeMaxPower( + 4, + new int[][] {{0, 1, 1}, {1, 3, 1}, {0, 2, 2}, {2, 3, 2}}, + 5, + new int[] {1, 10, 1, 0}, + 0, + 3), + equalTo(new long[] {4, 3})); + } + + @Test + void minTimeMaxPower9() { + // Minimum time takes priority over maximum power + assertThat( + new Solution() + .minTimeMaxPower( + 4, + new int[][] {{0, 1, 1}, {1, 3, 1}, {0, 2, 5}, {2, 3, 5}}, + 10, + new int[] {0, 9, 0, 0}, + 0, + 3), + equalTo(new long[] {2, 1})); + } + + @Test + void minTimeMaxPower10() { + // Edges are directed: reverse edge does not make target reachable + assertThat( + new Solution() + .minTimeMaxPower(2, new int[][] {{1, 0, 1}}, 5, new int[] {0, 0}, 0, 1), + equalTo(new long[] {-1, -1})); + } + + @Test + void minTimeMaxPower11() { + // Zero power and zero costs: travel still possible + assertThat( + new Solution() + .minTimeMaxPower( + 3, + new int[][] {{0, 1, 4}, {1, 2, 6}}, + 0, + new int[] {0, 0, 0}, + 0, + 2), + equalTo(new long[] {10, 0})); + } + + @Test + void minTimeMaxPower12() { + // Node 1 is first reached early with too little power, + // then revisited later with more power, which allows reaching the target + assertThat( + new Solution() + .minTimeMaxPower( + 5, + new int[][] {{0, 2, 1}, {2, 1, 1}, {0, 3, 1}, {3, 1, 2}, {1, 4, 1}}, + 6, + new int[] {0, 3, 5, 0, 0}, + 0, + 4), + equalTo(new long[] {4, 3})); + } } From 1e165c4581585fa29ce27b4f7ff3c39bd4b6900f Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Wed, 4 Nov 2026 17:19:42 +0200 Subject: [PATCH 12/12] Added test --- .../SolutionTest.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/test/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/SolutionTest.java b/src/test/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/SolutionTest.java index 9339855ce..c3f1f6b7f 100644 --- a/src/test/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/SolutionTest.java +++ b/src/test/java/g3901_4000/s3977_minimum_time_to_reach_target_with_limited_power/SolutionTest.java @@ -164,4 +164,23 @@ void minTimeMaxPower12() { 4), equalTo(new long[] {4, 3})); } + + @Test + void minTimeMaxPower13() { + assertThat( + new Solution() + .minTimeMaxPower( + 5, + new int[][] { + {4, 4, 9}, {0, 2, 2}, {4, 1, 1}, {0, 2, 9}, {0, 4, 1}, + {3, 4, 5}, {2, 1, 5}, {0, 0, 6}, {2, 4, 10}, {3, 4, 8}, + {2, 3, 3}, {0, 1, 1}, {4, 0, 5}, {0, 3, 4}, {0, 1, 10}, + {0, 0, 1}, {0, 2, 7}, {2, 0, 10}, {2, 0, 10}, {0, 3, 9} + }, + 5, + new int[] {4, 2, 1, 4, 2}, + 0, + 4), + equalTo(new long[] {1, 1})); + } }