From 1d8c980eca44795326997060c21a6f4bc7a38600 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 8 Aug 2023 07:41:45 +0300 Subject: [PATCH] Added tasks 2712-2800 --- README.md | 37 ++++ .../readme.md | 2 +- .../readme.md | 123 +++++++++++++ .../readme.md | 93 ++++++++++ .../readme.md | 101 +++++++++++ .../s2716_minimize_string_length/readme.md | 58 ++++++ .../s2717_semi_ordered_permutation/readme.md | 79 +++++++++ .../readme.md | 79 +++++++++ .../s2719_count_of_integers/readme.md | 97 ++++++++++ .../readme.md | 95 ++++++++++ .../s2722_join_two_arrays_by_id/readme.md | 109 ++++++++++++ .../s2723_add_two_promises/readme.md | 47 +++++ .../kotlin/g2701_2800/s2724_sort_by/readme.md | 53 ++++++ .../s2725_interval_cancellation/readme.md | 166 ++++++++++++++++++ .../readme.md | 95 ++++++++++ .../s2727_is_object_empty/readme.md | 53 ++++++ .../readme.md | 62 +++++++ .../readme.md | 62 +++++++ .../s2731_movement_of_robots/readme.md | 83 +++++++++ .../readme.md | 92 ++++++++++ .../readme.md | 59 +++++++ .../readme.md | 87 +++++++++ .../s2735_collecting_chocolates/readme.md | 68 +++++++ .../s2736_maximum_sum_queries/readme.md | 110 ++++++++++++ .../s2739_total_distance_traveled/readme.md | 54 ++++++ .../readme.md | 64 +++++++ .../s2741_special_permutations/readme.md | 86 +++++++++ .../s2742_painting_the_walls/readme.md | 60 +++++++ .../readme.md | 75 ++++++++ .../readme.md | 48 +++++ .../readme.md | 115 ++++++++++++ .../readme.md | 93 ++++++++++ .../s2748_number_of_beautiful_pairs/readme.md | 91 ++++++++++ .../readme.md | 59 +++++++ .../readme.md | 109 ++++++++++++ .../readme.md | 94 ++++++++++ .../readme.md | 69 ++++++++ .../readme.md | 77 ++++++++ .../readme.md | 104 +++++++++++ 39 files changed, 3107 insertions(+), 1 deletion(-) create mode 100644 src/main/kotlin/g2701_2800/s2712_minimum_cost_to_make_all_characters_equal/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2713_maximum_strictly_increasing_cells_in_a_matrix/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2715_execute_cancellable_function_with_delay/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2716_minimize_string_length/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2717_semi_ordered_permutation/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2718_sum_of_matrix_after_queries/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2719_count_of_integers/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2721_execute_asynchronous_functions_in_parallel/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2722_join_two_arrays_by_id/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2723_add_two_promises/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2724_sort_by/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2725_interval_cancellation/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2726_calculator_with_method_chaining/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2727_is_object_empty/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2729_check_if_the_number_is_fascinating/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2730_find_the_longest_semi_repetitive_substring/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2731_movement_of_robots/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2732_find_a_good_subset_of_the_matrix/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2733_neither_minimum_nor_maximum/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2734_lexicographically_smallest_string_after_substring_operation/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2735_collecting_chocolates/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2736_maximum_sum_queries/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2739_total_distance_traveled/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2740_find_the_value_of_the_partition/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2741_special_permutations/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2742_painting_the_walls/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2744_find_maximum_number_of_string_pairs/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2745_construct_the_longest_new_string/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2746_decremental_string_concatenation/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2747_count_zero_request_servers/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2748_number_of_beautiful_pairs/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2749_minimum_operations_to_make_the_integer_zero/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2790_maximum_number_of_groups_with_increasing_length/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2791_count_paths_that_can_form_a_palindrome_in_a_tree/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2798_number_of_employees_who_met_the_target/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2799_count_complete_subarrays_in_an_array/readme.md create mode 100644 src/main/kotlin/g2701_2800/s2800_shortest_string_that_contains_three_strings/readme.md diff --git a/README.md b/README.md index d625ac9d..dca37598 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/main/kotlin/g2701_2800/s2709_greatest_common_divisor_traversal/readme.md b/src/main/kotlin/g2701_2800/s2709_greatest_common_divisor_traversal/readme.md index 85821029..5e263a31 100644 --- a/src/main/kotlin/g2701_2800/s2709_greatest_common_divisor_traversal/readme.md +++ b/src/main/kotlin/g2701_2800/s2709_greatest_common_divisor_traversal/readme.md @@ -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? = 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 } } diff --git a/src/main/kotlin/g2701_2800/s2712_minimum_cost_to_make_all_characters_equal/readme.md b/src/main/kotlin/g2701_2800/s2712_minimum_cost_to_make_all_characters_equal/readme.md new file mode 100644 index 00000000..d01bbaad --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2712_minimum_cost_to_make_all_characters_equal/readme.md @@ -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:** + +* 1 <= s.length == n <= 105 +* `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 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2713_maximum_strictly_increasing_cells_in_a_matrix/readme.md b/src/main/kotlin/g2701_2800/s2713_maximum_strictly_increasing_cells_in_a_matrix/readme.md new file mode 100644 index 00000000..f29cbb7d --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2713_maximum_strictly_increasing_cells_in_a_matrix/readme.md @@ -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` +* 1 <= m, n <= 105 +* 1 <= m * n <= 105 +* -105 <= mat[i][j] <= 105 + +## Solution + +```kotlin +import java.util.concurrent.atomic.AtomicInteger + +class Solution { + fun maxIncreasingCells(mat: Array): Int { + val n = mat.size + val m = mat[0].size + val map: MutableMap> = 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() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2715_execute_cancellable_function_with_delay/readme.md b/src/main/kotlin/g2701_2800/s2715_execute_cancellable_function_with_delay/readme.md new file mode 100644 index 00000000..497bd40b --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2715_execute_cancellable_function_with_delay/readme.md @@ -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 } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2716_minimize_string_length/readme.md b/src/main/kotlin/g2701_2800/s2716_minimize_string_length/readme.md new file mode 100644 index 00000000..1eb260d9 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2716_minimize_string_length/readme.md @@ -0,0 +1,58 @@ +[![](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) + +## 2716\. Minimize String Length + +Easy + +Given a **0-indexed** string `s`, repeatedly perform the following operation **any** number of times: + +* Choose an index `i` in the string, and let `c` be the character in position `i`. **Delete** the **closest occurrence** of `c` to the **left** of `i` (if any) and the **closest occurrence** of `c` to the **right** of `i` (if any). + +Your task is to **minimize** the length of `s` by performing the above operation any number of times. + +Return _an integer denoting the length of the **minimized** string._ + +**Example 1:** + +**Input:** s = "aaabc" + +**Output:** 3 + +**Explanation:** In this example, s is "aaabc". We can start by selecting the character 'a' at index 1. We then remove the closest 'a' to the left of index 1, which is at index 0, and the closest 'a' to the right of index 1, which is at index 2. After this operation, the string becomes "abc". Any further operation we perform on the string will leave it unchanged. Therefore, the length of the minimized string is 3. + +**Example 2:** + +**Input:** s = "cbbd" + +**Output:** 3 + +**Explanation:** For this we can start with character 'b' at index 1. There is no occurrence of 'b' to the left of index 1, but there is one to the right at index 2, so we delete the 'b' at index 2. The string becomes "cbd" and further operations will leave it unchanged. Hence, the minimized length is 3. + +**Example 3:** + +**Input:** s = "dddaaa" + +**Output:** 2 + +**Explanation:** For this, we can start with the character 'd' at index 1. The closest occurrence of a 'd' to its left is at index 0, and the closest occurrence of a 'd' to its right is at index 2. We delete both index 0 and 2, so the string becomes "daaa". In the new string, we can select the character 'a' at index 2. The closest occurrence of an 'a' to its left is at index 1, and the closest occurrence of an 'a' to its right is at index 3. We delete both of them, and the string becomes "da". We cannot minimize this further, so the minimized length is 2. + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` contains only lowercase English letters + +## Solution + +```kotlin +class Solution { + fun minimizedStringLength(s: String): Int { + val charMap = HashMap() + for (i in s.indices) { + val currentCount = charMap.getOrDefault(s[i], 0) + charMap.put(s[i], currentCount + 1) + } + return charMap.size + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2717_semi_ordered_permutation/readme.md b/src/main/kotlin/g2701_2800/s2717_semi_ordered_permutation/readme.md new file mode 100644 index 00000000..01305038 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2717_semi_ordered_permutation/readme.md @@ -0,0 +1,79 @@ +[![](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) + +## 2717\. Semi-Ordered Permutation + +Easy + +You are given a **0-indexed** permutation of `n` integers `nums`. + +A permutation is called **semi-ordered** if the first number equals `1` and the last number equals `n`. You can perform the below operation as many times as you want until you make `nums` a **semi-ordered** permutation: + +* Pick two adjacent elements in `nums`, then swap them. + +Return _the minimum number of operations to make_ `nums` _a **semi-ordered permutation**_. + +A **permutation** is a sequence of integers from `1` to `n` of length `n` containing each number exactly once. + +**Example 1:** + +**Input:** nums = [2,1,4,3] + +**Output:** 2 + +**Explanation:** We can make the permutation semi-ordered using these sequence of operations: + +1 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. + +2 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. + +It can be proved that there is no sequence of less than two operations that make nums a semi-ordered permutation. + +**Example 2:** + +**Input:** nums = [2,4,1,3] + +**Output:** 3 + +**Explanation:** We can make the permutation semi-ordered using these sequence of operations: + +1 - swap i = 1 and j = 2. The permutation becomes [2,1,4,3]. + +2 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. + +3 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. + +It can be proved that there is no sequence of less than three operations that make nums a semi-ordered permutation. + +**Example 3:** + +**Input:** nums = [1,3,4,2,5] + +**Output:** 0 + +**Explanation:** The permutation is already a semi-ordered permutation. + +**Constraints:** + +* `2 <= nums.length == n <= 50` +* `1 <= nums[i] <= 50` +* `nums is a permutation.` + +## Solution + +```kotlin +class Solution { + fun semiOrderedPermutation(nums: IntArray): Int { + val a = 1 + var b = nums.size + var idxA = 0 + var idxB = 0 + for (i in nums.indices) { + if (nums[i] == a) idxA = i + if (nums[i] == b) idxB = i + } + b = b - idxB - 1 + return if (idxB < idxA) idxA + b - 1 else idxA + b + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2718_sum_of_matrix_after_queries/readme.md b/src/main/kotlin/g2701_2800/s2718_sum_of_matrix_after_queries/readme.md new file mode 100644 index 00000000..8006ed03 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2718_sum_of_matrix_after_queries/readme.md @@ -0,0 +1,79 @@ +[![](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) + +## 2718\. Sum of Matrix After Queries + +Medium + +You are given an integer `n` and a **0-indexed** **2D array** `queries` where queries[i] = [typei, indexi, vali]. + +Initially, there is a **0-indexed** `n x n` matrix filled with `0`'s. For each query, you must apply one of the following changes: + +* if typei == 0, set the values in the row with indexi to vali, overwriting any previous values. +* if typei == 1, set the values in the column with indexi to vali, overwriting any previous values. + +Return _the sum of integers in the matrix after all queries are applied_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/05/11/exm1.png) + +**Input:** n = 3, queries = \[\[0,0,1],[1,2,2],[0,2,3],[1,0,4]] + +**Output:** 23 + +**Explanation:** The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 23. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/05/11/exm2.png) + +**Input:** n = 3, queries = \[\[0,0,4],[0,1,2],[1,0,1],[0,2,3],[1,2,1]] + +**Output:** 17 + +**Explanation:** The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 17. + +**Constraints:** + +* 1 <= n <= 104 +* 1 <= queries.length <= 5 * 104 +* `queries[i].length == 3` +* 0 <= typei <= 1 +* 0 <= indexi < n +* 0 <= vali <= 105 + +## Solution + +```kotlin +class Solution { + fun matrixSumQueries(n: Int, queries: Array): Long { + val queriedRow = BooleanArray(n) + val queriedCol = BooleanArray(n) + var sum: Long = 0 + var remainingRows = n + var remainingCols = n + for (i in queries.indices.reversed()) { + val type = queries[i][0] + val index = queries[i][1] + val value = queries[i][2] + if (type == 0) { + if (queriedRow[index]) { + continue + } + sum += (value * remainingCols).toLong() + remainingRows-- + queriedRow[index] = true + } else { + if (queriedCol[index]) { + continue + } + sum += (value * remainingRows).toLong() + remainingCols-- + queriedCol[index] = true + } + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2719_count_of_integers/readme.md b/src/main/kotlin/g2701_2800/s2719_count_of_integers/readme.md new file mode 100644 index 00000000..2ec3685d --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2719_count_of_integers/readme.md @@ -0,0 +1,97 @@ +[![](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) + +## 2719\. Count of Integers + +Hard + +You are given two numeric strings `num1` and `num2` and two integers `max_sum` and `min_sum`. We denote an integer `x` to be _good_ if: + +* `num1 <= x <= num2` +* `min_sum <= digit_sum(x) <= max_sum`. + +Return _the number of good integers_. Since the answer may be large, return it modulo 109 + 7. + +Note that `digit_sum(x)` denotes the sum of the digits of `x`. + +**Example 1:** + +**Input:** num1 = "1", num2 = "12", `min_sum` = 1, max\_sum = 8 + +**Output:** 11 + +**Explanation:** There are 11 integers whose sum of digits lies between 1 and 8 are 1,2,3,4,5,6,7,8,10,11, and 12. Thus, we return 11. + +**Example 2:** + +**Input:** num1 = "1", num2 = "5", `min_sum` = 1, max\_sum = 5 + +**Output:** 5 + +**Explanation:** The 5 integers whose sum of digits lies between 1 and 5 are 1,2,3,4, and 5. Thus, we return 5. + +**Constraints:** + +* 1 <= num1 <= num2 <= 1022 +* `1 <= min_sum <= max_sum <= 400` + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + private lateinit var dp: Array>> + private fun countStrings(i: Int, tight1: Boolean, tight2: Boolean, sum: Int, num1: String, num2: String): Int { + if (sum < 0) return 0 + if (i == num2.length) return 1 + if (dp[i][if (tight1) 1 else 0][if (tight2) 1 else 0][sum] != -1) + return dp[i][if (tight1) 1 else 0][if (tight2) 1 else 0][sum] + val lo = if (tight1) num1[i].code - '0'.code else 0 + val hi = if (tight2) num2[i].code - '0'.code else 9 + var count = 0 + for (idx in lo..hi) { + count = ( + count % MOD + countStrings( + i + 1, + tight1 and (idx == lo), tight2 and (idx == hi), + sum - idx, num1, num2 + ) % MOD + ) % MOD + } + return count.also { dp[i][if (tight1) 1 else 0][if (tight2) 1 else 0][sum] = it } + } + + fun count(num1: String, num2: String, minSum: Int, maxSum: Int): Int { + val maxLength = num2.length + val minLength = num1.length + val leadingZeroes = maxLength - minLength + val num1extended: String = "0".repeat(leadingZeroes) + num1 + dp = Array(maxLength) { + Array(2) { + Array(2) { + IntArray(401) + } + } + } + for (dim1 in dp) { + for (dim2 in dim1) { + for (dim3 in dim2) { + Arrays.fill(dim3, -1) + } + } + } + val total = countStrings(0, true, true, maxSum, num1extended, num2) + val unnecessary = countStrings(0, true, true, minSum - 1, num1extended, num2) + var ans = (total - unnecessary) % MOD + if (ans < 0) { + ans += MOD + } + return ans + } + + companion object { + private const val MOD = 1e9.toInt() + 7 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2721_execute_asynchronous_functions_in_parallel/readme.md b/src/main/kotlin/g2701_2800/s2721_execute_asynchronous_functions_in_parallel/readme.md new file mode 100644 index 00000000..2ba721b9 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2721_execute_asynchronous_functions_in_parallel/readme.md @@ -0,0 +1,95 @@ +[![](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) + +## 2721\. Execute Asynchronous Functions in Parallel + +Medium + +Given an array of asynchronous functions `functions`, return a new promise `promise`. Each function in the array accepts no arguments and returns a promise. + +`promise` resolves: + +* When all the promises returned from `functions` were resolved successfully. The resolved value of `promise` should be an array of all the resolved values of promises in the same order as they were in the `functions`. + +`promise` rejects: + +* When any of the promises returned from `functions` were rejected. `promise` should also reject with the reason of the first rejection. + +Please solve it without using the built-in `Promise.all` function. + +**Example 1:** + +**Input:** + + functions = [ + () => new Promise(resolve => setTimeout(() => resolve(5), 200)) + ] + +**Output:** {"t": 200, "resolved": [5]} + +**Explanation:** promiseAll(functions).then(console.log); // [5] The single function was resolved at 200ms with a value of 5. + +**Example 2:** + +**Input:** + + functions = [ + () => new Promise(resolve => setTimeout(() => resolve(1), 200)), + () => new Promise((resolve, reject) => setTimeout(() => reject("Error"), 100)) + ] + +**Output:** {"t": 100, "rejected": "Error"} + +**Explanation:** Since one of the promises rejected, the returned promise also rejected with the same error at the same time. + +**Example 3:** + +**Input:** + + functions = [ + () => new Promise(resolve => setTimeout(() => resolve(4), 50)), + () => new Promise(resolve => setTimeout(() => resolve(10), 150)), + () => new Promise(resolve => setTimeout(() => resolve(16), 100)) + ] + +**Output:** {"t": 150, "resolved": [4, 10, 16]} + +**Explanation:** All the promises resolved with a value. The returned promise resolved when the last promise resolved. + +**Constraints:** + +* `functions is an array of functions that returns promises` +* `1 <= functions.length <= 10` + +## Solution + +```typescript +async function promiseAll(functions: (() => Promise)[]): Promise { + const resolved = [] + let counter = 0 + + return new Promise((resolve, reject) => { + for (let i = 0; i < functions.length; i++) { + functions[i]() + .then((res) => { + // must specify index of array + resolved[i] = res + counter++ + if (counter === functions.length) { + resolve(resolved) + } + }) + .catch((err) => { + reject(err) + }) + } + }) +} + +/* + * const promise = promiseAll([() => new Promise(res => res(42))]) + * promise.then(console.log); // [42] + */ + +export { promiseAll } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2722_join_two_arrays_by_id/readme.md b/src/main/kotlin/g2701_2800/s2722_join_two_arrays_by_id/readme.md new file mode 100644 index 00000000..a42402ef --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2722_join_two_arrays_by_id/readme.md @@ -0,0 +1,109 @@ +[![](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) + +## 2722\. Join Two Arrays by ID + +Medium + +Given two arrays `arr1` and `arr2`, return a new array `joinedArray`. All the objects in each of the two inputs arrays will contain an `id` field that has an integer value. `joinedArray` is an array formed by merging `arr1` and `arr2` based on their `id` key. The length of `joinedArray` should be the length of unique values of `id`. The returned array should be sorted in **ascending** order based on the `id` key. + +If a given `id` exists in one array but not the other, the single object with that `id` should be included in the result array without modification. + +If two objects share an `id`, their properties should be merged into a single object: + +* If a key only exists in one object, that single key-value pair should be included in the object. +* If a key is included in both objects, the value in the object from `arr2` should override the value from `arr1`. + +**Example 1:** + +**Input:** + + arr1 = [ + {"id": 1, "x": 1}, + {"id": 2, "x": 9} + ], + arr2 = [ + {"id": 3, "x": 5} + ] + +**Output:** + + [ + {"id": 1, "x": 1}, + {"id": 2, "x": 9}, + {"id": 3, "x": 5} + ] + +**Explanation:** There are no duplicate ids so arr1 is simply concatenated with arr2. + +**Example 2:** + +**Input:** + + arr1 = [ + {"id": 1, "x": 2, "y": 3}, + {"id": 2, "x": 3, "y": 6} + ], + arr2 = [ + {"id": 2, "x": 10, "y": 20}, + {"id": 3, "x": 0, "y": 0} + ] + +**Output:** + + [ + {"id": 1, "x": 2, "y": 3}, + {"id": 2, "x": 10, "y": 20}, + {"id": 3, "x": 0, "y": 0} + ] + +**Explanation:** The two objects with id=1 and id=3 are included in the result array without modifiction. The two objects with id=2 are merged together. The keys from arr2 override the values in arr1. + +**Example 3:** + +**Input:** + + arr1 = [ + {"id": 1, "b": {"b": 94},"v": [4, 3], "y": 48} + ] + arr2 = [ + {"id": 1, "b": {"c": 84}, "v": [1, 3]} + ] + +**Output:** + + [ + {"id": 1, "b": {"c": 84}, "v": [1, 3], "y": 48} + ] + +**Explanation:** The two objects with id=1 are merged together. For the keys "b" and "v" the values from arr2 are used. Since the key "y" only exists in arr1, that value is taken form arr1. + +**Constraints:** + +* `arr1 and arr2 are valid JSON arrays` +* `Each object in arr1 and arr2 has a unique integer id key` +* 2 <= JSON.stringify(arr1).length <= 106 +* 2 <= JSON.stringify(arr2).length <= 106 + +## Solution + +```typescript +function join(arr1: any[], arr2: any[]): any[] { + const result: any = {} + for (let obj of arr1) { + result[obj.id] = obj + } + for (let obj of arr2) { + if (result[obj.id]) { + for (let key in obj) { + result[obj.id][key] = obj[key] + } + } else { + result[obj.id] = obj + } + } + return Object.values(result) +} + +export { join } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2723_add_two_promises/readme.md b/src/main/kotlin/g2701_2800/s2723_add_two_promises/readme.md new file mode 100644 index 00000000..d41a9f9a --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2723_add_two_promises/readme.md @@ -0,0 +1,47 @@ +[![](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) + +## 2723\. Add Two Promises + +Easy + +Given two promises `promise1` and `promise2`, return a new promise. `promise1` and `promise2` will both resolve with a number. The returned promise should resolve with the sum of the two numbers. + +**Example 1:** + +**Input:** promise1 = new Promise(resolve => setTimeout(() => resolve(2), 20)), + +promise2 = new Promise(resolve => setTimeout(() => resolve(5), 60)) + +**Output:** 7 + +**Explanation:** The two input promises resolve with the values of 2 and 5 respectively. The returned promise should resolve with a value of 2 + 5 = 7. The time the returned promise resolves is not judged for this problem. + +**Example 2:** + +**Input:** promise1 = new Promise(resolve => setTimeout(() => resolve(10), 50)), + +promise2 = new Promise(resolve => setTimeout(() => resolve(-12), 30)) + +**Output:** -2 + +**Explanation:** The two input promises resolve with the values of 10 and -12 respectively. The returned promise should resolve with a value of 10 + -12 = -2. + +**Constraints:** + +* `promise1 and promise2 are promises that resolve with a number` + +## Solution + +```typescript +async function addTwoPromises(promise1: Promise, promise2: Promise): Promise { + return (await promise1) + (await promise2) +} + +/* + * addTwoPromises(Promise.resolve(2), Promise.resolve(2)) + * .then(console.log); // 4 + */ + +export { addTwoPromises } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2724_sort_by/readme.md b/src/main/kotlin/g2701_2800/s2724_sort_by/readme.md new file mode 100644 index 00000000..6148fb42 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2724_sort_by/readme.md @@ -0,0 +1,53 @@ +[![](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) + +## 2724\. Sort By + +Easy + +Given an array `arr` and a function `fn`, return a sorted array `sortedArr`. You can assume `fn` only returns numbers and those numbers determine the sort order of `sortedArr`. `sortedArray` must be sorted in **ascending order** by `fn` output. + +You may assume that `fn` will never duplicate numbers for a given array. + +**Example 1:** + +**Input:** arr = [5, 4, 1, 2, 3], fn = (x) => x + +**Output:** [1, 2, 3, 4, 5] + +**Explanation:** fn simply returns the number passed to it so the array is sorted in ascending order. + +**Example 2:** + +**Input:** arr = [{"x": 1}, {"x": 0}, {"x": -1}], fn = (d) => d.x + +**Output:** [{"x": -1}, {"x": 0}, {"x": 1}] + +**Explanation:** fn returns the value for the "x" key. So the array is sorted based on that value. + +**Example 3:** + +**Input:** arr = \[\[3, 4], [5, 2], [10, 1]], fn = (x) => x[1] + +**Output:** [[10, 1], [5, 2], [3, 4]] + +**Explanation:** arr is sorted in ascending order by number at index=1. + +**Constraints:** + +* `arr is a valid JSON array` +* `fn is a function that returns a number` +* 1 <= arr.length <= 5 * 105 + +## Solution + +```typescript +function sortBy(arr: any[], fn: Function): any[] { + let swap: any = (a: any, b: any) => { + return fn(a) < fn(b) ? -1 : 1 + } + return arr.sort(swap) +} + +export { sortBy } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2725_interval_cancellation/readme.md b/src/main/kotlin/g2701_2800/s2725_interval_cancellation/readme.md new file mode 100644 index 00000000..8b0e34e3 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2725_interval_cancellation/readme.md @@ -0,0 +1,166 @@ +[![](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) + +## 2725\. Interval Cancellation + +Easy + +Given a function `fn`, an array of arguments `args`, and an interval time `t`, return a cancel function `cancelFn`. + +The function `fn` should be called with `args` immediately and then called again every `t` milliseconds until `cancelFn` is called at `cancelT` ms. + +**Example 1:** + +**Input:** fn = (x) => x * 2, args = [4], t = 20, cancelT = 110 + +**Output:** + + [ + {"time": 0, "returned": 8}, + {"time": 20, "returned": 8}, + {"time": 40, "returned": 8}, + {"time": 60, "returned": 8}, + {"time": 80, "returned": 8}, + {"time": 100, "returned": 8} + ] + +**Explanation:** + + const cancel = cancellable(x => x * 2, [4], 20); + setTimeout(cancel, 110); + +Every 20ms, fn(4) is called. Until t=110ms, then it is cancelled. + +1st fn call is at 0ms. fn(4) returns 8. + +2nd fn call is at 20ms. fn(4) returns 8. + +3rd fn call is at 40ms. fn(4) returns 8. + +4th fn call is at 60ms. fn(4) returns 8. + +5th fn call is at 80ms. fn(4) returns 8. + +6th fn call is at 100ms. fn(4) returns 8. + +Cancelled at 110ms + +**Example 2:** + +**Input:** fn = (x1, x2) => (x1 * x2), args = [2, 5], t = 25, cancelT = 140 + +**Output:** + + [ + {"time": 0, "returned": 10}, + {"time": 25, "returned": 10}, + {"time": 50, "returned": 10}, + {"time": 75, "returned": 10}, + {"time": 100, "returned": 10}, + {"time": 125, "returned": 10} + ] + +**Explanation:** + + const cancel = cancellable((x1, x2) => (x1 * x2), [2, 5], 25); + setTimeout(cancel, 140); + +Every 25ms, fn(2, 5) is called. Until t=140ms, then it is cancelled. + +1st fn call is at 0ms + +2nd fn call is at 25ms + +3rd fn call is at 50ms + +4th fn call is at 75ms + +5th fn call is at 100ms + +6th fn call is at 125ms + +Cancelled at 140ms + +**Example 3:** + +**Input:** fn = (x1, x2, x3) => (x1 + x2 + x3), args = [5, 1, 3], t = 50, cancelT = 180 + +**Output:** + + [ + {"time": 0, "returned": 9}, + {"time": 50, "returned": 9}, + {"time": 100, "returned": 9}, + {"time": 150, "returned": 9} + ] + +**Explanation:** + + const cancel = cancellable((x1, x2, x3) => (x1 + x2 + x3), [5, 1, 3], 50); + setTimeout(cancel, 180); + +Every 50ms, fn(5, 1, 3) is called. Until t=180ms, then it is cancelled. + +1st fn call is at 0ms + +2nd fn call is at 50ms + +3rd fn call is at 100ms + +4th fn call is at 150ms + +Cancelled at 180ms + +**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 { + fn(...args) + const timer = setInterval(() => { + fn(...args) + }, t) + + return () => clearTimeout(timer) +} + +/* + * const result = [] + * + * const fn = (x) => x * 2 + * const args = [4], t = 20, cancelT = 110 + * + * 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); + * + * setTimeout(() => { + * cancel() + * }, cancelT) + * + * setTimeout(() => { + * console.log(result) // [ + * // {"time":0,"returned":8}, + * // {"time":20,"returned":8}, + * // {"time":40,"returned":8}, + * // {"time":60,"returned":8}, + * // {"time":80,"returned":8}, + * // {"time":100,"returned":8} + * // ] + * }, cancelT + t + 15) + */ + +export { cancellable } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2726_calculator_with_method_chaining/readme.md b/src/main/kotlin/g2701_2800/s2726_calculator_with_method_chaining/readme.md new file mode 100644 index 00000000..2244d0b2 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2726_calculator_with_method_chaining/readme.md @@ -0,0 +1,95 @@ +[![](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) + +## 2726\. Calculator with Method Chaining + +Easy + +Design a `Calculator` class. The class should provide the mathematical operations of addition, subtraction, multiplication, division, and exponentiation. It should also allow consecutive operations to be performed using method chaining. The `Calculator` class constructor should accept a number which serves as the initial value of `result`. + +Your `Calculator` class should have the following methods: + +* `add` - This method adds the given number `value` to the `result` and returns the updated `Calculator`. +* `subtract` - This method subtracts the given number `value` from the `result` and returns the updated `Calculator`. +* `multiply` - This method multiplies the `result` by the given number `value` and returns the updated `Calculator`. +* `divide` - This method divides the `result` by the given number `value` and returns the updated `Calculator`. If the passed value is `0`, an error `"Division by zero is not allowed"` should be thrown. +* `power` - This method raises the `result` to the power of the given number `value` and returns the updated `Calculator`. +* `getResult` - This method returns the `result`. + +Solutions within 10-5 of the actual result are considered correct. + +**Example 1:** + +**Input:** actions = ["Calculator", "add", "subtract", "getResult"], values = [10, 5, 7] + +**Output:** 8 + +**Explanation:** new Calculator(10).add(5).subtract(7).getResult() // 10 + 5 - 7 = 8 + +**Example 2:** + +**Input:** actions = ["Calculator", "multiply", "power", "getResult"], values = [2, 5, 2] + +**Output:** 100 + +**Explanation:** new Calculator(2).multiply(5).power(2).getResult() // (2 \* 5) ^ 2 = 100 + +**Example 3:** + +**Input:** actions = ["Calculator", "divide", "getResult"], values = [20, 0] + +**Output:** "Division by zero is not allowed" + +**Explanation:** new Calculator(20).divide(0).getResult() // 20 / 0 The error should be thrown because we cannot divide by zero. + +**Constraints:** + +* 2 <= actions.length <= 2 * 104 +* 1 <= values.length <= 2 * 104 - 1 +* `actions[i] is one of "Calculator", "add", "subtract", "multiply", "divide", "power", and "getResult"` +* `Last action is always "getResult"` +* `values is a JSON array of numbers` + +## Solution + +```typescript +class Calculator { + init: number + + constructor(value: number) { + this.init = value + } + + add(value: number): Calculator { //NOSONAR + this.init += value + return this + } + + subtract(value: number): Calculator { //NOSONAR + this.init -= value + return this + } + + multiply(value: number): Calculator { //NOSONAR + this.init *= value + return this + } + + divide(value: number): Calculator { //NOSONAR + if (value === 0) throw Error('Division by zero is not allowed') + this.init /= value + return this + } + + power(value: number): Calculator { //NOSONAR + this.init = this.init ** value + return this + } + + getResult(): number { + return this.init + } +} + +export { Calculator } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2727_is_object_empty/readme.md b/src/main/kotlin/g2701_2800/s2727_is_object_empty/readme.md new file mode 100644 index 00000000..62f57c40 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2727_is_object_empty/readme.md @@ -0,0 +1,53 @@ +[![](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) + +## 2727\. Is Object Empty + +Easy + +Given an object or an array, return if it is empty. + +* An empty object contains no key-value pairs. +* An empty array contains no elements. + +You may assume the object or array is the output of `JSON.parse`. + +**Example 1:** + +**Input:** obj = {"x": 5, "y": 42} + +**Output:** false + +**Explanation:** The object has 2 key-value pairs so it is not empty. + +**Example 2:** + +**Input:** obj = {} + +**Output:** true + +**Explanation:** The object doesn't have any key-value pairs so it is empty. + +**Example 3:** + +**Input:** obj = [null, false, 0] + +**Output:** false + +**Explanation:** The array has 3 elements so it is not empty. + +**Constraints:** + +* 2 <= JSON.stringify(obj).length <= 105 + +**Can you solve it in O(1) time?** + +## Solution + +```typescript +function isEmpty(obj: Record | any[]): boolean { + return Object.keys(obj).length === 0 +} + +export { isEmpty } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2729_check_if_the_number_is_fascinating/readme.md b/src/main/kotlin/g2701_2800/s2729_check_if_the_number_is_fascinating/readme.md new file mode 100644 index 00000000..86a08335 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2729_check_if_the_number_is_fascinating/readme.md @@ -0,0 +1,62 @@ +[![](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) + +## 2729\. Check if The Number is Fascinating + +Easy + +You are given an integer `n` that consists of exactly `3` digits. + +We call the number `n` **fascinating** if, after the following modification, the resulting number contains all the digits from `1` to `9` **exactly** once and does not contain any `0`'s: + +* **Concatenate** `n` with the numbers `2 * n` and `3 * n`. + +Return `true` _if_ `n` _is fascinating, or_ `false` _otherwise_. + +**Concatenating** two numbers means joining them together. For example, the concatenation of `121` and `371` is `121371`. + +**Example 1:** + +**Input:** n = 192 + +**Output:** true + +**Explanation:** We concatenate the numbers n = 192 and 2 \* n = 384 and 3 \* n = 576. The resulting number is 192384576. This number contains all the digits from 1 to 9 exactly once. + +**Example 2:** + +**Input:** n = 100 + +**Output:** false + +**Explanation:** We concatenate the numbers n = 100 and 2 \* n = 200 and 3 \* n = 300. The resulting number is 100200300. This number does not satisfy any of the conditions. + +**Constraints:** + +* `100 <= n <= 999` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun isFascinating(n: Int): Boolean { + val set = HashSet() + fun add(_cur: Int): Boolean { + var cur = _cur + while (cur > 0) { + val n = cur % 10 + if (n == 0 || set.contains(n)) + return false + set.add(n) + cur /= 10 + } + return true + } + + if (!add(n) || !add(2 * n) || !add(3 * n)) + return false + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2730_find_the_longest_semi_repetitive_substring/readme.md b/src/main/kotlin/g2701_2800/s2730_find_the_longest_semi_repetitive_substring/readme.md new file mode 100644 index 00000000..1d59be37 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2730_find_the_longest_semi_repetitive_substring/readme.md @@ -0,0 +1,62 @@ +[![](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) + +## 2730\. Find the Longest Semi-Repetitive Substring + +Medium + +You are given a **0-indexed** string `s` that consists of digits from `0` to `9`. + +A string `t` is called a **semi-repetitive** if there is at most one consecutive pair of the same digits inside `t`. For example, `0010`, `002020`, `0123`, `2002`, and `54944` are semi-repetitive while `00101022`, and `1101234883` are not. + +Return _the length of the longest semi-repetitive substring inside_ `s`. + +A **substring** is a contiguous **non-empty** sequence of characters within a string. + +**Example 1:** + +**Input:** s = "52233" + +**Output:** 4 + +**Explanation:** The longest semi-repetitive substring is "5223", which starts at i = 0 and ends at j = 3. + +**Example 2:** + +**Input:** s = "5494" + +**Output:** 4 + +**Explanation:** s is a semi-reptitive string, so the answer is 4. + +**Example 3:** + +**Input:** s = "1111111" + +**Output:** 2 + +**Explanation:** The longest semi-repetitive substring is "11", which starts at i = 0 and ends at j = 1. + +**Constraints:** + +* `1 <= s.length <= 50` +* `'0' <= s[i] <= '9'` + +## Solution + +```kotlin +class Solution { + fun longestSemiRepetitiveSubstring(s: String): Int { + var i = 0 + var cur = 0 + val n = s.length + for (j in 1 until n) { + cur += if (s[j] == s[j - 1]) 1 else 0 + if (cur > 1) { + cur -= if (s[++i] == s[i - 1]) 1 else 0 + } + } + return n - i + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2731_movement_of_robots/readme.md b/src/main/kotlin/g2701_2800/s2731_movement_of_robots/readme.md new file mode 100644 index 00000000..8870c167 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2731_movement_of_robots/readme.md @@ -0,0 +1,83 @@ +[![](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) + +## 2731\. Movement of Robots + +Medium + +Some robots are standing on an infinite number line with their initial coordinates given by a **0-indexed** integer array `nums` and will start moving once given the command to move. The robots will move a unit distance each second. + +You are given a string `s` denoting the direction in which robots will move on command. `'L'` means the robot will move towards the left side or negative side of the number line, whereas `'R'` means the robot will move towards the right side or positive side of the number line. + +If two robots collide, they will start moving in opposite directions. + +Return _the sum of distances between all the pairs of robots_ `d` _seconds after the command._ Since the sum can be very large, return it modulo 109 + 7. + +**Note:** + +* For two robots at the index `i` and `j`, pair `(i,j)` and pair `(j,i)` are considered the same pair. +* When robots collide, they **instantly change** their directions without wasting any time. +* Collision happens when two robots share the same place in a moment. + * For example, if a robot is positioned in 0 going to the right and another is positioned in 2 going to the left, the next second they'll be both in 1 and they will change direction and the next second the first one will be in 0, heading left, and another will be in 2, heading right. + * For example, if a robot is positioned in 0 going to the right and another is positioned in 1 going to the left, the next second the first one will be in 0, heading left, and another will be in 1, heading right. + +**Example 1:** + +**Input:** nums = [-2,0,2], s = "RLL", d = 3 + +**Output:** 8 + +**Explanation:** + +After 1 second, the positions are [-1,-1,1]. Now, the robot at index 0 will move left, and the robot at index 1 will move right. + +After 2 seconds, the positions are [-2,0,0]. Now, the robot at index 1 will move left, and the robot at index 2 will move right. + +After 3 seconds, the positions are [-3,-1,1]. + +The distance between the robot at index 0 and 1 is abs(-3 - (-1)) = 2. + +The distance between the robot at index 0 and 2 is abs(-3 - 1) = 4. + +The distance between the robot at index 1 and 2 is abs(-1 - 1) = 2. + +The sum of the pairs of all distances = 2 + 4 + 2 = 8. + +**Example 2:** + +**Input:** nums = [1,0], s = "RL", d = 2 + +**Output:** 5 + +**Explanation:** + +After 1 second, the positions are [2,-1]. + +After 2 seconds, the positions are [3,-2]. + +The distance between the two robots is abs(-2 - 3) = 5. + +**Constraints:** + +* 2 <= nums.length <= 105 +* -2 * 109 <= nums[i] <= 2 * 109 +* 0 <= d <= 109 +* `nums.length == s.length` +* `s` consists of 'L' and 'R' only +* `nums[i]` will be unique. + +## Solution + +```kotlin +class Solution { + fun sumDistance(nums: IntArray, s: String, d: Int): Int { + val n = nums.size + val mod = 1e9.toInt() + 7 + for (i in 0 until n) nums[i] += if (s[i] == 'R') d else -d + nums.sort() + var res: Long = 0 + for (i in 0 until n) res = (res + (1L + i + i - n) * nums[i]) % mod + return (res + mod).toInt() % mod + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2732_find_a_good_subset_of_the_matrix/readme.md b/src/main/kotlin/g2701_2800/s2732_find_a_good_subset_of_the_matrix/readme.md new file mode 100644 index 00000000..c88780ca --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2732_find_a_good_subset_of_the_matrix/readme.md @@ -0,0 +1,92 @@ +[![](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) + +## 2732\. Find a Good Subset of the Matrix + +Hard + +You are given a **0-indexed** `m x n` binary matrix `grid`. + +Let us call a **non-empty** subset of rows **good** if the sum of each column of the subset is at most half of the length of the subset. + +More formally, if the length of the chosen subset of rows is `k`, then the sum of each column should be at most `floor(k / 2)`. + +Return _an integer array that contains row indices of a good subset sorted in **ascending** order._ + +If there are multiple good subsets, you can return any of them. If there are no good subsets, return an empty array. + +A **subset** of rows of the matrix `grid` is any matrix that can be obtained by deleting some (possibly none or all) rows from `grid`. + +**Example 1:** + +**Input:** grid = \[\[0,1,1,0],[0,0,0,1],[1,1,1,1]] + +**Output:** [0,1] + +**Explanation:** We can choose the 0th and 1st rows to create a good subset of rows. The length of the chosen subset is 2. +- The sum of the 0th column is 0 + 0 = 0, which is at most half of the length of the subset. +- The sum of the 1st column is 1 + 0 = 1, which is at most half of the length of the subset. +- The sum of the 2nd column is 1 + 0 = 1, which is at most half of the length of the subset. +- The sum of the 3rd column is 0 + 1 = 1, which is at most half of the length of the subset. + +**Example 2:** + +**Input:** grid = \[\[0]] + +**Output:** [0] + +**Explanation:** We can choose the 0th row to create a good subset of rows. The length of the chosen subset is 1. +- The sum of the 0th column is 0, which is at most half of the length of the subset. + +**Example 3:** + +**Input:** grid = \[\[1,1,1],[1,1,1]] + +**Output:** [] + +**Explanation:** It is impossible to choose any subset of rows to create a good subset. + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* 1 <= m <= 104 +* `1 <= n <= 5` +* `grid[i][j]` is either `0` or `1`. + +## Solution + +```kotlin +class Solution { + fun goodSubsetofBinaryMatrix(grid: Array): List { + val m = grid.size + val n = grid[0].size + if (m == 1 && grid[0].sum() == 0) { + return listOf(0) + } + val pos = mutableMapOf() + for (i in grid.indices) { + for (mask in 0 until (1 shl n)) { + var valid = true + for (j in 0 until n) { + if ((mask and (1 shl j)) != 0 && grid[i][j] + 1 > 1) { + valid = false + break + } + } + if (valid && mask in pos) { + return listOf(pos[mask]!!, i) + } + } + var curr = 0 + for (j in 0 until n) { + if (grid[i][j] == 1) { + curr = curr or (1 shl j) + } + } + pos[curr] = i + } + return emptyList() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2733_neither_minimum_nor_maximum/readme.md b/src/main/kotlin/g2701_2800/s2733_neither_minimum_nor_maximum/readme.md new file mode 100644 index 00000000..5da19b8d --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2733_neither_minimum_nor_maximum/readme.md @@ -0,0 +1,59 @@ +[![](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) + +## 2733\. Neither Minimum nor Maximum + +Easy + +Given an integer array `nums` containing **distinct** **positive** integers, find and return **any** number from the array that is neither the **minimum** nor the **maximum** value in the array, or **`-1`** if there is no such number. + +Return _the selected integer._ + +**Example 1:** + +**Input:** nums = [3,2,1,4] + +**Output:** 2 + +**Explanation:** In this example, the minimum value is 1 and the maximum value is 4. Therefore, either 2 or 3 can be valid answers. + +**Example 2:** + +**Input:** nums = [1,2] + +**Output:** -1 + +**Explanation:** Since there is no number in nums that is neither the maximum nor the minimum, we cannot select a number that satisfies the given condition. Therefore, there is no answer. + +**Example 3:** + +**Input:** nums = [2,1,3] + +**Output:** 2 + +**Explanation:** Since 2 is neither the maximum nor the minimum value in nums, it is the only valid answer. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `1 <= nums[i] <= 100` +* All values in `nums` are distinct + +## Solution + +```kotlin +class Solution { + fun findNonMinOrMax(nums: IntArray): Int { + var mn = 999 + var mx: Int = -1 + nums.forEach { + mn = kotlin.math.min(it, mn) + mx = kotlin.math.max(it, mx) + } + nums.forEach { + if (it != mn && it != mx)return it + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2734_lexicographically_smallest_string_after_substring_operation/readme.md b/src/main/kotlin/g2701_2800/s2734_lexicographically_smallest_string_after_substring_operation/readme.md new file mode 100644 index 00000000..83aedcd9 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2734_lexicographically_smallest_string_after_substring_operation/readme.md @@ -0,0 +1,87 @@ +[![](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) + +## 2734\. Lexicographically Smallest String After Substring Operation + +Medium + +You are given a string `s` consisting of only lowercase English letters. In one operation, you can do the following: + +* Select any non-empty substring of `s`, possibly the entire string, then replace each one of its characters with the previous character of the English alphabet. For example, 'b' is converted to 'a', and 'a' is converted to 'z'. + +Return _the **lexicographically smallest** string you can obtain after performing the above operation **exactly once**._ + +A **substring** is a contiguous sequence of characters in a string. + +A string `x` is **lexicographically smaller** than a string `y` of the same length if `x[i]` comes before `y[i]` in alphabetic order for the first position `i` such that `x[i] != y[i]`. + +**Example 1:** + +**Input:** s = "cbabc" + +**Output:** "baabc" + +**Explanation:** We apply the operation on the substring starting at index 0, and ending at index 1 inclusive. It can be proven that the resulting string is the lexicographically smallest. + +**Example 2:** + +**Input:** s = "acbbc" + +**Output:** "abaab" + +**Explanation:** We apply the operation on the substring starting at index 1, and ending at index 4 inclusive. It can be proven that the resulting string is the lexicographically smallest. + +**Example 3:** + +**Input:** s = "leetcode" + +**Output:** "kddsbncd" + +**Explanation:** We apply the operation on the entire string. It can be proven that the resulting string is the lexicographically smallest. + +**Constraints:** + +* 1 <= s.length <= 3 * 105 +* `s` consists of lowercase English letters + +## Solution + +```kotlin +class Solution { + fun smallestString(s: String): String { + var resultArray = CharArray(s.length) + var found = false + var i = 0 + while (i < s.length) { + var c = s[i] + if (c != 'a' && !found) { + found = true + while (i < s.length) { + c = s[i] + if (c != 'a') { + c-- + resultArray[i] = c + } else { + i-- + break + } + i++ + } + } else { + resultArray[i] = c + } + i++ + } + if (!found) { + resultArray = CharArray(s.length) + i = 0 + while (i < s.length - 1) { + resultArray[i] = 'a' + i++ + } + resultArray[s.length - 1] = 'z' + } + return String(resultArray) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2735_collecting_chocolates/readme.md b/src/main/kotlin/g2701_2800/s2735_collecting_chocolates/readme.md new file mode 100644 index 00000000..69b1f46a --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2735_collecting_chocolates/readme.md @@ -0,0 +1,68 @@ +[![](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) + +## 2735\. Collecting Chocolates + +Medium + +You are given a **0-indexed** integer array `nums` of size `n` representing the cost of collecting different chocolates. The cost of collecting the chocolate at the index `i` is `nums[i]`. Each chocolate is of a different type, and initially, the chocolate at the index `i` is of ith type. + +In one operation, you can do the following with an incurred **cost** of `x`: + +* Simultaneously change the chocolate of ith type to ((i + 1) mod n)th type for all chocolates. + +Return _the minimum cost to collect chocolates of all types, given that you can perform as many operations as you would like._ + +**Example 1:** + +**Input:** nums = [20,1,15], x = 5 + +**Output:** 13 + +**Explanation:** Initially, the chocolate types are [0,1,2]. We will buy the 1st type of chocolate at a cost of 1. + +Now, we will perform the operation at a cost of 5, and the types of chocolates will become [1,2,0]. We will buy the 2nd type of chocolate at a cost of 1. + +Now, we will again perform the operation at a cost of 5, and the chocolate types will become [2,0,1]. We will buy the 0th type of chocolate at a cost of 1. + +Thus, the total cost will become (1 + 5 + 1 + 5 + 1) = 13. We can prove that this is optimal. + +**Example 2:** + +**Input:** nums = [1,2,3], x = 4 + +**Output:** 6 + +**Explanation:** We will collect all three types of chocolates at their own price without performing any operations. Therefore, the total cost is 1 + 2 + 3 = 6. + +**Constraints:** + +* `1 <= nums.length <= 1000` +* 1 <= nums[i] <= 109 +* 1 <= x <= 109 + +## Solution + +```kotlin +class Solution { + fun minCost(nums: IntArray, x: Int): Long { + val n = nums.size + val dp = IntArray(n) + var res: Long = 0 + for (i in 0 until n) { + dp[i] = nums[i] + res += nums[i].toLong() + } + for (i in 1 until n) { + var sum: Long = i.toLong() * x.toLong() + for (j in 0 until n) { + val currIndex: Int = if (j + i >= n) j + i - n else j + i + dp[j] = dp[j].coerceAtMost(nums[currIndex]) + sum += dp[j].toLong() + } + res = res.coerceAtMost(sum) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2736_maximum_sum_queries/readme.md b/src/main/kotlin/g2701_2800/s2736_maximum_sum_queries/readme.md new file mode 100644 index 00000000..e911f044 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2736_maximum_sum_queries/readme.md @@ -0,0 +1,110 @@ +[![](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) + +## 2736\. Maximum Sum Queries + +Hard + +You are given two **0-indexed** integer arrays `nums1` and `nums2`, each of length `n`, and a **1-indexed 2D array** `queries` where queries[i] = [xi, yi]. + +For the ith query, find the **maximum value** of `nums1[j] + nums2[j]` among all indices `j` `(0 <= j < n)`, where nums1[j] >= xi and nums2[j] >= yi, or **\-1** if there is no `j` satisfying the constraints. + +Return _an array_ `answer` _where_ `answer[i]` _is the answer to the_ ith _query._ + +**Example 1:** + +**Input:** nums1 = [4,3,1,2], nums2 = [2,4,9,5], queries = \[\[4,1],[1,3],[2,5]] + +**Output:** [6,10,7] + +**Explanation:** + +For the 1st query xi = 4 and yi = 1, we can select index `j = 0` since `nums1[j] >= 4` and `nums2[j] >= 1`. The sum `nums1[j] + nums2[j]` is 6, and we can show that 6 is the maximum we can obtain. + +For the 2nd query xi = 1 and yi = 3, we can select index `j = 2` since `nums1[j] >= 1` and `nums2[j] >= 3`. The sum `nums1[j] + nums2[j]` is 10, and we can show that 10 is the maximum we can obtain. + +For the 3rd query xi = 2 and yi = 5, we can select index `j = 3` since `nums1[j] >= 2` and `nums2[j] >= 5`. The sum `nums1[j] + nums2[j]` is 7, and we can show that 7 is the maximum we can obtain. + +Therefore, we return `[6,10,7]`. + +**Example 2:** + +**Input:** nums1 = [3,2,5], nums2 = [2,3,4], queries = \[\[4,4],[3,2],[1,1]] + +**Output:** [9,9,9] + +**Explanation:** For this example, we can use index `j = 2` for all the queries since it satisfies the constraints for each query. + +**Example 3:** + +**Input:** nums1 = [2,1], nums2 = [2,3], queries = \[\[3,3]] + +**Output:** [-1] + +**Explanation:** There is one query in this example with xi = 3 and yi = 3. For every index, j, either nums1[j] < xi or nums2[j] < yi. Hence, there is no solution. + +**Constraints:** + +* `nums1.length == nums2.length` +* `n == nums1.length` +* 1 <= n <= 105 +* 1 <= nums1[i], nums2[i] <= 109 +* 1 <= queries.length <= 105 +* `queries[i].length == 2` +* xi == queries[i][1] +* yi == queries[i][2] +* 1 <= xi, yi <= 109 + +## Solution + +```kotlin +import java.util.TreeMap + +class Solution { + private fun update(map: TreeMap, num: Int, sum: Int) { + var entry = map.floorEntry(num) + while (entry != null && entry.value <= sum) { + map.remove(entry.key) + val x = entry.key + entry = map.floorEntry(x) + } + entry = map.ceilingEntry(num) + if (entry == null || entry.value < sum) map.put(num, sum) + } + + private fun queryVal(map: TreeMap, num: Int): Int { + val (_, value) = map.ceilingEntry(num) ?: return -1 + return value + } + + fun maximumSumQueries(nums1: IntArray, nums2: IntArray, queries: Array): IntArray { + val n = nums1.size + val m = queries.size + val v: MutableList = ArrayList() + for (i in 0 until n) { + v.add(intArrayOf(nums1[i], nums2[i])) + } + v.sortWith( + Comparator { a: IntArray, b: IntArray -> + a[0] - b[0] + } + ) + val ind: MutableList = ArrayList() + for (i in 0 until m) ind.add(i) + ind.sortWith(Comparator { a: Int?, b: Int? -> queries[b!!][0] - queries[a!!][0] }) + val values = TreeMap() + var j = n - 1 + val ans = IntArray(m) + for (i in ind) { + val a = queries[i][0] + val b = queries[i][1] + while (j >= 0 && v[j][0] >= a) { + update(values, v[j][1], v[j][0] + v[j][1]) + j-- + } + ans[i] = queryVal(values, b) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2739_total_distance_traveled/readme.md b/src/main/kotlin/g2701_2800/s2739_total_distance_traveled/readme.md new file mode 100644 index 00000000..076c6433 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2739_total_distance_traveled/readme.md @@ -0,0 +1,54 @@ +[![](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) + +## 2739\. Total Distance Traveled + +Easy + +A truck has two fuel tanks. You are given two integers, `mainTank` representing the fuel present in the main tank in liters and `additionalTank` representing the fuel present in the additional tank in liters. + +The truck has a mileage of `10` km per liter. Whenever `5` liters of fuel get used up in the main tank, if the additional tank has at least `1` liters of fuel, `1` liters of fuel will be transferred from the additional tank to the main tank. + +Return _the maximum distance which can be traveled._ + +**Note:** Injection from the additional tank is not continuous. It happens suddenly and immediately for every 5 liters consumed. + +**Example 1:** + +**Input:** mainTank = 5, additionalTank = 10 + +**Output:** 60 + +**Explanation:** + +After spending 5 litre of fuel, fuel remaining is (5 - 5 + 1) = 1 litre and distance traveled is 50km. + +After spending another 1 litre of fuel, no fuel gets injected in the main tank and the main tank becomes empty. + +Total distance traveled is 60km. + +**Example 2:** + +**Input:** mainTank = 1, additionalTank = 2 + +**Output:** 10 + +**Explanation:** After spending 1 litre of fuel, the main tank becomes empty. Total distance traveled is 10km. + +**Constraints:** + +* `1 <= mainTank, additionalTank <= 100` + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + fun distanceTraveled(mainTank: Int, additionalTank: Int): Int { + val transferableTimes = (mainTank - 1) / 4 + val transferredLiters = min(transferableTimes, additionalTank) + return (mainTank + transferredLiters) * 10 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2740_find_the_value_of_the_partition/readme.md b/src/main/kotlin/g2701_2800/s2740_find_the_value_of_the_partition/readme.md new file mode 100644 index 00000000..e3f3c03a --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2740_find_the_value_of_the_partition/readme.md @@ -0,0 +1,64 @@ +[![](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) + +## 2740\. Find the Value of the Partition + +Medium + +You are given a **positive** integer array `nums`. + +Partition `nums` into two arrays, `nums1` and `nums2`, such that: + +* Each element of the array `nums` belongs to either the array `nums1` or the array `nums2`. +* Both arrays are **non-empty**. +* The value of the partition is **minimized**. + +The value of the partition is `|max(nums1) - min(nums2)|`. + +Here, `max(nums1)` denotes the maximum element of the array `nums1`, and `min(nums2)` denotes the minimum element of the array `nums2`. + +Return _the integer denoting the value of such partition_. + +**Example 1:** + +**Input:** nums = [1,3,2,4] + +**Output:** 1 + +**Explanation:** We can partition the array nums into nums1 = [1,2] and nums2 = [3,4]. +- The maximum element of the array nums1 is equal to 2. +- The minimum element of the array nums2 is equal to 3. + +The value of the partition is \|2 - 3\| = 1. + +It can be proven that 1 is the minimum value out of all partitions. + +**Example 2:** + +**Input:** nums = [100,1,10] + +**Output:** 9 + +**Explanation:** We can partition the array nums into nums1 = [10] and nums2 = [100,1]. +- The maximum element of the array nums1 is equal to 10. +- The minimum element of the array nums2 is equal to 1. + +The value of the partition is \|10 - 1\| = 9. + +It can be proven that 9 is the minimum value out of all partitions. + +**Constraints:** + +* 2 <= nums.length <= 105 +* 1 <= nums[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun findValueOfPartition(nums: IntArray): Int = nums + .sortedDescending() + .zipWithNext(Int::minus) + .min() +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2741_special_permutations/readme.md b/src/main/kotlin/g2701_2800/s2741_special_permutations/readme.md new file mode 100644 index 00000000..a4bb33d0 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2741_special_permutations/readme.md @@ -0,0 +1,86 @@ +[![](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) + +## 2741\. Special Permutations + +Medium + +You are given a **0-indexed** integer array `nums` containing `n` **distinct** positive integers. A permutation of `nums` is called special if: + +* For all indexes `0 <= i < n - 1`, either `nums[i] % nums[i+1] == 0` or `nums[i+1] % nums[i] == 0`. + +Return _the total number of special permutations. _As the answer could be large, return it **modulo **109 + 7. + +**Example 1:** + +**Input:** nums = [2,3,6] + +**Output:** 2 + +**Explanation:** [3,6,2] and [2,6,3] are the two special permutations of nums. + +**Example 2:** + +**Input:** nums = [1,4,3] + +**Output:** 2 + +**Explanation:** [3,1,4] and [4,1,3] are the two special permutations of nums. + +**Constraints:** + +* `2 <= nums.length <= 14` +* 1 <= nums[i] <= 109 + +## Solution + +```kotlin +class Solution { + private var dp = HashMap, Long>() + private var adj = HashMap>() + private var mod = 1000000007 + + private fun count(destIdx: Int, set: Int): Long { + if (Integer.bitCount(set) == 1) return 1 + val p = destIdx to set + if (dp.containsKey(p)) { + return dp[p]!! + } + var sum = 0L + val newSet = set xor (1 shl destIdx) + for (i in adj[destIdx]!!) { + if ((set and (1 shl i)) == 0) continue + sum += count(i, newSet) % mod + sum %= mod + } + dp[p] = sum + return sum + } + + fun specialPerm(nums: IntArray): Int { + for (i in nums.indices) adj[i] = hashSetOf() + for ((i, vI) in nums.withIndex()) { + for ((j, vJ) in nums.withIndex()) { + if (vI != vJ && vI % vJ == 0) { + adj[i]!!.add(j) + adj[j]!!.add(i) + } + } + } + if (adj.all { it.value.size == nums.size - 1 }) { + return (fact(nums.size.toLong()) % mod).toInt() + } + var total = 0 + for (i in nums.indices) { + total += (count(i, (1 shl nums.size) - 1) % mod).toInt() + total %= mod + } + return total + } + + private fun fact(n: Long): Long { + if (n == 1L) return n + return n * fact(n - 1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2742_painting_the_walls/readme.md b/src/main/kotlin/g2701_2800/s2742_painting_the_walls/readme.md new file mode 100644 index 00000000..8a9f4d7b --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2742_painting_the_walls/readme.md @@ -0,0 +1,60 @@ +[![](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) + +## 2742\. Painting the Walls + +Hard + +You are given two **0-indexed** integer arrays, `cost` and `time`, of size `n` representing the costs and the time taken to paint `n` different walls respectively. There are two painters available: + +* A** paid painter** that paints the ith wall in `time[i]` units of time and takes `cost[i]` units of money. +* A** free painter** that paints **any** wall in `1` unit of time at a cost of `0`. But the free painter can only be used if the paid painter is already **occupied**. + +Return _the minimum amount of money required to paint the_ `n` _walls._ + +**Example 1:** + +**Input:** cost = [1,2,3,2], time = [1,2,3,2] + +**Output:** 3 + +**Explanation:** The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3. + +**Example 2:** + +**Input:** cost = [2,3,4,2], time = [1,1,1,1] + +**Output:** 4 + +**Explanation:** The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4. + +**Constraints:** + +* `1 <= cost.length <= 500` +* `cost.length == time.length` +* 1 <= cost[i] <= 106 +* `1 <= time[i] <= 500` + +## Solution + +```kotlin +class Solution { + fun paintWalls(cost: IntArray, time: IntArray): Int { + val n = cost.size + val dp = Array(n + 1) { IntArray(n + 1) } + return solve(n, cost, 0, time, dp) + } + + private fun solve(wallsRem: Int, cost: IntArray, idx: Int, time: IntArray, dp: Array): Int { + if (wallsRem <= 0) return 0 + if (idx >= cost.size) return 1000000000 + if (dp[idx][wallsRem] != 0) { + return dp[idx][wallsRem] + } + val skip = solve(wallsRem, cost, idx + 1, time, dp) + val take = cost[idx] + solve(wallsRem - time[idx] - 1, cost, idx + 1, time, dp) + dp[idx][wallsRem] = skip.coerceAtMost(take) + return dp[idx][wallsRem] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2744_find_maximum_number_of_string_pairs/readme.md b/src/main/kotlin/g2701_2800/s2744_find_maximum_number_of_string_pairs/readme.md new file mode 100644 index 00000000..461d8331 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2744_find_maximum_number_of_string_pairs/readme.md @@ -0,0 +1,75 @@ +[![](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) + +## 2744\. Find Maximum Number of String Pairs + +Easy + +You are given a **0-indexed** array `words` consisting of **distinct** strings. + +The string `words[i]` can be paired with the string `words[j]` if: + +* The string `words[i]` is equal to the reversed string of `words[j]`. +* `0 <= i < j < words.length`. + +Return _the **maximum** number of pairs that can be formed from the array_ `words`_._ + +Note that each string can belong in **at most one** pair. + +**Example 1:** + +**Input:** words = ["cd","ac","dc","ca","zz"] + +**Output:** 2 + +**Explanation:** In this example, we can form 2 pair of strings in the following way: +- We pair the 0th string with the 2nd string, as the reversed string of word[0] is "dc" and is equal to words[2]. +- We pair the 1st string with the 3rd string, as the reversed string of word[1] is "ca" and is equal to words[3]. + +It can be proven that 2 is the maximum number of pairs that can be formed. + +**Example 2:** + +**Input:** words = ["ab","ba","cc"] + +**Output:** 1 + +**Explanation:** In this example, we can form 1 pair of strings in the following way: +- We pair the 0th string with the 1st string, as the reversed string of words[1] is "ab" and is equal to words[0]. + +It can be proven that 1 is the maximum number of pairs that can be formed. + +**Example 3:** + +**Input:** words = ["aa","ab"] + +**Output:** 0 + +**Explanation:** In this example, we are unable to form any pair of strings. + +**Constraints:** + +* `1 <= words.length <= 50` +* `words[i].length == 2` +* `words` consists of distinct strings. +* `words[i]` contains only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun maximumNumberOfStringPairs(words: Array): Int { + val set: MutableSet = HashSet() + var cnt = 0 + for (s in words) { + val sb = StringBuilder(s).reverse() + if (set.contains(sb.toString())) { + cnt++ + } else { + set.add(s) + } + } + return cnt + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2745_construct_the_longest_new_string/readme.md b/src/main/kotlin/g2701_2800/s2745_construct_the_longest_new_string/readme.md new file mode 100644 index 00000000..ebc5aa58 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2745_construct_the_longest_new_string/readme.md @@ -0,0 +1,48 @@ +[![](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) + +## 2745\. Construct the Longest New String + +Medium + +You are given three integers `x`, `y`, and `z`. + +You have `x` strings equal to `"AA"`, `y` strings equal to `"BB"`, and `z` strings equal to `"AB"`. You want to choose some (possibly all or none) of these strings and concactenate them in some order to form a new string. This new string must not contain `"AAA"` or `"BBB"` as a substring. + +Return _the maximum possible length of the new string_. + +A **substring** is a contiguous **non-empty** sequence of characters within a string. + +**Example 1:** + +**Input:** x = 2, y = 5, z = 1 + +**Output:** 12 + +**Explanation:** We can concactenate the strings "BB", "AA", "BB", "AA", "BB", and "AB" in that order. Then, our new string is "BBAABBAABBAB". That string has length 12, and we can show that it is impossible to construct a string of longer length. + +**Example 2:** + +**Input:** x = 3, y = 2, z = 2 + +**Output:** 14 + +**Explanation:** We can concactenate the strings "AB", "AB", "AA", "BB", "AA", "BB", and "AA" in that order. Then, our new string is "ABABAABBAABBAA". That string has length 14, and we can show that it is impossible to construct a string of longer length. + +**Constraints:** + +* `1 <= x, y, z <= 50` + +## Solution + +```kotlin +class Solution { + fun longestString(x: Int, y: Int, z: Int): Int { + var first = x.coerceAtMost(y) + var second = if (x == y) first else first + 1 + first = first shl 1 + second = second shl 1 + return first + second + (z shl 1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2746_decremental_string_concatenation/readme.md b/src/main/kotlin/g2701_2800/s2746_decremental_string_concatenation/readme.md new file mode 100644 index 00000000..b49463ad --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2746_decremental_string_concatenation/readme.md @@ -0,0 +1,115 @@ +[![](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) + +## 2746\. Decremental String Concatenation + +Medium + +You are given a **0-indexed** array `words` containing `n` strings. + +Let's define a **join** operation `join(x, y)` between two strings `x` and `y` as concatenating them into `xy`. However, if the last character of `x` is equal to the first character of `y`, one of them is **deleted**. + +For example `join("ab", "ba") = "aba"` and `join("ab", "cde") = "abcde"`. + +You are to perform `n - 1` **join** operations. Let str0 = words[0]. Starting from `i = 1` up to `i = n - 1`, for the ith operation, you can do one of the following: + +* Make stri = join(stri - 1, words[i]) +* Make stri = join(words[i], stri - 1) + +Your task is to **minimize** the length of strn - 1. + +Return _an integer denoting the minimum possible length of_ strn - 1. + +**Example 1:** + +**Input:** words = ["aa","ab","bc"] + +**Output:** 4 + +**Explanation:** In this example, we can perform join operations in the following order to minimize the length of str2: + +str0 = "aa" + +str1 = join(str0, "ab") = "aab" + +str2 = join(str1, "bc") = "aabc" + +It can be shown that the minimum possible length of str2 is 4. + +**Example 2:** + +**Input:** words = ["ab","b"] + +**Output:** 2 + +**Explanation:** In this example, str0 = "ab", there are two ways to get str1: join(str0, "b") = "ab" or join("b", str0) = "bab". The first string, "ab", has the minimum length. Hence, the answer is 2. + +**Example 3:** + +**Input:** words = ["aaa","c","aba"] + +**Output:** 6 + +**Explanation:** In this example, we can perform join operations in the following order to minimize the length of str2: + +str0 = "aaa" + +str1 = join(str0, "c") = "aaac" + +str2 = join("aba", str1) = "abaaac" + +It can be shown that the minimum possible length of str2 is 6. + +**Constraints:** + +* `1 <= words.length <= 1000` +* `1 <= words[i].length <= 50` +* Each character in `words[i]` is an English lowercase letter + +## Solution + +```kotlin +class Solution { + private val inf = 1e9.toInt() + private lateinit var dp: Array>> + + fun minimizeConcatenatedLength(words: Array): Int { + val n = words.size + dp = Array(n) { + Array(26) { + arrayOfNulls( + 26 + ) + } + } + val curWord = words[0] + val curLen = curWord.length + val curFirst = curWord[0] + val curLast = curWord[curLen - 1] + return curLen + solve(1, curFirst, curLast, n, words) + } + + private fun solve(idx: Int, prevFirst: Char, prevLast: Char, n: Int, words: Array): Int { + if (idx == n) return 0 + if (dp[idx][prevFirst.code - 'a'.code][prevLast.code - 'a'.code] != null) { + return dp[idx][prevFirst.code - 'a'.code][prevLast.code - 'a'.code]!! + } + val curWord = words[idx] + val curLen = curWord.length + val curFirst = curWord[0] + val curLast = curWord[curLen - 1] + var ans = inf + ans = if (prevFirst == curLast) { + ans.coerceAtMost(curLen - 1 + solve(idx + 1, curFirst, prevLast, n, words)) + } else { + ans.coerceAtMost(curLen + solve(idx + 1, curFirst, prevLast, n, words)) + } + ans = if (prevLast == curFirst) { + ans.coerceAtMost(curLen - 1 + solve(idx + 1, prevFirst, curLast, n, words)) + } else { + ans.coerceAtMost(curLen + solve(idx + 1, prevFirst, curLast, n, words)) + } + return ans.also { dp[idx][prevFirst.code - 'a'.code][prevLast.code - 'a'.code] = it } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2747_count_zero_request_servers/readme.md b/src/main/kotlin/g2701_2800/s2747_count_zero_request_servers/readme.md new file mode 100644 index 00000000..0c5d73b4 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2747_count_zero_request_servers/readme.md @@ -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) + +## 2747\. Count Zero Request Servers + +Medium + +You are given an integer `n` denoting the total number of servers and a **2D** **0-indexed** integer array `logs`, where `logs[i] = [server_id, time]` denotes that the server with id `server_id` received a request at time `time`. + +You are also given an integer `x` and a **0-indexed** integer array `queries`. + +Return _a **0-indexed** integer array_ `arr` _of length_ `queries.length` _where_ `arr[i]` _represents the number of servers that **did not receive** any requests during the time interval_ `[queries[i] - x, queries[i]]`. + +Note that the time intervals are inclusive. + +**Example 1:** + +**Input:** n = 3, logs = \[\[1,3],[2,6],[1,5]], x = 5, queries = [10,11] + +**Output:** [1,2] + +**Explanation:** + +For queries[0]: The servers with ids 1 and 2 get requests in the duration of [5, 10]. + +Hence, only server 3 gets zero requests. + +For queries[1]: Only the server with id 2 gets a request in duration of [6,11]. Hence, the servers with ids 1 and 3 are the only servers that do not receive any requests during that time period. + +**Example 2:** + +**Input:** n = 3, logs = \[\[2,4],[2,1],[1,2],[3,1]], x = 2, queries = [3,4] + +**Output:** [0,1] + +**Explanation:** + +For queries[0]: All servers get at least one request in the duration of [1, 3]. + +For queries[1]: Only server with id 3 gets no request in the duration [2,4]. + +**Constraints:** + +* 1 <= n <= 105 +* 1 <= logs.length <= 105 +* 1 <= queries.length <= 105 +* `logs[i].length == 2` +* `1 <= logs[i][0] <= n` +* 1 <= logs[i][1] <= 106 +* 1 <= x <= 105 +* x < queries[i] <= 106 + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun countServers(n: Int, logs: Array, x: Int, qs: IntArray): IntArray { + val m = qs.size + val valIdx = Array(m) { IntArray(2) } + for (i in 0 until m) valIdx[i] = intArrayOf(qs[i], i) + Arrays.sort(valIdx) { a: IntArray, b: IntArray -> + a[0] - b[0] + } + Arrays.sort(logs) { a: IntArray, b: IntArray -> + a[1] - b[1] + } + var l = 0 + var r = 0 + val res = IntArray(m) + val servCount: HashMap = HashMap() + for (q in valIdx) { + val rVal = q[0] + val lVal = q[0] - x + val i = q[1] + while (r < logs.size && logs[r][1] <= rVal) servCount.merge(logs[r++][0], 1) { a: Int, b: Int -> + Integer.sum( + a, + b + ) + } + while (l < r && logs[l][1] < lVal) { + servCount.compute(logs[l][0]) { _, v -> v!! - 1 } + servCount.remove(logs[l][0], 0) + l++ + } + res[i] = n - servCount.size + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2748_number_of_beautiful_pairs/readme.md b/src/main/kotlin/g2701_2800/s2748_number_of_beautiful_pairs/readme.md new file mode 100644 index 00000000..d22d3fa1 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2748_number_of_beautiful_pairs/readme.md @@ -0,0 +1,91 @@ +[![](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) + +## 2748\. Number of Beautiful Pairs + +Easy + +You are given a **0-indexed** integer array `nums`. A pair of indices `i`, `j` where `0 <= i < j < nums.length` is called beautiful if the **first digit** of `nums[i]` and the **last digit** of `nums[j]` are **coprime**. + +Return _the total number of beautiful pairs in_ `nums`. + +Two integers `x` and `y` are **coprime** if there is no integer greater than 1 that divides both of them. In other words, `x` and `y` are coprime if `gcd(x, y) == 1`, where `gcd(x, y)` is the **greatest common divisor** of `x` and `y`. + +**Example 1:** + +**Input:** nums = [2,5,1,4] + +**Output:** 5 + +**Explanation:** There are 5 beautiful pairs in nums: + +When i = 0 and j = 1: the first digit of nums[0] is 2, and the last digit of nums[1] is 5. We can confirm that 2 and 5 are coprime, since gcd(2,5) == 1. + +When i = 0 and j = 2: the first digit of nums[0] is 2, and the last digit of nums[2] is 1. Indeed, gcd(2,1) == 1. + +When i = 1 and j = 2: the first digit of nums[1] is 5, and the last digit of nums[2] is 1. Indeed, gcd(5,1) == 1. + +When i = 1 and j = 3: the first digit of nums[1] is 5, and the last digit of nums[3] is 4. Indeed, gcd(5,4) == 1. + +When i = 2 and j = 3: the first digit of nums[2] is 1, and the last digit of nums[3] is 4. Indeed, gcd(1,4) == 1. + +Thus, we return 5. + +**Example 2:** + +**Input:** nums = [11,21,12] + +**Output:** 2 + +**Explanation:** There are 2 beautiful pairs: + +When i = 0 and j = 1: the first digit of nums[0] is 1, and the last digit of nums[1] is 1. Indeed, gcd(1,1) == 1. + +When i = 0 and j = 2: the first digit of nums[0] is 1, and the last digit of nums[2] is 2. Indeed, gcd(1,2) == 1. + +Thus, we return 2. + +**Constraints:** + +* `2 <= nums.length <= 100` +* `1 <= nums[i] <= 9999` +* `nums[i] % 10 != 0` + +## Solution + +```kotlin +class Solution { + fun countBeautifulPairs(nums: IntArray): Int { + var beautifulPairs = 0 + var i = 0 + var j = 1 + while (i < nums.size - 1) { + val firstDigit = getFirstDigit(nums[i]) + while (j < nums.size) { + val lastDigit = nums[j] % 10 + val botDigitsAreEqualAndNot1 = firstDigit == lastDigit && firstDigit > 1 + val botDigitsAreDivisibleBy2 = firstDigit % 2 == 0 && lastDigit % 2 == 0 + val botDigitsAreDivisibleBy3 = firstDigit % 3 == 0 && lastDigit % 3 == 0 + + if (!botDigitsAreEqualAndNot1 && !botDigitsAreDivisibleBy2 && !botDigitsAreDivisibleBy3) { + beautifulPairs++ + } + j++ + } + i++ + j = i + 1 + } + return beautifulPairs + } + + private fun getFirstDigit(num: Int): Int { + var n = num + var digit = 0 + while (n > 0) { + digit = n % 10 + n /= 10 + } + return digit + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2749_minimum_operations_to_make_the_integer_zero/readme.md b/src/main/kotlin/g2701_2800/s2749_minimum_operations_to_make_the_integer_zero/readme.md new file mode 100644 index 00000000..9736add8 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2749_minimum_operations_to_make_the_integer_zero/readme.md @@ -0,0 +1,59 @@ +[![](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) + +## 2749\. Minimum Operations to Make the Integer Zero + +Medium + +You are given two integers `num1` and `num2`. + +In one operation, you can choose integer `i` in the range `[0, 60]` and subtract 2i + num2 from `num1`. + +Return _the integer denoting the **minimum** number of operations needed to make_ `num1` _equal to_ `0`. + +If it is impossible to make `num1` equal to `0`, return `-1`. + +**Example 1:** + +**Input:** num1 = 3, num2 = -2 + +**Output:** 3 + +**Explanation:** We can make 3 equal to 0 with the following operations: +- We choose i = 2 and substract 22 + (-2) from 3, 3 - (4 + (-2)) = 1. +- We choose i = 2 and substract 22 + (-2) from 1, 1 - (4 + (-2)) = -1. +- We choose i = 0 and substract 20 + (-2) from -1, (-1) - (1 + (-2)) = 0. + +It can be proven, that 3 is the minimum number of operations that we need to perform. + +**Example 2:** + +**Input:** num1 = 5, num2 = 7 + +**Output:** -1 + +**Explanation:** It can be proven, that it is impossible to make 5 equal to 0 with the given operation. + +**Constraints:** + +* 1 <= num1 <= 109 +* -109 <= num2 <= 109 + +## Solution + +```kotlin +class Solution { + fun makeTheIntegerZero(num1: Int, num2: Int): Int { + val n1 = num1.toLong() + val n2 = num2.toLong() + for (i in 0..60) { + val target = n1 - n2 * i + val noOfBits = java.lang.Long.bitCount(target) + if (i.toLong() in noOfBits..target) { + return i + } + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2790_maximum_number_of_groups_with_increasing_length/readme.md b/src/main/kotlin/g2701_2800/s2790_maximum_number_of_groups_with_increasing_length/readme.md new file mode 100644 index 00000000..c9e15513 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2790_maximum_number_of_groups_with_increasing_length/readme.md @@ -0,0 +1,109 @@ +[![](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) + +## 2790\. Maximum Number of Groups With Increasing Length + +Hard + +You are given a **0-indexed** array `usageLimits` of length `n`. + +Your task is to create **groups** using numbers from `0` to `n - 1`, ensuring that each number, `i`, is used no more than `usageLimits[i]` times in total **across all groups**. You must also satisfy the following conditions: + +* Each group must consist of **distinct** numbers, meaning that no duplicate numbers are allowed within a single group. +* Each group (except the first one) must have a length **strictly greater** than the previous group. + +Return _an integer denoting the **maximum** number of groups you can create while satisfying these conditions._ + +**Example 1:** + +**Input:** `usageLimits` = [1,2,5] + +**Output:** 3 + +**Explanation:** + +In this example, we can use 0 at most once, 1 at most twice, and 2 at most five times. + +One way of creating the maximum number of groups while satisfying the conditions is: + +Group 1 contains the number [2]. + +Group 2 contains the numbers [1,2]. + +Group 3 contains the numbers [0,1,2]. + +It can be shown that the maximum number of groups is 3. + +So, the output is 3. + +**Example 2:** + +**Input:** `usageLimits` = [2,1,2] + +**Output:** 2 + +**Explanation:** + +In this example, we can use 0 at most twice, 1 at most once, and 2 at most twice. + +One way of creating the maximum number of groups while satisfying the conditions is: + +Group 1 contains the number [0]. + +Group 2 contains the numbers [1,2]. + +It can be shown that the maximum number of groups is 2. + +So, the output is 2. + +**Example 3:** + +**Input:** `usageLimits` = [1,1] + +**Output:** 1 + +**Explanation:** + +In this example, we can use both 0 and 1 at most once. + +One way of creating the maximum number of groups while satisfying the conditions is: + +Group 1 contains the number [0]. + +It can be shown that the maximum number of groups is 1. + +So, the output is 1. + +**Constraints:** + +* 1 <= usageLimits.length <= 105 +* 1 <= usageLimits[i] <= 109 + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + fun maxIncreasingGroups(usageLimits: List): Int { + val n: Int = usageLimits.size + var total: Long = 0 + var k: Long = 0 + val count = IntArray(n + 1) + count.fill(0) + for (a in usageLimits) { + val localA = min(a.toDouble(), n.toDouble()).toInt() + count[localA]++ + } + for (i in 0..n) { + for (j in 0 until count[i]) { + total += i.toLong() + if (total >= (k + 1) * (k + 2) / 2) { + k++ + } + } + } + return k.toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2791_count_paths_that_can_form_a_palindrome_in_a_tree/readme.md b/src/main/kotlin/g2701_2800/s2791_count_paths_that_can_form_a_palindrome_in_a_tree/readme.md new file mode 100644 index 00000000..ab470acd --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2791_count_paths_that_can_form_a_palindrome_in_a_tree/readme.md @@ -0,0 +1,94 @@ +[![](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) + +## 2791\. Count Paths That Can Form a Palindrome in a Tree + +Hard + +You are given a **tree** (i.e. a connected, undirected graph that has no cycles) **rooted** at node `0` consisting of `n` nodes numbered from `0` to `n - 1`. The tree is represented by a **0-indexed** array `parent` of size `n`, where `parent[i]` is the parent of node `i`. Since node `0` is the root, `parent[0] == -1`. + +You are also given a string `s` of length `n`, where `s[i]` is the character assigned to the edge between `i` and `parent[i]`. `s[0]` can be ignored. + +Return _the number of pairs of nodes_ `(u, v)` _such that_ `u < v` _and the characters assigned to edges on the path from_ `u` _to_ `v` _can be **rearranged** to form a **palindrome**_. + +A string is a **palindrome** when it reads the same backwards as forwards. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/07/15/treedrawio-8drawio.png) + +**Input:** parent = [-1,0,0,1,1,2], s = "acaabc" + +**Output:** 8 + +**Explanation:** + +The valid pairs are: + +- All the pairs (0,1), (0,2), (1,3), (1,4) and (2,5) result in one character which is always a palindrome. + +- The pair (2,3) result in the string "aca" which is a palindrome. + +- The pair (1,5) result in the string "cac" which is a palindrome. + +- The pair (3,5) result in the string "acac" which can be rearranged into the palindrome "acca". + +**Example 2:** + +**Input:** parent = [-1,0,0,0,0], s = "aaaaa" + +**Output:** 10 + +**Explanation:** Any pair of nodes (u,v) where u < v is valid. + +**Constraints:** + +* `n == parent.length == s.length` +* 1 <= n <= 105 +* `0 <= parent[i] <= n - 1` for all `i >= 1` +* `parent[0] == -1` +* `parent` represents a valid tree. +* `s` consists of only lowercase English letters. + +## Solution + +```kotlin +class Solution { + private fun getMap(parent: List, s: String, dp: IntArray, idx: Int): Int { + if (dp[idx] < 0) { + dp[idx] = 0 + dp[idx] = getMap(parent, s, dp, parent[idx]) xor (1 shl s[idx].code - 'a'.code) + } + return dp[idx] + } + + fun countPalindromePaths(parent: List, s: String): Long { + val n: Int = parent.size + val dp = IntArray(n) + var ans: Long = 0 + val mapCount: MutableMap = HashMap() + dp.fill(-1) + dp[0] = 0 + for (i in 0 until n) { + val currMap = getMap(parent, s, dp, i) + // if map are same, two points can form a path; + val evenCount = mapCount[currMap] ?: 0 + mapCount.put(currMap, evenCount + 1) + } + for (key in mapCount.keys) { + val value = mapCount[key]!! + ans += value.toLong() * (value - 1) shr 1 + for (i in 0..25) { + val base = 1 shl i + // if this map at i is 1, which means odd this bit + if (key and base > 0 && mapCount.containsKey(key xor base)) { + // key ^ base is the map that is 0 at bit i, odd pairs with even, + // can pair and no duplicate + ans += value.toLong() * mapCount[key xor base]!! + } + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2798_number_of_employees_who_met_the_target/readme.md b/src/main/kotlin/g2701_2800/s2798_number_of_employees_who_met_the_target/readme.md new file mode 100644 index 00000000..379a39ef --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2798_number_of_employees_who_met_the_target/readme.md @@ -0,0 +1,69 @@ +[![](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) + +## 2798\. Number of Employees Who Met the Target + +Easy + +There are `n` employees in a company, numbered from `0` to `n - 1`. Each employee `i` has worked for `hours[i]` hours in the company. + +The company requires each employee to work for **at least** `target` hours. + +You are given a **0-indexed** array of non-negative integers `hours` of length `n` and a non-negative integer `target`. + +Return _the integer denoting the number of employees who worked at least_ `target` _hours_. + +**Example 1:** + +**Input:** hours = [0,1,2,3,4], target = 2 + +**Output:** 3 + +**Explanation:** + +The company wants each employee to work for at least 2 hours. + +- Employee 0 worked for 0 hours and didn't meet the target. + +- Employee 1 worked for 1 hours and didn't meet the target. + +- Employee 2 worked for 2 hours and met the target. + +- Employee 3 worked for 3 hours and met the target. + +- Employee 4 worked for 4 hours and met the target. + +There are 3 employees who met the target. + +**Example 2:** + +**Input:** hours = [5,1,4,2,2], target = 6 + +**Output:** 0 + +**Explanation:** + +The company wants each employee to work for at least 6 hours. + +There are 0 employees who met the target. + +**Constraints:** + +* `1 <= n == hours.length <= 50` +* 0 <= hours[i], target <= 105 + +## Solution + +```kotlin +class Solution { + fun numberOfEmployeesWhoMetTarget(hours: IntArray, target: Int): Int { + var count = 0 + for (i in hours) { + if (i >= target) { + count++ + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2799_count_complete_subarrays_in_an_array/readme.md b/src/main/kotlin/g2701_2800/s2799_count_complete_subarrays_in_an_array/readme.md new file mode 100644 index 00000000..5a94f19a --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2799_count_complete_subarrays_in_an_array/readme.md @@ -0,0 +1,77 @@ +[![](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) + +## 2799\. Count Complete Subarrays in an Array + +Medium + +You are given an array `nums` consisting of **positive** integers. + +We call a subarray of an array **complete** if the following condition is satisfied: + +* The number of **distinct** elements in the subarray is equal to the number of distinct elements in the whole array. + +Return _the number of **complete** subarrays_. + +A **subarray** is a contiguous non-empty part of an array. + +**Example 1:** + +**Input:** nums = [1,3,1,2,2] + +**Output:** 4 + +**Explanation:** The complete subarrays are the following: [1,3,1,2], [1,3,1,2,2], [3,1,2] and [3,1,2,2]. + +**Example 2:** + +**Input:** nums = [5,5,5,5] + +**Output:** 10 + +**Explanation:** The array consists only of the integer 5, so any subarray is complete. The number of subarrays that we can choose is 10. + +**Constraints:** + +* `1 <= nums.length <= 1000` +* `1 <= nums[i] <= 2000` + +## Solution + +```kotlin +class Solution { + fun countCompleteSubarrays(nums: IntArray): Int { + val n = nums.size + var map = IntArray(2001) + var distinct = 0 + var last = 0 + for (i in 0 until n) { + map[nums[i]]++ + if (map[nums[i]] == 1) { + distinct++ + last = i + } + } + map = IntArray(2001) + for (i in 0..last) map[nums[i]]++ + var ans = 0 + for (i in 0 until n) { + ans += n - last + map[nums[i]]-- + if (map[nums[i]] == 0) { + var possLast = 0 + var j = last + 1 + while (j < n && map[nums[i]] == 0) { + map[nums[j]]++ + possLast = j + ++j + } + last = if (map[nums[i]] > 0) { + possLast + } else break + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2800_shortest_string_that_contains_three_strings/readme.md b/src/main/kotlin/g2701_2800/s2800_shortest_string_that_contains_three_strings/readme.md new file mode 100644 index 00000000..f9399077 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2800_shortest_string_that_contains_three_strings/readme.md @@ -0,0 +1,104 @@ +[![](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) + +## 2800\. Shortest String That Contains Three Strings + +Medium + +Given three strings `a`, `b`, and `c`, your task is to find a string that has the **minimum** length and contains all three strings as **substrings**. + +If there are multiple such strings, return the **lexicographically smallest** one. + +Return _a string denoting the answer to the problem._ + +**Notes** + +* 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`. +* A **substring** is a contiguous sequence of characters within a string. + +**Example 1:** + +**Input:** a = "abc", b = "bca", c = "aaa" + +**Output:** "aaabca" + +**Explanation:** We show that "aaabca" contains all the given strings: a = ans[2...4], b = ans[3..5], c = ans[0..2]. It can be shown that the length of the resulting string would be at least 6 and "aaabca" is the lexicographically smallest one. + +**Example 2:** + +**Input:** a = "ab", b = "ba", c = "aba" + +**Output:** "aba" + +**Explanation:** We show that the string "aba" contains all the given strings: a = ans[0..1], b = ans[1..2], c = ans[0..2]. Since the length of c is 3, the length of the resulting string would be at least 3. It can be shown that "aba" is the lexicographically smallest one. + +**Constraints:** + +* `1 <= a.length, b.length, c.length <= 100` +* `a`, `b`, `c` consist only of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun minimumString(a: String, b: String, c: String): String { + val ar = a.toCharArray() + val br = b.toCharArray() + val cr = c.toCharArray() + return String( + getSmaller( + combine(ar, br, cr), + getSmaller( + combine(ar, cr, br), + getSmaller( + combine(br, ar, cr), + getSmaller( + combine(br, cr, ar), + getSmaller(combine(cr, ar, br), combine(cr, br, ar)) + ) + ) + ) + ) + ) + } + + private fun combine(a: CharArray, b: CharArray, c: CharArray): CharArray { + return combine(combine(a, b), c) + } + + private fun combine(a: CharArray, b: CharArray): CharArray { + var insertIndex = a.size + for (i in a.indices) { + if (a[i] == b[0]) { + var ii = i + 1 + var match = 1 + var j = 1 + while (j < b.size && ii < a.size) { + if (a[ii] == b[j]) match++ else break + ii++ + ++j + } + if (match == b.size) { + return a + } else if (match == a.size - i) { + insertIndex = i + break + } + } + } + val tmp = CharArray(b.size + insertIndex) + for (i in 0 until insertIndex) tmp[i] = a[i] + for (i in b.indices) tmp[i + insertIndex] = b[i] + return tmp + } + + private fun getSmaller(res: CharArray, test: CharArray): CharArray { + if (res.size > test.size) return test else if (res.size < test.size) return res else { + for (i in res.indices) { + if (res[i] > test[i]) return test else if (res[i] < test[i]) return res + } + } + return res + } +} +``` \ No newline at end of file