diff --git a/src/main/java/g3901_4000/s3922_minimum_flips_to_make_binary_string_coherent/Solution.java b/src/main/java/g3901_4000/s3922_minimum_flips_to_make_binary_string_coherent/Solution.java new file mode 100644 index 000000000..b74d0260f --- /dev/null +++ b/src/main/java/g3901_4000/s3922_minimum_flips_to_make_binary_string_coherent/Solution.java @@ -0,0 +1,37 @@ +package g3901_4000.s3922_minimum_flips_to_make_binary_string_coherent; + +// #Medium #String #Senior #Biweekly_Contest_182 +// #2026_09_29_Time_4_ms_(100.00%)_Space_47.56_MB_(76.92%) + +public class Solution { + public int minFlips(String s) { + int n = s.length(); + int count1 = 0; + for (char c : s.toCharArray()) { + count1 += c - '0'; + } + int count0 = n - count1; + // Option 1: all 0s + int ans = count1; + // Option 2: all 1s + ans = Math.min(ans, count0); + // Option 3: exactly one 1 (at any position) + if (count1 >= 1) { + ans = Math.min(ans, count1 - 1); + } else { + ans = Math.min(ans, 1); + } + // Option 4: "10...01" (1 at position 0 and position n-1) + if (n >= 2 && count1 >= 2) { + int cost4 = count1; + if (s.charAt(0) == '1') { + cost4--; + } + if (s.charAt(n - 1) == '1') { + cost4--; + } + ans = Math.min(ans, cost4); + } + return ans; + } +} diff --git a/src/main/java/g3901_4000/s3922_minimum_flips_to_make_binary_string_coherent/readme.md b/src/main/java/g3901_4000/s3922_minimum_flips_to_make_binary_string_coherent/readme.md new file mode 100644 index 000000000..e852391ac --- /dev/null +++ b/src/main/java/g3901_4000/s3922_minimum_flips_to_make_binary_string_coherent/readme.md @@ -0,0 +1,46 @@ +3922\. Minimum Flips to Make Binary String Coherent + +Medium + +You are given a binary string `s`. + +A string is considered **coherent** if it does **not** contain `"011"` or `"110"` as subsequences. + +In one operation, you can **flip** any character in `s` (`'0'` to `'1'` or `'1'` to `'0'`). + +Return an integer denoting the **minimum** number of operations required to make `s` coherent. + +**Example 1:** + +**Input:** s = "1010" + +**Output:** 1 + +**Explanation:** + +Flip `s[0]` to get `"0010"`, which contains no `"011"` or `"110"` subsequences. + +**Example 2:** + +**Input:** s = "0110" + +**Output:** 1 + +**Explanation:** + +Flip `s[1]` to get `"0010"`, removing all forbidden subsequences `"011"` and `"110"`. + +**Example 3:** + +**Input:** s = "1000" + +**Output:** 0 + +**Explanation:** + +The string already has no `"011"` or `"110"` subsequences, so no flips are needed. + +**Constraints:** + +* 1 <= s.length <= 105 +* `s[i]` is either `'0'` or `'1'`. \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3923_minimum_generations_to_target_point/Solution.java b/src/main/java/g3901_4000/s3923_minimum_generations_to_target_point/Solution.java new file mode 100644 index 000000000..c13fa0cbb --- /dev/null +++ b/src/main/java/g3901_4000/s3923_minimum_generations_to_target_point/Solution.java @@ -0,0 +1,104 @@ +package g3901_4000.s3923_minimum_generations_to_target_point; + +// #Medium #Array #Hash_Table #Simulation #Staff #Biweekly_Contest_182 +// #2026_09_29_Time_24_ms_(100.00%)_Space_46.83_MB_(67.86%) + +import java.util.ArrayList; +import java.util.List; + +public class Solution { + private static final int SIZE = 7; + private static final int TOTAL_POINTS = SIZE * SIZE * SIZE; + + public int minGenerations(int[][] points, int[] target) { + boolean[] visited = new boolean[TOTAL_POINTS]; + List allPoints = new ArrayList<>(); + List frontier = new ArrayList<>(); + int targetCode = encode(target[0], target[1], target[2]); + initializePoints(points, visited, allPoints, frontier); + if (frontier.contains(targetCode)) { + return 0; + } + int generation = 0; + while (!frontier.isEmpty()) { + generation++; + List nextFrontier = generateNextFrontier(frontier, allPoints, visited); + if (nextFrontier.contains(targetCode)) { + return generation; + } + addPoints(nextFrontier, visited, allPoints); + frontier = nextFrontier; + } + return -1; + } + + private void initializePoints( + int[][] points, boolean[] visited, List allPoints, List frontier) { + for (int[] point : points) { + int code = encode(point[0], point[1], point[2]); + visited[code] = true; + allPoints.add(code); + frontier.add(code); + } + } + + private List generateNextFrontier( + List frontier, List allPoints, boolean[] visited) { + List nextFrontier = new ArrayList<>(); + boolean[] addedThisGeneration = new boolean[TOTAL_POINTS]; + for (int pointA : frontier) { + addGeneratedPoints(pointA, allPoints, visited, addedThisGeneration, nextFrontier); + } + return nextFrontier; + } + + private void addGeneratedPoints( + int pointA, + List allPoints, + boolean[] visited, + boolean[] addedThisGeneration, + List nextFrontier) { + int[] a = decode(pointA); + for (int pointB : allPoints) { + if (pointA != pointB) { + addGeneratedPoint(a, pointB, visited, addedThisGeneration, nextFrontier); + } + } + } + + private void addGeneratedPoint( + int[] a, + int pointB, + boolean[] visited, + boolean[] addedThisGeneration, + List nextFrontier) { + int[] b = decode(pointB); + int x = (a[0] + b[0]) / 2; + int y = (a[1] + b[1]) / 2; + int z = (a[2] + b[2]) / 2; + int newPoint = encode(x, y, z); + if (!visited[newPoint] && !addedThisGeneration[newPoint]) { + addedThisGeneration[newPoint] = true; + nextFrontier.add(newPoint); + } + } + + private void addPoints(List points, boolean[] visited, List allPoints) { + for (int point : points) { + visited[point] = true; + allPoints.add(point); + } + } + + private int encode(int x, int y, int z) { + return x * SIZE * SIZE + y * SIZE + z; + } + + private int[] decode(int code) { + int x = code / (SIZE * SIZE); + code %= SIZE * SIZE; + int y = code / SIZE; + int z = code % SIZE; + return new int[] {x, y, z}; + } +} diff --git a/src/main/java/g3901_4000/s3923_minimum_generations_to_target_point/readme.md b/src/main/java/g3901_4000/s3923_minimum_generations_to_target_point/readme.md new file mode 100644 index 000000000..e750436b0 --- /dev/null +++ b/src/main/java/g3901_4000/s3923_minimum_generations_to_target_point/readme.md @@ -0,0 +1,85 @@ +3923\. Minimum Generations to Target Point + +Medium + +You are given a 2D integer array `points` where points[i] = [xi, yi, zi] represents a point in 3D space, and an integer array `target` representing a target point. + +Define **generation** 0 as the initial list of points. For each integer `k >= 1`, form generation `k` as follows: + +* Consider every pair of two **distinct** points a = [x1, y1, z1] and b = [x2, y2, z2] taken from all points produced in generations 0 through `k - 1`. +* For each such pair, compute c = [floor((x1 + x2) / 2), floor((y1 + y2) / 2), floor((z1 + z2) / 2)] and collect every such `c` into a generation `k`. +* All points in the generation `k` are produced **simultaneously** from points in generations 0 through `k - 1`. +* After generation `k` is formed, the points in the generation `k` are considered available for forming later generations. + +Return the **smallest** integer `k` such that the `target` appears in one of the generations 0 through `k`. If the `target` is already in the initial points, return 0. If it is impossible to obtain the `target`, return -1. + +Notes: + +* **floor** denotes rounding **down** to the nearest integer. +* "Two **distinct** points" means the two chosen points must have **different** `(x, y, z)` coordinates. A point cannot be paired with itself, and pairing two points with **identical** coordinates is not possible. + +**Example 1:** + +**Input:** points = [[0,0,0],[6,6,6]], target = [3,3,3] + +**Output:** 1 + +**Explanation:** + +* **Generation 0:** The initial `points = [[0, 0, 0], [6, 6, 6]]`. +* The `target = [3, 3, 3]` does not exist in generation 0. +* **Generation 1:** For each pair of points in generation 0, we create new points. + * Using `[0, 0, 0]` and `[6, 6, 6]`, we generate `[3, 3, 3]`. +* After generation 1, `points = [[0, 0, 0], [6, 6, 6], [3, 3, 3]]`. +* The `target = [3, 3, 3]` is found in generation 1, so the smallest `k` is 1. + +**Example 2:** + +**Input:** points = [[0,0,0],[5,5,5]], target = [1,1,1] + +**Output:** 2 + +**Explanation:** + +* **Generation 0:** The initial `points = [[0, 0, 0], [5, 5, 5]]`. +* The `target = [1, 1, 1]` does not exist in generation 0. +* **Generation 1:** For each pair of points in generation 0, we create new points. + * Using `[0, 0, 0]` and `[5, 5, 5]`, we generate `[2, 2, 2]`. +* After generation 1, `points = [[0, 0, 0], [5, 5, 5], [2, 2, 2]]`. +* **Generation 2:** For each pair of points available after generation 1, we create new points. + * Using `[0, 0, 0]` and `[5, 5, 5]`, we generate `[2, 2, 2]`. + * Using `[0, 0, 0]` and `[2, 2, 2]`, we generate `[1, 1, 1]`. + * Using `[5, 5, 5]` and `[2, 2, 2]`, we generate `[3, 3, 3]`. +* After generation 2, `points = [[0, 0, 0], [5, 5, 5], [2, 2, 2], [1, 1, 1], [3, 3, 3]]`. +* The `target = [1, 1, 1]` is found in generation 2, so the smallest `k` is 2. + +**Example 3:** + +**Input:** points = [[0,0,0],[2,2,2],[3,3,3]], target = [2,2,2] + +**Output:** 0 + +**Explanation:** + +* **Generation 0:** The initial `points = [[0, 0, 0], [2, 2, 2], [3, 3, 3]]`. +* The `target = [2, 2, 2]` already exists in generation 0, so the smallest `k` is 0. + +**Example 4:** + +**Input:** points = [[1,2,3]], target = [5,5,5] + +**Output:** \-1 + +**Explanation:** + +* Only one initial point is available, so no new points can be generated. +* Therefore, the target cannot be obtained, and the answer is -1. + +**Constraints:** + +* `1 <= points.length <= 20` +* points[i] = [xi, yi, zi] +* 0 <= xi, yi, zi <= 6 +* `target.length == 3` +* `0 <= target[i] <= 6` +* The initial set of points contains no duplicates. \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3924_minimum_threshold_path_with_limited_heavy_edges/Solution.java b/src/main/java/g3901_4000/s3924_minimum_threshold_path_with_limited_heavy_edges/Solution.java new file mode 100644 index 000000000..facc0900d --- /dev/null +++ b/src/main/java/g3901_4000/s3924_minimum_threshold_path_with_limited_heavy_edges/Solution.java @@ -0,0 +1,103 @@ +package g3901_4000.s3924_minimum_threshold_path_with_limited_heavy_edges; + +// #Hard #Binary_Search #Senior_Staff #Biweekly_Contest_182 #Breadth_First_Search #Graph_Theory +// #2026_09_29_Time_30_ms_(98.28%)_Space_47.81_MB_(58.62%) + +import java.util.ArrayDeque; +import java.util.Arrays; + +public class Solution { + private int[] head; + private int[] to; + private int[] weight; + private int[] next; + private int n; + private int source; + private int target; + private int k; + + public int minimumThreshold(int n, int[][] edges, int source, int target, int k) { + if (source == target) { + return 0; + } + this.n = n; + this.source = source; + this.target = target; + this.k = k; + // make adj list (you dont have to do this fancy version, standard adj list works) + int m = edges.length; + this.head = new int[n]; + this.to = new int[m << 1]; + this.weight = new int[m << 1]; + this.next = new int[m << 1]; + Arrays.fill(head, -1); + for (int i = 0; i < m; i++) { + int a = edges[i][0]; + int b = edges[i][1]; + int c = edges[i][2]; + to[i << 1] = b; + next[i << 1] = head[a]; + head[a] = i << 1; + to[i << 1 | 1] = a; + next[i << 1 | 1] = head[b]; + head[b] = i << 1 | 1; + weight[i << 1] = weight[i << 1 | 1] = c; + } + // check if it's possible to reach the target at all + if (!check(Integer.MAX_VALUE)) { + return -1; + } + if (k == m) { + return 0; + } + int left = 0; + int right = 0; + // set right pointer to max edge weight, cuz any threshold larger than that is pointless + for (int[] edge : edges) { + if (edge[2] > right) { + right = edge[2]; + } + } + // binary search on the answer + while (left < right) { + int mid = left + right >>> 1; + if (check(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } + + private boolean check(int threshold) { + // 0-1 BFS + int[] dist = new int[n]; + Arrays.fill(dist, k + 1); + dist[source] = 0; + ArrayDeque queue = new ArrayDeque<>(n); + queue.add(source); + while (!queue.isEmpty()) { + int current = queue.poll(); + if (current == target) { + return true; + } + int currentDist = dist[current]; + // go through each adj node (a regular adj list works here as well) + for (int i = head[current]; i != -1; i = next[i]) { + int node = to[i]; + int newWeight = weight[i] > threshold ? 1 : 0; + int newDist = newWeight + currentDist; + if (newDist < dist[node]) { + dist[node] = newDist; + if (newWeight == 0) { + queue.addFirst(node); + } else { + queue.addLast(node); + } + } + } + } + return false; + } +} diff --git a/src/main/java/g3901_4000/s3924_minimum_threshold_path_with_limited_heavy_edges/readme.md b/src/main/java/g3901_4000/s3924_minimum_threshold_path_with_limited_heavy_edges/readme.md new file mode 100644 index 000000000..96b8dcbf3 --- /dev/null +++ b/src/main/java/g3901_4000/s3924_minimum_threshold_path_with_limited_heavy_edges/readme.md @@ -0,0 +1,75 @@ +3924\. Minimum Threshold Path With Limited Heavy Edges + +Hard + +There is an undirected weighted graph with `n` nodes labeled from 0 to `n - 1`. + +The graph is represented by a 2D integer array `edges`, where each edge edges[i] = [ui, vi, wi] indicates that there is an undirected edge between nodes ui and vi with weight wi. + +You are also given integers `source`, `target` and `k`. + +A `threshold` value determines whether an edge is considered **light** or **heavy**: + +* An edge is **light** if its weight is **less than** or **equal** to `threshold`. + +* An edge is **heavy** if its weight is **greater than** `threshold`. + + +A path from `source` to `target` is **valid** if it contains **at most** `k` heavy edges. + +Return the **minimum integer** `threshold` such that **at least** one **valid** path exists from `source` to `target`. If no such path exists, return -1. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2025/10/13/g6.png) + +**Input:** n = 6, edges = [[0,1,5],[1,2,3],[3,4,4],[4,5,1],[1,4,2]], source = 0, target = 3, k = 1 + +**Output:** 4 + +**Explanation:** + +The minimum `threshold` such that a path from node 0 to node 3 uses at most 1 heavy edge is 4. + +* Light edges: `[1, 2, 3]`, `[3, 4, 4]`, `[4, 5, 1]`, `[1, 4, 2]` + +* Heavy edges: `[0, 1, 5]` + + +A valid path is `0 → 1 → 4 → 3`. It uses only 1 heavy edge (`[0, 1, 5]`), which satisfies the limit `k = 1`. + +Any smaller `threshold` would make it impossible to reach node 3 without exceeding 1 heavy edge. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2025/10/12/g3_f.png) + +**Input:** n = 6, edges = [[0,1,3],[1,2,4],[3,4,5],[4,5,6]], source = 0, target = 4, k = 1 + +**Output:** \-1 + +**Explanation:** + +There is no path from node 0 to node 4. Since the target cannot be reached, the output is -1. + +**Example 3:** + +**![](https://assets.leetcode.com/uploads/2025/10/12/g5.png)** + +**Input:** n = 4, edges = [[0,1,2],[1,2,2],[2,3,2],[3,0,2]], source = 0, target = 0, k = 0 + +**Output:** 0 + +**Explanation:** + +The source and target are the same node. No edges need to be traversed, so the minimum `threshold` is 0. + +**Constraints:** + +* 1 <= n <= 103 +* 0 <= edges.length <= 103 +* edges[i] = [ui, vi, wi] +* 0 <= ui, vi <= n - 1 +* 1 <= wi <= 109 +* `0 <= source, target <= n - 1` +* `0 <= k <= edges.length` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3925_concatenate_array_with_reverse/Solution.java b/src/main/java/g3901_4000/s3925_concatenate_array_with_reverse/Solution.java new file mode 100644 index 000000000..c8a571197 --- /dev/null +++ b/src/main/java/g3901_4000/s3925_concatenate_array_with_reverse/Solution.java @@ -0,0 +1,20 @@ +package g3901_4000.s3925_concatenate_array_with_reverse; + +// #Easy #Array #Simulation #Mid_Level #Weekly_Contest_501 +// #2026_09_29_Time_1_ms_(97.85%)_Space_47.45_MB_(24.79%) + +public class Solution { + public int[] concatWithReverse(int[] nums) { + int n = nums.length; + int[] ans = new int[n * 2]; + int count = 0; + for (int i = 0; i < n; i++) { + ans[i] = nums[i]; + count++; + } + for (int i = n - 1; i >= 0; i--) { + ans[count++] = nums[i]; + } + return ans; + } +} diff --git a/src/main/java/g3901_4000/s3925_concatenate_array_with_reverse/readme.md b/src/main/java/g3901_4000/s3925_concatenate_array_with_reverse/readme.md new file mode 100644 index 000000000..eb4625f11 --- /dev/null +++ b/src/main/java/g3901_4000/s3925_concatenate_array_with_reverse/readme.md @@ -0,0 +1,47 @@ +3925\. Concatenate Array With Reverse + +Easy + +You are given an integer array `nums` of length `n`. + +Construct a new array `ans` of length `2 * n` such that the first `n` elements are the same as `nums`, and the next `n` elements are the elements of `nums` in reverse order. + +Formally, for `0 <= i <= n - 1`: + +* `ans[i] = nums[i]` +* `ans[i + n] = nums[n - i - 1]` + +Return an integer array `ans`. + +**Example 1:** + +**Input:** nums = [1,2,3] + +**Output:** [1,2,3,3,2,1] + +**Explanation:** + +The first `n` elements of `ans` are the same as `nums`. + +For the next `n = 3` elements, each element is taken from `nums` in reverse order: + +* `ans[3] = nums[2] = 3` +* `ans[4] = nums[1] = 2` +* `ans[5] = nums[0] = 1` + +Thus, `ans = [1, 2, 3, 3, 2, 1]`. + +**Example 2:** + +**Input:** nums = [1] + +**Output:** [1,1] + +**Explanation:** + +The array remains the same when reversed. Thus, `ans = [1, 1]`. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `1 <= nums[i] <= 100` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3926_count_valid_word_occurrences/Solution.java b/src/main/java/g3901_4000/s3926_count_valid_word_occurrences/Solution.java new file mode 100644 index 000000000..802efbe55 --- /dev/null +++ b/src/main/java/g3901_4000/s3926_count_valid_word_occurrences/Solution.java @@ -0,0 +1,109 @@ +package g3901_4000.s3926_count_valid_word_occurrences; + +// #Medium #Array #String #Hash_Table #Counting #Staff #Weekly_Contest_501 +// #2026_09_29_Time_39_ms_(98.70%)_Space_189.00_MB_(5.19%) + +public class Solution { + public int[] countWordOccurrences(String[] chunks, String[] queries) { + Trie trie = new Trie(); + trie.fill(chunks); + int n = queries.length; + int[] result = new int[n]; + for (int k = 0; k < n; k++) { + result[k] = trie.count(queries[k]); + } + return result; + } + + private static class Trie { + private final Trie[] children = new Trie[27]; + private int count = 0; + + private void fill(String[] chunks) { + Trie node = this; + char last = '@'; + for (int j = 0; j < chunks.length; j++) { + String chunk = chunks[j]; + for (int k = 0; k < chunk.length(); k++) { + char c = processCharacter(chunk, k, j, chunks, last); + node = addCharacter(node, c); + node = finalizeWordIfNeeded(node, c); + last = c; + } + } + incrementCountIfNeeded(node); + } + + private char processCharacter( + String chunk, int index, int chunkIndex, String[] chunks, char last) { + char c = chunk.charAt(index); + if (c == '-') { + char next = getNextCharacter(chunk, index, chunkIndex, chunks); + if (!isLetter(last) || !isLetter(next)) { + return '@'; + } + } + return c; + } + + private char getNextCharacter(String chunk, int index, int chunkIndex, String[] chunks) { + if (index < chunk.length() - 1) { + return chunk.charAt(index + 1); + } + if (chunkIndex < chunks.length - 1) { + return chunks[chunkIndex + 1].charAt(0); + } + return '@'; + } + + private Trie addCharacter(Trie node, char c) { + if (!isValidCharacter(c)) { + return node; + } + int index = getIndex(c); + if (node.children[index] == null) { + node.children[index] = new Trie(); + } + return node.children[index]; + } + + private Trie finalizeWordIfNeeded(Trie node, char c) { + if (isValidCharacter(c)) { + return node; + } + incrementCountIfNeeded(node); + return this; + } + + private void incrementCountIfNeeded(Trie node) { + if (node != this) { + node.count++; + } + } + + private static boolean isValidCharacter(char c) { + return c == '-' || isLetter(c); + } + + private int count(String s) { + int n = s.length(); + Trie node = this; + for (int k = 0; k < n; k++) { + int i = getIndex(s.charAt(k)); + if (node.children[i] == null) { + return 0; + } + node = node.children[i]; + } + return node.count; + } + + private static int getIndex(char c) { + return c == '-' ? 26 : c - 'a'; + } + + private static boolean isLetter(char c) { + return 'a' <= c && c <= 'z'; + } + } +} diff --git a/src/main/java/g3901_4000/s3926_count_valid_word_occurrences/readme.md b/src/main/java/g3901_4000/s3926_count_valid_word_occurrences/readme.md new file mode 100644 index 000000000..20dc06863 --- /dev/null +++ b/src/main/java/g3901_4000/s3926_count_valid_word_occurrences/readme.md @@ -0,0 +1,64 @@ +3926\. Count Valid Word Occurrences + +Medium + +You are given an array of strings `chunks`. Concatenate all strings in `chunks` in order to form a string `s`. + +You are also given an array of strings `queries`. + +A **joiner hyphen** is a hyphen character `'-'` in `s` whose previous and next characters both exist and are lowercase English letters. + +A **word** is a **maximal** substring of `s` consisting only of lowercase English letters and **joiner hyphens**. + +All other characters, including spaces and hyphens that are not **joiner hyphens**, are treated as separators. + +Return an integer array `ans`, where `ans[i]` is the number of times `queries[i]` appears as a word in `s`. + +**Example 1:** + +**Input:** chunks = ["hello wor","ld hello"], queries = ["hello","world","wor"] + +**Output:** [2,1,0] + +**Explanation:** + +* After concatenating all strings in `chunks`, `s = "hello world hello"`. +* The words are `"hello"`, `"world"`, and `"hello"`. +* The substring `"wor"` appears inside `"world"`, but it is not a full word. + +**Example 2:** + +**Input:** chunks = ["a-b a--b ","a-","b"], queries = ["a-b","a","b"] + +**Output:** [2,1,1] + +**Explanation:** + +* After concatenating all strings in `chunks`, `s = "a-b a--b a-b"`. +* In `"a-b"`, the hyphen is a joiner hyphen because it is between two lowercase English letters, so `"a-b"` is one word. +* In `"a--b"`, neither hyphen is a joiner hyphen, so it is split into the words `"a"` and `"b"`. +* Therefore, the words are `"a-b"`, `"a"`, `"b"`, and `"a-b"`. + +**Example 3:** + +**Input:** chunks = ["-cat dog- mouse"], queries = ["cat","dog","mouse","cat-dog"] + +**Output:** [1,1,1,0] + +**Explanation:** + +* After concatenating all strings in `chunks`, `s = "-cat dog- mouse"`. +* The leading hyphen before `"cat"` and the trailing hyphen after `"dog"` are not joiner hyphens, so they are separators. +* The words are `"cat"`, `"dog"`, and `"mouse"`. + +**Constraints:** + +* 1 <= chunks.length <= 105 +* 1 <= chunks[i].length <= 105 +* The total length of all strings in `chunks` does not exceed 105. +* `chunks[i]` consists only of lowercase English letters, spaces, and `'-'`. +* 1 <= queries.length <= 105 +* 1 <= queries[i].length <= 105 +* The total length of all strings in `queries` does not exceed 105. +* `queries[i]` consists only of lowercase English letters and `'-'`. +* `queries[i]` is a valid word: it does not start or end with `'-'`, and it does not contain two consecutive hyphens. \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3927_minimize_array_sum_using_divisible_replacements/Solution.java b/src/main/java/g3901_4000/s3927_minimize_array_sum_using_divisible_replacements/Solution.java new file mode 100644 index 000000000..def34e66e --- /dev/null +++ b/src/main/java/g3901_4000/s3927_minimize_array_sum_using_divisible_replacements/Solution.java @@ -0,0 +1,37 @@ +package g3901_4000.s3927_minimize_array_sum_using_divisible_replacements; + +// #Medium #Array #Hash_Table #Math #Greedy #Number_Theory #Staff #Weekly_Contest_501 +// #2026_09_29_Time_11_ms_(96.83%)_Space_130.23_MB_(43.65%) + +public class Solution { + public long minArraySum(int[] nums) { + int max = 0; + long sum = 0; + for (int num : nums) { + if (num == 1) { + return nums.length; + } + if (num > max) { + max = num; + } + } + int[] min = new int[max + 1]; + for (int num : nums) { + min[num] = num; + } + for (int num : nums) { + if (min[num] < num) { + continue; + } + for (int i = num; i <= max; i += num) { + if (num < min[i]) { + min[i] = num; + } + } + } + for (int num : nums) { + sum += min[num]; + } + return sum; + } +} diff --git a/src/main/java/g3901_4000/s3927_minimize_array_sum_using_divisible_replacements/readme.md b/src/main/java/g3901_4000/s3927_minimize_array_sum_using_divisible_replacements/readme.md new file mode 100644 index 000000000..09c5a2dac --- /dev/null +++ b/src/main/java/g3901_4000/s3927_minimize_array_sum_using_divisible_replacements/readme.md @@ -0,0 +1,53 @@ +3927\. Minimize Array Sum Using Divisible Replacements + +Medium + +You are given an integer array `nums`. + +You can perform the following operation any number of times: + +* Choose two indices `a` and `b` such that `nums[a] % nums[b] == 0`. +* Replace `nums[a]` with `nums[b]`. + +Return the **minimum** possible sum of the array after performing any number of operations. + +**Example 1:** + +**Input:** nums = [3,6,2] + +**Output:** 7 + +**Explanation:** + +* Choose `a = 1`, `b = 2`, where `nums[a] = 6` and `nums[b] = 2`. Since `6 % 2 == 0`, replace `nums[1]` with `nums[2]`. +* The array becomes `[3, 2, 2]`. +* No further operation reduces the sum. Thus, the final sum is `3 + 2 + 2 = 7`. + +**Example 2:** + +**Input:** nums = [4,2,8,3] + +**Output:** 9 + +**Explanation:** + +* Choose `a = 0`, `b = 1`, where `nums[a] = 4` and `nums[b] = 2`. Since `4 % 2 == 0`, replace `nums[0]` with `nums[1]`. +* Choose `a = 2`, `b = 1`, where `nums[a] = 8` and `nums[b] = 2`. Since `8 % 2 == 0`, replace `nums[2]` with `nums[1]`. +* The array becomes `[2, 2, 2, 3]`. +* No further operation reduces the sum. Thus, the final sum is `2 + 2 + 2 + 3 = 9`. + +**Example 3:** + +**Input:** nums = [7,5,9] + +**Output:** 21 + +**Explanation:** + +* There is no pair `(a, b)` such that `nums[a] % nums[b] == 0`. +* Hence, no operation can be performed. The sum remains `7 + 5 + 9 = 21`. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 105 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3928_minimum_cost_to_buy_apples_ii/Solution.java b/src/main/java/g3901_4000/s3928_minimum_cost_to_buy_apples_ii/Solution.java new file mode 100644 index 000000000..78b74520f --- /dev/null +++ b/src/main/java/g3901_4000/s3928_minimum_cost_to_buy_apples_ii/Solution.java @@ -0,0 +1,93 @@ +package g3901_4000.s3928_minimum_cost_to_buy_apples_ii; + +// #Hard #Array #Heap_Priority_Queue #Shortest_Path #Senior_Staff #Graph_Theory #Weekly_Contest_501 +// #2026_09_29_Time_694_ms_(97.40%)_Space_49.62_MB_(84.42%) + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.PriorityQueue; + +@SuppressWarnings("java:S1210") +public class Solution { + public int[] minCost(int n, int[] prices, int[][] roads) { + List> adj = adjacency(n, roads); + int[] ans = Arrays.copyOf(prices, n); + for (int i = 0; i < n; ++i) { + long[] forward = shortestPath(adj, i, prices[i], true); + long[] backward = shortestPath(adj, i, prices[i], false); + for (int j = 0; j < n; ++j) { + if (j != i && forward[j] != Long.MAX_VALUE && backward[j] != Long.MAX_VALUE) { + long d = forward[j] + prices[j] + backward[j]; + if (d < ans[i]) { + ans[i] = (int) d; + } + } + } + } + return ans; + } + + private long[] shortestPath(List> adj, int src, int maxPrice, boolean forward) { + long[] dist = new long[adj.size()]; + Arrays.fill(dist, Long.MAX_VALUE); + dist[src] = 0L; + PriorityQueue pq = new PriorityQueue<>(); + pq.offer(new Distance(src, dist[src])); + while (!pq.isEmpty() && pq.peek().dist <= maxPrice) { + Distance distance = pq.poll(); + if (distance.dist > dist[distance.node]) { + continue; + } + for (Edge edge : adj.get(distance.node)) { + long d = forward ? edge.forward : edge.backward; + if (dist[edge.node] > dist[distance.node] + d) { + dist[edge.node] = dist[distance.node] + d; + pq.offer(new Distance(edge.node, dist[edge.node])); + } + } + } + return dist; + } + + private List> adjacency(int n, int[][] roads) { + List> adj = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + adj.add(new ArrayList<>()); + } + for (int[] r : roads) { + long f = r[2]; + long b = f * r[3]; + adj.get(r[0]).add(new Edge(r[1], f, b)); + adj.get(r[1]).add(new Edge(r[0], f, b)); + } + return adj; + } + + private static final class Edge { + private final int node; + private final long forward; + private final long backward; + + private Edge(int node, long forward, long backward) { + this.node = node; + this.forward = forward; + this.backward = backward; + } + } + + private static final class Distance implements Comparable { + private final int node; + private final long dist; + + private Distance(int node, long dist) { + this.node = node; + this.dist = dist; + } + + @Override + public int compareTo(Distance other) { + return Long.compare(this.dist, other.dist); + } + } +} diff --git a/src/main/java/g3901_4000/s3928_minimum_cost_to_buy_apples_ii/readme.md b/src/main/java/g3901_4000/s3928_minimum_cost_to_buy_apples_ii/readme.md new file mode 100644 index 000000000..40648d8c6 --- /dev/null +++ b/src/main/java/g3901_4000/s3928_minimum_cost_to_buy_apples_ii/readme.md @@ -0,0 +1,86 @@ +3928\. Minimum Cost to Buy Apples II + +Hard + +You are given an integer `n` and an integer array `prices` of length `n`, where `prices[i]` is the price of apples at shop `i`. + +You are also given a 2D integer array `roads`, where roads[i] = [ui, vi, costi, taxi] represents a **bidirectional** road: + +* ui and vi are the shops connected by the road. +* costi is the cost to travel the road **without** carrying apples. +* taxi is the multiplier applied to costi when traveling **with** apples. + +For each shop `i`, you can either: + +* Buy apples locally at shop `i` for `prices[i]`. +* Travel **empty** to any shop `j` using **any** number of roads, buy apples for `prices[j]`, and return to shop `i` while carrying apples, paying `cost * tax` on each road used for the return trip. + +The forward path, where you travel empty, and the return path may be **different**. + +Return an integer array `ans` of length `n`, where `ans[i]` is the **minimum** total cost to buy apples starting from shop `i`. + +**Example 1:** + +**Input:** n = 2, prices = [8,3], roads = [[0,1,1,2]] + +**Output:** [6,3] + +**Explanation:** + +![](https://assets.leetcode.com/uploads/2025/08/22/screenshot-2025-08-23-at-23341-am.png) + +| Shop `i` | `prices[i]` | Shop `j` | `prices[j]` | `costᵢ` | `taxᵢ` | Travel cost | Return cost | Total | Minimum | +| -------: | ----------: | -------: | ----------: | ------: | -----: | ----------: | ----------: | ---------------: | ---------------: | +| 0 | 8 | 1 | 3 | 1 | 2 | 1 | `1 * 2 = 2` | `1 + 2 + 3 = 6` | `min(8, 6) = 6` | +| 1 | 3 | 0 | 8 | 1 | 2 | 1 | `1 * 2 = 2` | `1 + 2 + 8 = 11` | `min(3, 11) = 3` | + +Thus, the answer is `[6, 3]`. + +**Example 2:** + +**Input:** n = 3, prices = [9,4,6], roads = [[0,1,1,3],[1,2,4,2]] + +**Output:** [8,4,6] + +**Explanation:** + +![](https://assets.leetcode.com/uploads/2025/08/22/screenshot-2025-08-23-at-23736-am.png) + +| Shop `i` | `prices[i]` | Shop `j` | `prices[j]` | `costᵢ` | `taxᵢ` | Travel cost | Return cost | Total | Minimum | +| -------: | ----------: | -------: | ----------: | ------: | -----: | ----------: | ----------: | ---------------: | ---------------: | +| 0 | 9 | 1 | 4 | 1 | 3 | 1 | `1 * 3 = 3` | `1 + 3 + 4 = 8` | `min(9, 8) = 8` | +| 1 | 4 | 2 | 6 | 4 | 2 | 4 | `4 * 2 = 8` | `4 + 8 + 6 = 18` | `min(4, 18) = 4` | +| 2 | 6 | 1 | 4 | 4 | 2 | 4 | `4 * 2 = 8` | `4 + 8 + 4 = 16` | `min(6, 16) = 6` | + +Thus, the answer is `[8, 4, 6]`. + +**Example 3:** + +**Input:** n = 3, prices = [10,11,1], roads = [[0,2,1,3],[1,2,3,4],[0,1,5,2]] + +**Output:** [5,11,1] + +**Explanation:** + +![](https://assets.leetcode.com/uploads/2025/08/22/screenshot-2025-08-23-at-24644-am.png) + +| Shop `i` | `prices[i]` | Shop `j` | `prices[j]` | `costᵢ` | `taxᵢ` | Travel cost | Return cost | Total | Minimum | +| -------: | ----------: | -------: | ----------: | ------: | -----: | ----------: | -----------: | ----------------: | -----------------: | +| 0 | 10 | 2 | 1 | 1 | 3 | 1 | `1 * 3 = 3` | `1 + 3 + 1 = 5` | `min(10, 5) = 5` | +| 1 | 11 | 2 | 1 | 3 | 4 | 3 | `3 * 4 = 12` | `3 + 12 + 1 = 16` | `min(11, 16) = 11` | +| 2 | 1 | 0 | 10 | 1 | 3 | 1 | `1 * 3 = 3` | `1 + 3 + 10 = 14` | `min(1, 14) = 1` | + +Thus, the answer is `[5, 11, 1]`. + +**Constraints:** + +* `1 <= n <= 1000` +* `prices.length == n` +* 1 <= prices[i] <= 109 +* `0 <= roads.length <= min(n × (n - 1) / 2, 2000)` +* roads[i] = [ui, vi, costi, taxi] +* 0 <= ui, vi <= n - 1 +* ui != vi +* 1 <= costi <= 109 +* 1 <= taxi <= 100 +* There are no **repeated** edges. diff --git a/src/main/java/g3901_4000/s3931_check_adjacent_digit_differences/Solution.java b/src/main/java/g3901_4000/s3931_check_adjacent_digit_differences/Solution.java new file mode 100644 index 000000000..7698cc431 --- /dev/null +++ b/src/main/java/g3901_4000/s3931_check_adjacent_digit_differences/Solution.java @@ -0,0 +1,15 @@ +package g3901_4000.s3931_check_adjacent_digit_differences; + +// #Easy #String #Mid_Level #Weekly_Contest_502 +// #2026_09_29_Time_1_ms_(100.00%)_Space_43.68_MB_(59.35%) + +public class Solution { + public boolean isAdjacentDiffAtMostTwo(String s) { + for (int i = 0; i < s.length() - 1; i++) { + if (Math.abs(s.charAt(i) - s.charAt(i + 1)) > 2) { + return false; + } + } + return true; + } +} diff --git a/src/main/java/g3901_4000/s3931_check_adjacent_digit_differences/readme.md b/src/main/java/g3901_4000/s3931_check_adjacent_digit_differences/readme.md new file mode 100644 index 000000000..8d25622d7 --- /dev/null +++ b/src/main/java/g3901_4000/s3931_check_adjacent_digit_differences/readme.md @@ -0,0 +1,38 @@ +3931\. Check Adjacent Digit Differences + +Easy + +You are given a string `s` consisting of digits. + +Return `true` if the **absolute difference** between every pair of **adjacent** digits is at most 2, otherwise return `false`. + +The absolute difference between `a` and `b` is defined as `abs(a - b)`. + +**Example 1:** + +**Input:** s = "132" + +**Output:** true + +**Explanation:** + +* The absolute difference between digits at `s[0]` and `s[1]` is `abs(1 - 3) = 2`. +* The absolute difference between digits at `s[1]` and `s[2]` is `abs(3 - 2) = 1`. +* Since both differences are at most 2, the answer is true. + +**Example 2:** + +**Input:** s = "129" + +**Output:** false + +**Explanation:** + +* The absolute difference between digits at `s[0]` and `s[1]` is `abs(1 - 2) = 1`. +* The absolute difference between digits at `s[1]` and `s[2]` is `abs(2 - 9) = 7`, which is greater than 2. +* Therefore, the answer is false. + +**Constraints:** + +* `2 <= s.length <= 100` +* `s` consists only of digits. \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3932_count_k_th_roots_in_a_range/Solution.java b/src/main/java/g3901_4000/s3932_count_k_th_roots_in_a_range/Solution.java new file mode 100644 index 000000000..e67ee9f7c --- /dev/null +++ b/src/main/java/g3901_4000/s3932_count_k_th_roots_in_a_range/Solution.java @@ -0,0 +1,25 @@ +package g3901_4000.s3932_count_k_th_roots_in_a_range; + +// #Medium #Math #Binary_Search #Senior #Weekly_Contest_502 +// #2026_09_29_Time_1_ms_(100.00%)_Space_42.94_MB_(7.52%) + +public class Solution { + public int countKthRoots(int l, int r, int k) { + if (k == 1) { + return r - l + 1; + } + int ans = 0; + int start = 0; + int pow = (int) Math.pow(start, k); + while (l > pow) { + start++; + pow = (int) Math.pow(start, k); + } + while (pow <= r) { + start++; + pow = (int) Math.pow(start, k); + ans++; + } + return ans; + } +} diff --git a/src/main/java/g3901_4000/s3932_count_k_th_roots_in_a_range/readme.md b/src/main/java/g3901_4000/s3932_count_k_th_roots_in_a_range/readme.md new file mode 100644 index 000000000..40a2ed79a --- /dev/null +++ b/src/main/java/g3901_4000/s3932_count_k_th_roots_in_a_range/readme.md @@ -0,0 +1,45 @@ +3932\. Count K-th Roots in a Range + +Medium + +You are given three integers `l`, `r`, and `k`. + +An integer `y` is said to be a **perfect kth power** if there exists an integer `x` such that y = xk. + +Return the number of integers `y` in the range `[l, r]` (inclusive) that are **perfect kth powers**. + +**Example 1:** + +**Input:** l = 1, r = 9, k = 3 + +**Output:** 2 + +**Explanation:** + +The perfect cubes in the range `[1, 9]` are: + +* 1 = 13 +* 8 = 23 + +Hence, the answer is 2. + +**Example 2:** + +**Input:** l = 8, r = 30, k = 2 + +**Output:** 3 + +**Explanation:** + +The perfect squares in the range `[8, 30]` are: + +* 9 = 32 +* 16 = 42 +* 25 = 52 + +Hence, the answer is 3. + +**Constraints:** + +* 0 <= l <= r <= 109 +* `1 <= k <= 30` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3933_largest_local_values_in_a_matrix_ii/Solution.java b/src/main/java/g3901_4000/s3933_largest_local_values_in_a_matrix_ii/Solution.java new file mode 100644 index 000000000..57994e4e8 --- /dev/null +++ b/src/main/java/g3901_4000/s3933_largest_local_values_in_a_matrix_ii/Solution.java @@ -0,0 +1,87 @@ +package g3901_4000.s3933_largest_local_values_in_a_matrix_ii; + +// #Medium #Array #Matrix #Prefix_Sum #Staff #Weekly_Contest_502 +// #2026_09_29_Time_40_ms_(100.00%)_Space_163.99_MB_(56.67%) + +public class Solution { + public int countLocalMaximums(int[][] matrix) { + int n = matrix.length; + int m = matrix[0].length; + int wn = 32 - Integer.numberOfLeadingZeros(n); + int wm = 32 - Integer.numberOfLeadingZeros(m); + int[][][][] st = buildSparseTable(matrix, n, m, wn, wm); + return countMaximums(matrix, st, n, m); + } + + private int[][][][] buildSparseTable(int[][] matrix, int n, int m, int wn, int wm) { + int[][][][] st = new int[wn][wm][n][m]; + st[0][0] = matrix; + buildHorizontalLevels(st, n, m, wm); + buildVerticalLevels(st, n, m, wn, wm); + return st; + } + + private void buildHorizontalLevels(int[][][][] st, int n, int m, int wm) { + for (int k2 = 1; k2 < wm; k2++) { + int half = 1 << (k2 - 1); + int width = 1 << k2; + for (int i = 0; i < n; i++) { + for (int j = 0; j <= m - width; j++) { + st[0][k2][i][j] = Math.max(st[0][k2 - 1][i][j], st[0][k2 - 1][i][j + half]); + } + } + } + } + + private void buildVerticalLevels(int[][][][] st, int n, int m, int wn, int wm) { + for (int k1 = 1; k1 < wn; k1++) { + int half = 1 << (k1 - 1); + int height = 1 << k1; + for (int k2 = 0; k2 < wm; k2++) { + int width = 1 << k2; + for (int i = 0; i <= n - height; i++) { + for (int j = 0; j <= m - width; j++) { + st[k1][k2][i][j] = + Math.max(st[k1 - 1][k2][i][j], st[k1 - 1][k2][i + half][j]); + } + } + } + } + } + + private int countMaximums(int[][] matrix, int[][][][] st, int n, int m) { + int ans = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (isLocalMaximum(matrix, st, i, j, n, m)) { + ans++; + } + } + } + return ans; + } + + private boolean isLocalMaximum(int[][] matrix, int[][][][] st, int i, int j, int n, int m) { + int x = matrix[i][j]; + if (x == 0) { + return false; + } + int max1 = query(st, i - x, j - x + 1, i + x + 1, j + x, n, m); + int max2 = query(st, i - x + 1, j - x, i + x, j + x + 1, n, m); + return Math.max(max1, max2) <= x; + } + + private int query(int[][][][] st, int r1, int c1, int r2, int c2, int n, int m) { + r1 = Math.max(r1, 0); + c1 = Math.max(c1, 0); + r2 = Math.min(r2, n); + c2 = Math.min(c2, m); + int k1 = 31 - Integer.numberOfLeadingZeros(r2 - r1); + int k2 = 31 - Integer.numberOfLeadingZeros(c2 - c1); + int bottom = r2 - (1 << k1); + int right = c2 - (1 << k2); + return Math.max( + Math.max(st[k1][k2][r1][c1], st[k1][k2][bottom][c1]), + Math.max(st[k1][k2][r1][right], st[k1][k2][bottom][right])); + } +} diff --git a/src/main/java/g3901_4000/s3933_largest_local_values_in_a_matrix_ii/readme.md b/src/main/java/g3901_4000/s3933_largest_local_values_in_a_matrix_ii/readme.md new file mode 100644 index 000000000..2451b5d9d --- /dev/null +++ b/src/main/java/g3901_4000/s3933_largest_local_values_in_a_matrix_ii/readme.md @@ -0,0 +1,69 @@ +3933\. Largest Local Values in a Matrix II + +Medium + +You are given an `n x m` integer matrix `matrix` containing non-negative integers. + +A **non-zero** cell `(row, col)` checks the cells near it as follows: + +* Let `x = matrix[row][col]`. +* Consider every cell within `x` rows and `x` columns of `(row, col)`. +* Ignore cells that are outside the matrix. +* Ignore the cells where both the row distance and column distance are exactly `x`. + +The cell `(row, col)` is a **local maximum** if it is **non-zero** and no considered cell has a value **greater than** `x`. + +Return an integer denoting the number of **local maximums** in `matrix`. + +**Example 1:** + +**Input:** matrix = [[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,2,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0]] + +**Output:** 1 + +![](https://assets.leetcode.com/uploads/2026/05/13/chatgpt-image-may-14-2026-01_53_19-am.png) + +**Explanation:** + +* For the non-zero cell `(3, 3)`, `x = matrix[3][3] = 2`. +* The highlighted cells are the considered cells within `x` rows and `x` columns of `(3, 3)`. +* The four cells with both row and column distances equal to `x = 2` are ignored. +* No considered cell has a value greater than 2, so `(3, 3)` is a local maximum. +* There are no other non-zero cells, so the answer is 1. + +**Example 2:** + +**Input:** matrix = [[1,2],[3,4]] + +**Output:** 1 + +**Explanation:** + +Only the cell with value 4 is a local maximum. Every other non-zero cell considers a cell with a greater value. + +**Example 3:** + +**Input:** matrix = [[1,0,1],[0,1,0],[1,0,1]] + +**Output:** 5 + +**Explanation:** + +* For a cell with value 1, the considered cells are the cell itself and its 4-directionally adjacent cells that are inside the matrix. +* Each of the five cells with value 1 only considers cells with values 0 or 1, so all five of them are local maximums. + +**Example 4:** + +**Input:** matrix = [[1,1],[1,1]] + +**Output:** 4 + +**Explanation:** + +All cells have the same value. Therefore, no cell considers another cell with a greater value, so all 4 cells are local maximums. + +**Constraints:** + +* `1 <= n == matrix.length <= 200` +* `1 <= m == matrix[i].length <= 200` +* `0 <= matrix[i][j] <= 200` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3934_smallest_unique_subarray/Solution.java b/src/main/java/g3901_4000/s3934_smallest_unique_subarray/Solution.java new file mode 100644 index 000000000..23d68a4f4 --- /dev/null +++ b/src/main/java/g3901_4000/s3934_smallest_unique_subarray/Solution.java @@ -0,0 +1,240 @@ +package g3901_4000.s3934_smallest_unique_subarray; + +// #Hard #Array #Hash_Table #Binary_Search #Hash_Function #Rolling_Hash #Suffix_Array #Senior_Staff +// #Weekly_Contest_502 #2026_09_29_Time_215_ms_(100.00%)_Space_95.82_MB_(94.20%) + +import java.util.Arrays; + +public class Solution { + public int smallestUniqueSubarray(int[] nums) { + int n = nums.length; + if (n == 1) { + return 1; + } + int[] sa = buildSuffixArray(nums); + int[] lcp = buildLCP(nums, sa); + return findSmallestUniqueLength(sa, lcp, n); + } + + private int findSmallestUniqueLength(int[] sa, int[] lcp, int n) { + int ans = n; + for (int rank = 0; rank < n; rank++) { + int maxLcp = getMaxLcp(rank, lcp, n); + int suffixLength = n - sa[rank]; + int uniqueLength = maxLcp + 1; + + if (uniqueLength <= suffixLength) { + ans = Math.min(ans, uniqueLength); + } + } + return ans; + } + + private int getMaxLcp(int rank, int[] lcp, int n) { + int maxLcp = 0; + if (rank > 0) { + maxLcp = Math.max(maxLcp, lcp[rank - 1]); + } + if (rank < n - 1) { + maxLcp = Math.max(maxLcp, lcp[rank]); + } + return maxLcp; + } + + // ------------------------------------------------------------ + // Build suffix array using prefix doubling + counting sort + // ------------------------------------------------------------ + private int[] buildSuffixArray(int[] nums) { + int n = nums.length; + int m = n + 1; + int[] a = addSentinel(nums); + SuffixArrayData data = initializeSuffixArray(a, m); + for (int len = 1; len < m && data.classes < m; len *= 2) { + buildNextSuffixArray(data, len, m); + if (shouldStopDoubling(len, m)) { + break; + } + } + return removeSentinel(data.sa, n); + } + + private int[] addSentinel(int[] nums) { + int[] a = Arrays.copyOf(nums, nums.length + 1); + a[nums.length] = 0; + return a; + } + + private SuffixArrayData initializeSuffixArray(int[] a, int m) { + int[] sa = new int[m]; + int[] rank = new int[m]; + int[] tmpRank = new int[m]; + int[] tmpSa = new int[m]; + int maxValue = Math.max(100000, m) + 1; + int[] count = new int[maxValue]; + sortInitialValues(a, sa, count); + int classes = assignInitialRanks(a, sa, rank); + return new SuffixArrayData(sa, rank, tmpRank, tmpSa, count, classes); + } + + private void sortInitialValues(int[] a, int[] sa, int[] count) { + for (int x : a) { + count[x]++; + } + buildPrefixCounts(count); + for (int i = a.length - 1; i >= 0; i--) { + sa[--count[a[i]]] = i; + } + } + + private void buildPrefixCounts(int[] count) { + for (int i = 1; i < count.length; i++) { + count[i] += count[i - 1]; + } + } + + private void buildPrefixCounts(int[] count, int classes) { + for (int i = 1; i < classes; i++) { + count[i] += count[i - 1]; + } + } + + private int assignInitialRanks(int[] a, int[] sa, int[] rank) { + int classes = 1; + rank[sa[0]] = 0; + for (int i = 1; i < a.length; i++) { + if (a[sa[i]] != a[sa[i - 1]]) { + classes++; + } + rank[sa[i]] = classes - 1; + } + return classes; + } + + private SuffixArrayData buildNextSuffixArray(SuffixArrayData data, int len, int m) { + shiftSuffixes(data.sa, data.tmpSa, len, m); + countingSortByRank(data, m); + int newClasses = assignNewRanks(data, len, m); + int[] swap = data.rank; + data.rank = data.tmpRank; + data.tmpRank = swap; + data.classes = newClasses; + return data; + } + + private void shiftSuffixes(int[] sa, int[] tmpSa, int len, int m) { + for (int i = 0; i < m; i++) { + int shifted = sa[i] - len; + if (shifted < 0) { + shifted += m; + } + tmpSa[i] = shifted; + } + } + + private void countingSortByRank(SuffixArrayData data, int m) { + Arrays.fill(data.count, 0, data.classes, 0); + for (int i = 0; i < m; i++) { + data.count[data.rank[data.tmpSa[i]]]++; + } + buildPrefixCounts(data.count, data.classes); + for (int i = m - 1; i >= 0; i--) { + int x = data.tmpSa[i]; + data.sa[--data.count[data.rank[x]]] = x; + } + } + + private int assignNewRanks(SuffixArrayData data, int len, int m) { + data.tmpRank[data.sa[0]] = 0; + int newClasses = 1; + for (int i = 1; i < m; i++) { + int cur = data.sa[i]; + int prev = data.sa[i - 1]; + if (differentRanks(data.rank, cur, prev, len, m)) { + newClasses++; + } + data.tmpRank[cur] = newClasses - 1; + } + return newClasses; + } + + private boolean differentRanks(int[] rank, int cur, int prev, int len, int m) { + int curSecond = (cur + len) % m; + int prevSecond = (prev + len) % m; + return rank[cur] != rank[prev] || rank[curSecond] != rank[prevSecond]; + } + + private boolean shouldStopDoubling(int len, int m) { + return len > m / 2; + } + + private int[] removeSentinel(int[] sa, int n) { + int[] result = new int[n]; + int idx = 0; + for (int x : sa) { + if (x != n) { + result[idx++] = x; + } + } + return result; + } + + private int[] buildLCP(int[] nums, int[] sa) { + int n = nums.length; + int[] rank = buildRanks(sa, n); + int[] lcp = new int[n - 1]; + buildLcpValues(nums, sa, rank, lcp, n); + return lcp; + } + + private int[] buildRanks(int[] sa, int n) { + int[] rank = new int[n]; + for (int i = 0; i < n; i++) { + rank[sa[i]] = i; + } + return rank; + } + + private void buildLcpValues(int[] nums, int[] sa, int[] rank, int[] lcp, int n) { + int k = 0; + for (int i = 0; i < n; i++) { + int r = rank[i]; + if (r == n - 1) { + k = 0; + continue; + } + int j = sa[r + 1]; + k = calculateLcp(nums, i, j, k); + lcp[r] = k; + if (k > 0) { + k--; + } + } + } + + private int calculateLcp(int[] nums, int i, int j, int k) { + while (i + k < nums.length && j + k < nums.length && nums[i + k] == nums[j + k]) { + k++; + } + return k; + } + + private static class SuffixArrayData { + private int[] sa; + private int[] rank; + private int[] tmpRank; + private final int[] tmpSa; + private final int[] count; + private int classes; + + private SuffixArrayData( + int[] sa, int[] rank, int[] tmpRank, int[] tmpSa, int[] count, int classes) { + + this.sa = sa; + this.rank = rank; + this.tmpRank = tmpRank; + this.tmpSa = tmpSa; + this.count = count; + this.classes = classes; + } + } +} diff --git a/src/main/java/g3901_4000/s3934_smallest_unique_subarray/readme.md b/src/main/java/g3901_4000/s3934_smallest_unique_subarray/readme.md new file mode 100644 index 000000000..f779f5671 --- /dev/null +++ b/src/main/java/g3901_4000/s3934_smallest_unique_subarray/readme.md @@ -0,0 +1,68 @@ +3934\. Smallest Unique Subarray + +Hard + +You are given an integer array `nums`. + +Find the **minimum** length of a subarray that is **not** **identical** to any other **subarray** in `nums`. + +Return an integer denoting the **minimum possible length** of such a **subarray**. + +Two **subarrays** are considered identical if they have the same length and the same elements in corresponding positions. + +**Example 1:** + +**Input:** nums = [3,3,3] + +**Output:** 3 + +**Explanation:** + +* Subarrays of length 1: `[3]` → appears 3 times +* Subarrays of length 2: `[3, 3]` → appears 2 times +* Subarrays of length 3: `[3, 3, 3]` → appears once + +The subarray `[3, 3, 3]` is unique, so the smallest unique subarray length is 3. + +**Example 2:** + +**Input:** nums = [2,1,2,3,3] + +**Output:** 1 + +**Explanation:** + +Subarrays of length 1: + +* `[2]` → appears 2 times +* `[1]` → appears once +* `[3]` → appears 2 times + +The subarray `[1]` is unique, so the smallest unique subarray length is 1. + +**Example 3:** + +**Input:** nums = [1,1,2,2,1] + +**Output:** 2 + +**Explanation:** + +Subarrays of length 1: + +* `[1]` → appears 3 times +* `[2]` → appears 2 times + +Subarrays of length 2: + +* `[1, 1]` → appears once +* `[1, 2]` → appears once +* `[2, 2]` → appears once +* `[2, 1]` → appears once + +There is at least one subarray of length 2 that is unique, so the smallest unique subarray length is 2. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 105 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3936_minimum_swaps_to_move_zeros_to_end/Solution.java b/src/main/java/g3901_4000/s3936_minimum_swaps_to_move_zeros_to_end/Solution.java new file mode 100644 index 000000000..33831b916 --- /dev/null +++ b/src/main/java/g3901_4000/s3936_minimum_swaps_to_move_zeros_to_end/Solution.java @@ -0,0 +1,32 @@ +package g3901_4000.s3936_minimum_swaps_to_move_zeros_to_end; + +// #Easy #Array #Two_Pointers #Mid_Level #Biweekly_Contest_183 +// #2026_09_29_Time_1_ms_(99.59%)_Space_46.22_MB_(83.18%) + +public class Solution { + private void swap(int[] nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } + + public int minimumSwaps(int[] nums) { + int n = nums.length; + int count = 0; + int l = 0; + int r = n - 1; + while (l < r) { + if (nums[l] == 0 && nums[r] != 0) { + swap(nums, l, r); + count++; + l++; + r--; + } else if (nums[l] != 0) { + l++; + } else if (nums[r] == 0) { + r--; + } + } + return count; + } +} diff --git a/src/main/java/g3901_4000/s3936_minimum_swaps_to_move_zeros_to_end/readme.md b/src/main/java/g3901_4000/s3936_minimum_swaps_to_move_zeros_to_end/readme.md new file mode 100644 index 000000000..b5c02c5ad --- /dev/null +++ b/src/main/java/g3901_4000/s3936_minimum_swaps_to_move_zeros_to_end/readme.md @@ -0,0 +1,53 @@ +3936\. Minimum Swaps to Move Zeros to End + +Easy + +You are given an integer array `nums`. + +In one operation, you can choose any two **distinct** indices `i` and `j` and swap `nums[i]` and `nums[j]`. + +Return an integer denoting the **minimum** number of operations required to move all 0s to the end of the array. + +**Example 1:** + +**Input:** nums = [0,1,0,3,12] + +**Output:** 2 + +**Explanation:** + +We perform the following swap operations: + +* Swap `nums[0]` and `nums[3]`, giving `nums = [3, 1, 0, 0, 12]`. +* Swap `nums[2]` and `nums[4]`, giving `nums = [3, 1, 12, 0, 0]`. + +Thus, the answer is 2. + +**Example 2:** + +**Input:** nums = [0,1,0,2] + +**Output:** 1 + +**Explanation:** + +We perform the following swap operations: + +* Swap `nums[0]` and `nums[3]`, giving `nums = [2, 1, 0, 0]`. + +Thus, the answer is 1. + +**Example 3:** + +**Input:** nums = [1,2,0] + +**Output:** 0 + +**Explanation:** + +The array already satisfies the condition. Therefore, no swap operations are needed. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `0 <= nums[i] <= 100` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3937_minimum_operations_to_make_array_modulo_alternating_i/Solution.java b/src/main/java/g3901_4000/s3937_minimum_operations_to_make_array_modulo_alternating_i/Solution.java new file mode 100644 index 000000000..7ee855a7b --- /dev/null +++ b/src/main/java/g3901_4000/s3937_minimum_operations_to_make_array_modulo_alternating_i/Solution.java @@ -0,0 +1,32 @@ +package g3901_4000.s3937_minimum_operations_to_make_array_modulo_alternating_i; + +// #Medium #Array #Enumeration #Senior #Biweekly_Contest_183 +// #2026_09_29_Time_5_ms_(98.11%)_Space_44.80_MB_(86.79%) + +public class Solution { + public int minOperations(int[] nums, int k) { + int[] even = new int[k]; + int[] odd = new int[k]; + for (int i = 0; i < nums.length; i++) { + int rem = nums[i] % k; + for (int j = 0; j < k; j++) { + int diff = Math.abs(rem - j); + int cost = Math.min(diff, k - diff); + if (i % 2 == 0) { + even[j] += cost; + } else { + odd[j] += cost; + } + } + } + int ans = Integer.MAX_VALUE; + for (int x = 0; x < k; x++) { + for (int y = 0; y < k; y++) { + if (x != y) { + ans = Math.min(ans, odd[x] + even[y]); + } + } + } + return ans; + } +} diff --git a/src/main/java/g3901_4000/s3937_minimum_operations_to_make_array_modulo_alternating_i/readme.md b/src/main/java/g3901_4000/s3937_minimum_operations_to_make_array_modulo_alternating_i/readme.md new file mode 100644 index 000000000..fff279274 --- /dev/null +++ b/src/main/java/g3901_4000/s3937_minimum_operations_to_make_array_modulo_alternating_i/readme.md @@ -0,0 +1,46 @@ +3937\. Minimum Operations to Make Array Modulo Alternating I + +Medium + +You are given an integer array `nums` and an integer `k`. + +In one operation, you can **increase** or **decrease** any element of `nums` by 1. + +An array is called **modulo alternating** if there exist two **distinct** integers `x` and `y` (`0 <= x, y < k`) such that: + +* For every **even** index `i`, `nums[i] % k == x` +* For every **odd** index `i`, `nums[i] % k == y` + +Return the **minimum** number of operations required to make `nums` **modulo alternating**. + +**Example 1:** + +**Input:** nums = [1,4,2,8], k = 3 + +**Output:** 2 + +**Explanation:** + +* Let's choose `x = 1` for even indices and `y = 2` for odd indices. +* Perform the following operations: + * Increment `nums[1] = 4` by 1, giving `nums = [1, 5, 2, 8]`. + * Decrement `nums[2] = 2` by 1, giving `nums = [1, 5, 1, 8]`. +* Now, for even indices, `nums[i] % k = 1`, and for odd indices, `nums[i] % k = 2`. +* Thus, the total number of operations required is 2. + +**Example 2:** + +**Input:** nums = [1,1,1], k = 3 + +**Output:** 1 + +**Explanation:** + +* Incrementing `nums[1]` by 1 gives `nums = [1, 2, 1]`, which satisfies the condition with `x = 1` and `y = 2`. +* Thus, the total number of operations required is 1. + +**Constraints:** + +* `1 <= nums.length <= 100` +* 1 <= nums[i] <= 109 +* `2 <= k <= 100` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3938_maximum_path_intersection_sum_in_a_grid/Solution.java b/src/main/java/g3901_4000/s3938_maximum_path_intersection_sum_in_a_grid/Solution.java new file mode 100644 index 000000000..cdb4ad4cc --- /dev/null +++ b/src/main/java/g3901_4000/s3938_maximum_path_intersection_sum_in_a_grid/Solution.java @@ -0,0 +1,35 @@ +package g3901_4000.s3938_maximum_path_intersection_sum_in_a_grid; + +// #Medium #Array #Dynamic_Programming #Matrix #Prefix_Sum #Staff #Biweekly_Contest_183 +// #2026_09_29_Time_9_ms_(100.00%)_Space_181.37_MB_(48.98%) + +public class Solution { + public int maxScore(int[][] grid) { + int ans = Integer.MIN_VALUE; + int m = grid.length; + int n = grid[0].length; + // 1. Check all strictly interior single cells + for (int i = 1; i < m - 1; i++) { + for (int j = 1; j < n - 1; j++) { + ans = Math.max(ans, grid[i][j]); + } + } + // 2. Modified Kadane's for Rows (Minimum length 2) + for (int[] ints : grid) { + int currentSum = ints[0]; + for (int j = 1; j < n; j++) { + ans = Math.max(ans, currentSum + ints[j]); + currentSum = Math.max(ints[j], currentSum + ints[j]); + } + } + // 3. Modified Kadane's for Columns (Minimum length 2) + for (int j = 0; j < n; j++) { + int currentSum = grid[0][j]; + for (int i = 1; i < m; i++) { + ans = Math.max(ans, currentSum + grid[i][j]); + currentSum = Math.max(grid[i][j], currentSum + grid[i][j]); + } + } + return ans; + } +} diff --git a/src/main/java/g3901_4000/s3938_maximum_path_intersection_sum_in_a_grid/readme.md b/src/main/java/g3901_4000/s3938_maximum_path_intersection_sum_in_a_grid/readme.md new file mode 100644 index 000000000..8f8ed65ef --- /dev/null +++ b/src/main/java/g3901_4000/s3938_maximum_path_intersection_sum_in_a_grid/readme.md @@ -0,0 +1,62 @@ +3938\. Maximum Path Intersection Sum in a Grid + +Medium + +You are given an `m x n` integer matrix `grid`. + +Two players move across the grid: + +* Player 1 starts at the top-left cell `(0, 0)` and can move only right or down. Their destination is the bottom-right cell `(m - 1, n - 1)`. +* Player 2 starts at the bottom-left cell `(m - 1, 0)` and can move only right or up. Their destination is the top-right cell `(0, n - 1)`. + +Each player must choose a valid path from their respective starting cell to their destination. + +A cell is called **shared** if it belongs to **both** chosen paths. + +Return an integer denoting the **maximum** possible sum of values of all **shared** cells. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2026/05/19/image.png) + +**Input:** grid = [[1,2,0,-3],[1,-2,1,0],[-4,2,-1,3],[3,-3,3,-2],[-1,-5,0,1]] + +**Output:** 4 + +**Explanation:** + +The diagram shows one optimal choice of paths. + +* Player 1 follows the red/purple path from the top-left cell to the bottom-right cell: + * `(0, 0) → (1, 0) → (2, 0) → (2, 1) → (2, 2) → (2, 3) → (3, 3) → (4, 3)` +* Player 2 follows the blue/purple path from the bottom-left cell to the top-right cell: + * `(4, 0) → (4, 1) → (3, 1) → (2, 1) → (2, 2) → (2, 3) → (1, 3) → (0, 3)` +* The shared cells are `(2, 1)`, `(2, 2)`, and `(2, 3)`. +* The sum is `2 + (-1) + 3 = 4`, which is the maximum possible sum. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2026/05/19/chatgpt-image-may-19-2026-01_39_39-pm.png) + +**Input:** grid = [[4,-2,-3],[-1,-3,-1],[-4,2,-1]] + +**Output:** 3 + +**Explanation:** + +One optimal pair of paths is shown in the diagram. + +* Player 1 follows the red/purple path: + * `(0, 0) → (1, 0) → (1, 1) → (1, 2) → (2, 2)` +* Player 2 follows the blue/purple path: + * `(2, 0) → (1, 0) → (0, 0) → (0, 1) → (0, 2)` +* The shared cells are `(0, 0)` and `(1, 0)`. +* The sum is `4 + (-1) = 3`, which is the maximum possible. + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `2 <= m, n <= 1000` +* 4 <= m * n <= 5 * 105 +* `-100 <= grid[i][j] <= 100` \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3939_count_non_adjacent_subsets_in_a_rooted_tree/Solution.java b/src/main/java/g3901_4000/s3939_count_non_adjacent_subsets_in_a_rooted_tree/Solution.java new file mode 100644 index 000000000..c4eb83656 --- /dev/null +++ b/src/main/java/g3901_4000/s3939_count_non_adjacent_subsets_in_a_rooted_tree/Solution.java @@ -0,0 +1,112 @@ +package g3901_4000.s3939_count_non_adjacent_subsets_in_a_rooted_tree; + +// #Hard #Array #Dynamic_Programming #Tree #Senior_Staff #Biweekly_Contest_183 #Depth_First_Search +// #2026_09_29_Time_83_ms_(94.12%)_Space_49.60_MB_(29.41%) + +import java.util.Arrays; + +public class Solution { + private static final int MOD = 1000000007; + + public int countValidSubsets(int[] parent, int[] nums, int k) { + int n = parent.length; + int[] h = new int[n]; + int[] to = new int[n - 1]; + int[] nx = new int[n - 1]; + buildTree(parent, h, to, nx); + long[][][] dp = new long[n][2][k]; + dfs(0, h, to, nx, nums, k, dp); + return getResult(dp); + } + + private void buildTree(int[] parent, int[] h, int[] to, int[] nx) { + Arrays.fill(h, -1); + int idx = 0; + for (int i = 1; i < parent.length; i++) { + to[idx] = i; + nx[idx] = h[parent[i]]; + h[parent[i]] = idx++; + } + } + + private void dfs(int u, int[] h, int[] to, int[] nx, int[] nums, int k, long[][][] dp) { + initializeDp(u, nums, k, dp); + for (int e = h[u]; e != -1; e = nx[e]) { + int v = to[e]; + dfs(v, h, to, nx, nums, k, dp); + mergeChild(dp[u], dp[v], k); + } + } + + private void initializeDp(int u, int[] nums, int k, long[][][] dp) { + dp[u][0][0] = 1; + dp[u][1][nums[u] % k] = 1; + } + + private void mergeChild(long[][] current, long[][] child, int k) { + long[][] next = new long[2][k]; + mergeExcludedState(current[0], child, next[0], k); + mergeSelectedState(current[1], child[0], next[1], k); + copyState(next, current, k); + } + + private void mergeExcludedState(long[] current, long[][] child, long[] next, int k) { + for (int a = 0; a < k; a++) { + if (current[a] != 0) { + mergeWithChildStates(current[a], child[0], child[1], next, a, k); + } + } + } + + private void mergeSelectedState(long[] current, long[] childExcluded, long[] next, int k) { + for (int a = 0; a < k; a++) { + if (current[a] != 0) { + mergeWithSingleChildState(current[a], childExcluded, next, a, k); + } + } + } + + private void mergeWithChildStates( + long currentWays, + long[] childExcluded, + long[] childSelected, + long[] next, + int currentMod, + int k) { + for (int childMod = 0; childMod < k; childMod++) { + long childWays = (childExcluded[childMod] + childSelected[childMod]) % MOD; + addWays(next, currentMod, childMod, currentWays, childWays, k); + } + } + + private void mergeWithSingleChildState( + long currentWays, long[] child, long[] next, int currentMod, int k) { + for (int childMod = 0; childMod < k; childMod++) { + addWays(next, currentMod, childMod, currentWays, child[childMod], k); + } + } + + private void addWays( + long[] target, int currentMod, int childMod, long currentWays, long childWays, int k) { + if (childWays == 0) { + return; + } + int newMod = (currentMod + childMod) % k; + target[newMod] = (target[newMod] + currentWays * childWays) % MOD; + } + + private void copyState(long[][] source, long[][] target, int k) { + for (int state = 0; state < 2; state++) { + if (k >= 0) { + System.arraycopy(source[state], 0, target[state], 0, k); + } + } + } + + private int getResult(long[][][] dp) { + long result = dp[0][0][0] + dp[0][1][0]; + result %= MOD; + result = (result - 1 + MOD) % MOD; + return (int) result; + } +} diff --git a/src/main/java/g3901_4000/s3939_count_non_adjacent_subsets_in_a_rooted_tree/readme.md b/src/main/java/g3901_4000/s3939_count_non_adjacent_subsets_in_a_rooted_tree/readme.md new file mode 100644 index 000000000..6d9336b3d --- /dev/null +++ b/src/main/java/g3901_4000/s3939_count_non_adjacent_subsets_in_a_rooted_tree/readme.md @@ -0,0 +1,57 @@ +3939\. Count Non Adjacent Subsets in a Rooted Tree + +Hard + +You are given a rooted tree with `n` nodes labeled from 0 to `n - 1`, represented by an integer array `parent` of length `n`, where: + +* `parent[0] = -1` (node 0 is the root). +* For each `1 <= i < n`, `parent[i]` is the parent of node `i` (`0 <= parent[i] < i`). + +You are also given an integer array nums of length `n`, where `nums[i]` is the value of node `i`, and an integer `k`. + +A non-empty subset of nodes is called **valid** if: + +* The **sum** of the values of the selected nodes is **divisible** by `k`. +* No **two** selected nodes are **adjacent** in the tree (no node and its direct parent are both included in the subset). + +Return the number of valid subsets modulo 109 + 7. + +**Example 1:** + +**Input:** parent = [-1,0,1], nums = [1,2,3], k = 3 + +**Output:** 1 + +**Explanation:** + +**![](https://assets.leetcode.com/uploads/2025/07/17/image1.png)** + +The only valid subset is `{2}`. It contains node 2 with value 3, which is divisible by 3. + +**Example 2:** + +**Input:** parent = [-1,0,0,0], nums = [2,1,2,1], k = 3 + +**Output:** 2 + +**Explanation:** + +**![](https://assets.leetcode.com/uploads/2025/07/17/image2.png)** + +The valid subsets are: + +* `{1, 2}`: Nodes 1 and 2 are both children of node 0 and not directly connected to each other. Their values sum to `1 + 2 = 3`, which is divisible by 3. +* `{2, 3}`: Nodes 2 and 3 are also non-adjacent. Their values sum to `2 + 1 = 3`, which is divisible by 3. + +No other subset satisfies both conditions. Therefore, the answer is 2. + +**Constraints:** + +* `n == parent.length == nums.length` +* `1 <= n <= 1000` +* `parent[0] == -1` +* For all `1 <= i < n`: + * `0 <= parent[i] < i` +* 1 <= nums[i] <= 109 +* `1 <= k <= 100` +* `parent` describes a valid rooted tree. \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3940_limit_occurrences_in_sorted_array/Solution.java b/src/main/java/g3901_4000/s3940_limit_occurrences_in_sorted_array/Solution.java new file mode 100644 index 000000000..3862551b4 --- /dev/null +++ b/src/main/java/g3901_4000/s3940_limit_occurrences_in_sorted_array/Solution.java @@ -0,0 +1,30 @@ +package g3901_4000.s3940_limit_occurrences_in_sorted_array; + +// #Easy #Array #Two_Pointers #Mid_Level #Weekly_Contest_503 +// #2026_09_29_Time_1_ms_(100.00%)_Space_46.77_MB_(68.82%) + +import java.util.ArrayList; +import java.util.List; + +public class Solution { + public int[] limitOccurrences(int[] nums, int k) { + List ls = new ArrayList<>(); + ls.add(nums[0]); + int freq = 1; + for (int i = 1; i < nums.length; i++) { + if (nums[i] == nums[i - 1]) { + freq++; + } else { + freq = 1; + } + if (freq <= k) { + ls.add(nums[i]); + } + } + int[] ans = new int[ls.size()]; + for (int i = 0; i < ls.size(); i++) { + ans[i] = ls.get(i); + } + return ans; + } +} diff --git a/src/main/java/g3901_4000/s3940_limit_occurrences_in_sorted_array/readme.md b/src/main/java/g3901_4000/s3940_limit_occurrences_in_sorted_array/readme.md new file mode 100644 index 000000000..ec5245e3b --- /dev/null +++ b/src/main/java/g3901_4000/s3940_limit_occurrences_in_sorted_array/readme.md @@ -0,0 +1,47 @@ +3940\. Limit Occurrences in Sorted Array + +Easy + +You are given a **sorted** integer array `nums` and an integer `k`. + +Return an array such that each **distinct** element appears **at most** `k` times, while preserving the relative order of the elements in `nums`. + +Note: If a distinct element appears **at least** `k` times, then it must appear **exactly** `k` times in the resulting array. + +**Example 1:** + +**Input:** nums = [1,1,1,2,2,3], k = 2 + +**Output:** [1,1,2,2,3] + +**Explanation:** + +Each element can appear at most 2 times. + +* The element 1 appears 3 times, so only 2 occurrences are kept. +* The element 2 appears 2 times, so both occurrences are kept. +* The element 3 appears 1 time, so it is kept. + +Thus, the resulting array is `[1, 1, 2, 2, 3]`. + +**Example 2:** + +**Input:** nums = [1,2,3], k = 1 + +**Output:** [1,2,3] + +**Explanation:** + +All elements are distinct and already appear at most once, so the array remains unchanged. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `1 <= nums[i] <= 100` +* `nums` is sorted in non-decreasing order. +* `1 <= k <= nums.length` + +**Follow-up:** + +* Can you solve this in-place using O(1) extra space? +* Note that the space used for returning or resizing the result does not count toward the space complexity mentioned above, as some languages do not support in-place resizing. \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3941_password_strength/Solution.java b/src/main/java/g3901_4000/s3941_password_strength/Solution.java new file mode 100644 index 000000000..cf4ec5514 --- /dev/null +++ b/src/main/java/g3901_4000/s3941_password_strength/Solution.java @@ -0,0 +1,42 @@ +package g3901_4000.s3941_password_strength; + +// #Medium #String #Hash_Table #Senior #Weekly_Contest_503 +// #2026_09_29_Time_2_ms_(100.00%)_Space_47.21_MB_(40.64%) + +public class Solution { + public int passwordStrength(String password) { + int strength = 0; + boolean[] present = new boolean[256]; + for (int i = 0; i < password.length(); i++) { + present[password.charAt(i)] = true; + } + for (int i = 97; i <= 122; i++) { + if (present[i]) { + strength++; + } + } + for (int i = 65; i <= 90; i++) { + if (present[i]) { + strength += 2; + } + } + for (int i = 48; i <= 57; i++) { + if (present[i]) { + strength += 3; + } + } + if (present['!']) { + strength += 5; + } + if (present['@']) { + strength += 5; + } + if (present['#']) { + strength += 5; + } + if (present['$']) { + strength += 5; + } + return strength; + } +} diff --git a/src/main/java/g3901_4000/s3941_password_strength/readme.md b/src/main/java/g3901_4000/s3941_password_strength/readme.md new file mode 100644 index 000000000..95ddc8e08 --- /dev/null +++ b/src/main/java/g3901_4000/s3941_password_strength/readme.md @@ -0,0 +1,43 @@ +3941\. Password Strength + +Medium + +You are given a string `password`. + +The **strength** of the password is calculated based on the following rules: + +* 1 point for each distinct lowercase letter (`'a'` to `'z'`). +* 2 points for each distinct uppercase letter (`'A'` to `'Z'`). +* 3 points for each distinct digit (`'0'` to `'9'`). +* 5 points for each distinct special character from the set `"!@#$"`. + +Each character contributes **at most** once, even if it appears multiple times. + +Return an integer denoting the strength of the password. + +**Example 1:** + +**Input:** password = "aA1!" + +**Output:** 11 + +**Explanation:** + +* The distinct characters are `'a'`, `'A'`, `'1'` and `'!'`. +* Thus, the `strength = 1 + 2 + 3 + 5 = 11`. + +**Example 2:** + +**Input:** password = "bbB11#" + +**Output:** 11 + +**Explanation:** + +* The distinct characters are `'b'`, `'B'`, `'1'` and `'#'`. +* Thus, the `strength = 1 + 2 + 3 + 5 = 11`. + +**Constraints:** + +* 1 <= password.length <= 105 +* `password` consists of lowercase and uppercase English letters, digits, and special characters from `"!@#$"`. \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3942_minimum_operations_to_sort_a_permutation/Solution.java b/src/main/java/g3901_4000/s3942_minimum_operations_to_sort_a_permutation/Solution.java new file mode 100644 index 000000000..d61048c94 --- /dev/null +++ b/src/main/java/g3901_4000/s3942_minimum_operations_to_sort_a_permutation/Solution.java @@ -0,0 +1,47 @@ +package g3901_4000.s3942_minimum_operations_to_sort_a_permutation; + +// #Medium #Array #Staff #Weekly_Contest_503 #2026_09_29_Time_2_ms_(100.00%)_Space_94.88_MB_(91.76%) + +public class Solution { + public int minOperations(int[] nums) { + int ans = -1; + int zeroIdx = 0; + int prev = nums[0]; + boolean forward = true; + for (int i = 1; i < nums.length; i++) { + if (nums[i] == 0) { + zeroIdx = i; + // new start + } else if (nums[i] != (prev + 1)) { + forward = false; + break; + } + prev = nums[i]; + } + if (forward) { + ans = Math.min(zeroIdx, nums.length - zeroIdx + 2); + } + zeroIdx = nums.length - 1; + prev = nums[nums.length - 1]; + boolean backward = true; + for (int i = nums.length - 2; i >= 0; i--) { + if (nums[i] == 0) { + zeroIdx = i; + // new start + } else if (nums[i] != (prev + 1)) { + backward = false; + break; + } + prev = nums[i]; + } + if (backward) { + int b = Math.min(nums.length - zeroIdx, zeroIdx + 2); + if (ans == -1) { + ans = b; + } else { + ans = Math.min(ans, b); + } + } + return ans; + } +} diff --git a/src/main/java/g3901_4000/s3942_minimum_operations_to_sort_a_permutation/readme.md b/src/main/java/g3901_4000/s3942_minimum_operations_to_sort_a_permutation/readme.md new file mode 100644 index 000000000..49bae3f48 --- /dev/null +++ b/src/main/java/g3901_4000/s3942_minimum_operations_to_sort_a_permutation/readme.md @@ -0,0 +1,54 @@ +3942\. Minimum Operations to Sort a Permutation + +Medium + +You are given an integer array `nums` of length `n`, where `nums` is a permutation of the integers from 0 to `n - 1`. + +You may perform **only** the following operations: + +* **Reverse** the entire array. +* **Rotate Left by One**: Move the first element to the end of the array, and rest elements to left by one position. + +Return an integer denoting the **minimum** number of operations required to sort the array in **increasing** order. If it is **not possible** to sort the array using only the given operations, return -1. + +**Example 1:** + +**Input:** nums = [0,2,1] + +**Output:** 2 + +**Explanation:** + +* Rotate Left by one: `[2, 1, 0]` +* Reverse the array: `[0, 1, 2]` + +The array becomes sorted in 2 operations, which is minimal + +**Example 2:** + +**Input:** nums = [1,0,2] + +**Output:** 2 + +**Explanation:** + +* Reverse the array: `[2, 0, 1]` +* Rotate Left by one: `[0, 1, 2]` + +The array becomes sorted in 2 operations, which is minimal. + +**Example 3:** + +**Input:** nums = [2,0,1,3] + +**Output:** \-1 + +**Explanation:** + +It is impossible to reach `[2, 0, 1, 3]`. Thus, the answer is -1. + +**Constraints:** + +* 1 <= n == nums.length <= 105 +* `0 <= nums[i] <= n - 1` +* `nums` is a permutation of integers from 0 to `n - 1`. \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3943_number_of_pairs_after_increment/Solution.java b/src/main/java/g3901_4000/s3943_number_of_pairs_after_increment/Solution.java new file mode 100644 index 000000000..8f99f321c --- /dev/null +++ b/src/main/java/g3901_4000/s3943_number_of_pairs_after_increment/Solution.java @@ -0,0 +1,124 @@ +package g3901_4000.s3943_number_of_pairs_after_increment; + +// #Hard #Array #Hash_Table #Counting #Divide_and_Conquer #Senior_Staff #Weekly_Contest_503 +// #2026_09_29_Time_233_ms_(98.11%)_Space_189.48_MB_(39.62%) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class Solution { + private HashMap cache; + + private void update(long[] nums2, int l, int r, long val) { + if (r < l) { + return; + } + for (int i = l; i <= r; i++) { + long oldValue = nums2[i]; + long newValue = nums2[i] + val; + cache.put(oldValue, cache.getOrDefault(oldValue, 0L) - 1); + cache.put(newValue, cache.getOrDefault(newValue, 0L) + 1); + nums2[i] = newValue; + } + } + + public int[] numberOfPairs(int[] nums1, int[] nums2, int[][] queries) { + long[] n2 = initialize(nums2); + long globalOffset = 0; + List answers = new ArrayList<>(); + int q = 0; + while (q < queries.length) { + QueryResult result = processQuery(q, queries, nums1, n2, globalOffset); + q = result.nextIndex; + globalOffset = result.globalOffset; + if (result.answer != null) { + answers.add(result.answer); + } + } + return toArray(answers); + } + + private long[] initialize(int[] nums2) { + cache = new HashMap<>(); + long[] result = new long[nums2.length]; + for (int i = 0; i < nums2.length; i++) { + result[i] = nums2[i]; + incrementCount(result[i]); + } + return result; + } + + private void incrementCount(long value) { + cache.put(value, cache.getOrDefault(value, 0L) + 1); + } + + private QueryResult processQuery( + int index, int[][] queries, int[] nums1, long[] nums2, long globalOffset) { + int[] query = queries[index]; + if (query[0] == 1) { + return processUpdateQuery(index, queries, nums2, globalOffset); + } + int answer = countPairs(nums1, query[1], globalOffset); + return new QueryResult(index + 1, globalOffset, answer); + } + + private QueryResult processUpdateQuery( + int index, int[][] queries, long[] nums2, long globalOffset) { + int[] query = queries[index]; + int l = query[1]; + int r = query[2]; + long val = query[3]; + int nextIndex = index + 1; + while (nextIndex < queries.length && hasSameRange(queries[nextIndex], l, r)) { + val += queries[nextIndex][3]; + nextIndex++; + } + globalOffset = applyUpdate(nums2, l, r, val, globalOffset); + return new QueryResult(nextIndex, globalOffset, null); + } + + private boolean hasSameRange(int[] query, int l, int r) { + return query.length == 4 && query[1] == l && query[2] == r; + } + + private long applyUpdate(long[] nums2, int l, int r, long val, long globalOffset) { + int length = r - l + 1; + if (length <= nums2.length / 2) { + update(nums2, l, r, val); + return globalOffset; + } + update(nums2, 0, l - 1, -val); + update(nums2, r + 1, nums2.length - 1, -val); + return globalOffset + val; + } + + private int countPairs(int[] nums1, long target, long globalOffset) { + long totalPairs = 0; + for (int num1 : nums1) { + long num2 = target - num1 - globalOffset; + totalPairs += cache.getOrDefault(num2, 0L); + } + return (int) totalPairs; + } + + private int[] toArray(List answers) { + int[] result = new int[answers.size()]; + for (int i = 0; i < answers.size(); i++) { + result[i] = answers.get(i); + } + return result; + } + + private static final class QueryResult { + private final int nextIndex; + private final long globalOffset; + private final Integer answer; + + private QueryResult(int nextIndex, long globalOffset, Integer answer) { + this.nextIndex = nextIndex; + this.globalOffset = globalOffset; + this.answer = answer; + } + } +} diff --git a/src/main/java/g3901_4000/s3943_number_of_pairs_after_increment/readme.md b/src/main/java/g3901_4000/s3943_number_of_pairs_after_increment/readme.md new file mode 100644 index 000000000..cf11af426 --- /dev/null +++ b/src/main/java/g3901_4000/s3943_number_of_pairs_after_increment/readme.md @@ -0,0 +1,64 @@ +3943\. Number of Pairs After Increment + +Hard + +You are given two integer arrays `nums1` and `nums2`, and a 2D integer array `queries`. + +Each `queries[i]` is one of the following types: + +* `[1, x, y, val]` – **Add** `val` to every element in `nums2[x..y]`. +* `[2, tot]` – **Compute** the number of pairs `(j, k)` such that `nums1[j] + nums2[k] == tot`. + +Return an integer array `answer`, where `answer[j]` is the number of pairs for the jth query of type 2. + +**Example 1:** + +**Input:** nums1 = [1,2], nums2 = [3,4], queries = [[2,5],[1,0,0,2],[2,5]] + +**Output:** [2,1] + +**Explanation:** + +* `queries[0] = [2, 5]`: Valid pairs are `nums1[0] + nums2[1] = 1 + 4 = 5` and `nums1[1] + nums2[0] = 2 + 3 = 5`. +* `queries[1] = [1, 0, 0, 2]`: Add 2 to `nums2[0]`, resulting in `nums2 = [5, 4]`. +* `queries[2] = [2, 5]`: Valid pair is `nums1[0] + nums2[1] = 1 + 4 = 5`. +* Thus, the `answer = [2, 1]`. + +**Example 2:** + +**Input:** nums1 = [1,1], nums2 = [2,2,3], queries = [[2,4],[1,0,1,1],[2,4]] + +**Output:** [2,6] + +**Explanation:** + +* `queries[0] = [2, 4]`: Valid pairs are `nums1[0] + nums2[2] = 1 + 3` and `nums1[1] + nums2[2] = 1 + 3`. +* `queries[1] = [1, 0, 1, 1]`: Add 1 to `nums2[0]` and `nums2[1]`, resulting in `nums2 = [3, 3, 3]`. +* `queries[2] = [2, 4]`: Every element of `nums1 = [1, 1]` pairs with every element of `nums2 = [3, 3, 3]` as `1 + 3 = 4`. That gives `2 × 3 = 6` pairs in total. +* Thus, the `answer = [2, 6]`. + +**Example 3:** + +**Input:** nums1 = [2,5,8,4], nums2 = [1,3,8], queries = [[2,9],[1,1,2,1],[2,10]] + +**Output:** [1,0] + +**Explanation:** + +* `queries[0] = [2, 9]`: Only valid pair is `nums1[2] + nums2[0] = 8 + 1 = 9`. +* `queries[1] = [1, 1, 2, 1]`: Add 1 to `nums2[1]` and `nums2[2]`, resulting in `nums2 = [1, 4, 9]`. +* `queries[2] = [2, 10]`: No pair sums to `10`. +* Thus, the `answer = [1, 0]`. + +**Constraints:** + +* `1 <= nums1.length <= 5` +* 1 <= nums2.length <= 5 * 104 +* 1 <= nums1[i], nums2[i] <= 105 +* 1 <= queries.length <= 5 * 104 +* `queries[i].length == 2 or 4` + * `queries[i] == [1, x, y, val], or` + * `queries[i] == [2, tot]` + * `0 <= x <= y < nums2.length` + * 1 <= val <= 105 + * 1 <= tot <= 109 \ No newline at end of file diff --git a/src/main/java/g3901_4000/s3945_digit_frequency_score/Solution.java b/src/main/java/g3901_4000/s3945_digit_frequency_score/Solution.java new file mode 100644 index 000000000..0695db67b --- /dev/null +++ b/src/main/java/g3901_4000/s3945_digit_frequency_score/Solution.java @@ -0,0 +1,15 @@ +package g3901_4000.s3945_digit_frequency_score; + +// #Easy #Hash_Table #Math #Mid_Level #Weekly_Contest_504 +// #2026_09_29_Time_1_ms_(98.46%)_Space_42.42_MB_(81.44%) + +public class Solution { + public int digitFrequencyScore(int n) { + int sum = 0; + while (n > 0) { + sum += (n % 10); + n /= 10; + } + return sum; + } +} diff --git a/src/main/java/g3901_4000/s3945_digit_frequency_score/readme.md b/src/main/java/g3901_4000/s3945_digit_frequency_score/readme.md new file mode 100644 index 000000000..5dc4535b5 --- /dev/null +++ b/src/main/java/g3901_4000/s3945_digit_frequency_score/readme.md @@ -0,0 +1,37 @@ +3945\. Digit Frequency Score + +Easy + +You are given an integer `n`. + +The **score** of `n` is defined as the **sum** of `d * freq(d)` over all **distinct** digits `d`, where `freq(d)` denotes the number of times the digit `d` appears in `n`. + +Return an integer denoting the score of `n`. + +**Example 1:** + +**Input:** n = 122 + +**Output:** 5 + +**Explanation:** + +* The digit 1 appears 1 time, contributing `1 * 1 = 1`. +* The digit 2 appears 2 times, contributing `2 * 2 = 4`. +* Thus, the score of `n` is `1 + 4 = 5`. + +**Example 2:** + +**Input:** n = 101 + +**Output:** 2 + +**Explanation:** + +* The digit 0 appears 1 time, contributing `0 * 1 = 0`. +* The digit 1 appears 2 times, contributing `1 * 2 = 2`. +* Thus, the score of `n` is 2. + +**Constraints:** + +* 1 <= n <= 109 \ No newline at end of file diff --git a/src/test/java/g3901_4000/s3922_minimum_flips_to_make_binary_string_coherent/SolutionTest.java b/src/test/java/g3901_4000/s3922_minimum_flips_to_make_binary_string_coherent/SolutionTest.java new file mode 100644 index 000000000..c775c79fc --- /dev/null +++ b/src/test/java/g3901_4000/s3922_minimum_flips_to_make_binary_string_coherent/SolutionTest.java @@ -0,0 +1,53 @@ +package g3901_4000.s3922_minimum_flips_to_make_binary_string_coherent; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minFlips() { + assertThat(new Solution().minFlips("1010"), equalTo(1)); + } + + @Test + void minFlips2() { + assertThat(new Solution().minFlips("0110"), equalTo(1)); + } + + @Test + void minFlips3() { + assertThat(new Solution().minFlips("1000"), equalTo(0)); + } + + @Test + void minFlips4() { + assertThat(new Solution().minFlips("0"), equalTo(0)); + } + + @Test + void minFlips5() { + assertThat(new Solution().minFlips("1111"), equalTo(0)); + } + + @Test + void minFlips6() { + assertThat(new Solution().minFlips("0000"), equalTo(0)); + } + + @Test + void minFlips7() { + assertThat(new Solution().minFlips("10001"), equalTo(0)); + } + + @Test + void minFlips8() { + assertThat(new Solution().minFlips("01010"), equalTo(1)); + } + + @Test + void minFlips9() { + assertThat(new Solution().minFlips("011110"), equalTo(2)); + } +} diff --git a/src/test/java/g3901_4000/s3923_minimum_generations_to_target_point/SolutionTest.java b/src/test/java/g3901_4000/s3923_minimum_generations_to_target_point/SolutionTest.java new file mode 100644 index 000000000..0db061494 --- /dev/null +++ b/src/test/java/g3901_4000/s3923_minimum_generations_to_target_point/SolutionTest.java @@ -0,0 +1,56 @@ +package g3901_4000.s3923_minimum_generations_to_target_point; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minGenerations() { + assertThat( + new Solution() + .minGenerations(new int[][] {{0, 0, 0}, {6, 6, 6}}, new int[] {3, 3, 3}), + equalTo(1)); + } + + @Test + void minGenerations2() { + assertThat( + new Solution() + .minGenerations(new int[][] {{0, 0, 0}, {5, 5, 5}}, new int[] {1, 1, 1}), + equalTo(2)); + } + + @Test + void minGenerations3() { + assertThat( + new Solution() + .minGenerations( + new int[][] {{0, 0, 0}, {2, 2, 2}, {3, 3, 3}}, new int[] {2, 2, 2}), + equalTo(0)); + } + + @Test + void minGenerations4() { + assertThat( + new Solution().minGenerations(new int[][] {{1, 2, 3}}, new int[] {5, 5, 5}), + equalTo(-1)); + } + + @Test + void minGenerations5() { + assertThat( + new Solution() + .minGenerations(new int[][] {{0, 0, 0}, {6, 6, 6}}, new int[] {1, 2, 3}), + equalTo(-1)); + } + + @Test + void minGenerations6() { + assertThat( + new Solution() + .minGenerations(new int[][] {{0, 2, 4}, {5, 3, 1}}, new int[] {2, 2, 2}), + equalTo(1)); + } +} diff --git a/src/test/java/g3901_4000/s3924_minimum_threshold_path_with_limited_heavy_edges/SolutionTest.java b/src/test/java/g3901_4000/s3924_minimum_threshold_path_with_limited_heavy_edges/SolutionTest.java new file mode 100644 index 000000000..6f628898e --- /dev/null +++ b/src/test/java/g3901_4000/s3924_minimum_threshold_path_with_limited_heavy_edges/SolutionTest.java @@ -0,0 +1,74 @@ +package g3901_4000.s3924_minimum_threshold_path_with_limited_heavy_edges; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minimumThreshold() { + assertThat( + new Solution() + .minimumThreshold( + 6, + new int[][] {{0, 1, 5}, {1, 2, 3}, {3, 4, 4}, {4, 5, 1}, {1, 4, 2}}, + 0, + 3, + 1), + equalTo(4)); + } + + @Test + void minimumThreshold2() { + assertThat( + new Solution() + .minimumThreshold( + 6, + new int[][] {{0, 1, 3}, {1, 2, 4}, {3, 4, 5}, {4, 5, 6}}, + 0, + 4, + 1), + equalTo(-1)); + } + + @Test + void minimumThreshold3() { + assertThat(new Solution().minimumThreshold(1, new int[][] {}, 0, 0, 0), equalTo(0)); + } + + @Test + void minimumThreshold4() { + assertThat(new Solution().minimumThreshold(2, new int[][] {}, 0, 1, 0), equalTo(-1)); + } + + @Test + void minimumThreshold5() { + assertThat( + new Solution() + .minimumThreshold( + 3, new int[][] {{0, 1, 9}, {1, 2, 4}, {0, 2, 7}}, 0, 2, 0), + equalTo(7)); + } + + @Test + void minimumThreshold6() { + assertThat( + new Solution().minimumThreshold(3, new int[][] {{0, 1, 9}, {1, 2, 4}}, 2, 0, 1), + equalTo(4)); + } + + @Test + void minimumThreshold7() { + assertThat( + new Solution().minimumThreshold(3, new int[][] {{0, 1, 9}, {1, 2, 4}}, 0, 2, 2), + equalTo(0)); + } + + @Test + void minimumThreshold8() { + assertThat( + new Solution().minimumThreshold(2, new int[][] {{0, 1, 1000000000}}, 0, 1, 0), + equalTo(1000000000)); + } +} diff --git a/src/test/java/g3901_4000/s3925_concatenate_array_with_reverse/SolutionTest.java b/src/test/java/g3901_4000/s3925_concatenate_array_with_reverse/SolutionTest.java new file mode 100644 index 000000000..2fc47f949 --- /dev/null +++ b/src/test/java/g3901_4000/s3925_concatenate_array_with_reverse/SolutionTest.java @@ -0,0 +1,34 @@ +package g3901_4000.s3925_concatenate_array_with_reverse; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void concatWithReverse() { + assertThat( + new Solution().concatWithReverse(new int[] {1, 2, 3}), + equalTo(new int[] {1, 2, 3, 3, 2, 1})); + } + + @Test + void concatWithReverse2() { + assertThat(new Solution().concatWithReverse(new int[] {1}), equalTo(new int[] {1, 1})); + } + + @Test + void concatWithReverse3() { + assertThat( + new Solution().concatWithReverse(new int[] {2, 2}), + equalTo(new int[] {2, 2, 2, 2})); + } + + @Test + void concatWithReverse4() { + assertThat( + new Solution().concatWithReverse(new int[] {100, 1}), + equalTo(new int[] {100, 1, 1, 100})); + } +} diff --git a/src/test/java/g3901_4000/s3926_count_valid_word_occurrences/SolutionTest.java b/src/test/java/g3901_4000/s3926_count_valid_word_occurrences/SolutionTest.java new file mode 100644 index 000000000..148baaeb4 --- /dev/null +++ b/src/test/java/g3901_4000/s3926_count_valid_word_occurrences/SolutionTest.java @@ -0,0 +1,66 @@ +package g3901_4000.s3926_count_valid_word_occurrences; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void countWordOccurrences() { + assertThat( + new Solution() + .countWordOccurrences( + new String[] {"hello wor", "ld hello"}, + new String[] {"hello", "world", "wor"}), + equalTo(new int[] {2, 1, 0})); + } + + @Test + void countWordOccurrences2() { + assertThat( + new Solution() + .countWordOccurrences( + new String[] {"a-b a--b ", "a-", "b"}, + new String[] {"a-b", "a", "b"}), + equalTo(new int[] {2, 1, 1})); + } + + @Test + void countWordOccurrences3() { + assertThat( + new Solution() + .countWordOccurrences( + new String[] {"-cat dog- mouse"}, + new String[] {"cat", "dog", "mouse", "cat-dog"}), + equalTo(new int[] {1, 1, 1, 0})); + } + + @Test + void countWordOccurrences4() { + assertThat( + new Solution() + .countWordOccurrences( + new String[] {" -- ", "-"}, new String[] {"a", "a-b"}), + equalTo(new int[] {0, 0})); + } + + @Test + void countWordOccurrences5() { + assertThat( + new Solution() + .countWordOccurrences( + new String[] {"a", "-", "b a", "-b-"}, + new String[] {"a-b", "a", "b", "a-b"}), + equalTo(new int[] {2, 0, 0, 2})); + } + + @Test + void countWordOccurrences6() { + assertThat( + new Solution() + .countWordOccurrences( + new String[] {"a b ab a"}, new String[] {"a", "ab", "abc", "b"}), + equalTo(new int[] {2, 1, 0, 1})); + } +} diff --git a/src/test/java/g3901_4000/s3927_minimize_array_sum_using_divisible_replacements/SolutionTest.java b/src/test/java/g3901_4000/s3927_minimize_array_sum_using_divisible_replacements/SolutionTest.java new file mode 100644 index 000000000..42ba41118 --- /dev/null +++ b/src/test/java/g3901_4000/s3927_minimize_array_sum_using_divisible_replacements/SolutionTest.java @@ -0,0 +1,50 @@ +package g3901_4000.s3927_minimize_array_sum_using_divisible_replacements; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minArraySum8() { + int[] nums = new int[30000]; + java.util.Arrays.fill(nums, 100000); + assertThat(new Solution().minArraySum(nums), equalTo(3000000000L)); + } + + @Test + void minArraySum() { + assertThat(new Solution().minArraySum(new int[] {3, 6, 2}), equalTo(7L)); + } + + @Test + void minArraySum2() { + assertThat(new Solution().minArraySum(new int[] {4, 2, 8, 3}), equalTo(9L)); + } + + @Test + void minArraySum3() { + assertThat(new Solution().minArraySum(new int[] {7, 5, 9}), equalTo(21L)); + } + + @Test + void minArraySum4() { + assertThat(new Solution().minArraySum(new int[] {100000, 1, 7}), equalTo(3L)); + } + + @Test + void minArraySum5() { + assertThat(new Solution().minArraySum(new int[] {8}), equalTo(8L)); + } + + @Test + void minArraySum6() { + assertThat(new Solution().minArraySum(new int[] {12, 6, 3, 2, 12}), equalTo(11L)); + } + + @Test + void minArraySum7() { + assertThat(new Solution().minArraySum(new int[] {5, 5, 5}), equalTo(15L)); + } +} diff --git a/src/test/java/g3901_4000/s3928_minimum_cost_to_buy_apples_ii/SolutionTest.java b/src/test/java/g3901_4000/s3928_minimum_cost_to_buy_apples_ii/SolutionTest.java new file mode 100644 index 000000000..a83a6b3e4 --- /dev/null +++ b/src/test/java/g3901_4000/s3928_minimum_cost_to_buy_apples_ii/SolutionTest.java @@ -0,0 +1,69 @@ +package g3901_4000.s3928_minimum_cost_to_buy_apples_ii; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minCost() { + assertThat( + new Solution().minCost(2, new int[] {8, 3}, new int[][] {{0, 1, 1, 2}}), + equalTo(new int[] {6, 3})); + } + + @Test + void minCost2() { + assertThat( + new Solution() + .minCost(3, new int[] {9, 4, 6}, new int[][] {{0, 1, 1, 3}, {1, 2, 4, 2}}), + equalTo(new int[] {8, 4, 6})); + } + + @Test + void minCost3() { + assertThat( + new Solution() + .minCost( + 3, + new int[] {10, 11, 1}, + new int[][] {{0, 2, 1, 3}, {1, 2, 3, 4}, {0, 1, 5, 2}}), + equalTo(new int[] {5, 11, 1})); + } + + @Test + void minCost4() { + assertThat( + new Solution().minCost(2, new int[] {4, 2}, new int[][] {}), + equalTo(new int[] {4, 2})); + } + + @Test + void minCost5() { + assertThat( + new Solution() + .minCost( + 3, + new int[] {100, 100, 1}, + new int[][] {{0, 2, 1, 100}, {0, 1, 2, 1}, {1, 2, 2, 1}}), + equalTo(new int[] {6, 5, 1})); + } + + @Test + void minCost6() { + assertThat( + new Solution() + .minCost( + 2, + new int[] {1000000000, 1}, + new int[][] {{0, 1, 1000000000, 100}}), + equalTo(new int[] {1000000000, 1})); + } + + @Test + void minCost7() { + assertThat( + new Solution().minCost(1, new int[] {7}, new int[][] {}), equalTo(new int[] {7})); + } +} diff --git a/src/test/java/g3901_4000/s3931_check_adjacent_digit_differences/SolutionTest.java b/src/test/java/g3901_4000/s3931_check_adjacent_digit_differences/SolutionTest.java new file mode 100644 index 000000000..ec9b3ecab --- /dev/null +++ b/src/test/java/g3901_4000/s3931_check_adjacent_digit_differences/SolutionTest.java @@ -0,0 +1,43 @@ +package g3901_4000.s3931_check_adjacent_digit_differences; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void isAdjacentDiffAtMostTwo() { + assertThat(new Solution().isAdjacentDiffAtMostTwo("132"), equalTo(true)); + } + + @Test + void isAdjacentDiffAtMostTwo2() { + assertThat(new Solution().isAdjacentDiffAtMostTwo("129"), equalTo(false)); + } + + @Test + void isAdjacentDiffAtMostTwo3() { + assertThat(new Solution().isAdjacentDiffAtMostTwo("00"), equalTo(true)); + } + + @Test + void isAdjacentDiffAtMostTwo4() { + assertThat(new Solution().isAdjacentDiffAtMostTwo("97531"), equalTo(true)); + } + + @Test + void isAdjacentDiffAtMostTwo5() { + assertThat(new Solution().isAdjacentDiffAtMostTwo("03"), equalTo(false)); + } + + @Test + void isAdjacentDiffAtMostTwo6() { + assertThat(new Solution().isAdjacentDiffAtMostTwo("90"), equalTo(false)); + } + + @Test + void isAdjacentDiffAtMostTwo7() { + assertThat(new Solution().isAdjacentDiffAtMostTwo("0123456789"), equalTo(true)); + } +} diff --git a/src/test/java/g3901_4000/s3932_count_k_th_roots_in_a_range/SolutionTest.java b/src/test/java/g3901_4000/s3932_count_k_th_roots_in_a_range/SolutionTest.java new file mode 100644 index 000000000..7d7b6feb2 --- /dev/null +++ b/src/test/java/g3901_4000/s3932_count_k_th_roots_in_a_range/SolutionTest.java @@ -0,0 +1,53 @@ +package g3901_4000.s3932_count_k_th_roots_in_a_range; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void countKthRoots() { + assertThat(new Solution().countKthRoots(1, 9, 3), equalTo(2)); + } + + @Test + void countKthRoots2() { + assertThat(new Solution().countKthRoots(8, 30, 2), equalTo(3)); + } + + @Test + void countKthRoots3() { + assertThat(new Solution().countKthRoots(0, 0, 30), equalTo(1)); + } + + @Test + void countKthRoots4() { + assertThat(new Solution().countKthRoots(0, 1000000000, 1), equalTo(1000000001)); + } + + @Test + void countKthRoots5() { + assertThat(new Solution().countKthRoots(16, 16, 2), equalTo(1)); + } + + @Test + void countKthRoots6() { + assertThat(new Solution().countKthRoots(17, 24, 2), equalTo(0)); + } + + @Test + void countKthRoots7() { + assertThat(new Solution().countKthRoots(0, 1000000000, 30), equalTo(2)); + } + + @Test + void countKthRoots8() { + assertThat(new Solution().countKthRoots(999950884, 1000000000, 2), equalTo(1)); + } + + @Test + void countKthRoots9() { + assertThat(new Solution().countKthRoots(8, 27, 3), equalTo(2)); + } +} diff --git a/src/test/java/g3901_4000/s3933_largest_local_values_in_a_matrix_ii/SolutionTest.java b/src/test/java/g3901_4000/s3933_largest_local_values_in_a_matrix_ii/SolutionTest.java new file mode 100644 index 000000000..d24c9a0c2 --- /dev/null +++ b/src/test/java/g3901_4000/s3933_largest_local_values_in_a_matrix_ii/SolutionTest.java @@ -0,0 +1,50 @@ +package g3901_4000.s3933_largest_local_values_in_a_matrix_ii; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void countLocalMaximums() { + assertThat(new Solution().countLocalMaximums(new int[][] {{1, 2}, {3, 4}}), equalTo(1)); + } + + @Test + void countLocalMaximums2() { + assertThat( + new Solution().countLocalMaximums(new int[][] {{1, 0, 1}, {0, 1, 0}, {1, 0, 1}}), + equalTo(5)); + } + + @Test + void countLocalMaximums3() { + assertThat(new Solution().countLocalMaximums(new int[][] {{1, 1}, {1, 1}}), equalTo(4)); + } + + @Test + void countLocalMaximums4() { + assertThat(new Solution().countLocalMaximums(new int[][] {{0, 0}, {0, 0}}), equalTo(0)); + } + + @Test + void countLocalMaximums5() { + assertThat(new Solution().countLocalMaximums(new int[][] {{200}}), equalTo(1)); + } + + @Test + void countLocalMaximums6() { + assertThat(new Solution().countLocalMaximums(new int[][] {{1, 0}, {0, 2}}), equalTo(2)); + } + + @Test + void countLocalMaximums7() { + assertThat(new Solution().countLocalMaximums(new int[][] {{1, 2, 0}}), equalTo(1)); + } + + @Test + void countLocalMaximums8() { + assertThat(new Solution().countLocalMaximums(new int[][] {{1}, {0}, {2}}), equalTo(2)); + } +} diff --git a/src/test/java/g3901_4000/s3934_smallest_unique_subarray/SolutionTest.java b/src/test/java/g3901_4000/s3934_smallest_unique_subarray/SolutionTest.java new file mode 100644 index 000000000..19038b2fe --- /dev/null +++ b/src/test/java/g3901_4000/s3934_smallest_unique_subarray/SolutionTest.java @@ -0,0 +1,45 @@ +package g3901_4000.s3934_smallest_unique_subarray; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void smallestUniqueSubarray() { + assertThat(new Solution().smallestUniqueSubarray(new int[] {3, 3, 3}), equalTo(3)); + } + + @Test + void smallestUniqueSubarray2() { + assertThat(new Solution().smallestUniqueSubarray(new int[] {2, 1, 2, 3, 3}), equalTo(1)); + } + + @Test + void smallestUniqueSubarray3() { + assertThat(new Solution().smallestUniqueSubarray(new int[] {1, 1, 2, 2, 1}), equalTo(2)); + } + + @Test + void smallestUniqueSubarray4() { + assertThat(new Solution().smallestUniqueSubarray(new int[] {100000}), equalTo(1)); + } + + @Test + void smallestUniqueSubarray5() { + assertThat(new Solution().smallestUniqueSubarray(new int[] {1, 2, 1, 2}), equalTo(2)); + } + + @Test + void smallestUniqueSubarray6() { + assertThat(new Solution().smallestUniqueSubarray(new int[] {1, 2, 1, 2, 1, 2}), equalTo(4)); + } + + @Test + void smallestUniqueSubarray7() { + assertThat( + new Solution().smallestUniqueSubarray(new int[] {100000, 1, 100000, 1}), + equalTo(2)); + } +} diff --git a/src/test/java/g3901_4000/s3936_minimum_swaps_to_move_zeros_to_end/SolutionTest.java b/src/test/java/g3901_4000/s3936_minimum_swaps_to_move_zeros_to_end/SolutionTest.java new file mode 100644 index 000000000..875657fa2 --- /dev/null +++ b/src/test/java/g3901_4000/s3936_minimum_swaps_to_move_zeros_to_end/SolutionTest.java @@ -0,0 +1,43 @@ +package g3901_4000.s3936_minimum_swaps_to_move_zeros_to_end; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void minimumSwaps() { + assertThat(new Solution().minimumSwaps(new int[] {0, 1, 0, 3, 12}), equalTo(2)); + } + + @Test + void minimumSwaps2() { + assertThat(new Solution().minimumSwaps(new int[] {0, 1, 0, 2}), equalTo(1)); + } + + @Test + void minimumSwaps3() { + assertThat(new Solution().minimumSwaps(new int[] {1, 2, 0}), equalTo(0)); + } + + @Test + void minimumSwaps4() { + assertThat(new Solution().minimumSwaps(new int[] {0}), equalTo(0)); + } + + @Test + void minimumSwaps5() { + assertThat(new Solution().minimumSwaps(new int[] {1, 2, 3}), equalTo(0)); + } + + @Test + void minimumSwaps6() { + assertThat(new Solution().minimumSwaps(new int[] {0, 0, 0}), equalTo(0)); + } + + @Test + void minimumSwaps7() { + assertThat(new Solution().minimumSwaps(new int[] {0, 0, 1, 2}), equalTo(2)); + } +} diff --git a/src/test/java/g3901_4000/s3937_minimum_operations_to_make_array_modulo_alternating_i/SolutionTest.java b/src/test/java/g3901_4000/s3937_minimum_operations_to_make_array_modulo_alternating_i/SolutionTest.java new file mode 100644 index 000000000..c93c513f8 --- /dev/null +++ b/src/test/java/g3901_4000/s3937_minimum_operations_to_make_array_modulo_alternating_i/SolutionTest.java @@ -0,0 +1,38 @@ +package g3901_4000.s3937_minimum_operations_to_make_array_modulo_alternating_i; + +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, 4, 2, 8}, 3), equalTo(2)); + } + + @Test + void minOperations2() { + assertThat(new Solution().minOperations(new int[] {1, 1, 1}, 3), equalTo(1)); + } + + @Test + void minOperations3() { + assertThat(new Solution().minOperations(new int[] {1000000000}, 100), equalTo(0)); + } + + @Test + void minOperations4() { + assertThat(new Solution().minOperations(new int[] {1, 2, 3, 4}, 2), equalTo(0)); + } + + @Test + void minOperations5() { + assertThat(new Solution().minOperations(new int[] {2, 2, 2, 2}, 2), equalTo(2)); + } + + @Test + void minOperations6() { + assertThat(new Solution().minOperations(new int[] {1, 5, 1, 4}, 5), equalTo(1)); + } +} diff --git a/src/test/java/g3901_4000/s3938_maximum_path_intersection_sum_in_a_grid/SolutionTest.java b/src/test/java/g3901_4000/s3938_maximum_path_intersection_sum_in_a_grid/SolutionTest.java new file mode 100644 index 000000000..8767dc0f5 --- /dev/null +++ b/src/test/java/g3901_4000/s3938_maximum_path_intersection_sum_in_a_grid/SolutionTest.java @@ -0,0 +1,63 @@ +package g3901_4000.s3938_maximum_path_intersection_sum_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 maxScore() { + assertThat( + new Solution() + .maxScore( + new int[][] { + {1, 2, 0, -3}, + {1, -2, 1, 0}, + {-4, 2, -1, 3}, + {3, -3, 3, -2}, + {-1, -5, 0, 1} + }), + equalTo(4)); + } + + @Test + void maxScore2() { + assertThat( + new Solution().maxScore(new int[][] {{4, -2, -3}, {-1, -3, -1}, {-4, 2, -1}}), + equalTo(3)); + } + + @Test + void maxScore3() { + assertThat(new Solution().maxScore(new int[][] {{-1, -2}, {-3, -4}}), equalTo(-3)); + } + + @Test + void maxScore4() { + assertThat( + new Solution() + .maxScore( + new int[][] { + {-100, -100, -100}, {-100, -1, -100}, {-100, -100, -100} + }), + equalTo(-1)); + } + + @Test + void maxScore5() { + assertThat(new Solution().maxScore(new int[][] {{1, 2}, {3, 4}}), equalTo(7)); + } + + @Test + void maxScore6() { + assertThat(new Solution().maxScore(new int[][] {{0, 0}, {0, 0}}), equalTo(0)); + } + + @Test + void maxScore7() { + assertThat( + new Solution().maxScore(new int[][] {{5, -100}, {5, -100}, {5, -100}}), + equalTo(15)); + } +} diff --git a/src/test/java/g3901_4000/s3939_count_non_adjacent_subsets_in_a_rooted_tree/SolutionTest.java b/src/test/java/g3901_4000/s3939_count_non_adjacent_subsets_in_a_rooted_tree/SolutionTest.java new file mode 100644 index 000000000..f4eb0c846 --- /dev/null +++ b/src/test/java/g3901_4000/s3939_count_non_adjacent_subsets_in_a_rooted_tree/SolutionTest.java @@ -0,0 +1,65 @@ +package g3901_4000.s3939_count_non_adjacent_subsets_in_a_rooted_tree; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void countValidSubsets8() { + int[] parent = new int[32]; + parent[0] = -1; + int[] nums = new int[32]; + java.util.Arrays.fill(nums, 1); + // Any non-empty leaf subset or the root alone: 2^31 subsets modulo 1_000_000_007. + assertThat(new Solution().countValidSubsets(parent, nums, 1), equalTo(147483634)); + } + + @Test + void countValidSubsets() { + assertThat( + new Solution().countValidSubsets(new int[] {-1, 0, 1}, new int[] {1, 2, 3}, 3), + equalTo(1)); + } + + @Test + void countValidSubsets2() { + assertThat( + new Solution() + .countValidSubsets(new int[] {-1, 0, 0, 0}, new int[] {2, 1, 2, 1}, 3), + equalTo(2)); + } + + @Test + void countValidSubsets3() { + assertThat(new Solution().countValidSubsets(new int[] {-1}, new int[] {6}, 3), equalTo(1)); + } + + @Test + void countValidSubsets4() { + assertThat(new Solution().countValidSubsets(new int[] {-1}, new int[] {5}, 3), equalTo(0)); + } + + @Test + void countValidSubsets5() { + assertThat( + new Solution().countValidSubsets(new int[] {-1, 0, 1}, new int[] {1, 1, 1}, 1), + equalTo(4)); + } + + @Test + void countValidSubsets6() { + assertThat( + new Solution() + .countValidSubsets(new int[] {-1, 0, 0, 0}, new int[] {1, 1, 1, 1}, 1), + equalTo(8)); + } + + @Test + void countValidSubsets7() { + assertThat( + new Solution().countValidSubsets(new int[] {-1, 0}, new int[] {1, 2}, 3), + equalTo(0)); + } +} diff --git a/src/test/java/g3901_4000/s3940_limit_occurrences_in_sorted_array/SolutionTest.java b/src/test/java/g3901_4000/s3940_limit_occurrences_in_sorted_array/SolutionTest.java new file mode 100644 index 000000000..99511a040 --- /dev/null +++ b/src/test/java/g3901_4000/s3940_limit_occurrences_in_sorted_array/SolutionTest.java @@ -0,0 +1,39 @@ +package g3901_4000.s3940_limit_occurrences_in_sorted_array; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void limitOccurrences() { + assertThat( + new Solution().limitOccurrences(new int[] {1, 1, 1, 2, 2, 3}, 2), + equalTo(new int[] {1, 1, 2, 2, 3})); + } + + @Test + void limitOccurrences2() { + assertThat( + new Solution().limitOccurrences(new int[] {1, 2, 3}, 1), + equalTo(new int[] {1, 2, 3})); + } + + @Test + void limitOccurrences3() { + assertThat(new Solution().limitOccurrences(new int[] {5, 5, 5}, 1), equalTo(new int[] {5})); + } + + @Test + void limitOccurrences4() { + assertThat(new Solution().limitOccurrences(new int[] {100}, 1), equalTo(new int[] {100})); + } + + @Test + void limitOccurrences5() { + assertThat( + new Solution().limitOccurrences(new int[] {1, 1, 2, 2}, 4), + equalTo(new int[] {1, 1, 2, 2})); + } +} diff --git a/src/test/java/g3901_4000/s3941_password_strength/SolutionTest.java b/src/test/java/g3901_4000/s3941_password_strength/SolutionTest.java new file mode 100644 index 000000000..0b8522a58 --- /dev/null +++ b/src/test/java/g3901_4000/s3941_password_strength/SolutionTest.java @@ -0,0 +1,47 @@ +package g3901_4000.s3941_password_strength; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void passwordStrength() { + assertThat(new Solution().passwordStrength("aA1!"), equalTo(11)); + } + + @Test + void passwordStrength2() { + assertThat(new Solution().passwordStrength("bbB11#"), equalTo(11)); + } + + @Test + void passwordStrength3() { + assertThat(new Solution().passwordStrength("aaaa"), equalTo(1)); + } + + @Test + void passwordStrength4() { + assertThat(new Solution().passwordStrength("ZZZ"), equalTo(2)); + } + + @Test + void passwordStrength5() { + assertThat(new Solution().passwordStrength("000"), equalTo(3)); + } + + @Test + void passwordStrength6() { + assertThat(new Solution().passwordStrength("!@#$!"), equalTo(20)); + } + + @Test + void passwordStrength7() { + assertThat( + new Solution() + .passwordStrength( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$"), + equalTo(128)); + } +} diff --git a/src/test/java/g3901_4000/s3942_minimum_operations_to_sort_a_permutation/SolutionTest.java b/src/test/java/g3901_4000/s3942_minimum_operations_to_sort_a_permutation/SolutionTest.java new file mode 100644 index 000000000..a31c68f92 --- /dev/null +++ b/src/test/java/g3901_4000/s3942_minimum_operations_to_sort_a_permutation/SolutionTest.java @@ -0,0 +1,53 @@ +package g3901_4000.s3942_minimum_operations_to_sort_a_permutation; + +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[] {0, 2, 1}), equalTo(2)); + } + + @Test + void minOperations2() { + assertThat(new Solution().minOperations(new int[] {1, 0, 2}), equalTo(2)); + } + + @Test + void minOperations3() { + assertThat(new Solution().minOperations(new int[] {2, 0, 1, 3}), equalTo(-1)); + } + + @Test + void minOperations4() { + assertThat(new Solution().minOperations(new int[] {0}), equalTo(0)); + } + + @Test + void minOperations5() { + assertThat(new Solution().minOperations(new int[] {0, 1, 2, 3}), equalTo(0)); + } + + @Test + void minOperations6() { + assertThat(new Solution().minOperations(new int[] {3, 2, 1, 0}), equalTo(1)); + } + + @Test + void minOperations7() { + assertThat(new Solution().minOperations(new int[] {3, 0, 1, 2}), equalTo(1)); + } + + @Test + void minOperations8() { + assertThat(new Solution().minOperations(new int[] {1, 2, 3, 4, 5, 0}), equalTo(3)); + } + + @Test + void minOperations9() { + assertThat(new Solution().minOperations(new int[] {0, 5, 4, 3, 2, 1}), equalTo(2)); + } +} diff --git a/src/test/java/g3901_4000/s3943_number_of_pairs_after_increment/SolutionTest.java b/src/test/java/g3901_4000/s3943_number_of_pairs_after_increment/SolutionTest.java new file mode 100644 index 000000000..9b53ae4a6 --- /dev/null +++ b/src/test/java/g3901_4000/s3943_number_of_pairs_after_increment/SolutionTest.java @@ -0,0 +1,83 @@ +package g3901_4000.s3943_number_of_pairs_after_increment; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void numberOfPairs7() { + int[][] queries = new int[30001][]; + for (int i = 0; i < queries.length - 1; i++) { + queries[i] = new int[] {1, 0, 0, 100000}; + } + queries[queries.length - 1] = new int[] {2, 1000000000}; + assertThat( + new Solution().numberOfPairs(new int[] {1}, new int[] {1}, queries), + equalTo(new int[] {0})); + } + + @Test + void numberOfPairs() { + assertThat( + new Solution() + .numberOfPairs( + new int[] {1, 2}, + new int[] {3, 4}, + new int[][] {{2, 5}, {1, 0, 0, 2}, {2, 5}}), + equalTo(new int[] {2, 1})); + } + + @Test + void numberOfPairs2() { + assertThat( + new Solution() + .numberOfPairs( + new int[] {1, 1}, + new int[] {2, 2, 3}, + new int[][] {{2, 4}, {1, 0, 1, 1}, {2, 4}}), + equalTo(new int[] {2, 6})); + } + + @Test + void numberOfPairs3() { + assertThat( + new Solution() + .numberOfPairs( + new int[] {2, 5, 8, 4}, + new int[] {1, 3, 8}, + new int[][] {{2, 9}, {1, 1, 2, 1}, {2, 10}}), + equalTo(new int[] {1, 0})); + } + + @Test + void numberOfPairs4() { + assertThat( + new Solution() + .numberOfPairs( + new int[] {1}, + new int[] {1, 2, 3, 4}, + new int[][] {{1, 1, 2, 1}, {1, 1, 2, 2}, {2, 5}, {2, 6}, {2, 7}}), + equalTo(new int[] {1, 1, 1})); + } + + @Test + void numberOfPairs5() { + assertThat( + new Solution() + .numberOfPairs( + new int[] {1}, + new int[] {1, 2, 3}, + new int[][] {{1, 0, 2, 5}, {1, 1, 1, 2}, {2, 7}, {2, 10}, {2, 9}}), + equalTo(new int[] {1, 1, 1})); + } + + @Test + void numberOfPairs6() { + assertThat( + new Solution() + .numberOfPairs(new int[] {1}, new int[] {1}, new int[][] {{1, 0, 0, 1}}), + equalTo(new int[] {})); + } +} diff --git a/src/test/java/g3901_4000/s3945_digit_frequency_score/SolutionTest.java b/src/test/java/g3901_4000/s3945_digit_frequency_score/SolutionTest.java new file mode 100644 index 000000000..085cdb895 --- /dev/null +++ b/src/test/java/g3901_4000/s3945_digit_frequency_score/SolutionTest.java @@ -0,0 +1,38 @@ +package g3901_4000.s3945_digit_frequency_score; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.Test; + +class SolutionTest { + @Test + void digitFrequencyScore() { + assertThat(new Solution().digitFrequencyScore(122), equalTo(5)); + } + + @Test + void digitFrequencyScore2() { + assertThat(new Solution().digitFrequencyScore(101), equalTo(2)); + } + + @Test + void digitFrequencyScore3() { + assertThat(new Solution().digitFrequencyScore(1), equalTo(1)); + } + + @Test + void digitFrequencyScore4() { + assertThat(new Solution().digitFrequencyScore(999999999), equalTo(81)); + } + + @Test + void digitFrequencyScore5() { + assertThat(new Solution().digitFrequencyScore(1000000000), equalTo(1)); + } + + @Test + void digitFrequencyScore6() { + assertThat(new Solution().digitFrequencyScore(987654321), equalTo(45)); + } +}