Skip to content

Commit ab77f7c

Browse files
authored
Added tasks 2715-2723
1 parent bae56ce commit ab77f7c

File tree

14 files changed

+536
-0
lines changed

14 files changed

+536
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
2715\. Timeout Cancellation
2+
3+
Easy
4+
5+
Given a function `fn`, an array of arguments `args`, and a timeout `t` in milliseconds, return a cancel function `cancelFn`.
6+
7+
After a delay of `t`, `fn` should be called with `args` passed as parameters **unless** `cancelFn` was invoked before the delay of `t` milliseconds elapses, specifically at `cancelT` ms. In that case, `fn` should never be called.
8+
9+
**Example 1:**
10+
11+
**Input:** fn = (x) => x \* 5, args = [2], t = 20, cancelT = 50
12+
13+
**Output:** [{"time": 20, "returned": 10}]
14+
15+
**Explanation:**
16+
17+
const cancel = cancellable((x) => x \* 5, [2], 20); // fn(2) called at t=20ms
18+
setTimeout(cancel, 50);
19+
20+
The cancellation was scheduled to occur after a delay of cancelT (50ms), which happened after the execution of fn(2) at 20ms.
21+
22+
**Example 2:**
23+
24+
**Input:** fn = (x) => x\*\*2, args = [2], t = 100, cancelT = 50
25+
26+
**Output:** []
27+
28+
**Explanation:**
29+
30+
const cancel = cancellable((x) => x\*\*2, [2], 100); // fn(2) not called
31+
setTimeout(cancel, 50);
32+
33+
The cancellation was scheduled to occur after a delay of cancelT (50ms), which happened before the execution of fn(2) at 100ms, resulting in fn(2) never being called.
34+
35+
**Example 3:**
36+
37+
**Input:** fn = (x1, x2) => x1 \* x2, args = [2,4], t = 30, cancelT = 100
38+
39+
**Output:** [{"time": 30, "returned": 8}]
40+
41+
**Explanation:**
42+
43+
const cancel = cancellable((x1, x2) => x1 \* x2, [2,4], 30); // fn(2,4) called at t=30ms
44+
setTimeout(cancel, 100);
45+
46+
The cancellation was scheduled to occur after a delay of cancelT (100ms), which happened after the execution of fn(2,4) at 30ms.
47+
48+
**Constraints:**
49+
50+
* `fn is a function`
51+
* `args is a valid JSON array`
52+
* `1 <= args.length <= 10`
53+
* `20 <= t <= 1000`
54+
* `10 <= cancelT <= 1000`
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// #Easy #2023_08_02_Time_64_ms_(91.95%)_Space_42.3_MB_(96.51%)
2+
3+
function cancellable(fn: Function, args: any[], t: number): Function {
4+
let cancelled: boolean = false;
5+
setTimeout(() => {
6+
if (!cancelled) {
7+
fn(...args)
8+
}
9+
}, t);
10+
return () => {
11+
cancelled = true
12+
}
13+
}
14+
15+
/*
16+
* const result = []
17+
*
18+
* const fn = (x) => x * 5
19+
* const args = [2], t = 20, cancelT = 50
20+
*
21+
* const start = performance.now()
22+
*
23+
* const log = (...argsArr) => {
24+
* const diff = Math.floor(performance.now() - start);
25+
* result.push({"time": diff, "returned": fn(...argsArr))
26+
* }
27+
*
28+
* const cancel = cancellable(log, args, t);
29+
*
30+
* const maxT = Math.max(t, cancelT)
31+
*
32+
* setTimeout(() => {
33+
* cancel()
34+
* }, cancelT)
35+
*
36+
* setTimeout(() => {
37+
* console.log(result) // [{"time":20,"returned":10}]
38+
* }, maxT + 15)
39+
*/
40+
41+
export { cancellable }
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package g2701_2800.s2719_count_of_integers
2+
3+
// #Hard #String #Dynamic_Programming #Math #2023_08_02_Time_208_ms_(100.00%)_Space_38_MB_(68.42%)
4+
5+
import java.util.Arrays
6+
7+
class Solution {
8+
private lateinit var dp: Array<Array<Array<IntArray>>>
9+
private fun countStrings(i: Int, tight1: Boolean, tight2: Boolean, sum: Int, num1: String, num2: String): Int {
10+
if (sum < 0) return 0
11+
if (i == num2.length) return 1
12+
if (dp[i][if (tight1) 1 else 0][if (tight2) 1 else 0][sum] != -1)
13+
return dp[i][if (tight1) 1 else 0][if (tight2) 1 else 0][sum]
14+
val lo = if (tight1) num1[i].code - '0'.code else 0
15+
val hi = if (tight2) num2[i].code - '0'.code else 9
16+
var count = 0
17+
for (idx in lo..hi) {
18+
count = (
19+
count % MOD + countStrings(
20+
i + 1,
21+
tight1 and (idx == lo), tight2 and (idx == hi),
22+
sum - idx, num1, num2
23+
) % MOD
24+
) % MOD
25+
}
26+
return count.also { dp[i][if (tight1) 1 else 0][if (tight2) 1 else 0][sum] = it }
27+
}
28+
29+
fun count(num1: String, num2: String, minSum: Int, maxSum: Int): Int {
30+
val maxLength = num2.length
31+
val minLength = num1.length
32+
val leadingZeroes = maxLength - minLength
33+
val num1extended: String = "0".repeat(leadingZeroes) + num1
34+
dp = Array(maxLength) {
35+
Array(2) {
36+
Array(2) {
37+
IntArray(401)
38+
}
39+
}
40+
}
41+
for (dim1 in dp) {
42+
for (dim2 in dim1) {
43+
for (dim3 in dim2) {
44+
Arrays.fill(dim3, -1)
45+
}
46+
}
47+
}
48+
val total = countStrings(0, true, true, maxSum, num1extended, num2)
49+
val unnecessary = countStrings(0, true, true, minSum - 1, num1extended, num2)
50+
var ans = (total - unnecessary) % MOD
51+
if (ans < 0) {
52+
ans += MOD
53+
}
54+
return ans
55+
}
56+
57+
companion object {
58+
private const val MOD = 1e9.toInt() + 7
59+
}
60+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
2719\. Count of Integers
2+
3+
Hard
4+
5+
You are given two numeric strings `num1` and `num2` and two integers `max_sum` and `min_sum`. We denote an integer `x` to be _good_ if:
6+
7+
* `num1 <= x <= num2`
8+
* `min_sum <= digit_sum(x) <= max_sum`.
9+
10+
Return _the number of good integers_. Since the answer may be large, return it modulo <code>10<sup>9</sup> + 7</code>.
11+
12+
Note that `digit_sum(x)` denotes the sum of the digits of `x`.
13+
14+
**Example 1:**
15+
16+
**Input:** num1 = "1", num2 = "12", `min_sum` = 1, max\_sum = 8
17+
18+
**Output:** 11
19+
20+
**Explanation:** There are 11 integers whose sum of digits lies between 1 and 8 are 1,2,3,4,5,6,7,8,10,11, and 12. Thus, we return 11.
21+
22+
**Example 2:**
23+
24+
**Input:** num1 = "1", num2 = "5", `min_sum` = 1, max\_sum = 5
25+
26+
**Output:** 5
27+
28+
**Explanation:** The 5 integers whose sum of digits lies between 1 and 5 are 1,2,3,4, and 5. Thus, we return 5.
29+
30+
**Constraints:**
31+
32+
* <code>1 <= num1 <= num2 <= 10<sup>22</sup></code>
33+
* `1 <= min_sum <= max_sum <= 400`
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
2721\. Execute Asynchronous Functions in Parallel
2+
3+
Medium
4+
5+
Given an array of asynchronous functions `functions`, return a new promise `promise`. Each function in the array accepts no arguments and returns a promise.
6+
7+
`promise` resolves:
8+
9+
* When all the promises returned from `functions` were resolved successfully. The resolved value of `promise` should be an array of all the resolved values of promises in the same order as they were in the `functions`.
10+
11+
`promise` rejects:
12+
13+
* When any of the promises returned from `functions` were rejected. `promise` should also reject with the reason of the first rejection.
14+
15+
Please solve it without using the built-in `Promise.all` function.
16+
17+
**Example 1:**
18+
19+
**Input:**
20+
21+
functions = [
22+
() => new Promise(resolve => setTimeout(() => resolve(5), 200))
23+
]
24+
25+
**Output:** {"t": 200, "resolved": [5]}
26+
27+
**Explanation:** promiseAll(functions).then(console.log); // [5] The single function was resolved at 200ms with a value of 5.
28+
29+
**Example 2:**
30+
31+
**Input:**
32+
33+
functions = [
34+
() => new Promise(resolve => setTimeout(() => resolve(1), 200)),
35+
() => new Promise((resolve, reject) => setTimeout(() => reject("Error"), 100))
36+
]
37+
38+
**Output:** {"t": 100, "rejected": "Error"}
39+
40+
**Explanation:** Since one of the promises rejected, the returned promise also rejected with the same error at the same time.
41+
42+
**Example 3:**
43+
44+
**Input:**
45+
46+
functions = [
47+
() => new Promise(resolve => setTimeout(() => resolve(4), 50)),
48+
() => new Promise(resolve => setTimeout(() => resolve(10), 150)),
49+
() => new Promise(resolve => setTimeout(() => resolve(16), 100))
50+
]
51+
52+
**Output:** {"t": 150, "resolved": [4, 10, 16]}
53+
54+
**Explanation:** All the promises resolved with a value. The returned promise resolved when the last promise resolved.
55+
56+
**Constraints:**
57+
58+
* `functions is an array of functions that returns promises`
59+
* `1 <= functions.length <= 10`
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// #Medium #2023_08_02_Time_63_ms_(99.09%)_Space_43_MB_(82.94%)
2+
3+
async function promiseAll<T>(functions: (() => Promise<T>)[]): Promise<T[]> {
4+
const resolved = []
5+
let counter = 0
6+
7+
return new Promise((resolve, reject) => {
8+
for (let i = 0; i < functions.length; i++) {
9+
functions[i]().then((res) => {
10+
// must specify index of array
11+
resolved[i] = res
12+
counter++
13+
if (counter === functions.length) {
14+
resolve(resolved)
15+
}
16+
}).catch((err) => {
17+
reject(err)
18+
})
19+
}
20+
})
21+
}
22+
23+
/*
24+
* const promise = promiseAll([() => new Promise(res => res(42))])
25+
* promise.then(console.log); // [42]
26+
*/
27+
28+
export { promiseAll }
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
2722\. Join Two Arrays by ID
2+
3+
Medium
4+
5+
Given two arrays `arr1` and `arr2`, return a new array `joinedArray`. All the objects in each of the two inputs arrays will contain an `id` field that has an integer value. `joinedArray` is an array formed by merging `arr1` and `arr2` based on their `id` key. The length of `joinedArray` should be the length of unique values of `id`. The returned array should be sorted in **ascending** order based on the `id` key.
6+
7+
If a given `id` exists in one array but not the other, the single object with that `id` should be included in the result array without modification.
8+
9+
If two objects share an `id`, their properties should be merged into a single object:
10+
11+
* If a key only exists in one object, that single key-value pair should be included in the object.
12+
* If a key is included in both objects, the value in the object from `arr2` should override the value from `arr1`.
13+
14+
**Example 1:**
15+
16+
**Input:**
17+
18+
arr1 = [
19+
{"id": 1, "x": 1},
20+
{"id": 2, "x": 9}
21+
],
22+
arr2 = [
23+
{"id": 3, "x": 5}
24+
]
25+
26+
**Output:**
27+
28+
[
29+
{"id": 1, "x": 1},
30+
{"id": 2, "x": 9},
31+
{"id": 3, "x": 5}
32+
]
33+
34+
**Explanation:** There are no duplicate ids so arr1 is simply concatenated with arr2.
35+
36+
**Example 2:**
37+
38+
**Input:**
39+
40+
arr1 = [
41+
{"id": 1, "x": 2, "y": 3},
42+
{"id": 2, "x": 3, "y": 6}
43+
],
44+
arr2 = [
45+
{"id": 2, "x": 10, "y": 20},
46+
{"id": 3, "x": 0, "y": 0}
47+
]
48+
49+
**Output:**
50+
51+
[
52+
{"id": 1, "x": 2, "y": 3},
53+
{"id": 2, "x": 10, "y": 20},
54+
{"id": 3, "x": 0, "y": 0}
55+
]
56+
57+
**Explanation:** The two objects with id=1 and id=3 are included in the result array without modifiction. The two objects with id=2 are merged together. The keys from arr2 override the values in arr1.
58+
59+
**Example 3:**
60+
61+
**Input:**
62+
63+
arr1 = [
64+
{"id": 1, "b": {"b": 94},"v": [4, 3], "y": 48}
65+
]
66+
arr2 = [
67+
{"id": 1, "b": {"c": 84}, "v": [1, 3]}
68+
]
69+
70+
**Output:**
71+
72+
[
73+
{"id": 1, "b": {"c": 84}, "v": [1, 3], "y": 48}
74+
]
75+
76+
**Explanation:** The two objects with id=1 are merged together. For the keys "b" and "v" the values from arr2 are used. Since the key "y" only exists in arr1, that value is taken form arr1.
77+
78+
**Constraints:**
79+
80+
* `arr1 and arr2 are valid JSON arrays`
81+
* `Each object in arr1 and arr2 has a unique integer id key`
82+
* <code>2 <= JSON.stringify(arr1).length <= 10<sup>6</sup></code>
83+
* <code>2 <= JSON.stringify(arr2).length <= 10<sup>6</sup></code>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// #Medium #2023_08_02_Time_280_ms_(98.29%)_Space_99.7_MB_(97.43%)
2+
3+
function join(arr1: any[], arr2: any[]): any[] {
4+
const result: any = {}
5+
for(let obj of arr1) {
6+
result[obj.id] = obj
7+
}
8+
for(let obj of arr2) {
9+
if(result[obj.id]) {
10+
for(let key in obj) {
11+
result[obj.id][key] = obj[key]
12+
}
13+
} else {
14+
result[obj.id] = obj
15+
}
16+
}
17+
return Object.values(result)
18+
}
19+
20+
export { join }

0 commit comments

Comments
 (0)