diff --git a/README.md b/README.md index cf815b4e..c798686d 100644 --- a/README.md +++ b/README.md @@ -1816,6 +1816,37 @@ | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- +| 3108 |[Minimum Cost Walk in Weighted Graph](src/main/kotlin/g3101_3200/s3108_minimum_cost_walk_in_weighted_graph)| Hard | Array, Bit_Manipulation, Graph, Union_Find | 791 | 100.00 +| 3107 |[Minimum Operations to Make Median of Array Equal to K](src/main/kotlin/g3101_3200/s3107_minimum_operations_to_make_median_of_array_equal_to_k)| Medium | Array, Sorting, Greedy | 554 | 100.00 +| 3106 |[Lexicographically Smallest String After Operations With Constraint](src/main/kotlin/g3101_3200/s3106_lexicographically_smallest_string_after_operations_with_constraint)| Medium | String, Greedy | 162 | 74.19 +| 3105 |[Longest Strictly Increasing or Strictly Decreasing Subarray](src/main/kotlin/g3101_3200/s3105_longest_strictly_increasing_or_strictly_decreasing_subarray)| Easy | Array | 159 | 94.00 +| 3102 |[Minimize Manhattan Distances](src/main/kotlin/g3101_3200/s3102_minimize_manhattan_distances)| Hard | Array, Math | 701 | 95.83 +| 3101 |[Count Alternating Subarrays](src/main/kotlin/g3101_3200/s3101_count_alternating_subarrays)| Medium | Array, Math | 499 | 97.78 +| 3100 |[Water Bottles II](src/main/kotlin/g3001_3100/s3100_water_bottles_ii)| Medium | Math, Simulation | 137 | 70.49 +| 3099 |[Harshad Number](src/main/kotlin/g3001_3100/s3099_harshad_number)| Easy | Math | 119 | 82.67 +| 3098 |[Find the Sum of Subsequence Powers](src/main/kotlin/g3001_3100/s3098_find_the_sum_of_subsequence_powers)| Hard | Array, Dynamic_Programming, Sorting | 294 | 77.78 +| 3097 |[Shortest Subarray With OR at Least K II](src/main/kotlin/g3001_3100/s3097_shortest_subarray_with_or_at_least_k_ii)| Medium | Array, Bit_Manipulation, Sliding_Window | 489 | 93.33 +| 3096 |[Minimum Levels to Gain More Points](src/main/kotlin/g3001_3100/s3096_minimum_levels_to_gain_more_points)| Medium | Array, Prefix_Sum | 850 | 100.00 +| 3095 |[Shortest Subarray With OR at Least K I](src/main/kotlin/g3001_3100/s3095_shortest_subarray_with_or_at_least_k_i)| Easy | Array, Bit_Manipulation, Sliding_Window | 161 | 95.65 +| 3093 |[Longest Common Suffix Queries](src/main/kotlin/g3001_3100/s3093_longest_common_suffix_queries)| Hard | Array, String, Trie | 860 | 89.29 +| 3092 |[Most Frequent IDs](src/main/kotlin/g3001_3100/s3092_most_frequent_ids)| Medium | Array, Hash_Table, Heap_Priority_Queue, Ordered_Set | 758 | 100.00 +| 3091 |[Apply Operations to Make Sum of Array Greater Than or Equal to k](src/main/kotlin/g3001_3100/s3091_apply_operations_to_make_sum_of_array_greater_than_or_equal_to_k)| Medium | Math, Greedy, Enumeration | 134 | 73.21 +| 3090 |[Maximum Length Substring With Two Occurrences](src/main/kotlin/g3001_3100/s3090_maximum_length_substring_with_two_occurrences)| Easy | String, Hash_Table, Sliding_Window | 157 | 90.24 +| 3086 |[Minimum Moves to Pick K Ones](src/main/kotlin/g3001_3100/s3086_minimum_moves_to_pick_k_ones)| Hard | Array, Greedy, Prefix_Sum, Sliding_Window | 368 | 100.00 +| 3085 |[Minimum Deletions to Make String K-Special](src/main/kotlin/g3001_3100/s3085_minimum_deletions_to_make_string_k_special)| Medium | String, Hash_Table, Sorting, Greedy, Counting | 221 | 93.33 +| 3084 |[Count Substrings Starting and Ending with Given Character](src/main/kotlin/g3001_3100/s3084_count_substrings_starting_and_ending_with_given_character)| Medium | String, Math, Counting | 177 | 98.55 +| 3083 |[Existence of a Substring in a String and Its Reverse](src/main/kotlin/g3001_3100/s3083_existence_of_a_substring_in_a_string_and_its_reverse)| Easy | String, Hash_Table | 168 | 79.49 +| 3082 |[Find the Sum of the Power of All Subsequences](src/main/kotlin/g3001_3100/s3082_find_the_sum_of_the_power_of_all_subsequences)| Hard | Array, Dynamic_Programming | 176 | 90.00 +| 3081 |[Replace Question Marks in String to Minimize Its Value](src/main/kotlin/g3001_3100/s3081_replace_question_marks_in_string_to_minimize_its_value)| Medium | String, Hash_Table, Sorting, Greedy, Heap_Priority_Queue, Counting | 249 | 100.00 +| 3080 |[Mark Elements on Array by Performing Queries](src/main/kotlin/g3001_3100/s3080_mark_elements_on_array_by_performing_queries)| Medium | Array, Hash_Table, Sorting, Heap_Priority_Queue, Simulation | 937 | 97.78 +| 3079 |[Find the Sum of Encrypted Integers](src/main/kotlin/g3001_3100/s3079_find_the_sum_of_encrypted_integers)| Easy | Array, Math | 172 | 80.60 +| 3077 |[Maximum Strength of K Disjoint Subarrays](src/main/kotlin/g3001_3100/s3077_maximum_strength_of_k_disjoint_subarrays)| Hard | Array, Dynamic_Programming, Prefix_Sum | 351 | 75.00 +| 3076 |[Shortest Uncommon Substring in an Array](src/main/kotlin/g3001_3100/s3076_shortest_uncommon_substring_in_an_array)| Medium | Array, String, Hash_Table, Trie | 256 | 100.00 +| 3075 |[Maximize Happiness of Selected Children](src/main/kotlin/g3001_3100/s3075_maximize_happiness_of_selected_children)| Medium | Array, Sorting, Greedy | 608 | 93.24 +| 3074 |[Apple Redistribution into Boxes](src/main/kotlin/g3001_3100/s3074_apple_redistribution_into_boxes)| Easy | Array, Sorting, Greedy | 168 | 97.37 +| 3072 |[Distribute Elements Into Two Arrays II](src/main/kotlin/g3001_3100/s3072_distribute_elements_into_two_arrays_ii)| Hard | Array, Simulation, Segment_Tree, Binary_Indexed_Tree | 890 | 100.00 +| 3071 |[Minimum Operations to Write the Letter Y on a Grid](src/main/kotlin/g3001_3100/s3071_minimum_operations_to_write_the_letter_y_on_a_grid)| Medium | Array, Hash_Table, Matrix, Counting | 268 | 91.11 +| 3070 |[Count Submatrices with Top-Left Element and Sum Less Than k](src/main/kotlin/g3001_3100/s3070_count_submatrices_with_top_left_element_and_sum_less_than_k)| Medium | Array, Matrix, Prefix_Sum | 773 | 85.71 | 3069 |[Distribute Elements Into Two Arrays I](src/main/kotlin/g3001_3100/s3069_distribute_elements_into_two_arrays_i)| Easy | Array, Simulation | 207 | 96.92 | 3068 |[Find the Maximum Sum of Node Values](src/main/kotlin/g3001_3100/s3068_find_the_maximum_sum_of_node_values)| Hard | Array, Dynamic_Programming, Sorting, Greedy, Tree, Bit_Manipulation | 531 | 66.67 | 3067 |[Count Pairs of Connectable Servers in a Weighted Tree Network](src/main/kotlin/g3001_3100/s3067_count_pairs_of_connectable_servers_in_a_weighted_tree_network)| Medium | Array, Depth_First_Search, Tree | 578 | 83.33 diff --git a/src/main/kotlin/g1201_1300/s1275_find_winner_on_a_tic_tac_toe_game/readme.md b/src/main/kotlin/g1201_1300/s1275_find_winner_on_a_tic_tac_toe_game/readme.md index 7a40e674..12bac42c 100644 --- a/src/main/kotlin/g1201_1300/s1275_find_winner_on_a_tic_tac_toe_game/readme.md +++ b/src/main/kotlin/g1201_1300/s1275_find_winner_on_a_tic_tac_toe_game/readme.md @@ -111,4 +111,4 @@ class Solution { } } } -``` +``` \ No newline at end of file diff --git a/src/main/kotlin/g1501_1600/s1579_remove_max_number_of_edges_to_keep_graph_fully_traversable/readme.md b/src/main/kotlin/g1501_1600/s1579_remove_max_number_of_edges_to_keep_graph_fully_traversable/readme.md index 6511ae6b..017eb59f 100644 --- a/src/main/kotlin/g1501_1600/s1579_remove_max_number_of_edges_to_keep_graph_fully_traversable/readme.md +++ b/src/main/kotlin/g1501_1600/s1579_remove_max_number_of_edges_to_keep_graph_fully_traversable/readme.md @@ -57,11 +57,9 @@ Return _the maximum number of edges you can remove, or return_ `-1` _if it's imp ## Solution ```kotlin -import java.util.Arrays - class Solution { fun maxNumEdgesToRemove(n: Int, edges: Array): Int { - Arrays.sort(edges) { a: IntArray, b: IntArray -> b[0] - a[0] } + edges.sortWith { a: IntArray, b: IntArray -> b[0] - a[0] } val alice = IntArray(n + 1) val rankAlice = IntArray(n + 1) val bob = IntArray(n + 1) diff --git a/src/main/kotlin/g1601_1700/s1632_rank_transform_of_a_matrix/readme.md b/src/main/kotlin/g1601_1700/s1632_rank_transform_of_a_matrix/readme.md index 51e88240..a0dc7a5a 100644 --- a/src/main/kotlin/g1601_1700/s1632_rank_transform_of_a_matrix/readme.md +++ b/src/main/kotlin/g1601_1700/s1632_rank_transform_of_a_matrix/readme.md @@ -62,8 +62,6 @@ The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] ## Solution ```kotlin -import java.util.Arrays - class Solution { fun matrixRankTransform(matrix: Array): Array { val rowCount = matrix.size @@ -108,7 +106,7 @@ class Solution { } else { val rowCount = matrix.size val ufind = IntArray(rowCount + matrix[0].size) - Arrays.fill(ufind, -1) + ufind.fill(-1) for (nIdx in startIdx until endIdx) { val r = nums[nIdx].toInt() shr 16 and 0xFFFF val c = nums[nIdx].toInt() and 0xFFFF diff --git a/src/main/kotlin/g1601_1700/s1665_minimum_initial_energy_to_finish_tasks/readme.md b/src/main/kotlin/g1601_1700/s1665_minimum_initial_energy_to_finish_tasks/readme.md index 19fef918..6681c42a 100644 --- a/src/main/kotlin/g1601_1700/s1665_minimum_initial_energy_to_finish_tasks/readme.md +++ b/src/main/kotlin/g1601_1700/s1665_minimum_initial_energy_to_finish_tasks/readme.md @@ -84,11 +84,9 @@ Starting with 27 energy, we finish the tasks in the following order: ## Solution ```kotlin -import java.util.Arrays - class Solution { fun minimumEffort(tasks: Array): Int { - Arrays.sort(tasks) { a: IntArray, b: IntArray -> a[1] - a[0] - b[1] + b[0] } + tasks.sortWith { a: IntArray, b: IntArray -> a[1] - a[0] - b[1] + b[0] } var prev = 0 for (item in tasks) { prev = Math.max(prev + item[0], item[1]) diff --git a/src/main/kotlin/g1601_1700/s1691_maximum_height_by_stacking_cuboids/readme.md b/src/main/kotlin/g1601_1700/s1691_maximum_height_by_stacking_cuboids/readme.md index 1ec1e441..59457b4f 100644 --- a/src/main/kotlin/g1601_1700/s1691_maximum_height_by_stacking_cuboids/readme.md +++ b/src/main/kotlin/g1601_1700/s1691_maximum_height_by_stacking_cuboids/readme.md @@ -64,16 +64,13 @@ The maximum height of stacked cuboids is 6 \* 17 = 102. ## Solution ```kotlin -import java.util.Arrays - class Solution { fun maxHeight(cuboids: Array): Int { for (a in cuboids) { a.sort() } - Arrays.sort( - cuboids - ) { a: IntArray, b: IntArray -> + + cuboids.sortWith sort@{ a: IntArray, b: IntArray -> if (a[0] != b[0]) { return@sort a[0] - b[0] } else if (a[1] != b[1]) { diff --git a/src/main/kotlin/g1601_1700/s1697_checking_existence_of_edge_length_limited_paths/readme.md b/src/main/kotlin/g1601_1700/s1697_checking_existence_of_edge_length_limited_paths/readme.md index 6cb8c210..d07b68d4 100644 --- a/src/main/kotlin/g1601_1700/s1697_checking_existence_of_edge_length_limited_paths/readme.md +++ b/src/main/kotlin/g1601_1700/s1697_checking_existence_of_edge_length_limited_paths/readme.md @@ -48,8 +48,6 @@ For the second query, there is a path (0 -> 1 -> 2) of two edges with distances ## Solution ```kotlin -import java.util.Arrays - class Solution { private class Dsu(n: Int) { private val parent: IntArray @@ -77,12 +75,12 @@ class Solution { } fun distanceLimitedPathsExist(n: Int, edgeList: Array, queries: Array): BooleanArray { - Arrays.sort(edgeList) { o1: IntArray, o2: IntArray -> Integer.compare(o1[2], o2[2]) } + edgeList.sortWith { o1: IntArray, o2: IntArray -> Integer.compare(o1[2], o2[2]) } val data = Array(queries.size) { IntArray(4) } for (i in queries.indices) { data[i] = intArrayOf(queries[i][0], queries[i][1], queries[i][2], i) } - Arrays.sort(data) { o1: IntArray, o2: IntArray -> Integer.compare(o1[2], o2[2]) } + data.sortWith { o1: IntArray, o2: IntArray -> Integer.compare(o1[2], o2[2]) } val d = Dsu(n) var j = 0 val ans = BooleanArray(queries.size) diff --git a/src/main/kotlin/g1701_1800/s1710_maximum_units_on_a_truck/readme.md b/src/main/kotlin/g1701_1800/s1710_maximum_units_on_a_truck/readme.md index 2017e5d6..f324f6c9 100644 --- a/src/main/kotlin/g1701_1800/s1710_maximum_units_on_a_truck/readme.md +++ b/src/main/kotlin/g1701_1800/s1710_maximum_units_on_a_truck/readme.md @@ -43,13 +43,11 @@ Return _the **maximum** total number of **units** that can be put on the truck._ ## Solution ```kotlin -import java.util.Arrays - @Suppress("NAME_SHADOWING") class Solution { fun maximumUnits(boxTypes: Array, truckSize: Int): Int { var truckSize = truckSize - Arrays.sort(boxTypes) { b1: IntArray, b2: IntArray -> Integer.compare(b2[1], b1[1]) } + boxTypes.sortWith { b1: IntArray, b2: IntArray -> Integer.compare(b2[1], b1[1]) } var maxUnits = 0 var i = 0 while (truckSize > 0 && i < boxTypes.size) { diff --git a/src/main/kotlin/g1701_1800/s1751_maximum_number_of_events_that_can_be_attended_ii/readme.md b/src/main/kotlin/g1701_1800/s1751_maximum_number_of_events_that_can_be_attended_ii/readme.md index 08b699f7..d82a7ef6 100644 --- a/src/main/kotlin/g1701_1800/s1751_maximum_number_of_events_that_can_be_attended_ii/readme.md +++ b/src/main/kotlin/g1701_1800/s1751_maximum_number_of_events_that_can_be_attended_ii/readme.md @@ -65,7 +65,7 @@ class Solution { } } val n = events.size - Arrays.sort(events, { a: IntArray, b: IntArray -> a[0].compareTo(b[0]) }) + events.sortWith { a: IntArray, b: IntArray -> a[0].compareTo(b[0]) } val memo = Array(n) { IntArray(k + 1) } return dfs(events, 0, k, memo) } diff --git a/src/main/kotlin/g1801_1900/s1847_closest_room/readme.md b/src/main/kotlin/g1801_1900/s1847_closest_room/readme.md index 2c0253d2..645eb7e7 100644 --- a/src/main/kotlin/g1801_1900/s1847_closest_room/readme.md +++ b/src/main/kotlin/g1801_1900/s1847_closest_room/readme.md @@ -56,7 +56,6 @@ Query = [2,5]: Room number 3 is the only room with a size of at least 5. The ans ## Solution ```kotlin -import java.util.Arrays import java.util.TreeSet class Solution { @@ -66,8 +65,8 @@ class Solution { for (i in 0 until numQuery) { queries[i] = intArrayOf(queries[i][0], queries[i][1], i) } - Arrays.sort(rooms) { a: IntArray, b: IntArray -> if (a[1] != b[1]) a[1] - b[1] else a[0] - b[0] } - Arrays.sort(queries) { a: IntArray, b: IntArray -> if (a[1] != b[1]) a[1] - b[1] else a[0] - b[0] } + rooms.sortWith { a: IntArray, b: IntArray -> if (a[1] != b[1]) a[1] - b[1] else a[0] - b[0] } + queries.sortWith { a: IntArray, b: IntArray -> if (a[1] != b[1]) a[1] - b[1] else a[0] - b[0] } val roomIds = TreeSet() val result = IntArray(numQuery) var j = numRoom - 1 diff --git a/src/main/kotlin/g1801_1900/s1851_minimum_interval_to_include_each_query/readme.md b/src/main/kotlin/g1801_1900/s1851_minimum_interval_to_include_each_query/readme.md index 81e27dcd..64bcac2c 100644 --- a/src/main/kotlin/g1801_1900/s1851_minimum_interval_to_include_each_query/readme.md +++ b/src/main/kotlin/g1801_1900/s1851_minimum_interval_to_include_each_query/readme.md @@ -54,7 +54,6 @@ Return _an array containing the answers to the queries_. ## Solution ```kotlin -import java.util.Arrays import java.util.PriorityQueue class Solution { @@ -64,8 +63,8 @@ class Solution { for (i in 0 until numQuery) { queriesWithIndex[i] = intArrayOf(queries[i], i) } - Arrays.sort(intervals, { a: IntArray, b: IntArray -> a[0].compareTo(b[0]) }) - Arrays.sort(queriesWithIndex, { a: IntArray, b: IntArray -> a[0].compareTo(b[0]) }) + intervals.sortWith { a: IntArray, b: IntArray -> a[0].compareTo(b[0]) } + queriesWithIndex.sortWith { a: IntArray, b: IntArray -> a[0].compareTo(b[0]) } val minHeap = PriorityQueue({ a: IntArray, b: IntArray -> (a[1] - a[0]).compareTo(b[1] - b[0]) }) val result = IntArray(numQuery) var j = 0 diff --git a/src/main/kotlin/g3001_3100/s3070_count_submatrices_with_top_left_element_and_sum_less_than_k/readme.md b/src/main/kotlin/g3001_3100/s3070_count_submatrices_with_top_left_element_and_sum_less_than_k/readme.md new file mode 100644 index 00000000..59352614 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3070_count_submatrices_with_top_left_element_and_sum_less_than_k/readme.md @@ -0,0 +1,63 @@ +[![](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) + +## 3070\. Count Submatrices with Top-Left Element and Sum Less Than k + +Medium + +You are given a **0-indexed** integer matrix `grid` and an integer `k`. + +Return _the **number** of submatrices that contain the top-left element of the_ `grid`, _and have a sum less than or equal to_ `k`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2024/01/01/example1.png) + +**Input:** grid = \[\[7,6,3],[6,6,1]], k = 18 + +**Output:** 4 + +**Explanation:** There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2024/01/01/example21.png) + +**Input:** grid = \[\[7,2,9],[1,5,0],[2,6,6]], k = 20 + +**Output:** 6 + +**Explanation:** There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20. + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `1 <= n, m <= 1000` +* `0 <= grid[i][j] <= 1000` +* 1 <= k <= 109 + +## Solution + +```kotlin +class Solution { + fun countSubmatrices(grid: Array, k: Int): Int { + val n = grid[0].size + val sums = IntArray(n) + var ans = 0 + for (ints in grid) { + var sum = 0 + for (col in 0 until n) { + sum += ints[col] + sums[col] += sum + if (sums[col] <= k) { + ans++ + } else { + break + } + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3071_minimum_operations_to_write_the_letter_y_on_a_grid/readme.md b/src/main/kotlin/g3001_3100/s3071_minimum_operations_to_write_the_letter_y_on_a_grid/readme.md new file mode 100644 index 00000000..e7d62ed6 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3071_minimum_operations_to_write_the_letter_y_on_a_grid/readme.md @@ -0,0 +1,99 @@ +[![](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) + +## 3071\. Minimum Operations to Write the Letter Y on a Grid + +Medium + +You are given a **0-indexed** `n x n` grid where `n` is odd, and `grid[r][c]` is `0`, `1`, or `2`. + +We say that a cell belongs to the Letter **Y** if it belongs to one of the following: + +* The diagonal starting at the top-left cell and ending at the center cell of the grid. +* The diagonal starting at the top-right cell and ending at the center cell of the grid. +* The vertical line starting at the center cell and ending at the bottom border of the grid. + +The Letter **Y** is written on the grid if and only if: + +* All values at cells belonging to the Y are equal. +* All values at cells not belonging to the Y are equal. +* The values at cells belonging to the Y are different from the values at cells not belonging to the Y. + +Return _the **minimum** number of operations needed to write the letter Y on the grid given that in one operation you can change the value at any cell to_ `0`_,_ `1`_,_ _or_ `2`_._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2024/01/22/y2.png) + +**Input:** grid = \[\[1,2,2],[1,1,0],[0,1,0]] + +**Output:** 3 + +**Explanation:** We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 1 while those that do not belong to Y are equal to 0. It can be shown that 3 is the minimum number of operations needed to write Y on the grid. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2024/01/22/y3.png) + +**Input:** grid = \[\[0,1,0,1,0],[2,1,0,1,2],[2,2,2,0,1],[2,2,2,2,2],[2,1,2,2,2]] + +**Output:** 12 + +**Explanation:** We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 0 while those that do not belong to Y are equal to 2. It can be shown that 12 is the minimum number of operations needed to write Y on the grid. + +**Constraints:** + +* `3 <= n <= 49` +* `n == grid.length == grid[i].length` +* `0 <= grid[i][j] <= 2` +* `n` is odd. + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + fun minimumOperationsToWriteY(arr: Array): Int { + val n = arr.size + val cnt1 = IntArray(3) + val cnt2 = IntArray(3) + val x = n / 2 + val y = n / 2 + for (j in x until n) { + cnt1[arr[j][y]]++ + arr[j][y] = 3 + } + for (j in x downTo 0) { + if (arr[j][j] != 3) { + cnt1[arr[j][j]]++ + } + arr[j][j] = 3 + } + for (j in x downTo 0) { + if (arr[j][n - 1 - j] != 3) { + cnt1[arr[j][n - 1 - j]]++ + } + arr[j][n - 1 - j] = 3 + } + for (ints in arr) { + for (j in 0 until n) { + if (ints[j] != 3) { + cnt2[ints[j]]++ + } + } + } + val s1 = cnt1[0] + cnt1[1] + cnt1[2] + val s2 = cnt2[0] + cnt2[1] + cnt2[2] + var min = Int.MAX_VALUE + for (i in 0..2) { + for (j in 0..2) { + if (i != j) { + min = min((s1 - cnt1[i] + s2 - cnt2[j]), min) + } + } + } + return min + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3072_distribute_elements_into_two_arrays_ii/readme.md b/src/main/kotlin/g3001_3100/s3072_distribute_elements_into_two_arrays_ii/readme.md new file mode 100644 index 00000000..b6f83785 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3072_distribute_elements_into_two_arrays_ii/readme.md @@ -0,0 +1,155 @@ +[![](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) + +## 3072\. Distribute Elements Into Two Arrays II + +Hard + +You are given a **1-indexed** array of integers `nums` of length `n`. + +We define a function `greaterCount` such that `greaterCount(arr, val)` returns the number of elements in `arr` that are **strictly greater** than `val`. + +You need to distribute all the elements of `nums` between two arrays `arr1` and `arr2` using `n` operations. In the first operation, append `nums[1]` to `arr1`. In the second operation, append `nums[2]` to `arr2`. Afterwards, in the ith operation: + +* If `greaterCount(arr1, nums[i]) > greaterCount(arr2, nums[i])`, append `nums[i]` to `arr1`. +* If `greaterCount(arr1, nums[i]) < greaterCount(arr2, nums[i])`, append `nums[i]` to `arr2`. +* If `greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i])`, append `nums[i]` to the array with a **lesser** number of elements. +* If there is still a tie, append `nums[i]` to `arr1`. + +The array `result` is formed by concatenating the arrays `arr1` and `arr2`. For example, if `arr1 == [1,2,3]` and `arr2 == [4,5,6]`, then `result = [1,2,3,4,5,6]`. + +Return _the integer array_ `result`. + +**Example 1:** + +**Input:** nums = [2,1,3,3] + +**Output:** [2,3,1,3] + +**Explanation:** After the first 2 operations, arr1 = [2] and arr2 = [1]. + +In the 3rd operation, the number of elements greater than 3 is zero in both arrays. + +Also, the lengths are equal, hence, append nums[3] to arr1. In the 4th operation, the number of elements greater than 3 is zero in both arrays. As the length of arr2 is lesser, hence, append nums[4] to arr2. + +After 4 operations, arr1 = [2,3] and arr2 = [1,3]. Hence, the array result formed by concatenation is [2,3,1,3]. + +**Example 2:** + +**Input:** nums = [5,14,3,1,2] + +**Output:** [5,3,1,2,14] + +**Explanation:** After the first 2 operations, arr1 = [5] and arr2 = [14]. + +In the 3rd operation, the number of elements greater than 3 is one in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1. + +In the 4th operation, the number of elements greater than 1 is greater in arr1 than arr2 (2 > 1). Hence, append nums[4] to arr1. In the 5th operation, the number of elements greater than 2 is greater in arr1 than arr2 (2 > 1). Hence, append nums[5] to arr1. + +zAfter 5 operations, arr1 = [5,3,1,2] and arr2 = [14]. Hence, the array result formed by concatenation is [5,3,1,2,14]. + +**Example 3:** + +**Input:** nums = [3,3,3,3] + +**Output:** [3,3,3,3] + +**Explanation:** At the end of 4 operations, arr1 = [3,3] and arr2 = [3,3]. Hence, the array result formed by concatenation is [3,3,3,3]. + +**Constraints:** + +* 3 <= n <= 105 +* 1 <= nums[i] <= 109 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING", "kotlin:S1871") +class Solution { + internal inner class BIT(size: Int) { + private val tree = IntArray(size + 1) + + fun update(ind: Int) { + var ind = ind + while (ind < tree.size) { + tree[ind]++ + ind += lsb(ind) + } + } + + fun rsq(ind: Int): Int { + var ind = ind + var sum = 0 + while (ind > 0) { + sum += tree[ind] + ind -= lsb(ind) + } + return sum + } + + private fun lsb(n: Int): Int { + return n and (-n) + } + } + + fun resultArray(source: IntArray): IntArray { + val nums = shrink(source) + val arr1 = IntArray(nums.size) + val arr2 = IntArray(nums.size) + arr1[0] = source[0] + arr2[0] = source[1] + var p1 = 0 + var p2 = 0 + val bit1 = BIT(nums.size) + bit1.update(nums[0]) + val bit2 = BIT(nums.size) + bit2.update(nums[1]) + for (i in 2 until nums.size) { + val g1 = p1 + 1 - bit1.rsq(nums[i]) + val g2 = p2 + 1 - bit2.rsq(nums[i]) + if (g1 > g2) { + p1++ + arr1[p1] = source[i] + bit1.update(nums[i]) + } else if (g1 < g2) { + p2++ + arr2[p2] = source[i] + bit2.update(nums[i]) + } else if (p1 < p2) { + p1++ + arr1[p1] = source[i] + bit1.update(nums[i]) + } else if (p1 > p2) { + p2++ + arr2[p2] = source[i] + bit2.update(nums[i]) + } else { + p1++ + arr1[p1] = source[i] + bit1.update(nums[i]) + } + } + for (i in p1 + 1 until arr1.size) { + arr1[i] = arr2[i - p1 - 1] + } + return arr1 + } + + private fun shrink(nums: IntArray): IntArray { + val b = LongArray(nums.size) + for (i in nums.indices) { + b[i] = nums[i].toLong() shl 32 or i.toLong() + } + b.sort() + val result = IntArray(nums.size) + var p = 1 + for (i in nums.indices) { + if (i > 0 && (b[i] xor b[i - 1]) shr 32 != 0L) { + p++ + } + result[b[i].toInt()] = p + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3074_apple_redistribution_into_boxes/readme.md b/src/main/kotlin/g3001_3100/s3074_apple_redistribution_into_boxes/readme.md new file mode 100644 index 00000000..e53e7ab3 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3074_apple_redistribution_into_boxes/readme.md @@ -0,0 +1,72 @@ +[![](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) + +## 3074\. Apple Redistribution into Boxes + +Easy + +You are given an array `apple` of size `n` and an array `capacity` of size `m`. + +There are `n` packs where the ith pack contains `apple[i]` apples. There are `m` boxes as well, and the ith box has a capacity of `capacity[i]` apples. + +Return _the **minimum** number of boxes you need to select to redistribute these_ `n` _packs of apples into boxes_. + +**Note** that, apples from the same pack can be distributed into different boxes. + +**Example 1:** + +**Input:** apple = [1,3,2], capacity = [4,3,1,5,2] + +**Output:** 2 + +**Explanation:** We will use boxes with capacities 4 and 5. It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples. + +**Example 2:** + +**Input:** apple = [5,5,5], capacity = [2,4,2,7] + +**Output:** 4 + +**Explanation:** We will need to use all the boxes. + +**Constraints:** + +* `1 <= n == apple.length <= 50` +* `1 <= m == capacity.length <= 50` +* `1 <= apple[i], capacity[i] <= 50` +* The input is generated such that it's possible to redistribute packs of apples into boxes. + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun minimumBoxes(apple: IntArray, capacity: IntArray): Int { + val count = IntArray(51) + var appleSum = 0 + for (j in apple) { + appleSum += j + } + var reqCapacity = 0 + var max = 0 + for (j in capacity) { + count[j]++ + max = max(max.toDouble(), j.toDouble()).toInt() + } + for (i in max downTo 0) { + if (count[i] >= 1) { + while (count[i] != 0) { + appleSum -= i + reqCapacity++ + if (appleSum <= 0) { + return reqCapacity + } + count[i]-- + } + } + } + return reqCapacity + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3075_maximize_happiness_of_selected_children/readme.md b/src/main/kotlin/g3001_3100/s3075_maximize_happiness_of_selected_children/readme.md new file mode 100644 index 00000000..8e1dc3f3 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3075_maximize_happiness_of_selected_children/readme.md @@ -0,0 +1,73 @@ +[![](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) + +## 3075\. Maximize Happiness of Selected Children + +Medium + +You are given an array `happiness` of length `n`, and a **positive** integer `k`. + +There are `n` children standing in a queue, where the ith child has **happiness value** `happiness[i]`. You want to select `k` children from these `n` children in `k` turns. + +In each turn, when you select a child, the **happiness value** of all the children that have **not** been selected till now decreases by `1`. Note that the happiness value **cannot** become negative and gets decremented **only** if it is positive. + +Return _the **maximum** sum of the happiness values of the selected children you can achieve by selecting_ `k` _children_. + +**Example 1:** + +**Input:** happiness = [1,2,3], k = 2 + +**Output:** 4 + +**Explanation:** We can pick 2 children in the following way: +- Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0,1]. +- Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0. + +The sum of the happiness values of the selected children is 3 + 1 = 4. + +**Example 2:** + +**Input:** happiness = [1,1,1,1], k = 2 + +**Output:** 1 + +**Explanation:** We can pick 2 children in the following way: +- Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0,0,0]. +- Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0,0]. + +The sum of the happiness values of the selected children is 1 + 0 = 1. + +**Example 3:** + +**Input:** happiness = [2,3,4,5], k = 1 + +**Output:** 5 + +**Explanation:** We can pick 1 child in the following way: +- Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1,2,3]. + +The sum of the happiness values of the selected children is 5. + +**Constraints:** + +* 1 <= n == happiness.length <= 2 * 105 +* 1 <= happiness[i] <= 108 +* `1 <= k <= n` + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun maximumHappinessSum(happiness: IntArray, k: Int): Long { + happiness.sort() + var sum: Long = 0 + for (i in happiness.size - 1 downTo happiness.size - k) { + happiness[i] = max(0, happiness[i] - (happiness.size - 1 - i)) + sum += happiness[i].toLong() + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3076_shortest_uncommon_substring_in_an_array/readme.md b/src/main/kotlin/g3001_3100/s3076_shortest_uncommon_substring_in_an_array/readme.md new file mode 100644 index 00000000..631c1e95 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3076_shortest_uncommon_substring_in_an_array/readme.md @@ -0,0 +1,124 @@ +[![](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) + +## 3076\. Shortest Uncommon Substring in an Array + +Medium + +You are given an array `arr` of size `n` consisting of **non-empty** strings. + +Find a string array `answer` of size `n` such that: + +* `answer[i]` is the **shortest** substring of `arr[i]` that does **not** occur as a substring in any other string in `arr`. If multiple such substrings exist, `answer[i]` should be the lexicographically smallest. And if no such substring exists, `answer[i]` should be an empty string. + +Return _the array_ `answer`. + +**Example 1:** + +**Input:** arr = ["cab","ad","bad","c"] + +**Output:** ["ab","","ba",""] + +**Explanation:** We have the following: +- For the string "cab", the shortest substring that does not occur in any other string is either "ca" or "ab", we choose the lexicographically smaller substring, which is "ab". +- For the string "ad", there is no substring that does not occur in any other string. +- For the string "bad", the shortest substring that does not occur in any other string is "ba". +- For the string "c", there is no substring that does not occur in any other string. + +**Example 2:** + +**Input:** arr = ["abc","bcd","abcd"] + +**Output:** ["","","abcd"] + +**Explanation:** We have the following: +- For the string "abc", there is no substring that does not occur in any other string. +- For the string "bcd", there is no substring that does not occur in any other string. +- For the string "abcd", the shortest substring that does not occur in any other string is "abcd". + +**Constraints:** + +* `n == arr.length` +* `2 <= n <= 100` +* `1 <= arr[i].length <= 20` +* `arr[i]` consists only of lowercase English letters. + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + private val root = Trie() + + fun shortestSubstrings(arr: Array): Array { + val n = arr.size + for (k in 0 until n) { + val s = arr[k] + val cs = s.toCharArray() + val m = cs.size + for (i in 0 until m) { + insert(cs, i, m, k) + } + } + val ans = arrayOfNulls(n) + for (k in 0 until n) { + val s = arr[k] + val cs = s.toCharArray() + val m = cs.size + var result = "" + var resultLen = m + 1 + for (i in 0 until m) { + val curLen = search( + cs, i, + min(m.toDouble(), (i + resultLen).toDouble()) + .toInt(), + k + ) + if (curLen != -1) { + val sub = String(cs, i, curLen) + if (curLen < resultLen || result.compareTo(sub) > 0) { + result = sub + resultLen = curLen + } + } + } + ans[k] = result + } + return ans + } + + private fun insert(cs: CharArray, start: Int, end: Int, wordIndex: Int) { + var curr: Trie? = root + for (i in start until end) { + val index = cs[i].code - 'a'.code + if (curr!!.children[index] == null) { + curr.children[index] = Trie() + } + curr = curr.children[index] + if (curr!!.wordIndex == -1 || curr.wordIndex == wordIndex) { + curr.wordIndex = wordIndex + } else { + curr.wordIndex = -2 + } + } + } + + private fun search(cs: CharArray, start: Int, end: Int, wordIndex: Int): Int { + var cur: Trie? = root + for (i in start until end) { + val index = cs[i].code - 'a'.code + cur = cur!!.children[index] + if (cur!!.wordIndex == wordIndex) { + return i - start + 1 + } + } + return -1 + } + + private class Trie { + var children: Array = arrayOfNulls(26) + var wordIndex: Int = -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3077_maximum_strength_of_k_disjoint_subarrays/readme.md b/src/main/kotlin/g3001_3100/s3077_maximum_strength_of_k_disjoint_subarrays/readme.md new file mode 100644 index 00000000..0981b772 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3077_maximum_strength_of_k_disjoint_subarrays/readme.md @@ -0,0 +1,96 @@ +[![](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) + +## 3077\. Maximum Strength of K Disjoint Subarrays + +Hard + +You are given a **0-indexed** array of integers `nums` of length `n`, and a **positive** **odd** integer `k`. + +The strength of `x` subarrays is defined as `strength = sum[1] * x - sum[2] * (x - 1) + sum[3] * (x - 2) - sum[4] * (x - 3) + ... + sum[x] * 1` where `sum[i]` is the sum of the elements in the ith subarray. Formally, strength is sum of (-1)i+1 * sum[i] * (x - i + 1) over all `i`'s such that `1 <= i <= x`. + +You need to select `k` **disjoint subarrays** from `nums`, such that their **strength** is **maximum**. + +Return _the **maximum** possible **strength** that can be obtained_. + +**Note** that the selected subarrays **don't** need to cover the entire array. + +**Example 1:** + +**Input:** nums = [1,2,3,-1,2], k = 3 + +**Output:** 22 + +**Explanation:** The best possible way to select 3 subarrays is: nums[0..2], nums[3..3], and nums[4..4]. The strength is (1 + 2 + 3) \* 3 - (-1) \* 2 + 2 \* 1 = 22. + +**Example 2:** + +**Input:** nums = [12,-2,-2,-2,-2], k = 5 + +**Output:** 64 + +**Explanation:** The only possible way to select 5 disjoint subarrays is: nums[0..0], nums[1..1], nums[2..2], nums[3..3], and nums[4..4]. The strength is 12 \* 5 - (-2) \* 4 + (-2) \* 3 - (-2) \* 2 + (-2) \* 1 = 64. + +**Example 3:** + +**Input:** nums = [-1,-2,-3], k = 1 + +**Output:** -1 + +**Explanation:** The best possible way to select 1 subarray is: nums[0..0]. The strength is -1. + +**Constraints:** + +* 1 <= n <= 104 +* -109 <= nums[i] <= 109 +* `1 <= k <= n` +* 1 <= n * k <= 106 +* `k` is odd. + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun maximumStrength(n: IntArray, k: Int): Long { + if (n.size == 1) { + return n[0].toLong() + } + val dp = Array(n.size) { LongArray(k) } + dp[0][0] = k.toLong() * n[0] + for (i in 1 until k) { + var pm: Long = -1 + dp[i][0] = (max(0, dp[i - 1][0]) + k.toLong() * n[i]) + for (j in 1 until i) { + dp[i][j] = ( + max( + dp[i - 1][j], + dp[i - 1][j - 1] + ) + (k.toLong() - j) * n[i] * pm + ) + pm = -pm + } + dp[i][i] = dp[i - 1][i - 1] + (k.toLong() - i) * n[i] * pm + } + var max = dp[k - 1][k - 1] + for (i in k until n.size) { + var pm: Long = 1 + dp[i][0] = (max(0, dp[i - 1][0]) + k.toLong() * n[i]) + for (j in 1 until k) { + pm = -pm + dp[i][j] = ( + max( + dp[i - 1][j], + dp[i - 1][j - 1] + ) + (k.toLong() - j) * n[i] * pm + ) + } + if (max < dp[i][k - 1]) { + max = dp[i][k - 1] + } + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3079_find_the_sum_of_encrypted_integers/readme.md b/src/main/kotlin/g3001_3100/s3079_find_the_sum_of_encrypted_integers/readme.md new file mode 100644 index 00000000..1ca70005 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3079_find_the_sum_of_encrypted_integers/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) + +## 3079\. Find the Sum of Encrypted Integers + +Easy + +You are given an integer array `nums` containing **positive** integers. We define a function `encrypt` such that `encrypt(x)` replaces **every** digit in `x` with the **largest** digit in `x`. For example, `encrypt(523) = 555` and `encrypt(213) = 333`. + +Return _the **sum** of encrypted elements_. + +**Example 1:** + +**Input:** nums = [1,2,3] + +**Output:** 6 + +**Explanation:** The encrypted elements are `[1,2,3]`. The sum of encrypted elements is `1 + 2 + 3 == 6`. + +**Example 2:** + +**Input:** nums = [10,21,31] + +**Output:** 66 + +**Explanation:** The encrypted elements are `[11,22,33]`. The sum of encrypted elements is `11 + 22 + 33 == 66`. + +**Constraints:** + +* `1 <= nums.length <= 50` +* `1 <= nums[i] <= 1000` + +## Solution + +```kotlin +import kotlin.math.max + +@Suppress("NAME_SHADOWING") +class Solution { + private fun encrypt(x: Int): Int { + var x = x + var nDigits = 0 + var max = 0 + while (x > 0) { + max = max(max, (x % 10)) + x /= 10 + nDigits++ + } + var ans = 0 + for (i in 0 until nDigits) { + ans = ans * 10 + max + } + return ans + } + + fun sumOfEncryptedInt(nums: IntArray): Int { + var ret = 0 + for (num in nums) { + ret += encrypt(num) + } + return ret + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3080_mark_elements_on_array_by_performing_queries/readme.md b/src/main/kotlin/g3001_3100/s3080_mark_elements_on_array_by_performing_queries/readme.md new file mode 100644 index 00000000..0069fce9 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3080_mark_elements_on_array_by_performing_queries/readme.md @@ -0,0 +1,135 @@ +[![](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) + +## 3080\. Mark Elements on Array by Performing Queries + +Medium + +You are given a **0-indexed** array `nums` of size `n` consisting of positive integers. + +You are also given a 2D array `queries` of size `m` where queries[i] = [indexi, ki]. + +Initially all elements of the array are **unmarked**. + +You need to apply `m` queries on the array in order, where on the ith query you do the following: + +* Mark the element at index indexi if it is not already marked. +* Then mark ki unmarked elements in the array with the **smallest** values. If multiple such elements exist, mark the ones with the smallest indices. And if less than ki unmarked elements exist, then mark all of them. + +Return _an array answer of size_ `m` _where_ `answer[i]` _is the **sum** of unmarked elements in the array after the_ ith _query_. + +**Example 1:** + +**Input:** nums = [1,2,2,1,2,3,1], queries = \[\[1,2],[3,3],[4,2]] + +**Output:** [8,3,0] + +**Explanation:** + +We do the following queries on the array: + +* Mark the element at index `1`, and `2` of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are nums = [**1**,**2**,2,**1**,2,3,1]. The sum of unmarked elements is `2 + 2 + 3 + 1 = 8`. +* Mark the element at index `3`, since it is already marked we skip it. Then we mark `3` of the smallest unmarked elements with the smallest indices, the marked elements now are nums = [**1**,**2**,**2**,**1**,**2**,3,**1**]. The sum of unmarked elements is `3`. +* Mark the element at index `4`, since it is already marked we skip it. Then we mark `2` of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are nums = [**1**,**2**,**2**,**1**,**2**,**3**,**1**]. The sum of unmarked elements is `0`. + +**Example 2:** + +**Input:** nums = [1,4,2,3], queries = \[\[0,1]] + +**Output:** [7] + +**Explanation:** We do one query which is mark the element at index `0` and mark the smallest element among unmarked elements. The marked elements will be nums = [**1**,4,**2**,3], and the sum of unmarked elements is `4 + 3 = 7`. + +**Constraints:** + +* `n == nums.length` +* `m == queries.length` +* 1 <= m <= n <= 105 +* 1 <= nums[i] <= 105 +* `queries[i].length == 2` +* 0 <= indexi, ki <= n - 1 + +## Solution + +```kotlin +@Suppress("kotlin:S1871") +class Solution { + fun unmarkedSumArray(nums: IntArray, queries: Array): LongArray { + val l = nums.size + val orig = IntArray(l) + for (i in 0 until l) { + orig[i] = i + } + var x = 1 + while (x < l) { + val temp = IntArray(l) + val teor = IntArray(l) + var y = 0 + while (y < l) { + var s1 = 0 + var s2 = 0 + while (s1 + s2 < 2 * x && y + s1 + s2 < l) { + if (s2 >= x || y + x + s2 >= l) { + temp[y + s1 + s2] = nums[y + s1] + teor[y + s1 + s2] = orig[y + s1] + s1++ + } else if (s1 >= x) { + temp[y + s1 + s2] = nums[y + x + s2] + teor[y + s1 + s2] = orig[y + x + s2] + s2++ + } else if (nums[y + s1] <= nums[y + x + s2]) { + temp[y + s1 + s2] = nums[y + s1] + teor[y + s1 + s2] = orig[y + s1] + s1++ + } else { + temp[y + s1 + s2] = nums[y + x + s2] + teor[y + s1 + s2] = orig[y + x + s2] + s2++ + } + } + y += 2 * x + } + for (i in 0 until l) { + nums[i] = temp[i] + orig[i] = teor[i] + } + x *= 2 + } + val change = IntArray(l) + for (i in 0 until l) { + change[orig[i]] = i + } + val mark = BooleanArray(l) + val m = queries.size + var st = 0 + var sum: Long = 0 + for (num in nums) { + sum += num.toLong() + } + val out = LongArray(m) + for (i in 0 until m) { + val a = queries[i][0] + if (!mark[change[a]]) { + mark[change[a]] = true + sum -= nums[change[a]].toLong() + } + val b = queries[i][1] + var many = 0 + while (many < b) { + if (st == l) { + out[i] = sum + break + } + if (!mark[st]) { + mark[st] = true + sum -= nums[st].toLong() + many++ + } + st++ + } + out[i] = sum + } + return out + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3081_replace_question_marks_in_string_to_minimize_its_value/readme.md b/src/main/kotlin/g3001_3100/s3081_replace_question_marks_in_string_to_minimize_its_value/readme.md new file mode 100644 index 00000000..a6a34876 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3081_replace_question_marks_in_string_to_minimize_its_value/readme.md @@ -0,0 +1,107 @@ +[![](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) + +## 3081\. Replace Question Marks in String to Minimize Its Value + +Medium + +You are given a string `s`. `s[i]` is either a lowercase English letter or `'?'`. + +For a string `t` having length `m` containing **only** lowercase English letters, we define the function `cost(i)` for an index `i` as the number of characters **equal** to `t[i]` that appeared before it, i.e. in the range `[0, i - 1]`. + +The **value** of `t` is the **sum** of `cost(i)` for all indices `i`. + +For example, for the string `t = "aab"`: + +* `cost(0) = 0` +* `cost(1) = 1` +* `cost(2) = 0` +* Hence, the value of `"aab"` is `0 + 1 + 0 = 1`. + +Your task is to **replace all** occurrences of `'?'` in `s` with any lowercase English letter so that the **value** of `s` is **minimized**. + +Return _a string denoting the modified string with replaced occurrences of_ `'?'`_. If there are multiple strings resulting in the **minimum value**, return the lexicographically smallest one._ + +**Example 1:** + +**Input:** s = "???" + +**Output:** "abc" + +**Explanation:** In this example, we can replace the occurrences of `'?'` to make `s` equal to `"abc"`. + +For `"abc"`, `cost(0) = 0`, `cost(1) = 0`, and `cost(2) = 0`. + +The value of `"abc"` is `0`. + +Some other modifications of `s` that have a value of `0` are `"cba"`, `"abz"`, and, `"hey"`. + +Among all of them, we choose the lexicographically smallest. + +**Example 2:** + +**Input:** s = "a?a?" + +**Output:** "abac" + +**Explanation:** In this example, the occurrences of `'?'` can be replaced to make `s` equal to `"abac"`. + +For `"abac"`, `cost(0) = 0`, `cost(1) = 0`, `cost(2) = 1`, and `cost(3) = 0`. + +The value of `"abac"` is `1`. + +**Constraints:** + +* 1 <= s.length <= 105 +* `s[i]` is either a lowercase English letter or `'?'`. + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + fun minimizeStringValue(s: String): String { + val n = s.length + var time = 0 + val count = IntArray(26) + val res = IntArray(26) + val str = s.toCharArray() + for (c in str) { + if (c != '?') { + count[c.code - 'a'.code]++ + } else { + time++ + } + } + var minTime = Int.MAX_VALUE + for (i in 0..25) { + minTime = min(minTime, count[i]) + } + while (time > 0) { + for (j in 0..25) { + if (count[j] == minTime) { + res[j]++ + count[j]++ + time-- + } + if (time == 0) { + break + } + } + minTime++ + } + var start = 0 + for (i in 0 until n) { + if (str[i] == '?') { + while (res[start] == 0) { + start++ + } + str[i] = ('a'.code + start).toChar() + res[start]-- + } + } + return String(str) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3082_find_the_sum_of_the_power_of_all_subsequences/readme.md b/src/main/kotlin/g3001_3100/s3082_find_the_sum_of_the_power_of_all_subsequences/readme.md new file mode 100644 index 00000000..a7f035d7 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3082_find_the_sum_of_the_power_of_all_subsequences/readme.md @@ -0,0 +1,84 @@ +[![](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) + +## 3082\. Find the Sum of the Power of All Subsequences + +Hard + +You are given an integer array `nums` of length `n` and a **positive** integer `k`. + +The **power** of an array of integers is defined as the number of subsequences with their sum **equal** to `k`. + +Return _the **sum** of **power** of all subsequences of_ `nums`_._ + +Since the answer may be very large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** nums = [1,2,3], k = 3 + +**Output:** 6 + +**Explanation:** + +There are `5` subsequences of nums with non-zero power: + +* The subsequence [**1**,**2**,**3**] has `2` subsequences with `sum == 3`: [1,2,3] and [1,2,3]. +* The subsequence [**1**,2,**3**] has `1` subsequence with `sum == 3`: [1,2,3]. +* The subsequence [1,**2**,**3**] has `1` subsequence with `sum == 3`: [1,2,3]. +* The subsequence [**1**,**2**,3] has `1` subsequence with `sum == 3`: [1,2,3]. +* The subsequence [1,2,**3**] has `1` subsequence with `sum == 3`: [1,2,3]. + +Hence the answer is `2 + 1 + 1 + 1 + 1 = 6`. + +**Example 2:** + +**Input:** nums = [2,3,3], k = 5 + +**Output:** 4 + +**Explanation:** + +There are `3` subsequences of nums with non-zero power: + +* The subsequence [**2**,**3**,**3**] has 2 subsequences with `sum == 5`: [2,3,3] and [2,3,3]. +* The subsequence [**2**,3,**3**] has 1 subsequence with `sum == 5`: [2,3,3]. +* The subsequence [**2**,**3**,3] has 1 subsequence with `sum == 5`: [2,3,3]. + +Hence the answer is `2 + 1 + 1 = 4`. + +**Example 3:** + +**Input:** nums = [1,2,3], k = 7 + +**Output:** 0 + +**Explanation: **There exists no subsequence with sum `7`. Hence all subsequences of nums have `power = 0`. + +**Constraints:** + +* `1 <= n <= 100` +* 1 <= nums[i] <= 104 +* `1 <= k <= 100` + +## Solution + +```kotlin +class Solution { + fun sumOfPower(nums: IntArray, k: Int): Int { + val kMod = 1000000007 + val dp = IntArray(k + 1) + dp[0] = 1 + for (num in nums) { + for (i in k downTo 0) { + if (i < num) { + dp[i] = ((dp[i] * 2L) % kMod).toInt() + } else { + dp[i] = ((dp[i] * 2L + dp[i - num]) % kMod).toInt() + } + } + } + return dp[k] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3083_existence_of_a_substring_in_a_string_and_its_reverse/readme.md b/src/main/kotlin/g3001_3100/s3083_existence_of_a_substring_in_a_string_and_its_reverse/readme.md new file mode 100644 index 00000000..879888e1 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3083_existence_of_a_substring_in_a_string_and_its_reverse/readme.md @@ -0,0 +1,63 @@ +[![](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) + +## 3083\. Existence of a Substring in a String and Its Reverse + +Easy + +Given a string `s`, find any substring of length `2` which is also present in the reverse of `s`. + +Return `true` _if such a substring exists, and_ `false` _otherwise._ + +**Example 1:** + +**Input:** s = "leetcode" + +**Output:** true + +**Explanation:** Substring `"ee"` is of length `2` which is also present in `reverse(s) == "edocteel"`. + +**Example 2:** + +**Input:** s = "abcba" + +**Output:** true + +**Explanation:** All of the substrings of length `2` `"ab"`, `"bc"`, `"cb"`, `"ba"` are also present in `reverse(s) == "abcba"`. + +**Example 3:** + +**Input:** s = "abcd" + +**Output:** false + +**Explanation:** There is no substring of length `2` in `s`, which is also present in the reverse of `s`. + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` consists only of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun isSubstringPresent(s: String): Boolean { + if (s.length == 1) { + return false + } + val revSb = StringBuilder() + for (i in s.length - 1 downTo 0) { + revSb.append(s[i]) + } + val rev = revSb.toString() + for (i in 0 until s.length - 1) { + val sub = s.substring(i, i + 2) + if (rev.contains(sub)) { + return true + } + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3084_count_substrings_starting_and_ending_with_given_character/readme.md b/src/main/kotlin/g3001_3100/s3084_count_substrings_starting_and_ending_with_given_character/readme.md new file mode 100644 index 00000000..94f7c604 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3084_count_substrings_starting_and_ending_with_given_character/readme.md @@ -0,0 +1,45 @@ +[![](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) + +## 3084\. Count Substrings Starting and Ending with Given Character + +Medium + +You are given a string `s` and a character `c`. Return _the total number of substrings of_ `s` _that start and end with_ `c`_._ + +**Example 1:** + +**Input:** s = "abada", c = "a" + +**Output:** 6 + +**Explanation:** Substrings starting and ending with `"a"` are: "**a**bada", "**aba**da", "**abada**", "ab**a**da", "ab**ada**", "abad**a**". + +**Example 2:** + +**Input:** s = "zzz", c = "z" + +**Output:** 6 + +**Explanation:** There are a total of `6` substrings in `s` and all start and end with `"z"`. + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` and `c` consist only of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun countSubstrings(s: String, c: Char): Long { + var count: Long = 0 + for (element in s) { + if (element == c) { + count++ + } + } + return count * (count + 1) / 2 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3085_minimum_deletions_to_make_string_k_special/readme.md b/src/main/kotlin/g3001_3100/s3085_minimum_deletions_to_make_string_k_special/readme.md new file mode 100644 index 00000000..b8359605 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3085_minimum_deletions_to_make_string_k_special/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) + +## 3085\. Minimum Deletions to Make String K-Special + +Medium + +You are given a string `word` and an integer `k`. + +We consider `word` to be **k-special** if `|freq(word[i]) - freq(word[j])| <= k` for all indices `i` and `j` in the string. + +Here, `freq(x)` denotes the frequency of the character `x` in `word`, and `|y|` denotes the absolute value of `y`. + +Return _the **minimum** number of characters you need to delete to make_ `word` **_k-special_**. + +**Example 1:** + +**Input:** word = "aabcaba", k = 0 + +**Output:** 3 + +**Explanation:** We can make `word` `0`\-special by deleting `2` occurrences of `"a"` and `1` occurrence of `"c"`. Therefore, `word` becomes equal to `"baba"` where `freq('a') == freq('b') == 2`. + +**Example 2:** + +**Input:** word = "dabdcbdcdcd", k = 2 + +**Output:** 2 + +**Explanation:** We can make `word` `2`\-special by deleting `1` occurrence of `"a"` and `1` occurrence of `"d"`. Therefore, `word` becomes equal to "bdcbdcdcd" where `freq('b') == 2`, `freq('c') == 3`, and `freq('d') == 4`. + +**Example 3:** + +**Input:** word = "aaabaaa", k = 2 + +**Output:** 1 + +**Explanation:** We can make `word` `2`\-special by deleting `1` occurrence of `"b"`. Therefore, `word` becomes equal to `"aaaaaa"` where each letter's frequency is now uniformly `6`. + +**Constraints:** + +* 1 <= word.length <= 105 +* 0 <= k <= 105 +* `word` consists only of lowercase English letters. + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + fun minimumDeletions(word: String, k: Int): Int { + val arr = IntArray(26) + for (element in word) { + arr[element.code - 'a'.code]++ + } + var min = Int.MAX_VALUE + for (value in arr) { + if (value != 0) { + val u = value + k + var res = 0 + for (i in arr) { + if (i < value) { + res += i + } else if (i > u) { + res += (i - u) + } + } + min = min(res, min) + } + } + return min + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3086_minimum_moves_to_pick_k_ones/readme.md b/src/main/kotlin/g3001_3100/s3086_minimum_moves_to_pick_k_ones/readme.md new file mode 100644 index 00000000..68f79a38 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3086_minimum_moves_to_pick_k_ones/readme.md @@ -0,0 +1,113 @@ +[![](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) + +## 3086\. Minimum Moves to Pick K Ones + +Hard + +You are given a binary array `nums` of length `n`, a **positive** integer `k` and a **non-negative** integer `maxChanges`. + +Alice plays a game, where the goal is for Alice to pick up `k` ones from `nums` using the **minimum** number of **moves**. When the game starts, Alice picks up any index `aliceIndex` in the range `[0, n - 1]` and stands there. If `nums[aliceIndex] == 1` , Alice picks up the one and `nums[aliceIndex]` becomes `0`(this **does not** count as a move). After this, Alice can make **any** number of **moves** (**including** **zero**) where in each move Alice must perform **exactly** one of the following actions: + +* Select any index `j != aliceIndex` such that `nums[j] == 0` and set `nums[j] = 1`. This action can be performed **at** **most** `maxChanges` times. +* Select any two adjacent indices `x` and `y` (`|x - y| == 1`) such that `nums[x] == 1`, `nums[y] == 0`, then swap their values (set `nums[y] = 1` and `nums[x] = 0`). If `y == aliceIndex`, Alice picks up the one after this move and `nums[y]` becomes `0`. + +Return _the **minimum** number of moves required by Alice to pick **exactly**_ `k` _ones_. + +**Example 1:** + +**Input:** nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1 + +**Output:** 3 + +**Explanation:** Alice can pick up `3` ones in `3` moves, if Alice performs the following actions in each move when standing at `aliceIndex == 1`: + +* At the start of the game Alice picks up the one and `nums[1]` becomes `0`. `nums` becomes [1,**1**,1,0,0,1,1,0,0,1]. +* Select `j == 2` and perform an action of the first type. `nums` becomes [1,**0**,1,0,0,1,1,0,0,1] +* Select `x == 2` and `y == 1`, and perform an action of the second type. `nums` becomes [1,**1**,0,0,0,1,1,0,0,1]. As `y == aliceIndex`, Alice picks up the one and `nums` becomes [1,**0**,0,0,0,1,1,0,0,1]. +* Select `x == 0` and `y == 1`, and perform an action of the second type. `nums` becomes [0,**1**,0,0,0,1,1,0,0,1]. As `y == aliceIndex`, Alice picks up the one and `nums` becomes [0,**0**,0,0,0,1,1,0,0,1]. + +Note that it may be possible for Alice to pick up `3` ones using some other sequence of `3` moves. + +**Example 2:** + +**Input:** nums = [0,0,0,0], k = 2, maxChanges = 3 + +**Output:** 4 + +**Explanation:** Alice can pick up `2` ones in `4` moves, if Alice performs the following actions in each move when standing at `aliceIndex == 0`: + +* Select `j == 1` and perform an action of the first type. `nums` becomes [**0**,1,0,0]. +* Select `x == 1` and `y == 0`, and perform an action of the second type. `nums` becomes [**1**,0,0,0]. As `y == aliceIndex`, Alice picks up the one and `nums` becomes [**0**,0,0,0]. +* Select `j == 1` again and perform an action of the first type. `nums` becomes [**0**,1,0,0]. +* Select `x == 1` and `y == 0` again, and perform an action of the second type. `nums` becomes [**1**,0,0,0]. As `y == aliceIndex`, Alice picks up the one and `nums` becomes [**0**,0,0,0]. + +**Constraints:** + +* 2 <= n <= 105 +* `0 <= nums[i] <= 1` +* 1 <= k <= 105 +* 0 <= maxChanges <= 105 +* `maxChanges + sum(nums) >= k` + +## Solution + +```kotlin +import kotlin.math.max +import kotlin.math.min + +class Solution { + fun minimumMoves(nums: IntArray, k: Int, maxChanges: Int): Long { + var maxAdjLen = 0 + val n = nums.size + var numOne = 0 + var l = 0 + var r = 0 + while (r < n) { + if (nums[r] != 1) { + maxAdjLen = max(maxAdjLen, (r - l)) + l = r + 1 + } else { + numOne++ + } + r++ + } + maxAdjLen = min(3, max(maxAdjLen, (r - l))) + if (maxAdjLen + maxChanges >= k) { + return if (maxAdjLen >= k) { + k - 1L + } else { + max(0, (maxAdjLen - 1)) + (k - maxAdjLen) * 2L + } + } + val ones = IntArray(numOne) + var ind = 0 + for (i in 0 until n) { + if (nums[i] == 1) { + ones[ind++] = i + } + } + val preSum = LongArray(ones.size + 1) + for (i in 1 until preSum.size) { + preSum[i] = preSum[i - 1] + ones[i - 1] + } + val target = k - maxChanges + l = 0 + var res = Long.MAX_VALUE + while (l <= ones.size - target) { + r = l + target - 1 + val mid = (l + r) / 2 + val median = ones[mid] + val sum1 = preSum[mid + 1] - preSum[l] + val sum2 = preSum[r + 1] - preSum[mid + 1] + val area1 = (mid - l + 1).toLong() * median + val area2 = (r - mid).toLong() * median + val curRes = area1 - sum1 + sum2 - area2 + res = min(res.toDouble(), curRes.toDouble()).toLong() + l++ + } + res += 2L * maxChanges + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3090_maximum_length_substring_with_two_occurrences/readme.md b/src/main/kotlin/g3001_3100/s3090_maximum_length_substring_with_two_occurrences/readme.md new file mode 100644 index 00000000..d8d722cc --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3090_maximum_length_substring_with_two_occurrences/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) + +## 3090\. Maximum Length Substring With Two Occurrences + +Easy + +Given a string `s`, return the **maximum** length of a substring such that it contains _at most two occurrences_ of each character. + +**Example 1:** + +**Input:** s = "bcbbbcba" + +**Output:** 4 + +**Explanation:** + +The following substring has a length of 4 and contains at most two occurrences of each character: "bcbbbcba". + +**Example 2:** + +**Input:** s = "aaaa" + +**Output:** 2 + +**Explanation:** + +The following substring has a length of 2 and contains at most two occurrences of each character: "aaaa". + +**Constraints:** + +* `2 <= s.length <= 100` +* `s` consists only of lowercase English letters. + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun maximumLengthSubstring(s: String): Int { + val freq = IntArray(26) + val chars = s.toCharArray() + var i = 0 + val len = s.length + var max = 0 + for (j in 0 until len) { + ++freq[chars[j].code - 'a'.code] + while (freq[chars[j].code - 'a'.code] == 3) { + --freq[chars[i].code - 'a'.code] + i++ + } + max = max(max, (j - i + 1)) + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3091_apply_operations_to_make_sum_of_array_greater_than_or_equal_to_k/readme.md b/src/main/kotlin/g3001_3100/s3091_apply_operations_to_make_sum_of_array_greater_than_or_equal_to_k/readme.md new file mode 100644 index 00000000..662cfe82 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3091_apply_operations_to_make_sum_of_array_greater_than_or_equal_to_k/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) + +## 3091\. Apply Operations to Make Sum of Array Greater Than or Equal to k + +Medium + +You are given a **positive** integer `k`. Initially, you have an array `nums = [1]`. + +You can perform **any** of the following operations on the array **any** number of times (**possibly zero**): + +* Choose any element in the array and **increase** its value by `1`. +* Duplicate any element in the array and add it to the end of the array. + +Return _the **minimum** number of operations required to make the **sum** of elements of the final array greater than or equal to_ `k`. + +**Example 1:** + +**Input:** k = 11 + +**Output:** 5 + +**Explanation:** + +We can do the following operations on the array `nums = [1]`: + +* Increase the element by `1` three times. The resulting array is `nums = [4]`. +* Duplicate the element two times. The resulting array is `nums = [4,4,4]`. + +The sum of the final array is `4 + 4 + 4 = 12` which is greater than or equal to `k = 11`. +The total number of operations performed is `3 + 2 = 5`. + +**Example 2:** + +**Input:** k = 1 + +**Output:** 0 + +**Explanation:** + +The sum of the original array is already greater than or equal to `1`, so no operations are needed. + +**Constraints:** + +* 1 <= k <= 105 + +## Solution + +```kotlin +import kotlin.math.sqrt + +class Solution { + fun minOperations(k: Int): Int { + val a = sqrt(k.toDouble()).toInt() + return a + (k - 1) / a - 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3092_most_frequent_ids/readme.md b/src/main/kotlin/g3001_3100/s3092_most_frequent_ids/readme.md new file mode 100644 index 00000000..16de23fd --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3092_most_frequent_ids/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) + +## 3092\. Most Frequent IDs + +Medium + +The problem involves tracking the frequency of IDs in a collection that changes over time. You have two integer arrays, `nums` and `freq`, of equal length `n`. Each element in `nums` represents an ID, and the corresponding element in `freq` indicates how many times that ID should be added to or removed from the collection at each step. + +* **Addition of IDs:** If `freq[i]` is positive, it means `freq[i]` IDs with the value `nums[i]` are added to the collection at step `i`. +* **Removal of IDs:** If `freq[i]` is negative, it means `-freq[i]` IDs with the value `nums[i]` are removed from the collection at step `i`. + +Return an array `ans` of length `n`, where `ans[i]` represents the **count** of the _most frequent ID_ in the collection after the ith step. If the collection is empty at any step, `ans[i]` should be 0 for that step. + +**Example 1:** + +**Input:** nums = [2,3,2,1], freq = [3,2,-3,1] + +**Output:** [3,3,2,2] + +**Explanation:** + +After step 0, we have 3 IDs with the value of 2. So `ans[0] = 3`. +After step 1, we have 3 IDs with the value of 2 and 2 IDs with the value of 3. So `ans[1] = 3`. +After step 2, we have 2 IDs with the value of 3. So `ans[2] = 2`. +After step 3, we have 2 IDs with the value of 3 and 1 ID with the value of 1. So `ans[3] = 2`. + +**Example 2:** + +**Input:** nums = [5,5,3], freq = [2,-2,1] + +**Output:** [2,0,1] + +**Explanation:** + +After step 0, we have 2 IDs with the value of 5. So `ans[0] = 2`. +After step 1, there are no IDs. So `ans[1] = 0`. +After step 2, we have 1 ID with the value of 3. So `ans[2] = 1`. + +**Constraints:** + +* 1 <= nums.length == freq.length <= 105 +* 1 <= nums[i] <= 105 +* -105 <= freq[i] <= 105 +* `freq[i] != 0` +* The input is generated such that the occurrences of an ID will not be negative in any step. + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun mostFrequentIDs(nums: IntArray, freq: IntArray): LongArray { + var max = Int.MIN_VALUE + val n = nums.size + for (num in nums) { + max = max(max.toDouble(), num.toDouble()).toInt() + } + val bins = LongArray(max + 1) + var mostFrequentID = 0 + var maxCount: Long = 0 + val ans = LongArray(n) + for (i in 0 until n) { + bins[nums[i]] += freq[i].toLong() + if (freq[i] > 0) { + if (bins[nums[i]] > maxCount) { + maxCount = bins[nums[i]] + mostFrequentID = nums[i] + } + } else { + if (nums[i] == mostFrequentID) { + maxCount = bins[nums[i]] + for (j in 0..max) { + if (bins[j] > maxCount) { + maxCount = bins[j] + mostFrequentID = j + } + } + } + } + ans[i] = maxCount + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3093_longest_common_suffix_queries/readme.md b/src/main/kotlin/g3001_3100/s3093_longest_common_suffix_queries/readme.md new file mode 100644 index 00000000..25019bd9 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3093_longest_common_suffix_queries/readme.md @@ -0,0 +1,116 @@ +[![](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) + +## 3093\. Longest Common Suffix Queries + +Hard + +You are given two arrays of strings `wordsContainer` and `wordsQuery`. + +For each `wordsQuery[i]`, you need to find a string from `wordsContainer` that has the **longest common suffix** with `wordsQuery[i]`. If there are two or more strings in `wordsContainer` that share the longest common suffix, find the string that is the **smallest** in length. If there are two or more such strings that have the **same** smallest length, find the one that occurred **earlier** in `wordsContainer`. + +Return _an array of integers_ `ans`_, where_ `ans[i]` _is the index of the string in_ `wordsContainer` _that has the **longest common suffix** with_ `wordsQuery[i]`_._ + +**Example 1:** + +**Input:** wordsContainer = ["abcd","bcd","xbcd"], wordsQuery = ["cd","bcd","xyz"] + +**Output:** [1,1,1] + +**Explanation:** + +Let's look at each `wordsQuery[i]` separately: + +* For `wordsQuery[0] = "cd"`, strings from `wordsContainer` that share the longest common suffix `"cd"` are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3. +* For `wordsQuery[1] = "bcd"`, strings from `wordsContainer` that share the longest common suffix `"bcd"` are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3. +* For `wordsQuery[2] = "xyz"`, there is no string from `wordsContainer` that shares a common suffix. Hence the longest common suffix is `""`, that is shared with strings at index 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3. + +**Example 2:** + +**Input:** wordsContainer = ["abcdefgh","poiuygh","ghghgh"], wordsQuery = ["gh","acbfgh","acbfegh"] + +**Output:** [2,0,2] + +**Explanation:** + +Let's look at each `wordsQuery[i]` separately: + +* For `wordsQuery[0] = "gh"`, strings from `wordsContainer` that share the longest common suffix `"gh"` are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6. +* For `wordsQuery[1] = "acbfgh"`, only the string at index 0 shares the longest common suffix `"fgh"`. Hence it is the answer, even though the string at index 2 is shorter. +* For `wordsQuery[2] = "acbfegh"`, strings from `wordsContainer` that share the longest common suffix `"gh"` are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6. + +**Constraints:** + +* 1 <= wordsContainer.length, wordsQuery.length <= 104 +* 1 <= wordsContainer[i].length <= 5 * 103 +* 1 <= wordsQuery[i].length <= 5 * 103 +* `wordsContainer[i]` consists only of lowercase English letters. +* `wordsQuery[i]` consists only of lowercase English letters. +* Sum of `wordsContainer[i].length` is at most 5 * 105. +* Sum of `wordsQuery[i].length` is at most 5 * 105. + +## Solution + +```kotlin +class Solution { + fun stringIndices(wc: Array, wq: Array): IntArray { + var minLength = wc[0].length + var minIndex = 0 + val n = wc.size + val m = wq.size + for (i in 0 until n) { + if (minLength > wc[i].length) { + minLength = wc[i].length + minIndex = i + } + } + val root = Trie(minIndex) + for (i in 0 until n) { + var curr: Trie? = root + for (j in wc[i].length - 1 downTo 0) { + val ch = wc[i][j] + if (curr!!.has(ch)) { + val next = curr.get(ch) + if (wc[next!!.index].length > wc[i].length) { + next.index = i + } + curr = next + } else { + curr.put(ch, i) + curr = curr.get(ch) + } + } + } + val ans = IntArray(m) + for (i in 0 until m) { + var curr: Trie? = root + for (j in wq[i].length - 1 downTo 0) { + val ch = wq[i][j] + if (curr!!.has(ch)) { + curr = curr.get(ch) + } else { + break + } + } + ans[i] = curr!!.index + } + return ans + } + + private class Trie(var index: Int) { + var ch: Array = arrayOfNulls(26) + + fun get(ch: Char): Trie? { + return this.ch[ch.code - 'a'.code] + } + + fun has(ch: Char): Boolean { + return this.ch[ch.code - 'a'.code] != null + } + + fun put(ch: Char, index: Int) { + this.ch[ch.code - 'a'.code] = Trie(index) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3095_shortest_subarray_with_or_at_least_k_i/readme.md b/src/main/kotlin/g3001_3100/s3095_shortest_subarray_with_or_at_least_k_i/readme.md new file mode 100644 index 00000000..3f88e8fd --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3095_shortest_subarray_with_or_at_least_k_i/readme.md @@ -0,0 +1,72 @@ +[![](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) + +## 3095\. Shortest Subarray With OR at Least K I + +Easy + +You are given an array `nums` of **non-negative** integers and an integer `k`. + +An array is called **special** if the bitwise `OR` of all of its elements is **at least** `k`. + +Return _the length of the **shortest** **special** **non-empty** subarray of_ `nums`, _or return_ `-1` _if no special subarray exists_. + +**Example 1:** + +**Input:** nums = [1,2,3], k = 2 + +**Output:** 1 + +**Explanation:** + +The subarray `[3]` has `OR` value of `3`. Hence, we return `1`. + +**Example 2:** + +**Input:** nums = [2,1,8], k = 10 + +**Output:** 3 + +**Explanation:** + +The subarray `[2,1,8]` has `OR` value of `11`. Hence, we return `3`. + +**Example 3:** + +**Input:** nums = [1,2], k = 0 + +**Output:** 1 + +**Explanation:** + +The subarray `[1]` has `OR` value of `1`. Hence, we return `1`. + +**Constraints:** + +* `1 <= nums.length <= 50` +* `0 <= nums[i] <= 50` +* `0 <= k < 64` + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + fun minimumSubarrayLength(nums: IntArray, k: Int): Int { + val n = nums.size + var maxL = n + 1 + var `val`: Int + for (i in 0 until n) { + `val` = 0 + for (j in i until n) { + `val` = `val` or nums[j] + if (`val` >= k) { + maxL = min(maxL, (j - i + 1)) + } + } + } + return if (maxL == n + 1) -1 else maxL + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3096_minimum_levels_to_gain_more_points/readme.md b/src/main/kotlin/g3001_3100/s3096_minimum_levels_to_gain_more_points/readme.md new file mode 100644 index 00000000..e9d09722 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3096_minimum_levels_to_gain_more_points/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) + +## 3096\. Minimum Levels to Gain More Points + +Medium + +You are given a binary array `possible` of length `n`. + +Alice and Bob are playing a game that consists of `n` levels. Some of the levels in the game are **impossible** to clear while others can **always** be cleared. In particular, if `possible[i] == 0`, then the ith level is **impossible** to clear for **both** the players. A player gains `1` point on clearing a level and loses `1` point if the player fails to clear it. + +At the start of the game, Alice will play some levels in the **given order** starting from the 0th level, after which Bob will play for the rest of the levels. + +Alice wants to know the **minimum** number of levels she should play to gain more points than Bob, if both players play optimally to **maximize** their points. + +Return _the **minimum** number of levels Alice should play to gain more points_. _If this is **not** possible, return_ `-1`. + +**Note** that each player must play at least `1` level. + +**Example 1:** + +**Input:** possible = [1,0,1,0] + +**Output:** 1 + +**Explanation:** + +Let's look at all the levels that Alice can play up to: + +* If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has -1 + 1 - 1 = -1 point. +* If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 1 - 1 = 0 points, while Bob has 1 - 1 = 0 points. +* If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 1 - 1 + 1 = 1 point, while Bob has -1 point. + +Alice must play a minimum of 1 level to gain more points. + +**Example 2:** + +**Input:** possible = [1,1,1,1,1] + +**Output:** 3 + +**Explanation:** + +Let's look at all the levels that Alice can play up to: + +* If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has 4 points. +* If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 2 points, while Bob has 3 points. +* If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 3 points, while Bob has 2 points. +* If Alice plays till level 3 and Bob plays the rest of the levels, Alice has 4 points, while Bob has 1 point. + +Alice must play a minimum of 3 levels to gain more points. + +**Example 3:** + +**Input:** possible = [0,0] + +**Output:** \-1 + +**Explanation:** + +The only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points, Alice can't gain more points than Bob. + +**Constraints:** + +* 2 <= n == possible.length <= 105 +* `possible[i]` is either `0` or `1`. + +## Solution + +```kotlin +class Solution { + fun minimumLevels(possible: IntArray): Int { + val n = possible.size + var sum = 0 + for (p in possible) { + sum += p + } + if (sum == 0 && n == 2) { + return -1 + } + if (sum == 0 && n > 2) { + return 1 + } + var sumLeft = 0 + for (i in 0 until n - 1) { + sumLeft += possible[i] + val sumRight = sum - sumLeft + val danScore = sumLeft - ((i + 1) - sumLeft) + val bobScore = sumRight - ((n - i - 1) - sumRight) + if (danScore > bobScore) { + return i + 1 + } + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3097_shortest_subarray_with_or_at_least_k_ii/readme.md b/src/main/kotlin/g3001_3100/s3097_shortest_subarray_with_or_at_least_k_ii/readme.md new file mode 100644 index 00000000..b7540849 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3097_shortest_subarray_with_or_at_least_k_ii/readme.md @@ -0,0 +1,81 @@ +[![](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) + +## 3097\. Shortest Subarray With OR at Least K II + +Medium + +You are given an array `nums` of **non-negative** integers and an integer `k`. + +An array is called **special** if the bitwise `OR` of all of its elements is **at least** `k`. + +Return _the length of the **shortest** **special** **non-empty** subarray of_ `nums`, _or return_ `-1` _if no special subarray exists_. + +**Example 1:** + +**Input:** nums = [1,2,3], k = 2 + +**Output:** 1 + +**Explanation:** + +The subarray `[3]` has `OR` value of `3`. Hence, we return `1`. + +**Example 2:** + +**Input:** nums = [2,1,8], k = 10 + +**Output:** 3 + +**Explanation:** + +The subarray `[2,1,8]` has `OR` value of `11`. Hence, we return `3`. + +**Example 3:** + +**Input:** nums = [1,2], k = 0 + +**Output:** 1 + +**Explanation:** + +The subarray `[1]` has `OR` value of `1`. Hence, we return `1`. + +**Constraints:** + +* 1 <= nums.length <= 2 * 105 +* 0 <= nums[i] <= 109 +* 0 <= k <= 109 + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + fun minimumSubarrayLength(nums: IntArray, k: Int): Int { + val n = nums.size + if (nums[0] >= k) { + return 1 + } + var res = Int.MAX_VALUE + for (i in 1 until n) { + if (nums[i] >= k) { + return 1 + } + var j = i - 1 + while (j >= 0 && (nums[i] or nums[j]) != nums[j]) { + nums[j] = nums[j] or nums[i] + if (nums[j] >= k) { + res = min(res, (i - j + 1)) + } + j-- + } + } + if (res == Int.MAX_VALUE) { + return -1 + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3098_find_the_sum_of_subsequence_powers/readme.md b/src/main/kotlin/g3001_3100/s3098_find_the_sum_of_subsequence_powers/readme.md new file mode 100644 index 00000000..784ee950 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3098_find_the_sum_of_subsequence_powers/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) + +## 3098\. Find the Sum of Subsequence Powers + +Hard + +You are given an integer array `nums` of length `n`, and a **positive** integer `k`. + +The **power** of a subsequence is defined as the **minimum** absolute difference between **any** two elements in the subsequence. + +Return _the **sum** of **powers** of **all** subsequences of_ `nums` _which have length_ **_equal to_** `k`. + +Since the answer may be large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** nums = [1,2,3,4], k = 3 + +**Output:** 4 + +**Explanation:** + +There are 4 subsequences in `nums` which have length 3: `[1,2,3]`, `[1,3,4]`, `[1,2,4]`, and `[2,3,4]`. The sum of powers is `|2 - 3| + |3 - 4| + |2 - 1| + |3 - 4| = 4`. + +**Example 2:** + +**Input:** nums = [2,2], k = 2 + +**Output:** 0 + +**Explanation:** + +The only subsequence in `nums` which has length 2 is `[2,2]`. The sum of powers is `|2 - 2| = 0`. + +**Example 3:** + +**Input:** nums = [4,3,-1], k = 2 + +**Output:** 10 + +**Explanation:** + +There are 3 subsequences in `nums` which have length 2: `[4,3]`, `[4,-1]`, and `[3,-1]`. The sum of powers is `|4 - 3| + |4 - (-1)| + |3 - (-1)| = 10`. + +**Constraints:** + +* `2 <= n == nums.length <= 50` +* -108 <= nums[i] <= 108 +* `2 <= k <= n` + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + private var len = 0 + + private fun dfs(lastIdx: Int, k: Int, minDiff: Int, dp: MutableMap, nums: IntArray): Int { + if (k == 0) { + return minDiff + } + val key = ((minDiff.toLong()) shl 12) + (lastIdx.toLong() shl 6) + k + if (dp.containsKey(key)) { + return dp[key]!! + } + var res = 0 + for (i in lastIdx + 1..len - k) { + res = ( + res + dfs( + i, k - 1, min(minDiff, (nums[i] - nums[lastIdx])), dp, nums + ) + ) % MOD + } + dp[key] = res + return res + } + + fun sumOfPowers(nums: IntArray, k: Int): Int { + len = nums.size + nums.sort() + val dp: MutableMap = HashMap() + var res = 0 + for (i in 0..len - k) { + res = (res + dfs(i, k - 1, nums[len - 1] - nums[0], dp, nums)) % MOD + } + return res + } + + companion object { + private const val MOD = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3099_harshad_number/readme.md b/src/main/kotlin/g3001_3100/s3099_harshad_number/readme.md new file mode 100644 index 00000000..5c258430 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3099_harshad_number/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) + +## 3099\. Harshad Number + +Easy + +An integer divisible by the **sum** of its digits is said to be a **Harshad** number. You are given an integer `x`. Return _the sum of the digits_ of `x` if `x` is a **Harshad** number, otherwise, return `-1`_._ + +**Example 1:** + +**Input:** x = 18 + +**Output:** 9 + +**Explanation:** + +The sum of digits of `x` is `9`. `18` is divisible by `9`. So `18` is a Harshad number and the answer is `9`. + +**Example 2:** + +**Input:** x = 23 + +**Output:** \-1 + +**Explanation:** + +The sum of digits of `x` is `5`. `23` is not divisible by `5`. So `23` is not a Harshad number and the answer is `-1`. + +**Constraints:** + +* `1 <= x <= 100` + +## Solution + +```kotlin +class Solution { + fun sumOfTheDigitsOfHarshadNumber(x: Int): Int { + var sum = 0 + var digit: Int + var temp = x + while (temp != 0) { + digit = temp % 10 + sum += digit + temp /= 10 + } + if (sum != 0 && x % sum == 0) { + return sum + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3100_water_bottles_ii/readme.md b/src/main/kotlin/g3001_3100/s3100_water_bottles_ii/readme.md new file mode 100644 index 00000000..6099fb11 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3100_water_bottles_ii/readme.md @@ -0,0 +1,61 @@ +[![](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) + +## 3100\. Water Bottles II + +Medium + +You are given two integers `numBottles` and `numExchange`. + +`numBottles` represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations: + +* Drink any number of full water bottles turning them into empty bottles. +* Exchange `numExchange` empty bottles with one full water bottle. Then, increase `numExchange` by one. + +Note that you cannot exchange multiple batches of empty bottles for the same value of `numExchange`. For example, if `numBottles == 3` and `numExchange == 1`, you cannot exchange `3` empty water bottles for `3` full bottles. + +Return _the **maximum** number of water bottles you can drink_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2024/01/28/exampleone1.png) + +**Input:** numBottles = 13, numExchange = 6 + +**Output:** 15 + +**Explanation:** The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2024/01/28/example231.png) + +**Input:** numBottles = 10, numExchange = 3 + +**Output:** 13 + +**Explanation:** The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. + +**Constraints:** + +* `1 <= numBottles <= 100` +* `1 <= numExchange <= 100` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun maxBottlesDrunk(numBottles: Int, numExchange: Int): Int { + var numExchange = numExchange + var emptyBottles = numBottles + var bottleDrinks = numBottles + while (numExchange <= emptyBottles) { + bottleDrinks += 1 + emptyBottles = 1 + (emptyBottles - numExchange) + numExchange++ + } + return bottleDrinks + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3101_3200/s3101_count_alternating_subarrays/readme.md b/src/main/kotlin/g3101_3200/s3101_count_alternating_subarrays/readme.md new file mode 100644 index 00000000..fb13ae8b --- /dev/null +++ b/src/main/kotlin/g3101_3200/s3101_count_alternating_subarrays/readme.md @@ -0,0 +1,63 @@ +[![](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) + +## 3101\. Count Alternating Subarrays + +Medium + +You are given a binary array `nums`. + +We call a subarray **alternating** if **no** two **adjacent** elements in the subarray have the **same** value. + +Return _the number of alternating subarrays in_ `nums`. + +**Example 1:** + +**Input:** nums = [0,1,1,1] + +**Output:** 5 + +**Explanation:** + +The following subarrays are alternating: `[0]`, `[1]`, `[1]`, `[1]`, and `[0,1]`. + +**Example 2:** + +**Input:** nums = [1,0,1,0] + +**Output:** 10 + +**Explanation:** + +Every subarray of the array is alternating. There are 10 possible subarrays that we can choose. + +**Constraints:** + +* 1 <= nums.length <= 105 +* `nums[i]` is either `0` or `1`. + +## Solution + +```kotlin +class Solution { + fun countAlternatingSubarrays(nums: IntArray): Long { + var count: Long = 0 + var length: Long + var start = 0 + var end = 1 + while (end < nums.size) { + if (nums[end] != nums[end - 1]) { + end++ + } else { + length = end - start.toLong() + count += (length * (length + 1)) / 2 + start = end + end++ + } + } + length = end - start.toLong() + count += (length * (length + 1)) / 2 + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3101_3200/s3102_minimize_manhattan_distances/readme.md b/src/main/kotlin/g3101_3200/s3102_minimize_manhattan_distances/readme.md new file mode 100644 index 00000000..7c5fe36c --- /dev/null +++ b/src/main/kotlin/g3101_3200/s3102_minimize_manhattan_distances/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) + +## 3102\. Minimize Manhattan Distances + +Hard + +You are given a array `points` representing integer coordinates of some points on a 2D plane, where points[i] = [xi, yi]. + +The distance between two points is defined as their Manhattan distance. + +Return _the **minimum** possible value for **maximum** distance between any two points by removing exactly one point_. + +**Example 1:** + +**Input:** points = \[\[3,10],[5,15],[10,2],[4,4]] + +**Output:** 12 + +**Explanation:** + +The maximum distance after removing each point is the following: + +* After removing the 0th point the maximum distance is between points (5, 15) and (10, 2), which is `|5 - 10| + |15 - 2| = 18`. +* After removing the 1st point the maximum distance is between points (3, 10) and (10, 2), which is `|3 - 10| + |10 - 2| = 15`. +* After removing the 2nd point the maximum distance is between points (5, 15) and (4, 4), which is `|5 - 4| + |15 - 4| = 12`. +* After removing the 3rd point the maximum distance is between points (5, 15) and (10, 2), which is `|5 - 10| + |15 - 2| = 18`. + +12 is the minimum possible maximum distance between any two points after removing exactly one point. + +**Example 2:** + +**Input:** points = \[\[1,1],[1,1],[1,1]] + +**Output:** 0 + +**Explanation:** + +Removing any of the points results in the maximum distance between any two points of 0. + +**Constraints:** + +* 3 <= points.length <= 105 +* `points[i].length == 2` +* 1 <= points[i][0], points[i][1] <= 108 + +## Solution + +```kotlin +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min + +class Solution { + private fun manhattan(points: Array, i: Int, j: Int): Int { + return ( + abs(points[i][0] - points[j][0]) + abs( + points[i][1] - points[j][1] + ) + ) + } + + private fun maxManhattanDistance(points: Array, remove: Int): IntArray { + val n = points.size + var maxSum = Int.MIN_VALUE + var minSum = Int.MAX_VALUE + var maxDiff = Int.MIN_VALUE + var minDiff = Int.MAX_VALUE + var maxSumIndex = -1 + var minSumIndex = -1 + var maxDiffIndex = -1 + var minDiffIndex = -1 + for (i in 0 until n) { + if (i != remove) { + val sum = points[i][0] + points[i][1] + val diff = points[i][0] - points[i][1] + if (sum > maxSum) { + maxSumIndex = i + maxSum = sum + } + if (sum < minSum) { + minSumIndex = i + minSum = sum + } + if (diff > maxDiff) { + maxDiffIndex = i + maxDiff = diff + } + if (diff < minDiff) { + minDiffIndex = i + minDiff = diff + } + } + } + return if (max(maxSum - minSum, maxDiff - minDiff) == maxSum - minSum + ) intArrayOf(maxSumIndex, minSumIndex) + else intArrayOf(maxDiffIndex, minDiffIndex) + } + + fun minimumDistance(points: Array): Int { + val m = maxManhattanDistance(points, -1) + val m1 = maxManhattanDistance(points, m[0]) + val m2 = maxManhattanDistance(points, m[1]) + return min( + manhattan(points, m1[0], m1[1]), + manhattan(points, m2[0], m2[1]) + ) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3101_3200/s3105_longest_strictly_increasing_or_strictly_decreasing_subarray/readme.md b/src/main/kotlin/g3101_3200/s3105_longest_strictly_increasing_or_strictly_decreasing_subarray/readme.md new file mode 100644 index 00000000..96269ab1 --- /dev/null +++ b/src/main/kotlin/g3101_3200/s3105_longest_strictly_increasing_or_strictly_decreasing_subarray/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) + +## 3105\. Longest Strictly Increasing or Strictly Decreasing Subarray + +Easy + +You are given an array of integers `nums`. Return _the length of the **longest** subarray of_ `nums` _which is either **strictly increasing** or **strictly decreasing**_. + +**Example 1:** + +**Input:** nums = [1,4,3,3,2] + +**Output:** 2 + +**Explanation:** + +The strictly increasing subarrays of `nums` are `[1]`, `[2]`, `[3]`, `[3]`, `[4]`, and `[1,4]`. + +The strictly decreasing subarrays of `nums` are `[1]`, `[2]`, `[3]`, `[3]`, `[4]`, `[3,2]`, and `[4,3]`. + +Hence, we return `2`. + +**Example 2:** + +**Input:** nums = [3,3,3,3] + +**Output:** 1 + +**Explanation:** + +The strictly increasing subarrays of `nums` are `[3]`, `[3]`, `[3]`, and `[3]`. + +The strictly decreasing subarrays of `nums` are `[3]`, `[3]`, `[3]`, and `[3]`. + +Hence, we return `1`. + +**Example 3:** + +**Input:** nums = [3,2,1] + +**Output:** 3 + +**Explanation:** + +The strictly increasing subarrays of `nums` are `[3]`, `[2]`, and `[1]`. + +The strictly decreasing subarrays of `nums` are `[3]`, `[2]`, `[1]`, `[3,2]`, `[2,1]`, and `[3,2,1]`. + +Hence, we return `3`. + +**Constraints:** + +* `1 <= nums.length <= 50` +* `1 <= nums[i] <= 50` + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun longestMonotonicSubarray(nums: IntArray): Int { + var inc = 1 + var dec = 1 + var res = 1 + for (i in 1 until nums.size) { + if (nums[i] > nums[i - 1]) { + inc += 1 + dec = 1 + } else if (nums[i] < nums[i - 1]) { + dec += 1 + inc = 1 + } else { + inc = 1 + dec = 1 + } + res = max(res, max(inc, dec)) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3101_3200/s3106_lexicographically_smallest_string_after_operations_with_constraint/readme.md b/src/main/kotlin/g3101_3200/s3106_lexicographically_smallest_string_after_operations_with_constraint/readme.md new file mode 100644 index 00000000..1759f19f --- /dev/null +++ b/src/main/kotlin/g3101_3200/s3106_lexicographically_smallest_string_after_operations_with_constraint/readme.md @@ -0,0 +1,85 @@ +[![](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) + +## 3106\. Lexicographically Smallest String After Operations With Constraint + +Medium + +You are given a string `s` and an integer `k`. + +Define a function distance(s1, s2) between two strings s1 and s2 of the same length `n` as: + +* The **sum** of the **minimum distance** between s1[i] and s2[i] when the characters from `'a'` to `'z'` are placed in a **cyclic** order, for all `i` in the range `[0, n - 1]`. + +For example, `distance("ab", "cd") == 4`, and `distance("a", "z") == 1`. + +You can **change** any letter of `s` to **any** other lowercase English letter, **any** number of times. + +Return a string denoting the **lexicographically smallest** string `t` you can get after some changes, such that `distance(s, t) <= k`. + +**Example 1:** + +**Input:** s = "zbbz", k = 3 + +**Output:** "aaaz" + +**Explanation:** + +Change `s` to `"aaaz"`. The distance between `"zbbz"` and `"aaaz"` is equal to `k = 3`. + +**Example 2:** + +**Input:** s = "xaxcd", k = 4 + +**Output:** "aawcd" + +**Explanation:** + +The distance between "xaxcd" and "aawcd" is equal to k = 4. + +**Example 3:** + +**Input:** s = "lol", k = 0 + +**Output:** "lol" + +**Explanation:** + +It's impossible to change any character as `k = 0`. + +**Constraints:** + +* `1 <= s.length <= 100` +* `0 <= k <= 2000` +* `s` consists only of lowercase English letters. + +## Solution + +```kotlin +import kotlin.math.abs +import kotlin.math.min + +@Suppress("NAME_SHADOWING") +class Solution { + fun getSmallestString(s: String, k: Int): String { + var k = k + val sArray = s.toCharArray() + for (i in sArray.indices) { + val distToA = cyclicDistance(sArray[i], 'a') + if (distToA <= k) { + sArray[i] = 'a' + k -= distToA + } else if (k > 0) { + sArray[i] = (sArray[i].code - k).toChar() + k = 0 + } + } + return String(sArray) + } + + private fun cyclicDistance(ch1: Char, ch2: Char): Int { + val dist = abs(ch1.code - ch2.code) + return min(dist, (26 - dist)) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3101_3200/s3107_minimum_operations_to_make_median_of_array_equal_to_k/readme.md b/src/main/kotlin/g3101_3200/s3107_minimum_operations_to_make_median_of_array_equal_to_k/readme.md new file mode 100644 index 00000000..58c2dca0 --- /dev/null +++ b/src/main/kotlin/g3101_3200/s3107_minimum_operations_to_make_median_of_array_equal_to_k/readme.md @@ -0,0 +1,81 @@ +[![](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) + +## 3107\. Minimum Operations to Make Median of Array Equal to K + +Medium + +You are given an integer array `nums` and a **non-negative** integer `k`. In one operation, you can increase or decrease any element by 1. + +Return the **minimum** number of operations needed to make the **median** of `nums` _equal_ to `k`. + +The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken. + +**Example 1:** + +**Input:** nums = [2,5,6,8,5], k = 4 + +**Output:** 2 + +**Explanation:** + +We can subtract one from `nums[1]` and `nums[4]` to obtain `[2, 4, 6, 8, 4]`. The median of the resulting array is equal to `k`. + +**Example 2:** + +**Input:** nums = [2,5,6,8,5], k = 7 + +**Output:** 3 + +**Explanation:** + +We can add one to `nums[1]` twice and add one to `nums[2]` once to obtain `[2, 7, 7, 8, 5]`. + +**Example 3:** + +**Input:** nums = [1,2,3,4,5,6], k = 4 + +**Output:** 0 + +**Explanation:** + +The median of the array is already equal to `k`. + +**Constraints:** + +* 1 <= nums.length <= 2 * 105 +* 1 <= nums[i] <= 109 +* 1 <= k <= 109 + +## Solution + +```kotlin +import kotlin.math.abs + +class Solution { + fun minOperationsToMakeMedianK(nums: IntArray, k: Int): Long { + nums.sort() + val n = nums.size + val medianIndex = n / 2 + var result: Long = 0 + var totalElements = 0 + var totalSum: Long = 0 + var i = medianIndex + if (nums[medianIndex] > k) { + while (i >= 0 && nums[i] > k) { + totalElements += 1 + totalSum += nums[i].toLong() + i -= 1 + } + } else if (nums[medianIndex] < k) { + while (i < n && nums[i] < k) { + totalElements += 1 + totalSum += nums[i].toLong() + i += 1 + } + } + result += abs(totalSum - (totalElements.toLong() * k)) + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3101_3200/s3108_minimum_cost_walk_in_weighted_graph/readme.md b/src/main/kotlin/g3101_3200/s3108_minimum_cost_walk_in_weighted_graph/readme.md new file mode 100644 index 00000000..7f38469c --- /dev/null +++ b/src/main/kotlin/g3101_3200/s3108_minimum_cost_walk_in_weighted_graph/readme.md @@ -0,0 +1,138 @@ +[![](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) + +## 3108\. Minimum Cost Walk in Weighted Graph + +Hard + +There is an undirected weighted graph with `n` vertices labeled from `0` to `n - 1`. + +You are given the integer `n` and an array `edges`, where edges[i] = [ui, vi, wi] indicates that there is an edge between vertices ui and vi with a weight of wi. + +A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It's important to note that a walk may visit the same edge or vertex more than once. + +The **cost** of a walk starting at node `u` and ending at node `v` is defined as the bitwise `AND` of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is w0, w1, w2, ..., wk, then the cost is calculated as w0 & w1 & w2 & ... & wk, where `&` denotes the bitwise `AND` operator. + +You are also given a 2D array `query`, where query[i] = [si, ti]. For each query, you need to find the minimum cost of the walk starting at vertex si and ending at vertex ti. If there exists no such walk, the answer is `-1`. + +Return _the array_ `answer`_, where_ `answer[i]` _denotes the **minimum** cost of a walk for query_ `i`. + +**Example 1:** + +**Input:** n = 5, edges = \[\[0,1,7],[1,3,7],[1,2,1]], query = \[\[0,3],[3,4]] + +**Output:** [1,-1] + +**Explanation:** + +![](https://assets.leetcode.com/uploads/2024/01/31/q4_example1-1.png) + +To achieve the cost of 1 in the first query, we need to move on the following edges: `0->1` (weight 7), `1->2` (weight 1), `2->1` (weight 1), `1->3` (weight 7). + +In the second query, there is no walk between nodes 3 and 4, so the answer is -1. + +**Example 2:** + +**Input:** n = 3, edges = \[\[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = \[\[1,2]] + +**Output:** [0] + +**Explanation:** + +![](https://assets.leetcode.com/uploads/2024/01/31/q4_example2e.png) + +To achieve the cost of 0 in the first query, we need to move on the following edges: `1->2` (weight 1), `2->1` (weight 6), `1->2` (weight 1). + +**Constraints:** + +* 2 <= n <= 105 +* 0 <= edges.length <= 105 +* `edges[i].length == 3` +* 0 <= ui, vi <= n - 1 +* ui != vi +* 0 <= wi <= 105 +* 1 <= query.length <= 105 +* `query[i].length == 2` +* 0 <= si, ti <= n - 1 +* si != ti + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun minimumCost(n: Int, edges: Array, query: Array): IntArray { + val parent = IntArray(n) + val bitwise = IntArray(n) + val size = IntArray(n) + var i = 0 + while (i < n) { + parent[i] = i + size[i] = 1 + bitwise[i] = -1 + i++ + } + val len = edges.size + i = 0 + while (i < len) { + val node1 = edges[i][0] + val node2 = edges[i][1] + val weight = edges[i][2] + val parent1 = findParent(node1, parent) + val parent2 = findParent(node2, parent) + if (parent1 == parent2) { + bitwise[parent1] = bitwise[parent1] and weight + } else { + var bitwiseVal: Int + val check1 = bitwise[parent1] == -1 + val check2 = bitwise[parent2] == -1 + bitwiseVal = if (check1 && check2) { + weight + } else if (check1) { + weight and bitwise[parent2] + } else if (check2) { + weight and bitwise[parent1] + } else { + weight and bitwise[parent1] and bitwise[parent2] + } + if (size[parent1] >= size[parent2]) { + parent[parent2] = parent1 + size[parent1] += size[parent2] + bitwise[parent1] = bitwiseVal + } else { + parent[parent1] = parent2 + size[parent2] += size[parent1] + bitwise[parent2] = bitwiseVal + } + } + i++ + } + val queryLen = query.size + val result = IntArray(queryLen) + i = 0 + while (i < queryLen) { + val start = query[i][0] + val end = query[i][1] + val parentStart = findParent(start, parent) + val parentEnd = findParent(end, parent) + if (start == end) { + result[i] = 0 + } else if (parentStart == parentEnd) { + result[i] = bitwise[parentStart] + } else { + result[i] = -1 + } + i++ + } + return result + } + + private fun findParent(node: Int, parent: IntArray): Int { + var node = node + while (parent[node] != node) { + node = parent[node] + } + return node + } +} +``` \ No newline at end of file