diff --git a/src/main/java/g3801_3900/s3806_maximum_bitwise_and_after_increment_operations/Solution.java b/src/main/java/g3801_3900/s3806_maximum_bitwise_and_after_increment_operations/Solution.java new file mode 100644 index 000000000..6aa7bf61c --- /dev/null +++ b/src/main/java/g3801_3900/s3806_maximum_bitwise_and_after_increment_operations/Solution.java @@ -0,0 +1,40 @@ +package g3801_3900.s3806_maximum_bitwise_and_after_increment_operations; + +// #Hard #Array #Sorting #Greedy #Bit_Manipulation #Senior_Staff #Weekly_Contest_484 +// #2026_06_09_Time_107_ms_(78.72%)_Space_51.33_MB_(44.68%) + +import java.util.Arrays; + +public class Solution { + public int maximumAND(int[] a, int b, int c) { + long e = 0; + int f = a.length; + long[] g = new long[f]; + for (int h = 30; h >= 0; --h) { + long i = e | (1L << h); + for (int j = 0; j < f; ++j) { + long k = a[j]; + long l = i & ~k; + if (l == 0) { + g[j] = 0; + } else { + int n = 63 - Long.numberOfLeadingZeros(l); + while (((k >> n) & 1) == 1) { + n++; + } + long o = (1L << n) - 1; + g[j] = ((k & ~o) | (1L << n) | (i & o)) - k; + } + } + Arrays.sort(g); + long p = 0; + for (int q = 0; q < c; ++q) { + p += g[q]; + } + if (p <= b) { + e = i; + } + } + return (int) e; + } +} diff --git a/src/main/java/g3801_3900/s3806_maximum_bitwise_and_after_increment_operations/readme.md b/src/main/java/g3801_3900/s3806_maximum_bitwise_and_after_increment_operations/readme.md new file mode 100644 index 000000000..0ab3eed7d --- /dev/null +++ b/src/main/java/g3801_3900/s3806_maximum_bitwise_and_after_increment_operations/readme.md @@ -0,0 +1,55 @@ +3806\. Maximum Bitwise AND After Increment Operations + +Hard + +You are given an integer array `nums` and two integers `k` and `m`. + +You may perform **at most** `k` operations. In one operation, you may choose any index `i` and **increase** `nums[i]` by 1. + +Return an integer denoting the **maximum** possible **bitwise AND** of any **subset** of size `m` after performing up to `k` operations optimally. + +**Example 1:** + +**Input:** nums = [3,1,2], k = 8, m = 2 + +**Output:** 6 + +**Explanation:** + +* We need a subset of size `m = 2`. Choose indices `[0, 2]`. +* Increase `nums[0] = 3` to 6 using 3 operations, and increase `nums[2] = 2` to 6 using 4 operations. +* The total number of operations used is 7, which is not greater than `k = 8`. +* The two chosen values become `[6, 6]`, and their bitwise AND is `6`, which is the maximum possible. + +**Example 2:** + +**Input:** nums = [1,2,8,4], k = 7, m = 3 + +**Output:** 4 + +**Explanation:** + +* We need a subset of size `m = 3`. Choose indices `[0, 1, 3]`. +* Increase `nums[0] = 1` to 4 using 3 operations, increase `nums[1] = 2` to 4 using 2 operations, and keep `nums[3] = 4`. +* The total number of operations used is 5, which is not greater than `k = 7`. +* The three chosen values become `[4, 4, 4]`, and their bitwise AND is 4, which is the maximum possible. + +**Example 3:** + +**Input:** nums = [1,1], k = 3, m = 2 + +**Output:** 2 + +**Explanation:** + +* We need a subset of size `m = 2`. Choose indices `[0, 1]`. +* Increase both values from 1 to 2 using 1 operation each. +* The total number of operations used is 2, which is not greater than `k = 3`. +* The two chosen values become `[2, 2]`, and their bitwise AND is 2, which is the maximum possible. + +**Constraints:** + +* 1 <= n == nums.length <= 5 * 104 +* 1 <= nums[i] <= 109 +* 1 <= k <= 109 +* `1 <= m <= n` \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3808_find_emotionally_consistent_users/readme.md b/src/main/java/g3801_3900/s3808_find_emotionally_consistent_users/readme.md new file mode 100644 index 000000000..c130a328b --- /dev/null +++ b/src/main/java/g3801_3900/s3808_find_emotionally_consistent_users/readme.md @@ -0,0 +1,85 @@ +3808\. Find Emotionally Consistent Users + +Medium + +Table: `reactions` + + +--------------+---------+ + | Column Name | Type | + +--------------+---------+ + | user_id | int | + | content_id | int | + | reaction | varchar | + +--------------+---------+ + +(user_id, content_id) is the primary key (unique value) for this table. +Each row represents a reaction given by a user to a piece of content. + +Write a solution to identify **emotionally consistent users** based on the following requirements: + +* For each user, count the total number of reactions they have given. +* Only include users who have reacted to **at least** `5` **different content items**. +* A user is considered **emotionally consistent** if **at least** `60%` of their reactions are of the **same type**. + +Return _the result table ordered by_ `reaction_ratio` _in **descending** order and then by_ `user_id` _in **ascending** order_. + +**Note:** + +* `reaction_ratio` should be rounded to `2` decimal places + +The result format is in the following example. + +**Example:** + +**Input:** + +reactions table: + + +---------+------------+----------+ + | user_id | content_id | reaction | + +---------+------------+----------+ + | 1 | 101 | like | + | 1 | 102 | like | + | 1 | 103 | like | + | 1 | 104 | wow | + | 1 | 105 | like | + | 2 | 201 | like | + | 2 | 202 | wow | + | 2 | 203 | sad | + | 2 | 204 | like | + | 2 | 205 | wow | + | 3 | 301 | love | + | 3 | 302 | love | + | 3 | 303 | love | + | 3 | 304 | love | + | 3 | 305 | love | + +---------+------------+----------+ + +**Output:** + + +---------+-------------------+----------------+ + | user_id | dominant_reaction | reaction_ratio | + +---------+-------------------+----------------+ + | 3 | love | 1.00 | + | 1 | like | 0.80 | + +---------+-------------------+----------------+ + +**Explanation:** + +* **User 1**: + * Total reactions = 5 + * like appears 4 times + * reaction_ratio = 4 / 5 = 0.80 + * Meets the 60% consistency requirement +* **User 2**: + * Total reactions = 5 + * Most frequent reaction appears only 2 times + * reaction_ratio = 2 / 5 = 0.40 + * Does not meet the consistency requirement +* **User 3**: + * Total reactions = 5 + * 'love' appears 5 times + * reaction_ratio = 5 / 5 = 1.00 + * Meets the consistency requirement + +The Results table is ordered by reaction_ratio in descending order, then by user_id in ascending order. diff --git a/src/main/java/g3801_3900/s3808_find_emotionally_consistent_users/script.sql b/src/main/java/g3801_3900/s3808_find_emotionally_consistent_users/script.sql new file mode 100644 index 000000000..5d388a0a3 --- /dev/null +++ b/src/main/java/g3801_3900/s3808_find_emotionally_consistent_users/script.sql @@ -0,0 +1,50 @@ +# #Medium #2026_06_09_Time_290_ms_(87.69%)_Space_0.0_MB_(100.00%) +# Write your MySQL query statement below +WITH user_selection AS +(SELECT + user_id, + COUNT(reaction) AS total_reaction_count +FROM + reactions +GROUP BY + user_id +HAVING + COUNT(DISTINCT content_id) >= 5 +), +reaction_counts +AS +(SELECT + user_id, + reaction, + COUNT(*) AS reaction_count +FROM +reactions +group by + user_id, + reaction +), +ranked_reactions AS ( + -- Step 2: Use a window function to find the max for each user + SELECT + user_id, + reaction, + reaction_count, + RANK() OVER(PARTITION BY user_id ORDER BY reaction_count DESC) as rnk + FROM reaction_counts +) +SELECT + rc.user_id, + rc.reaction AS dominant_reaction, + ROUND(reaction_count / total_reaction_count, 2) AS reaction_ratio +FROM + ranked_reactions rc +INNER JOIN + user_selection us +ON + rc.user_id = us.user_id +WHERE + rc.rnk = 1 + AND ROUND(reaction_count / total_reaction_count, 2) >= 0.60 +ORDER BY + 3 DESC, + rc.user_id diff --git a/src/main/java/g3801_3900/s3809_best_reachable_tower/Solution.java b/src/main/java/g3801_3900/s3809_best_reachable_tower/Solution.java new file mode 100644 index 000000000..0d0f08e91 --- /dev/null +++ b/src/main/java/g3801_3900/s3809_best_reachable_tower/Solution.java @@ -0,0 +1,30 @@ +package g3801_3900.s3809_best_reachable_tower; + +// #Medium #Array #Senior #Biweekly_Contest_174 +// #2026_06_09_Time_3_ms_(70.30%)_Space_219.56_MB_(26.73%) + +public class Solution { + public int[] bestTower(int[][] towers, int[] center, int radius) { + int bestX = -1; + int bestY = -1; + int bestQ = -1; + int cx = center[0]; + int cy = center[1]; + for (int[] t : towers) { + int x = t[0]; + int y = t[1]; + int q = t[2]; + long dx = Math.abs((long) x - cx); + long dy = Math.abs((long) y - cy); + if (dx + dy <= radius + && (q > bestQ + || (q == bestQ + && (bestX == -1 || x < bestX || (x == bestX && y < bestY))))) { + bestQ = q; + bestX = x; + bestY = y; + } + } + return bestQ == -1 ? new int[] {-1, -1} : new int[] {bestX, bestY}; + } +} diff --git a/src/main/java/g3801_3900/s3809_best_reachable_tower/readme.md b/src/main/java/g3801_3900/s3809_best_reachable_tower/readme.md new file mode 100644 index 000000000..d0e5976eb --- /dev/null +++ b/src/main/java/g3801_3900/s3809_best_reachable_tower/readme.md @@ -0,0 +1,69 @@ +3809\. Best Reachable Tower + +Medium + +You are given a 2D integer array `towers`, where towers[i] = [xi, yi, qi] represents the coordinates (xi, yi) and quality factor qi of the ith tower. + +You are also given an integer array `center = [cx, cy]` representing your location, and an integer `radius`. + +A tower is **reachable** if its **Manhattan distance** from `center` is **less than or equal** to `radius`. + +Among all reachable towers: + +* Return the coordinates of the tower with the **maximum** quality factor. +* If there is a tie, return the tower with the **lexicographically smallest** coordinate. If no tower is reachable, return `[-1, -1]`. + +The **Manhattan Distance** between two cells (xi, yi) and (xj, yj) is |xi - xj| + |yi - yj|. + +A coordinate [xi, yi] is **lexicographically smaller** than [xj, yj] if xi < xj, or xi == xj and yi < yj. + +`|x|` denotes the **absolute** **value** of `x`. + +**Example 1:** + +**Input:** towers = [[1,2,5], [2,1,7], [3,1,9]], center = [1,1], radius = 2 + +**Output:** [3,1] + +**Explanation:** + +* Tower `[1, 2, 5]`: Manhattan distance = `|1 - 1| + |2 - 1| = 1`, reachable. +* Tower `[2, 1, 7]`: Manhattan distance = `|2 - 1| + |1 - 1| = 1`, reachable. +* Tower `[3, 1, 9]`: Manhattan distance = `|3 - 1| + |1 - 1| = 2`, reachable. + +All towers are reachable. The maximum quality factor is 9, which corresponds to tower `[3, 1]`. + +**Example 2:** + +**Input:** towers = [[1,3,4], [2,2,4], [4,4,7]], center = [0,0], radius = 5 + +**Output:** [1,3] + +**Explanation:** + +* Tower `[1, 3, 4]`: Manhattan distance = `|1 - 0| + |3 - 0| = 4`, reachable. +* Tower `[2, 2, 4]`: Manhattan distance = `|2 - 0| + |2 - 0| = 4`, reachable. +* Tower `[4, 4, 7]`: Manhattan distance = `|4 - 0| + |4 - 0| = 8`, not reachable. + +Among the reachable towers, the maximum quality factor is 4. Both `[1, 3]` and `[2, 2]` have the same quality, so the lexicographically smaller coordinate is `[1, 3]`. + +**Example 3:** + +**Input:** towers = [[5,6,8], [0,3,5]], center = [1,2], radius = 1 + +**Output:** [-1,-1] + +**Explanation:** + +* Tower `[5, 6, 8]`: Manhattan distance = `|5 - 1| + |6 - 2| = 8`, not reachable. +* Tower `[0, 3, 5]`: Manhattan distance = `|0 - 1| + |3 - 2| = 2`, not reachable. + +No tower is reachable within the given radius, so `[-1, -1]` is returned. + +**Constraints:** + +* 1 <= towers.length <= 105 +* towers[i] = [xi, yi, qi] +* `center = [cx, cy]` +* 0 <= xi, yi, qi, cx, cy <= 105 +* 0 <= radius <= 105 \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3810_minimum_operations_to_reach_target_array/Solution.java b/src/main/java/g3801_3900/s3810_minimum_operations_to_reach_target_array/Solution.java new file mode 100644 index 000000000..c40419eee --- /dev/null +++ b/src/main/java/g3801_3900/s3810_minimum_operations_to_reach_target_array/Solution.java @@ -0,0 +1,19 @@ +package g3801_3900.s3810_minimum_operations_to_reach_target_array; + +// #Medium #Array #Hash_Table #Greedy #Senior #Biweekly_Contest_174 +// #2026_06_09_Time_24_ms_(89.58%)_Space_123.26_MB_(72.92%) + +import java.util.HashSet; +import java.util.Set; + +public class Solution { + public int minOperations(int[] nums, int[] target) { + Set virelantos = new HashSet<>(); + for (int i = 0; i < nums.length; i++) { + if (nums[i] != target[i]) { + virelantos.add(nums[i]); + } + } + return virelantos.size(); + } +} diff --git a/src/main/java/g3801_3900/s3810_minimum_operations_to_reach_target_array/readme.md b/src/main/java/g3801_3900/s3810_minimum_operations_to_reach_target_array/readme.md new file mode 100644 index 000000000..2a0ea05d6 --- /dev/null +++ b/src/main/java/g3801_3900/s3810_minimum_operations_to_reach_target_array/readme.md @@ -0,0 +1,54 @@ +3810\. Minimum Operations to Reach Target Array + +Medium + +You are given two integer arrays `nums` and `target`, each of length `n`, where `nums[i]` is the current value at index `i` and `target[i]` is the desired value at index `i`. + +You may perform the following operation any number of times (including zero): + +* Choose an integer value `x` +* Find all **maximal contiguous segments** where `nums[i] == x` (a segment is **maximal** if it cannot be extended to the left or right while keeping all values equal to `x`) +* For each such segment `[l, r]`, update **simultaneously**: + * `nums[l] = target[l], nums[l + 1] = target[l + 1], ..., nums[r] = target[r]` + +Return the **minimum** number of operations required to make `nums` equal to `target`. + +**Example 1:** + +**Input:** nums = [1,2,3], target = [2,1,3] + +**Output:** 2 + +**Explanation:** + +* Choose `x = 1`: maximal segment `[0, 0]` updated -> nums becomes `[2, 2, 3]` +* Choose `x = 2`: maximal segment `[0, 1]` updated (`nums[0]` stays 2, `nums[1]` becomes 1) -> `nums` becomes `[2, 1, 3]` +* Thus, 2 operations are required to convert `nums` to `target`. + +**Example 2:** + +**Input:** nums = [4,1,4], target = [5,1,4] + +**Output:** 1 + +**Explanation:** + +* Choose `x = 4`: maximal segments `[0, 0]` and `[2, 2]` updated (`nums[2]` stays 4) -> `nums` becomes `[5, 1, 4]` +* Thus, 1 operation is required to convert `nums` to `target`. + +**Example 3:** + +**Input:** nums = [7,3,7], target = [5,5,9] + +**Output:** 2 + +**Explanation:** + +* Choose `x = 7`: maximal segments `[0, 0]` and `[2, 2]` updated -> `nums` becomes `[5, 3, 9]` +* Choose `x = 3`: maximal segment `[1, 1]` updated -> `nums` becomes `[5, 5, 9]` +* Thus, 2 operations are required to convert `nums` to `target`. + +**Constraints:** + +* 1 <= n == nums.length == target.length <= 105 +* 1 <= nums[i], target[i] <= 105 \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3811_number_of_alternating_xor_partitions/Solution.java b/src/main/java/g3801_3900/s3811_number_of_alternating_xor_partitions/Solution.java new file mode 100644 index 000000000..6e8fd0c1e --- /dev/null +++ b/src/main/java/g3801_3900/s3811_number_of_alternating_xor_partitions/Solution.java @@ -0,0 +1,64 @@ +package g3801_3900.s3811_number_of_alternating_xor_partitions; + +// #Medium #Array #Hash_Table #Dynamic_Programming #Bit_Manipulation #Staff #Biweekly_Contest_174 +// #2026_06_09_Time_5_ms_(100.00%)_Space_93.31_MB_(44.19%) + +public class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int alternatingXOR(int[] nums, int target1, int target2) { + int t1 = 0; + int t2 = 0; + int t3 = 0; + int t4 = 0; + int combXor = target1 ^ target2; + int runningXor = 0; + int ans; + int n = nums.length; + for (int i = 0; i < n; i++) { + int num = nums[i]; + runningXor ^= num; + ans = 0; + if (runningXor == target1) { + ans = t4 + 1; + } + if (runningXor == combXor) { + ans += t1; + } + if (runningXor == target2) { + ans += t2; + } + if (runningXor == 0) { + ans += t3; + } + int ct1 = t1; + int ct2 = t2; + int ct3 = t3; + int ct4 = t4; + if (runningXor == target1) { + ct1 += t4 + 1; + ct1 %= MOD; + } + if (runningXor == combXor) { + ct2 += t1; + ct2 %= MOD; + } + if (runningXor == target2) { + ct3 += t2; + ct3 %= MOD; + } + if (runningXor == 0) { + ct4 += t3; + ct4 %= MOD; + } + t1 = ct1; + t2 = ct2; + t3 = ct3; + t4 = ct4; + if (i == n - 1) { + return ans % MOD; + } + } + return 0; + } +} diff --git a/src/main/java/g3801_3900/s3811_number_of_alternating_xor_partitions/readme.md b/src/main/java/g3801_3900/s3811_number_of_alternating_xor_partitions/readme.md new file mode 100644 index 000000000..fecdd8d6a --- /dev/null +++ b/src/main/java/g3801_3900/s3811_number_of_alternating_xor_partitions/readme.md @@ -0,0 +1,60 @@ +3811\. Number of Alternating XOR Partitions + +Medium + +You are given an integer array `nums` and two **distinct** integers `target1` and `target2`. + +A **partition** of `nums` splits it into one or more **contiguous, non-empty** blocks that cover the entire array without overlap. + +A partition is **valid** if the **bitwise XOR** of elements in its blocks **alternates** between `target1` and `target2`, starting with `target1`. + +Formally, for blocks `b1`, `b2`, …: + +* `XOR(b1) = target1` +* `XOR(b2) = target2` (if it exists) +* `XOR(b3) = target1`, and so on. + +Return the number of valid partitions of `nums`, modulo 109 + 7. + +**Note:** A single block is valid if its **XOR** equals `target1`. + +**Example 1:** + +**Input:** nums = [2,3,1,4], target1 = 1, target2 = 5 + +**Output:** 1 + +**Explanation:** + +* The XOR of `[2, 3]` is 1, which matches `target1`. +* The XOR of the remaining block `[1, 4]` is 5, which matches `target2`. +* This is the only valid alternating partition, so the answer is 1. + +**Example 2:** + +**Input:** nums = [1,0,0], target1 = 1, target2 = 0 + +**Output:** 3 + +**Explanation:** + +* The XOR of `[1, 0, 0]` is 1, which matches `target1`. +* The XOR of `[1]` and `[0, 0]` are 1 and 0, matching `target1` and `target2`. +* The XOR of `[1, 0]` and `[0]` are 1 and 0, matching `target1` and `target2`. +* Thus, the answer is 3. + +**Example 3:** + +**Input:** nums = [7], target1 = 1, target2 = 7 + +**Output:** 0 + +**Explanation:** + +* The XOR of `[7]` is 7, which does not match `target1`, so no valid partition exists. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 0 <= nums[i], target1, target2 <= 105 +* `target1 != target2` \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3812_minimum_edge_toggles_on_a_tree/Solution.java b/src/main/java/g3801_3900/s3812_minimum_edge_toggles_on_a_tree/Solution.java new file mode 100644 index 000000000..fa14dca7b --- /dev/null +++ b/src/main/java/g3801_3900/s3812_minimum_edge_toggles_on_a_tree/Solution.java @@ -0,0 +1,64 @@ +package g3801_3900.s3812_minimum_edge_toggles_on_a_tree; + +// #Hard #Sorting #Tree #Topological_Sort #Senior_Staff #Depth_First_Search #Biweekly_Contest_174 +// #Graph_Theory #2026_06_09_Time_89_ms_(86.67%)_Space_303.92_MB_(28.33%) + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class Solution { + private boolean[] visited; + private List[] adjList; + private int[] flips; + private List ans; + private String s; + private String t; + + public List minimumFlips(int n, int[][] edges, String start, String target) { + s = start; + t = target; + flips = new int[n]; + adjList = new List[n]; + for (int i = 0; i < n; i++) { + adjList[i] = new ArrayList<>(); + } + for (int i = 0; i < edges.length; i++) { + int[] edge = edges[i]; + adjList[edge[0]].add(new int[] {edge[1], i}); + adjList[edge[1]].add(new int[] {edge[0], i}); + } + ans = new ArrayList<>(); + visited = new boolean[n]; + dfs(0, -1, -1); + // Sort indices as required + Collections.sort(ans); + // If root is still mismatched, it's impossible (no parent to flip) + if (mismatch(0)) { + ans = new ArrayList<>(); + ans.add(-1); + } + return ans; + } + + // Helper to check if current state matches target + // Logic: If flips is even, bit is original. If flips is odd, bit is inverted. + private boolean mismatch(int u) { + return ((flips[u] % 2 == 0) && s.charAt(u) != t.charAt(u)) + || ((flips[u] % 2 == 1) && s.charAt(u) == t.charAt(u)); + } + + private void dfs(int u, int parent, int index) { + visited[u] = true; + for (int[] v : adjList[u]) { + if (!visited[v[0]]) { + dfs(v[0], u, v[1]); + } + } + if (parent != -1 && (mismatch(u))) { + ans.add(index); + flips[u]++; + flips[parent]++; + } + } +} diff --git a/src/main/java/g3801_3900/s3812_minimum_edge_toggles_on_a_tree/readme.md b/src/main/java/g3801_3900/s3812_minimum_edge_toggles_on_a_tree/readme.md new file mode 100644 index 000000000..4fef41343 --- /dev/null +++ b/src/main/java/g3801_3900/s3812_minimum_edge_toggles_on_a_tree/readme.md @@ -0,0 +1,64 @@ +3812\. Minimum Edge Toggles on a Tree + +Hard + +You are given an **undirected tree** with `n` nodes, numbered from 0 to `n - 1`. It is represented by a 2D integer array `edges` of length `n - 1`, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. + +You are also given two **binary** strings `start` and `target` of length `n`. For each node `x`, `start[x]` is its initial color and `target[x]` is its desired color. + +In one operation, you may pick an edge with index `i` and **toggle** both of its endpoints. That is, if the edge is `[u, v]`, then the colors of nodes `u` and `v` **each** flip from `'0'` to `'1'` or from `'1'` to `'0'`. + +Return an array of edge indices whose operations transform `start` into `target`. Among all valid sequences with **minimum possible length**, return the edge indices in **increasing** order. + +If it is impossible to transform `start` into `target`, return an array containing a single element equal to -1. + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2025/12/18/example1.png)** + +**Input:** n = 3, edges = [[0,1],[1,2]], start = "010", target = "100" + +**Output:** [0] + +**Explanation:** + +Toggle edge with index 0, which flips nodes 0 and 1. +The string changes from `"010"` to `"100"`, matching the target. + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2025/12/18/example2.png)** + +**Input:** n = 7, edges = [[0,1],[1,2],[2,3],[3,4],[3,5],[1,6]], start = "0011000", target = "0010001" + +**Output:** [1,2,5] + +**Explanation:** + +* Toggle edge with index 1, which flips nodes 1 and 2. +* Toggle edge with index 2, which flips nodes 2 and 3. +* Toggle edge with index 5, which flips nodes 1 and 6. + +After these operations, the resulting string becomes `"0010001"`, which matches the target. + +**Example 3:** + +**![](https://assets.leetcode.com/uploads/2025/12/18/example3.png)** + +**Input:** n = 2, edges = [[0,1]], start = "00", target = "01" + +**Output:** [-1] + +**Explanation:** + +There is no sequence of edge toggles that transforms `"00"` into `"01"`. Therefore, we return `[-1]`. + +**Constraints:** + +* 2 <= n == start.length == target.length <= 105 +* `edges.length == n - 1` +* edges[i] = [ai, bi] +* 0 <= ai, bi < n +* `start[i]` is either `'0'` or `'1'`. +* `target[i]` is either `'0'` or `'1'`. +* The input is generated such that `edges` represents a valid tree. \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3813_vowel_consonant_score/Solution.java b/src/main/java/g3801_3900/s3813_vowel_consonant_score/Solution.java new file mode 100644 index 000000000..beb08a5e8 --- /dev/null +++ b/src/main/java/g3801_3900/s3813_vowel_consonant_score/Solution.java @@ -0,0 +1,22 @@ +package g3801_3900.s3813_vowel_consonant_score; + +// #Easy #String #Simulation #Mid_Level #Weekly_Contest_485 +// #2026_06_09_Time_1_ms_(100.00%)_Space_43.49_MB_(68.40%) + +public class Solution { + public int vowelConsonantScore(String s) { + int count = 0; + String vowels = "aeiou"; + int con = 0; + for (char ch : s.toCharArray()) { + if (vowels.indexOf(ch) != -1) { + count++; + continue; + } + if (Character.isAlphabetic(ch)) { + con++; + } + } + return con == 0 ? 0 : count / con; + } +} diff --git a/src/main/java/g3801_3900/s3813_vowel_consonant_score/readme.md b/src/main/java/g3801_3900/s3813_vowel_consonant_score/readme.md new file mode 100644 index 000000000..d643948d5 --- /dev/null +++ b/src/main/java/g3801_3900/s3813_vowel_consonant_score/readme.md @@ -0,0 +1,55 @@ +3813\. Vowel-Consonant Score + +Easy + +You are given a string `s` consisting of lowercase English letters, spaces, and digits. + +Let `v` be the number of vowels in `s` and `c` be the number of consonants in `s`. + +A vowel is one of the letters `'a'`, `'e'`, `'i'`, `'o'`, or `'u'`, while any other letter in the English alphabet is considered a consonant. + +The **score** of the string `s` is defined as follows: + +* If `c > 0`, the `score = floor(v / c)` where floor denotes **rounding down** to the nearest integer. +* Otherwise, the `score = 0`. + +Return an integer denoting the score of the string. + +**Example 1:** + +**Input:** s = "cooear" + +**Output:** 2 + +**Explanation:** + +The string `s = "cooear"` contains `v = 4` vowels `('o', 'o', 'e', 'a')` and `c = 2` consonants `('c', 'r')`. + +The score is `floor(v / c) = floor(4 / 2) = 2`. + +**Example 2:** + +**Input:** s = "axeyizou" + +**Output:** 1 + +**Explanation:** + +The string `s = "axeyizou"` contains `v = 5` vowels `('a', 'e', 'i', 'o', 'u')` and `c = 3` consonants `('x', 'y', 'z')`. + +The score is `floor(v / c) = floor(5 / 3) = 1`. + +**Example 3:** + +**Input:** s = "au 123" + +**Output:** 0 + +**Explanation:** + +The string `s = "au 123"` contains no consonants `(c = 0)`, so the score is 0. + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` consists of lowercase English letters, spaces and digits. \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3814_maximum_capacity_within_budget/Solution.java b/src/main/java/g3801_3900/s3814_maximum_capacity_within_budget/Solution.java new file mode 100644 index 000000000..af4ece34f --- /dev/null +++ b/src/main/java/g3801_3900/s3814_maximum_capacity_within_budget/Solution.java @@ -0,0 +1,32 @@ +package g3801_3900.s3814_maximum_capacity_within_budget; + +// #Medium #Array #Sorting #Binary_Search #Two_Pointers #Senior #Weekly_Contest_485 +// #2026_06_09_Time_8_ms_(100.00%)_Space_162.19_MB_(100.00%) + +public class Solution { + public int maxCapacity(int[] costs, int[] capacity, int budget) { + int[] mxCap = new int[budget]; + int maxCap = 0; + for (int i = 0; i < costs.length; i++) { + int cost = costs[i]; + int cap = capacity[i]; + if (cost >= budget) { + continue; + } + maxCap = Math.max(maxCap, cap); + if (cost * 2 < budget) { + maxCap = Math.max(maxCap, mxCap[cost] + cap); + } + if (cap > mxCap[cost]) { + mxCap[cost] = cap; + } + } + int[] preSum = new int[budget]; + for (int i = 1; i < budget; i++) { + int rem = Math.min(budget - i - 1, i - 1); + maxCap = Math.max(maxCap, mxCap[i] + preSum[rem]); + preSum[i] = Math.max(preSum[i - 1], mxCap[i]); + } + return maxCap; + } +} diff --git a/src/main/java/g3801_3900/s3814_maximum_capacity_within_budget/readme.md b/src/main/java/g3801_3900/s3814_maximum_capacity_within_budget/readme.md new file mode 100644 index 000000000..f63700a71 --- /dev/null +++ b/src/main/java/g3801_3900/s3814_maximum_capacity_within_budget/readme.md @@ -0,0 +1,53 @@ +3814\. Maximum Capacity Within Budget + +Medium + +You are given two integer arrays `costs` and `capacity`, both of length `n`, where `costs[i]` represents the purchase cost of the ith machine and `capacity[i]` represents its performance capacity. + +You are also given an integer `budget`. + +You may select **at most two distinct** machines such that the **total cost** of the selected machines is **strictly less** than `budget`. + +Return the **maximum** achievable total capacity of the selected machines. + +**Example 1:** + +**Input:** costs = [4,8,5,3], capacity = [1,5,2,7], budget = 8 + +**Output:** 8 + +**Explanation:** + +* Choose two machines with `costs[0] = 4` and `costs[3] = 3`. +* The total cost is `4 + 3 = 7`, which is strictly less than `budget = 8`. +* The maximum total capacity is `capacity[0] + capacity[3] = 1 + 7 = 8`. + +**Example 2:** + +**Input:** costs = [3,5,7,4], capacity = [2,4,3,6], budget = 7 + +**Output:** 6 + +**Explanation:** + +* Choose one machine with `costs[3] = 4`. +* The total cost is 4, which is strictly less than `budget = 7`. +* The maximum total capacity is `capacity[3] = 6`. + +**Example 3:** + +**Input:** costs = [2,2,2], capacity = [3,5,4], budget = 5 + +**Output:** 9 + +**Explanation:** + +* Choose two machines with `costs[1] = 2` and `costs[2] = 2`. +* The total cost is `2 + 2 = 4`, which is strictly less than `budget = 5`. +* The maximum total capacity is `capacity[1] + capacity[2] = 5 + 4 = 9`. + +**Constraints:** + +* 1 <= n == costs.length == capacity.length <= 105 +* 1 <= costs[i], capacity[i] <= 105 +* 1 <= budget <= 2 * 105 \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3815_design_auction_system/AuctionSystem.java b/src/main/java/g3801_3900/s3815_design_auction_system/AuctionSystem.java new file mode 100644 index 000000000..51ba3dea9 --- /dev/null +++ b/src/main/java/g3801_3900/s3815_design_auction_system/AuctionSystem.java @@ -0,0 +1,60 @@ +package g3801_3900.s3815_design_auction_system; + +// #Medium #Hash_Table #Design #Heap_Priority_Queue #Ordered_Set #Staff #Weekly_Contest_485 +// #2026_06_09_Time_96_ms_(93.30%)_Space_203.51_MB_(92.27%) + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.PriorityQueue; + +public class AuctionSystem { + private final Map bidMap; + private final Map> itemMap; + + public AuctionSystem() { + bidMap = new HashMap<>(); + itemMap = new HashMap<>(); + } + + public void addBid(int userId, int itemId, int bidAmount) { + int[] bid = new int[] {userId, itemId, bidAmount}; + bidMap.put((long) userId << 32 | itemId, bid); + itemMap.computeIfAbsent( + itemId, + item -> + new PriorityQueue<>( + (a, b) -> a[2] == b[2] ? b[0] - a[0] : b[2] - a[2])) + .add(bid); + } + + public void updateBid(int userId, int itemId, int newAmount) { + addBid(userId, itemId, newAmount); + } + + public void removeBid(int userId, int itemId) { + bidMap.remove((long) userId << 32 | itemId); + } + + public int getHighestBidder(int itemId) { + PriorityQueue pq = itemMap.get(itemId); + if (pq == null || pq.isEmpty()) { + return -1; + } + while (!pq.isEmpty()) { + int[] top = pq.peek(); + int[] cur = bidMap.get((long) top[0] << 32 | itemId); + if (Arrays.equals(top, cur)) { + return top[0]; + } + pq.poll(); + } + return -1; + } +} + +/** + * Your AuctionSystem object will be instantiated and called as such: AuctionSystem obj = new + * AuctionSystem(); obj.addBid(userId,itemId,bidAmount); obj.updateBid(userId,itemId,newAmount); + * obj.removeBid(userId,itemId); int param_4 = obj.getHighestBidder(itemId); + */ diff --git a/src/main/java/g3801_3900/s3815_design_auction_system/readme.md b/src/main/java/g3801_3900/s3815_design_auction_system/readme.md new file mode 100644 index 000000000..2d2442ddf --- /dev/null +++ b/src/main/java/g3801_3900/s3815_design_auction_system/readme.md @@ -0,0 +1,43 @@ +3815\. Design Auction System + +Medium + +You are asked to design an auction system that manages bids from multiple users in real time. + +Each bid is associated with a `userId`, an `itemId`, and a `bidAmount`. + +Implement the `AuctionSystem` class: + +* `AuctionSystem()`: Initializes the `AuctionSystem` object. +* `void addBid(int userId, int itemId, int bidAmount)`: Adds a new bid for `itemId` by `userId` with `bidAmount`. If the same `userId` **already** has a bid on `itemId`, **replace** it with the new `bidAmount`. +* `void updateBid(int userId, int itemId, int newAmount)`: Updates the existing bid of `userId` for `itemId` to `newAmount`. It is **guaranteed** that this bid _exists_. +* `void removeBid(int userId, int itemId)`: Removes the bid of `userId` for `itemId`. It is **guaranteed** that this bid _exists_. +* `int getHighestBidder(int itemId)`: Returns the `userId` of the **highest** bidder for `itemId`. If multiple users have the **same highest** `bidAmount`, return the user with the **highest** `userId`. If no bids exist for the item, return -1. + +**Example 1:** + +**Input:** +["AuctionSystem", "addBid", "addBid", "getHighestBidder", "updateBid", "getHighestBidder", "removeBid", "getHighestBidder", "getHighestBidder"] +[[], [1, 7, 5], [2, 7, 6], [7], [1, 7, 8], [7], [2, 7], [7], [3]] + +**Output:** +[null, null, null, 2, null, 1, null, 1, -1] + +**Explanation** + +AuctionSystem auctionSystem = new AuctionSystem(); // Initialize the Auction system +auctionSystem.addBid(1, 7, 5); // User 1 bids 5 on item 7 +auctionSystem.addBid(2, 7, 6); // User 2 bids 6 on item 7 +auctionSystem.getHighestBidder(7); // return 2 as User 2 has the highest bid +auctionSystem.updateBid(1, 7, 8); // User 1 updates bid to 8 on item 7 +auctionSystem.getHighestBidder(7); // return 1 as User 1 now has the highest bid +auctionSystem.removeBid(2, 7); // Remove User 2's bid on item 7 +auctionSystem.getHighestBidder(7); // return 1 as User 1 is the current highest bidder +auctionSystem.getHighestBidder(3); // return -1 as no bids exist for item 3 + +**Constraints:** + +* 1 <= userId, itemId <= 5 * 104 +* 1 <= bidAmount, newAmount <= 109 +* At most 5 * 104 total calls to `addBid`, `updateBid`, `removeBid`, and `getHighestBidder`. +* The input is generated such that for `updateBid` and `removeBid`, the bid from the given `userId` for the given `itemId` will be valid. \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3816_lexicographically_smallest_string_after_deleting_duplicate_characters/Solution.java b/src/main/java/g3801_3900/s3816_lexicographically_smallest_string_after_deleting_duplicate_characters/Solution.java new file mode 100644 index 000000000..3d0ba18f2 --- /dev/null +++ b/src/main/java/g3801_3900/s3816_lexicographically_smallest_string_after_deleting_duplicate_characters/Solution.java @@ -0,0 +1,41 @@ +package g3801_3900.s3816_lexicographically_smallest_string_after_deleting_duplicate_characters; + +// #Hard #String #Hash_Table #Greedy #Stack #Monotonic_Stack #Senior_Staff #Weekly_Contest_485 +// #2026_06_09_Time_65_ms_(91.61%)_Space_47.86_MB_(91.61%) + +public class Solution { + public String lexSmallestAfterDeletion(String s) { + char[] a = s.toCharArray(); + int[] rem = new int[26]; + for (char c : a) { + rem[c - 'a']++; + } + int[] cnt = new int[26]; + StringBuilder sb = new StringBuilder(); + for (char c : a) { + rem[c - 'a']--; + while (!sb.isEmpty()) { + char t = sb.charAt(sb.length() - 1); + if (t > c && (rem[t - 'a'] > 0 || cnt[t - 'a'] > 1)) { + cnt[t - 'a']--; + sb.setLength(sb.length() - 1); + } else { + break; + } + } + sb.append(c); + cnt[c - 'a']++; + } + while (!sb.isEmpty()) { + int i = sb.length() - 1; + char c = sb.charAt(i); + if (cnt[c - 'a'] > 1) { + cnt[c - 'a']--; + sb.setLength(i); + } else { + break; + } + } + return sb.toString(); + } +} diff --git a/src/main/java/g3801_3900/s3816_lexicographically_smallest_string_after_deleting_duplicate_characters/readme.md b/src/main/java/g3801_3900/s3816_lexicographically_smallest_string_after_deleting_duplicate_characters/readme.md new file mode 100644 index 000000000..582376d97 --- /dev/null +++ b/src/main/java/g3801_3900/s3816_lexicographically_smallest_string_after_deleting_duplicate_characters/readme.md @@ -0,0 +1,38 @@ +3816\. Lexicographically Smallest String After Deleting Duplicate Characters + +Hard + +You are given a string `s` that consists of lowercase English letters. + +You can perform the following operation any number of times (possibly zero times): + +* Choose any letter that appears **at least twice** in the current string `s` and delete any **one** occurrence. + +Return the **lexicographically smallest** resulting string that can be formed this way. + +**Example 1:** + +**Input:** s = "aaccb" + +**Output:** "aacb" + +**Explanation:** + +We can form the strings `"acb"`, `"aacb"`, `"accb"`, and `"aaccb"`. `"aacb"` is the lexicographically smallest one. + +For example, we can obtain `"aacb"` by choosing `'c'` and deleting its first occurrence. + +**Example 2:** + +**Input:** s = "z" + +**Output:** "z" + +**Explanation:** + +We cannot perform any operations. The only string we can form is `"z"`. + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` contains lowercase English letters only. \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3818_minimum_prefix_removal_to_make_array_strictly_increasing/Solution.java b/src/main/java/g3801_3900/s3818_minimum_prefix_removal_to_make_array_strictly_increasing/Solution.java new file mode 100644 index 000000000..24f435aa8 --- /dev/null +++ b/src/main/java/g3801_3900/s3818_minimum_prefix_removal_to_make_array_strictly_increasing/Solution.java @@ -0,0 +1,14 @@ +package g3801_3900.s3818_minimum_prefix_removal_to_make_array_strictly_increasing; + +// #Medium #Array #Senior #Weekly_Contest_486 +// #2026_06_09_Time_1_ms_(99.63%)_Space_119.92_MB_(80.97%) + +public class Solution { + public int minimumPrefixLength(int[] nums) { + int i = nums.length - 1; + while (i > 0 && nums[i - 1] < nums[i]) { + --i; + } + return i; + } +} diff --git a/src/main/java/g3801_3900/s3818_minimum_prefix_removal_to_make_array_strictly_increasing/readme.md b/src/main/java/g3801_3900/s3818_minimum_prefix_removal_to_make_array_strictly_increasing/readme.md new file mode 100644 index 000000000..eb86649e7 --- /dev/null +++ b/src/main/java/g3801_3900/s3818_minimum_prefix_removal_to_make_array_strictly_increasing/readme.md @@ -0,0 +1,44 @@ +3818\. Minimum Prefix Removal to Make Array Strictly Increasing + +Medium + +You are given an integer array `nums`. + +You need to remove **exactly** one prefix (possibly empty) from nums. + +Return an integer denoting the **minimum** length of the removed prefix such that the remaining array is **strictly increasing**. + +**Example 1:** + +**Input:** nums = [1,-1,2,3,3,4,5] + +**Output:** 4 + +**Explanation:** + +Removing the `prefix = [1, -1, 2, 3]` leaves the remaining array `[3, 4, 5]` which is strictly increasing. + +**Example 2:** + +**Input:** nums = [4,3,-2,-5] + +**Output:** 3 + +**Explanation:** + +Removing the `prefix = [4, 3, -2]` leaves the remaining array `[-5]` which is strictly increasing. + +**Example 3:** + +**Input:** nums = [1,2,3,4] + +**Output:** 0 + +**Explanation:** + +The array `nums = [1, 2, 3, 4]` is already strictly increasing so removing an empty prefix is sufficient. + +**Constraints:** + +* 1 <= nums.length <= 105 +* -109 <= nums[i] <= 109 \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3819_rotate_non_negative_elements/Solution.java b/src/main/java/g3801_3900/s3819_rotate_non_negative_elements/Solution.java new file mode 100644 index 000000000..2b9644600 --- /dev/null +++ b/src/main/java/g3801_3900/s3819_rotate_non_negative_elements/Solution.java @@ -0,0 +1,30 @@ +package g3801_3900.s3819_rotate_non_negative_elements; + +// #Medium #Array #Simulation #Senior #Weekly_Contest_486 +// #2026_06_09_Time_11_ms_(100.00%)_Space_265.42_MB_(74.38%) + +public class Solution { + public int[] rotateElements(int[] nums, int k) { + int n = nums.length; + int m = 0; + int[] a = new int[n]; + for (int x : nums) { + if (x >= 0) { + a[m++] = x; + } + } + if (m == 0) { + return nums; + } + k %= m; + int j = 0; + for (int i = 0; i < n; i++) { + if (nums[i] >= 0) { + int index = (j + k) % m; + nums[i] = a[index]; + j++; + } + } + return nums; + } +} diff --git a/src/main/java/g3801_3900/s3819_rotate_non_negative_elements/readme.md b/src/main/java/g3801_3900/s3819_rotate_non_negative_elements/readme.md new file mode 100644 index 000000000..d7e24c6dc --- /dev/null +++ b/src/main/java/g3801_3900/s3819_rotate_non_negative_elements/readme.md @@ -0,0 +1,56 @@ +3819\. Rotate Non Negative Elements + +Medium + +You are given an integer array `nums` and an integer `k`. + +Rotate only the **non-negative** elements of the array to the **left** by `k` positions, in a cyclic manner. + +All **negative** elements must stay in their original positions and must not move. + +After rotation, place the **non-negative** elements back into the array in the new order, filling only the positions that originally contained **non-negative** values and **skipping all negative** positions. + +Return the resulting array. + +**Example 1:** + +**Input:** nums = [1,-2,3,-4], k = 3 + +**Output:** [3,-2,1,-4] + +**Explanation:** + +* The non-negative elements, in order, are `[1, 3]`. +* Left rotation with `k = 3` results in: + * `[1, 3] -> [3, 1] -> [1, 3] -> [3, 1]` +* Placing them back into the non-negative indices results in `[3, -2, 1, -4]`. + +**Example 2:** + +**Input:** nums = [-3,-2,7], k = 1 + +**Output:** [-3,-2,7] + +**Explanation:** + +* The non-negative elements, in order, are `[7]`. +* Left rotation with `k = 1` results in `[7]`. +* Placing them back into the non-negative indices results in `[-3, -2, 7]`. + +**Example 3:** + +**Input:** nums = [5,4,-9,6], k = 2 + +**Output:** [6,5,-9,4] + +**Explanation:** + +* The non-negative elements, in order, are `[5, 4, 6]`. +* Left rotation with `k = 2` results in `[6, 5, 4]`. +* Placing them back into the non-negative indices results in `[6, 5, -9, 4]`. + +**Constraints:** + +* 1 <= nums.length <= 105 +* -105 <= nums[i] <= 105 +* 0 <= k <= 105 \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3820_pythagorean_distance_nodes_in_a_tree/Solution.java b/src/main/java/g3801_3900/s3820_pythagorean_distance_nodes_in_a_tree/Solution.java new file mode 100644 index 000000000..0977f3853 --- /dev/null +++ b/src/main/java/g3801_3900/s3820_pythagorean_distance_nodes_in_a_tree/Solution.java @@ -0,0 +1,71 @@ +package g3801_3900.s3820_pythagorean_distance_nodes_in_a_tree; + +// #Medium #Tree #Staff #Weekly_Contest_486 #Breadth_First_Search +// #2026_06_09_Time_96_ms_(90.83%)_Space_234.88_MB_(70.83%) + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Solution { + int[] bfs(int n, List[] adj, int start) { + int[] dist = new int[n]; + Arrays.fill(dist, -1); + dist[start] = 0; + ArrayDeque q = new ArrayDeque<>(); + q.add(start); + while (!q.isEmpty()) { + int u = q.poll(); + for (int v : adj[u]) { + // Check if this neighbour was not visited yet + if (dist[v] == -1) { + dist[v] = dist[u] + 1; + q.add(v); + } + } + } + return dist; + } + + public int specialNodes(int n, int[][] edges, int x, int y, int z) { + ArrayList[] adj = new ArrayList[n]; + for (int i = 0; i < n; i++) { + adj[i] = new ArrayList<>(); + } + for (int[] edge : edges) { + int u = edge[0]; + int v = edge[1]; + adj[u].add(v); + adj[v].add(u); + } + // Calculate distances from every node to x, y and z + int[] dx = bfs(n, adj, x); + int[] dy = bfs(n, adj, y); + int[] dz = bfs(n, adj, z); + int result = 0; + for (int i = 0; i < n; i++) { + long a = dx[i]; + int b = dy[i]; + int c = dz[i]; + // Ensure a <= b <= c + if (a > b) { + long t = a; + a = b; + b = (int) t; + } + if (b > c) { + long t = b; + b = c; + c = (int) t; + } + if (a > b) { + long t = a; + a = b; + b = (int) t; + } + result += (a * a + (long) b * b == (long) c * c) ? 1 : 0; + } + return result; + } +} diff --git a/src/main/java/g3801_3900/s3820_pythagorean_distance_nodes_in_a_tree/readme.md b/src/main/java/g3801_3900/s3820_pythagorean_distance_nodes_in_a_tree/readme.md new file mode 100644 index 000000000..a5ea7348f --- /dev/null +++ b/src/main/java/g3801_3900/s3820_pythagorean_distance_nodes_in_a_tree/readme.md @@ -0,0 +1,81 @@ +3820\. Pythagorean Distance Nodes in a Tree + +Medium + +You are given an integer `n` and an undirected tree with `n` nodes numbered from 0 to `n - 1`. The tree is represented by a 2D array `edges` of length `n - 1`, where edges[i] = [ui, vi] indicates an undirected edge between ui and vi. + +You are also given three **distinct** target nodes `x`, `y`, and `z`. + +For any node `u` in the tree: + +* Let `dx` be the distance from `u` to node `x` +* Let `dy` be the distance from `u` to node `y` +* Let `dz` be the distance from `u` to node `z` + +The node `u` is called **special** if the three distances form a **Pythagorean Triplet**. + +Return an integer denoting the number of special nodes in the tree. + +A **Pythagorean triplet** consists of three integers `a`, `b`, and `c` which, when sorted in **ascending** order, satisfy a2 + b2 = c2. + +The **distance** between two nodes in a tree is the number of edges on the unique path between them. + +**Example 1:** + +**Input:** n = 4, edges = [[0,1],[0,2],[0,3]], x = 1, y = 2, z = 3 + +**Output:** 3 + +**Explanation:** + +For each node, we compute its distances to nodes `x = 1`, `y = 2`, and `z = 3`. + +* Node 0 has distances 1, 1, and 1. After sorting, the distances are 1, 1, and 1, which do not satisfy the Pythagorean condition. +* Node 1 has distances 0, 2, and 2. After sorting, the distances are 0, 2, and 2. Since 02 + 22 = 22, node 1 is special. +* Node 2 has distances 2, 0, and 2. After sorting, the distances are 0, 2, and 2. Since 02 + 22 = 22, node 2 is special. +* Node 3 has distances 2, 2, and 0. After sorting, the distances are 0, 2, and 2. This also satisfies the Pythagorean condition. + +Therefore, nodes 1, 2, and 3 are special, and the answer is 3. + +**Example 2:** + +**Input:** n = 4, edges = [[0,1],[1,2],[2,3]], x = 0, y = 3, z = 2 + +**Output:** 0 + +**Explanation:** + +For each node, we compute its distances to nodes `x = 0`, `y = 3`, and `z = 2`. + +* Node 0 has distances 0, 3, and 2. After sorting, the distances are 0, 2, and 3, which do not satisfy the Pythagorean condition. +* Node 1 has distances 1, 2, and 1. After sorting, the distances are 1, 1, and 2, which do not satisfy the Pythagorean condition. +* Node 2 has distances 2, 1, and 0. After sorting, the distances are 0, 1, and 2, which do not satisfy the Pythagorean condition. +* Node 3 has distances 3, 0, and 1. After sorting, the distances are 0, 1, and 3, which do not satisfy the Pythagorean condition. + +No node satisfies the Pythagorean condition. Therefore, the answer is 0. + +**Example 3:** + +**Input:** n = 4, edges = [[0,1],[1,2],[1,3]], x = 1, y = 3, z = 0 + +**Output:** 1 + +**Explanation:** + +For each node, we compute its distances to nodes `x = 1`, `y = 3`, and `z = 0`. + +* Node 0 has distances 1, 2, and 0. After sorting, the distances are 0, 1, and 2, which do not satisfy the Pythagorean condition. +* Node 1 has distances 0, 1, and 1. After sorting, the distances are 0, 1, and 1. Since 02 + 12 = 12, node 1 is special. +* Node 2 has distances 1, 2, and 2. After sorting, the distances are 1, 2, and 2, which do not satisfy the Pythagorean condition. +* Node 3 has distances 1, 0, and 2. After sorting, the distances are 0, 1, and 2, which do not satisfy the Pythagorean condition. + +Therefore, the answer is 1. + +**Constraints:** + +* 4 <= n <= 105 +* `edges.length == n - 1` +* edges[i] = [ui, vi] +* 0 <= ui, vi, x, y, z <= n - 1 +* `x`, `y`, and `z` are pairwise **distinct**. +* The input is generated such that `edges` represent a valid tree. \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3821_find_nth_smallest_integer_with_k_one_bits/Solution.java b/src/main/java/g3801_3900/s3821_find_nth_smallest_integer_with_k_one_bits/Solution.java new file mode 100644 index 000000000..36af6d102 --- /dev/null +++ b/src/main/java/g3801_3900/s3821_find_nth_smallest_integer_with_k_one_bits/Solution.java @@ -0,0 +1,34 @@ +package g3801_3900.s3821_find_nth_smallest_integer_with_k_one_bits; + +// #Hard #Math #Bit_Manipulation #Combinatorics #Senior_Staff #Weekly_Contest_486 +// #2026_06_09_Time_2_ms_(98.59%)_Space_42.60_MB_(90.14%) + +public class Solution { + private static final int MX = 60; + private static final long[][] C = new long[MX][MX + 1]; + + static { + for (int i = 0; i < MX; i++) { + C[i][0] = 1; + for (int j = 1; j <= i; j++) { + C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; + } + } + } + + public long nthSmallest(long n, int k) { + long ans = 0; + for (int i = 50; i >= 0; i--) { + long count = C[i][k]; + if (n > count) { + n -= count; + ans |= (1L << i); + k--; + if (k == 0) { + break; + } + } + } + return ans; + } +} diff --git a/src/main/java/g3801_3900/s3821_find_nth_smallest_integer_with_k_one_bits/readme.md b/src/main/java/g3801_3900/s3821_find_nth_smallest_integer_with_k_one_bits/readme.md new file mode 100644 index 000000000..149ac6786 --- /dev/null +++ b/src/main/java/g3801_3900/s3821_find_nth_smallest_integer_with_k_one_bits/readme.md @@ -0,0 +1,42 @@ +3821\. Find Nth Smallest Integer With K One Bits + +Hard + +You are given two positive integers `n` and `k`. + +Return an integer denoting the nth smallest positive integer that has **exactly** `k` ones in its binary representation. It is guaranteed that the answer is **strictly less** than 250. + +**Example 1:** + +**Input:** n = 4, k = 2 + +**Output:** 9 + +**Explanation:** + +The 4 smallest positive integers that have exactly `k = 2` ones in their binary representations are: + +* 3 = 112 +* 5 = 1012 +* 6 = 1102 +* 9 = 10012 + +**Example 2:** + +**Input:** n = 3, k = 1 + +**Output:** 4 + +**Explanation:** + +The 3 smallest positive integers that have exactly `k = 1` one in their binary representations are: + +* 1 = 12 +* 2 = 102 +* 4 = 1002 + +**Constraints:** + +* 1 <= n <= 250 +* `1 <= k <= 50` +* The answer is strictly less than 250. \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3823_reverse_letters_then_special_characters_in_a_string/Solution.java b/src/main/java/g3801_3900/s3823_reverse_letters_then_special_characters_in_a_string/Solution.java new file mode 100644 index 000000000..a1e0e8da4 --- /dev/null +++ b/src/main/java/g3801_3900/s3823_reverse_letters_then_special_characters_in_a_string/Solution.java @@ -0,0 +1,41 @@ +package g3801_3900.s3823_reverse_letters_then_special_characters_in_a_string; + +// #Easy #String #Two_Pointers #Simulation #Mid_Level #Biweekly_Contest_175 +// #2026_06_09_Time_1_ms_(100.00%)_Space_44.12_MB_(93.04%) + +public class Solution { + public String reverseByType(String s) { + char[] arr = s.toCharArray(); + int low = 0; + int high = arr.length - 1; + while (low < high) { + if (arr[low] >= 'a' && arr[low] <= 'z' && arr[high] >= 'a' && arr[high] <= 'z') { + char t = arr[low]; + arr[low] = arr[high]; + arr[high] = t; + low++; + high--; + } else if (arr[low] < 'a' || arr[low] > 'z') { + low++; + } else { + high--; + } + } + int i = 0; + int j = arr.length - 1; + while (i < j) { + if ((arr[i] < 'a' || arr[i] > 'z') && (arr[j] < 'a' || arr[j] > 'z')) { + char t = arr[i]; + arr[i] = arr[j]; + arr[j] = t; + i++; + j--; + } else if (arr[i] >= 'a' && arr[i] <= 'z') { + i++; + } else { + j--; + } + } + return new String(arr); + } +} diff --git a/src/main/java/g3801_3900/s3823_reverse_letters_then_special_characters_in_a_string/readme.md b/src/main/java/g3801_3900/s3823_reverse_letters_then_special_characters_in_a_string/readme.md new file mode 100644 index 000000000..ac36bce4f --- /dev/null +++ b/src/main/java/g3801_3900/s3823_reverse_letters_then_special_characters_in_a_string/readme.md @@ -0,0 +1,52 @@ +3823\. Reverse Letters Then Special Characters in a String + +Easy + +You are given a string `s` consisting of lowercase English letters and special characters. + +Your task is to perform these **in order**: + +* **Reverse** the **lowercase letters** and place them back into the positions originally occupied by letters. +* **Reverse** the **special characters** and place them back into the positions originally occupied by special characters. + +Return the resulting string after performing the reversals. + +**Example 1:** + +**Input:** s = ")ebc#da@f(" + +**Output:** "(fad@cb#e)" + +**Explanation:** + +* The letters in the string are `['e', 'b', 'c', 'd', 'a', 'f']`: + * Reversing them gives `['f', 'a', 'd', 'c', 'b', 'e']` + * `s` becomes `")fad#cb@e("` +* The special characters in the string are `[')', '#', '@', '(']`: + * Reversing them gives `['(', '@', '#', ')']` + * `s` becomes `"(fad@cb#e)"` + +**Example 2:** + +**Input:** s = "z" + +**Output:** "z" + +**Explanation:** + +The string contains only one letter, and reversing it does not change the string. There are no special characters. + +**Example 3:** + +**Input:** s = "!@#$%^&\*()" + +**Output:** ")(\*&^%$#@!" + +**Explanation:** + +The string contains no letters. The string contains all special characters, so reversing the special characters reverses the whole string. + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` consists only of lowercase English letters and the special characters in `"!@#$%^&*()"`. \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3825_longest_strictly_increasing_subsequence_with_non_zero_bitwise_and/Solution.java b/src/main/java/g3801_3900/s3825_longest_strictly_increasing_subsequence_with_non_zero_bitwise_and/Solution.java new file mode 100644 index 000000000..2e0b3dedb --- /dev/null +++ b/src/main/java/g3801_3900/s3825_longest_strictly_increasing_subsequence_with_non_zero_bitwise_and/Solution.java @@ -0,0 +1,46 @@ +package g3801_3900.s3825_longest_strictly_increasing_subsequence_with_non_zero_bitwise_and; + +// #Medium #Array #Binary_Search #Bit_Manipulation #Enumeration #Staff #Biweekly_Contest_175 +// #2026_06_09_Time_327_ms_(92.65%)_Space_111.14_MB_(76.47%) + +public class Solution { + private int lis(int[] nums, int n) { + int[] tails = new int[n]; + int sz = 0; + for (int i = 0; i < n; i++) { + int x = nums[i]; + int l = 0; + int r = sz; + while (l < r) { + int m = (l + r) >>> 1; + if (tails[m] >= x) { + r = m; + } else { + l = m + 1; + } + } + tails[l] = x; + if (l == sz) { + sz++; + } + } + return sz; + } + + public int longestSubsequence(int[] nums) { + final int maxbits = 32; + int result = 0; + int n = nums.length; + int[] buf = new int[n]; + for (int bit = 0; bit < maxbits; bit++) { + int m = 0; + for (int x : nums) { + if (((x >> bit) & 1) != 0) { + buf[m++] = x; + } + } + result = Math.max(result, lis(buf, m)); + } + return result; + } +} diff --git a/src/main/java/g3801_3900/s3825_longest_strictly_increasing_subsequence_with_non_zero_bitwise_and/readme.md b/src/main/java/g3801_3900/s3825_longest_strictly_increasing_subsequence_with_non_zero_bitwise_and/readme.md new file mode 100644 index 000000000..d46ebb708 --- /dev/null +++ b/src/main/java/g3801_3900/s3825_longest_strictly_increasing_subsequence_with_non_zero_bitwise_and/readme.md @@ -0,0 +1,42 @@ +3825\. Longest Strictly Increasing Subsequence With Non-Zero Bitwise AND + +Medium + +You are given an integer array `nums`. + +Return the length of the **longest strictly increasing subsequence** in `nums` whose bitwise **AND** is **non-zero**. If no such **subsequence** exists, return 0. + +**Example 1:** + +**Input:** nums = [5,4,7] + +**Output:** 2 + +**Explanation:** + +One longest strictly increasing subsequence is `[5, 7]`. The bitwise AND is `5 AND 7 = 5`, which is non-zero. + +**Example 2:** + +**Input:** nums = [2,3,6] + +**Output:** 3 + +**Explanation:** + +The longest strictly increasing subsequence is `[2, 3, 6]`. The bitwise AND is `2 AND 3 AND 6 = 2`, which is non-zero. + +**Example 3:** + +**Input:** nums = [0,1] + +**Output:** 1 + +**Explanation:** + +One longest strictly increasing subsequence is `[1]`. The bitwise AND is 1, which is non-zero. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 0 <= nums[i] <= 109 \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3826_minimum_partition_score/Solution.java b/src/main/java/g3801_3900/s3826_minimum_partition_score/Solution.java new file mode 100644 index 000000000..297a4468f --- /dev/null +++ b/src/main/java/g3801_3900/s3826_minimum_partition_score/Solution.java @@ -0,0 +1,98 @@ +package g3801_3900.s3826_minimum_partition_score; + +// #Hard #Array #Dynamic_Programming #Prefix_Sum #Divide_and_Conquer #Queue #Monotonic_Queue +// #Principal #Biweekly_Contest_175 #2026_06_09_Time_70_ms_(96.97%)_Space_47.29_MB_(57.58%) + +import java.util.ArrayDeque; +import java.util.Deque; + +public class Solution { + private long[] prefix; + + private boolean isRedundant(Line l1, Line l2, Line l3) { + return (double) (l3.intercept - l1.intercept) * (l1.slope - l2.slope) + <= (double) (l2.intercept - l1.intercept) * (l1.slope - l3.slope); + } + + private Pair solveWithPenalty(long lambda) { + Deque dq = new ArrayDeque<>(); + dq.addLast(new Line(0, 0, 0)); + long di = 0; + int pi = 0; + for (int i = 1; i < prefix.length; i++) { + long x = prefix[i]; + // query + while (dq.size() > 1) { + Line first = dq.pollFirst(); + Line second = dq.peekFirst(); + if (first.eval(x) <= second.eval(x)) { + dq.addFirst(first); + break; + } + } + Line best = dq.peekFirst(); + di = x * x + x + 2 * lambda + best.eval(x); + pi = best.partition + 1; + Line newLine = new Line(-2 * x, di + x * x - x, pi); + while (dq.size() > 1) { + Line last = dq.pollLast(); + Line secondLast = dq.peekLast(); + if (!isRedundant(secondLast, last, newLine)) { + dq.addLast(last); + break; + } + } + dq.addLast(newLine); + } + return new Pair(di, pi); + } + + public long minPartitionScore(int[] nums, int k) { + int n = nums.length; + prefix = new long[n + 1]; + for (int i = 1; i <= n; i++) { + prefix[i] = prefix[i - 1] + nums[i - 1]; + } + long start = 0; + long end = (long) 1e15; + long bestLambda = 0; + while (start <= end) { + long mid = start + (end - start) / 2; + Pair res = solveWithPenalty(mid); + if (res.partition <= k) { + bestLambda = mid; + end = mid - 1; + } else { + start = mid + 1; + } + } + Pair ans = solveWithPenalty(bestLambda); + return (ans.score - 2L * k * bestLambda) / 2; + } + + private static class Line { + long slope; + long intercept; + int partition; + + Line(long slope, long intercept, int partition) { + this.slope = slope; + this.intercept = intercept; + this.partition = partition; + } + + long eval(long x) { + return slope * x + intercept; + } + } + + private static class Pair { + long score; + int partition; + + Pair(long score, int partition) { + this.score = score; + this.partition = partition; + } + } +} diff --git a/src/main/java/g3801_3900/s3826_minimum_partition_score/readme.md b/src/main/java/g3801_3900/s3826_minimum_partition_score/readme.md new file mode 100644 index 000000000..a8416909d --- /dev/null +++ b/src/main/java/g3801_3900/s3826_minimum_partition_score/readme.md @@ -0,0 +1,54 @@ +3826\. Minimum Partition Score + +Hard + +You are given an integer array `nums` and an integer `k`. + +Your task is to partition `nums` into **exactly** `k` non-empty subarrays and return an integer denoting the **minimum possible score** among all valid partitions. + +The **score** of a partition is the **sum** of the **values** of all its subarrays. + +The **value** of a subarray is defined as `sumArr * (sumArr + 1) / 2`, where `sumArr` is the sum of its elements. + +**Example 1:** + +**Input:** nums = [5,1,2,1], k = 2 + +**Output:** 25 + +**Explanation:** + +* We must partition the array into `k = 2` subarrays. One optimal partition is `[5]` and `[1, 2, 1]`. +* The first subarray has `sumArr = 5` and `value = 5 × 6 / 2 = 15`. +* The second subarray has `sumArr = 1 + 2 + 1 = 4` and `value = 4 × 5 / 2 = 10`. +* The score of this partition is `15 + 10 = 25`, which is the minimum possible score. + +**Example 2:** + +**Input:** nums = [1,2,3,4], k = 1 + +**Output:** 55 + +**Explanation:** + +* Since we must partition the array into `k = 1` subarray, all elements belong to the same subarray: `[1, 2, 3, 4]`. +* This subarray has `sumArr = 1 + 2 + 3 + 4 = 10` and `value = 10 × 11 / 2 = 55`. +* The score of this partition is 55, which is the minimum possible score. + +**Example 3:** + +**Input:** nums = [1,1,1], k = 3 + +**Output:** 3 + +**Explanation:** + +* We must partition the array into `k = 3` subarrays. The only valid partition is `[1], [1], [1]`. +* Each subarray has `sumArr = 1` and `value = 1 × 2 / 2 = 1`. +* The score of this partition is `1 + 1 + 1 = 3`, which is the minimum possible score. + +**Constraints:** + +* `1 <= nums.length <= 1000` +* 1 <= nums[i] <= 104 +* `1 <= k <= nums.length` \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3827_count_monobit_integers/Solution.java b/src/main/java/g3801_3900/s3827_count_monobit_integers/Solution.java new file mode 100644 index 000000000..62825045b --- /dev/null +++ b/src/main/java/g3801_3900/s3827_count_monobit_integers/Solution.java @@ -0,0 +1,18 @@ +package g3801_3900.s3827_count_monobit_integers; + +// #Easy #Bit_Manipulation #Enumeration #Mid_Level #Weekly_Contest_487 +// #2026_06_09_Time_1_ms_(99.41%)_Space_42.33_MB_(91.20%) + +public class Solution { + public int countMonobit(int n) { + int count = 1; + + int val = 1; + while (val <= n) { + count++; + val = (val << 1) | 1; + } + + return count; + } +} diff --git a/src/main/java/g3801_3900/s3827_count_monobit_integers/readme.md b/src/main/java/g3801_3900/s3827_count_monobit_integers/readme.md new file mode 100644 index 000000000..c33b69ac2 --- /dev/null +++ b/src/main/java/g3801_3900/s3827_count_monobit_integers/readme.md @@ -0,0 +1,35 @@ +3827\. Count Monobit Integers + +Easy + +You are given an integer `n`. + +An integer is called **Monobit** if all bits in its binary representation are the same. + +Return the count of **Monobit** integers in the range `[0, n]` (inclusive). + +**Example 1:** + +**Input:** n = 1 + +**Output:** 2 + +**Explanation:** + +* The integers in the range `[0, 1]` have binary representations `"0"` and `"1"`. +* Each representation consists of identical bits. Thus, the answer is 2. + +**Example 2:** + +**Input:** n = 4 + +**Output:** 3 + +**Explanation:** + +* The integers in the range `[0, 4]` include binaries `"0"`, `"1"`, `"10"`, `"11"`, and `"100"`. +* Only 0, 1 and 3 satisfy the Monobit condition. Thus, the answer is 3. + +**Constraints:** + +* `0 <= n <= 1000` \ No newline at end of file diff --git a/src/main/java/g3801_3900/s3828_final_element_after_subarray_deletions/Solution.java b/src/main/java/g3801_3900/s3828_final_element_after_subarray_deletions/Solution.java new file mode 100644 index 000000000..84e4f3eb7 --- /dev/null +++ b/src/main/java/g3801_3900/s3828_final_element_after_subarray_deletions/Solution.java @@ -0,0 +1,10 @@ +package g3801_3900.s3828_final_element_after_subarray_deletions; + +// #Medium #Array #Math #Game_Theory #Brainteaser #Staff #Weekly_Contest_487 +// #2026_06_09_Time_0_ms_(100.00%)_Space_114.36_MB_(5.56%) + +public class Solution { + public int finalElement(int[] nums) { + return Math.max(nums[0], nums[nums.length - 1]); + } +} diff --git a/src/main/java/g3801_3900/s3828_final_element_after_subarray_deletions/readme.md b/src/main/java/g3801_3900/s3828_final_element_after_subarray_deletions/readme.md new file mode 100644 index 000000000..74f99dedd --- /dev/null +++ b/src/main/java/g3801_3900/s3828_final_element_after_subarray_deletions/readme.md @@ -0,0 +1,41 @@ +3828\. Final Element After Subarray Deletions + +Medium + +You are given an integer array `nums`. + +Two players, Alice and Bob, play a game in turns, with Alice playing first. + +* In each turn, the current player chooses any **non-empty subarrays** `nums[l..r]` such that `r - l + 1 < m`, where `m` is the **current length** of the array. +* The selected **subarray is removed**, and the remaining elements are **concatenated** to form the new array. +* The game continues until **only one** element remains. + +Alice aims to **maximize** the final element, while Bob aims to **minimize** it. Assuming both play optimally, return the value of the final remaining element. + +**Example 1:** + +**Input:** nums = [1,5,2] + +**Output:** 2 + +**Explanation:** + +One valid optimal strategy: + +* Alice removes `[1]`, array becomes `[5, 2]`. +* Bob removes `[5]`, array becomes `[2]`. Thus, the answer is 2. + +**Example 2:** + +**Input:** nums = [3,7] + +**Output:** 7 + +**Explanation:** + +Alice removes `[3]`, leaving the array `[7]`. Since Bob cannot play a turn now, the answer is 7. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 105 \ No newline at end of file diff --git a/src/test/java/g3801_3900/s3806_maximum_bitwise_and_after_increment_operations/SolutionTest.java b/src/test/java/g3801_3900/s3806_maximum_bitwise_and_after_increment_operations/SolutionTest.java new file mode 100644 index 000000000..ce5276f17 --- /dev/null +++ b/src/test/java/g3801_3900/s3806_maximum_bitwise_and_after_increment_operations/SolutionTest.java @@ -0,0 +1,23 @@ +package g3801_3900.s3806_maximum_bitwise_and_after_increment_operations; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maximumAND() { + assertThat(new Solution().maximumAND(new int[] {3, 1, 2}, 8, 2), equalTo(6)); + } + + @Test + void maximumAND2() { + assertThat(new Solution().maximumAND(new int[] {1, 2, 8, 4}, 7, 3), equalTo(4)); + } + + @Test + void maximumAND3() { + assertThat(new Solution().maximumAND(new int[] {1, 1}, 3, 2), equalTo(2)); + } +} diff --git a/src/test/java/g3801_3900/s3808_find_emotionally_consistent_users/MysqlTest.java b/src/test/java/g3801_3900/s3808_find_emotionally_consistent_users/MysqlTest.java new file mode 100644 index 000000000..851646cc4 --- /dev/null +++ b/src/test/java/g3801_3900/s3808_find_emotionally_consistent_users/MysqlTest.java @@ -0,0 +1,82 @@ +package g3801_3900.s3808_find_emotionally_consistent_users; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import javax.sql.DataSource; +import org.junit.jupiter.api.Test; +import org.zapodot.junit.db.annotations.EmbeddedDatabase; +import org.zapodot.junit.db.annotations.EmbeddedDatabaseTest; +import org.zapodot.junit.db.common.CompatibilityMode; + +@EmbeddedDatabaseTest( + compatibilityMode = CompatibilityMode.MySQL, + initialSqls = + "CREATE TABLE reactions (" + + " user_id INTEGER," + + " content_id INTEGER," + + " reaction VARCHAR(32)" + + ");" + + "INSERT INTO reactions (user_id, content_id, reaction) VALUES" + + "(1, 1, 'like')," + + "(1, 2, 'like')," + + "(1, 3, 'like')," + + "(1, 4, 'like')," + + "(1, 5, 'like')," + + "(2, 1, 'like')," + + "(2, 2, 'like')," + + "(2, 3, 'like')," + + "(2, 4, 'like')," + + "(2, 5, 'like')," + + "(3, 1, 'like')," + + "(3, 2, 'like')," + + "(3, 3, 'like')," + + "(3, 4, 'like')," + + "(4, 1, 'like')," + + "(4, 2, 'like')," + + "(4, 3, 'love')," + + "(4, 4, 'love')," + + "(4, 5, 'sad');") +class MysqlTest { + @Test + void testScript(@EmbeddedDatabase DataSource dataSource) + throws SQLException, FileNotFoundException { + try (final Connection connection = dataSource.getConnection()) { + try (final Statement statement = connection.createStatement(); + final ResultSet resultSet = + statement.executeQuery( + new BufferedReader( + new FileReader( + "src/main/java/g3801_3900/" + + "s3808_find_emotionally_consistent_users/" + + "script.sql")) + .lines() + .collect(Collectors.joining("\n")) + .replaceAll("#.*?\\r?\\n", ""))) { + List actualRows = new ArrayList<>(); + while (resultSet.next()) { + actualRows.add( + resultSet.getString(1) + + "|" + + resultSet.getString(2) + + "|" + + resultSet.getString(3)); + } + + List expectedRows = Arrays.asList("1|like|1", "2|like|1"); + assertThat(actualRows, equalTo(expectedRows)); + } + } + } +} diff --git a/src/test/java/g3801_3900/s3809_best_reachable_tower/SolutionTest.java b/src/test/java/g3801_3900/s3809_best_reachable_tower/SolutionTest.java new file mode 100644 index 000000000..39135a18d --- /dev/null +++ b/src/test/java/g3801_3900/s3809_best_reachable_tower/SolutionTest.java @@ -0,0 +1,33 @@ +package g3801_3900.s3809_best_reachable_tower; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void bestTower() { + assertThat( + new Solution() + .bestTower( + new int[][] {{1, 2, 5}, {2, 1, 7}, {3, 1, 9}}, new int[] {1, 1}, 2), + equalTo(new int[] {3, 1})); + } + + @Test + void bestTower2() { + assertThat( + new Solution() + .bestTower( + new int[][] {{1, 3, 4}, {2, 2, 4}, {4, 4, 7}}, new int[] {0, 0}, 5), + equalTo(new int[] {1, 3})); + } + + @Test + void bestTower3() { + assertThat( + new Solution().bestTower(new int[][] {{5, 6, 8}, {0, 3, 5}}, new int[] {1, 2}, 1), + equalTo(new int[] {-1, -1})); + } +} diff --git a/src/test/java/g3801_3900/s3810_minimum_operations_to_reach_target_array/SolutionTest.java b/src/test/java/g3801_3900/s3810_minimum_operations_to_reach_target_array/SolutionTest.java new file mode 100644 index 000000000..abd948e11 --- /dev/null +++ b/src/test/java/g3801_3900/s3810_minimum_operations_to_reach_target_array/SolutionTest.java @@ -0,0 +1,26 @@ +package g3801_3900.s3810_minimum_operations_to_reach_target_array; + +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(new int[] {1, 2, 3}, new int[] {2, 1, 3}), equalTo(2)); + } + + @Test + void minOperations2() { + assertThat( + new Solution().minOperations(new int[] {4, 1, 4}, new int[] {5, 1, 4}), equalTo(1)); + } + + @Test + void minOperations3() { + assertThat( + new Solution().minOperations(new int[] {7, 3, 7}, new int[] {5, 5, 9}), equalTo(2)); + } +} diff --git a/src/test/java/g3801_3900/s3811_number_of_alternating_xor_partitions/SolutionTest.java b/src/test/java/g3801_3900/s3811_number_of_alternating_xor_partitions/SolutionTest.java new file mode 100644 index 000000000..915c53408 --- /dev/null +++ b/src/test/java/g3801_3900/s3811_number_of_alternating_xor_partitions/SolutionTest.java @@ -0,0 +1,23 @@ +package g3801_3900.s3811_number_of_alternating_xor_partitions; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void alternatingXOR() { + assertThat(new Solution().alternatingXOR(new int[] {2, 3, 1, 4}, 1, 5), equalTo(1)); + } + + @Test + void alternatingXOR2() { + assertThat(new Solution().alternatingXOR(new int[] {1, 0, 0}, 1, 0), equalTo(3)); + } + + @Test + void alternatingXOR3() { + assertThat(new Solution().alternatingXOR(new int[] {7}, 1, 7), equalTo(0)); + } +} diff --git a/src/test/java/g3801_3900/s3812_minimum_edge_toggles_on_a_tree/SolutionTest.java b/src/test/java/g3801_3900/s3812_minimum_edge_toggles_on_a_tree/SolutionTest.java new file mode 100644 index 000000000..cb6ea7367 --- /dev/null +++ b/src/test/java/g3801_3900/s3812_minimum_edge_toggles_on_a_tree/SolutionTest.java @@ -0,0 +1,35 @@ +package g3801_3900.s3812_minimum_edge_toggles_on_a_tree; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minimumFlips() { + assertThat( + new Solution().minimumFlips(3, new int[][] {{0, 1}, {1, 2}}, "010", "100"), + equalTo(Arrays.asList(0))); + } + + @Test + void minimumFlips2() { + assertThat( + new Solution() + .minimumFlips( + 7, + new int[][] {{0, 1}, {1, 2}, {2, 3}, {3, 4}, {3, 5}, {1, 6}}, + "0011000", + "0010001"), + equalTo(Arrays.asList(1, 2, 5))); + } + + @Test + void minimumFlips3() { + assertThat( + new Solution().minimumFlips(2, new int[][] {{0, 1}}, "00", "01"), + equalTo(Arrays.asList(-1))); + } +} diff --git a/src/test/java/g3801_3900/s3813_vowel_consonant_score/SolutionTest.java b/src/test/java/g3801_3900/s3813_vowel_consonant_score/SolutionTest.java new file mode 100644 index 000000000..ccd19d6f3 --- /dev/null +++ b/src/test/java/g3801_3900/s3813_vowel_consonant_score/SolutionTest.java @@ -0,0 +1,23 @@ +package g3801_3900.s3813_vowel_consonant_score; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void vowelConsonantScore() { + assertThat(new Solution().vowelConsonantScore("cooear"), equalTo(2)); + } + + @Test + void vowelConsonantScore2() { + assertThat(new Solution().vowelConsonantScore("axeyizou"), equalTo(1)); + } + + @Test + void vowelConsonantScore3() { + assertThat(new Solution().vowelConsonantScore("au 123"), equalTo(0)); + } +} diff --git a/src/test/java/g3801_3900/s3814_maximum_capacity_within_budget/SolutionTest.java b/src/test/java/g3801_3900/s3814_maximum_capacity_within_budget/SolutionTest.java new file mode 100644 index 000000000..964b5de22 --- /dev/null +++ b/src/test/java/g3801_3900/s3814_maximum_capacity_within_budget/SolutionTest.java @@ -0,0 +1,29 @@ +package g3801_3900.s3814_maximum_capacity_within_budget; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void maxCapacity() { + assertThat( + new Solution().maxCapacity(new int[] {4, 8, 5, 3}, new int[] {1, 5, 2, 7}, 8), + equalTo(8)); + } + + @Test + void maxCapacity2() { + assertThat( + new Solution().maxCapacity(new int[] {3, 5, 7, 4}, new int[] {2, 4, 3, 6}, 7), + equalTo(6)); + } + + @Test + void maxCapacity3() { + assertThat( + new Solution().maxCapacity(new int[] {2, 2, 2}, new int[] {3, 5, 4}, 5), + equalTo(9)); + } +} diff --git a/src/test/java/g3801_3900/s3815_design_auction_system/SolutionTest.java b/src/test/java/g3801_3900/s3815_design_auction_system/SolutionTest.java new file mode 100644 index 000000000..f877c76b1 --- /dev/null +++ b/src/test/java/g3801_3900/s3815_design_auction_system/SolutionTest.java @@ -0,0 +1,21 @@ +package g3801_3900.s3815_design_auction_system; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void auctionSystem() { + AuctionSystem auctionSystem = new AuctionSystem(); + auctionSystem.addBid(1, 7, 5); + auctionSystem.addBid(2, 7, 6); + assertThat(auctionSystem.getHighestBidder(7), equalTo(2)); + auctionSystem.updateBid(1, 7, 8); + assertThat(auctionSystem.getHighestBidder(7), equalTo(1)); + auctionSystem.removeBid(2, 7); + assertThat(auctionSystem.getHighestBidder(7), equalTo(1)); + assertThat(auctionSystem.getHighestBidder(3), equalTo(-1)); + } +} diff --git a/src/test/java/g3801_3900/s3816_lexicographically_smallest_string_after_deleting_duplicate_characters/SolutionTest.java b/src/test/java/g3801_3900/s3816_lexicographically_smallest_string_after_deleting_duplicate_characters/SolutionTest.java new file mode 100644 index 000000000..13289fe05 --- /dev/null +++ b/src/test/java/g3801_3900/s3816_lexicographically_smallest_string_after_deleting_duplicate_characters/SolutionTest.java @@ -0,0 +1,18 @@ +package g3801_3900.s3816_lexicographically_smallest_string_after_deleting_duplicate_characters; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void lexSmallestAfterDeletion() { + assertThat(new Solution().lexSmallestAfterDeletion("aaccb"), equalTo("aacb")); + } + + @Test + void lexSmallestAfterDeletion2() { + assertThat(new Solution().lexSmallestAfterDeletion("z"), equalTo("z")); + } +} diff --git a/src/test/java/g3801_3900/s3818_minimum_prefix_removal_to_make_array_strictly_increasing/SolutionTest.java b/src/test/java/g3801_3900/s3818_minimum_prefix_removal_to_make_array_strictly_increasing/SolutionTest.java new file mode 100644 index 000000000..a556dbe0f --- /dev/null +++ b/src/test/java/g3801_3900/s3818_minimum_prefix_removal_to_make_array_strictly_increasing/SolutionTest.java @@ -0,0 +1,24 @@ +package g3801_3900.s3818_minimum_prefix_removal_to_make_array_strictly_increasing; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minimumPrefixLength() { + assertThat( + new Solution().minimumPrefixLength(new int[] {1, -1, 2, 3, 3, 4, 5}), equalTo(4)); + } + + @Test + void minimumPrefixLength2() { + assertThat(new Solution().minimumPrefixLength(new int[] {4, 3, -2, -5}), equalTo(3)); + } + + @Test + void minimumPrefixLength3() { + assertThat(new Solution().minimumPrefixLength(new int[] {1, 2, 3, 4}), equalTo(0)); + } +} diff --git a/src/test/java/g3801_3900/s3819_rotate_non_negative_elements/SolutionTest.java b/src/test/java/g3801_3900/s3819_rotate_non_negative_elements/SolutionTest.java new file mode 100644 index 000000000..c53638f91 --- /dev/null +++ b/src/test/java/g3801_3900/s3819_rotate_non_negative_elements/SolutionTest.java @@ -0,0 +1,29 @@ +package g3801_3900.s3819_rotate_non_negative_elements; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void rotateElements() { + assertThat( + new Solution().rotateElements(new int[] {1, -2, 3, -4}, 3), + equalTo(new int[] {3, -2, 1, -4})); + } + + @Test + void rotateElements2() { + assertThat( + new Solution().rotateElements(new int[] {-3, -2, 7}, 1), + equalTo(new int[] {-3, -2, 7})); + } + + @Test + void rotateElements3() { + assertThat( + new Solution().rotateElements(new int[] {5, 4, -9, 6}, 2), + equalTo(new int[] {6, 5, -9, 4})); + } +} diff --git a/src/test/java/g3801_3900/s3820_pythagorean_distance_nodes_in_a_tree/SolutionTest.java b/src/test/java/g3801_3900/s3820_pythagorean_distance_nodes_in_a_tree/SolutionTest.java new file mode 100644 index 000000000..979688a00 --- /dev/null +++ b/src/test/java/g3801_3900/s3820_pythagorean_distance_nodes_in_a_tree/SolutionTest.java @@ -0,0 +1,29 @@ +package g3801_3900.s3820_pythagorean_distance_nodes_in_a_tree; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void specialNodes() { + assertThat( + new Solution().specialNodes(4, new int[][] {{0, 1}, {0, 2}, {0, 3}}, 1, 2, 3), + equalTo(3)); + } + + @Test + void specialNodes2() { + assertThat( + new Solution().specialNodes(4, new int[][] {{0, 1}, {1, 2}, {2, 3}}, 0, 3, 2), + equalTo(0)); + } + + @Test + void specialNodes3() { + assertThat( + new Solution().specialNodes(4, new int[][] {{0, 1}, {1, 2}, {1, 3}}, 1, 3, 0), + equalTo(1)); + } +} diff --git a/src/test/java/g3801_3900/s3821_find_nth_smallest_integer_with_k_one_bits/SolutionTest.java b/src/test/java/g3801_3900/s3821_find_nth_smallest_integer_with_k_one_bits/SolutionTest.java new file mode 100644 index 000000000..a05f01b73 --- /dev/null +++ b/src/test/java/g3801_3900/s3821_find_nth_smallest_integer_with_k_one_bits/SolutionTest.java @@ -0,0 +1,18 @@ +package g3801_3900.s3821_find_nth_smallest_integer_with_k_one_bits; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void nthSmallest() { + assertThat(new Solution().nthSmallest(4, 2), equalTo(9L)); + } + + @Test + void nthSmallest2() { + assertThat(new Solution().nthSmallest(3, 1), equalTo(4L)); + } +} diff --git a/src/test/java/g3801_3900/s3823_reverse_letters_then_special_characters_in_a_string/SolutionTest.java b/src/test/java/g3801_3900/s3823_reverse_letters_then_special_characters_in_a_string/SolutionTest.java new file mode 100644 index 000000000..c836aa485 --- /dev/null +++ b/src/test/java/g3801_3900/s3823_reverse_letters_then_special_characters_in_a_string/SolutionTest.java @@ -0,0 +1,23 @@ +package g3801_3900.s3823_reverse_letters_then_special_characters_in_a_string; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void reverseByType() { + assertThat(new Solution().reverseByType(")ebc#da@f("), equalTo("(fad@cb#e)")); + } + + @Test + void reverseByType2() { + assertThat(new Solution().reverseByType("z"), equalTo("z")); + } + + @Test + void reverseByType3() { + assertThat(new Solution().reverseByType("!@#$%^&*()"), equalTo(")(*&^%$#@!")); + } +} diff --git a/src/test/java/g3801_3900/s3825_longest_strictly_increasing_subsequence_with_non_zero_bitwise_and/SolutionTest.java b/src/test/java/g3801_3900/s3825_longest_strictly_increasing_subsequence_with_non_zero_bitwise_and/SolutionTest.java new file mode 100644 index 000000000..3a52cb000 --- /dev/null +++ b/src/test/java/g3801_3900/s3825_longest_strictly_increasing_subsequence_with_non_zero_bitwise_and/SolutionTest.java @@ -0,0 +1,23 @@ +package g3801_3900.s3825_longest_strictly_increasing_subsequence_with_non_zero_bitwise_and; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void longestSubsequence() { + assertThat(new Solution().longestSubsequence(new int[] {5, 4, 7}), equalTo(2)); + } + + @Test + void longestSubsequence2() { + assertThat(new Solution().longestSubsequence(new int[] {2, 3, 6}), equalTo(3)); + } + + @Test + void longestSubsequence3() { + assertThat(new Solution().longestSubsequence(new int[] {0, 1}), equalTo(1)); + } +} diff --git a/src/test/java/g3801_3900/s3826_minimum_partition_score/SolutionTest.java b/src/test/java/g3801_3900/s3826_minimum_partition_score/SolutionTest.java new file mode 100644 index 000000000..302f4a86d --- /dev/null +++ b/src/test/java/g3801_3900/s3826_minimum_partition_score/SolutionTest.java @@ -0,0 +1,23 @@ +package g3801_3900.s3826_minimum_partition_score; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minPartitionScore() { + assertThat(new Solution().minPartitionScore(new int[] {5, 1, 2, 1}, 2), equalTo(25L)); + } + + @Test + void minPartitionScore2() { + assertThat(new Solution().minPartitionScore(new int[] {1, 2, 3, 4}, 1), equalTo(55L)); + } + + @Test + void minPartitionScore3() { + assertThat(new Solution().minPartitionScore(new int[] {1, 1, 1}, 3), equalTo(3L)); + } +} diff --git a/src/test/java/g3801_3900/s3827_count_monobit_integers/SolutionTest.java b/src/test/java/g3801_3900/s3827_count_monobit_integers/SolutionTest.java new file mode 100644 index 000000000..ca520a8ab --- /dev/null +++ b/src/test/java/g3801_3900/s3827_count_monobit_integers/SolutionTest.java @@ -0,0 +1,18 @@ +package g3801_3900.s3827_count_monobit_integers; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void countMonobit() { + assertThat(new Solution().countMonobit(1), equalTo(2)); + } + + @Test + void countMonobit2() { + assertThat(new Solution().countMonobit(4), equalTo(3)); + } +} diff --git a/src/test/java/g3801_3900/s3828_final_element_after_subarray_deletions/SolutionTest.java b/src/test/java/g3801_3900/s3828_final_element_after_subarray_deletions/SolutionTest.java new file mode 100644 index 000000000..baf11343a --- /dev/null +++ b/src/test/java/g3801_3900/s3828_final_element_after_subarray_deletions/SolutionTest.java @@ -0,0 +1,18 @@ +package g3801_3900.s3828_final_element_after_subarray_deletions; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void finalElement() { + assertThat(new Solution().finalElement(new int[] {1, 5, 2}), equalTo(2)); + } + + @Test + void finalElement2() { + assertThat(new Solution().finalElement(new int[] {3, 7}), equalTo(7)); + } +}