Skip to content

Commit 25bbea3

Browse files
authoredMar 17, 2025··
Added tasks 3483-3490
1 parent 7ed6245 commit 25bbea3

File tree

24 files changed

+1004
-0
lines changed

24 files changed

+1004
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package g3401_3500.s3483_unique_3_digit_even_numbers;
2+
3+
// #Easy #Array #Hash_Table #Recursion #Enumeration
4+
// #2025_03_17_Time_5_ms_(100.00%)_Space_44.59_MB_(100.00%)
5+
6+
import java.util.HashSet;
7+
8+
public class Solution {
9+
public int totalNumbers(int[] digits) {
10+
HashSet<Integer> set = new HashSet<>();
11+
int n = digits.length;
12+
for (int i = 0; i < n; i++) {
13+
if (digits[i] == 0) {
14+
continue;
15+
}
16+
for (int j = 0; j < n; j++) {
17+
if (j == i) {
18+
continue;
19+
}
20+
for (int k = 0; k < n; k++) {
21+
if (k == i || k == j) {
22+
continue;
23+
}
24+
if (digits[k] % 2 == 0) {
25+
int number = digits[i] * 100 + digits[j] * 10 + digits[k];
26+
set.add(number);
27+
}
28+
}
29+
}
30+
}
31+
return set.size();
32+
}
33+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
3483\. Unique 3-Digit Even Numbers
2+
3+
Easy
4+
5+
You are given an array of digits called `digits`. Your task is to determine the number of **distinct** three-digit even numbers that can be formed using these digits.
6+
7+
**Note**: Each _copy_ of a digit can only be used **once per number**, and there may **not** be leading zeros.
8+
9+
**Example 1:**
10+
11+
**Input:** digits = [1,2,3,4]
12+
13+
**Output:** 12
14+
15+
**Explanation:** The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.
16+
17+
**Example 2:**
18+
19+
**Input:** digits = [0,2,2]
20+
21+
**Output:** 2
22+
23+
**Explanation:** The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.
24+
25+
**Example 3:**
26+
27+
**Input:** digits = [6,6,6]
28+
29+
**Output:** 1
30+
31+
**Explanation:** Only 666 can be formed.
32+
33+
**Example 4:**
34+
35+
**Input:** digits = [1,3,5]
36+
37+
**Output:** 0
38+
39+
**Explanation:** No even 3-digit numbers can be formed.
40+
41+
**Constraints:**
42+
43+
* `3 <= digits.length <= 10`
44+
* `0 <= digits[i] <= 9`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package g3401_3500.s3484_design_spreadsheet;
2+
3+
// #Medium #Array #String #Hash_Table #Matrix #Design
4+
// #2025_03_17_Time_117_ms_(100.00%)_Space_56.71_MB_(100.00%)
5+
6+
import java.util.HashMap;
7+
import java.util.Map;
8+
9+
@SuppressWarnings("unused")
10+
public class Spreadsheet {
11+
private final Map<String, Integer> data = new HashMap<>();
12+
13+
public Spreadsheet(int rows) {}
14+
15+
public void setCell(String cell, int value) {
16+
data.put(cell, value);
17+
}
18+
19+
public void resetCell(String cell) {
20+
data.put(cell, 0);
21+
}
22+
23+
public int getValue(String formula) {
24+
int index = formula.indexOf('+');
25+
String left = formula.substring(1, index);
26+
String right = formula.substring(index + 1);
27+
int x =
28+
Character.isLetter(left.charAt(0))
29+
? data.getOrDefault(left, 0)
30+
: Integer.parseInt(left);
31+
int y =
32+
Character.isLetter(right.charAt(0))
33+
? data.getOrDefault(right, 0)
34+
: Integer.parseInt(right);
35+
return x + y;
36+
}
37+
}
38+
39+
/*
40+
* Your Spreadsheet object will be instantiated and called as such:
41+
* Spreadsheet obj = new Spreadsheet(rows);
42+
* obj.setCell(cell,value);
43+
* obj.resetCell(cell);
44+
* int param_3 = obj.getValue(formula);
45+
*/
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
3484\. Design Spreadsheet
2+
3+
Medium
4+
5+
A spreadsheet is a grid with 26 columns (labeled from `'A'` to `'Z'`) and a given number of `rows`. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.
6+
7+
Implement the `Spreadsheet` class:
8+
9+
* `Spreadsheet(int rows)` Initializes a spreadsheet with 26 columns (labeled `'A'` to `'Z'`) and the specified number of rows. All cells are initially set to 0.
10+
* `void setCell(String cell, int value)` Sets the value of the specified `cell`. The cell reference is provided in the format `"AX"` (e.g., `"A1"`, `"B10"`), where the letter represents the column (from `'A'` to `'Z'`) and the number represents a **1-indexed** row.
11+
* `void resetCell(String cell)` Resets the specified cell to 0.
12+
* `int getValue(String formula)` Evaluates a formula of the form `"=X+Y"`, where `X` and `Y` are **either** cell references or non-negative integers, and returns the computed sum.
13+
14+
**Note:** If `getValue` references a cell that has not been explicitly set using `setCell`, its value is considered 0.
15+
16+
**Example 1:**
17+
18+
**Input:**
19+
["Spreadsheet", "getValue", "setCell", "getValue", "setCell", "getValue", "resetCell", "getValue"]
20+
[[3], ["=5+7"], ["A1", 10], ["=A1+6"], ["B2", 15], ["=A1+B2"], ["A1"], ["=A1+B2"]]
21+
22+
**Output:**
23+
[null, 12, null, 16, null, 25, null, 15]
24+
25+
**Explanation**
26+
27+
```java
28+
Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns
29+
spreadsheet.getValue("=5+7"); // returns 12 (5+7)
30+
spreadsheet.setCell("A1", 10); // sets A1 to 10
31+
spreadsheet.getValue("=A1+6"); // returns 16 (10+6)
32+
spreadsheet.setCell("B2", 15); // sets B2 to 15
33+
spreadsheet.getValue("=A1+B2"); // returns 25 (10+15)
34+
spreadsheet.resetCell("A1"); // resets A1 to 0
35+
spreadsheet.getValue("=A1+B2"); // returns 15 (0+15)
36+
```
37+
38+
**Constraints:**
39+
40+
* <code>1 <= rows <= 10<sup>3</sup></code>
41+
* <code>0 <= value <= 10<sup>5</sup></code>
42+
* The formula is always in the format `"=X+Y"`, where `X` and `Y` are either valid cell references or **non-negative** integers with values less than or equal to <code>10<sup>5</sup></code>.
43+
* Each cell reference consists of a capital letter from `'A'` to `'Z'` followed by a row number between `1` and `rows`.
44+
* At most <code>10<sup>4</sup></code> calls will be made in **total** to `setCell`, `resetCell`, and `getValue`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package g3401_3500.s3485_longest_common_prefix_of_k_strings_after_removal;
2+
3+
// #Hard #Array #String #Trie #2025_03_17_Time_333_ms_(100.00%)_Space_64.12_MB_(100.00%)
4+
5+
public class Solution {
6+
private static class TrieNode {
7+
TrieNode[] children = new TrieNode[26];
8+
int count = 0;
9+
int bestPrefixLength = -1;
10+
}
11+
12+
private TrieNode root;
13+
14+
public int[] longestCommonPrefix(String[] words, int k) {
15+
int totalWords = words.length;
16+
int[] result = new int[totalWords];
17+
if (totalWords - 1 < k) {
18+
return result;
19+
}
20+
root = new TrieNode();
21+
for (String word : words) {
22+
// insert the word with increasing the count by 1 (prefix count)
23+
updateTrie(word, 1, k);
24+
}
25+
for (int i = 0; i < totalWords; i++) {
26+
// temp deletion of the word with count decreased by 1
27+
updateTrie(words[i], -1, k);
28+
result[i] = root.bestPrefixLength;
29+
// re-insertion of the word
30+
updateTrie(words[i], 1, k);
31+
}
32+
return result;
33+
}
34+
35+
private void updateTrie(String word, int count, int k) {
36+
int wordLength = word.length();
37+
// used to store the path used during trie travesal to update the count and use the count
38+
TrieNode[] nodePath = new TrieNode[wordLength + 1];
39+
int[] depths = new int[wordLength + 1];
40+
nodePath[0] = root;
41+
depths[0] = 0;
42+
// trie insertion
43+
for (int i = 0; i < wordLength; i++) {
44+
int letterIndex = word.charAt(i) - 'a';
45+
if (nodePath[i].children[letterIndex] == null) {
46+
nodePath[i].children[letterIndex] = new TrieNode();
47+
}
48+
nodePath[i + 1] = nodePath[i].children[letterIndex];
49+
depths[i + 1] = depths[i] + 1;
50+
}
51+
// increase the count of each prefix
52+
for (TrieNode node : nodePath) {
53+
node.count += count;
54+
}
55+
// find the best prefix
56+
for (int i = nodePath.length - 1; i >= 0; i--) {
57+
TrieNode currentNode = nodePath[i];
58+
int candidate = (currentNode.count >= k ? depths[i] : -1);
59+
for (TrieNode childNode : currentNode.children) {
60+
if (childNode != null) {
61+
candidate = Math.max(candidate, childNode.bestPrefixLength);
62+
}
63+
}
64+
currentNode.bestPrefixLength = candidate;
65+
}
66+
}
67+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
3485\. Longest Common Prefix of K Strings After Removal
2+
3+
Hard
4+
5+
You are given an array of strings `words` and an integer `k`.
6+
7+
For each index `i` in the range `[0, words.length - 1]`, find the **length** of the **longest common prefix** among any `k` strings (selected at **distinct indices**) from the remaining array after removing the <code>i<sup>th</sup></code> element.
8+
9+
Return an array `answer`, where `answer[i]` is the answer for <code>i<sup>th</sup></code> element. If removing the <code>i<sup>th</sup></code> element leaves the array with fewer than `k` strings, `answer[i]` is 0.
10+
11+
**Example 1:**
12+
13+
**Input:** words = ["jump","run","run","jump","run"], k = 2
14+
15+
**Output:** [3,4,4,3,4]
16+
17+
**Explanation:**
18+
19+
* Removing index 0 (`"jump"`):
20+
* `words` becomes: `["run", "run", "jump", "run"]`. `"run"` occurs 3 times. Choosing any two gives the longest common prefix `"run"` (length 3).
21+
* Removing index 1 (`"run"`):
22+
* `words` becomes: `["jump", "run", "jump", "run"]`. `"jump"` occurs twice. Choosing these two gives the longest common prefix `"jump"` (length 4).
23+
* Removing index 2 (`"run"`):
24+
* `words` becomes: `["jump", "run", "jump", "run"]`. `"jump"` occurs twice. Choosing these two gives the longest common prefix `"jump"` (length 4).
25+
* Removing index 3 (`"jump"`):
26+
* `words` becomes: `["jump", "run", "run", "run"]`. `"run"` occurs 3 times. Choosing any two gives the longest common prefix `"run"` (length 3).
27+
* Removing index 4 ("run"):
28+
* `words` becomes: `["jump", "run", "run", "jump"]`. `"jump"` occurs twice. Choosing these two gives the longest common prefix `"jump"` (length 4).
29+
30+
**Example 2:**
31+
32+
**Input:** words = ["dog","racer","car"], k = 2
33+
34+
**Output:** [0,0,0]
35+
36+
**Explanation:**
37+
38+
* Removing any index results in an answer of 0.
39+
40+
**Constraints:**
41+
42+
* <code>1 <= k <= words.length <= 10<sup>5</sup></code>
43+
* <code>1 <= words[i].length <= 10<sup>4</sup></code>
44+
* `words[i]` consists of lowercase English letters.
45+
* The sum of `words[i].length` is smaller than or equal <code>10<sup>5</sup></code>.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package g3401_3500.s3486_longest_special_path_ii;
2+
3+
// #Hard #Array #Hash_Table #Tree #Prefix_Sum #Depth_First_Search
4+
// #2025_03_17_Time_166_ms_(100.00%)_Space_105.50_MB_(100.00%)
5+
6+
import java.util.ArrayList;
7+
import java.util.Arrays;
8+
import java.util.Comparator;
9+
import java.util.HashMap;
10+
import java.util.List;
11+
import java.util.Map;
12+
13+
@SuppressWarnings("java:S107")
14+
public class Solution {
15+
public int[] longestSpecialPath(int[][] edges, int[] nums) {
16+
int[] ans = {0, 1};
17+
Map<Integer, List<int[]>> graph = new HashMap<>();
18+
for (int[] edge : edges) {
19+
int a = edge[0];
20+
int b = edge[1];
21+
int c = edge[2];
22+
graph.computeIfAbsent(a, k -> new ArrayList<>()).add(new int[] {b, c});
23+
graph.computeIfAbsent(b, k -> new ArrayList<>()).add(new int[] {a, c});
24+
}
25+
List<Integer> costs = new ArrayList<>();
26+
Map<Integer, Integer> last = new HashMap<>();
27+
dfs(0, 0, -1, new ArrayList<>(Arrays.asList(0, 0)), nums, graph, costs, last, ans);
28+
return ans;
29+
}
30+
31+
private void dfs(
32+
int node,
33+
int currCost,
34+
int prev,
35+
List<Integer> left,
36+
int[] nums,
37+
Map<Integer, List<int[]>> graph,
38+
List<Integer> costs,
39+
Map<Integer, Integer> last,
40+
int[] ans) {
41+
int nodeColorIndexPrev = last.getOrDefault(nums[node], -1);
42+
last.put(nums[node], costs.size());
43+
costs.add(currCost);
44+
int diff = currCost - costs.get(left.get(0));
45+
int length = costs.size() - left.get(0);
46+
if (diff > ans[0] || (diff == ans[0] && length < ans[1])) {
47+
ans[0] = diff;
48+
ans[1] = length;
49+
}
50+
for (int[] next : graph.getOrDefault(node, new ArrayList<>())) {
51+
int nextNode = next[0];
52+
int nextCost = next[1];
53+
if (nextNode == prev) {
54+
continue;
55+
}
56+
List<Integer> nextLeft = new ArrayList<>(left);
57+
if (last.containsKey(nums[nextNode])) {
58+
nextLeft.add(last.get(nums[nextNode]) + 1);
59+
}
60+
nextLeft.sort(Comparator.naturalOrder());
61+
while (nextLeft.size() > 2) {
62+
nextLeft.remove(0);
63+
}
64+
dfs(nextNode, currCost + nextCost, node, nextLeft, nums, graph, costs, last, ans);
65+
}
66+
last.put(nums[node], nodeColorIndexPrev);
67+
costs.remove(costs.size() - 1);
68+
}
69+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
3486\. Longest Special Path II
2+
3+
Hard
4+
5+
You are given an undirected tree rooted at node `0`, with `n` nodes numbered from `0` to `n - 1`. This is represented by a 2D array `edges` of length `n - 1`, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, length<sub>i</sub>]</code> indicates an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with length <code>length<sub>i</sub></code>. You are also given an integer array `nums`, where `nums[i]` represents the value at node `i`.
6+
7+
A **special path** is defined as a **downward** path from an ancestor node to a descendant node in which all node values are **distinct**, except for **at most** one value that may appear twice.
8+
9+
Return an array `result` of size 2, where `result[0]` is the **length** of the **longest** special path, and `result[1]` is the **minimum** number of nodes in all _possible_ **longest** special paths.
10+
11+
**Example 1:**
12+
13+
**Input:** edges = [[0,1,1],[1,2,3],[1,3,1],[2,4,6],[4,7,2],[3,5,2],[3,6,5],[6,8,3]], nums = [1,1,0,3,1,2,1,1,0]
14+
15+
**Output:** [9,3]
16+
17+
**Explanation:**
18+
19+
In the image below, nodes are colored by their corresponding values in `nums`.
20+
21+
![](https://assets.leetcode.com/uploads/2025/02/18/e1.png)
22+
23+
The longest special paths are `1 -> 2 -> 4` and `1 -> 3 -> 6 -> 8`, both having a length of 9. The minimum number of nodes across all longest special paths is 3.
24+
25+
**Example 2:**
26+
27+
**Input:** edges = [[1,0,3],[0,2,4],[0,3,5]], nums = [1,1,0,2]
28+
29+
**Output:** [5,2]
30+
31+
**Explanation:**
32+
33+
![](https://assets.leetcode.com/uploads/2025/02/18/e2.png)
34+
35+
The longest path is `0 -> 3` consisting of 2 nodes with a length of 5.
36+
37+
**Constraints:**
38+
39+
* <code>2 <= n <= 5 * 10<sup>4</sup></code>
40+
* `edges.length == n - 1`
41+
* `edges[i].length == 3`
42+
* <code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code>
43+
* <code>1 <= length<sub>i</sub> <= 10<sup>3</sup></code>
44+
* `nums.length == n`
45+
* <code>0 <= nums[i] <= 5 * 10<sup>4</sup></code>
46+
* The input is generated such that `edges` represents a valid tree.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package g3401_3500.s3487_maximum_unique_subarray_sum_after_deletion;
2+
3+
// #Easy #Array #Hash_Table #Greedy #2025_03_17_Time_2_ms_(100.00%)_Space_42.64_MB_(100.00%)
4+
5+
import java.util.HashSet;
6+
import java.util.Set;
7+
8+
public class Solution {
9+
public int maxSum(int[] nums) {
10+
int sum = 0;
11+
Set<Integer> st = new HashSet<>();
12+
int mxNeg = Integer.MIN_VALUE;
13+
for (int num : nums) {
14+
if (num > 0) {
15+
st.add(num);
16+
} else {
17+
mxNeg = Math.max(mxNeg, num);
18+
}
19+
}
20+
for (int val : st) {
21+
sum += val;
22+
}
23+
if (!st.isEmpty()) {
24+
return sum;
25+
} else {
26+
return mxNeg;
27+
}
28+
}
29+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
3487\. Maximum Unique Subarray Sum After Deletion
2+
3+
Easy
4+
5+
You are given an integer array `nums`.
6+
7+
You are allowed to delete any number of elements from `nums` without making it **empty**. After performing the deletions, select a non-empty subarrays of `nums` such that:
8+
9+
1. All elements in the subarray are **unique**.
10+
2. The sum of the elements in the subarray is **maximized**.
11+
12+
Return the **maximum sum** of such a subarray.
13+
14+
**Example 1:**
15+
16+
**Input:** nums = [1,2,3,4,5]
17+
18+
**Output:** 15
19+
20+
**Explanation:**
21+
22+
Select the entire array without deleting any element to obtain the maximum sum.
23+
24+
**Example 2:**
25+
26+
**Input:** nums = [1,1,0,1,1]
27+
28+
**Output:** 1
29+
30+
**Explanation:**
31+
32+
Delete the element `nums[0] == 1`, `nums[1] == 1`, `nums[2] == 0`, and `nums[3] == 1`. Select the entire array `[1]` to obtain the maximum sum.
33+
34+
**Example 3:**
35+
36+
**Input:** nums = [1,2,-1,-2,1,0,-1]
37+
38+
**Output:** 3
39+
40+
**Explanation:**
41+
42+
Delete the elements `nums[2] == -1` and `nums[3] == -2`, and select the subarray `[2, 1]` from `[1, 2, 1, 0, -1]` to obtain the maximum sum.
43+
44+
**Constraints:**
45+
46+
* `1 <= nums.length <= 100`
47+
* `-100 <= nums[i] <= 100`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package g3401_3500.s3488_closest_equal_element_queries;
2+
3+
// #Medium #Array #Hash_Table #Binary_Search
4+
// #2025_03_17_Time_50_ms_(100.00%)_Space_74.96_MB_(100.00%)
5+
6+
import java.util.ArrayList;
7+
import java.util.HashMap;
8+
import java.util.List;
9+
import java.util.Map;
10+
11+
public class Solution {
12+
public List<Integer> solveQueries(int[] nums, int[] queries) {
13+
int sz = nums.length;
14+
Map<Integer, List<Integer>> indices = new HashMap<>();
15+
for (int i = 0; i < sz; i++) {
16+
indices.computeIfAbsent(nums[i], k -> new ArrayList<>()).add(i);
17+
}
18+
for (List<Integer> arr : indices.values()) {
19+
int m = arr.size();
20+
if (m == 1) {
21+
nums[arr.get(0)] = -1;
22+
continue;
23+
}
24+
for (int i = 0; i < m; i++) {
25+
int j = arr.get(i);
26+
int f = arr.get((i + 1) % m);
27+
int b = arr.get((i - 1 + m) % m);
28+
int forward = Math.min((sz - j - 1) + f + 1, Math.abs(j - f));
29+
int backward = Math.min(Math.abs(b - j), j + (sz - b));
30+
nums[j] = Math.min(backward, forward);
31+
}
32+
}
33+
List<Integer> res = new ArrayList<>();
34+
for (int q : queries) {
35+
res.add(nums[q]);
36+
}
37+
return res;
38+
}
39+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
3488\. Closest Equal Element Queries
2+
3+
Medium
4+
5+
You are given a **circular** array `nums` and an array `queries`.
6+
7+
For each query `i`, you have to find the following:
8+
9+
* The **minimum** distance between the element at index `queries[i]` and **any** other index `j` in the **circular** array, where `nums[j] == nums[queries[i]]`. If no such index exists, the answer for that query should be -1.
10+
11+
Return an array `answer` of the **same** size as `queries`, where `answer[i]` represents the result for query `i`.
12+
13+
**Example 1:**
14+
15+
**Input:** nums = [1,3,1,4,1,3,2], queries = [0,3,5]
16+
17+
**Output:** [2,-1,3]
18+
19+
**Explanation:**
20+
21+
* Query 0: The element at `queries[0] = 0` is `nums[0] = 1`. The nearest index with the same value is 2, and the distance between them is 2.
22+
* Query 1: The element at `queries[1] = 3` is `nums[3] = 4`. No other index contains 4, so the result is -1.
23+
* Query 2: The element at `queries[2] = 5` is `nums[5] = 3`. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: `5 -> 6 -> 0 -> 1`).
24+
25+
**Example 2:**
26+
27+
**Input:** nums = [1,2,3,4], queries = [0,1,2,3]
28+
29+
**Output:** [-1,-1,-1,-1]
30+
31+
**Explanation:**
32+
33+
Each value in `nums` is unique, so no index shares the same value as the queried element. This results in -1 for all queries.
34+
35+
**Constraints:**
36+
37+
* <code>1 <= queries.length <= nums.length <= 10<sup>5</sup></code>
38+
* <code>1 <= nums[i] <= 10<sup>6</sup></code>
39+
* `0 <= queries[i] < nums.length`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package g3401_3500.s3489_zero_array_transformation_iv;
2+
3+
// #Medium #Array #Dynamic_Programming #2025_03_17_Time_142_ms_(100.00%)_Space_56.22_MB_(100.00%)
4+
5+
import java.util.Arrays;
6+
7+
public class Solution {
8+
private int solve(int[][] q, int i, int target, int k, int[][] dp) {
9+
// we found a valid sum equal to target so return current index of query.
10+
if (target == 0) {
11+
return k;
12+
}
13+
// return a larger number to invalidate this flow
14+
if (k >= q.length || target < 0) {
15+
return q.length + 1;
16+
}
17+
if (dp[target][k] != -1) {
18+
return dp[target][k];
19+
}
20+
// skip current query val
21+
int res = solve(q, i, target, k + 1, dp);
22+
// pick the val if its range is in the range of target index
23+
if (q[k][0] <= i && i <= q[k][1]) {
24+
res = Math.min(res, solve(q, i, target - q[k][2], k + 1, dp));
25+
}
26+
dp[target][k] = res;
27+
return res;
28+
}
29+
30+
public int minZeroArray(int[] nums, int[][] queries) {
31+
int ans = -1;
32+
for (int i = 0; i < nums.length; ++i) {
33+
int[][] dp = new int[nums[i] + 1][queries.length];
34+
Arrays.stream(dp).forEach(row -> Arrays.fill(row, -1));
35+
ans = Math.max(ans, solve(queries, i, nums[i], 0, dp));
36+
}
37+
return (ans > queries.length) ? -1 : ans;
38+
}
39+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
3489\. Zero Array Transformation IV
2+
3+
Medium
4+
5+
You are given an integer array `nums` of length `n` and a 2D array `queries`, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>, val<sub>i</sub>]</code>.
6+
7+
Each `queries[i]` represents the following action on `nums`:
8+
9+
* Select a **subset** of indices in the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> from `nums`.
10+
* Decrement the value at each selected index by **exactly** <code>val<sub>i</sub></code>.
11+
12+
A **Zero Array** is an array with all its elements equal to 0.
13+
14+
Return the **minimum** possible **non-negative** value of `k`, such that after processing the first `k` queries in **sequence**, `nums` becomes a **Zero Array**. If no such `k` exists, return -1.
15+
16+
**Example 1:**
17+
18+
**Input:** nums = [2,0,2], queries = [[0,2,1],[0,2,1],[1,1,3]]
19+
20+
**Output:** 2
21+
22+
**Explanation:**
23+
24+
* **For query 0 (l = 0, r = 2, val = 1):**
25+
* Decrement the values at indices `[0, 2]` by 1.
26+
* The array will become `[1, 0, 1]`.
27+
* **For query 1 (l = 0, r = 2, val = 1):**
28+
* Decrement the values at indices `[0, 2]` by 1.
29+
* The array will become `[0, 0, 0]`, which is a Zero Array. Therefore, the minimum value of `k` is 2.
30+
31+
**Example 2:**
32+
33+
**Input:** nums = [4,3,2,1], queries = [[1,3,2],[0,2,1]]
34+
35+
**Output:** \-1
36+
37+
**Explanation:**
38+
39+
It is impossible to make nums a Zero Array even after all the queries.
40+
41+
**Example 3:**
42+
43+
**Input:** nums = [1,2,3,2,1], queries = [[0,1,1],[1,2,1],[2,3,2],[3,4,1],[4,4,1]]
44+
45+
**Output:** 4
46+
47+
**Explanation:**
48+
49+
* **For query 0 (l = 0, r = 1, val = 1):**
50+
* Decrement the values at indices `[0, 1]` by `1`.
51+
* The array will become `[0, 1, 3, 2, 1]`.
52+
* **For query 1 (l = 1, r = 2, val = 1):**
53+
* Decrement the values at indices `[1, 2]` by 1.
54+
* The array will become `[0, 0, 2, 2, 1]`.
55+
* **For query 2 (l = 2, r = 3, val = 2):**
56+
* Decrement the values at indices `[2, 3]` by 2.
57+
* The array will become `[0, 0, 0, 0, 1]`.
58+
* **For query 3 (l = 3, r = 4, val = 1):**
59+
* Decrement the value at index 4 by 1.
60+
* The array will become `[0, 0, 0, 0, 0]`. Therefore, the minimum value of `k` is 4.
61+
62+
**Example 4:**
63+
64+
**Input:** nums = [1,2,3,2,6], queries = [[0,1,1],[0,2,1],[1,4,2],[4,4,4],[3,4,1],[4,4,5]]
65+
66+
**Output:** 4
67+
68+
**Constraints:**
69+
70+
* `1 <= nums.length <= 10`
71+
* `0 <= nums[i] <= 1000`
72+
* `1 <= queries.length <= 1000`
73+
* <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>, val<sub>i</sub>]</code>
74+
* <code>0 <= l<sub>i</sub> <= r<sub>i</sub> < nums.length</code>
75+
* <code>1 <= val<sub>i</sub> <= 10</code>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package g3401_3500.s3490_count_beautiful_numbers;
2+
3+
// #Hard #Dynamic_Programming #2025_03_17_Time_523_ms_(100.00%)_Space_55.41_MB_(100.00%)
4+
5+
import java.util.HashMap;
6+
7+
public class Solution {
8+
public int beautifulNumbers(int l, int r) {
9+
return countBeautiful(r) - countBeautiful(l - 1);
10+
}
11+
12+
private int countBeautiful(int x) {
13+
char[] digits = getCharArray(x);
14+
HashMap<String, Integer> dp = new HashMap<>();
15+
return solve(0, 1, 0, 1, digits, dp);
16+
}
17+
18+
private char[] getCharArray(int x) {
19+
String str = String.valueOf(x);
20+
return str.toCharArray();
21+
}
22+
23+
private int solve(
24+
int i, int tight, int sum, int prod, char[] digits, HashMap<String, Integer> dp) {
25+
if (i == digits.length) {
26+
if (sum > 0 && prod % sum == 0) {
27+
return 1;
28+
} else {
29+
return 0;
30+
}
31+
}
32+
String str = i + " - " + tight + " - " + sum + " - " + prod;
33+
if (dp.containsKey(str)) {
34+
return dp.get(str);
35+
}
36+
int limit;
37+
if (tight == 1) {
38+
limit = digits[i] - '0';
39+
} else {
40+
limit = 9;
41+
}
42+
int count = 0;
43+
int j = 0;
44+
while (j <= limit) {
45+
int newTight = 0;
46+
if (tight == 1 && j == limit) {
47+
newTight = 1;
48+
}
49+
int newSum = sum + j;
50+
int newProd;
51+
if (j == 0 && sum == 0) {
52+
newProd = 1;
53+
} else {
54+
newProd = prod * j;
55+
}
56+
count += solve(i + 1, newTight, newSum, newProd, digits, dp);
57+
j++;
58+
}
59+
dp.put(str, count);
60+
return count;
61+
}
62+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
3490\. Count Beautiful Numbers
2+
3+
Hard
4+
5+
You are given two positive integers, `l` and `r`. A positive integer is called **beautiful** if the product of its digits is divisible by the sum of its digits.
6+
7+
Return the count of **beautiful** numbers between `l` and `r`, inclusive.
8+
9+
**Example 1:**
10+
11+
**Input:** l = 10, r = 20
12+
13+
**Output:** 2
14+
15+
**Explanation:**
16+
17+
The beautiful numbers in the range are 10 and 20.
18+
19+
**Example 2:**
20+
21+
**Input:** l = 1, r = 15
22+
23+
**Output:** 10
24+
25+
**Explanation:**
26+
27+
The beautiful numbers in the range are 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10.
28+
29+
**Constraints:**
30+
31+
* <code>1 <= l <= r < 10<sup>9</sup></code>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package g3401_3500.s3483_unique_3_digit_even_numbers;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void totalNumbers() {
11+
assertThat(new Solution().totalNumbers(new int[] {1, 2, 3, 4}), equalTo(12));
12+
}
13+
14+
@Test
15+
void totalNumbers2() {
16+
assertThat(new Solution().totalNumbers(new int[] {0, 2, 2}), equalTo(2));
17+
}
18+
19+
@Test
20+
void totalNumbers3() {
21+
assertThat(new Solution().totalNumbers(new int[] {6, 6, 6}), equalTo(1));
22+
}
23+
24+
@Test
25+
void totalNumbers4() {
26+
assertThat(new Solution().totalNumbers(new int[] {1, 3, 5}), equalTo(0));
27+
}
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package g3401_3500.s3484_design_spreadsheet;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SpreadsheetTest {
9+
@Test
10+
void spreadsheet() {
11+
// Initializes a spreadsheet with 3 rows and 26 columns
12+
Spreadsheet spreadsheet = new Spreadsheet(3);
13+
// returns 12 (5+7)
14+
assertThat(spreadsheet.getValue("=5+7"), equalTo(12));
15+
// sets A1 to 10
16+
spreadsheet.setCell("A1", 10);
17+
// returns 16 (10+6)
18+
assertThat(spreadsheet.getValue("=A1+6"), equalTo(16));
19+
// sets B2 to 15
20+
spreadsheet.setCell("B2", 15);
21+
// returns 25 (10+15)
22+
assertThat(spreadsheet.getValue("=A1+B2"), equalTo(25));
23+
// resets A1 to 0
24+
spreadsheet.resetCell("A1");
25+
// returns 15 (0+15)
26+
assertThat(spreadsheet.getValue("=A1+B2"), equalTo(15));
27+
}
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package g3401_3500.s3485_longest_common_prefix_of_k_strings_after_removal;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void longestCommonPrefix() {
11+
assertThat(
12+
new Solution()
13+
.longestCommonPrefix(new String[] {"jump", "run", "run", "jump", "run"}, 2),
14+
equalTo(new int[] {3, 4, 4, 3, 4}));
15+
}
16+
17+
@Test
18+
void longestCommonPrefix2() {
19+
assertThat(
20+
new Solution().longestCommonPrefix(new String[] {"dog", "racer", "car"}, 2),
21+
equalTo(new int[] {0, 0, 0}));
22+
}
23+
24+
@Test
25+
void longestCommonPrefix3() {
26+
assertThat(
27+
new Solution().longestCommonPrefix(new String[] {"cdbff"}, 1),
28+
equalTo(new int[] {0}));
29+
}
30+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package g3401_3500.s3486_longest_special_path_ii;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void longestSpecialPath() {
11+
assertThat(
12+
new Solution()
13+
.longestSpecialPath(
14+
new int[][] {
15+
{0, 1, 1}, {1, 2, 3}, {1, 3, 1}, {2, 4, 6}, {4, 7, 2},
16+
{3, 5, 2}, {3, 6, 5}, {6, 8, 3}
17+
},
18+
new int[] {1, 1, 0, 3, 1, 2, 1, 1, 0}),
19+
equalTo(new int[] {9, 3}));
20+
}
21+
22+
@Test
23+
void longestSpecialPath2() {
24+
assertThat(
25+
new Solution()
26+
.longestSpecialPath(
27+
new int[][] {{1, 0, 3}, {0, 2, 4}, {0, 3, 5}},
28+
new int[] {1, 1, 0, 2}),
29+
equalTo(new int[] {5, 2}));
30+
}
31+
32+
@Test
33+
void longestSpecialPath3() {
34+
assertThat(
35+
new Solution()
36+
.longestSpecialPath(
37+
new int[][] {{0, 2, 4}, {1, 2, 10}, {3, 1, 5}},
38+
new int[] {4, 5, 4, 5}),
39+
equalTo(new int[] {15, 3}));
40+
}
41+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package g3401_3500.s3487_maximum_unique_subarray_sum_after_deletion;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void maxSum() {
11+
assertThat(new Solution().maxSum(new int[] {1, 2, 3, 4, 5}), equalTo(15));
12+
}
13+
14+
@Test
15+
void maxSum2() {
16+
assertThat(new Solution().maxSum(new int[] {1, 1, 0, 1, 1}), equalTo(1));
17+
}
18+
19+
@Test
20+
void maxSum3() {
21+
assertThat(new Solution().maxSum(new int[] {1, 2, -1, -2, 1, 0, -1}), equalTo(3));
22+
}
23+
24+
@Test
25+
void maxSum4() {
26+
assertThat(new Solution().maxSum(new int[] {-100}), equalTo(-100));
27+
}
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package g3401_3500.s3488_closest_equal_element_queries;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import java.util.List;
7+
import org.junit.jupiter.api.Test;
8+
9+
class SolutionTest {
10+
@Test
11+
void solveQueries() {
12+
assertThat(
13+
new Solution().solveQueries(new int[] {1, 3, 1, 4, 1, 3, 2}, new int[] {0, 3, 5}),
14+
equalTo(List.of(2, -1, 3)));
15+
}
16+
17+
@Test
18+
void solveQueries2() {
19+
assertThat(
20+
new Solution().solveQueries(new int[] {1, 2, 3, 4}, new int[] {0, 1, 2, 3}),
21+
equalTo(List.of(-1, -1, -1, -1)));
22+
}
23+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package g3401_3500.s3489_zero_array_transformation_iv;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void minZeroArray() {
11+
assertThat(
12+
new Solution()
13+
.minZeroArray(
14+
new int[] {2, 0, 2}, new int[][] {{0, 2, 1}, {0, 2, 1}, {1, 1, 3}}),
15+
equalTo(2));
16+
}
17+
18+
@Test
19+
void minZeroArray2() {
20+
assertThat(
21+
new Solution()
22+
.minZeroArray(new int[] {4, 3, 2, 1}, new int[][] {{1, 3, 2}, {0, 2, 1}}),
23+
equalTo(-1));
24+
}
25+
26+
@Test
27+
void minZeroArray3() {
28+
assertThat(
29+
new Solution()
30+
.minZeroArray(
31+
new int[] {1, 2, 3, 2, 1},
32+
new int[][] {
33+
{0, 1, 1}, {1, 2, 1}, {2, 3, 2}, {3, 4, 1}, {4, 4, 1}
34+
}),
35+
equalTo(4));
36+
}
37+
38+
@Test
39+
void minZeroArray4() {
40+
assertThat(
41+
new Solution()
42+
.minZeroArray(
43+
new int[] {1, 2, 3, 2, 6},
44+
new int[][] {
45+
{0, 1, 1}, {0, 2, 1}, {1, 4, 2}, {4, 4, 4}, {3, 4, 1}, {4, 4, 5}
46+
}),
47+
equalTo(4));
48+
}
49+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package g3401_3500.s3490_count_beautiful_numbers;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void beautifulNumbers() {
11+
assertThat(new Solution().beautifulNumbers(10, 20), equalTo(2));
12+
}
13+
14+
@Test
15+
void beautifulNumbers2() {
16+
assertThat(new Solution().beautifulNumbers(1, 15), equalTo(10));
17+
}
18+
19+
@Test
20+
void beautifulNumbers3() {
21+
assertThat(new Solution().beautifulNumbers(6725, 270910825), equalTo(178996547));
22+
}
23+
}

0 commit comments

Comments
 (0)
Please sign in to comment.