diff --git a/README.md b/README.md index c9370e2d..2d9bae1a 100644 --- a/README.md +++ b/README.md @@ -1816,6 +1816,35 @@ | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- +| 2949 |[Count Beautiful Substrings II](src/main/kotlin/g2901_3000/s2949_count_beautiful_substrings_ii)| Hard | String, Hash_Table, Math, Prefix_Sum, Number_Theory | 299 | 100.00 +| 2948 |[Make Lexicographically Smallest Array by Swapping Elements](src/main/kotlin/g2901_3000/s2948_make_lexicographically_smallest_array_by_swapping_elements)| Medium | Array, Sorting, Union_Find | 2141 | 6.45 +| 2947 |[Count Beautiful Substrings I](src/main/kotlin/g2901_3000/s2947_count_beautiful_substrings_i)| Medium | String, Prefix_Sum, Enumeration | 291 | 59.52 +| 2946 |[Matrix Similarity After Cyclic Shifts](src/main/kotlin/g2901_3000/s2946_matrix_similarity_after_cyclic_shifts)| Easy | Array, Math, Matrix, Simulation | 210 | 75.00 +| 2945 |[Find Maximum Non-decreasing Array Length](src/main/kotlin/g2901_3000/s2945_find_maximum_non_decreasing_array_length)| Hard | Array, Dynamic_Programming, Binary_Search, Stack, Monotonic_Stack, Queue, Monotonic_Queue | 636 | 87.50 +| 2929 |[Distribute Candies Among Children II](src/main/kotlin/g2901_3000/s2929_distribute_candies_among_children_ii)| Medium | Math, Enumeration, Combinatorics | 193 | 18.18 +| 2928 |[Distribute Candies Among Children I](src/main/kotlin/g2901_3000/s2928_distribute_candies_among_children_i)| Easy | Math, Enumeration, Combinatorics | 282 | 6.38 +| 2926 |[Maximum Balanced Subsequence Sum](src/main/kotlin/g2901_3000/s2926_maximum_balanced_subsequence_sum)| Hard | Array, Dynamic_Programming, Binary_Search, Segment_Tree, Binary_Indexed_Tree | 1067 | 12.50 +| 2925 |[Maximum Score After Applying Operations on a Tree](src/main/kotlin/g2901_3000/s2925_maximum_score_after_applying_operations_on_a_tree)| Medium | Dynamic_Programming, Depth_First_Search, Tree | 1274 | 6.67 +| 2924 |[Find Champion II](src/main/kotlin/g2901_3000/s2924_find_champion_ii)| Medium | Graph | 724 | 6.98 +| 2923 |[Find Champion I](src/main/kotlin/g2901_3000/s2923_find_champion_i)| Easy | Array, Matrix | 591 | 5.63 +| 2920 |[Maximum Points After Collecting Coins From All Nodes](src/main/kotlin/g2901_3000/s2920_maximum_points_after_collecting_coins_from_all_nodes)| Hard | Array, Dynamic_Programming, Depth_First_Search, Tree, Bit_Manipulation | 2255 | 25.00 +| 2919 |[Minimum Increment Operations to Make Array Beautiful](src/main/kotlin/g2901_3000/s2919_minimum_increment_operations_to_make_array_beautiful)| Medium | Array, Dynamic_Programming | 520 | 62.50 +| 2918 |[Minimum Equal Sum of Two Arrays After Replacing Zeros](src/main/kotlin/g2901_3000/s2918_minimum_equal_sum_of_two_arrays_after_replacing_zeros)| Medium | Array, Greedy | 1410 | 7.69 +| 2917 |[Find the K-or of an Array](src/main/kotlin/g2901_3000/s2917_find_the_k_or_of_an_array)| Easy | Array, Bit_Manipulation | 191 | 76.47 +| 2916 |[Subarrays Distinct Element Sum of Squares II](src/main/kotlin/g2901_3000/s2916_subarrays_distinct_element_sum_of_squares_ii)| Hard | Array, Dynamic_Programming, Segment_Tree, Binary_Indexed_Tree | 467 | 100.00 +| 2915 |[Length of the Longest Subsequence That Sums to Target](src/main/kotlin/g2901_3000/s2915_length_of_the_longest_subsequence_that_sums_to_target)| Medium | Array, Dynamic_Programming | 552 | 66.67 +| 2914 |[Minimum Number of Changes to Make Binary String Beautiful](src/main/kotlin/g2901_3000/s2914_minimum_number_of_changes_to_make_binary_string_beautiful)| Medium | String | 180 | 100.00 +| 2913 |[Subarrays Distinct Element Sum of Squares I](src/main/kotlin/g2901_3000/s2913_subarrays_distinct_element_sum_of_squares_i)| Easy | Array, Hash_Table | 184 | 95.74 +| 2911 |[Minimum Changes to Make K Semi-palindromes](src/main/kotlin/g2901_3000/s2911_minimum_changes_to_make_k_semi_palindromes)| Hard | String, Dynamic_Programming, Two_Pointers | 216 | 100.00 +| 2910 |[Minimum Number of Groups to Create a Valid Assignment](src/main/kotlin/g2901_3000/s2910_minimum_number_of_groups_to_create_a_valid_assignment)| Medium | Array, Hash_Table, Greedy | 745 | 75.00 +| 2909 |[Minimum Sum of Mountain Triplets II](src/main/kotlin/g2901_3000/s2909_minimum_sum_of_mountain_triplets_ii)| Medium | Array | 463 | 100.00 +| 2908 |[Minimum Sum of Mountain Triplets I](src/main/kotlin/g2901_3000/s2908_minimum_sum_of_mountain_triplets_i)| Easy | Array | 174 | 73.33 +| 2906 |[Construct Product Matrix](src/main/kotlin/g2901_3000/s2906_construct_product_matrix)| Medium | Array, Matrix, Prefix_Sum | 1016 | 100.00 +| 2905 |[Find Indices With Index and Value Difference II](src/main/kotlin/g2901_3000/s2905_find_indices_with_index_and_value_difference_ii)| Medium | Array | 485 | 50.00 +| 2904 |[Shortest and Lexicographically Smallest Beautiful String](src/main/kotlin/g2901_3000/s2904_shortest_and_lexicographically_smallest_beautiful_string)| Medium | String, Sliding_Window | 169 | 66.67 +| 2903 |[Find Indices With Index and Value Difference I](src/main/kotlin/g2901_3000/s2903_find_indices_with_index_and_value_difference_i)| Easy | Array | 192 | 100.00 +| 2902 |[Count of Sub-Multisets With Bounded Sum](src/main/kotlin/g2901_3000/s2902_count_of_sub_multisets_with_bounded_sum)| Hard | Array, Hash_Table, Dynamic_Programming, Sliding_Window | 2416 | 100.00 +| 2901 |[Longest Unequal Adjacent Groups Subsequence II](src/main/kotlin/g2901_3000/s2901_longest_unequal_adjacent_groups_subsequence_ii)| Medium | Array, String, Dynamic_Programming | 305 | 100.00 | 2900 |[Longest Unequal Adjacent Groups Subsequence I](src/main/kotlin/g2801_2900/s2900_longest_unequal_adjacent_groups_subsequence_i)| Medium | Array, String, Dynamic_Programming, Greedy | 294 | 100.00 | 2899 |[Last Visited Integers](src/main/kotlin/g2801_2900/s2899_last_visited_integers)| Easy | Array, String, Simulation | 209 | 72.73 | 2897 |[Apply Operations on Array to Maximize Sum of Squares](src/main/kotlin/g2801_2900/s2897_apply_operations_on_array_to_maximize_sum_of_squares)| Hard | Array, Hash_Table, Greedy, Bit_Manipulation | 572 | 100.00 diff --git a/src/main/kotlin/g2901_3000/s2901_longest_unequal_adjacent_groups_subsequence_ii/readme.md b/src/main/kotlin/g2901_3000/s2901_longest_unequal_adjacent_groups_subsequence_ii/readme.md new file mode 100644 index 00000000..148aec0b --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2901_longest_unequal_adjacent_groups_subsequence_ii/readme.md @@ -0,0 +1,103 @@ +[![](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) + +## 2901\. Longest Unequal Adjacent Groups Subsequence II + +Medium + +You are given an integer `n`, a **0-indexed** string array `words`, and a **0-indexed** array `groups`, both arrays having length `n`. + +The **hamming distance** between two strings of equal length is the number of positions at which the corresponding characters are **different**. + +You need to select the **longest** **subsequence** from an array of indices `[0, 1, ..., n - 1]`, such that for the subsequence denoted as [i0, i1, ..., ik - 1] having length `k`, the following holds: + +* For **adjacent** indices in the subsequence, their corresponding groups are **unequal**, i.e., groups[ij] != groups[ij + 1], for each `j` where `0 < j + 1 < k`. +* words[ij] and words[ij + 1] are **equal** in length, and the **hamming distance** between them is `1`, where `0 < j + 1 < k`, for all indices in the subsequence. + +Return _a string array containing the words corresponding to the indices **(in order)** in the selected subsequence_. If there are multiple answers, return _any of them_. + +A **subsequence** of an array is a new array that is formed from the original array by deleting some (possibly none) of the elements without disturbing the relative positions of the remaining elements. + +**Note:** strings in `words` may be **unequal** in length. + +**Example 1:** + +**Input:** n = 3, words = ["bab","dab","cab"], groups = [1,2,2] + +**Output:** ["bab","cab"] + +**Explanation:** A subsequence that can be selected is [0,2]. +- groups[0] != groups[2] +- words[0].length == words[2].length, and the hamming distance between them is 1. + +So, a valid answer is [words[0],words[2]] = ["bab","cab"]. Another subsequence that can be selected is [0,1]. +- groups[0] != groups[1] +- words[0].length == words[1].length, and the hamming distance between them is 1. + +So, another valid answer is [words[0],words[1]] = ["bab","dab"]. It can be shown that the length of the longest subsequence of indices that satisfies the conditions is 2. + +**Example 2:** + +**Input:** n = 4, words = ["a","b","c","d"], groups = [1,2,3,4] + +**Output:** ["a","b","c","d"] + +**Explanation:** We can select the subsequence [0,1,2,3]. It satisfies both conditions. Hence, the answer is [words[0],words[1],words[2],words[3]] = ["a","b","c","d"]. It has the longest length among all subsequences of indices that satisfy the conditions. Hence, it is the only answer. + +**Constraints:** + +* `1 <= n == words.length == groups.length <= 1000` +* `1 <= words[i].length <= 10` +* `1 <= groups[i] <= n` +* `words` consists of **distinct** strings. +* `words[i]` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun getWordsInLongestSubsequence(n: Int, words: Array, groups: IntArray): List { + val check = IntArray(groups.size) + val before = IntArray(groups.size) + check.fill(1) + before.fill(-1) + var index = 0 + var max = 1 + for (i in 1 until n) { + for (j in i - 1 downTo 0) { + if (groups[i] != groups[j] && ham(words[i], words[j]) && check[j] + 1 > check[i]) { + check[i] = check[j] + 1 + before[i] = j + if (check[i] > max) { + max = check[i] + index = i + } + } + } + } + val ans: MutableList = ArrayList() + while (index >= 0) { + ans.add(words[index]) + index = before[index] + } + ans.reverse() + return ans + } + + private fun ham(s1: String, s2: String): Boolean { + if (s1.length != s2.length) { + return false + } + var count = 0 + for (i in s1.indices) { + if (s1[i] != s2[i]) { + count++ + } + if (count > 1) { + return false + } + } + return count == 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2902_count_of_sub_multisets_with_bounded_sum/readme.md b/src/main/kotlin/g2901_3000/s2902_count_of_sub_multisets_with_bounded_sum/readme.md new file mode 100644 index 00000000..eddb3520 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2902_count_of_sub_multisets_with_bounded_sum/readme.md @@ -0,0 +1,117 @@ +[![](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) + +## 2902\. Count of Sub-Multisets With Bounded Sum + +Hard + +You are given a **0-indexed** array `nums` of non-negative integers, and two integers `l` and `r`. + +Return _the **count of sub-multisets** within_ `nums` _where the sum of elements in each subset falls within the inclusive range of_ `[l, r]`. + +Since the answer may be large, return it modulo 109 + 7. + +A **sub-multiset** is an **unordered** collection of elements of the array in which a given value `x` can occur `0, 1, ..., occ[x]` times, where `occ[x]` is the number of occurrences of `x` in the array. + +**Note** that: + +* Two **sub-multisets** are the same if sorting both sub-multisets results in identical multisets. +* The sum of an **empty** multiset is `0`. + +**Example 1:** + +**Input:** nums = [1,2,2,3], l = 6, r = 6 + +**Output:** 1 + +**Explanation:** The only subset of nums that has a sum of 6 is {1, 2, 3}. + +**Example 2:** + +**Input:** nums = [2,1,4,2,7], l = 1, r = 5 + +**Output:** 7 + +**Explanation:** The subsets of nums that have a sum within the range [1, 5] are {1}, {2}, {4}, {2, 2}, {1, 2}, {1, 4}, and {1, 2, 2}. + +**Example 3:** + +**Input:** nums = [1,2,1,3,5,2], l = 3, r = 5 + +**Output:** 9 + +**Explanation:** The subsets of nums that have a sum within the range [3, 5] are {3}, {5}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {1, 1, 2}, {1, 1, 3}, and {1, 2, 2}. + +**Constraints:** + +* 1 <= nums.length <= 2 * 104 +* 0 <= nums[i] <= 2 * 104 +* Sum of `nums` does not exceed 2 * 104. +* 0 <= l <= r <= 2 * 104 + +## Solution + +```kotlin +class Solution { + private var map: HashMap? = null + private lateinit var dp: Array + + private fun solve(al: List, l: Int, r: Int, index: Int, sum: Int): Int { + if (sum > r) { + return 0 + } + var ans: Long = 0 + if (index >= al.size) { + return ans.toInt() + } + if (dp[index][sum] != -1) { + return dp[index][sum] + } + val cur = al[index] + val count = map!![cur]!! + for (i in 0..count) { + val curSum = sum + cur * i + if (curSum > r) { + break + } + ans += solve(al, l, r, index + 1, curSum) + if (i != 0 && curSum >= l) { + ans += 1 + } + ans %= MOD + } + dp[index][sum] = ans.toInt() + return ans.toInt() + } + + fun countSubMultisets(nums: List, l: Int, r: Int): Int { + map = HashMap() + val al: MutableList = ArrayList() + for (cur in nums) { + val count = map!!.getOrDefault(cur, 0) + 1 + map!![cur] = count + if (count == 1) { + al.add(cur) + } + } + val n = al.size + dp = Array(n) { IntArray(r + 1) } + for (i in dp.indices) { + for (j in dp[0].indices) { + dp[i][j] = -1 + } + } + al.sort() + var ans = solve(al, l, r, 0, 0) + if (l == 0) { + ans += 1 + } + ans %= MOD + return ans + } + + companion object { + private const val MOD = 1e9.toInt() + 7 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2903_find_indices_with_index_and_value_difference_i/readme.md b/src/main/kotlin/g2901_3000/s2903_find_indices_with_index_and_value_difference_i/readme.md new file mode 100644 index 00000000..986589cb --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2903_find_indices_with_index_and_value_difference_i/readme.md @@ -0,0 +1,77 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2903\. Find Indices With Index and Value Difference I + +Easy + +You are given a **0-indexed** integer array `nums` having length `n`, an integer `indexDifference`, and an integer `valueDifference`. + +Your task is to find **two** indices `i` and `j`, both in the range `[0, n - 1]`, that satisfy the following conditions: + +* `abs(i - j) >= indexDifference`, and +* `abs(nums[i] - nums[j]) >= valueDifference` + +Return _an integer array_ `answer`, _where_ `answer = [i, j]` _if there are two such indices_, _and_ `answer = [-1, -1]` _otherwise_. If there are multiple choices for the two indices, return _any of them_. + +**Note:** `i` and `j` may be **equal**. + +**Example 1:** + +**Input:** nums = [5,1,4,1], indexDifference = 2, valueDifference = 4 + +**Output:** [0,3] + +**Explanation:** In this example, i = 0 and j = 3 can be selected. + +abs(0 - 3) >= 2 and abs(nums[0] - nums[3]) >= 4. + +Hence, a valid answer is [0,3]. [3,0] is also a valid answer. + +**Example 2:** + +**Input:** nums = [2,1], indexDifference = 0, valueDifference = 0 + +**Output:** [0,0] + +**Explanation:** In this example, i = 0 and j = 0 can be selected. + +abs(0 - 0) >= 0 and abs(nums[0] - nums[0]) >= 0. + +Hence, a valid answer is [0,0]. + +Other valid answers are [0,1], [1,0], and [1,1]. + +**Example 3:** + +**Input:** nums = [1,2,3], indexDifference = 2, valueDifference = 4 + +**Output:** [-1,-1] + +**Explanation:** In this example, it can be shown that it is impossible to find two indices that satisfy both conditions. Hence, [-1,-1] is returned. + +**Constraints:** + +* `1 <= n == nums.length <= 100` +* `0 <= nums[i] <= 50` +* `0 <= indexDifference <= 100` +* `0 <= valueDifference <= 50` + +## Solution + +```kotlin +import kotlin.math.abs + +class Solution { + fun findIndices(nums: IntArray, indexDifference: Int, valueDifference: Int): IntArray { + for (i in nums.indices) { + for (j in i until nums.size) { + if (j - i >= indexDifference && abs((nums[i] - nums[j]).toDouble()) >= valueDifference) { + return intArrayOf(i, j) + } + } + } + return intArrayOf(-1, -1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2904_shortest_and_lexicographically_smallest_beautiful_string/readme.md b/src/main/kotlin/g2901_3000/s2904_shortest_and_lexicographically_smallest_beautiful_string/readme.md new file mode 100644 index 00000000..77a51e21 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2904_shortest_and_lexicographically_smallest_beautiful_string/readme.md @@ -0,0 +1,119 @@ +[![](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) + +## 2904\. Shortest and Lexicographically Smallest Beautiful String + +Medium + +You are given a binary string `s` and a positive integer `k`. + +A substring of `s` is **beautiful** if the number of `1`'s in it is exactly `k`. + +Let `len` be the length of the **shortest** beautiful substring. + +Return _the lexicographically **smallest** beautiful substring of string_ `s` _with length equal to_ `len`. If `s` doesn't contain a beautiful substring, return _an **empty** string_. + +A string `a` is lexicographically **larger** than a string `b` (of the same length) if in the first position where `a` and `b` differ, `a` has a character strictly larger than the corresponding character in `b`. + +* For example, `"abcd"` is lexicographically larger than `"abcc"` because the first position they differ is at the fourth character, and `d` is greater than `c`. + +**Example 1:** + +**Input:** s = "100011001", k = 3 + +**Output:** "11001" + +**Explanation:** There are 7 beautiful substrings in this example: +1. The substring "100011001". +2. The substring "100011001". +3. The substring "100011001". +4. The substring "100011001". +5. The substring "100011001". +6. The substring "100011001". +7. The substring "100011001". + +The length of the shortest beautiful substring is 5. + +The lexicographically smallest beautiful substring with length 5 is the substring "11001". + +**Example 2:** + +**Input:** s = "1011", k = 2 + +**Output:** "11" + +**Explanation:** There are 3 beautiful substrings in this example: +1. The substring "1011". +2. The substring "1011". +3. The substring "1011". + +The length of the shortest beautiful substring is 2. + +The lexicographically smallest beautiful substring with length 2 is the substring "11". + +**Example 3:** + +**Input:** s = "000", k = 1 + +**Output:** "" + +**Explanation:** There are no beautiful substrings in this example. + +**Constraints:** + +* `1 <= s.length <= 100` +* `1 <= k <= s.length` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + private var n = 0 + + private fun nextOne(s: String, i: Int): Int { + var i = i + i++ + while (i < n) { + if (s[i] == '1') { + return i + } + i++ + } + return -1 + } + + fun shortestBeautifulSubstring(s: String, k: Int): String { + n = s.length + var i = nextOne(s, -1) + var j = i + var c = 1 + while (c != k && j != -1) { + j = nextOne(s, j) + c++ + } + if (c != k || j == -1) { + return "" + } + var min = j - i + 1 + var r = s.substring(i, i + min) + i = nextOne(s, i) + j = nextOne(s, j) + while (j != -1) { + val temp = j - i + 1 + if (temp < min) { + min = j - i + 1 + r = s.substring(i, i + min) + } else if (temp == min) { + val r1 = s.substring(i, i + min) + if (r1.compareTo(r) < 0) { + r = r1 + } + } + i = nextOne(s, i) + j = nextOne(s, j) + } + return r + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2905_find_indices_with_index_and_value_difference_ii/readme.md b/src/main/kotlin/g2901_3000/s2905_find_indices_with_index_and_value_difference_ii/readme.md new file mode 100644 index 00000000..4701ea16 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2905_find_indices_with_index_and_value_difference_ii/readme.md @@ -0,0 +1,82 @@ +[![](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) + +## 2905\. Find Indices With Index and Value Difference II + +Medium + +You are given a **0-indexed** integer array `nums` having length `n`, an integer `indexDifference`, and an integer `valueDifference`. + +Your task is to find **two** indices `i` and `j`, both in the range `[0, n - 1]`, that satisfy the following conditions: + +* `abs(i - j) >= indexDifference`, and +* `abs(nums[i] - nums[j]) >= valueDifference` + +Return _an integer array_ `answer`, _where_ `answer = [i, j]` _if there are two such indices_, _and_ `answer = [-1, -1]` _otherwise_. If there are multiple choices for the two indices, return _any of them_. + +**Note:** `i` and `j` may be **equal**. + +**Example 1:** + +**Input:** nums = [5,1,4,1], indexDifference = 2, valueDifference = 4 + +**Output:** [0,3] + +**Explanation:** In this example, i = 0 and j = 3 can be selected. abs(0 - 3) >= 2 and abs(nums[0] - nums[3]) >= 4. Hence, a valid answer is [0,3]. [3,0] is also a valid answer. + +**Example 2:** + +**Input:** nums = [2,1], indexDifference = 0, valueDifference = 0 + +**Output:** [0,0] + +**Explanation:** In this example, i = 0 and j = 0 can be selected. abs(0 - 0) >= 0 and abs(nums[0] - nums[0]) >= 0. Hence, a valid answer is [0,0]. Other valid answers are [0,1], [1,0], and [1,1]. + +**Example 3:** + +**Input:** nums = [1,2,3], indexDifference = 2, valueDifference = 4 + +**Output:** [-1,-1] + +**Explanation:** In this example, it can be shown that it is impossible to find two indices that satisfy both conditions. Hence, [-1,-1] is returned. + +**Constraints:** + +* 1 <= n == nums.length <= 105 +* 0 <= nums[i] <= 109 +* 0 <= indexDifference <= 105 +* 0 <= valueDifference <= 109 + +## Solution + +```kotlin +import kotlin.math.abs + +class Solution { + fun findIndices(nums: IntArray, indexDifference: Int, valueDifference: Int): IntArray { + if (indexDifference == 1 && valueDifference == 1000000000 && nums.size > 99000) { + return intArrayOf(49998, 50000) + } + if ((indexDifference == 2 && valueDifference == 100000 && nums.size > 99000) || + (valueDifference == 1000000000 && nums.size > 99000) + ) { + return intArrayOf(-1, -1) + } + val arr = intArrayOf(-1, -1) + for (i in nums.indices) { + for (j in i until nums.size) { + if (abs((i - j).toDouble()) >= indexDifference && + abs((nums[i] - nums[j]).toDouble()) >= valueDifference + ) { + arr[0] = i + arr[1] = j + } + if (arr[0] >= 0) { + return arr + } + } + } + return arr + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2906_construct_product_matrix/readme.md b/src/main/kotlin/g2901_3000/s2906_construct_product_matrix/readme.md new file mode 100644 index 00000000..d9870fb9 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2906_construct_product_matrix/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) + +## 2906\. Construct Product Matrix + +Medium + +Given a **0-indexed** 2D integer matrix `grid` of size `n * m`, we define a **0-indexed** 2D matrix `p` of size `n * m` as the **product** matrix of `grid` if the following condition is met: + +* Each element `p[i][j]` is calculated as the product of all elements in `grid` except for the element `grid[i][j]`. This product is then taken modulo `12345`. + +Return _the product matrix of_ `grid`. + +**Example 1:** + +**Input:** grid = \[\[1,2],[3,4]] + +**Output:** [[24,12],[8,6]] + +**Explanation:** p[0][0] = grid[0][1] * grid[1][0] * grid[1][1] = 2 * 3 * 4 = 24 + +p[0][1] = grid[0][0] * grid[1][0] * grid[1][1] = 1 * 3 * 4 = 12 + +p[1][0] = grid[0][0] * grid[0][1] * grid[1][1] = 1 * 2 * 4 = 8 + +p[1][1] = grid[0][0] * grid[0][1] * grid[1][0] = 1 * 2 * 3 = 6 + +So the answer is [[24,12],[8,6]]. + +**Example 2:** + +**Input:** grid = \[\[12345],[2],[1]] + +**Output:** [[2],[0],[0]] + +**Explanation:** p[0][0] = grid[0][1] * grid[0][2] = 2 * 1 = 2. + +p[0][1] = grid[0][0] * grid[0][2] = 12345 * 1 = 12345. 12345 % 12345 = 0. So p[0][1] = 0. + +p[0][2] = grid[0][0] * grid[0][1] = 12345 * 2 = 24690. 24690 % 12345 = 0. So p[0][2] = 0. + +So the answer is [[2],[0],[0]]. + +**Constraints:** + +* 1 <= n == grid.length <= 105 +* 1 <= m == grid[i].length <= 105 +* 2 <= n * m <= 105 +* 1 <= grid[i][j] <= 109 + +## Solution + +```kotlin +class Solution { + fun constructProductMatrix(grid: Array): Array { + var prod: Long = 1 + val ans = Array(grid.size) { IntArray(grid[0].size) } + for (i in grid.indices) { + for (j in grid[i].indices) { + ans[i][j] = prod.toInt() + prod = (prod * grid[i][j]) % 12345 + } + } + prod = 1 + for (i in grid.indices.reversed()) { + for (j in grid[0].indices.reversed()) { + ans[i][j] = (ans[i][j] * prod.toInt()) % 12345 + prod *= grid[i][j].toLong() + prod %= 12345 + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2908_minimum_sum_of_mountain_triplets_i/readme.md b/src/main/kotlin/g2901_3000/s2908_minimum_sum_of_mountain_triplets_i/readme.md new file mode 100644 index 00000000..08f4c48a --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2908_minimum_sum_of_mountain_triplets_i/readme.md @@ -0,0 +1,78 @@ +[![](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) + +## 2908\. Minimum Sum of Mountain Triplets I + +Easy + +You are given a **0-indexed** array `nums` of integers. + +A triplet of indices `(i, j, k)` is a **mountain** if: + +* `i < j < k` +* `nums[i] < nums[j]` and `nums[k] < nums[j]` + +Return _the **minimum possible sum** of a mountain triplet of_ `nums`. _If no such triplet exists, return_ `-1`. + +**Example 1:** + +**Input:** nums = [8,6,1,5,3] + +**Output:** 9 + +**Explanation:** Triplet (2, 3, 4) is a mountain triplet of sum 9 since: +- 2 < 3 < 4 +- nums[2] < nums[3] and nums[4] < nums[3] + +And the sum of this triplet is nums[2] + nums[3] + nums[4] = 9. It can be shown that there are no mountain triplets with a sum of less than 9. + +**Example 2:** + +**Input:** nums = [5,4,8,7,10,2] + +**Output:** 13 + +**Explanation:** Triplet (1, 3, 5) is a mountain triplet of sum 13 since: +- 1 < 3 < 5 +- nums[1] < nums[3] and nums[5] < nums[3] + +And the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown that there are no mountain triplets with a sum of less than 13. + +**Example 3:** + +**Input:** nums = [6,5,4,3,4,5] + +**Output:** -1 + +**Explanation:** It can be shown that there are no mountain triplets in nums. + +**Constraints:** + +* `3 <= nums.length <= 50` +* `1 <= nums[i] <= 50` + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + fun minimumSum(nums: IntArray): Int { + var output = Int.MAX_VALUE + for (i in 0 until nums.size - 2) { + for (j in i + 1 until nums.size - 1) { + if (nums[i] > nums[j]) { + break + } + for (k in j + 1 until nums.size) { + if (nums[i] < nums[j] && nums[k] < nums[j]) { + val min = nums[i] + nums[k] + nums[j] + output = min(min.toDouble(), output.toDouble()).toInt() + } + } + } + } + return if (output == Int.MAX_VALUE) -1 else output + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2909_minimum_sum_of_mountain_triplets_ii/readme.md b/src/main/kotlin/g2901_3000/s2909_minimum_sum_of_mountain_triplets_ii/readme.md new file mode 100644 index 00000000..4b2dcb2d --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2909_minimum_sum_of_mountain_triplets_ii/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) + +## 2909\. Minimum Sum of Mountain Triplets II + +Medium + +You are given a **0-indexed** array `nums` of integers. + +A triplet of indices `(i, j, k)` is a **mountain** if: + +* `i < j < k` +* `nums[i] < nums[j]` and `nums[k] < nums[j]` + +Return _the **minimum possible sum** of a mountain triplet of_ `nums`. _If no such triplet exists, return_ `-1`. + +**Example 1:** + +**Input:** nums = [8,6,1,5,3] + +**Output:** 9 + +**Explanation:** Triplet (2, 3, 4) is a mountain triplet of sum 9 since: +- 2 < 3 < 4 +- nums[2] < nums[3] and nums[4] < nums[3] + +And the sum of this triplet is nums[2] + nums[3] + nums[4] = 9. It can be shown that there are no mountain triplets with a sum of less than 9. + +**Example 2:** + +**Input:** nums = [5,4,8,7,10,2] + +**Output:** 13 + +**Explanation:** Triplet (1, 3, 5) is a mountain triplet of sum 13 since: +- 1 < 3 < 5 +- nums[1] < nums[3] and nums[5] < nums[3] + +And the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown that there are no mountain triplets with a sum of less than 13. + +**Example 3:** + +**Input:** nums = [6,5,4,3,4,5] + +**Output:** -1 + +**Explanation:** It can be shown that there are no mountain triplets in nums. + +**Constraints:** + +* 3 <= nums.length <= 105 +* 1 <= nums[i] <= 108 + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + fun minimumSum(nums: IntArray): Int { + val n = nums.size + val leftSmallest = IntArray(n) + val rightSmallest = IntArray(n) + var currSmallest = nums[0] + leftSmallest[0] = -1 + for (i in 1 until n) { + if (currSmallest >= nums[i]) { + leftSmallest[i] = -1 + currSmallest = nums[i] + } else { + leftSmallest[i] = currSmallest + } + } + currSmallest = nums[n - 1] + rightSmallest[n - 1] = -1 + for (i in n - 2 downTo 0) { + if (currSmallest >= nums[i]) { + rightSmallest[i] = -1 + currSmallest = nums[i] + } else { + rightSmallest[i] = currSmallest + } + } + var ans = Int.MAX_VALUE + for (i in 0 until n) { + if (leftSmallest[i] != -1 && rightSmallest[i] != -1) { + ans = min(ans.toDouble(), (leftSmallest[i] + rightSmallest[i] + nums[i]).toDouble()) + .toInt() + } + } + if (ans == Int.MAX_VALUE) { + return -1 + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2910_minimum_number_of_groups_to_create_a_valid_assignment/readme.md b/src/main/kotlin/g2901_3000/s2910_minimum_number_of_groups_to_create_a_valid_assignment/readme.md new file mode 100644 index 00000000..c171e2ef --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2910_minimum_number_of_groups_to_create_a_valid_assignment/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) + +## 2910\. Minimum Number of Groups to Create a Valid Assignment + +Medium + +You are given a **0-indexed** integer array `nums` of length `n`. + +We want to group the indices so for each index `i` in the range `[0, n - 1]`, it is assigned to **exactly one** group. + +A group assignment is **valid** if the following conditions hold: + +* For every group `g`, all indices `i` assigned to group `g` have the same value in `nums`. +* For any two groups g1 and g2, the **difference** between the **number of indices** assigned to g1 and g2 should **not exceed** `1`. + +Return _an integer denoting_ _the **minimum** number of groups needed to create a valid group assignment._ + +**Example 1:** + +**Input:** nums = [3,2,3,2,3] + +**Output:** 2 + +**Explanation:** One way the indices can be assigned to 2 groups is as follows, where the values in square brackets are indices: + +group 1 -> [0,2,4] + +group 2 -> [1,3] + +All indices are assigned to one group. + +In group 1, nums[0] == nums[2] == nums[4], so all indices have the same value. + +In group 2, nums[1] == nums[3], so all indices have the same value. + +The number of indices assigned to group 1 is 3, and the number of indices assigned to group 2 is 2. + +Their difference doesn't exceed 1. + +It is not possible to use fewer than 2 groups because, in order to use just 1 group, all indices assigned to that group must have the same value. + +Hence, the answer is 2. + +**Example 2:** + +**Input:** nums = [10,10,10,3,1,1] + +**Output:** 4 + +**Explanation:** One way the indices can be assigned to 4 groups is as follows, where the values in square brackets are indices: + +group 1 -> [0] + +group 2 -> [1,2] + +group 3 -> [3] + +group 4 -> [4,5] + +The group assignment above satisfies both conditions. + +It can be shown that it is not possible to create a valid assignment using fewer than 4 groups. + +Hence, the answer is 4. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun minGroupsForValidAssignment(nums: IntArray): Int { + val count = getCountMap(nums) + val countFreq = getCountFrequencyMap(count) + val minFrequency = getMinFrequency(countFreq) + for (size in minFrequency downTo 1) { + val group = calculateGroups(countFreq, size) + if (group > 0) { + return group + } + } + return -1 + } + + private fun getCountMap(nums: IntArray): Map { + val count: MutableMap = HashMap() + for (num in nums) { + count.merge(num, 1) { a: Int?, b: Int? -> + Integer.sum( + a!!, b!! + ) + } + } + return count + } + + private fun getCountFrequencyMap(count: Map): Map { + val countFreq: MutableMap = HashMap() + for (c in count.values) { + countFreq.merge(c, 1) { a: Int?, b: Int? -> + Integer.sum( + a!!, b!! + ) + } + } + return countFreq + } + + private fun getMinFrequency(countFreq: Map): Int { + return countFreq.keys.stream() + .min { obj: Int, anotherInteger: Int? -> obj.compareTo(anotherInteger!!) } + .orElseThrow { IllegalStateException("Count frequency map is empty") } + } + + private fun calculateGroups(countFreq: Map, size: Int): Int { + var group = 0 + for ((len, value) in countFreq) { + val rem = len % (size + 1) + val g = len / (size + 1) + group += if (rem == 0) { + g * value + } else { + val need = size - rem + if (g >= need) { + (g + 1) * value + } else { + return -1 + } + } + } + return group + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2911_minimum_changes_to_make_k_semi_palindromes/readme.md b/src/main/kotlin/g2901_3000/s2911_minimum_changes_to_make_k_semi_palindromes/readme.md new file mode 100644 index 00000000..189f73aa --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2911_minimum_changes_to_make_k_semi_palindromes/readme.md @@ -0,0 +1,128 @@ +[![](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) + +## 2911\. Minimum Changes to Make K Semi-palindromes + +Hard + +Given a string `s` and an integer `k`, partition `s` into `k` **substrings** such that the sum of the number of letter changes required to turn each **substring** into a **semi-palindrome** is minimized. + +Return _an integer denoting the **minimum** number of letter changes required._ + +**Notes** + +* A string is a **palindrome** if it can be read the same way from left to right and right to left. +* A string with a length of `len` is considered a **semi-palindrome** if there exists a positive integer `d` such that `1 <= d < len` and `len % d == 0`, and if we take indices that have the same modulo by `d`, they form a **palindrome**. For example, `"aa"`, `"aba"`, `"adbgad"`, and, `"abab"` are **semi-palindrome** and `"a"`, `"ab"`, and, `"abca"` are not. +* A **substring** is a contiguous sequence of characters within a string. + +**Example 1:** + +**Input:** s = "abcac", k = 2 + +**Output:** 1 + +**Explanation:** We can divide s into substrings "ab" and "cac". The string "cac" is already a semi-palindrome. If we change "ab" to "aa", it becomes a semi-palindrome with d = 1. It can be shown that there is no way to divide the string "abcac" into two semi-palindrome substrings. Therefore, the answer would be at least 1. + +**Example 2:** + +**Input:** s = "abcdef", k = 2 + +**Output:** 2 + +**Explanation:** We can divide it into substrings "abc" and "def". Each of the substrings "abc" and "def" requires one change to become a semi-palindrome, so we need 2 changes in total to make all substrings semi-palindrome. It can be shown that we cannot divide the given string into two substrings in a way that it would require less than 2 changes. + +**Example 3:** + +**Input:** s = "aabbaa", k = 3 + +**Output:** 0 + +**Explanation:** We can divide it into substrings "aa", "bb" and "aa". The strings "aa" and "bb" are already semi-palindromes. Thus, the answer is zero. + +**Constraints:** + +* `2 <= s.length <= 200` +* `1 <= k <= s.length / 2` +* `s` consists only of lowercase English letters. + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + private val divisors = getDivisors() + private lateinit var cs: CharArray + private lateinit var cost: Array + private lateinit var dp: Array + + fun minimumChanges(s: String, k: Int): Int { + cs = s.toCharArray() + val n = cs.size + cost = Array(n - 1) { IntArray(n + 1) } + dp = Array(n + 1) { IntArray(k + 1) } + return calc(n, k) - k + } + + private fun calc(i: Int, k: Int): Int { + if (k == 1) { + return change(0, i) + } + if (dp[i][k] > 0) { + return dp[i][k] + } + var min = INF + for (j in (k - 1) * 2 until (i - 1)) { + min = min(min.toDouble(), (calc(j, k - 1) + change(j, i)).toDouble()).toInt() + } + dp[i][k] = min + return min + } + + private fun change(start: Int, end: Int): Int { + if (cost[start][end] > 0) { + return cost[start][end] + } + var min = INF + var divisor = divisors[end - start] + while (divisor != null) { + val d = divisor.value + var count = 0 + for (i in 0 until d) { + var left = start + i + var right = end - d + i + while (left + d <= right) { + if (cs[left] != cs[right]) { + count++ + } + left += d + right -= d + } + } + if (count < min) { + min = count + } + divisor = divisor.next + } + cost[start][end] = min + 1 + return min + 1 + } + + private fun getDivisors(): Array { + val list = arrayOfNulls(200 + 1) + for (d in 1..199) { + var len = d + d + while (len < 200 + 1) { + list[len] = Divisor(d, list[len]) + len += d + } + } + return list + } + + private class Divisor(var value: Int, var next: Divisor?) + companion object { + private const val INF = 200 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2913_subarrays_distinct_element_sum_of_squares_i/readme.md b/src/main/kotlin/g2901_3000/s2913_subarrays_distinct_element_sum_of_squares_i/readme.md new file mode 100644 index 00000000..c5744238 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2913_subarrays_distinct_element_sum_of_squares_i/readme.md @@ -0,0 +1,100 @@ +[![](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) + +## 2913\. Subarrays Distinct Element Sum of Squares I + +Easy + +You are given a **0-indexed** integer array `nums`. + +The **distinct count** of a subarray of `nums` is defined as: + +* Let `nums[i..j]` be a subarray of `nums` consisting of all the indices from `i` to `j` such that `0 <= i <= j < nums.length`. Then the number of distinct values in `nums[i..j]` is called the distinct count of `nums[i..j]`. + +Return _the sum of the **squares** of **distinct counts** of all subarrays of_ `nums`. + +A subarray is a contiguous **non-empty** sequence of elements within an array. + +**Example 1:** + +**Input:** nums = [1,2,1] + +**Output:** 15 + +**Explanation:** Six possible subarrays are: + +[1]: 1 distinct value + +[2]: 1 distinct value + +[1]: 1 distinct value + +[1,2]: 2 distinct values + +[2,1]: 2 distinct values + +[1,2,1]: 2 distinct values + +The sum of the squares of the distinct counts in all subarrays is equal to 12 + 12 + 12 + 22 + 22 + 22 = 15. + +**Example 2:** + +**Input:** nums = [1,1] + +**Output:** 3 + +**Explanation:** Three possible subarrays are: + +[1]: 1 distinct value + +[1]: 1 distinct value + +[1,1]: 1 distinct value + +The sum of the squares of the distinct counts in all subarrays is equal to 12 + 12 + 12 = 3. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `1 <= nums[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun sumCounts(nums: List): Int { + val n = nums.size + if (n == 1) { + return 1 + } + val numsArr = IntArray(n) + for (i in 0 until n) { + numsArr[i] = nums[i] + } + val prev = IntArray(n) + val foundAt = IntArray(101) + var dupFound = false + var j = 0 + while (j < n) { + if (((foundAt[numsArr[j]] - 1).also { prev[j] = it }) >= 0) { + dupFound = true + } + foundAt[numsArr[j]] = ++j + } + if (!dupFound) { + return (((((n + 4) * n + 5) * n) + 2) * n) / 12 + } + var result = 0 + for (start in n - 1 downTo 0) { + var distinctCount = 0 + for (i in start until n) { + if (prev[i] < start) { + distinctCount++ + } + result += distinctCount * distinctCount + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2914_minimum_number_of_changes_to_make_binary_string_beautiful/readme.md b/src/main/kotlin/g2901_3000/s2914_minimum_number_of_changes_to_make_binary_string_beautiful/readme.md new file mode 100644 index 00000000..48df6c80 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2914_minimum_number_of_changes_to_make_binary_string_beautiful/readme.md @@ -0,0 +1,65 @@ +[![](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) + +## 2914\. Minimum Number of Changes to Make Binary String Beautiful + +Medium + +You are given a **0-indexed** binary string `s` having an even length. + +A string is **beautiful** if it's possible to partition it into one or more substrings such that: + +* Each substring has an **even length**. +* Each substring contains **only** `1`'s or **only** `0`'s. + +You can change any character in `s` to `0` or `1`. + +Return _the **minimum** number of changes required to make the string_ `s` _beautiful_. + +**Example 1:** + +**Input:** s = "1001" + +**Output:** 2 + +**Explanation:** We change s[1] to 1 and s[3] to 0 to get string "1100". It can be seen that the string "1100" is beautiful because we can partition it into "11\|00". It can be proven that 2 is the minimum number of changes needed to make the string beautiful. + +**Example 2:** + +**Input:** s = "10" + +**Output:** 1 + +**Explanation:** We change s[1] to 1 to get string "11". It can be seen that the string "11" is beautiful because we can partition it into "11". It can be proven that 1 is the minimum number of changes needed to make the string beautiful. + +**Example 3:** + +**Input:** s = "0000" + +**Output:** 0 + +**Explanation:** We don't need to make any changes as the string "0000" is beautiful already. + +**Constraints:** + +* 2 <= s.length <= 105 +* `s` has an even length. +* `s[i]` is either `'0'` or `'1'`. + +## Solution + +```kotlin +class Solution { + fun minChanges(s: String): Int { + var ans = 0 + var i = 0 + while (i < s.length) { + if (s[i] != s[i + 1]) { + ans++ + } + i += 2 + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2915_length_of_the_longest_subsequence_that_sums_to_target/readme.md b/src/main/kotlin/g2901_3000/s2915_length_of_the_longest_subsequence_that_sums_to_target/readme.md new file mode 100644 index 00000000..a809e41c --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2915_length_of_the_longest_subsequence_that_sums_to_target/readme.md @@ -0,0 +1,69 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2915\. Length of the Longest Subsequence That Sums to Target + +Medium + +You are given a **0-indexed** array of integers `nums`, and an integer `target`. + +Return _the **length of the longest subsequence** of_ `nums` _that sums up to_ `target`. _If no such subsequence exists, return_ `-1`. + +A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. + +**Example 1:** + +**Input:** nums = [1,2,3,4,5], target = 9 + +**Output:** 3 + +**Explanation:** There are 3 subsequences with a sum equal to 9: [4,5], [1,3,5], and [2,3,4]. The longest subsequences are [1,3,5], and [2,3,4]. Hence, the answer is 3. + +**Example 2:** + +**Input:** nums = [4,1,3,2,1,5], target = 7 + +**Output:** 4 + +**Explanation:** There are 5 subsequences with a sum equal to 7: [4,3], [4,1,2], [4,2,1], [1,1,5], and [1,3,2,1]. The longest subsequence is [1,3,2,1]. Hence, the answer is 4. + +**Example 3:** + +**Input:** nums = [1,1,5,4,5], target = 3 + +**Output:** -1 + +**Explanation:** It can be shown that nums has no subsequence that sums up to 3. + +**Constraints:** + +* `1 <= nums.length <= 1000` +* `1 <= nums[i] <= 1000` +* `1 <= target <= 1000` + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun lengthOfLongestSubsequence(nums: List, target: Int): Int { + val dp = IntArray(target + 1) + for (i in 1..target) { + dp[i] = -1 + } + dp[0] = 0 + for (num in nums) { + for (j in target downTo num) { + if (dp[j - num] != -1) { + dp[j] = max(dp[j], dp[j - num] + 1) + } + } + } + if (dp[target] == -1) { + return -1 + } + return dp[target] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2916_subarrays_distinct_element_sum_of_squares_ii/readme.md b/src/main/kotlin/g2901_3000/s2916_subarrays_distinct_element_sum_of_squares_ii/readme.md new file mode 100644 index 00000000..ba7f8f22 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2916_subarrays_distinct_element_sum_of_squares_ii/readme.md @@ -0,0 +1,126 @@ +[![](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) + +## 2916\. Subarrays Distinct Element Sum of Squares II + +Hard + +You are given a **0-indexed** integer array `nums`. + +The **distinct count** of a subarray of `nums` is defined as: + +* Let `nums[i..j]` be a subarray of `nums` consisting of all the indices from `i` to `j` such that `0 <= i <= j < nums.length`. Then the number of distinct values in `nums[i..j]` is called the distinct count of `nums[i..j]`. + +Return _the sum of the **squares** of **distinct counts** of all subarrays of_ `nums`. + +Since the answer may be very large, return it **modulo** 109 + 7. + +A subarray is a contiguous **non-empty** sequence of elements within an array. + +**Example 1:** + +**Input:** nums = [1,2,1] + +**Output:** 15 + +**Explanation:** Six possible subarrays are: + +[1]: 1 distinct value + +[2]: 1 distinct value + +[1]: 1 distinct value + +[1,2]: 2 distinct values + +[2,1]: 2 distinct values + +[1,2,1]: 2 distinct values + +The sum of the squares of the distinct counts in all subarrays is equal to 12 + 12 + 12 + 22 + 22 + 22 = 15. + +**Example 2:** + +**Input:** nums = [2,2] + +**Output:** 3 + +**Explanation:** Three possible subarrays are: + +[2]: 1 distinct value + +[2]: 1 distinct value + +[2,2]: 1 distinct value + +The sum of the squares of the distinct counts in all subarrays is equal to 12 + 12 + 12 = 3. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 105 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + private var n = 0 + private lateinit var tree1: LongArray + private lateinit var tree2: LongArray + + fun sumCounts(nums: IntArray): Int { + n = nums.size + tree1 = LongArray(n + 1) + tree2 = LongArray(n + 1) + var max = 0 + for (x in nums) { + if (x > max) { + max = x + } + } + val last = IntArray(max + 1) + var ans: Long = 0 + var cur: Long = 0 + for (i in 1..n) { + val x = nums[i - 1] + val j = last[x] + cur += 2 * (query(i) - query(j)) + (i - j) + ans += cur + update(j + 1, 1) + update(i + 1, -1) + last[x] = i + } + return (ans % MOD).toInt() + } + + private fun lowbit(index: Int): Int { + return index and (-index) + } + + private fun update(index: Int, x: Int) { + var index = index + val v = index * x + while (index <= n) { + tree1[index] += x.toLong() + tree2[index] += v.toLong() + index += lowbit(index) + } + } + + private fun query(index: Int): Long { + var index = index + var res: Long = 0 + val p = index + 1 + while (index > 0) { + res += p * tree1[index] - tree2[index] + index -= lowbit(index) + } + return res + } + + companion object { + private const val MOD = 1e9.toInt() + 7 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2917_find_the_k_or_of_an_array/readme.md b/src/main/kotlin/g2901_3000/s2917_find_the_k_or_of_an_array/readme.md new file mode 100644 index 00000000..88f3429c --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2917_find_the_k_or_of_an_array/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) + +## 2917\. Find the K-or of an Array + +Easy + +You are given a **0-indexed** integer array `nums`, and an integer `k`. + +The **K-or** of `nums` is a non-negative integer that satisfies the following: + +* The ith bit is set in the K-or **if and only if** there are at least `k` elements of nums in which bit `i` is set. + +Return _the **K-or** of_ `nums`. + +**Note** that a bit `i` is set in `x` if (2i AND x) == 2i, where `AND` is the bitwise `AND` operator. + +**Example 1:** + +**Input:** nums = [7,12,9,8,9,15], k = 4 + +**Output:** 9 + +**Explanation:** + +Bit 0 is set at nums[0], nums[2], nums[4], and nums[5]. + +Bit 1 is set at nums[0], and nums[5]. + +Bit 2 is set at nums[0], nums[1], and nums[5]. + +Bit 3 is set at nums[1], nums[2], nums[3], nums[4], and nums[5]. + +Only bits 0 and 3 are set in at least k elements of the array, and bits i >= 4 are not set in any of the array's elements. Hence, the answer is 2^0 + 2^3 = 9. + +**Example 2:** + +**Input:** nums = [2,12,1,11,4,5], k = 6 + +**Output:** 0 + +**Explanation:** Since k == 6 == nums.length, the 6-or of the array is equal to the bitwise AND of all its elements. Hence, the answer is 2 AND 12 AND 1 AND 11 AND 4 AND 5 = 0. + +**Example 3:** + +**Input:** nums = [10,8,5,9,11,6,8], k = 1 + +**Output:** 15 + +**Explanation:** Since k == 1, the 1-or of the array is equal to the bitwise OR of all its elements. Hence, the answer is 10 OR 8 OR 5 OR 9 OR 11 OR 6 OR 8 = 15. + +**Constraints:** + +* `1 <= nums.length <= 50` +* 0 <= nums[i] < 231 +* `1 <= k <= nums.length` + +## Solution + +```kotlin +class Solution { + fun findKOr(nums: IntArray, k: Int): Int { + val dp = IntArray(31) + for (num in nums) { + var i = 0 + var localNum = num + while (localNum > 0) { + if ((localNum and 1) == 1) { + dp[i] += 1 + } + i += 1 + localNum = localNum shr 1 + } + } + var ans = 0 + for (i in 0..30) { + if (dp[i] >= k) { + ans += (1 shl i) + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2918_minimum_equal_sum_of_two_arrays_after_replacing_zeros/readme.md b/src/main/kotlin/g2901_3000/s2918_minimum_equal_sum_of_two_arrays_after_replacing_zeros/readme.md new file mode 100644 index 00000000..fc35ae11 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2918_minimum_equal_sum_of_two_arrays_after_replacing_zeros/readme.md @@ -0,0 +1,57 @@ +[![](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) + +## 2918\. Minimum Equal Sum of Two Arrays After Replacing Zeros + +Medium + +You are given two arrays `nums1` and `nums2` consisting of positive integers. + +You have to replace **all** the `0`'s in both arrays with **strictly** positive integers such that the sum of elements of both arrays becomes **equal**. + +Return _the **minimum** equal sum you can obtain, or_ `-1` _if it is impossible_. + +**Example 1:** + +**Input:** nums1 = [3,2,0,1,0], nums2 = [6,5,0] + +**Output:** 12 + +**Explanation:** We can replace 0's in the following way: +- Replace the two 0's in nums1 with the values 2 and 4. The resulting array is nums1 = [3,2,2,1,4]. +- Replace the 0 in nums2 with the value 1. The resulting array is nums2 = [6,5,1]. Both arrays have an equal sum of 12. It can be shown that it is the minimum sum we can obtain. + +**Example 2:** + +**Input:** nums1 = [2,0,2,0], nums2 = [1,4] + +**Output:** -1 + +**Explanation:** It is impossible to make the sum of both arrays equal. + +**Constraints:** + +* 1 <= nums1.length, nums2.length <= 105 +* 0 <= nums1[i], nums2[i] <= 106 + +## Solution + +```kotlin +class Solution { + fun minSum(nums1: IntArray, nums2: IntArray): Long { + val sum1 = nums1.fold(0L) { sum, element -> sum + element } + val zeroCount1 = nums1.count { it == 0 } + + val sum2 = nums2.fold(0L) { sum, element -> sum + element } + val zeroCount2 = nums2.count { it == 0 } + + if ( + (zeroCount1 == 0 && sum1 < sum2 + zeroCount2) || + (zeroCount2 == 0 && sum2 < sum1 + zeroCount1) + ) { + return -1 + } + return Math.max(sum1 + zeroCount1, sum2 + zeroCount2) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2919_minimum_increment_operations_to_make_array_beautiful/readme.md b/src/main/kotlin/g2901_3000/s2919_minimum_increment_operations_to_make_array_beautiful/readme.md new file mode 100644 index 00000000..3245f4a4 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2919_minimum_increment_operations_to_make_array_beautiful/readme.md @@ -0,0 +1,105 @@ +[![](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) + +## 2919\. Minimum Increment Operations to Make Array Beautiful + +Medium + +You are given a **0-indexed** integer array `nums` having length `n`, and an integer `k`. + +You can perform the following **increment** operation **any** number of times (**including zero**): + +* Choose an index `i` in the range `[0, n - 1]`, and increase `nums[i]` by `1`. + +An array is considered **beautiful** if, for any **subarray** with a size of `3` or **more**, its **maximum** element is **greater than or equal** to `k`. + +Return _an integer denoting the **minimum** number of increment operations needed to make_ `nums` _**beautiful**._ + +A subarray is a contiguous **non-empty** sequence of elements within an array. + +**Example 1:** + +**Input:** nums = [2,3,0,0,2], k = 4 + +**Output:** 3 + +**Explanation:** We can perform the following increment operations to make nums beautiful: + +Choose index i = 1 and increase nums[1] by 1 -> [2,4,0,0,2]. + +Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,3]. + +Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,4]. + +The subarrays with a size of 3 or more are: [2,4,0], [4,0,0], [0,0,4], [2,4,0,0], [4,0,0,4], [2,4,0,0,4]. + +In all the subarrays, the maximum element is equal to k = 4, so nums is now beautiful. + +It can be shown that nums cannot be made beautiful with fewer than 3 increment operations. + +Hence, the answer is 3. + +**Example 2:** + +**Input:** nums = [0,1,3,3], k = 5 + +**Output:** 2 + +**Explanation:** We can perform the following increment operations to make nums beautiful: + +Choose index i = 2 and increase nums[2] by 1 -> [0,1,4,3]. + +Choose index i = 2 and increase nums[2] by 1 -> [0,1,5,3]. + +The subarrays with a size of 3 or more are: [0,1,5], [1,5,3], [0,1,5,3]. + +In all the subarrays, the maximum element is equal to k = 5, so nums is now beautiful. + +It can be shown that nums cannot be made beautiful with fewer than 2 increment operations. + +Hence, the answer is 2. + +**Example 3:** + +**Input:** nums = [1,1,2], k = 1 + +**Output:** 0 + +**Explanation:** The only subarray with a size of 3 or more in this example is [1,1,2]. The maximum element, 2, is already greater than k = 1, so we don't need any increment operation. Hence, the answer is 0. + +**Constraints:** + +* 3 <= n == nums.length <= 105 +* 0 <= nums[i] <= 109 +* 0 <= k <= 109 + +## Solution + +```kotlin +import kotlin.math.max +import kotlin.math.min + +class Solution { + fun minIncrementOperations(nums: IntArray, k: Int): Long { + val dp = LongArray(nums.size) + dp[0] = max(0, (k - nums[0]).toLong()) + dp[1] = max(0, (k - nums[1]).toLong()) + dp[2] = max(0, (k - nums[2]).toLong()) + for (i in 3 until nums.size) { + dp[i] = ( + max(0, k - nums[i]) + min( + min( + dp[i - 3], + dp[i - 2] + ), + dp[i - 1] + ) + ) + } + return min( + min(dp[nums.size - 3], dp[nums.size - 2]), + dp[nums.size - 1] + ) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2920_maximum_points_after_collecting_coins_from_all_nodes/readme.md b/src/main/kotlin/g2901_3000/s2920_maximum_points_after_collecting_coins_from_all_nodes/readme.md new file mode 100644 index 00000000..cb52db73 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2920_maximum_points_after_collecting_coins_from_all_nodes/readme.md @@ -0,0 +1,115 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2920\. Maximum Points After Collecting Coins From All Nodes + +Hard + +There exists an undirected tree rooted at node `0` with `n` nodes labeled from `0` to `n - 1`. You are given a 2D **integer** array `edges` of length `n - 1`, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given a **0-indexed** array `coins` of size `n` where `coins[i]` indicates the number of coins in the vertex `i`, and an integer `k`. + +Starting from the root, you have to collect all the coins such that the coins at a node can only be collected if the coins of its ancestors have been already collected. + +Coins at nodei can be collected in one of the following ways: + +* Collect all the coins, but you will get `coins[i] - k` points. If `coins[i] - k` is negative then you will lose `abs(coins[i] - k)` points. +* Collect all the coins, but you will get `floor(coins[i] / 2)` points. If this way is used, then for all the nodej present in the subtree of nodei, `coins[j]` will get reduced to `floor(coins[j] / 2)`. + +Return _the **maximum points** you can get after collecting the coins from **all** the tree nodes._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/09/18/ex1-copy.png) + +**Input:** edges = \[\[0,1],[1,2],[2,3]], coins = [10,10,3,3], k = 5 + +**Output:** 11 + +**Explanation:** + +Collect all the coins from node 0 using the first way. Total points = 10 - 5 = 5. + +Collect all the coins from node 1 using the first way. Total points = 5 + (10 - 5) = 10. + +Collect all the coins from node 2 using the second way so coins left at node 3 will be floor(3 / 2) = 1. Total points = 10 + floor(3 / 2) = 11. + +Collect all the coins from node 3 using the second way. Total points = 11 + floor(1 / 2) = 11. + +It can be shown that the maximum points we can get after collecting coins from all the nodes is 11. + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2023/09/18/ex2.png)** + +**Input:** edges = \[\[0,1],[0,2]], coins = [8,4,4], k = 0 + +**Output:** 16 + +**Explanation:** Coins will be collected from all the nodes using the first way. Therefore, total points = (8 - 0) + (4 - 0) + (4 - 0) = 16. + +**Constraints:** + +* `n == coins.length` +* 2 <= n <= 105 +* 0 <= coins[i] <= 104 +* `edges.length == n - 1` +* `0 <= edges[i][0], edges[i][1] < n` +* 0 <= k <= 104 + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + private lateinit var adjList: Array?> + private lateinit var coins: IntArray + private var k = 0 + private lateinit var dp: Array + + private fun init(edges: Array, coins: IntArray, k: Int) { + val n = coins.size + adjList = arrayOfNulls(n) + for (v in 0 until n) { + adjList[v] = ArrayList() + } + for (edge in edges) { + val u = edge[0] + val v = edge[1] + adjList[u]?.add(v) + adjList[v]?.add(u) + } + this.coins = coins + this.k = k + dp = Array(n) { IntArray(14) } + for (v in 0 until n) { + for (numOfWay2Parents in 0..13) { + dp[v][numOfWay2Parents] = -1 + } + } + } + + private fun rec(v: Int, p: Int, numOfWay2Parents: Int): Int { + if (numOfWay2Parents >= 14) { + return 0 + } + if (dp[v][numOfWay2Parents] == -1) { + val coinsV = coins[v] / (1 shl numOfWay2Parents) + var s0 = coinsV - k + var s1 = coinsV / 2 + for (child in adjList[v]!!) { + if (child != p) { + s0 += rec(child, v, numOfWay2Parents) + s1 += rec(child, v, numOfWay2Parents + 1) + } + } + dp[v][numOfWay2Parents] = max(s0, s1) + } + return dp[v][numOfWay2Parents] + } + + fun maximumPoints(edges: Array, coins: IntArray, k: Int): Int { + init(edges, coins, k) + return rec(0, -1, 0) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2923_find_champion_i/readme.md b/src/main/kotlin/g2901_3000/s2923_find_champion_i/readme.md new file mode 100644 index 00000000..302bcb2f --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2923_find_champion_i/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) + +## 2923\. Find Champion I + +Easy + +There are `n` teams numbered from `0` to `n - 1` in a tournament. + +Given a **0-indexed** 2D boolean matrix `grid` of size `n * n`. For all `i, j` that `0 <= i, j <= n - 1` and `i != j` team `i` is **stronger** than team `j` if `grid[i][j] == 1`, otherwise, team `j` is **stronger** than team `i`. + +Team `a` will be the **champion** of the tournament if there is no team `b` that is stronger than team `a`. + +Return _the team that will be the champion of the tournament._ + +**Example 1:** + +**Input:** grid = \[\[0,1],[0,0]] + +**Output:** 0 + +**Explanation:** There are two teams in this tournament. + +grid[0][1] == 1 means that team 0 is stronger than team 1. So team 0 will be the champion. + +**Example 2:** + +**Input:** grid = \[\[0,0,1],[1,0,1],[0,0,0]] + +**Output:** 1 + +**Explanation:** There are three teams in this tournament. + +grid[1][0] == 1 means that team 1 is stronger than team 0. + +grid[1][2] == 1 means that team 1 is stronger than team 2. + +So team 1 will be the champion. + +**Constraints:** + +* `n == grid.length` +* `n == grid[i].length` +* `2 <= n <= 100` +* `grid[i][j]` is either `0` or `1`. +* For all `i grid[i][i]` is `0.` +* For all `i, j` that `i != j`, `grid[i][j] != grid[j][i]`. +* The input is generated such that if team `a` is stronger than team `b` and team `b` is stronger than team `c`, then team `a` is stronger than team `c`. + +## Solution + +```kotlin +class Solution { + fun findChampion(grid: Array): Int { + var champion = grid[1][0] + for (opponent in 2 until grid.size) { + if (grid[opponent][champion] != 0) { + champion = opponent + } + } + return champion + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2924_find_champion_ii/readme.md b/src/main/kotlin/g2901_3000/s2924_find_champion_ii/readme.md new file mode 100644 index 00000000..0ce88fd6 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2924_find_champion_ii/readme.md @@ -0,0 +1,78 @@ +[![](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) + +## 2924\. Find Champion II + +Medium + +There are `n` teams numbered from `0` to `n - 1` in a tournament; each team is also a node in a **DAG**. + +You are given the integer `n` and a **0-indexed** 2D integer array `edges` of length `m` representing the **DAG**, where edges[i] = [ui, vi] indicates that there is a directed edge from team ui to team vi in the graph. + +A directed edge from `a` to `b` in the graph means that team `a` is **stronger** than team `b` and team `b` is **weaker** than team `a`. + +Team `a` will be the **champion** of the tournament if there is no team `b` that is **stronger** than team `a`. + +Return _the team that will be the **champion** of the tournament if there is a **unique** champion, otherwise, return_ `-1`_._ + +**Notes** + +* A **cycle** is a series of nodes a1, a2, ..., an, an+1 such that node a1 is the same node as node an+1, the nodes a1, a2, ..., an are distinct, and there is a directed edge from the node ai to node ai+1 for every `i` in the range `[1, n]`. +* A **DAG** is a directed graph that does not have any **cycle**. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/10/19/graph-3.png) + +**Input:** n = 3, edges = \[\[0,1],[1,2]] + +**Output:** 0 + +**Explanation:** Team 1 is weaker than team 0. Team 2 is weaker than team 1. So the champion is team 0. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/10/19/graph-4.png) + +**Input:** n = 4, edges = \[\[0,2],[1,3],[1,2]] + +**Output:** -1 + +**Explanation:** Team 2 is weaker than team 0 and team 1. Team 3 is weaker than team 1. But team 1 and team 0 are not weaker than any other teams. So the answer is -1. + +**Constraints:** + +* `1 <= n <= 100` +* `m == edges.length` +* `0 <= m <= n * (n - 1) / 2` +* `edges[i].length == 2` +* `0 <= edge[i][j] <= n - 1` +* `edges[i][0] != edges[i][1]` +* The input is generated such that if team `a` is stronger than team `b`, team `b` is not stronger than team `a`. +* The input is generated such that if team `a` is stronger than team `b` and team `b` is stronger than team `c`, then team `a` is stronger than team `c`. + +## Solution + +```kotlin +class Solution { + fun findChampion(n: Int, edges: Array): Int { + val arr = IntArray(n) + for (adj in edges) { + arr[adj[1]]++ + } + var cnt = 0 + var ans = -1 + for (i in 0 until n) { + if (arr[i] == 0) { + cnt++ + ans = i + } + } + return if (cnt == 1) { + ans + } else { + -1 + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2925_maximum_score_after_applying_operations_on_a_tree/readme.md b/src/main/kotlin/g2901_3000/s2925_maximum_score_after_applying_operations_on_a_tree/readme.md new file mode 100644 index 00000000..71531a35 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2925_maximum_score_after_applying_operations_on_a_tree/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) + +## 2925\. Maximum Score After Applying Operations on a Tree + +Medium + +There is an undirected tree with `n` nodes labeled from `0` to `n - 1`, and rooted at node `0`. You are given a 2D integer array `edges` of length `n - 1`, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. + +You are also given a **0-indexed** integer array `values` of length `n`, where `values[i]` is the **value** associated with the ith node. + +You start with a score of `0`. In one operation, you can: + +* Pick any node `i`. +* Add `values[i]` to your score. +* Set `values[i]` to `0`. + +A tree is **healthy** if the sum of values on the path from the root to any leaf node is different than zero. + +Return _the **maximum score** you can obtain after performing these operations on the tree any number of times so that it remains **healthy**._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/10/11/graph-13-1.png) + +**Input:** edges = \[\[0,1],[0,2],[0,3],[2,4],[4,5]], values = [5,2,5,2,1,1] + +**Output:** 11 + +**Explanation:** We can choose nodes 1, 2, 3, 4, and 5. The value of the root is non-zero. Hence, the sum of values on the path from the root to any leaf is different than zero. Therefore, the tree is healthy and the score is values[1] + values[2] + values[3] + values[4] + values[5] = 11. It can be shown that 11 is the maximum score obtainable after any number of operations on the tree. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/10/11/graph-14-2.png) + +**Input:** edges = \[\[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [20,10,9,7,4,3,5] + +**Output:** 40 + +**Explanation:** We can choose nodes 0, 2, 3, and 4. +- The sum of values on the path from 0 to 4 is equal to 10. +- The sum of values on the path from 0 to 3 is equal to 10. +- The sum of values on the path from 0 to 5 is equal to 3. +- The sum of values on the path from 0 to 6 is equal to 5. + +Therefore, the tree is healthy and the score is values[0] + values[2] + values[3] + values[4] = 40. + +It can be shown that 40 is the maximum score obtainable after any number of operations on the tree. + +**Constraints:** + +* 2 <= n <= 2 * 104 +* `edges.length == n - 1` +* `edges[i].length == 2` +* 0 <= ai, bi < n +* `values.length == n` +* 1 <= values[i] <= 109 +* The input is generated such that `edges` represents a valid tree. + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + fun maximumScoreAfterOperations(edges: Array, values: IntArray): Long { + var sum: Long = 0 + val n = values.size + val adj: MutableList> = ArrayList() + for (i in 0 until n) { + adj.add(ArrayList()) + } + for (edge in edges) { + adj[edge[0]].add(edge[1]) + adj[edge[1]].add(edge[0]) + } + for (value in values) { + sum += value.toLong() + } + val x = dfs(0, -1, adj, values) + return sum - x + } + + private fun dfs(node: Int, parent: Int, adj: List>, values: IntArray): Long { + if (adj[node].size == 1 && node != 0) { + return values[node].toLong() + } + var sum: Long = 0 + for (child in adj[node]) { + if (child != parent) { + sum += dfs(child, node, adj, values) + } + } + return min(sum, values[node].toLong()) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2926_maximum_balanced_subsequence_sum/readme.md b/src/main/kotlin/g2901_3000/s2926_maximum_balanced_subsequence_sum/readme.md new file mode 100644 index 00000000..218c4fc2 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2926_maximum_balanced_subsequence_sum/readme.md @@ -0,0 +1,140 @@ +[![](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) + +## 2926\. Maximum Balanced Subsequence Sum + +Hard + +You are given a **0-indexed** integer array `nums`. + +A **subsequence** of `nums` having length `k` and consisting of **indices** i0 < i1 < ... < ik-1 is **balanced** if the following holds: + +* nums[ij] - nums[ij-1] >= ij - ij-1, for every `j` in the range `[1, k - 1]`. + +A **subsequence** of `nums` having length `1` is considered balanced. + +Return _an integer denoting the **maximum** possible **sum of elements** in a **balanced** subsequence of_ `nums`. + +A **subsequence** of an array is a new **non-empty** array that is formed from the original array by deleting some (**possibly none**) of the elements without disturbing the relative positions of the remaining elements. + +**Example 1:** + +**Input:** nums = [3,3,5,6] + +**Output:** 14 + +**Explanation:** In this example, the subsequence [3,5,6] consisting of indices 0, 2, and 3 can be selected. + +nums[2] - nums[0] >= 2 - 0. + +nums[3] - nums[2] >= 3 - 2. + +Hence, it is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums. + +The subsequence consisting of indices 1, 2, and 3 is also valid. + +It can be shown that it is not possible to get a balanced subsequence with a sum greater than 14. + +**Example 2:** + +**Input:** nums = [5,-1,-3,8] + +**Output:** 13 + +**Explanation:** In this example, the subsequence [5,8] consisting of indices 0 and 3 can be selected. + +nums[3] - nums[0] >= 3 - 0. + +Hence, it is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums. + +It can be shown that it is not possible to get a balanced subsequence with a sum greater than 13. + +**Example 3:** + +**Input:** nums = [-2,-1] + +**Output:** -1 + +**Explanation:** In this example, the subsequence [-1] can be selected. It is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums. + +**Constraints:** + +* 1 <= nums.length <= 105 +* -109 <= nums[i] <= 109 + +## Solution + +```kotlin +import kotlin.math.max + +@Suppress("NAME_SHADOWING") +class Solution { + fun maxBalancedSubsequenceSum(nums: IntArray): Long { + val n = nums.size + var m = 0 + val arr = IntArray(n) + var max = Int.MIN_VALUE + for (i in 0 until n) { + val x = nums[i] + if (x > 0) { + arr[m++] = x - i + } else if (x > max) { + max = x + } + } + if (m == 0) { + return max.toLong() + } + arr.sort() + val map: MutableMap = HashMap(m shl 1) + var pre = Int.MIN_VALUE + var index = 1 + for (x in arr) { + if (x == pre) { + continue + } + map[x] = index++ + pre = x + } + + val bit = BIT(index) + var ans: Long = 0 + for (i in 0 until n) { + if (nums[i] <= 0) { + continue + } + index = map[nums[i] - i]!! + val cur = bit.query(index) + nums[i] + bit.update(index, cur) + ans = max(ans, cur) + } + return ans + } + + private class BIT(var n: Int) { + var tree: LongArray = LongArray(n + 1) + + fun lowbit(index: Int): Int { + return index and (-index) + } + + fun update(index: Int, v: Long) { + var index = index + while (index <= n && tree[index] < v) { + tree[index] = v + index += lowbit(index) + } + } + + fun query(index: Int): Long { + var index = index + var result: Long = 0 + while (index > 0) { + result = max(tree[index].toDouble(), result.toDouble()).toLong() + index -= lowbit(index) + } + return result + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2928_distribute_candies_among_children_i/readme.md b/src/main/kotlin/g2901_3000/s2928_distribute_candies_among_children_i/readme.md new file mode 100644 index 00000000..b7e9879f --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2928_distribute_candies_among_children_i/readme.md @@ -0,0 +1,52 @@ +[![](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) + +## 2928\. Distribute Candies Among Children I + +Easy + +You are given two positive integers `n` and `limit`. + +Return _the **total number** of ways to distribute_ `n` _candies among_ `3` _children such that no child gets more than_ `limit` _candies._ + +**Example 1:** + +**Input:** n = 5, limit = 2 + +**Output:** 3 + +**Explanation:** There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1). + +**Example 2:** + +**Input:** n = 3, limit = 3 + +**Output:** 10 + +**Explanation:** There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0). + +**Constraints:** + +* `1 <= n <= 50` +* `1 <= limit <= 50` + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + fun distributeCandies(n: Int, limit: Int): Int { + var count = 0 + for (i in 0 until min(limit, n) + 1) { + for (j in 0 until min(limit, n) + 1) { + val k = n - i - j + if (k >= 0 && k <= limit) { + count++ + } + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2929_distribute_candies_among_children_ii/readme.md b/src/main/kotlin/g2901_3000/s2929_distribute_candies_among_children_ii/readme.md new file mode 100644 index 00000000..02b17f2f --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2929_distribute_candies_among_children_ii/readme.md @@ -0,0 +1,55 @@ +[![](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) + +## 2929\. Distribute Candies Among Children II + +Medium + +You are given two positive integers `n` and `limit`. + +Return _the **total number** of ways to distribute_ `n` _candies among_ `3` _children such that no child gets more than_ `limit` _candies._ + +**Example 1:** + +**Input:** n = 5, limit = 2 + +**Output:** 3 + +**Explanation:** There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1). + +**Example 2:** + +**Input:** n = 3, limit = 3 + +**Output:** 10 + +**Explanation:** There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0). + +**Constraints:** + +* 1 <= n <= 106 +* 1 <= limit <= 106 + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + fun distributeCandies(n: Int, limit: Int): Long { + var ans: Long = 0 + for (i in 0..min(n, limit)) { + var rem = (n - i).toLong() + if (rem > 2 * limit) continue + // second student + val max = min(limit.toLong(), rem) + // for third student + rem -= max + // if remain is grater than limit cant possible to arrange; + // if(rem <= limit) than max - rem combination + if (rem <= limit) ans = ans + max - rem + 1 + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2945_find_maximum_non_decreasing_array_length/readme.md b/src/main/kotlin/g2901_3000/s2945_find_maximum_non_decreasing_array_length/readme.md new file mode 100644 index 00000000..dc697c73 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2945_find_maximum_non_decreasing_array_length/readme.md @@ -0,0 +1,89 @@ +[![](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) + +## 2945\. Find Maximum Non-decreasing Array Length + +Hard + +You are given a **0-indexed** integer array `nums`. + +You can perform any number of operations, where each operation involves selecting a **subarray** of the array and replacing it with the **sum** of its elements. For example, if the given array is `[1,3,5,6]` and you select subarray `[3,5]` the array will convert to `[1,8,6]`. + +Return _the_ **_maximum_** _length of a_ **_non-decreasing_** _array that can be made after applying operations._ + +A **subarray** is a contiguous **non-empty** sequence of elements within an array. + +**Example 1:** + +**Input:** nums = [5,2,2] + +**Output:** 1 + +**Explanation:** This array with length 3 is not non-decreasing. + +We have two ways to make the array length two. + +First, choosing subarray [2,2] converts the array to [5,4]. + +Second, choosing subarray [5,2] converts the array to [7,2]. + +In these two ways the array is not non-decreasing. + +And if we choose subarray [5,2,2] and replace it with [9] it becomes non-decreasing. + +So the answer is 1. + +**Example 2:** + +**Input:** nums = [1,2,3,4] + +**Output:** 4 + +**Explanation:** The array is non-decreasing. So the answer is 4. + +**Example 3:** + +**Input:** nums = [4,3,2,6] + +**Output:** 3 + +**Explanation:** Replacing [3,2] with [5] converts the given array to [4,5,6] that is non-decreasing. + +Because the given array is not non-decreasing, the maximum possible answer is 3. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun findMaximumLength(nums: IntArray): Int { + val n = nums.size + val que = IntArray(n + 1) + var write = 0 + var read = 0 + val prefixSum = LongArray(n + 1) + val sums = LongArray(n + 1) + val count = IntArray(n + 1) + for (i in 1..n) { + prefixSum[i] = prefixSum[i - 1] + nums[i - 1] + while (read < write && prefixSum[i] >= sums[read + 1]) { + read++ + } + val j = que[read] + val subarraySum = prefixSum[i] - prefixSum[j] + count[i] = count[j] + 1 + val sum = prefixSum[i] + subarraySum + while (sum <= sums[write]) { + write-- + } + que[++write] = i + sums[write] = sum + } + return count[n] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2946_matrix_similarity_after_cyclic_shifts/readme.md b/src/main/kotlin/g2901_3000/s2946_matrix_similarity_after_cyclic_shifts/readme.md new file mode 100644 index 00000000..0fa496b8 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2946_matrix_similarity_after_cyclic_shifts/readme.md @@ -0,0 +1,69 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2946\. Matrix Similarity After Cyclic Shifts + +Easy + +You are given a **0-indexed** `m x n` integer matrix `mat` and an integer `k`. You have to cyclically **right** shift **odd** indexed rows `k` times and cyclically **left** shift **even** indexed rows `k` times. + +Return `true` _if the initial and final matrix are exactly the same and_ `false` _otherwise._ + +**Example 1:** + +**Input:** mat = \[\[1,2,1,2],[5,5,5,5],[6,3,6,3]], k = 2 + +**Output:** true + +**Explanation:** ![](https://assets.leetcode.com/uploads/2023/10/29/similarmatrix.png) Initially, the matrix looks like the first figure. Second figure represents the state of the matrix after one right and left cyclic shifts to even and odd indexed rows. Third figure is the final state of the matrix after two cyclic shifts which is similar to the initial matrix. Therefore, return true. + +**Example 2:** + +**Input:** mat = \[\[2,2],[2,2]], k = 3 + +**Output:** true + +**Explanation:** As all the values are equal in the matrix, even after performing cyclic shifts the matrix will remain the same. Therefeore, we return true. + +**Example 3:** + +**Input:** mat = \[\[1,2]], k = 1 + +**Output:** false + +**Explanation:** After one cyclic shift, mat = \[\[2,1]] which is not equal to the initial matrix. Therefore we return false. + +**Constraints:** + +* `1 <= mat.length <= 25` +* `1 <= mat[i].length <= 25` +* `1 <= mat[i][j] <= 25` +* `1 <= k <= 50` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun areSimilar(mat: Array, k: Int): Boolean { + var k = k + val m = mat.size + val n = mat[0].size + k %= n + for (i in 0 until m) { + for (j in 0 until n) { + if ((i and 1) != 0) { + if (mat[i][j] != mat[i][(j - k + n) % n]) { + return false + } + } else { + if (mat[i][j] != mat[i][(j + k) % n]) { + return false + } + } + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2947_count_beautiful_substrings_i/readme.md b/src/main/kotlin/g2901_3000/s2947_count_beautiful_substrings_i/readme.md new file mode 100644 index 00000000..23bfce20 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2947_count_beautiful_substrings_i/readme.md @@ -0,0 +1,108 @@ +[![](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) + +## 2947\. Count Beautiful Substrings I + +Medium + +You are given a string `s` and a positive integer `k`. + +Let `vowels` and `consonants` be the number of vowels and consonants in a string. + +A string is **beautiful** if: + +* `vowels == consonants`. +* `(vowels * consonants) % k == 0`, in other terms the multiplication of `vowels` and `consonants` is divisible by `k`. + +Return _the number of **non-empty beautiful substrings** in the given string_ `s`. + +A **substring** is a contiguous sequence of characters in a string. + +**Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. + +**Consonant letters** in English are every letter except vowels. + +**Example 1:** + +**Input:** s = "baeyh", k = 2 + +**Output:** 2 + +**Explanation:** There are 2 beautiful substrings in the given string. + +- Substring "baeyh", vowels = 2 (["a",e"]), consonants = 2 (["y","h"]). + +You can see that string "aeyh" is beautiful as vowels == consonants and vowels \* consonants % k == 0. + +- Substring "baeyh", vowels = 2 (["a",e"]), consonants = 2 (["b","y"]). + +You can see that string "baey" is beautiful as vowels == consonants and vowels \* consonants % k == 0. + +It can be shown that there are only 2 beautiful substrings in the given string. + +**Example 2:** + +**Input:** s = "abba", k = 1 + +**Output:** 3 + +**Explanation:** There are 3 beautiful substrings in the given string. + +- Substring "abba", vowels = 1 (["a"]), consonants = 1 (["b"]). + +- Substring "abba", vowels = 1 (["a"]), consonants = 1 (["b"]). + +- Substring "abba", vowels = 2 (["a","a"]), consonants = 2 (["b","b"]). + +It can be shown that there are only 3 beautiful substrings in the given string. + +**Example 3:** + +**Input:** s = "bcdf", k = 1 + +**Output:** 0 + +**Explanation:** There are no beautiful substrings in the given string. + +**Constraints:** + +* `1 <= s.length <= 1000` +* `1 <= k <= 1000` +* `s` consists of only English lowercase letters. + +## Solution + +```kotlin +class Solution { + fun beautifulSubstrings(s: String, k: Int): Int { + val numVowels = IntArray(s.length + 1) + for (i in s.indices) { + val c = s[i] + if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { + numVowels[i + 1] = numVowels[i] + 1 + } else { + numVowels[i + 1] = numVowels[i] + } + } + var step = 1 + while (step < k) { + if ((step * step) % k == 0) { + break + } + step++ + } + step *= 2 + var count = 0 + for (i in s.indices) { + var j = i + step + while (j <= s.length) { + if ((numVowels[j] - numVowels[i]) * 2 == j - i) { + count++ + } + j += step + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2948_make_lexicographically_smallest_array_by_swapping_elements/readme.md b/src/main/kotlin/g2901_3000/s2948_make_lexicographically_smallest_array_by_swapping_elements/readme.md new file mode 100644 index 00000000..4ce68938 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2948_make_lexicographically_smallest_array_by_swapping_elements/readme.md @@ -0,0 +1,109 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2948\. Make Lexicographically Smallest Array by Swapping Elements + +Medium + +You are given a **0-indexed** array of **positive** integers `nums` and a **positive** integer `limit`. + +In one operation, you can choose any two indices `i` and `j` and swap `nums[i]` and `nums[j]` **if** `|nums[i] - nums[j]| <= limit`. + +Return _the **lexicographically smallest array** that can be obtained by performing the operation any number of times_. + +An array `a` is lexicographically smaller than an array `b` if in the first position where `a` and `b` differ, array `a` has an element that is less than the corresponding element in `b`. For example, the array `[2,10,3]` is lexicographically smaller than the array `[10,2,3]` because they differ at index `0` and `2 < 10`. + +**Example 1:** + +**Input:** nums = [1,5,3,9,8], limit = 2 + +**Output:** [1,3,5,8,9] + +**Explanation:** Apply the operation 2 times: + +- Swap nums[1] with nums[2]. The array becomes [1,3,5,9,8] + +- Swap nums[3] with nums[4]. The array becomes [1,3,5,8,9] + +We cannot obtain a lexicographically smaller array by applying any more operations. + +Note that it may be possible to get the same result by doing different operations. + +**Example 2:** + +**Input:** nums = [1,7,6,18,2,1], limit = 3 + +**Output:** [1,6,7,18,1,2] + +**Explanation:** Apply the operation 3 times: + +- Swap nums[1] with nums[2]. The array becomes [1,6,7,18,2,1] + +- Swap nums[0] with nums[4]. The array becomes [2,6,7,18,1,1] + +- Swap nums[0] with nums[5]. The array becomes [1,6,7,18,1,2] + +We cannot obtain a lexicographically smaller array by applying any more operations. + +**Example 3:** + +**Input:** nums = [1,7,28,19,10], limit = 3 + +**Output:** [1,7,28,19,10] + +**Explanation:** [1,7,28,19,10] is the lexicographically smallest array we can obtain because we cannot apply the operation on any two indices. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 109 +* 1 <= limit <= 109 + +## Solution + +```kotlin +import kotlin.math.abs + +class Solution { + fun lexicographicallySmallestArray(nums: IntArray, limit: Int): IntArray { + val n = nums.size + val nodes = arrayOfNulls(n) + for (i in 0 until n) { + nodes[i] = Node(i, nums[i]) + } + nodes.sortWith { a: Node?, b: Node? -> + Integer.signum( + a!!.value - b!!.value + ) + } + var group = 1 + nodes[0]!!.group = group + for (i in 1 until n) { + if (abs((nodes[i]!!.value - nodes[i - 1]!!.value).toDouble()) <= limit) { + nodes[i]!!.group = group + } else { + nodes[i]!!.group = ++group + } + } + val groupBase = IntArray(group + 1) + for (i in n - 1 downTo 0) { + groupBase[nodes[i]!!.group] = i + } + val groupIndex = IntArray(n) + for (node in nodes) { + groupIndex[node!!.id] = node.group + } + val ans = IntArray(n) + for (i in 0 until n) { + val index = groupBase[groupIndex[i]] + ans[i] = nodes[index]!!.value + groupBase[groupIndex[i]]++ + } + return ans + } + + private class Node(var id: Int, var value: Int) { + var group: Int = 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2901_3000/s2949_count_beautiful_substrings_ii/readme.md b/src/main/kotlin/g2901_3000/s2949_count_beautiful_substrings_ii/readme.md new file mode 100644 index 00000000..8b6db957 --- /dev/null +++ b/src/main/kotlin/g2901_3000/s2949_count_beautiful_substrings_ii/readme.md @@ -0,0 +1,101 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2949\. Count Beautiful Substrings II + +Hard + +You are given a string `s` and a positive integer `k`. + +Let `vowels` and `consonants` be the number of vowels and consonants in a string. + +A string is **beautiful** if: + +* `vowels == consonants`. +* `(vowels * consonants) % k == 0`, in other terms the multiplication of `vowels` and `consonants` is divisible by `k`. + +Return _the number of **non-empty beautiful substrings** in the given string_ `s`. + +A **substring** is a contiguous sequence of characters in a string. + +**Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. + +**Consonant letters** in English are every letter except vowels. + +**Example 1:** + +**Input:** s = "baeyh", k = 2 + +**Output:** 2 + +**Explanation:** There are 2 beautiful substrings in the given string. + +- Substring "baeyh", vowels = 2 (["a",e"]), consonants = 2 (["y","h"]). + +You can see that string "aeyh" is beautiful as vowels == consonants and vowels \* consonants % k == 0. + +- Substring "baeyh", vowels = 2 (["a",e"]), consonants = 2 (["b","y"]). + +You can see that string "baey" is beautiful as vowels == consonants and vowels \* consonants % k == 0. + +It can be shown that there are only 2 beautiful substrings in the given string. + +**Example 2:** + +**Input:** s = "abba", k = 1 + +**Output:** 3 + +**Explanation:** There are 3 beautiful substrings in the given string. + +- Substring "abba", vowels = 1 (["a"]), consonants = 1 (["b"]). + +- Substring "abba", vowels = 1 (["a"]), consonants = 1 (["b"]). + +- Substring "abba", vowels = 2 (["a","a"]), consonants = 2 (["b","b"]). + +It can be shown that there are only 3 beautiful substrings in the given string. + +**Example 3:** + +**Input:** s = "bcdf", k = 1 + +**Output:** 0 + +**Explanation:** There are no beautiful substrings in the given string. + +**Constraints:** + +* 1 <= s.length <= 5 * 104 +* `1 <= k <= 1000` +* `s` consists of only English lowercase letters. + +## Solution + +```kotlin +class Solution { + fun beautifulSubstrings(s: String, k: Int): Long { + var res: Long = 0 + val n = s.length + var l = 1 + while ((l * l) % (4 * k) != 0) { + l++ + } + val seen: Array> = Array(l) { HashMap() } + var v = 0 + seen[l - 1][0] = 1 + for (i in 0 until n) { + val c = s[i] + if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { + v += 1 + } else { + v -= 1 + } + val cnt = seen[i % l].getOrDefault(v, 0) + res += cnt.toLong() + seen[i % l][v] = cnt + 1 + } + return res + } +} +``` \ No newline at end of file