Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1816,6 +1816,43 @@

| # | Title | Difficulty | Tag | Time, ms | Time, %
|------|----------------|-------------|-------------|----------|--------
| 2800 |[Shortest String That Contains Three Strings](src/main/kotlin/g2701_2800/s2800_shortest_string_that_contains_three_strings)| Medium | String, Greedy, Enumeration | 259 | 100.00
| 2799 |[Count Complete Subarrays in an Array](src/main/kotlin/g2701_2800/s2799_count_complete_subarrays_in_an_array)| Medium | Array, Hash_Table, Sliding_Window | 206 | 96.97
| 2798 |[Number of Employees Who Met the Target](src/main/kotlin/g2701_2800/s2798_number_of_employees_who_met_the_target)| Easy | Array, Enumeration | 153 | 92.50
| 2791 |[Count Paths That Can Form a Palindrome in a Tree](src/main/kotlin/g2701_2800/s2791_count_paths_that_can_form_a_palindrome_in_a_tree)| Hard | Dynamic_Programming, Tree, Bit_Manipulation, Bitmask, Depth_First_Search | 683 | 100.00
| 2790 |[Maximum Number of Groups With Increasing Length](src/main/kotlin/g2701_2800/s2790_maximum_number_of_groups_with_increasing_length)| Hard | Array, Math, Sorting, Greedy, Binary_Search | 545 | 100.00
| 2749 |[Minimum Operations to Make the Integer Zero](src/main/kotlin/g2701_2800/s2749_minimum_operations_to_make_the_integer_zero)| Medium | Bit_Manipulation, Brainteaser | 132 | 91.67
| 2748 |[Number of Beautiful Pairs](src/main/kotlin/g2701_2800/s2748_number_of_beautiful_pairs)| Easy | Array, Math, Number_Theory | 227 | 100.00
| 2747 |[Count Zero Request Servers](src/main/kotlin/g2701_2800/s2747_count_zero_request_servers)| Medium | Array, Hash_Table, Sorting, Sliding_Window | 991 | 100.00
| 2746 |[Decremental String Concatenation](src/main/kotlin/g2701_2800/s2746_decremental_string_concatenation)| Medium | Array, String, Dynamic_Programming | 264 | 100.00
| 2745 |[Construct the Longest New String](src/main/kotlin/g2701_2800/s2745_construct_the_longest_new_string)| Medium | Math, Greedy, Brainteaser | 146 | 97.37
| 2744 |[Find Maximum Number of String Pairs](src/main/kotlin/g2701_2800/s2744_find_maximum_number_of_string_pairs)| Easy | Array, String, Hash_Table, Simulation | 162 | 96.81
| 2742 |[Painting the Walls](src/main/kotlin/g2701_2800/s2742_painting_the_walls)| Hard | Array, Dynamic_Programming | 268 | 100.00
| 2741 |[Special Permutations](src/main/kotlin/g2701_2800/s2741_special_permutations)| Medium | Array, Dynamic_Programming, Bit_Manipulation, Bitmask | 623 | 82.35
| 2740 |[Find the Value of the Partition](src/main/kotlin/g2701_2800/s2740_find_the_value_of_the_partition)| Medium | Array, Sorting | 431 | 100.00
| 2739 |[Total Distance Traveled](src/main/kotlin/g2701_2800/s2739_total_distance_traveled)| Easy | Math, Simulation | 177 | 100.00
| 2736 |[Maximum Sum Queries](src/main/kotlin/g2701_2800/s2736_maximum_sum_queries)| Hard | Array, Sorting, Binary_Search, Stack, Monotonic_Stack, Segment_Tree, Binary_Indexed_Tree | 1043 | 100.00
| 2735 |[Collecting Chocolates](src/main/kotlin/g2701_2800/s2735_collecting_chocolates)| Medium | Array, Enumeration | 237 | 100.00
| 2734 |[Lexicographically Smallest String After Substring Operation](src/main/kotlin/g2701_2800/s2734_lexicographically_smallest_string_after_substring_operation)| Medium | String, Greedy | 384 | 100.00
| 2733 |[Neither Minimum nor Maximum](src/main/kotlin/g2701_2800/s2733_neither_minimum_nor_maximum)| Easy | Array, Sorting | 286 | 100.00
| 2732 |[Find a Good Subset of the Matrix](src/main/kotlin/g2701_2800/s2732_find_a_good_subset_of_the_matrix)| Hard | Array, Greedy, Matrix, Bit_Manipulation | 760 | 98.36
| 2731 |[Movement of Robots](src/main/kotlin/g2701_2800/s2731_movement_of_robots)| Medium | Array, Sorting, Prefix_Sum, Brainteaser | 414 | 100.00
| 2730 |[Find the Longest Semi-Repetitive Substring](src/main/kotlin/g2701_2800/s2730_find_the_longest_semi_repetitive_substring)| Medium | String, Sliding_Window | 251 | 84.62
| 2729 |[Check if The Number is Fascinating](src/main/kotlin/g2701_2800/s2729_check_if_the_number_is_fascinating)| Easy | Hash_Table, Math | 131 | 100.00
| 2727 |[Is Object Empty](src/main/kotlin/g2701_2800/s2727_is_object_empty)| Easy || 49 | 98.24
| 2726 |[Calculator with Method Chaining](src/main/kotlin/g2701_2800/s2726_calculator_with_method_chaining)| Easy || 43 | 99.15
| 2725 |[Interval Cancellation](src/main/kotlin/g2701_2800/s2725_interval_cancellation)| Easy || 52 | 99.60
| 2724 |[Sort By](src/main/kotlin/g2701_2800/s2724_sort_by)| Easy || 132 | 96.70
| 2723 |[Add Two Promises](src/main/kotlin/g2701_2800/s2723_add_two_promises)| Easy || 56 | 97.63
| 2722 |[Join Two Arrays by ID](src/main/kotlin/g2701_2800/s2722_join_two_arrays_by_id)| Medium || 280 | 98.29
| 2721 |[Execute Asynchronous Functions in Parallel](src/main/kotlin/g2701_2800/s2721_execute_asynchronous_functions_in_parallel)| Medium || 63 | 99.09
| 2719 |[Count of Integers](src/main/kotlin/g2701_2800/s2719_count_of_integers)| Hard | String, Dynamic_Programming, Math | 208 | 100.00
| 2718 |[Sum of Matrix After Queries](src/main/kotlin/g2701_2800/s2718_sum_of_matrix_after_queries)| Medium | Array, Hash_Table | 668 | 100.00
| 2717 |[Semi-Ordered Permutation](src/main/kotlin/g2701_2800/s2717_semi_ordered_permutation)| Easy | Array, Simulation | 186 | 100.00
| 2716 |[Minimize String Length](src/main/kotlin/g2701_2800/s2716_minimize_string_length)| Easy | String, Hash_Table | 204 | 97.62
| 2715 |[Timeout Cancellation](src/main/kotlin/g2701_2800/s2715_execute_cancellable_function_with_delay)| Easy || 64 | 91.95
| 2713 |[Maximum Strictly Increasing Cells in a Matrix](src/main/kotlin/g2701_2800/s2713_maximum_strictly_increasing_cells_in_a_matrix)| Hard | Array, Dynamic_Programming, Sorting, Binary_Search, Matrix, Memoization | 1141 | 100.00
| 2712 |[Minimum Cost to Make All Characters Equal](src/main/kotlin/g2701_2800/s2712_minimum_cost_to_make_all_characters_equal)| Medium | String, Dynamic_Programming, Greedy | 200 | 100.00
| 2711 |[Difference of Number of Distinct Values on Diagonals](src/main/kotlin/g2701_2800/s2711_difference_of_number_of_distinct_values_on_diagonals)| Medium | Array, Hash_Table, Matrix | 281 | 100.00
| 2710 |[Remove Trailing Zeros From a String](src/main/kotlin/g2701_2800/s2710_remove_trailing_zeros_from_a_string)| Easy | String | 191 | 93.02
| 2709 |[Greatest Common Divisor Traversal](src/main/kotlin/g2701_2800/s2709_greatest_common_divisor_traversal)| Hard | Array, Math, Union_Find, Number_Theory | 892 | 81.82
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ Return `true` _if it is possible to traverse between all such pairs of indices,_
@Suppress("NAME_SHADOWING")
class Solution {
private var map: MutableMap<Int, Int>? = null

private lateinit var set: IntArray

private fun findParent(u: Int): Int {
return if (u == set[u]) u else findParent(set[u]).also { set[u] = it }
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
[![](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)

## 2712\. Minimum Cost to Make All Characters Equal

Medium

You are given a **0-indexed** binary string `s` of length `n` on which you can apply two types of operations:

* Choose an index `i` and invert all characters from index `0` to index `i` (both inclusive), with a cost of `i + 1`
* Choose an index `i` and invert all characters from index `i` to index `n - 1` (both inclusive), with a cost of `n - i`

Return _the **minimum cost** to make all characters of the string **equal**_.

**Invert** a character means if its value is '0' it becomes '1' and vice-versa.

**Example 1:**

**Input:** s = "0011"

**Output:** 2

**Explanation:** Apply the second operation with `i = 2` to obtain `s = "0000" for a cost of 2`. It can be shown that 2 is the minimum cost to make all characters equal.

**Example 2:**

**Input:** s = "010101"

**Output:** 9

**Explanation:**

Apply the first operation with i = 2 to obtain s = "101101" for a cost of 3.

Apply the first operation with i = 1 to obtain s = "011101" for a cost of 2.

Apply the first operation with i = 0 to obtain s = "111101" for a cost of 1.

Apply the second operation with i = 4 to obtain s = "111110" for a cost of 2.

Apply the second operation with i = 5 to obtain s = "111111" for a cost of 1.

The total cost to make all characters equal is 9. It can be shown that 9 is the minimum cost to make all characters equal.

**Constraints:**

* <code>1 <= s.length == n <= 10<sup>5</sup></code>
* `s[i]` is either `'0'` or `'1'`

## Solution

```kotlin
class Solution {
fun minimumCost(s: String): Long {
val n = s.length
val h = n / 2
val ca = s.toCharArray()
var result: Long
// to 1's
var m = 0L
var inverse = false
for (i in h downTo 0) {
if (inverse) {
if (ca[i] == '1') {
inverse = false
m += i + 1
}
} else {
if (ca[i] == '0') {
inverse = true
m += i + 1
}
}
}
inverse = false
for (i in h + 1 until n) {
if (inverse) {
if (ca[i] == '1') {
inverse = false
m += n - i
}
} else {
if (ca[i] == '0') {
inverse = true
m += n - i
}
}
}
result = m
m = 0L
inverse = false
for (i in h downTo 0) {
if (inverse) {
if (ca[i] == '0') {
inverse = false
m += i + 1
}
} else {
if (ca[i] == '1') {
inverse = true
m += i + 1
}
}
}
inverse = false
for (i in h + 1 until n) {
if (inverse) {
if (ca[i] == '0') {
inverse = false
m += n - i
}
} else {
if (ca[i] == '1') {
inverse = true
m += n - i
}
}
}
result = result.coerceAtMost(m)
return result
}
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
[![](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)

## 2713\. Maximum Strictly Increasing Cells in a Matrix

Hard

Given a **1-indexed** `m x n` integer matrix `mat`, you can select any cell in the matrix as your **starting cell**.

From the starting cell, you can move to any other cell **in the** **same row or column**, but only if the value of the destination cell is **strictly greater** than the value of the current cell. You can repeat this process as many times as possible, moving from cell to cell until you can no longer make any moves.

Your task is to find the **maximum number of cells** that you can visit in the matrix by starting from some cell.

Return _an integer denoting the maximum number of cells that can be visited._

**Example 1:**

**![](https://assets.leetcode.com/uploads/2023/04/23/diag1drawio.png)**

**Input:** mat = \[\[3,1],[3,4]]

**Output:** 2

**Explanation:** The image shows how we can visit 2 cells starting from row 1, column 2. It can be shown that we cannot visit more than 2 cells no matter where we start from, so the answer is 2.

**Example 2:**

**![](https://assets.leetcode.com/uploads/2023/04/23/diag3drawio.png)**

**Input:** mat = \[\[1,1],[1,1]]

**Output:** 1

**Explanation:** Since the cells must be strictly increasing, we can only visit one cell in this example.

**Example 3:**

**![](https://assets.leetcode.com/uploads/2023/04/23/diag4drawio.png)**

**Input:** mat = \[\[3,1,6],[-9,5,7]]

**Output:** 4

**Explanation:** The image above shows how we can visit 4 cells starting from row 2, column 1. It can be shown that we cannot visit more than 4 cells no matter where we start from, so the answer is 4.

**Constraints:**

* `m == mat.length`
* `n == mat[i].length`
* <code>1 <= m, n <= 10<sup>5</sup></code>
* <code>1 <= m * n <= 10<sup>5</sup></code>
* <code>-10<sup>5</sup> <= mat[i][j] <= 10<sup>5</sup></code>

## Solution

```kotlin
import java.util.concurrent.atomic.AtomicInteger

class Solution {
fun maxIncreasingCells(mat: Array<IntArray>): Int {
val n = mat.size
val m = mat[0].size
val map: MutableMap<Int, MutableList<IntArray>> = HashMap()
for (i in 0 until n) {
for (j in 0 until m) {
val `val` = mat[i][j]
if (!map.containsKey(`val`)) {
map.put(`val`, ArrayList())
}
map[`val`]!!.add(intArrayOf(i, j))
}
}
val memo = Array(n) { IntArray(m) }
val res = IntArray(n + m)
val max = AtomicInteger()
map.keys.stream().sorted().forEach { a: Int ->
for (pos in map[a]!!) {
val i = pos[0]
val j = pos[1]
memo[i][j] = res[i].coerceAtLeast(res[n + j]) + 1
max.set(max.get().coerceAtLeast(memo[i][j]))
}
for (pos in map[a]!!) {
val i = pos[0]
val j = pos[1]
res[n + j] = res[n + j].coerceAtLeast(memo[i][j])
res[i] = res[i].coerceAtLeast(memo[i][j])
}
}
return max.get()
}
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
[![](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)

## 2715\. Timeout Cancellation

Easy

Given a function `fn`, an array of arguments `args`, and a timeout `t` in milliseconds, return a cancel function `cancelFn`.

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.

**Example 1:**

**Input:** fn = (x) => x \* 5, args = [2], t = 20, cancelT = 50

**Output:** [{"time": 20, "returned": 10}]

**Explanation:**

const cancel = cancellable((x) => x \* 5, [2], 20); // fn(2) called at t=20ms
setTimeout(cancel, 50);

The cancellation was scheduled to occur after a delay of cancelT (50ms), which happened after the execution of fn(2) at 20ms.

**Example 2:**

**Input:** fn = (x) => x\*\*2, args = [2], t = 100, cancelT = 50

**Output:** []

**Explanation:**

const cancel = cancellable((x) => x\*\*2, [2], 100); // fn(2) not called
setTimeout(cancel, 50);

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.

**Example 3:**

**Input:** fn = (x1, x2) => x1 \* x2, args = [2,4], t = 30, cancelT = 100

**Output:** [{"time": 30, "returned": 8}]

**Explanation:**

const cancel = cancellable((x1, x2) => x1 \* x2, [2,4], 30); // fn(2,4) called at t=30ms
setTimeout(cancel, 100);

The cancellation was scheduled to occur after a delay of cancelT (100ms), which happened after the execution of fn(2,4) at 30ms.

**Constraints:**

* `fn is a function`
* `args is a valid JSON array`
* `1 <= args.length <= 10`
* `20 <= t <= 1000`
* `10 <= cancelT <= 1000`

## Solution

```typescript
function cancellable(fn: Function, args: any[], t: number): Function {
let cancelled: boolean = false
setTimeout(() => {
if (!cancelled) {
fn(...args)
}
}, t)
return () => {
cancelled = true
}
}

/*
* const result = []
*
* const fn = (x) => x * 5
* const args = [2], t = 20, cancelT = 50
*
* const start = performance.now()
*
* const log = (...argsArr) => {
* const diff = Math.floor(performance.now() - start);
* result.push({"time": diff, "returned": fn(...argsArr))
* }
*
* const cancel = cancellable(log, args, t);
*
* const maxT = Math.max(t, cancelT)
*
* setTimeout(() => {
* cancel()
* }, cancelT)
*
* setTimeout(() => {
* console.log(result) // [{"time":20,"returned":10}]
* }, maxT + 15)
*/

export { cancellable }
```
Loading