diff --git a/README.md b/README.md index 9e374436..f4d49a1d 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,7 @@ | | | | | | |-|-|-|-|-|- +| 0785 |[Is Graph Bipartite?](src/main/kotlin/g0701_0800/s0785_is_graph_bipartite)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 215 | 82.35 ### SQL I @@ -946,6 +947,7 @@ |-|-|-|-|-|- | 0077 |[Combinations](src/main/kotlin/g0001_0100/s0077_combinations)| Medium | Backtracking | 244 | 100.00 | 0046 |[Permutations](src/main/kotlin/g0001_0100/s0046_permutations)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Backtracking | 186 | 100.00 +| 0784 |[Letter Case Permutation](src/main/kotlin/g0701_0800/s0784_letter_case_permutation)| Medium | String, Bit_Manipulation, Backtracking | 219 | 84.62 #### Day 12 Dynamic Programming @@ -1674,6 +1676,34 @@ | 1143 |[Longest Common Subsequence](src/main/kotlin/g1101_1200/s1143_longest_common_subsequence)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming, Algorithm_II_Day_17_Dynamic_Programming, Dynamic_Programming_I_Day_19, Udemy_Dynamic_Programming | 307 | 38.36 | 0994 |[Rotting Oranges](src/main/kotlin/g0901_1000/s0994_rotting_oranges)| Medium | Array, Breadth_First_Search, Matrix, Algorithm_I_Day_9_Breadth_First_Search_Depth_First_Search, Level_2_Day_10_Graph/BFS/DFS | 308 | 57.93 | 0864 |[Shortest Path to Get All Keys](src/main/kotlin/g0801_0900/s0864_shortest_path_to_get_all_keys)| Hard | Breadth_First_Search, Bit_Manipulation | 176 | 100.00 +| 0796 |[Rotate String](src/main/kotlin/g0701_0800/s0796_rotate_string)| Easy | String, String_Matching | 134 | 100.00 +| 0795 |[Number of Subarrays with Bounded Maximum](src/main/kotlin/g0701_0800/s0795_number_of_subarrays_with_bounded_maximum)| Medium | Array, Two_Pointers | 361 | 66.67 +| 0794 |[Valid Tic-Tac-Toe State](src/main/kotlin/g0701_0800/s0794_valid_tic_tac_toe_state)| Medium | Array, String | 138 | 100.00 +| 0793 |[Preimage Size of Factorial Zeroes Function](src/main/kotlin/g0701_0800/s0793_preimage_size_of_factorial_zeroes_function)| Hard | Math, Binary_Search | 114 | 100.00 +| 0792 |[Number of Matching Subsequences](src/main/kotlin/g0701_0800/s0792_number_of_matching_subsequences)| Medium | String, Hash_Table, Sorting, Trie | 346 | 100.00 +| 0791 |[Custom Sort String](src/main/kotlin/g0701_0800/s0791_custom_sort_string)| Medium | String, Hash_Table, Sorting | 133 | 90.00 +| 0790 |[Domino and Tromino Tiling](src/main/kotlin/g0701_0800/s0790_domino_and_tromino_tiling)| Medium | Dynamic_Programming | 116 | 100.00 +| 0789 |[Escape The Ghosts](src/main/kotlin/g0701_0800/s0789_escape_the_ghosts)| Medium | Array, Math | 187 | 100.00 +| 0788 |[Rotated Digits](src/main/kotlin/g0701_0800/s0788_rotated_digits)| Medium | Dynamic_Programming, Math | 137 | 80.00 +| 0787 |[Cheapest Flights Within K Stops](src/main/kotlin/g0701_0800/s0787_cheapest_flights_within_k_stops)| Medium | Dynamic_Programming, Depth_First_Search, Breadth_First_Search, Heap_Priority_Queue, Graph, Shortest_Path | 185 | 99.20 +| 0786 |[K-th Smallest Prime Fraction](src/main/kotlin/g0701_0800/s0786_k_th_smallest_prime_fraction)| Medium | Array, Binary_Search, Heap_Priority_Queue | 165 | 100.00 +| 0785 |[Is Graph Bipartite?](src/main/kotlin/g0701_0800/s0785_is_graph_bipartite)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find, Graph_Theory_I_Day_14_Graph_Theory | 215 | 82.35 +| 0784 |[Letter Case Permutation](src/main/kotlin/g0701_0800/s0784_letter_case_permutation)| Medium | String, Bit_Manipulation, Backtracking, Algorithm_I_Day_11_Recursion_Backtracking | 219 | 84.62 +| 0783 |[Minimum Distance Between BST Nodes](src/main/kotlin/g0701_0800/s0783_minimum_distance_between_bst_nodes)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 144 | 96.35 +| 0782 |[Transform to Chessboard](src/main/kotlin/g0701_0800/s0782_transform_to_chessboard)| Hard | Array, Math, Matrix, Bit_Manipulation | 188 | 100.00 +| 0781 |[Rabbits in Forest](src/main/kotlin/g0701_0800/s0781_rabbits_in_forest)| Medium | Array, Hash_Table, Math, Greedy | 132 | 100.00 +| 0780 |[Reaching Points](src/main/kotlin/g0701_0800/s0780_reaching_points)| Hard | Math | 139 | 100.00 +| 0779 |[K-th Symbol in Grammar](src/main/kotlin/g0701_0800/s0779_k_th_symbol_in_grammar)| Medium | Math, Bit_Manipulation, Recursion | 114 | 100.00 +| 0778 |[Swim in Rising Water](src/main/kotlin/g0701_0800/s0778_swim_in_rising_water)| Hard | Array, Depth_First_Search, Breadth_First_Search, Binary_Search, Matrix, Heap_Priority_Queue, Union_Find | 190 | 100.00 +| 0777 |[Swap Adjacent in LR String](src/main/kotlin/g0701_0800/s0777_swap_adjacent_in_lr_string)| Medium | String, Two_Pointers | 188 | 100.00 +| 0775 |[Global and Local Inversions](src/main/kotlin/g0701_0800/s0775_global_and_local_inversions)| Medium | Array, Math | 495 | 100.00 +| 0773 |[Sliding Puzzle](src/main/kotlin/g0701_0800/s0773_sliding_puzzle)| Hard | Array, Breadth_First_Search, Matrix | 166 | 100.00 +| 0771 |[Jewels and Stones](src/main/kotlin/g0701_0800/s0771_jewels_and_stones)| Easy | String, Hash_Table | 143 | 99.08 +| 0770 |[Basic Calculator IV](src/main/kotlin/g0701_0800/s0770_basic_calculator_iv)| Hard | String, Hash_Table, Math, Stack, Recursion | 222 | 100.00 +| 0769 |[Max Chunks To Make Sorted](src/main/kotlin/g0701_0800/s0769_max_chunks_to_make_sorted)| Medium | Array, Sorting, Greedy, Stack, Monotonic_Stack | 136 | 90.00 +| 0768 |[Max Chunks To Make Sorted II](src/main/kotlin/g0701_0800/s0768_max_chunks_to_make_sorted_ii)| Hard | Array, Sorting, Greedy, Stack, Monotonic_Stack | 202 | 100.00 +| 0767 |[Reorganize String](src/main/kotlin/g0701_0800/s0767_reorganize_string)| Medium | String, Hash_Table, Sorting, Greedy, Heap_Priority_Queue, Counting | 148 | 100.00 +| 0766 |[Toeplitz Matrix](src/main/kotlin/g0701_0800/s0766_toeplitz_matrix)| Easy | Array, Matrix | 174 | 100.00 | 0765 |[Couples Holding Hands](src/main/kotlin/g0701_0800/s0765_couples_holding_hands)| Hard | Depth_First_Search, Greedy, Breadth_First_Search, Graph, Union_Find | 131 | 100.00 | 0764 |[Largest Plus Sign](src/main/kotlin/g0701_0800/s0764_largest_plus_sign)| Medium | Array, Dynamic_Programming | 415 | 100.00 | 0763 |[Partition Labels](src/main/kotlin/g0701_0800/s0763_partition_labels)| Medium | Top_100_Liked_Questions, String, Hash_Table, Greedy, Two_Pointers, Data_Structure_II_Day_7_String | 235 | 84.75 diff --git a/src/main/kotlin/g0101_0200/s0106_construct_binary_tree_from_inorder_and_postorder_traversal/readme.md b/src/main/kotlin/g0101_0200/s0106_construct_binary_tree_from_inorder_and_postorder_traversal/readme.md index fa41890c..990c26ce 100644 --- a/src/main/kotlin/g0101_0200/s0106_construct_binary_tree_from_inorder_and_postorder_traversal/readme.md +++ b/src/main/kotlin/g0101_0200/s0106_construct_binary_tree_from_inorder_and_postorder_traversal/readme.md @@ -36,7 +36,7 @@ Given two integer arrays `inorder` and `postorder` where `inorder` is the inorde ```kotlin import com_github_leetcode.TreeNode -/** +/* * Example: * var ti = TreeNode(5) * var v = ti.`val` diff --git a/src/main/kotlin/g0101_0200/s0107_binary_tree_level_order_traversal_ii/readme.md b/src/main/kotlin/g0101_0200/s0107_binary_tree_level_order_traversal_ii/readme.md index 838cd27d..69ed358c 100644 --- a/src/main/kotlin/g0101_0200/s0107_binary_tree_level_order_traversal_ii/readme.md +++ b/src/main/kotlin/g0101_0200/s0107_binary_tree_level_order_traversal_ii/readme.md @@ -39,7 +39,7 @@ import com_github_leetcode.TreeNode import java.util.Collections import kotlin.collections.ArrayList -/** +/* * Example: * var ti = TreeNode(5) * var v = ti.`val` diff --git a/src/main/kotlin/g0101_0200/s0108_convert_sorted_array_to_binary_search_tree/readme.md b/src/main/kotlin/g0101_0200/s0108_convert_sorted_array_to_binary_search_tree/readme.md index 60af77cd..8824ac3e 100644 --- a/src/main/kotlin/g0101_0200/s0108_convert_sorted_array_to_binary_search_tree/readme.md +++ b/src/main/kotlin/g0101_0200/s0108_convert_sorted_array_to_binary_search_tree/readme.md @@ -40,7 +40,7 @@ A **height-balanced** binary tree is a binary tree in which the depth of the two ```kotlin import com_github_leetcode.TreeNode -/** +/* * Example: * var ti = TreeNode(5) * var v = ti.`val` diff --git a/src/main/kotlin/g0301_0400/s0352_data_stream_as_disjoint_intervals/readme.md b/src/main/kotlin/g0301_0400/s0352_data_stream_as_disjoint_intervals/readme.md index 515688f3..49840fa3 100644 --- a/src/main/kotlin/g0301_0400/s0352_data_stream_as_disjoint_intervals/readme.md +++ b/src/main/kotlin/g0301_0400/s0352_data_stream_as_disjoint_intervals/readme.md @@ -102,7 +102,7 @@ class SummaryRanges { } } -/** +/* * Your SummaryRanges object will be instantiated and called as such: * var obj = SummaryRanges() * obj.addNum(value) diff --git a/src/main/kotlin/g0501_0600/s0501_find_mode_in_binary_search_tree/readme.md b/src/main/kotlin/g0501_0600/s0501_find_mode_in_binary_search_tree/readme.md index 7b4552c6..2b4471c8 100644 --- a/src/main/kotlin/g0501_0600/s0501_find_mode_in_binary_search_tree/readme.md +++ b/src/main/kotlin/g0501_0600/s0501_find_mode_in_binary_search_tree/readme.md @@ -86,7 +86,6 @@ class Solution { } } processInOrder() - return ans.toIntArray() } } diff --git a/src/main/kotlin/g0501_0600/s0509_fibonacci_number/readme.md b/src/main/kotlin/g0501_0600/s0509_fibonacci_number/readme.md index b0bb26ac..df9b8f37 100644 --- a/src/main/kotlin/g0501_0600/s0509_fibonacci_number/readme.md +++ b/src/main/kotlin/g0501_0600/s0509_fibonacci_number/readme.md @@ -44,6 +44,7 @@ Given `n`, calculate `F(n)`. ```kotlin class Solution { private val memo = IntArray(31) + fun fib(n: Int): Int { if (n == 0) { return 0 diff --git a/src/main/kotlin/g0501_0600/s0520_detect_capital/readme.md b/src/main/kotlin/g0501_0600/s0520_detect_capital/readme.md index 0da33dee..6fc50a3c 100644 --- a/src/main/kotlin/g0501_0600/s0520_detect_capital/readme.md +++ b/src/main/kotlin/g0501_0600/s0520_detect_capital/readme.md @@ -34,8 +34,8 @@ Given a string `word`, return `true` if the usage of capitals in it is right. ```kotlin class Solution { - fun detectCapitalUse(word: String?): Boolean { - if (word == null || word.length == 0) { + fun detectCapitalUse(word: String): Boolean { + if (word.isEmpty()) { return false } var upper = 0 diff --git a/src/main/kotlin/g0501_0600/s0530_minimum_absolute_difference_in_bst/readme.md b/src/main/kotlin/g0501_0600/s0530_minimum_absolute_difference_in_bst/readme.md index 29f82761..f5f2db67 100644 --- a/src/main/kotlin/g0501_0600/s0530_minimum_absolute_difference_in_bst/readme.md +++ b/src/main/kotlin/g0501_0600/s0530_minimum_absolute_difference_in_bst/readme.md @@ -48,6 +48,7 @@ import com_github_leetcode.TreeNode class Solution { private var ans = Int.MAX_VALUE private var prev = Int.MAX_VALUE + fun getMinimumDifference(root: TreeNode?): Int { if (root == null) { return ans diff --git a/src/main/kotlin/g0501_0600/s0554_brick_wall/readme.md b/src/main/kotlin/g0501_0600/s0554_brick_wall/readme.md index 4a3c6a8f..cbb335d6 100644 --- a/src/main/kotlin/g0501_0600/s0554_brick_wall/readme.md +++ b/src/main/kotlin/g0501_0600/s0554_brick_wall/readme.md @@ -49,7 +49,6 @@ class Solution { } } var value = 0 - if (gapMap.size > 0) { value = gapMap.values.max() } diff --git a/src/main/kotlin/g0501_0600/s0558_logical_or_of_two_binary_grids_represented_as_quad_trees/readme.md b/src/main/kotlin/g0501_0600/s0558_logical_or_of_two_binary_grids_represented_as_quad_trees/readme.md index 7b7ea782..df27a7d0 100644 --- a/src/main/kotlin/g0501_0600/s0558_logical_or_of_two_binary_grids_represented_as_quad_trees/readme.md +++ b/src/main/kotlin/g0501_0600/s0558_logical_or_of_two_binary_grids_represented_as_quad_trees/readme.md @@ -80,7 +80,6 @@ If the value of `isLeaf` or `val` is True we represent it as **1** in the list ` * var bottomRight: Node? = null * } */ - class Solution { fun intersect(quadTree1: Node?, quadTree2: Node?): Node? { if (quadTree1!!.isLeaf) { diff --git a/src/main/kotlin/g0501_0600/s0559_maximum_depth_of_n_ary_tree/readme.md b/src/main/kotlin/g0501_0600/s0559_maximum_depth_of_n_ary_tree/readme.md index 96297511..0577e61b 100644 --- a/src/main/kotlin/g0501_0600/s0559_maximum_depth_of_n_ary_tree/readme.md +++ b/src/main/kotlin/g0501_0600/s0559_maximum_depth_of_n_ary_tree/readme.md @@ -43,7 +43,6 @@ import com_github_leetcode.Node * var neighbors: List = listOf() * } */ - class Solution { private var max = 0 diff --git a/src/main/kotlin/g0501_0600/s0563_binary_tree_tilt/readme.md b/src/main/kotlin/g0501_0600/s0563_binary_tree_tilt/readme.md index 7dcdb32b..06f5a665 100644 --- a/src/main/kotlin/g0501_0600/s0563_binary_tree_tilt/readme.md +++ b/src/main/kotlin/g0501_0600/s0563_binary_tree_tilt/readme.md @@ -72,6 +72,7 @@ import com_github_leetcode.TreeNode */ class Solution { private var sum = 0 + private fun sumTilt(root: TreeNode?): Int { if (root == null) { return 0 diff --git a/src/main/kotlin/g0501_0600/s0575_distribute_candies/readme.md b/src/main/kotlin/g0501_0600/s0575_distribute_candies/readme.md index daee8079..adf3818a 100644 --- a/src/main/kotlin/g0501_0600/s0575_distribute_candies/readme.md +++ b/src/main/kotlin/g0501_0600/s0575_distribute_candies/readme.md @@ -45,7 +45,7 @@ Given the integer array `candyType` of length `n`, return _the **maximum** numbe ## Solution ```kotlin -internal class Solution { +class Solution { fun distributeCandies(candyType: IntArray): Int { val s: MutableSet = HashSet() for (i in candyType) { diff --git a/src/main/kotlin/g0601_0700/s0684_redundant_connection/readme.md b/src/main/kotlin/g0601_0700/s0684_redundant_connection/readme.md index 5037a07c..9ece7bd4 100644 --- a/src/main/kotlin/g0601_0700/s0684_redundant_connection/readme.md +++ b/src/main/kotlin/g0601_0700/s0684_redundant_connection/readme.md @@ -42,6 +42,7 @@ Return _an edge that can be removed so that the resulting graph is a tree of_ `n ```kotlin class Solution { private lateinit var par: IntArray + fun findRedundantConnection(edges: Array): IntArray { val ans = IntArray(2) val n = edges.size diff --git a/src/main/kotlin/g0601_0700/s0690_employee_importance/readme.md b/src/main/kotlin/g0601_0700/s0690_employee_importance/readme.md index eaee504f..d41c7e3f 100644 --- a/src/main/kotlin/g0601_0700/s0690_employee_importance/readme.md +++ b/src/main/kotlin/g0601_0700/s0690_employee_importance/readme.md @@ -57,7 +57,6 @@ import com_github_leetcode.Employee * var subordinates:List = listOf() * } */ - class Solution { fun getImportance(employees: List, id: Int): Int { val map: MutableMap = HashMap() diff --git a/src/main/kotlin/g0701_0800/s0724_find_pivot_index/readme.md b/src/main/kotlin/g0701_0800/s0724_find_pivot_index/readme.md index c754c34c..af11ffd0 100644 --- a/src/main/kotlin/g0701_0800/s0724_find_pivot_index/readme.md +++ b/src/main/kotlin/g0701_0800/s0724_find_pivot_index/readme.md @@ -48,8 +48,8 @@ Return _the **leftmost pivot index**_. If no such index exists, return `-1`. ```kotlin class Solution { - fun pivotIndex(nums: IntArray?): Int { - if (nums == null || nums.isEmpty()) { + fun pivotIndex(nums: IntArray): Int { + if (nums.isEmpty()) { return -1 } val sums = IntArray(nums.size) diff --git a/src/main/kotlin/g0701_0800/s0749_contain_virus/readme.md b/src/main/kotlin/g0701_0800/s0749_contain_virus/readme.md index 8dfc7a27..277fb177 100644 --- a/src/main/kotlin/g0701_0800/s0749_contain_virus/readme.md +++ b/src/main/kotlin/g0701_0800/s0749_contain_virus/readme.md @@ -57,6 +57,7 @@ class Solution { private var m = 0 private var n = 0 private val dirs = arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(0, -1)) + fun containVirus(grid: Array): Int { m = grid.size n = grid[0].size diff --git a/src/main/kotlin/g0701_0800/s0766_toeplitz_matrix/readme.md b/src/main/kotlin/g0701_0800/s0766_toeplitz_matrix/readme.md new file mode 100644 index 00000000..1fe7b8d4 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0766_toeplitz_matrix/readme.md @@ -0,0 +1,88 @@ +[![](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) + +## 766\. Toeplitz Matrix + +Easy + +Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._ + +A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/04/ex1.jpg) + +**Input:** matrix = \[\[1,2,3,4],[5,1,2,3],[9,5,1,2]] + +**Output:** true + +**Explanation:** In the above grid, the diagonals are: "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]". In each diagonal all elements are the same, so the answer is True. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/11/04/ex2.jpg) + +**Input:** matrix = \[\[1,2],[2,2]] + +**Output:** false + +**Explanation:** The diagonal "[1, 2]" has different elements. + +**Constraints:** + +* `m == matrix.length` +* `n == matrix[i].length` +* `1 <= m, n <= 20` +* `0 <= matrix[i][j] <= 99` + +**Follow up:** + +* What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once? +* What if the `matrix` is so large that you can only load up a partial row into the memory at once? + +## Solution + +```kotlin +class Solution { + fun isToeplitzMatrix(matrix: Array): Boolean { + val m = matrix.size + val n = matrix[0].size + var i = 0 + var j = 0 + var sameVal = matrix[i][j] + while (++i < m && ++j < n) { + if (matrix[i][j] != sameVal) { + return false + } + } + i = 1 + j = 0 + while (i < m) { + var tmpI = i + var tmpJ = j + sameVal = matrix[i][j] + while (++tmpI < m && ++tmpJ < n) { + if (matrix[tmpI][tmpJ] != sameVal) { + return false + } + } + i++ + } + i = 0 + j = 1 + while (j < n) { + var tmpJ = j + var tmpI = i + sameVal = matrix[tmpI][tmpJ] + while (++tmpI < m && ++tmpJ < n) { + if (matrix[tmpI][tmpJ] != sameVal) { + return false + } + } + j++ + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0767_reorganize_string/readme.md b/src/main/kotlin/g0701_0800/s0767_reorganize_string/readme.md new file mode 100644 index 00000000..c82a6291 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0767_reorganize_string/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) + +## 767\. Reorganize String + +Medium + +Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. + +Return _any possible rearrangement of_ `s` _or return_ `""` _if not possible_. + +**Example 1:** + +**Input:** s = "aab" + +**Output:** "aba" + +**Example 2:** + +**Input:** s = "aaab" + +**Output:** "" + +**Constraints:** + +* `1 <= s.length <= 500` +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun reorganizeString(s: String): String { + val hash = IntArray(26) + for (element in s) { + hash[element.code - 'a'.code]++ + } + var max = 0 + var letter = 0 + for (i in hash.indices) { + if (hash[i] > max) { + max = hash[i] + letter = i + } + } + if (max > (s.length + 1) / 2) { + return "" + } + val res = CharArray(s.length) + var idx = 0 + while (hash[letter] > 0) { + res[idx] = (letter + 'a'.code).toChar() + idx += 2 + hash[letter]-- + } + for (i in hash.indices) { + while (hash[i] > 0) { + if (idx >= res.size) { + idx = 1 + } + res[idx] = (i + 'a'.code).toChar() + idx += 2 + hash[i]-- + } + } + return String(res) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0768_max_chunks_to_make_sorted_ii/readme.md b/src/main/kotlin/g0701_0800/s0768_max_chunks_to_make_sorted_ii/readme.md new file mode 100644 index 00000000..1161a98b --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0768_max_chunks_to_make_sorted_ii/readme.md @@ -0,0 +1,60 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 768\. Max Chunks To Make Sorted II + +Hard + +You are given an integer array `arr`. + +We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. + +Return _the largest number of chunks we can make to sort the array_. + +**Example 1:** + +**Input:** arr = [5,4,3,2,1] + +**Output:** 1 + +**Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted. + +**Example 2:** + +**Input:** arr = [2,1,3,4,4] + +**Output:** 4 + +**Explanation:** We can split into two chunks, such as [2, 1], [3, 4, 4]. However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible. + +**Constraints:** + +* `1 <= arr.length <= 2000` +* 0 <= arr[i] <= 108 + +## Solution + +```kotlin +class Solution { + fun maxChunksToSorted(arr: IntArray): Int { + val n = arr.size + val lmax = IntArray(n) + val rMin = IntArray(n + 1) + lmax[0] = arr[0] + for (i in 1 until n) { + lmax[i] = lmax[i - 1].coerceAtLeast(arr[i]) + } + rMin[n] = Int.MAX_VALUE + for (i in n - 1 downTo 0) { + rMin[i] = rMin[i + 1].coerceAtMost(arr[i]) + } + var chunks = 0 + for (i in 0 until n) { + if (lmax[i] <= rMin[i + 1]) { + chunks++ + } + } + return chunks + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0769_max_chunks_to_make_sorted/readme.md b/src/main/kotlin/g0701_0800/s0769_max_chunks_to_make_sorted/readme.md new file mode 100644 index 00000000..da8408c8 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0769_max_chunks_to_make_sorted/readme.md @@ -0,0 +1,53 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 769\. Max Chunks To Make Sorted + +Medium + +You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. + +We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. + +Return _the largest number of chunks we can make to sort the array_. + +**Example 1:** + +**Input:** arr = [4,3,2,1,0] + +**Output:** 1 + +**Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted. + +**Example 2:** + +**Input:** arr = [1,0,2,3,4] + +**Output:** 4 + +**Explanation:** We can split into two chunks, such as [1, 0], [2, 3, 4]. However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible. + +**Constraints:** + +* `n == arr.length` +* `1 <= n <= 10` +* `0 <= arr[i] < n` +* All the elements of `arr` are **unique**. + +## Solution + +```kotlin +class Solution { + fun maxChunksToSorted(arr: IntArray): Int { + var ans = 0 + var max = 0 + for (i in arr.indices) { + max = max.coerceAtLeast(arr[i]) + if (max == i) { + ans++ + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0770_basic_calculator_iv/readme.md b/src/main/kotlin/g0701_0800/s0770_basic_calculator_iv/readme.md new file mode 100644 index 00000000..ea8e4795 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0770_basic_calculator_iv/readme.md @@ -0,0 +1,241 @@ +[![](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) + +## 770\. Basic Calculator IV + +Hard + +Given an expression such as `expression = "e + 8 - a + 5"` and an evaluation map such as `{"e": 1}` (given in terms of `evalvars = ["e"]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `["-1*a","14"]` + +* An expression alternates chunks and symbols, with a space separating each chunk and symbol. +* A chunk is either an expression in parentheses, a variable, or a non-negative integer. +* A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like `"2x"` or `"-x"`. + +Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. + +* For example, `expression = "1 + 2 * 3"` has an answer of `["7"]`. + +The format of the output is as follows: + +* For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically. + * For example, we would never write a term like `"b*a*c"`, only `"a*b*c"`. +* Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term. + * For example, `"a*a*b*c"` has degree `4`. +* The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed. +* An example of a well-formatted answer is `["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"]`. +* Terms (including constant terms) with coefficient `0` are not included. + * For example, an expression of `"0"` has an output of `[]`. + +**Note:** You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]. + +**Example 1:** + +**Input:** expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1] + +**Output:** ["-1\*a","14"] + +**Example 2:** + +**Input:** expression = "e - 8 + temperature - pressure", evalvars = ["e", "temperature"], evalints = [1, 12] + +**Output:** ["-1\*pressure","5"] + +**Example 3:** + +**Input:** expression = "(e + 8) \* (e - 8)", evalvars = [], evalints = [] + +**Output:** ["1\*e\*e","-64"] + +**Constraints:** + +* `1 <= expression.length <= 250` +* `expression` consists of lowercase English letters, digits, `'+'`, `'-'`, `'*'`, `'('`, `')'`, `' '`. +* `expression` does not contain any leading or trailing spaces. +* All the tokens in `expression` are separated by a single space. +* `0 <= evalvars.length <= 100` +* `1 <= evalvars[i].length <= 20` +* `evalvars[i]` consists of lowercase English letters. +* `evalints.length == evalvars.length` +* `-100 <= evalints[i] <= 100` + +## Solution + +```kotlin +import java.util.Collections +import java.util.Stack + +internal class Solution { + internal inner class Node { + var mem: MutableMap, Int> = HashMap() + fun update(cur: List, cnt: Int) { + Collections.sort(cur) + mem[cur] = mem.getOrDefault(cur, 0) + cnt + } + + fun add(cur: Node): Node { + val ans = Node() + for (key1 in mem.keys) { + ans.update(key1, mem[key1]!!) + } + for (key2 in cur.mem.keys) { + ans.update(key2, cur.mem[key2]!!) + } + return ans + } + + fun sub(cur: Node): Node { + val ans = Node() + for (key1 in mem.keys) { + ans.update(key1, mem[key1]!!) + } + for (key2 in cur.mem.keys) { + ans.update(key2, -cur.mem[key2]!!) + } + return ans + } + + fun mul(cur: Node): Node { + val ans = Node() + for (key1 in mem.keys) { + for (key2 in cur.mem.keys) { + val next: MutableList = ArrayList() + next.addAll(key1) + next.addAll(key2) + ans.update(next, mem[key1]!! * cur.mem[key2]!!) + } + } + return ans + } + + fun evaluate(vars: Map): Node { + val ans = Node() + for (cur in mem.keys) { + var cnt = mem[cur]!! + val free: MutableList = ArrayList() + for (tmp in cur) { + if (vars.containsKey(tmp)) { + cnt *= vars[tmp]!! + } else { + free.add(tmp) + } + } + ans.update(free, cnt) + } + return ans + } + + fun toList(): List { + val ans: MutableList = ArrayList() + val keys: List> = ArrayList(mem.keys) + Collections.sort( + keys + ) { a: List, b: List -> + if (a.size != b.size) { + return@sort b.size - a.size + } + for (i in a.indices) { + if (a[i].compareTo(b[i]) != 0) { + return@sort a[i].compareTo(b[i]) + } + } + 0 + } + for (key in keys) { + if (mem[key] == 0) { + continue + } + var cur = "" + mem[key].toString() + for (data in key) { + cur += "*" + cur += data + } + ans.add(cur) + } + return ans + } + } + + private fun make(cur: String): Node { + val ans: Node = Node() + val tmp: MutableList = ArrayList() + if (Character.isDigit(cur[0])) { + ans.update(tmp, Integer.valueOf(cur)) + } else { + tmp.add(cur) + ans.update(tmp, 1) + } + return ans + } + + private fun getNext(expression: String, start: Int): Int { + var end = start + while (end < expression.length && Character.isLetterOrDigit(expression[end])) { + end++ + } + return end - 1 + } + + private fun getPriority(a: Char): Int { + if (a == '+' || a == '-') { + return 1 + } else if (a == '*') { + return 2 + } + return 0 + } + + private fun helper(numS: Stack, ops: Stack): Node { + val b = numS.pop() + val a = numS.pop() + val op = ops.pop() + if (op == '*') { + return a.mul(b) + } else if (op == '+') { + return a.add(b) + } + return a.sub(b) + } + + fun basicCalculatorIV(expression: String?, evalvarS: Array?, evalintS: IntArray?): List { + val ans: List = ArrayList() + if (expression.isNullOrEmpty() || evalvarS == null || evalintS == null) { + return ans + } + val vars: MutableMap = HashMap() + for (i in evalvarS.indices) { + vars[evalvarS[i]] = evalintS[i] + } + val n = expression.length + val numS = Stack() + val ops = Stack() + var i = 0 + while (i < n) { + val a = expression[i] + if (Character.isLetterOrDigit(a)) { + val end = getNext(expression, i) + val cur = expression.substring(i, end + 1) + i = end + val now = make(cur) + numS.add(now) + } else if (a == '(') { + ops.add(a) + } else if (a == ')') { + while (ops.peek() != '(') { + numS.add(helper(numS, ops)) + } + ops.pop() + } else if (a == '+' || a == '-' || a == '*') { + while (ops.size > 0 && getPriority(ops.peek()) >= getPriority(a)) { + numS.add(helper(numS, ops)) + } + ops.add(a) + } + i++ + } + while (ops.size > 0) { + numS.add(helper(numS, ops)) + } + return numS.peek().evaluate(vars).toList() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0771_jewels_and_stones/readme.md b/src/main/kotlin/g0701_0800/s0771_jewels_and_stones/readme.md new file mode 100644 index 00000000..220f8130 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0771_jewels_and_stones/readme.md @@ -0,0 +1,50 @@ +[![](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) + +## 771\. Jewels and Stones + +Easy + +You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. + +Letters are case sensitive, so `"a"` is considered a different type of stone from `"A"`. + +**Example 1:** + +**Input:** jewels = "aA", stones = "aAAbbbb" + +**Output:** 3 + +**Example 2:** + +**Input:** jewels = "z", stones = "ZZ" + +**Output:** 0 + +**Constraints:** + +* `1 <= jewels.length, stones.length <= 50` +* `jewels` and `stones` consist of only English letters. +* All the characters of `jewels` are **unique**. + +## Solution + +```kotlin +class Solution { + fun numJewelsInStones(jewels: String, stones: String): Int { + val x = IntArray(60) + var count = 0 + val len = jewels.length + val len2 = stones.length + for (i in 0 until len) { + x[jewels[i].code - 65]++ + } + for (i in 0 until len2) { + if (x[stones[i].code - 65] == 1) { + count++ + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0773_sliding_puzzle/readme.md b/src/main/kotlin/g0701_0800/s0773_sliding_puzzle/readme.md new file mode 100644 index 00000000..4451f715 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0773_sliding_puzzle/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) + +## 773\. Sliding Puzzle + +Hard + +On an `2 x 3` board, there are five tiles labeled from `1` to `5`, and an empty square represented by `0`. A **move** consists of choosing `0` and a 4-directionally adjacent number and swapping it. + +The state of the board is solved if and only if the board is `[[1,2,3],[4,5,0]]`. + +Given the puzzle board `board`, return _the least number of moves required so that the state of the board is solved_. If it is impossible for the state of the board to be solved, return `-1`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/06/29/slide1-grid.jpg) + +**Input:** board = \[\[1,2,3],[4,0,5]] + +**Output:** 1 + +**Explanation:** Swap the 0 and the 5 in one move. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/06/29/slide2-grid.jpg) + +**Input:** board = \[\[1,2,3],[5,4,0]] + +**Output:** -1 + +**Explanation:** No number of moves will make the board solved. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/06/29/slide3-grid.jpg) + +**Input:** board = \[\[4,1,2],[5,0,3]] + +**Output:** 5 + +**Explanation:** 5 is the smallest number of moves that solves the board. An example path: After move 0: [[4,1,2],[5,0,3]] After move 1: [[4,1,2],[0,5,3]] After move 2: [[0,1,2],[4,5,3]] After move 3: [[1,0,2],[4,5,3]] After move 4: [[1,2,0],[4,5,3]] After move 5: [[1,2,3],[4,5,0]] + +**Constraints:** + +* `board.length == 2` +* `board[i].length == 3` +* `0 <= board[i][j] <= 5` +* Each value `board[i][j]` is **unique**. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + private class Node(var board: String, var depth: Int, var y: Int, var x: Int) + fun slidingPuzzle(board: Array): Int { + val targetStr = "123450" + val sb = StringBuilder() + var y = 0 + var x = 0 + for (i in board.indices) { + for (j in board[0].indices) { + if (board[i][j] == 0) { + y = i + x = j + } + sb.append(board[i][j]) + } + } + val seen: MutableSet = HashSet() + val q: Queue = LinkedList() + q.add(Node(sb.toString(), 0, y, x)) + val dir = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1)) + while (!q.isEmpty()) { + val next = q.poll() + val s = next.board + if (!seen.contains(s)) { + if (s == targetStr) { + return next.depth + } + val nextDepth = next.depth + 1 + y = next.y + x = next.x + for (vector in dir) { + val nextY = y + vector[0] + val nextX = x + vector[1] + if (0 <= nextY && nextY < board.size && 0 <= nextX && nextX < board[0].size) { + val newBoard = swap(s, y, x, nextY, nextX) + q.add(Node(newBoard, nextDepth, nextY, nextX)) + } + } + seen.add(s) + } + } + return -1 + } + + private fun swap(board: String, y1: Int, x1: Int, y2: Int, x2: Int): String { + val arr = board.toCharArray() + val t = board[y1 * 3 + x1] + arr[y1 * 3 + x1] = board[y2 * 3 + x2] + arr[y2 * 3 + x2] = t + return String(arr) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0775_global_and_local_inversions/readme.md b/src/main/kotlin/g0701_0800/s0775_global_and_local_inversions/readme.md new file mode 100644 index 00000000..c041d091 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0775_global_and_local_inversions/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) + +## 775\. Global and Local Inversions + +Medium + +You are given an integer array `nums` of length `n` which represents a permutation of all the integers in the range `[0, n - 1]`. + +The number of **global inversions** is the number of the different pairs `(i, j)` where: + +* `0 <= i < j < n` +* `nums[i] > nums[j]` + +The number of **local inversions** is the number of indices `i` where: + +* `0 <= i < n - 1` +* `nums[i] > nums[i + 1]` + +Return `true` _if the number of **global inversions** is equal to the number of **local inversions**_. + +**Example 1:** + +**Input:** nums = [1,0,2] + +**Output:** true + +**Explanation:** There is 1 global inversion and 1 local inversion. + +**Example 2:** + +**Input:** nums = [1,2,0] + +**Output:** false + +**Explanation:** There are 2 global inversions and 1 local inversion. + +**Constraints:** + +* `n == nums.length` +* 1 <= n <= 105 +* `0 <= nums[i] < n` +* All the integers of `nums` are **unique**. +* `nums` is a permutation of all the numbers in the range `[0, n - 1]`. + +## Solution + +```kotlin +class Solution { + /* + * from the above solution, we can tell that if we can find the minimum of A[j] where j >= i + 2, + * then we could quickly return false, so two steps: + * 1. remembering minimum + * 2. scanning from right to left + *

