Skip to content

Commit eb660a9

Browse files
authored
Added tasks 2699-2706
1 parent 8e41555 commit eb660a9

File tree

15 files changed

+481
-0
lines changed

15 files changed

+481
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package g2601_2700.s2699_modify_graph_edge_weights
2+
3+
// #Hard #Heap_Priority_Queue #Graph #Shortest_Path
4+
// #2023_07_29_Time_1592_ms_(40.00%)_Space_65.3_MB_(60.00%)
5+
6+
import java.util.PriorityQueue
7+
8+
class Solution {
9+
private inner class Edge(var s: Int, var d: Int, var wt: Int)
10+
private lateinit var g: Array<ArrayList<Edge>?>
11+
private var n = 0
12+
private var t = 0
13+
fun modifiedGraphEdges(
14+
n: Int,
15+
edges: Array<IntArray>,
16+
source: Int,
17+
destination: Int,
18+
target: Int
19+
): Array<IntArray> {
20+
this.n = n
21+
g = arrayOfNulls(n)
22+
t = target
23+
for (i in 0 until n) {
24+
g[i] = ArrayList()
25+
}
26+
for (e in edges) {
27+
val s = e[0]
28+
val d = e[1]
29+
val wt = e[2]
30+
if (wt == -1) continue
31+
g[s]!!.add(Edge(s, d, wt))
32+
g[d]!!.add(Edge(d, s, wt))
33+
}
34+
val inc = shortestPath(source, destination)
35+
if (inc != -1 && inc < target) return Array(0) { IntArray(0) }
36+
if (inc == target) {
37+
ntomax(edges)
38+
return edges
39+
}
40+
for (e in edges) {
41+
if (e[2] == -1) {
42+
e[2] = 1
43+
val s = e[0]
44+
val d = e[1]
45+
val wt = e[2]
46+
g[s]!!.add(Edge(s, d, wt))
47+
g[d]!!.add(Edge(d, s, wt))
48+
val cost = shortestPath(source, destination)
49+
if (cost == -1) continue
50+
if (cost < target) {
51+
e[2] = target - cost + 1
52+
ntomax(edges)
53+
return edges
54+
}
55+
if (cost == target) {
56+
ntomax(edges)
57+
return edges
58+
}
59+
}
60+
}
61+
return Array(0) { IntArray(0) }
62+
}
63+
64+
private fun ntomax(edges: Array<IntArray>) {
65+
for (e in edges) {
66+
if (e[2] == -1) {
67+
e[2] = 1000000000
68+
}
69+
}
70+
}
71+
72+
private inner class Pair(var s: Int, var cost: Int) : Comparable<Pair?> {
73+
override operator fun compareTo(other: Pair?): Int {
74+
return cost - other!!.cost
75+
}
76+
}
77+
78+
private fun shortestPath(s: Int, d: Int): Int {
79+
val q = PriorityQueue<Pair>()
80+
q.add(Pair(s, 0))
81+
val vis = BooleanArray(n)
82+
while (q.isNotEmpty()) {
83+
val rem = q.remove()
84+
vis[rem.s] = true
85+
if (rem.s == d) return rem.cost
86+
for (e in g[rem.s]!!) {
87+
if (!vis[e.d]) {
88+
q.add(Pair(e.d, rem.cost + e.wt))
89+
}
90+
}
91+
}
92+
return -1
93+
}
94+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
2699\. Modify Graph Edge Weights
2+
3+
Hard
4+
5+
You are given an **undirected weighted** **connected** graph containing `n` nodes labeled from `0` to `n - 1`, and an integer array `edges` where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> with weight <code>w<sub>i</sub></code>.
6+
7+
Some edges have a weight of `-1` (<code>w<sub>i</sub> = -1</code>), while others have a **positive** weight (<code>w<sub>i</sub> > 0</code>).
8+
9+
Your task is to modify **all edges** with a weight of `-1` by assigning them **positive integer values** in the range <code>[1, 2 * 10<sup>9</sup>]</code> so that the **shortest distance** between the nodes `source` and `destination` becomes equal to an integer `target`. If there are **multiple** **modifications** that make the shortest distance between `source` and `destination` equal to `target`, any of them will be considered correct.
10+
11+
Return _an array containing all edges (even unmodified ones) in any order if it is possible to make the shortest distance from_ `source` _to_ `destination` _equal to_ `target`_, or an **empty array** if it's impossible._
12+
13+
**Note:** You are not allowed to modify the weights of edges with initial positive weights.
14+
15+
**Example 1:**
16+
17+
**![](https://assets.leetcode.com/uploads/2023/04/18/graph.png)**
18+
19+
**Input:** n = 5, edges = [[4,1,-1],[2,0,-1],[0,3,-1],[4,3,-1]], source = 0, destination = 1, target = 5
20+
21+
**Output:** [[4,1,1],[2,0,1],[0,3,3],[4,3,1]]
22+
23+
**Explanation:** The graph above shows a possible modification to the edges, making the distance from 0 to 1 equal to 5.
24+
25+
**Example 2:**
26+
27+
**![](https://assets.leetcode.com/uploads/2023/04/18/graph-2.png)**
28+
29+
**Input:** n = 3, edges = [[0,1,-1],[0,2,5]], source = 0, destination = 2, target = 6
30+
31+
**Output:** []
32+
33+
**Explanation:** The graph above contains the initial edges. It is not possible to make the distance from 0 to 2 equal to 6 by modifying the edge with weight -1. So, an empty array is returned.
34+
35+
**Example 3:**
36+
37+
**![](https://assets.leetcode.com/uploads/2023/04/19/graph-3.png)**
38+
39+
**Input:** n = 4, edges = [[1,0,4],[1,2,3],[2,3,5],[0,3,-1]], source = 0, destination = 2, target = 6
40+
41+
**Output:** [[1,0,4],[1,2,3],[2,3,5],[0,3,1]]
42+
43+
**Explanation:** The graph above shows a modified graph having the shortest distance from 0 to 2 as 6.
44+
45+
**Constraints:**
46+
47+
* `1 <= n <= 100`
48+
* `1 <= edges.length <= n * (n - 1) / 2`
49+
* `edges[i].length == 3`
50+
* <code>0 <= a<sub>i</sub>, b<sub>i </sub>< n</code>
51+
* <code>w<sub>i</sub> = -1 </code>or <code>1 <= w<sub>i </sub><= 10<sup>7</sup></code>
52+
* <code>a<sub>i </sub>!= b<sub>i</sub></code>
53+
* `0 <= source, destination < n`
54+
* `source != destination`
55+
* <code>1 <= target <= 10<sup>9</sup></code>
56+
* The graph is connected, and there are no self-loops or repeated edges
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
2703\. Return Length of Arguments Passed
2+
3+
Easy
4+
5+
Write a function `argumentsLength` that returns the count of arguments passed to it.
6+
7+
**Example 1:**
8+
9+
**Input:** argsArr = [5]
10+
11+
**Output:** 1
12+
13+
**Explanation:** argumentsLength(5); // 1 One value was passed to the function so it should return 1.
14+
15+
**Example 2:**
16+
17+
**Input:** argsArr = [{}, null, "3"]
18+
19+
**Output:** 3
20+
21+
**Explanation:** argumentsLength({}, null, "3"); // 3 Three values were passed to the function so it should return 3.
22+
23+
**Constraints:**
24+
25+
* `argsArr is a valid JSON array`
26+
* `0 <= argsArr.length <= 100`
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// #Easy #2023_07_29_Time_47_ms_(98.59%)_Space_41.5_MB_(100.00%)
2+
3+
function argumentsLength(...args: any[]): number {
4+
let result = 0
5+
for (let value of args) { // NOSONAR
6+
result += 1
7+
}
8+
return result
9+
}
10+
11+
/*
12+
* argumentsLength(1, 2, 3); // 3
13+
*/
14+
15+
export { argumentsLength }
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2704\. To Be Or Not To Be
2+
3+
Easy
4+
5+
Write a function `expect` that helps developers test their code. It should take in any value `val` and return an object with the following two functions.
6+
7+
* `toBe(val)` accepts another value and returns `true` if the two values `===` each other. If they are not equal, it should throw an error `"Not Equal"`.
8+
* `notToBe(val)` accepts another value and returns `true` if the two values `!==` each other. If they are equal, it should throw an error `"Equal"`.
9+
10+
**Example 1:**
11+
12+
**Input:** func = () => expect(5).toBe(5)
13+
14+
**Output:** {"value": true}
15+
16+
**Explanation:** 5 === 5 so this expression returns true.
17+
18+
**Example 2:**
19+
20+
**Input:** func = () => expect(5).toBe(null)
21+
22+
**Output:** {"error": "Not Equal"}
23+
24+
**Explanation:** 5 !== null so this expression throw the error "Not Equal".
25+
26+
**Example 3:**
27+
28+
**Input:** func = () => expect(5).notToBe(null)
29+
30+
**Output:** {"value": true}
31+
32+
**Explanation:** 5 !== null so this expression returns true.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// #Easy #2023_07_29_Time_49_ms_(97.88%)_Space_42.3_MB_(89.10%)
2+
3+
type ToBeOrNotToBe = {
4+
toBe: (val: any) => boolean
5+
notToBe: (val: any) => boolean
6+
};
7+
8+
const expect = (val: any): ToBeOrNotToBe => ({
9+
toBe: (equality: any) => {
10+
if (val !== equality) {
11+
throw new Error("Not Equal")
12+
}
13+
return true
14+
},
15+
notToBe: (equality: any) => {
16+
if (val === equality) {
17+
throw new Error("Equal")
18+
}
19+
return true
20+
},
21+
})
22+
23+
/*
24+
* expect(5).toBe(5); // true
25+
* expect(5).notToBe(5); // throws "Equal"
26+
*/
27+
28+
export { expect }
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
2705\. Compact Object
2+
3+
Medium
4+
5+
Given an object or array `obj`, return a **compact object**. A **compact object** is the same as the original object, except with keys containing **falsy** values removed. This operation applies to the object and any nested objects. Arrays are considered objects where the indices are keys. A value is considered **falsy** when `Boolean(value)` returns `false`.
6+
7+
You may assume the `obj` is the output of `JSON.parse`. In other words, it is valid JSON.
8+
9+
**Example 1:**
10+
11+
**Input:** obj = [null, 0, false, 1]
12+
13+
**Output:** [1]
14+
15+
**Explanation:** All falsy values have been removed from the array.
16+
17+
**Example 2:**
18+
19+
**Input:** obj = {"a": null, "b": [false, 1]}
20+
21+
**Output:** {"b": [1]}
22+
23+
**Explanation:** obj["a"] and obj["b"][0] had falsy values and were removed.
24+
25+
**Example 3:**
26+
27+
**Input:** obj = [null, 0, 5, [0], [false, 16]]
28+
29+
**Output:** [5, [], [16]]
30+
31+
**Explanation:** obj[0], obj[1], obj[3][0], and obj[4][0] were falsy and removed.
32+
33+
**Constraints:**
34+
35+
* `obj is a valid JSON object`
36+
* <code>2 <= JSON.stringify(obj).length <= 10<sup>6</sup></code>
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// #Medium #2023_07_29_Time_78_ms_(99.38%)_Space_53.4_MB_(71.88%)
2+
3+
type Obj = Record<any, any>
4+
5+
function compactObject(obj: Obj): Obj {
6+
if (Array.isArray(obj)) {
7+
let retArr = []
8+
obj.forEach((e, idx) => {
9+
if (e) {
10+
retArr.push(compactObject(e))
11+
}
12+
})
13+
return retArr
14+
} else if (obj !== null && typeof obj === 'object') {
15+
let retObj = {}
16+
for(const key of Object.keys(obj)) {
17+
if(obj[key]) {
18+
retObj[key] = compactObject(obj[key])
19+
}
20+
}
21+
return retObj
22+
}
23+
return obj
24+
}
25+
26+
export { compactObject }
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package g2701_2800.s2706_buy_two_chocolates
2+
3+
// #Easy #Array #Sorting #2023_07_29_Time_187_ms_(96.43%)_Space_39.9_MB_(46.43%)
4+
5+
class Solution {
6+
fun buyChoco(prices: IntArray, money: Int): Int {
7+
var minPrice1 = Int.MAX_VALUE
8+
var minPrice2 = Int.MAX_VALUE
9+
for (price in prices) {
10+
if (price < minPrice1) {
11+
minPrice2 = minPrice1
12+
minPrice1 = price
13+
} else if (price < minPrice2) {
14+
minPrice2 = price
15+
}
16+
}
17+
val totalPrice = minPrice1 + minPrice2
18+
return if (totalPrice > money) {
19+
money
20+
} else {
21+
money - totalPrice
22+
}
23+
}
24+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2706\. Buy Two Chocolates
2+
3+
Easy
4+
5+
You are given an integer array `prices` representing the prices of various chocolates in a store. You are also given a single integer `money`, which represents your initial amount of money.
6+
7+
You must buy **exactly** two chocolates in such a way that you still have some **non-negative** leftover money. You would like to minimize the sum of the prices of the two chocolates you buy.
8+
9+
Return _the amount of money you will have leftover after buying the two chocolates_. If there is no way for you to buy two chocolates without ending up in debt, return `money`. Note that the leftover must be non-negative.
10+
11+
**Example 1:**
12+
13+
**Input:** prices = [1,2,2], money = 3
14+
15+
**Output:** 0
16+
17+
**Explanation:** Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0.
18+
19+
**Example 2:**
20+
21+
**Input:** prices = [3,2,3], money = 3
22+
23+
**Output:** 3
24+
25+
**Explanation:** You cannot buy 2 chocolates without going in debt, so we return 3.
26+
27+
**Constraints:**
28+
29+
* `2 <= prices.length <= 50`
30+
* `1 <= prices[i] <= 100`
31+
* `1 <= money <= 100`

0 commit comments

Comments
 (0)