From 62586d583f21e49150bb14a9ad3eecc690e2ee33 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Fri, 17 Feb 2023 05:09:06 +0200 Subject: [PATCH] Added tasks 649-682 --- README.md | 31 +++++ .../g0601_0700/s0649_dota2_senate/readme.md | 84 ++++++++++++ .../s0650_2_keys_keyboard/readme.md | 58 ++++++++ .../s0652_find_duplicate_subtrees/readme.md | 78 +++++++++++ .../s0653_two_sum_iv_input_is_a_bst/readme.md | 80 +++++++++++ .../s0654_maximum_binary_tree/readme.md | 99 ++++++++++++++ .../s0655_print_binary_tree/readme.md | 103 ++++++++++++++ .../s0657_robot_return_to_origin/readme.md | 50 +++++++ .../s0658_find_k_closest_elements/readme.md | 56 ++++++++ .../readme.md | 86 ++++++++++++ .../g0601_0700/s0661_image_smoother/readme.md | 110 +++++++++++++++ .../readme.md | 108 +++++++++++++++ .../s0664_strange_printer/readme.md | 64 +++++++++ .../s0665_non_decreasing_array/readme.md | 70 ++++++++++ .../s0667_beautiful_arrangement_ii/readme.md | 49 +++++++ .../readme.md | 67 +++++++++ .../s0669_trim_a_binary_search_tree/readme.md | 67 +++++++++ .../g0601_0700/s0670_maximum_swap/readme.md | 59 ++++++++ .../readme.md | 76 +++++++++++ .../s0672_bulb_switcher_ii/readme.md | 78 +++++++++++ .../readme.md | 69 ++++++++++ .../readme.md | 55 ++++++++ .../readme.md | 127 ++++++++++++++++++ .../readme.md | 95 +++++++++++++ .../g0601_0700/s0677_map_sum_pairs/readme.md | 95 +++++++++++++ .../s0678_valid_parenthesis_string/readme.md | 58 ++++++++ .../kotlin/g0601_0700/s0679_24_game/readme.md | 100 ++++++++++++++ .../s0680_valid_palindrome_ii/readme.md | 65 +++++++++ .../g0601_0700/s0682_baseball_game/readme.md | 86 ++++++++++++ 29 files changed, 2223 insertions(+) create mode 100644 src/main/kotlin/g0601_0700/s0649_dota2_senate/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0650_2_keys_keyboard/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0652_find_duplicate_subtrees/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0653_two_sum_iv_input_is_a_bst/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0654_maximum_binary_tree/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0655_print_binary_tree/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0657_robot_return_to_origin/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0658_find_k_closest_elements/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0659_split_array_into_consecutive_subsequences/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0661_image_smoother/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0662_maximum_width_of_binary_tree/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0664_strange_printer/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0665_non_decreasing_array/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0667_beautiful_arrangement_ii/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0668_kth_smallest_number_in_multiplication_table/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0669_trim_a_binary_search_tree/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0670_maximum_swap/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0671_second_minimum_node_in_a_binary_tree/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0672_bulb_switcher_ii/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0673_number_of_longest_increasing_subsequence/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0674_longest_continuous_increasing_subsequence/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0675_cut_off_trees_for_golf_event/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0676_implement_magic_dictionary/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0677_map_sum_pairs/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0678_valid_parenthesis_string/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0679_24_game/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0680_valid_palindrome_ii/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0682_baseball_game/readme.md diff --git a/README.md b/README.md index e5429430..8fe76200 100644 --- a/README.md +++ b/README.md @@ -827,6 +827,7 @@ | | | | | | |-|-|-|-|-|- | 0098 |[Validate Binary Search Tree](src/main/kotlin/g0001_0100/s0098_validate_binary_search_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 330 | 41.38 +| 0653 |[Two Sum IV - Input is a BST](src/main/kotlin/g0601_0700/s0653_two_sum_iv_input_is_a_bst)| Easy | Hash_Table, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Two_Pointers, Binary_Search_Tree | 231 | 96.08 | 0235 |[Lowest Common Ancestor of a Binary Search Tree](src/main/kotlin/g0201_0300/s0235_lowest_common_ancestor_of_a_binary_search_tree)| Easy | Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 404 | 75.59 ### Data Structure II @@ -1188,6 +1189,7 @@ | | | | | | |-|-|-|-|-|- | 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search | 318 | 82.28 +| 0673 |[Number of Longest Increasing Subsequence](src/main/kotlin/g0601_0700/s0673_number_of_longest_increasing_subsequence)| Medium | Array, Dynamic_Programming, Segment_Tree, Binary_Indexed_Tree | 226 | 91.67 #### Day 17 Dynamic Programming @@ -1311,6 +1313,7 @@ | | | | | | |-|-|-|-|-|- +| 0658 |[Find K Closest Elements](src/main/kotlin/g0601_0700/s0658_find_k_closest_elements)| Medium | Array, Sorting, Binary_Search, Two_Pointers, Heap_Priority_Queue | 375 | 95.16 #### Day 3 @@ -1641,6 +1644,34 @@ | 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 | 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 | 0739 |[Daily Temperatures](src/main/kotlin/g0701_0800/s0739_daily_temperatures)| Medium | Top_100_Liked_Questions, Array, Stack, Monotonic_Stack, Programming_Skills_II_Day_6 | 936 | 80.54 +| 0682 |[Baseball Game](src/main/kotlin/g0601_0700/s0682_baseball_game)| Easy | Array, Stack, Simulation | 159 | 100.00 +| 0680 |[Valid Palindrome II](src/main/kotlin/g0601_0700/s0680_valid_palindrome_ii)| Easy | String, Greedy, Two_Pointers | 296 | 79.17 +| 0679 |[24 Game](src/main/kotlin/g0601_0700/s0679_24_game)| Hard | Array, Math, Backtracking | 175 | 100.00 +| 0678 |[Valid Parenthesis String](src/main/kotlin/g0601_0700/s0678_valid_parenthesis_string)| Medium | String, Dynamic_Programming, Greedy, Stack | 133 | 100.00 +| 0677 |[Map Sum Pairs](src/main/kotlin/g0601_0700/s0677_map_sum_pairs)| Medium | String, Hash_Table, Design, Trie | 197 | 80.00 +| 0676 |[Implement Magic Dictionary](src/main/kotlin/g0601_0700/s0676_implement_magic_dictionary)| Medium | String, Hash_Table, Design, Trie | 256 | 100.00 +| 0675 |[Cut Off Trees for Golf Event](src/main/kotlin/g0601_0700/s0675_cut_off_trees_for_golf_event)| Hard | Array, Breadth_First_Search, Matrix, Heap_Priority_Queue | 777 | 100.00 +| 0674 |[Longest Continuous Increasing Subsequence](src/main/kotlin/g0601_0700/s0674_longest_continuous_increasing_subsequence)| Easy | Array | 201 | 84.21 +| 0673 |[Number of Longest Increasing Subsequence](src/main/kotlin/g0601_0700/s0673_number_of_longest_increasing_subsequence)| Medium | Array, Dynamic_Programming, Segment_Tree, Binary_Indexed_Tree, Algorithm_II_Day_16_Dynamic_Programming | 226 | 91.67 +| 0672 |[Bulb Switcher II](src/main/kotlin/g0601_0700/s0672_bulb_switcher_ii)| Medium | Math, Depth_First_Search, Breadth_First_Search, Bit_Manipulation | 131 | 100.00 +| 0671 |[Second Minimum Node In a Binary Tree](src/main/kotlin/g0601_0700/s0671_second_minimum_node_in_a_binary_tree)| Easy | Depth_First_Search, Tree, Binary_Tree | 128 | 100.00 +| 0670 |[Maximum Swap](src/main/kotlin/g0601_0700/s0670_maximum_swap)| Medium | Math, Greedy | 143 | 100.00 +| 0669 |[Trim a Binary Search Tree](src/main/kotlin/g0601_0700/s0669_trim_a_binary_search_tree)| Medium | Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 195 | 100.00 +| 0668 |[Kth Smallest Number in Multiplication Table](src/main/kotlin/g0601_0700/s0668_kth_smallest_number_in_multiplication_table)| Hard | Math, Binary_Search | 151 | 100.00 +| 0667 |[Beautiful Arrangement II](src/main/kotlin/g0601_0700/s0667_beautiful_arrangement_ii)| Medium | Array, Math | 175 | 100.00 +| 0665 |[Non-decreasing Array](src/main/kotlin/g0601_0700/s0665_non_decreasing_array)| Medium | Array | 256 | 85.71 +| 0664 |[Strange Printer](src/main/kotlin/g0601_0700/s0664_strange_printer)| Hard | String, Dynamic_Programming | 196 | 100.00 +| 0662 |[Maximum Width of Binary Tree](src/main/kotlin/g0601_0700/s0662_maximum_width_of_binary_tree)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 189 | 75.00 +| 0661 |[Image Smoother](src/main/kotlin/g0601_0700/s0661_image_smoother)| Easy | Array, Matrix | 352 | 100.00 +| 0659 |[Split Array into Consecutive Subsequences](src/main/kotlin/g0601_0700/s0659_split_array_into_consecutive_subsequences)| Medium | Array, Hash_Table, Greedy, Heap_Priority_Queue | 352 | 100.00 +| 0658 |[Find K Closest Elements](src/main/kotlin/g0601_0700/s0658_find_k_closest_elements)| Medium | Array, Sorting, Binary_Search, Two_Pointers, Heap_Priority_Queue, Binary_Search_II_Day_2 | 375 | 95.16 +| 0657 |[Robot Return to Origin](src/main/kotlin/g0601_0700/s0657_robot_return_to_origin)| Easy | String, Simulation | 186 | 100.00 +| 0655 |[Print Binary Tree](src/main/kotlin/g0601_0700/s0655_print_binary_tree)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 176 | 100.00 +| 0654 |[Maximum Binary Tree](src/main/kotlin/g0601_0700/s0654_maximum_binary_tree)| Medium | Array, Tree, Binary_Tree, Stack, Monotonic_Stack, Divide_and_Conquer | 271 | 90.00 +| 0653 |[Two Sum IV - Input is a BST](src/main/kotlin/g0601_0700/s0653_two_sum_iv_input_is_a_bst)| Easy | Hash_Table, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Two_Pointers, Binary_Search_Tree, Data_Structure_I_Day_14_Tree | 231 | 96.08 +| 0652 |[Find Duplicate Subtrees](src/main/kotlin/g0601_0700/s0652_find_duplicate_subtrees)| Medium | Hash_Table, Depth_First_Search, Tree, Binary_Tree | 266 | 76.00 +| 0650 |[2 Keys Keyboard](src/main/kotlin/g0601_0700/s0650_2_keys_keyboard)| Medium | Dynamic_Programming, Math | 115 | 100.00 +| 0649 |[Dota2 Senate](src/main/kotlin/g0601_0700/s0649_dota2_senate)| Medium | String, Greedy, Queue | 217 | 100.00 | 0648 |[Replace Words](src/main/kotlin/g0601_0700/s0648_replace_words)| Medium | Array, String, Hash_Table, Trie | 392 | 100.00 | 0647 |[Palindromic Substrings](src/main/kotlin/g0601_0700/s0647_palindromic_substrings)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming | 266 | 67.83 | 0646 |[Maximum Length of Pair Chain](src/main/kotlin/g0601_0700/s0646_maximum_length_of_pair_chain)| Medium | Array, Dynamic_Programming, Sorting, Greedy | 249 | 100.00 diff --git a/src/main/kotlin/g0601_0700/s0649_dota2_senate/readme.md b/src/main/kotlin/g0601_0700/s0649_dota2_senate/readme.md new file mode 100644 index 00000000..7e89235a --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0649_dota2_senate/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) + +## 649\. Dota2 Senate + +Medium + +In the world of Dota2, there are two parties: the Radiant and the Dire. + +The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise **one** of the two rights: + +* **Ban one senator's right:** A senator can make another senator lose all his rights in this and all the following rounds. +* **Announce the victory:** If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game. + +Given a string `senate` representing each senator's party belonging. The character `'R'` and `'D'` represent the Radiant party and the Dire party. Then if there are `n` senators, the size of the given string will be `n`. + +The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. + +Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be `"Radiant"` or `"Dire"`. + +**Example 1:** + +**Input:** senate = "RD" + +**Output:** "Radiant" + +**Explanation:** The first senator comes from Radiant and he can just ban the next senator's right in round 1. And the second senator can't exercise any rights anymore since his right has been banned. And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. + +**Example 2:** + +**Input:** senate = "RDD" + +**Output:** "Dire" + +**Explanation:** The first senator comes from Radiant and he can just ban the next senator's right in round 1. And the second senator can't exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator's right in round 1. And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. + +**Constraints:** + +* `n == senate.length` +* 1 <= n <= 104 +* `senate[i]` is either `'R'` or `'D'`. + +## Solution + +```kotlin +class Solution { + fun predictPartyVictory(senate: String): String { + val blocks = IntArray(2) + val status = BooleanArray(senate.length) + var changes = true + while (changes) { + changes = false + for (i in senate.indices) { + if (status[i]) { + continue + } + val curr = senate[i] + val block: Int = if (curr == 'R') { + 0 + } else { + 1 + } + if (blocks[1 - block] > 0) { + status[i] = true + blocks[1 - block]-- + changes = true + } else { + blocks[block]++ + } + } + } + for (i in senate.indices) { + if (!status[i]) { + return if (senate[i] == 'R') { + "Radiant" + } else { + "Dire" + } + } + } + return "" + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0650_2_keys_keyboard/readme.md b/src/main/kotlin/g0601_0700/s0650_2_keys_keyboard/readme.md new file mode 100644 index 00000000..f3113627 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0650_2_keys_keyboard/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) + +## 650\. 2 Keys Keyboard + +Medium + +There is only one character `'A'` on the screen of a notepad. You can perform one of two operations on this notepad for each step: + +* Copy All: You can copy all the characters present on the screen (a partial copy is not allowed). +* Paste: You can paste the characters which are copied last time. + +Given an integer `n`, return _the minimum number of operations to get the character_ `'A'` _exactly_ `n` _times on the screen_. + +**Example 1:** + +**Input:** n = 3 + +**Output:** 3 + +**Explanation:** Initially, we have one character 'A'. + +In step 1, we use Copy All operation. + +In step 2, we use Paste operation to get 'AA'. + +In step 3, we use Paste operation to get 'AAA'. + +**Example 2:** + +**Input:** n = 1 + +**Output:** 0 + +**Constraints:** + +* `1 <= n <= 1000` + +## Solution + +```kotlin +class Solution { + fun minSteps(n: Int): Int { + var count = 1 + var cost = 0 + var addValue = 1 + while (count < n) { + cost++ + count += addValue + if (n % count == 0) { + cost++ + addValue = count + } + } + return cost + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0652_find_duplicate_subtrees/readme.md b/src/main/kotlin/g0601_0700/s0652_find_duplicate_subtrees/readme.md new file mode 100644 index 00000000..63c3c39a --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0652_find_duplicate_subtrees/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) + +## 652\. Find Duplicate Subtrees + +Medium + +Given the `root` of a binary tree, return all **duplicate subtrees**. + +For each kind of duplicate subtrees, you only need to return the root node of any **one** of them. + +Two trees are **duplicate** if they have the **same structure** with the **same node values**. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/08/16/e1.jpg) + +**Input:** root = [1,2,3,4,null,2,4,null,null,4] + +**Output:** [[2,4],[4]] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/08/16/e2.jpg) + +**Input:** root = [2,1,1] + +**Output:** [[1]] + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2020/08/16/e33.jpg) + +**Input:** root = [2,2,2,3,null,3,null] + +**Output:** [[2,3],[3]] + +**Constraints:** + +* The number of the nodes in the tree will be in the range `[1, 5000]` +* `-200 <= Node.val <= 200` + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * 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 { + fun findDuplicateSubtrees(root: TreeNode?): List { + val map: MutableMap = HashMap() + val list: MutableList = ArrayList() + helper(root, map, list) + return list + } + + private fun helper(root: TreeNode?, map: MutableMap, list: MutableList): String { + if (root == null) { + return "#" + } + val key = helper(root.left, map, list) + "#" + helper(root.right, map, list) + "#" + root.`val` + map[key] = map.getOrDefault(key, 0) + 1 + if (map[key] == 2) { + list.add(root) + } + return key + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0653_two_sum_iv_input_is_a_bst/readme.md b/src/main/kotlin/g0601_0700/s0653_two_sum_iv_input_is_a_bst/readme.md new file mode 100644 index 00000000..9c5c5fcf --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0653_two_sum_iv_input_is_a_bst/readme.md @@ -0,0 +1,80 @@ +[![](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) + +## 653\. Two Sum IV - Input is a BST + +Easy + +Given the `root` of a binary search tree and an integer `k`, return `true` _if there exist two elements in the BST such that their sum is equal to_ `k`, _or_ `false` _otherwise_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/21/sum_tree_1.jpg) + +**Input:** root = [5,3,6,2,4,null,7], k = 9 + +**Output:** true + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/09/21/sum_tree_2.jpg) + +**Input:** root = [5,3,6,2,4,null,7], k = 28 + +**Output:** false + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 104]. +* -104 <= Node.val <= 104 +* `root` is guaranteed to be a **valid** binary search tree. +* -105 <= k <= 105 + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * 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 { + fun findTarget(root: TreeNode?, k: Int): Boolean { + if (root == null) { + return false + } + val res: MutableList = ArrayList() + inOrder(res, root) + var i = 0 + var j = res.size - 1 + while (i < j) { + val val1 = res[i] + val val2 = res[j] + if (val1 + val2 == k) { + return true + } else if (val1 + val2 < k) { + i++ + } else { + j-- + } + } + return false + } + + private fun inOrder(res: MutableList, root: TreeNode?) { + if (root == null) { + return + } + inOrder(res, root.left) + res.add(root.`val`) + inOrder(res, root.right) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0654_maximum_binary_tree/readme.md b/src/main/kotlin/g0601_0700/s0654_maximum_binary_tree/readme.md new file mode 100644 index 00000000..d49374de --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0654_maximum_binary_tree/readme.md @@ -0,0 +1,99 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 654\. Maximum Binary Tree + +Medium + +You are given an integer array `nums` with no duplicates. A **maximum binary tree** can be built recursively from `nums` using the following algorithm: + +1. Create a root node whose value is the maximum value in `nums`. +2. Recursively build the left subtree on the **subarray prefix** to the **left** of the maximum value. +3. Recursively build the right subtree on the **subarray suffix** to the **right** of the maximum value. + +Return _the **maximum binary tree** built from_ `nums`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/12/24/tree1.jpg) + +**Input:** nums = [3,2,1,6,0,5] + +**Output:** [6,3,5,null,2,0,null,null,1] + +**Explanation:** The recursive calls are as follow: + +- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5]. + + - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1]. + + - Empty array, so no child. + + - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1]. + + - Empty array, so no child. + + - Only one element, so child is a node with value 1. + + - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is []. + + - Only one element, so child is a node with value 0. + + - Empty array, so no child. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/12/24/tree2.jpg) + +**Input:** nums = [3,2,1] + +**Output:** [3,null,2,null,1] + +**Constraints:** + +* `1 <= nums.length <= 1000` +* `0 <= nums[i] <= 1000` +* All integers in `nums` are **unique**. + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * 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 { + fun constructMaximumBinaryTree(nums: IntArray): TreeNode? { + return mbt(nums, 0, nums.size - 1) + } + + private fun mbt(nums: IntArray, l: Int, r: Int): TreeNode? { + if (l > r || l >= nums.size || r < 0) { + return null + } + if (l == r) { + return TreeNode(nums[r]) + } + var max = Int.MIN_VALUE + var maxidx = 0 + for (i in l..r) { + if (nums[i] > max) { + max = nums[i] + maxidx = i + } + } + val root = TreeNode(max) + root.left = mbt(nums, l, maxidx - 1) + root.right = mbt(nums, maxidx + 1, r) + return root + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0655_print_binary_tree/readme.md b/src/main/kotlin/g0601_0700/s0655_print_binary_tree/readme.md new file mode 100644 index 00000000..af44a609 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0655_print_binary_tree/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) + +## 655\. Print Binary Tree + +Medium + +Given the `root` of a binary tree, construct a **0-indexed** `m x n` string matrix `res` that represents a **formatted layout** of the tree. The formatted layout matrix should be constructed using the following rules: + +* The **height** of the tree is `height` and the number of rows `m` should be equal to `height + 1`. +* The number of columns `n` should be equal to 2height+1 - 1. +* Place the **root node** in the **middle** of the **top row** (more formally, at location `res[0][(n-1)/2]`). +* For each node that has been placed in the matrix at position `res[r][c]`, place its **left child** at res[r+1][c-2height-r-1] and its **right child** at res[r+1][c+2height-r-1]. +* Continue this process until all the nodes in the tree have been placed. +* Any empty cells should contain the empty string `""`. + +Return _the constructed matrix_ `res`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/05/03/print1-tree.jpg) + +**Input:** root = [1,2] + +**Output:** + + [["","1",""], + ["2","",""]] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/05/03/print2-tree.jpg) + +**Input:** root = [1,2,3,null,4] + +**Output:** + + [["","","","1","","",""], + ["","2","","","","3",""], + ["","","4","","","",""]] + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 210]. +* `-99 <= Node.val <= 99` +* The depth of the tree will be in the range `[1, 10]`. + +## Solution + +```kotlin +import com_github_leetcode.TreeNode +import java.util.LinkedList +import kotlin.math.pow + +/* + * 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 { + fun printTree(root: TreeNode?): List> { + val result: MutableList> = LinkedList() + val height = if (root == null) 1 else getHeight(root) + val columns = (2.0.pow(height.toDouble()) - 1).toInt() + val row: MutableList = ArrayList() + for (i in 0 until columns) { + row.add("") + } + for (i in 0 until height) { + result.add(ArrayList(row)) + } + populateResult(root, result, 0, height, 0, columns - 1) + return result + } + + private fun populateResult( + root: TreeNode?, + result: List>, + row: Int, + totalRows: Int, + i: Int, + j: Int + ) { + if (row == totalRows || root == null) { + return + } + result[row][(i + j) / 2] = root.`val`.toString() + populateResult(root.left, result, row + 1, totalRows, i, (i + j) / 2 - 1) + populateResult(root.right, result, row + 1, totalRows, (i + j) / 2 + 1, j) + } + + private fun getHeight(root: TreeNode?): Int { + return if (root == null) { + 0 + } else 1 + getHeight(root.left).coerceAtLeast(getHeight(root.right)) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0657_robot_return_to_origin/readme.md b/src/main/kotlin/g0601_0700/s0657_robot_return_to_origin/readme.md new file mode 100644 index 00000000..c4afd8e7 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0657_robot_return_to_origin/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) + +## 657\. Robot Return to Origin + +Easy + +There is a robot starting at the position `(0, 0)`, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot **ends up at** `(0, 0)` after it completes its moves. + +You are given a string `moves` that represents the move sequence of the robot where `moves[i]` represents its ith move. Valid moves are `'R'` (right), `'L'` (left), `'U'` (up), and `'D'` (down). + +Return `true` _if the robot returns to the origin after it finishes all of its moves, or_ `false` _otherwise_. + +**Note**: The way that the robot is "facing" is irrelevant. `'R'` will always make the robot move to the right once, `'L'` will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move. + +**Example 1:** + +**Input:** moves = "UD" + +**Output:** true + +**Explanation:**: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true. + +**Example 2:** + +**Input:** moves = "LL" + +**Output:** false + +**Explanation:**: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves. + +**Constraints:** + +* 1 <= moves.length <= 2 * 104 +* `moves` only contains the characters `'U'`, `'D'`, `'L'` and `'R'`. + +## Solution + +```kotlin +class Solution { + fun judgeCircle(moves: String): Boolean { + val map = IntArray(26) + for (c in moves.toCharArray()) { + map[c.code - 'A'.code]++ + } + return map['U'.code - 'A'.code] == map['D'.code - 'A'.code] && + map['L'.code - 'A'.code] == map['R'.code - 'A'.code] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0658_find_k_closest_elements/readme.md b/src/main/kotlin/g0601_0700/s0658_find_k_closest_elements/readme.md new file mode 100644 index 00000000..6d806552 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0658_find_k_closest_elements/readme.md @@ -0,0 +1,56 @@ +[![](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) + +## 658\. Find K Closest Elements + +Medium + +Given a **sorted** integer array `arr`, two integers `k` and `x`, return the `k` closest integers to `x` in the array. The result should also be sorted in ascending order. + +An integer `a` is closer to `x` than an integer `b` if: + +* `|a - x| < |b - x|`, or +* `|a - x| == |b - x|` and `a < b` + +**Example 1:** + +**Input:** arr = [1,2,3,4,5], k = 4, x = 3 + +**Output:** [1,2,3,4] + +**Example 2:** + +**Input:** arr = [1,2,3,4,5], k = 4, x = -1 + +**Output:** [1,2,3,4] + +**Constraints:** + +* `1 <= k <= arr.length` +* 1 <= arr.length <= 104 +* `arr` is sorted in **ascending** order. +* -104 <= arr[i], x <= 104 + +## Solution + +```kotlin +class Solution { + fun findClosestElements(arr: IntArray, k: Int, x: Int): List { + var left = 0 + var right = arr.size - k + val answer: MutableList = ArrayList() + while (left < right) { + val mid = left + (right - left) / 2 + if (x - arr[mid] > arr[mid + k] - x) { + left = mid + 1 + } else { + right = mid + } + } + for (i in left until left + k) { + answer.add(arr[i]) + } + return answer + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0659_split_array_into_consecutive_subsequences/readme.md b/src/main/kotlin/g0601_0700/s0659_split_array_into_consecutive_subsequences/readme.md new file mode 100644 index 00000000..28aee16b --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0659_split_array_into_consecutive_subsequences/readme.md @@ -0,0 +1,86 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 659\. Split Array into Consecutive Subsequences + +Medium + +You are given an integer array `nums` that is **sorted in non-decreasing order**. + +Determine if it is possible to split `nums` into **one or more subsequences** such that **both** of the following conditions are true: + +* Each subsequence is a **consecutive increasing sequence** (i.e. each integer is **exactly one** more than the previous integer). +* All subsequences have a length of `3` **or more**. + +Return `true` _if you can split_ `nums` _according to the above conditions, or_ `false` _otherwise_. + +A **subsequence** of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., `[1,3,5]` is a subsequence of [1,2,3,4,5] while `[1,3,2]` is not). + +**Example 1:** + +**Input:** nums = [1,2,3,3,4,5] + +**Output:** true + +**Explanation:** nums can be split into the following subsequences: + +[**1**,**2**,**3**,3,4,5] --> 1, 2, 3 + + [1,2,3,**3**,**4**,**5**] --> 3, 4, 5 + +**Example 2:** + +**Input:** nums = [1,2,3,3,4,4,5,5] + +**Output:** true + +**Explanation:** nums can be split into the following subsequences: + +[**1**,**2**,**3**,3,**4**,4,**5**,5] --> 1, 2, 3, 4, 5 + +[1,2,3,**3**,4,**4**,5,**5**] --> 3, 4, 5 + +**Example 3:** + +**Input:** nums = [1,2,3,4,4,5] + +**Output:** false + +**Explanation:** It is impossible to split nums into consecutive increasing subsequences of length 3 or more. + +**Constraints:** + +* 1 <= nums.length <= 104 +* `-1000 <= nums[i] <= 1000` +* `nums` is sorted in **non-decreasing** order. + +## Solution + +```kotlin +class Solution { + fun isPossible(nums: IntArray): Boolean { + val element = IntArray(2001) + for (num in nums) { + element[num + 1000] += 1 + } + for (i in element.indices) { + while (element[i] > 0) { + var length = 1 + while (i + length < element.size && + element[i + length] >= element[i + length - 1] + ) { + length += 1 + } + if (length < 3) { + return false + } else { + for (j in i until i + length) { + element[j] -= 1 + } + } + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0661_image_smoother/readme.md b/src/main/kotlin/g0601_0700/s0661_image_smoother/readme.md new file mode 100644 index 00000000..40c908c1 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0661_image_smoother/readme.md @@ -0,0 +1,110 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 661\. Image Smoother + +Easy + +An **image smoother** is a filter of the size `3 x 3` that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother). + +![](https://assets.leetcode.com/uploads/2021/05/03/smoother-grid.jpg) + +Given an `m x n` integer matrix `img` representing the grayscale of an image, return _the image after applying the smoother on each cell of it_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/05/03/smooth-grid.jpg) + +**Input:** img = \[\[1,1,1],[1,0,1],[1,1,1]] + +**Output:** [[0,0,0],[0,0,0],[0,0,0]] + +**Explanation:** + +For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 + +For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0 + +For the point (1,1): floor(8/9) = floor(0.88888889) = 0 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/05/03/smooth2-grid.jpg) + +**Input:** img = \[\[100,200,100],[200,50,200],[100,200,100]] + +**Output:** [[137,141,137],[141,138,141],[137,141,137]] + +**Explanation:** + +For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137 + +For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141 + +For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138 + +**Constraints:** + +* `m == img.length` +* `n == img[i].length` +* `1 <= m, n <= 200` +* `0 <= img[i][j] <= 255` + +## Solution + +```kotlin +class Solution { + fun imageSmoother(matrix: Array?): Array? { + if (matrix.isNullOrEmpty()) { + return matrix + } + val m = matrix.size + val n = matrix[0].size + val result = Array(m) { IntArray(n) } + for (i in 0 until m) { + for (j in 0 until n) { + bfs(matrix, i, j, result, m, n) + } + } + return result + } + + private fun bfs(matrix: Array, i: Int, j: Int, result: Array, m: Int, n: Int) { + var sum = matrix[i][j] + var denominator = 1 + if (j + 1 < n) { + sum += matrix[i][j + 1] + denominator++ + } + if (i + 1 < m && j + 1 < n) { + sum += matrix[i + 1][j + 1] + denominator++ + } + if (i + 1 < m) { + sum += matrix[i + 1][j] + denominator++ + } + if (i + 1 < m && j - 1 >= 0) { + sum += matrix[i + 1][j - 1] + denominator++ + } + if (j - 1 >= 0) { + sum += matrix[i][j - 1] + denominator++ + } + if (i - 1 >= 0 && j - 1 >= 0) { + sum += matrix[i - 1][j - 1] + denominator++ + } + if (i - 1 >= 0) { + sum += matrix[i - 1][j] + denominator++ + } + if (i - 1 >= 0 && j + 1 < n) { + sum += matrix[i - 1][j + 1] + denominator++ + } + result[i][j] = sum / denominator + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0662_maximum_width_of_binary_tree/readme.md b/src/main/kotlin/g0601_0700/s0662_maximum_width_of_binary_tree/readme.md new file mode 100644 index 00000000..aa35a2f7 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0662_maximum_width_of_binary_tree/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) + +## 662\. Maximum Width of Binary Tree + +Medium + +Given the `root` of a binary tree, return _the **maximum width** of the given tree_. + +The **maximum width** of a tree is the maximum **width** among all levels. + +The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation. + +It is **guaranteed** that the answer will in the range of a **32-bit** signed integer. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/05/03/width1-tree.jpg) + +**Input:** root = [1,3,2,5,3,null,9] + +**Output:** 4 + +**Explanation:** The maximum width exists in the third level with length 4 (5,3,null,9). + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2022/03/14/maximum-width-of-binary-tree-v3.jpg) + +**Input:** root = [1,3,2,5,null,null,9,6,null,7] + +**Output:** 7 + +**Explanation:** The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7). + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/05/03/width3-tree.jpg) + +**Input:** root = [1,3,2,5] + +**Output:** 2 + +**Explanation:** The maximum width exists in the second level with length 2 (3,2). + +**Constraints:** + +* The number of nodes in the tree is in the range `[1, 3000]`. +* `-100 <= Node.val <= 100` + +## Solution + +```kotlin +import com_github_leetcode.TreeNode +import java.util.LinkedList +import java.util.Objects +import java.util.Queue + +/* + * 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 { + internal class Pair(node: TreeNode, idx: Int) { + var node: TreeNode + var idx: Int + + init { + this.node = node + this.idx = idx + } + } + + fun widthOfBinaryTree(root: TreeNode): Int { + val q: Queue = LinkedList() + q.add(Pair(root, 0)) + var res = 1 + while (!q.isEmpty()) { + val qSize = q.size + var lastIdx = 0 + var firstIdx = 0 + for (i in 0 until qSize) { + val temp = q.poll() + if (i == 0) { + firstIdx = temp.idx + } + if (i == qSize - 1) { + lastIdx = Objects.requireNonNull(temp).idx + } + if (Objects.requireNonNull(temp).node.left != null) { + q.add(Pair(temp.node.left!!, 2 * temp.idx + 1)) + } + if (temp.node.right != null) { + q.add(Pair(temp.node.right!!, 2 * temp.idx + 2)) + } + } + res = (lastIdx - firstIdx + 1).coerceAtLeast(res) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0664_strange_printer/readme.md b/src/main/kotlin/g0601_0700/s0664_strange_printer/readme.md new file mode 100644 index 00000000..dd60d4b4 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0664_strange_printer/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) + +## 664\. Strange Printer + +Hard + +There is a strange printer with the following two special properties: + +* The printer can only print a sequence of **the same character** each time. +* At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters. + +Given a string `s`, return _the minimum number of turns the printer needed to print it_. + +**Example 1:** + +**Input:** s = "aaabbb" + +**Output:** 2 + +**Explanation:** Print "aaa" first and then print "bbb". + +**Example 2:** + +**Input:** s = "aba" + +**Output:** 2 + +**Explanation:** Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'. + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun strangePrinter(s: String): Int { + if (s.isEmpty()) { + return 0 + } + val dp = Array(s.length) { IntArray(s.length) } + for (i in s.length - 1 downTo 0) { + for (j in i until s.length) { + if (i == j) { + dp[i][j] = 1 + } else if (s[i] == s[i + 1]) { + dp[i][j] = dp[i + 1][j] + } else { + dp[i][j] = dp[i + 1][j] + 1 + for (k in i + 1..j) { + if (s[k] == s[i]) { + dp[i][j] = dp[i][j].coerceAtMost(dp[i + 1][k - 1] + dp[k][j]) + } + } + } + } + } + return dp[0][s.length - 1] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0665_non_decreasing_array/readme.md b/src/main/kotlin/g0601_0700/s0665_non_decreasing_array/readme.md new file mode 100644 index 00000000..b02f1d6d --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0665_non_decreasing_array/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) + +## 665\. Non-decreasing Array + +Medium + +Given an array `nums` with `n` integers, your task is to check if it could become non-decreasing by modifying **at most one element**. + +We define an array is non-decreasing if `nums[i] <= nums[i + 1]` holds for every `i` (**0-based**) such that (`0 <= i <= n - 2`). + +**Example 1:** + +**Input:** nums = [4,2,3] + +**Output:** true + +**Explanation:** You could modify the first 4 to 1 to get a non-decreasing array. + +**Example 2:** + +**Input:** nums = [4,2,1] + +**Output:** false + +**Explanation:** You cannot get a non-decreasing array by modifying at most one element. + +**Constraints:** + +* `n == nums.length` +* 1 <= n <= 104 +* -105 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun checkPossibility(nums: IntArray): Boolean { + val n = nums.size + if (n <= 2) { + return true + } + + var isModified = false + for (i in 0..(n - 2)) { + if (nums[i] <= nums[i + 1]) { + continue + } + if (isModified) { + return false + } + + when { + i == 0 || nums[i - 1] <= nums[i + 1] -> { + nums[i] = nums[i + 1] + isModified = true + } + i == n - 2 || nums[i] <= nums[i + 2] -> { + nums[i + 1] = nums[i] + isModified = true + } + else -> { + return false + } + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0667_beautiful_arrangement_ii/readme.md b/src/main/kotlin/g0601_0700/s0667_beautiful_arrangement_ii/readme.md new file mode 100644 index 00000000..e509ffd6 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0667_beautiful_arrangement_ii/readme.md @@ -0,0 +1,49 @@ +[![](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) + +## 667\. Beautiful Arrangement II + +Medium + +Given two integers `n` and `k`, construct a list `answer` that contains `n` different positive integers ranging from `1` to `n` and obeys the following requirement: + +* Suppose this list is answer = [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly `k` distinct integers. + +Return _the list_ `answer`. If there multiple valid answers, return **any of them**. + +**Example 1:** + +**Input:** n = 3, k = 1 + +**Output:** [1,2,3] Explanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1 + +**Example 2:** + +**Input:** n = 3, k = 2 + +**Output:** [1,3,2] Explanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2. + +**Constraints:** + +* 1 <= k < n <= 104 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun constructArray(n: Int, k: Int): IntArray { + var k = k + val res = IntArray(n) + var left = 1 + var right = n + for (i in 0 until n) { + res[i] = if (k % 2 == 0) left++ else right-- + if (k > 1) { + k-- + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0668_kth_smallest_number_in_multiplication_table/readme.md b/src/main/kotlin/g0601_0700/s0668_kth_smallest_number_in_multiplication_table/readme.md new file mode 100644 index 00000000..21e0b833 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0668_kth_smallest_number_in_multiplication_table/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) + +## 668\. Kth Smallest Number in Multiplication Table + +Hard + +Nearly everyone has used the [Multiplication Table](https://en.wikipedia.org/wiki/Multiplication_table). The multiplication table of size `m x n` is an integer matrix `mat` where `mat[i][j] == i * j` (**1-indexed**). + +Given three integers `m`, `n`, and `k`, return _the_ kth _smallest element in the_ `m x n` _multiplication table_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/05/02/multtable1-grid.jpg) + +**Input:** m = 3, n = 3, k = 5 + +**Output:** 3 + +**Explanation:** The 5th smallest number is 3. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/05/02/multtable2-grid.jpg) + +**Input:** m = 2, n = 3, k = 6 + +**Output:** 6 + +**Explanation:** The 6th smallest number is 6. + +**Constraints:** + +* 1 <= m, n <= 3 * 104 +* `1 <= k <= m * n` + +## Solution + +```kotlin +class Solution { + fun findKthNumber(m: Int, n: Int, k: Int): Int { + var lo = 1 + var hi = m * n + while (lo < hi) { + val mid = lo + (hi - lo) / 2 + var col = n + var row = 1 + var count = 0 + while (row <= m && col >= 1) { + val `val` = row * col + if (`val` > mid) { + col-- + } else { + count += col + row++ + } + } + if (count < k) { + lo = mid + 1 + } else { + hi = mid + } + } + return lo + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0669_trim_a_binary_search_tree/readme.md b/src/main/kotlin/g0601_0700/s0669_trim_a_binary_search_tree/readme.md new file mode 100644 index 00000000..ca65be0b --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0669_trim_a_binary_search_tree/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) + +## 669\. Trim a Binary Search Tree + +Medium + +Given the `root` of a binary search tree and the lowest and highest boundaries as `low` and `high`, trim the tree so that all its elements lies in `[low, high]`. Trimming the tree should **not** change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a **unique answer**. + +Return _the root of the trimmed binary search tree_. Note that the root may change depending on the given bounds. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/09/trim1.jpg) + +**Input:** root = [1,0,2], low = 1, high = 2 + +**Output:** [1,null,2] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/09/09/trim2.jpg) + +**Input:** root = [3,0,4,null,2,null,null,1], low = 1, high = 3 + +**Output:** [3,2,null,1] + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 104]. +* 0 <= Node.val <= 104 +* The value of each node in the tree is **unique**. +* `root` is guaranteed to be a valid binary search tree. +* 0 <= low <= high <= 104 + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * 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 { + fun trimBST(root: TreeNode?, l: Int, r: Int): TreeNode? { + if (root == null) { + return root + } + if (root.`val` > r) { + return trimBST(root.left, l, r) + } + if (root.`val` < l) { + return trimBST(root.right, l, r) + } + root.left = trimBST(root.left, l, r) + root.right = trimBST(root.right, l, r) + return root + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0670_maximum_swap/readme.md b/src/main/kotlin/g0601_0700/s0670_maximum_swap/readme.md new file mode 100644 index 00000000..0da891bd --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0670_maximum_swap/readme.md @@ -0,0 +1,59 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 670\. Maximum Swap + +Medium + +You are given an integer `num`. You can swap two digits at most once to get the maximum valued number. + +Return _the maximum valued number you can get_. + +**Example 1:** + +**Input:** num = 2736 + +**Output:** 7236 + +**Explanation:** Swap the number 2 and the number 7. + +**Example 2:** + +**Input:** num = 9973 + +**Output:** 9973 + +**Explanation:** No swap. + +**Constraints:** + +* 0 <= num <= 108 + +## Solution + +```kotlin +class Solution { + fun maximumSwap(num: Int): Int { + val chars = num.toString().toCharArray() + for (i in chars.indices) { + var j = chars.size - 1 + var indx = i + var c = chars[i] + while (j > i) { + if (chars[j] > c) { + c = chars[j] + indx = j + } + j-- + } + if (indx != i) { + val temp = chars[i] + chars[i] = chars[indx] + chars[indx] = temp + return String(chars).toInt() + } + } + return num + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0671_second_minimum_node_in_a_binary_tree/readme.md b/src/main/kotlin/g0601_0700/s0671_second_minimum_node_in_a_binary_tree/readme.md new file mode 100644 index 00000000..f4183154 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0671_second_minimum_node_in_a_binary_tree/readme.md @@ -0,0 +1,76 @@ +[![](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) + +## 671\. Second Minimum Node In a Binary Tree + +Easy + +Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly `two` or `zero` sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property `root.val = min(root.left.val, root.right.val)` always holds. + +Given such a binary tree, you need to output the **second minimum** value in the set made of all the nodes' value in the whole tree. + +If no such second minimum value exists, output -1 instead. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/15/smbt1.jpg) + +**Input:** root = [2,2,5,null,null,5,7] + +**Output:** 5 + +**Explanation:** The smallest value is 2, the second smallest value is 5. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/10/15/smbt2.jpg) + +**Input:** root = [2,2,2] + +**Output:** -1 + +**Explanation:** The smallest value is 2, but there isn't any second smallest value. + +**Constraints:** + +* The number of nodes in the tree is in the range `[1, 25]`. +* 1 <= Node.val <= 231 - 1 +* `root.val == min(root.left.val, root.right.val)` for each internal node of the tree. + +## 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 { + var min = Int.MAX_VALUE + var secMin = -1 + var diff = Int.MAX_VALUE + fun findSecondMinimumValue(root: TreeNode?): Int { + if (root == null) { + return -1 + } + if (root.`val` < min) { + min = root.`val` + } + if (root.`val` != min && abs(root.`val` - min) < diff) { + secMin = root.`val` + diff = abs(root.`val` - min) + } + findSecondMinimumValue(root.left) + findSecondMinimumValue(root.right) + return secMin + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0672_bulb_switcher_ii/readme.md b/src/main/kotlin/g0601_0700/s0672_bulb_switcher_ii/readme.md new file mode 100644 index 00000000..f9f199c7 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0672_bulb_switcher_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) + +## 672\. Bulb Switcher II + +Medium + +There is a room with `n` bulbs labeled from `1` to `n` that all are turned on initially, and **four buttons** on the wall. Each of the four buttons has a different functionality where: + +* **Button 1:** Flips the status of all the bulbs. +* **Button 2:** Flips the status of all the bulbs with even labels (i.e., `2, 4, ...`). +* **Button 3:** Flips the status of all the bulbs with odd labels (i.e., `1, 3, ...`). +* **Button 4:** Flips the status of all the bulbs with a label `j = 3k + 1` where `k = 0, 1, 2, ...` (i.e., `1, 4, 7, 10, ...`). + +You must make **exactly** `presses` button presses in total. For each press, you may pick **any** of the four buttons to press. + +Given the two integers `n` and `presses`, return _the number of **different possible statuses** after performing all_ `presses` _button presses_. + +**Example 1:** + +**Input:** n = 1, presses = 1 + +**Output:** 2 + +**Explanation:** Status can be: + +- \[off] by pressing button 1 + +- \[on] by pressing button 2 + +**Example 2:** + +**Input:** n = 2, presses = 1 + +**Output:** 3 + +**Explanation:** Status can be: + +- \[off, off] by pressing button 1 + +- \[on, off] by pressing button 2 + +- \[off, on] by pressing button 3 + +**Example 3:** + +**Input:** n = 3, presses = 1 + +**Output:** 4 + +**Explanation:** Status can be: - [off, off, off] by pressing button 1 - [off, on, off] by pressing button 2 - [on, off, on] by pressing button 3 - [off, on, on] by pressing button 4 + +**Constraints:** + +* `1 <= n <= 1000` +* `0 <= presses <= 1000` + +## Solution + +```kotlin +class Solution { + fun flipLights(n: Int, m: Int): Int { + return if (n == 1 && m > 0) { + 2 + } else if (n == 2 && m == 1) { + 3 + } else if (n > 2 && m == 1 || n == 2 && m > 1) { + 4 + } else if (n > 2 && m == 2) { + 7 + } else if (n > 2 && m > 2) { + 8 + } else { + 1 + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0673_number_of_longest_increasing_subsequence/readme.md b/src/main/kotlin/g0601_0700/s0673_number_of_longest_increasing_subsequence/readme.md new file mode 100644 index 00000000..b4f3202c --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0673_number_of_longest_increasing_subsequence/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) + +## 673\. Number of Longest Increasing Subsequence + +Medium + +Given an integer array `nums`, return _the number of longest increasing subsequences._ + +**Notice** that the sequence has to be **strictly** increasing. + +**Example 1:** + +**Input:** nums = [1,3,5,4,7] + +**Output:** 2 + +**Explanation:** The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7]. + +**Example 2:** + +**Input:** nums = [2,2,2,2,2] + +**Output:** 5 + +**Explanation:** The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5. + +**Constraints:** + +* `1 <= nums.length <= 2000` +* -106 <= nums[i] <= 106 + +## Solution + +```kotlin +class Solution { + fun findNumberOfLIS(nums: IntArray): Int { + val dp = IntArray(nums.size) + val count = IntArray(nums.size) + dp[0] = 1 + count[0] = 1 + var result = 0 + var max = Int.MIN_VALUE + for (i in 1 until nums.size) { + dp[i] = 1 + count[i] = 1 + for (j in i - 1 downTo 0) { + if (nums[j] < nums[i]) { + if (dp[i] < dp[j] + 1) { + dp[i] = dp[j] + 1 + count[i] = count[j] + } else if (dp[i] == dp[j] + 1) { + count[i] += count[j] + } + } + } + } + for (i in nums.indices) { + if (max < dp[i]) { + result = count[i] + max = dp[i] + } else if (max == dp[i]) { + result += count[i] + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0674_longest_continuous_increasing_subsequence/readme.md b/src/main/kotlin/g0601_0700/s0674_longest_continuous_increasing_subsequence/readme.md new file mode 100644 index 00000000..38ea018b --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0674_longest_continuous_increasing_subsequence/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) + +## 674\. Longest Continuous Increasing Subsequence + +Easy + +Given an unsorted array of integers `nums`, return _the length of the longest **continuous increasing subsequence** (i.e. subarray)_. The subsequence must be **strictly** increasing. + +A **continuous increasing subsequence** is defined by two indices `l` and `r` (`l < r`) such that it is `[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]` and for each `l <= i < r`, `nums[i] < nums[i + 1]`. + +**Example 1:** + +**Input:** nums = [1,3,5,4,7] + +**Output:** 3 + +**Explanation:** The longest continuous increasing subsequence is [1,3,5] with length 3. Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element 4. + +**Example 2:** + +**Input:** nums = [2,2,2,2,2] + +**Output:** 1 + +**Explanation:** The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly increasing. + +**Constraints:** + +* 1 <= nums.length <= 104 +* -109 <= nums[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun findLengthOfLCIS(nums: IntArray): Int { + var ans = 1 + var count = 1 + for (i in 0 until nums.size - 1) { + if (nums[i] < nums[i + 1]) { + count++ + } else { + ans = max(count, ans) + count = 1 + } + } + return max(ans, count) + } + + private fun max(n1: Int, n2: Int): Int { + return Math.max(n1, n2) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0675_cut_off_trees_for_golf_event/readme.md b/src/main/kotlin/g0601_0700/s0675_cut_off_trees_for_golf_event/readme.md new file mode 100644 index 00000000..dd7aab92 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0675_cut_off_trees_for_golf_event/readme.md @@ -0,0 +1,127 @@ +[![](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) + +## 675\. Cut Off Trees for Golf Event + +Hard + +You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an `m x n` matrix. In this matrix: + +* `0` means the cell cannot be walked through. +* `1` represents an empty cell that can be walked through. +* A number greater than `1` represents a tree in a cell that can be walked through, and this number is the tree's height. + +In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off. + +You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes `1` (an empty cell). + +Starting from the point `(0, 0)`, return _the minimum steps you need to walk to cut off all the trees_. If you cannot cut off all the trees, return `-1`. + +**Note:** The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/26/trees1.jpg) + +**Input:** forest = \[\[1,2,3],[0,0,4],[7,6,5]] + +**Output:** 6 + +**Explanation:** Following the path above allows you to cut off the trees from shortest to tallest in 6 steps. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/11/26/trees2.jpg) + +**Input:** forest = \[\[1,2,3],[0,0,0],[7,6,5]] + +**Output:** -1 + +**Explanation:** The trees in the bottom row cannot be accessed as the middle row is blocked. + +**Example 3:** + +**Input:** forest = \[\[2,3,4],[0,0,5],[8,7,6]] + +**Output:** 6 + +**Explanation:** You can follow the same path as Example 1 to cut off all the trees. Note that you can cut off the first tree at (0, 0) before making any steps. + +**Constraints:** + +* `m == forest.length` +* `n == forest[i].length` +* `1 <= m, n <= 50` +* 0 <= forest[i][j] <= 109 +* Heights of all trees are **distinct**. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Objects +import java.util.PriorityQueue +import java.util.Queue + +class Solution { + private var r = 0 + private var c = 0 + fun cutOffTree(forest: List>): Int { + val pq = PriorityQueue() + for (integers in forest) { + for (v in integers) { + if (v > 1) { + pq.add(v) + } + } + } + var steps = 0 + while (!pq.isEmpty()) { + val count = minSteps(forest, pq.poll()) + if (count == -1) { + return -1 + } + steps += count + } + return steps + } + + private fun minSteps(forest: List>, target: Int): Int { + var steps = 0 + val dirs = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0)) + val visited = Array(forest.size) { + BooleanArray( + forest[0].size + ) + } + val q: Queue = LinkedList() + q.add(intArrayOf(r, c)) + visited[r][c] = true + while (!q.isEmpty()) { + val qSize = q.size + for (i in 0 until qSize) { + val curr = q.poll() + if (forest[Objects.requireNonNull(curr)[0]][curr[1]] == target) { + r = curr[0] + c = curr[1] + return steps + } + for (k in 0..3) { + val dir = dirs[k] + val nr = dir[0] + curr[0] + val nc = dir[1] + curr[1] + if (nr < 0 || nr == visited.size || nc < 0 || nc == visited[0].size || + visited[nr][nc] || forest[nr][nc] == 0 + ) { + continue + } + q.add(intArrayOf(nr, nc)) + visited[nr][nc] = true + } + } + steps++ + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0676_implement_magic_dictionary/readme.md b/src/main/kotlin/g0601_0700/s0676_implement_magic_dictionary/readme.md new file mode 100644 index 00000000..68a53c68 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0676_implement_magic_dictionary/readme.md @@ -0,0 +1,95 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 676\. Implement Magic Dictionary + +Medium + +Design a data structure that is initialized with a list of **different** words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure. + +Implement the `MagicDictionary` class: + +* `MagicDictionary()` Initializes the object. +* `void buildDict(String[] dictionary)` Sets the data structure with an array of distinct strings `dictionary`. +* `bool search(String searchWord)` Returns `true` if you can change **exactly one character** in `searchWord` to match any string in the data structure, otherwise returns `false`. + +**Example 1:** + +**Input** + +["MagicDictionary", "buildDict", "search", "search", "search", "search"] [[], + +[["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]] + +**Output:** [null, null, false, true, false, false] + +**Explanation:** + + MagicDictionary magicDictionary = new MagicDictionary(); + magicDictionary.buildDict(["hello", "leetcode"]); + magicDictionary.search("hello"); // return False + magicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True + magicDictionary.search("hell"); // return False + magicDictionary.search("leetcoded"); // return False + +**Constraints:** + +* `1 <= dictionary.length <= 100` +* `1 <= dictionary[i].length <= 100` +* `dictionary[i]` consists of only lower-case English letters. +* All the strings in `dictionary` are **distinct**. +* `1 <= searchWord.length <= 100` +* `searchWord` consists of only lower-case English letters. +* `buildDict` will be called only once before `search`. +* At most `100` calls will be made to `search`. + +## Solution + +```kotlin +class MagicDictionary { + private var dictionaryWords: Array? = null + fun buildDict(dictionary: Array?) { + dictionaryWords = dictionary + } + + fun search(searchWord: String): Boolean { + for (word in dictionaryWords!!) { + if (isOffByOneLetter(word, searchWord)) { + return true + } + } + return false + } + + private fun isOffByOneLetter(word: String, searchWord: String): Boolean { + if (isDifferentLengths(word, searchWord) || word == searchWord) { + return false + } + var numDifferentLetters = 0 + for (i in word.indices) { + if (isNotTheSameLetter(word[i], searchWord[i])) { + numDifferentLetters++ + } + if (numDifferentLetters > 1) { + return false + } + } + return numDifferentLetters == 1 + } + + private fun isDifferentLengths(word: String, searchWord: String): Boolean { + return word.length != searchWord.length + } + + private fun isNotTheSameLetter(c1: Char, c2: Char): Boolean { + return c1 != c2 + } +} + +/* + * Your MagicDictionary object will be instantiated and called as such: + * var obj = MagicDictionary() + * obj.buildDict(dictionary) + * var param_2 = obj.search(searchWord) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0677_map_sum_pairs/readme.md b/src/main/kotlin/g0601_0700/s0677_map_sum_pairs/readme.md new file mode 100644 index 00000000..f25d0768 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0677_map_sum_pairs/readme.md @@ -0,0 +1,95 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 677\. Map Sum Pairs + +Medium + +Design a map that allows you to do the following: + +* Maps a string key to a given value. +* Returns the sum of the values that have a key with a prefix equal to a given string. + +Implement the `MapSum` class: + +* `MapSum()` Initializes the `MapSum` object. +* `void insert(String key, int val)` Inserts the `key-val` pair into the map. If the `key` already existed, the original `key-value` pair will be overridden to the new one. +* `int sum(string prefix)` Returns the sum of all the pairs' value whose `key` starts with the `prefix`. + +**Example 1:** + +**Input** + +["MapSum", "insert", "sum", "insert", "sum"] [[], + +["apple", 3], ["ap"], ["app", 2], ["ap"]] + +**Output:** [null, null, 3, null, 5] + +**Explanation:** + + MapSum mapSum = new MapSum(); + mapSum.insert("apple", 3); + mapSum.sum("ap"); // return 3 (apple = 3) + mapSum.insert("app", 2); + mapSum.sum("ap"); // return 5 (apple + app = 3 + 2 = 5) + +**Constraints:** + +* `1 <= key.length, prefix.length <= 50` +* `key` and `prefix` consist of only lowercase English letters. +* `1 <= val <= 1000` +* At most `50` calls will be made to `insert` and `sum`. + +## Solution + +```kotlin +class MapSum { + internal class Node { + var `val`: Int = 0 + var child: Array = arrayOfNulls(26) + } + + private val root: Node = Node() + + fun insert(key: String, `val`: Int) { + var curr: Node? = root + for (c in key.toCharArray()) { + if (curr!!.child[c.code - 'a'.code] == null) { + curr.child[c.code - 'a'.code] = Node() + } + curr = curr.child[c.code - 'a'.code] + } + curr!!.`val` = `val` + } + + private fun sumHelper(root: Node?): Int { + var o = 0 + for (i in 0..25) { + if (root!!.child[i] != null) { + o += root.child[i]!!.`val` + sumHelper(root.child[i]) + } + } + return o + } + + fun sum(prefix: String): Int { + var curr: Node? = root + for (c in prefix.toCharArray()) { + if (curr!!.child[c.code - 'a'.code] == null) { + return 0 + } + curr = curr.child[c.code - 'a'.code] + } + val sum = curr!!.`val` + return sum + sumHelper(curr) + } +} + +/* + * Your MapSum object will be instantiated and called as such: + * var obj = MapSum() + * obj.insert(key,`val`) + * var param_2 = obj.sum(prefix) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0678_valid_parenthesis_string/readme.md b/src/main/kotlin/g0601_0700/s0678_valid_parenthesis_string/readme.md new file mode 100644 index 00000000..d47ab5db --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0678_valid_parenthesis_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) + +## 678\. Valid Parenthesis String + +Medium + +Given a string `s` containing only three types of characters: `'('`, `')'` and `'*'`, return `true` _if_ `s` _is **valid**_. + +The following rules define a **valid** string: + +* Any left parenthesis `'('` must have a corresponding right parenthesis `')'`. +* Any right parenthesis `')'` must have a corresponding left parenthesis `'('`. +* Left parenthesis `'('` must go before the corresponding right parenthesis `')'`. +* `'*'` could be treated as a single right parenthesis `')'` or a single left parenthesis `'('` or an empty string `""`. + +**Example 1:** + +**Input:** s = "()" + +**Output:** true + +**Example 2:** + +**Input:** s = "(\*)" + +**Output:** true + +**Example 3:** + +**Input:** s = "(\*))" + +**Output:** true + +**Constraints:** + +* `1 <= s.length <= 100` +* `s[i]` is `'('`, `')'` or `'*'`. + +## Solution + +```kotlin +class Solution { + fun checkValidString(s: String): Boolean { + var lo = 0 + var hi = 0 + for (i in s.indices) { + lo += if (s[i] == '(') 1 else -1 + hi += if (s[i] != ')') 1 else -1 + if (hi < 0) { + break + } + lo = 0.coerceAtLeast(lo) + } + return lo == 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0679_24_game/readme.md b/src/main/kotlin/g0601_0700/s0679_24_game/readme.md new file mode 100644 index 00000000..7e59acca --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0679_24_game/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) + +## 679\. 24 Game + +Hard + +You are given an integer array `cards` of length `4`. You have four cards, each containing a number in the range `[1, 9]`. You should arrange the numbers on these cards in a mathematical expression using the operators `['+', '-', '*', '/']` and the parentheses `'('` and `')'` to get the value 24. + +You are restricted with the following rules: + +* The division operator `'/'` represents real division, not integer division. + * For example, `4 / (1 - 2 / 3) = 4 / (1 / 3) = 12`. +* Every operation done is between two numbers. In particular, we cannot use `'-'` as a unary operator. + * For example, if `cards = [1, 1, 1, 1]`, the expression `"-1 - 1 - 1 - 1"` is **not allowed**. +* You cannot concatenate numbers together + * For example, if `cards = [1, 2, 1, 2]`, the expression `"12 + 12"` is not valid. + +Return `true` if you can get such expression that evaluates to `24`, and `false` otherwise. + +**Example 1:** + +**Input:** cards = [4,1,8,7] + +**Output:** true + +**Explanation:** (8-4) \* (7-1) = 24 + +**Example 2:** + +**Input:** cards = [1,2,1,2] + +**Output:** false + +**Constraints:** + +* `cards.length == 4` +* `1 <= cards[i] <= 9` + +## Solution + +```kotlin +import java.util.Arrays +import kotlin.math.abs + +class Solution { + private fun backtrack(list: DoubleArray, n: Int): Boolean { + if (n == 1) { + return abs(list[0] - 24) < EPS + } + for (i in 0 until n) { + for (j in i + 1 until n) { + val a = list[i] + val b = list[j] + list[j] = list[n - 1] + list[i] = a + b + if (backtrack(list, n - 1)) { + return true + } + list[i] = a - b + if (backtrack(list, n - 1)) { + return true + } + list[i] = b - a + if (backtrack(list, n - 1)) { + return true + } + list[i] = a * b + if (backtrack(list, n - 1)) { + return true + } + if (Math.abs(b) > EPS) { + list[i] = a / b + if (backtrack(list, n - 1)) { + return true + } + } + if (Math.abs(a) > EPS) { + list[i] = b / a + if (backtrack(list, n - 1)) { + return true + } + } + list[i] = a + list[j] = b + } + } + return false + } + + fun judgePoint24(nums: IntArray?): Boolean { + val a = Arrays.stream(nums).asDoubleStream().toArray() + return backtrack(a, a.size) + } + + companion object { + private const val EPS = 1e-6 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0680_valid_palindrome_ii/readme.md b/src/main/kotlin/g0601_0700/s0680_valid_palindrome_ii/readme.md new file mode 100644 index 00000000..6857fe7b --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0680_valid_palindrome_ii/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) + +## 680\. Valid Palindrome II + +Easy + +Given a string `s`, return `true` _if the_ `s` _can be palindrome after deleting **at most one** character from it_. + +**Example 1:** + +**Input:** s = "aba" + +**Output:** true + +**Example 2:** + +**Input:** s = "abca" + +**Output:** true + +**Explanation:** You could delete the character 'c'. + +**Example 3:** + +**Input:** s = "abc" + +**Output:** false + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun validPalindrome(s: String): Boolean { + var l = 0 + var r = s.length - 1 + while (l < r) { + if (s[l] != s[r]) { + return isPalindrome(s.substring(l + 1, r + 1)) || isPalindrome(s.substring(l, r)) + } + l++ + r-- + } + return true + } + + private fun isPalindrome(s: String): Boolean { + var l = 0 + var r = s.length - 1 + while (l < r) { + if (s[l] != s[r]) { + return false + } + l++ + r-- + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0682_baseball_game/readme.md b/src/main/kotlin/g0601_0700/s0682_baseball_game/readme.md new file mode 100644 index 00000000..8225c6d2 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0682_baseball_game/readme.md @@ -0,0 +1,86 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 682\. Baseball Game + +Easy + +You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores. + +At the beginning of the game, you start with an empty record. You are given a list of strings `ops`, where `ops[i]` is the ith operation you must apply to the record and is one of the following: + +1. An integer `x` - Record a new score of `x`. +2. `"+"` - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores. +3. `"D"` - Record a new score that is double the previous score. It is guaranteed there will always be a previous score. +4. `"C"` - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score. + +Return _the sum of all the scores on the record_. + +**Example 1:** + +**Input:** ops = ["5","2","C","D","+"] + +**Output:** 30 + +**Explanation:** + + "5" - Add 5 to the record, record is now [5]. + "2" - Add 2 to the record, record is now [5, 2]. + "C" - Invalidate and remove the previous score, record is now [5]. + "D" - Add 2 \* 5 = 10 to the record, record is now [5, 10]. + "+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15]. + The total sum is 5 + 10 + 15 = 30. + +**Example 2:** + +**Input:** ops = ["5","-2","4","C","D","9","+","+"] + +**Output:** 27 + +**Explanation:** + + "5" - Add 5 to the record, record is now [5]. + "-2" - Add -2 to the record, record is now [5, -2]. + "4" - Add 4 to the record, record is now [5, -2, 4]. + "C" - Invalidate and remove the previous score, record is now [5, -2]. + "D" - Add 2 \* -2 = -4 to the record, record is now [5, -2, -4]. + "9" - Add 9 to the record, record is now [5, -2, -4, 9]. + "+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5]. + "+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14]. + The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27. + +**Example 3:** + +**Input:** ops = ["1"] + +**Output:** 1 + +**Constraints:** + +* `1 <= ops.length <= 1000` +* `ops[i]` is `"C"`, `"D"`, `"+"`, or a string representing an integer in the range [-3 * 104, 3 * 104]. +* For operation `"+"`, there will always be at least two previous scores on the record. +* For operations `"C"` and `"D"`, there will always be at least one previous score on the record. + +## Solution + +```kotlin +class Solution { + fun calPoints(ops: Array): Int { + val resultList: MutableList = ArrayList(ops.size) + for (op in ops) { + val size = resultList.size + if ("C" == op) { + resultList.removeAt(size - 1) + } else if ("D" == op) { + resultList.add(resultList[size - 1] * 2) + } else if ("+" == op) { + resultList.add(resultList[size - 1] + resultList[size - 2]) + } else { + resultList.add(op.toInt()) + } + } + return resultList.stream().reduce(0) { a: Int, b: Int -> Integer.sum(a, b) } + } +} +``` \ No newline at end of file