Skip to content

Commit 292cd87

Browse files
authored
Added tasks 3483-3490
1 parent 54c8b54 commit 292cd87

File tree

24 files changed

+1024
-0
lines changed

24 files changed

+1024
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package g3401_3500.s3483_unique_3_digit_even_numbers
2+
3+
// #Easy #Array #Hash_Table #Recursion #Enumeration
4+
// #2025_03_16_Time_6_ms_(100.00%)_Space_44.99_MB_(100.00%)
5+
6+
class Solution {
7+
fun totalNumbers(digits: IntArray): Int {
8+
val set = HashSet<Int>()
9+
val n = digits.size
10+
for (i in 0..<n) {
11+
if (digits[i] == 0) {
12+
continue
13+
}
14+
for (j in 0..<n) {
15+
if (j == i) {
16+
continue
17+
}
18+
for (k in 0..<n) {
19+
if (k == i || k == j) {
20+
continue
21+
}
22+
if (digits[k] % 2 == 0) {
23+
val number = digits[i] * 100 + digits[j] * 10 + digits[k]
24+
set.add(number)
25+
}
26+
}
27+
}
28+
}
29+
return set.size
30+
}
31+
}
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,44 @@
1+
package g3401_3500.s3484_design_spreadsheet
2+
3+
// #Medium #Array #String #Hash_Table #Matrix #Design
4+
// #2025_03_16_Time_176_ms_(100.00%)_Space_79.62_MB_(100.00%)
5+
6+
@Suppress("unused")
7+
class Spreadsheet(rows: Int) {
8+
private val data: MutableMap<String, Int> = HashMap<String, Int>()
9+
10+
fun setCell(cell: String, value: Int) {
11+
data.put(cell, value)
12+
}
13+
14+
fun resetCell(cell: String) {
15+
data.put(cell, 0)
16+
}
17+
18+
fun getValue(formula: String): Int {
19+
val index = formula.indexOf('+')
20+
val left = formula.substring(1, index)
21+
val right = formula.substring(index + 1)
22+
val x =
23+
if (Character.isLetter(left[0])) {
24+
data.getOrDefault(left, 0)
25+
} else {
26+
left.toInt()
27+
}
28+
val y =
29+
if (Character.isLetter(right[0])) {
30+
data.getOrDefault(right, 0)
31+
} else {
32+
right.toInt()
33+
}
34+
return x + y
35+
}
36+
}
37+
38+
/*
39+
* Your Spreadsheet object will be instantiated and called as such:
40+
* var obj = Spreadsheet(rows)
41+
* obj.setCell(cell,value)
42+
* obj.resetCell(cell)
43+
* var param_3 = obj.getValue(formula)
44+
*/
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,69 @@
1+
package g3401_3500.s3485_longest_common_prefix_of_k_strings_after_removal
2+
3+
// #Hard #Array #String #Trie #2025_03_16_Time_251_ms_(100.00%)_Space_86.10_MB_(100.00%)
4+
5+
import kotlin.math.max
6+
7+
class Solution {
8+
private class TrieNode {
9+
var children: Array<TrieNode?> = arrayOfNulls<TrieNode>(26)
10+
var count: Int = 0
11+
var bestPrefixLength: Int = -1
12+
}
13+
14+
private var root: TrieNode? = null
15+
16+
fun longestCommonPrefix(words: Array<String>, k: Int): IntArray {
17+
val totalWords = words.size
18+
val result = IntArray(totalWords)
19+
if (totalWords - 1 < k) {
20+
return result
21+
}
22+
root = TrieNode()
23+
for (word in words) {
24+
// insert the word with increasing the count by 1 (prefix count)
25+
updateTrie(word, 1, k)
26+
}
27+
for (i in 0..<totalWords) {
28+
// temp deletion of the word with count decreased by 1
29+
updateTrie(words[i], -1, k)
30+
result[i] = root!!.bestPrefixLength
31+
// re-insertion of the word
32+
updateTrie(words[i], 1, k)
33+
}
34+
return result
35+
}
36+
37+
private fun updateTrie(word: String, count: Int, k: Int) {
38+
val wordLength = word.length
39+
// used to store the path used during trie travesal to update the count and use the count
40+
val nodePath: Array<TrieNode> = Array<TrieNode>(wordLength + 1) { TrieNode() }
41+
val depths = IntArray(wordLength + 1)
42+
nodePath[0] = root!!
43+
depths[0] = 0
44+
// trie insertion
45+
for (i in 0..<wordLength) {
46+
val letterIndex = word[i].code - 'a'.code
47+
if (nodePath[i].children[letterIndex] == null) {
48+
nodePath[i].children[letterIndex] = TrieNode()
49+
}
50+
nodePath[i + 1] = nodePath[i].children[letterIndex]!!
51+
depths[i + 1] = depths[i] + 1
52+
}
53+
// increase the count of each prefix
54+
for (node in nodePath) {
55+
node.count += count
56+
}
57+
// find the best prefix
58+
for (i in nodePath.indices.reversed()) {
59+
val currentNode = nodePath[i]
60+
var candidate = (if (currentNode.count >= k) depths[i] else -1)
61+
for (childNode in currentNode.children) {
62+
if (childNode != null) {
63+
candidate = max(candidate, childNode.bestPrefixLength)
64+
}
65+
}
66+
currentNode.bestPrefixLength = candidate
67+
}
68+
}
69+
}
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,65 @@
1+
package g3401_3500.s3486_longest_special_path_ii
2+
3+
// #Hard #Array #Hash_Table #Depth_First_Search #Tree #Prefix_Sum
4+
// #2025_03_16_Time_255_ms_(100.00%)_Space_125.42_MB_(100.00%)
5+
6+
@Suppress("kotlin:S107")
7+
class Solution {
8+
fun longestSpecialPath(edges: Array<IntArray>, nums: IntArray): IntArray {
9+
val ans = intArrayOf(0, 1)
10+
val graph: MutableMap<Int, MutableList<IntArray>> = HashMap<Int, MutableList<IntArray>>()
11+
for (edge in edges) {
12+
val a = edge[0]
13+
val b = edge[1]
14+
val c = edge[2]
15+
graph.computeIfAbsent(a) { _: Int -> ArrayList<IntArray>() }
16+
.add(intArrayOf(b, c))
17+
graph.computeIfAbsent(b) { _: Int -> ArrayList<IntArray>() }
18+
.add(intArrayOf(a, c))
19+
}
20+
val costs: MutableList<Int> = ArrayList<Int>()
21+
val last: MutableMap<Int, Int> = HashMap<Int, Int>()
22+
dfs(0, 0, -1, ArrayList<Int>(mutableListOf<Int>(0, 0)), nums, graph, costs, last, ans)
23+
return ans
24+
}
25+
26+
private fun dfs(
27+
node: Int,
28+
currCost: Int,
29+
prev: Int,
30+
left: MutableList<Int>,
31+
nums: IntArray,
32+
graph: MutableMap<Int, MutableList<IntArray>>,
33+
costs: MutableList<Int>,
34+
last: MutableMap<Int, Int>,
35+
ans: IntArray,
36+
) {
37+
val nodeColorIndexPrev: Int = last.getOrDefault(nums[node], -1)
38+
last.put(nums[node], costs.size)
39+
costs.add(currCost)
40+
val diff = currCost - costs[left[0]]
41+
val length = costs.size - left[0]
42+
if (diff > ans[0] || (diff == ans[0] && length < ans[1])) {
43+
ans[0] = diff
44+
ans[1] = length
45+
}
46+
for (next in graph.getOrDefault(node, ArrayList<IntArray>())) {
47+
val nextNode = next[0]
48+
val nextCost = next[1]
49+
if (nextNode == prev) {
50+
continue
51+
}
52+
val nextLeft: MutableList<Int> = ArrayList<Int>(left)
53+
if (last.containsKey(nums[nextNode])) {
54+
nextLeft.add(last[nums[nextNode]]!! + 1)
55+
}
56+
nextLeft.sortWith(Comparator.naturalOrder<Int?>())
57+
while (nextLeft.size > 2) {
58+
nextLeft.removeAt(0)
59+
}
60+
dfs(nextNode, currCost + nextCost, node, nextLeft, nums, graph, costs, last, ans)
61+
}
62+
last.put(nums[node], nodeColorIndexPrev)
63+
costs.removeAt(costs.size - 1)
64+
}
65+
}
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.

0 commit comments

Comments
 (0)