+ * Time: O(n) + */ + fun isIdealPermutation(nums: IntArray): Boolean { + var min = nums.size + for (i in nums.size - 1 downTo 2) { + min = min.coerceAtMost(nums[i]) + if (nums[i - 2] > min) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0777_swap_adjacent_in_lr_string/readme.md b/src/main/kotlin/g0701_0800/s0777_swap_adjacent_in_lr_string/readme.md new file mode 100644 index 00000000..1dedfdb8 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0777_swap_adjacent_in_lr_string/readme.md @@ -0,0 +1,85 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 777\. Swap Adjacent in LR String + +Medium + +In a string composed of `'L'`, `'R'`, and `'X'` characters, like `"RXXLRXRXL"`, a move consists of either replacing one occurrence of `"XL"` with `"LX"`, or replacing one occurrence of `"RX"` with `"XR"`. Given the starting string `start` and the ending string `end`, return `True` if and only if there exists a sequence of moves to transform one string to the other. + +**Example 1:** + +**Input:** start = "RXXLRXRXL", end = "XRLXXRRLX" + +**Output:** true + +**Explanation:** We can transform start to end following these steps: + +RXXLRXRXL -> + +XRXLRXRXL -> + +XRLXRXRXL -> + +XRLXXRRXL -> + +XRLXXRRLX + +**Example 2:** + +**Input:** start = "X", end = "L" + +**Output:** false + +**Constraints:** + +* 1 <= start.length <= 104 +* `start.length == end.length` +* Both `start` and `end` will only consist of characters in `'L'`, `'R'`, and `'X'`. + +## Solution + +```kotlin +class Solution { + fun canTransform(start: String, end: String): Boolean { + var i1 = 0 + var i2 = 0 + val s1 = start.toCharArray() + val s2 = end.toCharArray() + while (i1 < s1.size && i2 < s2.size) { + while (i1 < s1.size && s1[i1] == 'X') { + i1++ + } + while (i2 < s2.size && s2[i2] == 'X') { + i2++ + } + if (i1 == s1.size && i2 == s2.size) { + return true + } + if (i1 == s1.size || i2 == s2.size) { + return false + } + val c1 = s1[i1] + val c2 = s2[i2] + if (c1 != c2) { + return false + } + if (c1 == 'L' && i1 < i2) { + return false + } + if (c1 == 'R' && i1 > i2) { + return false + } + i1++ + i2++ + } + while (i1 < s1.size && start[i1] == 'X') { + i1++ + } + while (i2 < s2.size && end[i2] == 'X') { + i2++ + } + return i1 == s1.size && i2 == s2.size + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0778_swim_in_rising_water/readme.md b/src/main/kotlin/g0701_0800/s0778_swim_in_rising_water/readme.md new file mode 100644 index 00000000..f147784e --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0778_swim_in_rising_water/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) + +## 778\. Swim in Rising Water + +Hard + +You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`. + +The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most `t`. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim. + +Return _the least time until you can reach the bottom right square_ `(n - 1, n - 1)` _if you start at the top left square_ `(0, 0)`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/06/29/swim1-grid.jpg) + +**Input:** grid = \[\[0,2],[1,3]] + +**Output:** 3 Explanation: + +At time 0, you are in grid location (0, 0). + +You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. + +You cannot reach point (1, 1) until time 3. + +When the depth of water is 3, we can swim anywhere inside the grid. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/06/29/swim2-grid-1.jpg) + +**Input:** grid = \[\[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]] + +**Output:** 16 + +**Explanation:** The final route is shown. We need to wait until time 16 so that (0, 0) and (4, 4) are connected. + +**Constraints:** + +* `n == grid.length` +* `n == grid[i].length` +* `1 <= n <= 50` +* 0 <= grid[i][j] < n2 +* Each value `grid[i][j]` is **unique**. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + private val dir = intArrayOf(-1, 0, 1, 0, -1) + + fun swimInWater(grid: Array): Int { + var max = 0 + // find the maximum value in the matrix + for (ints in grid) { + for (j in grid[0].indices) { + max = max.coerceAtLeast(ints[j]) + } + } + var l = 0 + var r = max + var res = 0 + // perform binary search + while (l <= r) { + // find test water level + val mid = (l + r) / 2 + // if you can reach destination with current water level, store it as an answer and try + // lowering water level + if (bfs(grid, mid)) { + res = mid + r = mid - 1 + } else { + // otherwise increase water level and try again + l = mid + 1 + } + } + return res + } + + private fun bfs(grid: Array, limit: Int): Boolean { + // use queue to process cells starting from top left corner + val que: Queue = LinkedList() + // boolean array to keep track of visited cells + val visited = Array(grid.size) { + BooleanArray( + grid[0].size + ) + } + // we start from top left corner + que.add(intArrayOf(0, 0)) + visited[0][0] = true + while (!que.isEmpty()) { + // get current cell + val cur = que.poll() + val x = cur[0] + val y = cur[1] + // if value of current cell is greater than limit return false + if (grid[x][y] > limit) { + return false + } + // if we reached the destination return true + if (x == grid.size - 1 && y == grid[0].size - 1) { + return true + } + // check cells in all 4 directions + for (i in 0 until dir.size - 1) { + val dx = x + dir[i] + val dy = y + dir[i + 1] + // if neighboring cell is in bounds, and hasn't been visited yet, + // and its value is less than current water level, add it to visited array and to + // the queue + if (dx >= 0 && dy >= 0 && dx < grid.size && dy < grid[0].size && + !visited[dx][dy] && grid[dx][dy] <= limit + ) { + visited[dx][dy] = true + que.add(intArrayOf(dx, dy)) + } + } + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0779_k_th_symbol_in_grammar/readme.md b/src/main/kotlin/g0701_0800/s0779_k_th_symbol_in_grammar/readme.md new file mode 100644 index 00000000..a58f6a36 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0779_k_th_symbol_in_grammar/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) + +## 779\. K-th Symbol in Grammar + +Medium + +We build a table of `n` rows (**1-indexed**). We start by writing `0` in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`. + +* For example, for `n = 3`, the 1st row is `0`, the 2nd row is `01`, and the 3rd row is `0110`. + +Given two integer `n` and `k`, return the kth (**1-indexed**) symbol in the nth row of a table of `n` rows. + +**Example 1:** + +**Input:** n = 1, k = 1 + +**Output:** 0 + +**Explanation:** row 1: 0 + +**Example 2:** + +**Input:** n = 2, k = 1 + +**Output:** 0 + +**Explanation:** row 1: 0 row 2: 01 + +**Example 3:** + +**Input:** n = 2, k = 2 + +**Output:** 1 + +**Explanation:** row 1: 0 row 2: 01 + +**Constraints:** + +* `1 <= n <= 30` +* 1 <= k <= 2n - 1 + +## Solution + +```kotlin +class Solution { + /* + * Time: O(logn) + * Space: O(1) + */ + fun kthGrammar(n: Int, k: Int): Int { + return Integer.bitCount(k - 1) % 2 + n - n + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0780_reaching_points/readme.md b/src/main/kotlin/g0701_0800/s0780_reaching_points/readme.md new file mode 100644 index 00000000..5f3e2c7e --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0780_reaching_points/readme.md @@ -0,0 +1,70 @@ +[![](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) + +## 780\. Reaching Points + +Hard + +Given four integers `sx`, `sy`, `tx`, and `ty`, return `true` _if it is possible to convert the point_ `(sx, sy)` _to the point_ `(tx, ty)` _through some operations__, or_ `false` _otherwise_. + +The allowed operation on some point `(x, y)` is to convert it to either `(x, x + y)` or `(x + y, y)`. + +**Example 1:** + +**Input:** sx = 1, sy = 1, tx = 3, ty = 5 + +**Output:** true + +**Explanation:** One series of moves that transforms the starting point to the target is: + +(1, 1) -> (1, 2) + +(1, 2) -> (3, 2) + +(3, 2) -> (3, 5) + +**Example 2:** + +**Input:** sx = 1, sy = 1, tx = 2, ty = 2 + +**Output:** false + +**Example 3:** + +**Input:** sx = 1, sy = 1, tx = 1, ty = 1 + +**Output:** true + +**Constraints:** + +* 1 <= sx, sy, tx, ty <= 109 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun reachingPoints(sx: Int, sy: Int, tx: Int, ty: Int): Boolean { + var tx = tx + var ty = ty + while (tx >= sx && ty >= sy) { + if (tx > ty) { + tx %= if (ty == sy) { + // ty==sy + return (tx - sx) % sy == 0 + } else { + // ty > sy + ty + } + } else if (sx == tx) { + // ty >= tx + return (ty - sy) % sx == 0 + } else { + // (tx > sx) + ty %= tx + } + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0781_rabbits_in_forest/readme.md b/src/main/kotlin/g0701_0800/s0781_rabbits_in_forest/readme.md new file mode 100644 index 00000000..440fe843 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0781_rabbits_in_forest/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) + +## 781\. Rabbits in Forest + +Medium + +There is a forest with an unknown number of rabbits. We asked n rabbits **"How many rabbits have the same color as you?"** and collected the answers in an integer array `answers` where `answers[i]` is the answer of the ith rabbit. + +Given the array `answers`, return _the minimum number of rabbits that could be in the forest_. + +**Example 1:** + +**Input:** answers = [1,1,2] + +**Output:** 5 + +**Explanation:** + +The two rabbits that answered "1" could both be the same color, say red. + +The rabbit that answered "2" can't be red or the answers would be inconsistent. + +Say the rabbit that answered "2" was blue. + +Then there should be 2 other blue rabbits in the forest that didn't answer into the array. + +The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't. + +**Example 2:** + +**Input:** answers = [10,10,10] + +**Output:** 11 + +**Constraints:** + +* `1 <= answers.length <= 1000` +* `0 <= answers[i] < 1000` + +## Solution + +```kotlin +class Solution { + fun numRabbits(answers: IntArray): Int { + val counts = IntArray(1001) + for (element in answers) { + counts[element]++ + } + var answer = counts[0] + for (i in 1..1000) { + if (counts[i] > 0) { + val rabbitsInPartialGroup = counts[i] % (i + 1) + val rabbitsInCompleteGroups = counts[i] - rabbitsInPartialGroup + answer += rabbitsInCompleteGroups + if (rabbitsInPartialGroup > 0) { + answer += i + 1 + } + } + } + return answer + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0782_transform_to_chessboard/readme.md b/src/main/kotlin/g0701_0800/s0782_transform_to_chessboard/readme.md new file mode 100644 index 00000000..6a6beecb --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0782_transform_to_chessboard/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) + +## 782\. Transform to Chessboard + +Hard + +You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other. + +Return _the minimum number of moves to transform the board into a **chessboard board**_. If the task is impossible, return `-1`. + +A **chessboard board** is a board where no `0`'s and no `1`'s are 4-directionally adjacent. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/06/29/chessboard1-grid.jpg) + +**Input:** board = \[\[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]] + +**Output:** 2 + +**Explanation:** One potential sequence of moves is shown. + +The first move swaps the first and second column. + +The second move swaps the second and third row. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/06/29/chessboard2-grid.jpg) + +**Input:** board = \[\[0,1],[1,0]] + +**Output:** 0 + +**Explanation:** Also note that the board with 0 in the top left corner, is also a valid chessboard. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/06/29/chessboard3-grid.jpg) + +**Input:** board = \[\[1,0],[1,0]] + +**Output:** -1 + +**Explanation:** No matter what sequence of moves you make, you cannot end with a valid chessboard. + +**Constraints:** + +* `n == board.length` +* `n == board[i].length` +* `2 <= n <= 30` +* `board[i][j]` is either `0` or `1`. + +## Solution + +```kotlin +class Solution { + fun movesToChessboard(board: Array): Int { + val n = board.size + var colToMove = 0 + var rowToMove = 0 + var rowOneCnt = 0 + var colOneCnt = 0 + for (ints in board) { + for (j in 0 until n) { + if (board[0][0] xor ints[0] xor (ints[j] xor board[0][j]) == 1) { + return -1 + } + } + } + for (i in 0 until n) { + rowOneCnt += board[0][i] + colOneCnt += board[i][0] + if (board[i][0] == i % 2) { + rowToMove++ + } + if (board[0][i] == i % 2) { + colToMove++ + } + } + if (rowOneCnt < n / 2 || rowOneCnt > (n + 1) / 2) { + return -1 + } + if (colOneCnt < n / 2 || colOneCnt > (n + 1) / 2) { + return -1 + } + if (n % 2 == 1) { + // we cannot make it when ..ToMove is odd + if (colToMove % 2 == 1) { + colToMove = n - colToMove + } + if (rowToMove % 2 == 1) { + rowToMove = n - rowToMove + } + } else { + colToMove = colToMove.coerceAtMost(n - colToMove) + rowToMove = rowToMove.coerceAtMost(n - rowToMove) + } + return (colToMove + rowToMove) / 2 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0783_minimum_distance_between_bst_nodes/readme.md b/src/main/kotlin/g0701_0800/s0783_minimum_distance_between_bst_nodes/readme.md new file mode 100644 index 00000000..3e060de0 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0783_minimum_distance_between_bst_nodes/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) + +## 783\. Minimum Distance Between BST Nodes + +Easy + +Given the `root` of a Binary Search Tree (BST), return _the minimum difference between the values of any two different nodes in the tree_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/05/bst1.jpg) + +**Input:** root = [4,2,6,1,3] + +**Output:** 1 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/02/05/bst2.jpg) + +**Input:** root = [1,0,48,null,null,12,49] + +**Output:** 1 + +**Constraints:** + +* The number of nodes in the tree is in the range `[2, 100]`. +* 0 <= Node.val <= 105 + +**Note:** This question is the same as 530: [https://leetcode.com/problems/minimum-absolute-difference-in-bst/](https://leetcode.com/problems/minimum-absolute-difference-in-bst/) + +## Solution + +```kotlin +import com_github_leetcode.TreeNode +import kotlin.math.abs + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private var prev = -1 + private var min = Int.MAX_VALUE + fun minDiffInBST(root: TreeNode?): Int { + if (root == null) { + return min + } + minDiffInBST(root.left) + if (prev != -1) { + min = min.coerceAtMost(abs(root.`val` - prev)) + } + prev = root.`val` + minDiffInBST(root.right) + return min + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0784_letter_case_permutation/readme.md b/src/main/kotlin/g0701_0800/s0784_letter_case_permutation/readme.md new file mode 100644 index 00000000..9a860ae8 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0784_letter_case_permutation/readme.md @@ -0,0 +1,60 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 784\. Letter Case Permutation + +Medium + +Given a string `s`, you can transform every letter individually to be lowercase or uppercase to create another string. + +Return _a list of all possible strings we could create_. Return the output in **any order**. + +**Example 1:** + +**Input:** s = "a1b2" + +**Output:** ["a1b2","a1B2","A1b2","A1B2"] + +**Example 2:** + +**Input:** s = "3z4" + +**Output:** ["3z4","3Z4"] + +**Constraints:** + +* `1 <= s.length <= 12` +* `s` consists of lowercase English letters, uppercase English letters, and digits. + +## Solution + +```kotlin +import java.util.Locale + +class Solution { + private val ans: MutableList = ArrayList() + + fun letterCasePermutation(s: String): List { + helper(s, 0, "") + return ans + } + + private fun helper(s: String, curr: Int, temp: String) { + if (curr == s.length) { + ans.add(temp) + return + } + if (Character.isDigit(s[curr])) { + helper(s, curr + 1, temp + s[curr]) + } else { + if (Character.isLowerCase(s[curr])) { + helper(s, curr + 1, temp + s[curr]) + helper(s, curr + 1, temp + s.substring(curr, curr + 1).uppercase(Locale.getDefault())) + } else { + helper(s, curr + 1, temp + s[curr]) + helper(s, curr + 1, temp + s.substring(curr, curr + 1).lowercase(Locale.getDefault())) + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0785_is_graph_bipartite/readme.md b/src/main/kotlin/g0701_0800/s0785_is_graph_bipartite/readme.md new file mode 100644 index 00000000..77bab15d --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0785_is_graph_bipartite/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) + +## 785\. Is Graph Bipartite? + +Medium + +There is an **undirected** graph with `n` nodes, where each node is numbered between `0` and `n - 1`. You are given a 2D array `graph`, where `graph[u]` is an array of nodes that node `u` is adjacent to. More formally, for each `v` in `graph[u]`, there is an undirected edge between node `u` and node `v`. The graph has the following properties: + +* There are no self-edges (`graph[u]` does not contain `u`). +* There are no parallel edges (`graph[u]` does not contain duplicate values). +* If `v` is in `graph[u]`, then `u` is in `graph[v]` (the graph is undirected). +* The graph may not be connected, meaning there may be two nodes `u` and `v` such that there is no path between them. + +A graph is **bipartite** if the nodes can be partitioned into two independent sets `A` and `B` such that **every** edge in the graph connects a node in set `A` and a node in set `B`. + +Return `true` _if and only if it is **bipartite**_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/21/bi2.jpg) + +**Input:** graph = \[\[1,2,3],[0,2],[0,1,3],[0,2]] + +**Output:** false + +**Explanation:** There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/10/21/bi1.jpg) + +**Input:** graph = \[\[1,3],[0,2],[1,3],[0,2]] + +**Output:** true + +**Explanation:** We can partition the nodes into two sets: {0, 2} and {1, 3}. + +**Constraints:** + +* `graph.length == n` +* `1 <= n <= 100` +* `0 <= graph[u].length < n` +* `0 <= graph[u][i] <= n - 1` +* `graph[u]` does not contain `u`. +* All the values of `graph[u]` are **unique**. +* If `graph[u]` contains `v`, then `graph[v]` contains `u`. + +## Solution + +```kotlin +class Solution { + fun isBipartite(graph: Array): Boolean { + val n = graph.size + val color = IntArray(n) + for (i in 0 until n) { + if (color[i] == 0 && !helper(graph, i, -1, color)) { + return false + } + } + return true + } + + private fun helper(graph: Array, curr: Int, c: Int, color: IntArray): Boolean { + if (color[curr] == c) { + return true + } + color[curr] = c + for (x in graph[curr]) { + if (color[x] == c || !helper(graph, x, c * -1, color)) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0786_k_th_smallest_prime_fraction/readme.md b/src/main/kotlin/g0701_0800/s0786_k_th_smallest_prime_fraction/readme.md new file mode 100644 index 00000000..0ebccc9b --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0786_k_th_smallest_prime_fraction/readme.md @@ -0,0 +1,90 @@ +[![](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) + +## 786\. K-th Smallest Prime Fraction + +Medium + +You are given a sorted integer array `arr` containing `1` and **prime** numbers, where all the integers of `arr` are unique. You are also given an integer `k`. + +For every `i` and `j` where `0 <= i < j < arr.length`, we consider the fraction `arr[i] / arr[j]`. + +Return _the_ kth _smallest fraction considered_. Return your answer as an array of integers of size `2`, where `answer[0] == arr[i]` and `answer[1] == arr[j]`. + +**Example 1:** + +**Input:** arr = [1,2,3,5], k = 3 + +**Output:** [2,5] + +**Explanation:** The fractions to be considered in sorted order are: 1/5, 1/3, 2/5, 1/2, 3/5, and 2/3. The third fraction is 2/5. + +**Example 2:** + +**Input:** arr = [1,7], k = 1 + +**Output:** [1,7] + +**Constraints:** + +* `2 <= arr.length <= 1000` +* 1 <= arr[i] <= 3 * 104 +* `arr[0] == 1` +* `arr[i]` is a **prime** number for `i > 0`. +* All the numbers of `arr` are **unique** and sorted in **strictly increasing** order. +* `1 <= k <= arr.length * (arr.length - 1) / 2` + +**Follow up:** Can you solve the problem with better than O(n2) complexity? + +## Solution + +```kotlin +class Solution { + fun kthSmallestPrimeFraction(arr: IntArray, k: Int): IntArray { + val n = arr.size + var low = 0.0 + var high = 1.0 + while (low < high) { + val mid = (low + high) / 2 + val res = getFractionsLessThanMid(arr, n, mid) + if (res[0] == k) { + return intArrayOf(arr[res[1]], arr[res[2]]) + } else if (res[0] > k) { + high = mid + } else { + low = mid + } + } + return intArrayOf() + } + + private fun getFractionsLessThanMid(arr: IntArray, n: Int, mid: Double): IntArray { + var maxLessThanMid = 0.0 + // stores indices of max fraction less than mid; + var x = 0 + var y = 0 + // for storing fractions less than mid + var total = 0 + var j = 1 + for (i in 0 until n - 1) { + // while fraction is greater than mid increment j + while (j < n && arr[i] > arr[j] * mid) { + j++ + } + if (j == n) { + break + } + // j fractions greater than mid, n-j fractions smaller than mid, add fractions smaller + // than mid to total + total += n - j + val fraction = arr[i].toDouble() / arr[j] + if (fraction > maxLessThanMid) { + maxLessThanMid = fraction + x = i + y = j + } + } + return intArrayOf(total, x, y) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0787_cheapest_flights_within_k_stops/readme.md b/src/main/kotlin/g0701_0800/s0787_cheapest_flights_within_k_stops/readme.md new file mode 100644 index 00000000..249d831c --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0787_cheapest_flights_within_k_stops/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) + +## 787\. Cheapest Flights Within K Stops + +Medium + +There are `n` cities connected by some number of flights. You are given an array `flights` where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei. + +You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-3drawio.png) + +**Input:** n = 4, flights = \[\[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 + +**Output:** 700 + +**Explanation:** + +The graph is shown above. + +The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. + +Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-1drawio.png) + +**Input:** n = 3, flights = \[\[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 + +**Output:** 200 + +**Explanation:** + +The graph is shown above. + +The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-2drawio.png) + +**Input:** n = 3, flights = \[\[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0 + +**Output:** 500 + +**Explanation:** + +The graph is shown above. + +The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. + +**Constraints:** + +* `1 <= n <= 100` +* `0 <= flights.length <= (n * (n - 1) / 2)` +* `flights[i].length == 3` +* 0 <= fromi, toi < n +* fromi != toi +* 1 <= pricei <= 104 +* There will not be any multiple flights between two cities. +* `0 <= src, dst, k < n` +* `src != dst` + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun findCheapestPrice(n: Int, flights: Array, src: Int, dst: Int, k: Int): Int { + // k + 2 becase there are total of k(intermediate stops) + 1(src) + 1(dst) + // dp[i][j] = cost to reach j using atmost i edges from src + val dp = Array(k + 2) { IntArray(n) } + for (row in dp) { + Arrays.fill(row, Int.MAX_VALUE) + } + // cost to reach src is always 0 + for (i in 0..k + 1) { + dp[i][src] = 0 + } + // k+1 because k stops + dst + for (i in 1..k + 1) { + for (flight in flights) { + val srcAirport = flight[0] + val destAirport = flight[1] + val cost = flight[2] + // if cost to reach srcAirport in i - 1 steps is already found out then + // the cost to reach destAirport will be min(cost to reach destAirport computed + // already from some other srcAirport OR cost to reach srcAirport in i - 1 steps + + // the cost to reach destAirport from srcAirport) + if (dp[i - 1][srcAirport] != Int.MAX_VALUE) { + dp[i][destAirport] = dp[i][destAirport].coerceAtMost(dp[i - 1][srcAirport] + cost) + } + } + } + // checking for dp[k + 1][dst] because there are 'k + 2' airports in a path and distance + // covered between 'k + 2' airports is 'k + 1' + return if (dp[k + 1][dst] == Int.MAX_VALUE) -1 else dp[k + 1][dst] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0788_rotated_digits/readme.md b/src/main/kotlin/g0701_0800/s0788_rotated_digits/readme.md new file mode 100644 index 00000000..158dd288 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0788_rotated_digits/readme.md @@ -0,0 +1,79 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 788\. Rotated Digits + +Medium + +An integer `x` is a **good** if after rotating each digit individually by 180 degrees, we get a valid number that is different from `x`. Each digit must be rotated - we cannot choose to leave it alone. + +A number is valid if each digit remains a digit after rotation. For example: + +* `0`, `1`, and `8` rotate to themselves, +* `2` and `5` rotate to each other (in this case they are rotated in a different direction, in other words, `2` or `5` gets mirrored), +* `6` and `9` rotate to each other, and +* the rest of the numbers do not rotate to any other number and become invalid. + +Given an integer `n`, return _the number of **good** integers in the range_ `[1, n]`. + +**Example 1:** + +**Input:** n = 10 + +**Output:** 4 + +**Explanation:** There are four good numbers in the range [1, 10] : 2, 5, 6, 9. Note that 1 and 10 are not good numbers, since they remain unchanged after rotating. + +**Example 2:** + +**Input:** n = 1 + +**Output:** 0 + +**Example 3:** + +**Input:** n = 2 + +**Output:** 1 + +**Constraints:** + +* 1 <= n <= 104 + +## Solution + +```kotlin +class Solution { + fun rotatedDigits(n: Int): Int { + val flag = IntArray(n + 1) + flag[0] = 2 + val indexesValueTwo = intArrayOf(1, 8) + for (value in indexesValueTwo) { + if (n >= value) { + flag[value] = 2 + } + } + val indexesValueOne = intArrayOf(2, 5, 6, 9) + for (value in indexesValueOne) { + if (n >= value) { + flag[value] = 1 + } + } + var rs = 0 + for (i in 1..n) { + val residual = i % 10 + if (flag[residual] != 0) { + if ((residual == 1 || residual == 0 || residual == 8) && flag[i / 10] == 2) { + flag[i] = 2 + continue + } + if (flag[i / 10] != 0) { + flag[i] = 1 + rs++ + } + } + } + return rs + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0789_escape_the_ghosts/readme.md b/src/main/kotlin/g0701_0800/s0789_escape_the_ghosts/readme.md new file mode 100644 index 00000000..bf7ae118 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0789_escape_the_ghosts/readme.md @@ -0,0 +1,71 @@ +[![](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) + +## 789\. Escape The Ghosts + +Medium + +You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point `[0, 0]`, and you are given a destination point target = [xtarget, ytarget] that you are trying to get to. There are several ghosts on the map with their starting positions given as a 2D array `ghosts`, where ghosts[i] = [xi, yi] represents the starting position of the ith ghost. All inputs are **integral coordinates**. + +Each turn, you and all the ghosts may independently choose to either **move 1 unit** in any of the four cardinal directions: north, east, south, or west, or **stay still**. All actions happen **simultaneously**. + +You escape if and only if you can reach the target **before** any ghost reaches you. If you reach any square (including the target) at the **same time** as a ghost, it **does not** count as an escape. + +Return `true` _if it is possible to escape regardless of how the ghosts move, otherwise return_ `false`_._ + +**Example 1:** + +**Input:** ghosts = \[\[1,0],[0,3]], target = [0,1] + +**Output:** true + +**Explanation:** You can reach the destination (0, 1) after 1 turn, while the ghosts located at (1, 0) and (0, 3) cannot catch up with you. + +**Example 2:** + +**Input:** ghosts = \[\[1,0]], target = [2,0] + +**Output:** false + +**Explanation:** You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination. + +**Example 3:** + +**Input:** ghosts = \[\[2,0]], target = [1,0] + +**Output:** false + +**Explanation:** The ghost can reach the target at the same time as you. + +**Constraints:** + +* `1 <= ghosts.length <= 100` +* `ghosts[i].length == 2` +* -104 <= xi, yi <= 104 +* There can be **multiple ghosts** in the same location. +* `target.length == 2` +* -104 <= xtarget, ytarget <= 104 + +## Solution + +```kotlin +import kotlin.math.abs + +class Solution { + fun escapeGhosts(ghosts: Array, target: IntArray): Boolean { + val currPos = intArrayOf(0, 0) + val selfDist = getDist(currPos, target) + for (ghost in ghosts) { + val ghostDist = getDist(ghost, target) + if (ghostDist <= selfDist) { + return false + } + } + return true + } + + private fun getDist(p1: IntArray, p2: IntArray): Int { + return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0790_domino_and_tromino_tiling/readme.md b/src/main/kotlin/g0701_0800/s0790_domino_and_tromino_tiling/readme.md new file mode 100644 index 00000000..0585e9b0 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0790_domino_and_tromino_tiling/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) + +## 790\. Domino and Tromino Tiling + +Medium + +You have two types of tiles: a `2 x 1` domino shape and a tromino shape. You may rotate these shapes. + +![](https://assets.leetcode.com/uploads/2021/07/15/lc-domino.jpg) + +Given an integer n, return _the number of ways to tile an_ `2 x n` _board_. Since the answer may be very large, return it **modulo** 109 + 7. + +In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/07/15/lc-domino1.jpg) + +**Input:** n = 3 + +**Output:** 5 + +**Explanation:** The five different ways are show above. + +**Example 2:** + +**Input:** n = 1 + +**Output:** 1 + +**Constraints:** + +* `1 <= n <= 1000` + +## Solution + +```kotlin +class Solution { + fun numTilings(n: Int): Int { + val result = when (n) { + 1 -> 1 + 2 -> 2 + 3 -> 5 + 4 -> 11 + 5 -> 24 + else -> { + val dp = LongArray(n + 1) + dp[0] = 0 + dp[1] = 1 + dp[2] = 2 + dp[3] = 5 + dp[4] = 11 + dp[5] = 24 + dp[6] = 53 + for (i in 7..n) { + dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % 1000000007 + } + return dp[n].toInt() % 1000000007 + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0791_custom_sort_string/readme.md b/src/main/kotlin/g0701_0800/s0791_custom_sort_string/readme.md new file mode 100644 index 00000000..a6247d22 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0791_custom_sort_string/readme.md @@ -0,0 +1,58 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 791\. Custom Sort String + +Medium + +You are given two strings order and s. All the words of `order` are **unique** and were sorted in some custom order previously. + +Permute the characters of `s` so that they match the order that `order` was sorted. More specifically, if a character `x` occurs before a character `y` in `order`, then `x` should occur before `y` in the permuted string. + +Return _any permutation of_ `s` _that satisfies this property_. + +**Example 1:** + +**Input:** order = "cba", s = "abcd" + +**Output:** "cbad" + +**Explanation:** "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a". Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs. + +**Example 2:** + +**Input:** order = "cbafg", s = "abcd" + +**Output:** "cbad" + +**Constraints:** + +* `1 <= order.length <= 26` +* `1 <= s.length <= 200` +* `order` and `s` consist of lowercase English letters. +* All the characters of `order` are **unique**. + +## Solution + +```kotlin +class Solution { + fun customSortString(order: String, s: String): String { + val ord = IntArray(26) + val sb = StringBuilder() + for (c in s.toCharArray()) { + ord[c.code - 'a'.code]++ + } + for (c in order.toCharArray()) { + while (ord[c.code - 'a'.code]-- > 0) { + sb.append(c) + } + } + for (c in s.toCharArray()) { + while (ord[c.code - 'a'.code]-- > 0) { + sb.append(c) + } + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0792_number_of_matching_subsequences/readme.md b/src/main/kotlin/g0701_0800/s0792_number_of_matching_subsequences/readme.md new file mode 100644 index 00000000..6d5880c5 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0792_number_of_matching_subsequences/readme.md @@ -0,0 +1,67 @@ +[![](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) + +## 792\. Number of Matching Subsequences + +Medium + +Given a string `s` and an array of strings `words`, return _the number of_ `words[i]` _that is a subsequence of_ `s`. + +A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. + +* For example, `"ace"` is a subsequence of `"abcde"`. + +**Example 1:** + +**Input:** s = "abcde", words = ["a","bb","acd","ace"] + +**Output:** 3 + +**Explanation:** There are three strings in words that are a subsequence of s: "a", "acd", "ace". + +**Example 2:** + +**Input:** s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"] + +**Output:** 2 + +**Constraints:** + +* 1 <= s.length <= 5 * 104 +* `1 <= words.length <= 5000` +* `1 <= words[i].length <= 50` +* `s` and `words[i]` consist of only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun numMatchingSubseq(s: String, words: Array): Int { + val buckets: Array?> = arrayOfNulls(26) + for (i in buckets.indices) { + buckets[i] = ArrayList() + } + for (word in words) { + val start = word[0] + buckets[start.code - 'a'.code]?.add(Node(word, 0)) + } + var result = 0 + for (c in s.toCharArray()) { + val currBucket: MutableList? = buckets[c.code - 'a'.code] + buckets[c.code - 'a'.code] = ArrayList() + for (node in currBucket!!) { + node.index++ + if (node.index == node.word.length) { + result++ + } else { + val start = node.word[node.index] + buckets[start.code - 'a'.code]?.add(node) + } + } + } + return result + } + + private class Node(var word: String, var index: Int) +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0793_preimage_size_of_factorial_zeroes_function/readme.md b/src/main/kotlin/g0701_0800/s0793_preimage_size_of_factorial_zeroes_function/readme.md new file mode 100644 index 00000000..014e82aa --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0793_preimage_size_of_factorial_zeroes_function/readme.md @@ -0,0 +1,72 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 793\. Preimage Size of Factorial Zeroes Function + +Hard + +Let `f(x)` be the number of zeroes at the end of `x!`. Recall that `x! = 1 * 2 * 3 * ... * x` and by convention, `0! = 1`. + +* For example, `f(3) = 0` because `3! = 6` has no zeroes at the end, while `f(11) = 2` because `11! = 39916800` has two zeroes at the end. + +Given an integer `k`, return the number of non-negative integers `x` have the property that `f(x) = k`. + +**Example 1:** + +**Input:** k = 0 + +**Output:** 5 + +**Explanation:** 0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes. + +**Example 2:** + +**Input:** k = 5 + +**Output:** 0 + +**Explanation:** There is no x such that x! ends in k = 5 zeroes. + +**Example 3:** + +**Input:** k = 3 + +**Output:** 5 + +**Constraints:** + +* 0 <= k <= 109 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun preimageSizeFZF(k: Int): Int { + var left: Long = 0 + var right = 5L * (k + 1) + while (left < right - 1) { + val mid = left + (right - left) / 2 + val cnt = countZeros(mid) + if (cnt == k) { + return 5 + } else if (cnt < k) { + left = mid + } else { + right = mid + } + } + return if (countZeros(left) == k || countZeros(right) == k) 5 else 0 + } + + private fun countZeros(n: Long): Int { + var n = n + var rst: Long = 0 + while (n > 0) { + rst += n / 5 + n /= 5 + } + return rst.toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0794_valid_tic_tac_toe_state/readme.md b/src/main/kotlin/g0701_0800/s0794_valid_tic_tac_toe_state/readme.md new file mode 100644 index 00000000..19617ad9 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0794_valid_tic_tac_toe_state/readme.md @@ -0,0 +1,118 @@ +[![](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) + +## 794\. Valid Tic-Tac-Toe State + +Medium + +Given a Tic-Tac-Toe board as a string array `board`, return `true` if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game. + +The board is a `3 x 3` array that consists of characters `' '`, `'X'`, and `'O'`. The `' '` character represents an empty square. + +Here are the rules of Tic-Tac-Toe: + +* Players take turns placing characters into empty squares `' '`. +* The first player always places `'X'` characters, while the second player always places `'O'` characters. +* `'X'` and `'O'` characters are always placed into empty squares, never filled ones. +* The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal. +* The game also ends if all squares are non-empty. +* No more moves can be played if the game is over. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/05/15/tictactoe1-grid.jpg) + +**Input:** board = ["O "," "," "] + +**Output:** false + +**Explanation:** The first player always plays "X". + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/05/15/tictactoe2-grid.jpg) + +**Input:** board = ["XOX"," X "," "] + +**Output:** false + +**Explanation:** Players take turns making moves. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/05/15/tictactoe4-grid.jpg) + +**Input:** board = ["XOX","O O","XOX"] + +**Output:** true + +**Constraints:** + +* `board.length == 3` +* `board[i].length == 3` +* `board[i][j]` is either `'X'`, `'O'`, or `' '`. + +## Solution + +```kotlin +import kotlin.math.abs + +class Solution { + fun validTicTacToe(board: Array): Boolean { + // X=1,O=-1,’ ’=0 + var sum = 0 + val winsCol = IntArray(3) + val winsDig = IntArray(2) + var xWin = false + var oWin = false + for (i in 0..2) { + val str = board[i] + var rowSum = 0 + for (j in 0..2) { + // char chr=str.toCharArray()[j]; + var intchr = 0 + if (str.toCharArray()[j] == 'X') { + intchr = 1 + } + if (str.toCharArray()[j] == 'O') { + intchr = -1 + } + rowSum += intchr + winsCol[j] += intchr + if (i == 2 && winsCol[j] == 3) { + xWin = true + } + if (i == 2 && winsCol[j] == -3) { + oWin = true + } + if (abs(i - j) != 1) { + if (i == j && i == 1) { + winsDig[0] += intchr + winsDig[1] += intchr + } else if (i == j) { + winsDig[0] += intchr + } else { + winsDig[1] += intchr + } + } + if (i == 2 && winsDig[0].coerceAtLeast(winsDig[1]) == 3) { + xWin = true + } + if (i == 2 && winsDig[0].coerceAtMost(winsDig[1]) == -3) { + oWin = true + } + } + if (rowSum == 3) { + xWin = true + } + if (rowSum == -3) { + oWin = true + } + sum += rowSum + } + return if (sum == 0 && !xWin) { + true + } else sum == 1 && !oWin + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0795_number_of_subarrays_with_bounded_maximum/readme.md b/src/main/kotlin/g0701_0800/s0795_number_of_subarrays_with_bounded_maximum/readme.md new file mode 100644 index 00000000..b678fbbf --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0795_number_of_subarrays_with_bounded_maximum/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) + +## 795\. Number of Subarrays with Bounded Maximum + +Medium + +Given an integer array `nums` and two integers `left` and `right`, return _the number of contiguous non-empty **subarrays** such that the value of the maximum array element in that subarray is in the range_ `[left, right]`. + +The test cases are generated so that the answer will fit in a **32-bit** integer. + +**Example 1:** + +**Input:** nums = [2,1,4,3], left = 2, right = 3 + +**Output:** 3 + +**Explanation:** There are three subarrays that meet the requirements: [2], [2, 1], [3]. + +**Example 2:** + +**Input:** nums = [2,9,2,5,6], left = 2, right = 8 + +**Output:** 7 + +**Constraints:** + +* 1 <= nums.length <= 105 +* 0 <= nums[i] <= 109 +* 0 <= left <= right <= 109 + +## Solution + +```kotlin +class Solution { + fun numSubarrayBoundedMax(arr: IntArray, left: Int, right: Int): Int { + var ans = 0 + var si = 0 + var ei = 0 + var prev = 0 + while (ei < arr.size) { + // if in range + if (arr[ei] in left..right) { + prev = ei - si + 1 + ans += prev + } else if (arr[ei] < left) { + ans += prev + } else if (arr[ei] > right) { + prev = 0 + si = ei + 1 + } + ei++ + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0701_0800/s0796_rotate_string/readme.md b/src/main/kotlin/g0701_0800/s0796_rotate_string/readme.md new file mode 100644 index 00000000..4adf5744 --- /dev/null +++ b/src/main/kotlin/g0701_0800/s0796_rotate_string/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) + +## 796\. Rotate String + +Easy + +Given two strings `s` and `goal`, return `true` _if and only if_ `s` _can become_ `goal` _after some number of **shifts** on_ `s`. + +A **shift** on `s` consists of moving the leftmost character of `s` to the rightmost position. + +* For example, if `s = "abcde"`, then it will be `"bcdea"` after one shift. + +**Example 1:** + +**Input:** s = "abcde", goal = "cdeab" + +**Output:** true + +**Example 2:** + +**Input:** s = "abcde", goal = "abced" + +**Output:** false + +**Constraints:** + +* `1 <= s.length, goal.length <= 100` +* `s` and `goal` consist of lowercase English letters. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + private fun check(s: String, goal: String, i: Int): Boolean { + var i = i + var j = 0 + val len = goal.length + while (j < len) { + if (i == len) { + i = 0 + } + if (s[i] != goal[j]) { + return false + } + j++ + i++ + } + return true + } + + fun rotateString(s: String, goal: String): Boolean { + if (s.length != goal.length) { + return false + } + val len = s.length + if (s[0] == goal[0] && s != goal) { + return false + } + for (i in 0 until len) { + if (s[i] == goal[0] && check(s, goal, i)) { + return true + } + } + return false + } +} +``` \ No newline at end of file