Skip to content

Commit 373fa8e

Browse files
authored
Added tasks 2707-2711
1 parent 560fecb commit 373fa8e

File tree

6 files changed

+594
-215
lines changed
  • src/main/kotlin/g2701_2800
    • s2707_extra_characters_in_a_string
    • s2708_maximum_strength_of_a_group
    • s2709_greatest_common_divisor_traversal
    • s2710_remove_trailing_zeros_from_a_string
    • s2711_difference_of_number_of_distinct_values_on_diagonals

6 files changed

+594
-215
lines changed

README.md

Lines changed: 220 additions & 215 deletions
Large diffs are not rendered by default.
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork)
3+
4+
## 2707\. Extra Characters in a String
5+
6+
Medium
7+
8+
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.
9+
10+
Return _the **minimum** number of extra characters left over if you break up_ `s` _optimally._
11+
12+
**Example 1:**
13+
14+
**Input:** s = "leetscode", dictionary = ["leet","code","leetcode"]
15+
16+
**Output:** 1
17+
18+
**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.
19+
20+
**Example 2:**
21+
22+
**Input:** s = "sayhelloworld", dictionary = ["hello","world"]
23+
24+
**Output:** 3
25+
26+
**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.
27+
28+
**Constraints:**
29+
30+
* `1 <= s.length <= 50`
31+
* `1 <= dictionary.length <= 50`
32+
* `1 <= dictionary[i].length <= 50`
33+
* `dictionary[i]` and `s` consists of only lowercase English letters
34+
* `dictionary` contains distinct words
35+
36+
## Solution
37+
38+
```kotlin
39+
class Solution {
40+
fun minExtraChar(s: String, dictionary: Array<String>): Int {
41+
val dict: MutableSet<String> = HashSet()
42+
val dp = IntArray(s.length + 1)
43+
for (word in dictionary) dict.add(word)
44+
for (i in 1 until dp.size) {
45+
dp[i] = dp[i - 1] + 1
46+
for (j in i - 1 downTo 0) {
47+
val sub: String = s.substring(j, i)
48+
if (dict.contains(sub)) dp[i] = dp[i].coerceAtMost(dp[j])
49+
}
50+
}
51+
return dp[dp.size - 1]
52+
}
53+
}
54+
```
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork)
3+
4+
## 2708\. Maximum Strength of a Group
5+
6+
Medium
7+
8+
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>.
9+
10+
Return _the maximum strength of a group the teacher can create_.
11+
12+
**Example 1:**
13+
14+
**Input:** nums = [3,-1,-5,2,5,-9]
15+
16+
**Output:** 1350
17+
18+
**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.
19+
20+
**Example 2:**
21+
22+
**Input:** nums = [-4,-5,-4]
23+
24+
**Output:** 20
25+
26+
**Explanation:** Group the students at indices [0, 1] . Then, we’ll have a resulting strength of 20. We cannot achieve greater strength.
27+
28+
**Constraints:**
29+
30+
* `1 <= nums.length <= 13`
31+
* `-9 <= nums[i] <= 9`
32+
33+
## Solution
34+
35+
```kotlin
36+
class Solution {
37+
fun maxStrength(nums: IntArray): Long {
38+
val filtered = mutableListOf<Int>()
39+
var product = 1L
40+
var hasZero = false
41+
for (num in nums) {
42+
if (num == 0) {
43+
hasZero = true
44+
continue
45+
}
46+
filtered.add(num)
47+
product *= num.toLong()
48+
}
49+
if (filtered.isEmpty()) return 0
50+
if (filtered.size == 1 && filtered[0] <= 0) return if (hasZero) 0 else filtered[0].toLong()
51+
var result = product
52+
for (num in nums) {
53+
if (num == 0) continue
54+
result = result.coerceAtLeast(product / num.toLong())
55+
}
56+
return result
57+
}
58+
}
59+
```
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork)
3+
4+
## 2709\. Greatest Common Divisor Traversal
5+
6+
Hard
7+
8+
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**.
9+
10+
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`.
11+
12+
Return `true` _if it is possible to traverse between all such pairs of indices,_ _or_ `false` _otherwise._
13+
14+
**Example 1:**
15+
16+
**Input:** nums = [2,3,6]
17+
18+
**Output:** true
19+
20+
**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.
21+
22+
**Example 2:**
23+
24+
**Input:** nums = [3,9,5]
25+
26+
**Output:** false
27+
28+
**Explanation:** No sequence of traversals can take us from index 0 to index 2 in this example. So, we return false.
29+
30+
**Example 3:**
31+
32+
**Input:** nums = [4,3,12,8]
33+
34+
**Output:** true
35+
36+
**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.
37+
38+
**Constraints:**
39+
40+
* <code>1 <= nums.length <= 10<sup>5</sup></code>
41+
* <code>1 <= nums[i] <= 10<sup>5</sup></code>
42+
43+
## Solution
44+
45+
```kotlin
46+
@Suppress("NAME_SHADOWING")
47+
class Solution {
48+
private var map: MutableMap<Int, Int>? = null
49+
50+
private lateinit var set: IntArray
51+
private fun findParent(u: Int): Int {
52+
return if (u == set[u]) u else findParent(set[u]).also { set[u] = it }
53+
}
54+
55+
private fun union(a: Int, b: Int) {
56+
val p1 = findParent(a)
57+
val p2 = findParent(b)
58+
if (p1 != p2) {
59+
set[b] = p1
60+
}
61+
set[p2] = p1
62+
}
63+
64+
private fun solve(n: Int, index: Int) {
65+
var n = n
66+
if (n % 2 == 0) {
67+
val x = map!!.getOrDefault(2, -1)
68+
if (x != -1) {
69+
union(x, index)
70+
}
71+
while (n % 2 == 0) n /= 2
72+
map!!.put(2, index)
73+
}
74+
val sqrt = kotlin.math.sqrt(n.toDouble()).toInt()
75+
for (i in 3..sqrt) {
76+
if (n % i == 0) {
77+
val x = map!!.getOrDefault(i, -1)
78+
if (x != -1) {
79+
union(x, index)
80+
}
81+
while (n % i == 0) n /= i
82+
map!!.put(i, index)
83+
}
84+
}
85+
if (n > 2) {
86+
val x = map!!.getOrDefault(n, -1)
87+
if (x != -1) {
88+
union(x, index)
89+
}
90+
map!!.put(n, index)
91+
}
92+
}
93+
94+
fun canTraverseAllPairs(nums: IntArray): Boolean {
95+
set = IntArray(nums.size)
96+
map = HashMap()
97+
for (i in nums.indices) set[i] = i
98+
for (i in nums.indices) solve(nums[i], i)
99+
val p = findParent(0)
100+
for (i in nums.indices) if (p != findParent(i)) return false
101+
return true
102+
}
103+
}
104+
```
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork)
3+
4+
## 2710\. Remove Trailing Zeros From a String
5+
6+
Easy
7+
8+
Given a **positive** integer `num` represented as a string, return _the integer_ `num` _without trailing zeros as a string_.
9+
10+
**Example 1:**
11+
12+
**Input:** num = "51230100"
13+
14+
**Output:** "512301"
15+
16+
**Explanation:** Integer "51230100" has 2 trailing zeros, we remove them and return integer "512301".
17+
18+
**Example 2:**
19+
20+
**Input:** num = "123"
21+
22+
**Output:** "123"
23+
24+
**Explanation:** Integer "123" has no trailing zeros, we return integer "123".
25+
26+
**Constraints:**
27+
28+
* `1 <= num.length <= 1000`
29+
* `num` consists of only digits.
30+
* `num` doesn't have any leading zeros.
31+
32+
## Solution
33+
34+
```kotlin
35+
class Solution {
36+
fun removeTrailingZeros(num: String): String {
37+
return num.dropLastWhile { it == '0' }
38+
}
39+
}
40+
```
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork)
3+
4+
## 2711\. Difference of Number of Distinct Values on Diagonals
5+
6+
Medium
7+
8+
Given a **0-indexed** 2D `grid` of size `m x n`, you should find the matrix `answer` of size `m x n`.
9+
10+
The value of each cell `(r, c)` of the matrix `answer` is calculated in the following way:
11+
12+
* Let `topLeft[r][c]` be the number of **distinct** values in the top-left diagonal of the cell `(r, c)` in the matrix `grid`.
13+
* Let `bottomRight[r][c]` be the number of **distinct** values in the bottom-right diagonal of the cell `(r, c)` in the matrix `grid`.
14+
15+
Then `answer[r][c] = |topLeft[r][c] - bottomRight[r][c]|`.
16+
17+
Return _the matrix_ `answer`.
18+
19+
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.
20+
21+
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.
22+
23+
**Example 1:**
24+
25+
![](https://assets.leetcode.com/uploads/2023/04/19/ex2.png)
26+
27+
**Input:** grid = \[\[1,2,3],[3,1,5],[3,2,1]]
28+
29+
**Output:** [[1,1,0],[1,0,1],[0,1,1]]
30+
31+
**Explanation:**
32+
33+
The 1<sup>st</sup> diagram denotes the initial grid.
34+
35+
The 2<sup>nd</sup> diagram denotes a grid for cell (0,0), where blue-colored cells are cells on its bottom-right diagonal.
36+
37+
The 3<sup>rd</sup> diagram denotes a grid for cell (1,2), where red-colored cells are cells on its top-left diagonal.
38+
39+
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.
40+
- The cell (0,0) contains [1,1] on its bottom-right diagonal and [] on its top-left diagonal. The answer is \|1 - 0\| = 1.
41+
- The cell (1,2) contains [] on its bottom-right diagonal and [2] on its top-left diagonal. The answer is \|0 - 1\| = 1.
42+
- The cell (1,1) contains [1] on its bottom-right diagonal and [1] on its top-left diagonal. The answer is \|1 - 1\| = 0.
43+
44+
The answers of other cells are similarly calculated.
45+
46+
**Example 2:**
47+
48+
**Input:** grid = \[\[1]]
49+
50+
**Output:** [[0]]
51+
52+
**Explanation:** - The cell (0,0) contains [] on its bottom-right diagonal and [] on its top-left diagonal. The answer is \|0 - 0\| = 0.
53+
54+
**Constraints:**
55+
56+
* `m == grid.length`
57+
* `n == grid[i].length`
58+
* `1 <= m, n, grid[i][j] <= 50`
59+
60+
## Solution
61+
62+
```kotlin
63+
class Solution {
64+
fun differenceOfDistinctValues(grid: Array<IntArray>): Array<IntArray> {
65+
val m = grid.size
66+
val n = grid[0].size
67+
val arrTopLeft = Array(m) { IntArray(n) }
68+
val arrBotRight = Array(m) { IntArray(n) }
69+
for (i in m - 1 downTo 0) {
70+
var c = 0
71+
var r: Int = i
72+
val set: MutableSet<Int> = HashSet()
73+
while (cellExists(r, c, grid)) {
74+
arrTopLeft[r][c] = set.size
75+
set.add(grid[r++][c++])
76+
}
77+
}
78+
for (i in 1 until n) {
79+
var r = 0
80+
var c: Int = i
81+
val set: MutableSet<Int> = HashSet()
82+
while (cellExists(r, c, grid)) {
83+
arrTopLeft[r][c] = set.size
84+
set.add(grid[r++][c++])
85+
}
86+
}
87+
for (i in 0 until n) {
88+
var r = m - 1
89+
var c: Int = i
90+
val set: MutableSet<Int> = HashSet()
91+
while (cellExists(r, c, grid)) {
92+
arrBotRight[r][c] = set.size
93+
set.add(grid[r--][c--])
94+
}
95+
}
96+
for (i in m - 1 downTo 0) {
97+
var c = n - 1
98+
var r: Int = i
99+
val set: MutableSet<Int> = HashSet()
100+
while (cellExists(r, c, grid)) {
101+
arrBotRight[r][c] = set.size
102+
set.add(grid[r--][c--])
103+
}
104+
}
105+
for (r in 0 until m) {
106+
for (c in 0 until n) {
107+
grid[r][c] = kotlin.math.abs(arrTopLeft[r][c] - arrBotRight[r][c])
108+
}
109+
}
110+
return grid
111+
}
112+
113+
private fun cellExists(r: Int, c: Int, grid: Array<IntArray>): Boolean {
114+
return r >= 0 && r < grid.size && c >= 0 && c < grid[0].size
115+
}
116+
}
117+
```

0 commit comments

Comments
 (0)