Skip to content

Added tasks 3483-3490 #1945

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Mar 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package g3401_3500.s3483_unique_3_digit_even_numbers;

// #Easy #Array #Hash_Table #Recursion #Enumeration
// #2025_03_17_Time_5_ms_(100.00%)_Space_44.59_MB_(100.00%)

import java.util.HashSet;

public class Solution {
public int totalNumbers(int[] digits) {
HashSet<Integer> set = new HashSet<>();
int n = digits.length;
for (int i = 0; i < n; i++) {
if (digits[i] == 0) {
continue;
}
for (int j = 0; j < n; j++) {
if (j == i) {
continue;
}
for (int k = 0; k < n; k++) {
if (k == i || k == j) {
continue;
}
if (digits[k] % 2 == 0) {
int number = digits[i] * 100 + digits[j] * 10 + digits[k];
set.add(number);
}
}
}
}
return set.size();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
3483\. Unique 3-Digit Even Numbers

Easy

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.

**Note**: Each _copy_ of a digit can only be used **once per number**, and there may **not** be leading zeros.

**Example 1:**

**Input:** digits = [1,2,3,4]

**Output:** 12

**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.

**Example 2:**

**Input:** digits = [0,2,2]

**Output:** 2

**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.

**Example 3:**

**Input:** digits = [6,6,6]

**Output:** 1

**Explanation:** Only 666 can be formed.

**Example 4:**

**Input:** digits = [1,3,5]

**Output:** 0

**Explanation:** No even 3-digit numbers can be formed.

**Constraints:**

* `3 <= digits.length <= 10`
* `0 <= digits[i] <= 9`
45 changes: 45 additions & 0 deletions src/main/java/g3401_3500/s3484_design_spreadsheet/Spreadsheet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package g3401_3500.s3484_design_spreadsheet;

// #Medium #Array #String #Hash_Table #Matrix #Design
// #2025_03_17_Time_117_ms_(100.00%)_Space_56.71_MB_(100.00%)

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("unused")
public class Spreadsheet {
private final Map<String, Integer> data = new HashMap<>();

public Spreadsheet(int rows) {}

public void setCell(String cell, int value) {
data.put(cell, value);
}

public void resetCell(String cell) {
data.put(cell, 0);
}

public int getValue(String formula) {
int index = formula.indexOf('+');
String left = formula.substring(1, index);
String right = formula.substring(index + 1);
int x =
Character.isLetter(left.charAt(0))
? data.getOrDefault(left, 0)
: Integer.parseInt(left);
int y =
Character.isLetter(right.charAt(0))
? data.getOrDefault(right, 0)
: Integer.parseInt(right);
return x + y;
}
}

/*
* Your Spreadsheet object will be instantiated and called as such:
* Spreadsheet obj = new Spreadsheet(rows);
* obj.setCell(cell,value);
* obj.resetCell(cell);
* int param_3 = obj.getValue(formula);
*/
44 changes: 44 additions & 0 deletions src/main/java/g3401_3500/s3484_design_spreadsheet/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
3484\. Design Spreadsheet

Medium

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>.

Implement the `Spreadsheet` class:

* `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.
* `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.
* `void resetCell(String cell)` Resets the specified cell to 0.
* `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.

**Note:** If `getValue` references a cell that has not been explicitly set using `setCell`, its value is considered 0.

**Example 1:**

**Input:**
["Spreadsheet", "getValue", "setCell", "getValue", "setCell", "getValue", "resetCell", "getValue"]
[[3], ["=5+7"], ["A1", 10], ["=A1+6"], ["B2", 15], ["=A1+B2"], ["A1"], ["=A1+B2"]]

**Output:**
[null, 12, null, 16, null, 25, null, 15]

**Explanation**

```java
Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns
spreadsheet.getValue("=5+7"); // returns 12 (5+7)
spreadsheet.setCell("A1", 10); // sets A1 to 10
spreadsheet.getValue("=A1+6"); // returns 16 (10+6)
spreadsheet.setCell("B2", 15); // sets B2 to 15
spreadsheet.getValue("=A1+B2"); // returns 25 (10+15)
spreadsheet.resetCell("A1"); // resets A1 to 0
spreadsheet.getValue("=A1+B2"); // returns 15 (0+15)
```

**Constraints:**

* <code>1 <= rows <= 10<sup>3</sup></code>
* <code>0 <= value <= 10<sup>5</sup></code>
* 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>.
* Each cell reference consists of a capital letter from `'A'` to `'Z'` followed by a row number between `1` and `rows`.
* At most <code>10<sup>4</sup></code> calls will be made in **total** to `setCell`, `resetCell`, and `getValue`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package g3401_3500.s3485_longest_common_prefix_of_k_strings_after_removal;

// #Hard #Array #String #Trie #2025_03_17_Time_333_ms_(100.00%)_Space_64.12_MB_(100.00%)

public class Solution {
private static class TrieNode {
TrieNode[] children = new TrieNode[26];
int count = 0;
int bestPrefixLength = -1;
}

private TrieNode root;

public int[] longestCommonPrefix(String[] words, int k) {
int totalWords = words.length;
int[] result = new int[totalWords];
if (totalWords - 1 < k) {
return result;
}
root = new TrieNode();
for (String word : words) {
// insert the word with increasing the count by 1 (prefix count)
updateTrie(word, 1, k);
}
for (int i = 0; i < totalWords; i++) {
// temp deletion of the word with count decreased by 1
updateTrie(words[i], -1, k);
result[i] = root.bestPrefixLength;
// re-insertion of the word
updateTrie(words[i], 1, k);
}
return result;
}

private void updateTrie(String word, int count, int k) {
int wordLength = word.length();
// used to store the path used during trie travesal to update the count and use the count
TrieNode[] nodePath = new TrieNode[wordLength + 1];
int[] depths = new int[wordLength + 1];
nodePath[0] = root;
depths[0] = 0;
// trie insertion
for (int i = 0; i < wordLength; i++) {
int letterIndex = word.charAt(i) - 'a';
if (nodePath[i].children[letterIndex] == null) {
nodePath[i].children[letterIndex] = new TrieNode();
}
nodePath[i + 1] = nodePath[i].children[letterIndex];
depths[i + 1] = depths[i] + 1;
}
// increase the count of each prefix
for (TrieNode node : nodePath) {
node.count += count;
}
// find the best prefix
for (int i = nodePath.length - 1; i >= 0; i--) {
TrieNode currentNode = nodePath[i];
int candidate = (currentNode.count >= k ? depths[i] : -1);
for (TrieNode childNode : currentNode.children) {
if (childNode != null) {
candidate = Math.max(candidate, childNode.bestPrefixLength);
}
}
currentNode.bestPrefixLength = candidate;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
3485\. Longest Common Prefix of K Strings After Removal

Hard

You are given an array of strings `words` and an integer `k`.

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.

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.

**Example 1:**

**Input:** words = ["jump","run","run","jump","run"], k = 2

**Output:** [3,4,4,3,4]

**Explanation:**

* Removing index 0 (`"jump"`):
* `words` becomes: `["run", "run", "jump", "run"]`. `"run"` occurs 3 times. Choosing any two gives the longest common prefix `"run"` (length 3).
* Removing index 1 (`"run"`):
* `words` becomes: `["jump", "run", "jump", "run"]`. `"jump"` occurs twice. Choosing these two gives the longest common prefix `"jump"` (length 4).
* Removing index 2 (`"run"`):
* `words` becomes: `["jump", "run", "jump", "run"]`. `"jump"` occurs twice. Choosing these two gives the longest common prefix `"jump"` (length 4).
* Removing index 3 (`"jump"`):
* `words` becomes: `["jump", "run", "run", "run"]`. `"run"` occurs 3 times. Choosing any two gives the longest common prefix `"run"` (length 3).
* Removing index 4 ("run"):
* `words` becomes: `["jump", "run", "run", "jump"]`. `"jump"` occurs twice. Choosing these two gives the longest common prefix `"jump"` (length 4).

**Example 2:**

**Input:** words = ["dog","racer","car"], k = 2

**Output:** [0,0,0]

**Explanation:**

* Removing any index results in an answer of 0.

**Constraints:**

* <code>1 <= k <= words.length <= 10<sup>5</sup></code>
* <code>1 <= words[i].length <= 10<sup>4</sup></code>
* `words[i]` consists of lowercase English letters.
* The sum of `words[i].length` is smaller than or equal <code>10<sup>5</sup></code>.
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package g3401_3500.s3486_longest_special_path_ii;

// #Hard #Array #Hash_Table #Tree #Prefix_Sum #Depth_First_Search
// #2025_03_17_Time_166_ms_(100.00%)_Space_105.50_MB_(100.00%)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("java:S107")
public class Solution {
public int[] longestSpecialPath(int[][] edges, int[] nums) {
int[] ans = {0, 1};
Map<Integer, List<int[]>> graph = new HashMap<>();
for (int[] edge : edges) {
int a = edge[0];
int b = edge[1];
int c = edge[2];
graph.computeIfAbsent(a, k -> new ArrayList<>()).add(new int[] {b, c});
graph.computeIfAbsent(b, k -> new ArrayList<>()).add(new int[] {a, c});
}
List<Integer> costs = new ArrayList<>();
Map<Integer, Integer> last = new HashMap<>();
dfs(0, 0, -1, new ArrayList<>(Arrays.asList(0, 0)), nums, graph, costs, last, ans);
return ans;
}

private void dfs(
int node,
int currCost,
int prev,
List<Integer> left,
int[] nums,
Map<Integer, List<int[]>> graph,
List<Integer> costs,
Map<Integer, Integer> last,
int[] ans) {
int nodeColorIndexPrev = last.getOrDefault(nums[node], -1);
last.put(nums[node], costs.size());
costs.add(currCost);
int diff = currCost - costs.get(left.get(0));
int length = costs.size() - left.get(0);
if (diff > ans[0] || (diff == ans[0] && length < ans[1])) {
ans[0] = diff;
ans[1] = length;
}
for (int[] next : graph.getOrDefault(node, new ArrayList<>())) {
int nextNode = next[0];
int nextCost = next[1];
if (nextNode == prev) {
continue;
}
List<Integer> nextLeft = new ArrayList<>(left);
if (last.containsKey(nums[nextNode])) {
nextLeft.add(last.get(nums[nextNode]) + 1);
}
nextLeft.sort(Comparator.naturalOrder());
while (nextLeft.size() > 2) {
nextLeft.remove(0);
}
dfs(nextNode, currCost + nextCost, node, nextLeft, nums, graph, costs, last, ans);
}
last.put(nums[node], nodeColorIndexPrev);
costs.remove(costs.size() - 1);
}
}
Loading