Skip to content

Commit 6151041

Browse files
authored
Added tasks 2707-2711
1 parent 350851f commit 6151041

File tree

15 files changed

+493
-0
lines changed

15 files changed

+493
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package g2701_2800.s2707_extra_characters_in_a_string
2+
3+
// #Medium #Array #String #Hash_Table #Dynamic_Programming #Trie
4+
// #2023_07_31_Time_276_ms_(85.71%)_Space_38_MB_(100.00%)
5+
6+
class Solution {
7+
fun minExtraChar(s: String, dictionary: Array<String>): Int {
8+
val dict: MutableSet<String> = HashSet()
9+
val dp = IntArray(s.length + 1)
10+
for (word in dictionary) dict.add(word)
11+
for (i in 1 until dp.size) {
12+
dp[i] = dp[i - 1] + 1
13+
for (j in i - 1 downTo 0) {
14+
val sub: String = s.substring(j, i)
15+
if (dict.contains(sub)) dp[i] = dp[i].coerceAtMost(dp[j])
16+
}
17+
}
18+
return dp[dp.size - 1]
19+
}
20+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2707\. Extra Characters in a String
2+
3+
Medium
4+
5+
You are given a **0-indexed** string `s` and a dictionary of words `dictionary`. You have to break `s` into one or more **non-overlapping** substrings such that each substring is present in `dictionary`. There may be some **extra characters** in `s` which are not present in any of the substrings.
6+
7+
Return _the **minimum** number of extra characters left over if you break up_ `s` _optimally._
8+
9+
**Example 1:**
10+
11+
**Input:** s = "leetscode", dictionary = ["leet","code","leetcode"]
12+
13+
**Output:** 1
14+
15+
**Explanation:** We can break s in two substrings: "leet" from index 0 to 3 and "code" from index 5 to 8. There is only 1 unused character (at index 4), so we return 1.
16+
17+
**Example 2:**
18+
19+
**Input:** s = "sayhelloworld", dictionary = ["hello","world"]
20+
21+
**Output:** 3
22+
23+
**Explanation:** We can break s in two substrings: "hello" from index 3 to 7 and "world" from index 8 to 12. The characters at indices 0, 1, 2 are not used in any substring and thus are considered as extra characters. Hence, we return 3.
24+
25+
**Constraints:**
26+
27+
* `1 <= s.length <= 50`
28+
* `1 <= dictionary.length <= 50`
29+
* `1 <= dictionary[i].length <= 50`
30+
* `dictionary[i]` and `s` consists of only lowercase English letters
31+
* `dictionary` contains distinct words
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package g2701_2800.s2708_maximum_strength_of_a_group
2+
3+
// #Medium #Array #Sorting #Greedy #Backtracking
4+
// #2023_07_31_Time_183_ms_(100.00%)_Space_36.9_MB_(90.91%)
5+
6+
class Solution {
7+
fun maxStrength(nums: IntArray): Long {
8+
val filtered = mutableListOf<Int>()
9+
var product = 1L
10+
var hasZero = false
11+
for (num in nums) {
12+
if (num == 0) {
13+
hasZero = true
14+
continue
15+
}
16+
filtered.add(num)
17+
product *= num.toLong()
18+
}
19+
if (filtered.isEmpty()) return 0
20+
if (filtered.size == 1 && filtered[0] <= 0) return if (hasZero) 0 else filtered[0].toLong()
21+
var result = product
22+
for (num in nums) {
23+
if (num == 0) continue
24+
result = result.coerceAtLeast(product / num.toLong())
25+
}
26+
return result
27+
}
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2708\. Maximum Strength of a Group
2+
3+
Medium
4+
5+
You are given a **0-indexed** integer array `nums` representing the score of students in an exam. The teacher would like to form one **non-empty** group of students with maximal **strength**, where the strength of a group of students of indices <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, <code>i<sub>2</sub></code>, ... , <code>i<sub>k</sub></code> is defined as <code>nums[i<sub>0</sub>] * nums[i<sub>1</sub>] * nums[i<sub>2</sub>] * ... * nums[i<sub>k</sub>]</code>.
6+
7+
Return _the maximum strength of a group the teacher can create_.
8+
9+
**Example 1:**
10+
11+
**Input:** nums = [3,-1,-5,2,5,-9]
12+
13+
**Output:** 1350
14+
15+
**Explanation:** One way to form a group of maximal strength is to group the students at indices [0,2,3,4,5]. Their strength is 3 \* (-5) \* 2 \* 5 \* (-9) = 1350, which we can show is optimal.
16+
17+
**Example 2:**
18+
19+
**Input:** nums = [-4,-5,-4]
20+
21+
**Output:** 20
22+
23+
**Explanation:** Group the students at indices [0, 1] . Then, we’ll have a resulting strength of 20. We cannot achieve greater strength.
24+
25+
**Constraints:**
26+
27+
* `1 <= nums.length <= 13`
28+
* `-9 <= nums[i] <= 9`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package g2701_2800.s2709_greatest_common_divisor_traversal
2+
3+
// #Hard #Array #Math #Union_Find #Number_Theory
4+
// #2023_07_31_Time_892_ms_(81.82%)_Space_73.7_MB_(81.82%)
5+
6+
@Suppress("NAME_SHADOWING")
7+
class Solution {
8+
private var map: MutableMap<Int, Int>? = null
9+
10+
private lateinit var set: IntArray
11+
private fun findParent(u: Int): Int {
12+
return if (u == set[u]) u else findParent(set[u]).also { set[u] = it }
13+
}
14+
15+
private fun union(a: Int, b: Int) {
16+
val p1 = findParent(a)
17+
val p2 = findParent(b)
18+
if (p1 != p2) {
19+
set[b] = p1
20+
}
21+
set[p2] = p1
22+
}
23+
24+
private fun solve(n: Int, index: Int) {
25+
var n = n
26+
if (n % 2 == 0) {
27+
val x = map!!.getOrDefault(2, -1)
28+
if (x != -1) {
29+
union(x, index)
30+
}
31+
while (n % 2 == 0) n /= 2
32+
map!!.put(2, index)
33+
}
34+
val sqrt = kotlin.math.sqrt(n.toDouble()).toInt()
35+
for (i in 3..sqrt) {
36+
if (n % i == 0) {
37+
val x = map!!.getOrDefault(i, -1)
38+
if (x != -1) {
39+
union(x, index)
40+
}
41+
while (n % i == 0) n /= i
42+
map!!.put(i, index)
43+
}
44+
}
45+
if (n > 2) {
46+
val x = map!!.getOrDefault(n, -1)
47+
if (x != -1) {
48+
union(x, index)
49+
}
50+
map!!.put(n, index)
51+
}
52+
}
53+
54+
fun canTraverseAllPairs(nums: IntArray): Boolean {
55+
set = IntArray(nums.size)
56+
map = HashMap()
57+
for (i in nums.indices) set[i] = i
58+
for (i in nums.indices) solve(nums[i], i)
59+
val p = findParent(0)
60+
for (i in nums.indices) if (p != findParent(i)) return false
61+
return true
62+
}
63+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
2709\. Greatest Common Divisor Traversal
2+
3+
Hard
4+
5+
You are given a **0-indexed** integer array `nums`, and you are allowed to **traverse** between its indices. You can traverse between index `i` and index `j`, `i != j`, if and only if `gcd(nums[i], nums[j]) > 1`, where `gcd` is the **greatest common divisor**.
6+
7+
Your task is to determine if for **every pair** of indices `i` and `j` in nums, where `i < j`, there exists a **sequence of traversals** that can take us from `i` to `j`.
8+
9+
Return `true` _if it is possible to traverse between all such pairs of indices,_ _or_ `false` _otherwise._
10+
11+
**Example 1:**
12+
13+
**Input:** nums = [2,3,6]
14+
15+
**Output:** true
16+
17+
**Explanation:** In this example, there are 3 possible pairs of indices: (0, 1), (0, 2), and (1, 2). To go from index 0 to index 1, we can use the sequence of traversals 0 -> 2 -> 1, where we move from index 0 to index 2 because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1, and then move from index 2 to index 1 because gcd(nums[2], nums[1]) = gcd(6, 3) = 3 > 1. To go from index 0 to index 2, we can just go directly because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1. Likewise, to go from index 1 to index 2, we can just go directly because gcd(nums[1], nums[2]) = gcd(3, 6) = 3 > 1.
18+
19+
**Example 2:**
20+
21+
**Input:** nums = [3,9,5]
22+
23+
**Output:** false
24+
25+
**Explanation:** No sequence of traversals can take us from index 0 to index 2 in this example. So, we return false.
26+
27+
**Example 3:**
28+
29+
**Input:** nums = [4,3,12,8]
30+
31+
**Output:** true
32+
33+
**Explanation:** There are 6 possible pairs of indices to traverse between: (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), and (2, 3). A valid sequence of traversals exists for each pair, so we return true.
34+
35+
**Constraints:**
36+
37+
* <code>1 <= nums.length <= 10<sup>5</sup></code>
38+
* <code>1 <= nums[i] <= 10<sup>5</sup></code>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package g2701_2800.s2710_remove_trailing_zeros_from_a_string
2+
3+
// #Easy #String #2023_07_31_Time_191_ms_(93.02%)_Space_38.1_MB_(46.51%)
4+
5+
class Solution {
6+
fun removeTrailingZeros(num: String): String {
7+
return num.dropLastWhile { it == '0' }
8+
}
9+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
2710\. Remove Trailing Zeros From a String
2+
3+
Easy
4+
5+
Given a **positive** integer `num` represented as a string, return _the integer_ `num` _without trailing zeros as a string_.
6+
7+
**Example 1:**
8+
9+
**Input:** num = "51230100"
10+
11+
**Output:** "512301"
12+
13+
**Explanation:** Integer "51230100" has 2 trailing zeros, we remove them and return integer "512301".
14+
15+
**Example 2:**
16+
17+
**Input:** num = "123"
18+
19+
**Output:** "123"
20+
21+
**Explanation:** Integer "123" has no trailing zeros, we return integer "123".
22+
23+
**Constraints:**
24+
25+
* `1 <= num.length <= 1000`
26+
* `num` consists of only digits.
27+
* `num` doesn't have any leading zeros.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package g2701_2800.s2711_difference_of_number_of_distinct_values_on_diagonals
2+
3+
// #Medium #Array #Hash_Table #Matrix #2023_07_31_Time_281_ms_(100.00%)_Space_44.5_MB_(70.00%)
4+
5+
class Solution {
6+
fun differenceOfDistinctValues(grid: Array<IntArray>): Array<IntArray> {
7+
val m = grid.size
8+
val n = grid[0].size
9+
val arrTopLeft = Array(m) { IntArray(n) }
10+
val arrBotRight = Array(m) { IntArray(n) }
11+
for (i in m - 1 downTo 0) {
12+
var c = 0
13+
var r: Int = i
14+
val set: MutableSet<Int> = HashSet()
15+
while (cellExists(r, c, grid)) {
16+
arrTopLeft[r][c] = set.size
17+
set.add(grid[r++][c++])
18+
}
19+
}
20+
for (i in 1 until n) {
21+
var r = 0
22+
var c: Int = i
23+
val set: MutableSet<Int> = HashSet()
24+
while (cellExists(r, c, grid)) {
25+
arrTopLeft[r][c] = set.size
26+
set.add(grid[r++][c++])
27+
}
28+
}
29+
for (i in 0 until n) {
30+
var r = m - 1
31+
var c: Int = i
32+
val set: MutableSet<Int> = HashSet()
33+
while (cellExists(r, c, grid)) {
34+
arrBotRight[r][c] = set.size
35+
set.add(grid[r--][c--])
36+
}
37+
}
38+
for (i in m - 1 downTo 0) {
39+
var c = n - 1
40+
var r: Int = i
41+
val set: MutableSet<Int> = HashSet()
42+
while (cellExists(r, c, grid)) {
43+
arrBotRight[r][c] = set.size
44+
set.add(grid[r--][c--])
45+
}
46+
}
47+
for (r in 0 until m) {
48+
for (c in 0 until n) {
49+
grid[r][c] = kotlin.math.abs(arrTopLeft[r][c] - arrBotRight[r][c])
50+
}
51+
}
52+
return grid
53+
}
54+
55+
private fun cellExists(r: Int, c: Int, grid: Array<IntArray>): Boolean {
56+
return r >= 0 && r < grid.size && c >= 0 && c < grid[0].size
57+
}
58+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
2711\. Difference of Number of Distinct Values on Diagonals
2+
3+
Medium
4+
5+
Given a **0-indexed** 2D `grid` of size `m x n`, you should find the matrix `answer` of size `m x n`.
6+
7+
The value of each cell `(r, c)` of the matrix `answer` is calculated in the following way:
8+
9+
* Let `topLeft[r][c]` be the number of **distinct** values in the top-left diagonal of the cell `(r, c)` in the matrix `grid`.
10+
* Let `bottomRight[r][c]` be the number of **distinct** values in the bottom-right diagonal of the cell `(r, c)` in the matrix `grid`.
11+
12+
Then `answer[r][c] = |topLeft[r][c] - bottomRight[r][c]|`.
13+
14+
Return _the matrix_ `answer`.
15+
16+
A **matrix diagonal** is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end.
17+
18+
A cell <code>(r<sub>1</sub>, c<sub>1</sub>)</code> belongs to the top-left diagonal of the cell `(r, c)`, if both belong to the same diagonal and <code>r<sub>1</sub> < r</code>. Similarly is defined bottom-right diagonal.
19+
20+
**Example 1:**
21+
22+
![](https://assets.leetcode.com/uploads/2023/04/19/ex2.png)
23+
24+
**Input:** grid = [[1,2,3],[3,1,5],[3,2,1]]
25+
26+
**Output:** [[1,1,0],[1,0,1],[0,1,1]]
27+
28+
**Explanation:**
29+
30+
The 1<sup>st</sup> diagram denotes the initial grid.
31+
32+
The 2<sup>nd</sup> diagram denotes a grid for cell (0,0), where blue-colored cells are cells on its bottom-right diagonal.
33+
34+
The 3<sup>rd</sup> diagram denotes a grid for cell (1,2), where red-colored cells are cells on its top-left diagonal.
35+
36+
The 4<sup>th</sup> diagram denotes a grid for cell (1,1), where blue-colored cells are cells on its bottom-right diagonal and red-colored cells are cells on its top-left diagonal.
37+
- The cell (0,0) contains [1,1] on its bottom-right diagonal and [] on its top-left diagonal. The answer is |1 - 0| = 1.
38+
- The cell (1,2) contains [] on its bottom-right diagonal and [2] on its top-left diagonal. The answer is |0 - 1| = 1.
39+
- The cell (1,1) contains [1] on its bottom-right diagonal and [1] on its top-left diagonal. The answer is |1 - 1| = 0.
40+
41+
The answers of other cells are similarly calculated.
42+
43+
**Example 2:**
44+
45+
**Input:** grid = [[1]]
46+
47+
**Output:** [[0]]
48+
49+
**Explanation:** - The cell (0,0) contains [] on its bottom-right diagonal and [] on its top-left diagonal. The answer is |0 - 0| = 0.
50+
51+
**Constraints:**
52+
53+
* `m == grid.length`
54+
* `n == grid[i].length`
55+
* `1 <= m, n, grid[i][j] <= 50`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package g2701_2800.s2707_extra_characters_in_a_string
2+
3+
import org.hamcrest.CoreMatchers.equalTo
4+
import org.hamcrest.MatcherAssert.assertThat
5+
import org.junit.jupiter.api.Test
6+
7+
internal class SolutionTest {
8+
@Test
9+
fun minExtraChar() {
10+
assertThat(
11+
Solution().minExtraChar("leetscode", arrayOf("leet", "code", "leetcode")),
12+
equalTo(1)
13+
)
14+
}
15+
16+
@Test
17+
fun minExtraChar2() {
18+
assertThat(
19+
Solution().minExtraChar("sayhelloworld", arrayOf("hello", "world")),
20+
equalTo(3)
21+
)
22+
}
23+
}

0 commit comments

Comments
 (0)