Skip to content

Commit 8e41555

Browse files
authored
Added tasks 2694-2698
1 parent 31a99ff commit 8e41555

File tree

15 files changed

+506
-0
lines changed

15 files changed

+506
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
2694\. Event Emitter
2+
3+
Medium
4+
5+
Design an `EventEmitter` class. This interface is similar (but with some differences) to the one found in Node.js or the Event Target interface of the DOM. The `EventEmitter` should allow for subscribing to events and emitting them.
6+
7+
Your `EventEmitter` class should have the following two methods:
8+
9+
* **subscribe** - This method takes in two arguments: the name of an event as a string and a callback function. This callback function will later be called when the event is emitted.
10+
An event should be able to have multiple listeners for the same event. When emitting an event with multiple callbacks, each should be called in the order in which they were subscribed. An array of results should be returned. You can assume no callbacks passed to `subscribe` are referentially identical.
11+
The `subscribe` method should also return an object with an `unsubscribe` method that enables the user to unsubscribe. When it is called, the callback should be removed from the list of subscriptions and `undefined` should be returned.
12+
* **emit** - This method takes in two arguments: the name of an event as a string and an optional array of arguments that will be passed to the callback(s). If there are no callbacks subscribed to the given event, return an empty array. Otherwise, return an array of the results of all callback calls in the order they were subscribed.
13+
14+
**Example 1:**
15+
16+
**Input:** actions = ["EventEmitter", "emit", "subscribe", "subscribe", "emit"], values = [[], ["firstEvent", "function cb1() { return 5; }"], ["firstEvent", "function cb1() { return 6; }"], ["firstEvent"]]
17+
18+
**Output:** [[],["emitted",[]],["subscribed"],["subscribed"],["emitted",[5,6]]]
19+
20+
**Explanation:**
21+
22+
const emitter = new EventEmitter();
23+
emitter.emit("firstEvent"); // [], no callback are subscribed yet
24+
emitter.subscribe("firstEvent", function cb1() { return 5; });
25+
emitter.subscribe("firstEvent", function cb2() { return 6; });
26+
emitter.emit("firstEvent"); // [5, 6], returns the output of cb1 and cb2
27+
28+
**Example 2:**
29+
30+
**Input:** actions = ["EventEmitter", "subscribe", "emit", "emit"], values = [[], ["firstEvent", "function cb1(...args) { return args.join(','); }"], ["firstEvent", [1,2,3]], ["firstEvent", [3,4,6]]]
31+
32+
**Output:** [[],["subscribed"],["emitted",["1,2,3"]],["emitted",["3,4,6"]]]
33+
34+
**Explanation:** Note that the emit method should be able to accept an OPTIONAL array of arguments.
35+
36+
const emitter = new EventEmitter();
37+
emitter.subscribe("firstEvent, function cb1(...args) { return args.join(','); });
38+
emitter.emit("firstEvent", [1, 2, 3]); // ["1,2,3"]
39+
emitter.emit("firstEvent", [3, 4, 6]); // ["3,4,6"]
40+
41+
**Example 3:**
42+
43+
**Input:** actions = ["EventEmitter", "subscribe", "emit", "unsubscribe", "emit"], values = [[], ["firstEvent", "(...args) => args.join(',')"], ["firstEvent", [1,2,3]], [0], ["firstEvent", [4,5,6]]]
44+
45+
**Output:** [[],["subscribed"],["emitted",["1,2,3"]],["unsubscribed",0],["emitted",[]]]
46+
47+
**Explanation:**
48+
49+
const emitter = new EventEmitter();
50+
const sub = emitter.subscribe("firstEvent", (...args) => args.join(','));
51+
emitter.emit("firstEvent", [1, 2, 3]); // ["1,2,3"] sub.unsubscribe(); // undefined
52+
emitter.emit("firstEvent", [4, 5, 6]); // [], there are no subscriptions
53+
54+
**Example 4:**
55+
56+
**Input:** actions = ["EventEmitter", "subscribe", "subscribe", "unsubscribe", "emit"], values = [[], ["firstEvent", "x => x + 1"], ["firstEvent", "x => x + 2"], [0], ["firstEvent", [5]]]
57+
58+
**Output:** [[],["subscribed"],["emitted",["1,2,3"]],["unsubscribed",0],["emitted",[7]]]
59+
60+
**Explanation:**
61+
62+
const emitter = new EventEmitter();
63+
const sub1 = emitter.subscribe("firstEvent", x => x + 1);
64+
const sub2 = emitter.subscribe("firstEvent", x => x + 2);
65+
sub1.unsubscribe(); // undefined
66+
emitter.emit("firstEvent", [5]); // [7]
67+
68+
**Constraints:**
69+
70+
* `1 <= actions.length <= 10`
71+
* `values.length === actions.length`
72+
* All test cases are valid, e.g. you don't need to handle scenarios when unsubscribing from a non-existing subscription.
73+
* There are only 4 different actions: `EventEmitter`, `emit`, `subscribe`, and `unsubscribe`.
74+
* The `EventEmitter` action doesn't take any arguments.
75+
* The `emit` action takes between either 1 or 2 arguments. The first argument is the name of the event we want to emit, and the 2nd argument is passed to the callback functions.
76+
* The `subscribe` action takes 2 arguments, where the first one is the event name and the second is the callback function.
77+
* The `unsubscribe` action takes one argument, which is the 0-indexed order of the subscription made before.
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// #Medium #2023_07_29_Time_45_ms_(99.58%)_Space_44.6_MB_(72.08%)
2+
3+
type Callback = (...args: any[]) => any;
4+
type Subscription = {
5+
unsubscribe: () => void
6+
}
7+
8+
class EventEmitter {
9+
subs: Record<string, Callback[]> = {}
10+
11+
subscribe(eventName: string, callback: Callback): Subscription {
12+
if (!this.subs[eventName])
13+
this.subs[eventName] = []
14+
const idx = this.subs[eventName].push(callback) - 1
15+
return {
16+
unsubscribe: () => this.subs[eventName].splice(idx, 1)
17+
}
18+
}
19+
20+
emit(eventName: string, args: any[] = []): any[] {
21+
return this.subs[eventName]?.map(callback => callback(...args)) || []
22+
}
23+
}
24+
25+
/*
26+
* const emitter = new EventEmitter();
27+
*
28+
* // Subscribe to the onClick event with onClickCallback
29+
* function onClickCallback() { return 99 }
30+
* const sub = emitter.subscribe('onClick', onClickCallback);
31+
*
32+
* emitter.emit('onClick'); // [99]
33+
* sub.unsubscribe(); // undefined
34+
* emitter.emit('onClick'); // []
35+
*/
36+
37+
export { EventEmitter }
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
2695\. Array Wrapper
2+
3+
Easy
4+
5+
Create a class `ArrayWrapper` that accepts an array of integers in its constructor. This class should have two features:
6+
7+
* When two instances of this class are added together with the `+` operator, the resulting value is the sum of all the elements in both arrays.
8+
* When the `String()` function is called on the instance, it will return a comma separated string surrounded by brackets. For example, `[1,2,3]`.
9+
10+
**Example 1:**
11+
12+
**Input:** nums = [[1,2],[3,4]], operation = "Add"
13+
14+
**Output:** 10
15+
16+
**Explanation:**
17+
18+
const obj1 = new ArrayWrapper([1,2]);
19+
const obj2 = new ArrayWrapper([3,4]);
20+
obj1 + obj2; // 10
21+
22+
**Example 2:**
23+
24+
**Input:** nums = [[23,98,42,70]], operation = "String"
25+
26+
**Output:** "[23,98,42,70]"
27+
28+
**Explanation:**
29+
30+
const obj = new ArrayWrapper([23,98,42,70]);
31+
String(obj); // "[23,98,42,70]"
32+
33+
**Example 3:**
34+
35+
**Input:** nums = [[],[]], operation = "Add"
36+
37+
**Output:** 0
38+
39+
**Explanation:**
40+
41+
const obj1 = new ArrayWrapper([]);
42+
const obj2 = new ArrayWrapper([]);
43+
obj1 + obj2; // 0
44+
45+
**Constraints:**
46+
47+
* `0 <= nums.length <= 1000`
48+
* `0 <= nums[i] <= 1000`
49+
* `Note: nums is the array passed to the constructor`
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// #Easy #2023_07_29_Time_40_ms_(100.00%)_Space_45_MB_(48.83%)
2+
3+
class ArrayWrapper {
4+
nums: number[];
5+
constructor(nums: number[]) {
6+
this.nums = nums;
7+
}
8+
9+
valueOf() {
10+
return this.nums.reduce((n, a) => n + a, 0);
11+
}
12+
13+
toString() {
14+
return '[' + this.nums.join(',') + ']'
15+
}
16+
};
17+
18+
/*
19+
* const obj1 = new ArrayWrapper([1,2]);
20+
* const obj2 = new ArrayWrapper([3,4]);
21+
* obj1 + obj2; // 10
22+
* String(obj1); // "[1,2]"
23+
* String(obj2); // "[3,4]"
24+
*/
25+
26+
export { ArrayWrapper }
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package g2601_2700.s2696_minimum_string_length_after_removing_substrings
2+
3+
// #Easy #String #Stack #Simulation #2023_07_29_Time_185_ms_(100.00%)_Space_37_MB_(76.00%)
4+
5+
class Solution {
6+
fun minLength(s: String): Int {
7+
val stack = ArrayDeque<Char>()
8+
s.forEach { c ->
9+
if (stack.isNotEmpty() &&
10+
(
11+
(c == 'B' && stack.last() == 'A') ||
12+
(c == 'D' && stack.last() == 'C')
13+
)
14+
) {
15+
stack.removeLast()
16+
} else {
17+
stack.addLast(c)
18+
}
19+
}
20+
return stack.size
21+
}
22+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
2696\. Minimum String Length After Removing Substrings
2+
3+
Easy
4+
5+
You are given a string `s` consisting only of **uppercase** English letters.
6+
7+
You can apply some operations to this string where, in one operation, you can remove **any** occurrence of one of the substrings `"AB"` or `"CD"` from `s`.
8+
9+
Return _the **minimum** possible length of the resulting string that you can obtain_.
10+
11+
**Note** that the string concatenates after removing the substring and could produce new `"AB"` or `"CD"` substrings.
12+
13+
**Example 1:**
14+
15+
**Input:** s = "ABFCACDB"
16+
17+
**Output:** 2
18+
19+
**Explanation:** We can do the following operations:
20+
- Remove the substring "<ins>AB</ins>FCACDB", so s = "FCACDB".
21+
- Remove the substring "FCA<ins>CD</ins>B", so s = "FCAB".
22+
- Remove the substring "FC<ins>AB</ins>", so s = "FC".
23+
24+
So the resulting length of the string is 2.
25+
26+
It can be shown that it is the minimum length that we can obtain.
27+
28+
**Example 2:**
29+
30+
**Input:** s = "ACBBD"
31+
32+
**Output:** 5
33+
34+
**Explanation:** We cannot do any operations on the string so the length remains the same.
35+
36+
**Constraints:**
37+
38+
* `1 <= s.length <= 100`
39+
* `s` consists only of uppercase English letters.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package g2601_2700.s2697_lexicographically_smallest_palindrome
2+
3+
// #Easy #String #Two_Pointers #2023_07_29_Time_267_ms_(100.00%)_Space_37.7_MB_(77.78%)
4+
5+
class Solution {
6+
fun makeSmallestPalindrome(s: String): String {
7+
var l = 0
8+
var r = s.lastIndex
9+
val res = s.toCharArray()
10+
while (l <= r) {
11+
if (s[l] < s[r])
12+
res[r] = s[l]
13+
else
14+
res[l] = s[r]
15+
l++
16+
r--
17+
}
18+
return String(res)
19+
}
20+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
2697\. Lexicographically Smallest Palindrome
2+
3+
Easy
4+
5+
You are given a string `s` consisting of **lowercase English letters**, and you are allowed to perform operations on it. In one operation, you can **replace** a character in `s` with another lowercase English letter.
6+
7+
Your task is to make `s` a **palindrome** with the **minimum** **number** **of operations** possible. If there are **multiple palindromes** that can be made using the **minimum** number of operations, make the **lexicographically smallest** one.
8+
9+
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`.
10+
11+
Return _the resulting palindrome string._
12+
13+
**Example 1:**
14+
15+
**Input:** s = "egcfe"
16+
17+
**Output:** "efcfe"
18+
19+
**Explanation:** The minimum number of operations to make "egcfe" a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is "efcfe", by changing 'g'.
20+
21+
**Example 2:**
22+
23+
**Input:** s = "abcd"
24+
25+
**Output:** "abba"
26+
27+
**Explanation:** The minimum number of operations to make "abcd" a palindrome is 2, and the lexicographically smallest palindrome string we can get by modifying two characters is "abba".
28+
29+
**Example 3:**
30+
31+
**Input:** s = "seven"
32+
33+
**Output:** "neven"
34+
35+
**Explanation:** The minimum number of operations to make "seven" a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is "neven".
36+
37+
**Constraints:**
38+
39+
* `1 <= s.length <= 1000`
40+
* `s` consists of only lowercase English letters**.**
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package g2601_2700.s2698_find_the_punishment_number_of_an_integer
2+
3+
// #Medium #Math #Backtracking #2023_07_29_Time_133_ms_(100.00%)_Space_33.1_MB_(100.00%)
4+
5+
class Solution {
6+
fun punishmentNumber(n: Int): Int {
7+
fun partition(x: Int, target: Int): Boolean {
8+
if (x == target) return true
9+
if (target < 0 || x < target) return false
10+
return partition(x / 10, target - (x % 10)) ||
11+
partition(x / 100, target - (x % 100)) ||
12+
partition(x / 1000, target - (x % 1000))
13+
}
14+
var res = 0
15+
for (i in 1..n) {
16+
val iSq = i * i
17+
if (partition(iSq, i))
18+
res += iSq
19+
}
20+
return res
21+
}
22+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2698\. Find the Punishment Number of an Integer
2+
3+
Medium
4+
5+
Given a positive integer `n`, return _the **punishment number**_ of `n`.
6+
7+
The **punishment number** of `n` is defined as the sum of the squares of all integers `i` such that:
8+
9+
* `1 <= i <= n`
10+
* The decimal representation of `i * i` can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals `i`.
11+
12+
**Example 1:**
13+
14+
**Input:** n = 10
15+
16+
**Output:** 182
17+
18+
**Explanation:** There are exactly 3 integers i that satisfy the conditions in the statement:
19+
- 1 since 1 \* 1 = 1
20+
- 9 since 9 \* 9 = 81 and 81 can be partitioned into 8 + 1.
21+
- 10 since 10 \* 10 = 100 and 100 can be partitioned into 10 + 0.
22+
23+
Hence, the punishment number of 10 is 1 + 81 + 100 = 182
24+
25+
**Example 2:**
26+
27+
**Input:** n = 37
28+
29+
**Output:** 1478
30+
31+
**Explanation:** There are exactly 4 integers i that satisfy the conditions in the statement:
32+
- 1 since 1 \* 1 = 1.
33+
- 9 since 9 \* 9 = 81 and 81 can be partitioned into 8 + 1.
34+
- 10 since 10 \* 10 = 100 and 100 can be partitioned into 10 + 0.
35+
- 36 since 36 \* 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6.
36+
37+
Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478
38+
39+
**Constraints:**
40+
41+
* `1 <= n <= 1000`

0 commit comments

Comments
 (0)