diff --git a/README.md b/README.md index 9ecf2b18..4259860b 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,6 @@ [![](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) > ["For coding interview preparation, LeetCode is one of the best online resource providing a rich library of more than 300 real coding interview questions for you to practice from using one of the 7 supported languages - C, C++, Java, Python, C#, JavaScript, Ruby."](https://www.quora.com/How-effective-is-Leetcode-for-preparing-for-technical-interviews) -* [SQL I](#sql-i) * [Level 1](#level-1) * [Level 2](#level-2) * [Udemy](#udemy) @@ -16,71 +15,7 @@ * [Programming Skills I](#programming-skills-i) * [Programming Skills II](#programming-skills-ii) * [Graph Theory I](#graph-theory-i) - -### SQL I - -#### Day 1 Select - -| | | | | | -|-|-|-|-|-|- -| 0595 |[Big Countries](src/main/kotlin/g0501_0600/s0595_big_countries)| Easy | Database | 417 | 56.09 -| 0584 |[Find Customer Referee](src/main/kotlin/g0501_0600/s0584_find_customer_referee)| Easy | Database | 779 | 43.48 -| 0183 |[Customers Who Never Order](src/main/kotlin/g0101_0200/s0183_customers_who_never_order)| Easy | Database | 712 | 33.67 - -#### Day 2 Select and Order - -| | | | | | -|-|-|-|-|-|- -| 0627 |[Swap Salary](src/main/kotlin/g0601_0700/s0627_swap_salary)| Easy | Database | 400 | 51.04 -| 0196 |[Delete Duplicate Emails](src/main/kotlin/g0101_0200/s0196_delete_duplicate_emails)| Easy | Database | 593 | 94.17 - -#### Day 3 String Processing Functions - -| | | | | | -|-|-|-|-|-|- - -#### Day 4 Union and Select - -| | | | | | -|-|-|-|-|-|- -| 0608 |[Tree Node](src/main/kotlin/g0601_0700/s0608_tree_node)| Medium | LeetCode_Curated_SQL_70, Database | 794 | 48.38 -| 0176 |[Second Highest Salary](src/main/kotlin/g0101_0200/s0176_second_highest_salary)| Medium | Database | 219 | 92.54 - -#### Day 5 Union - -| | | | | | -|-|-|-|-|-|- -| 0175 |[Combine Two Tables](src/main/kotlin/g0101_0200/s0175_combine_two_tables)| Easy | Database | 473 | 54.97 - -#### Day 6 Union - -| | | | | | -|-|-|-|-|-|- -| 0197 |[Rising Temperature](src/main/kotlin/g0101_0200/s0197_rising_temperature)| Easy | Database | 394 | 94.15 -| 0607 |[Sales Person](src/main/kotlin/g0601_0700/s0607_sales_person)| Easy | LeetCode_Curated_SQL_70, Database | 2142 | 44.56 - -#### Day 7 Function - -| | | | | | -|-|-|-|-|-|- - -#### Day 8 Function - -| | | | | | -|-|-|-|-|-|- -| 0586 |[Customer Placing the Largest Number of Orders](src/main/kotlin/g0501_0600/s0586_customer_placing_the_largest_number_of_orders)| Easy | LeetCode_Curated_SQL_70, Database | 768 | 44.85 -| 0511 |[Game Play Analysis I](src/main/kotlin/g0501_0600/s0511_game_play_analysis_i)| Easy | LeetCode_Curated_SQL_70, Database | 790 | 45.04 - -#### Day 9 Control of Flow - -| | | | | | -|-|-|-|-|-|- - -#### Day 10 Where - -| | | | | | -|-|-|-|-|-|- -| 0182 |[Duplicate Emails](src/main/kotlin/g0101_0200/s0182_duplicate_emails)| Easy | Database | 396 | 68.40 +* [SQL I](#sql-i) ### Level 1 @@ -323,6 +258,7 @@ | | | | | | |-|-|-|-|-|- | 0547 |[Number of Provinces](src/main/kotlin/g0501_0600/s0547_number_of_provinces)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 229 | 79.73 +| 0947 |[Most Stones Removed with Same Row or Column](src/main/kotlin/g0901_1000/s0947_most_stones_removed_with_same_row_or_column)| Medium | Depth_First_Search, Graph, Union_Find | 200 | 100.00 #### Day 20 Brute Force/Backtracking @@ -460,6 +396,7 @@ | 0103 |[Binary Tree Zigzag Level Order Traversal](src/main/kotlin/g0101_0200/s0103_binary_tree_zigzag_level_order_traversal)| Medium | Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 316 | 34.25 | 0108 |[Convert Sorted Array to Binary Search Tree](src/main/kotlin/g0101_0200/s0108_convert_sorted_array_to_binary_search_tree)| Easy | Top_Interview_Questions, Array, Tree, Binary_Tree, Binary_Search_Tree, Divide_and_Conquer | 334 | 35.39 | 0543 |[Diameter of Binary Tree](src/main/kotlin/g0501_0600/s0543_diameter_of_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree | 307 | 43.93 +| 0938 |[Range Sum of BST](src/main/kotlin/g0901_1000/s0938_range_sum_of_bst)| Easy | Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 356 | 55.36 | 0100 |[Same Tree](src/main/kotlin/g0001_0100/s0100_same_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 208 | 72.24 | 0226 |[Invert Binary Tree](src/main/kotlin/g0201_0300/s0226_invert_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 233 | 54.90 | 0111 |[Minimum Depth of Binary Tree](src/main/kotlin/g0101_0200/s0111_minimum_depth_of_binary_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 525 | 90.51 @@ -1333,6 +1270,7 @@ | | | | | | |-|-|-|-|-|- +| 0931 |[Minimum Falling Path Sum](src/main/kotlin/g0901_1000/s0931_minimum_falling_path_sum)| Medium | Array, Dynamic_Programming, Matrix | 201 | 84.21 | 0120 |[Triangle](src/main/kotlin/g0101_0200/s0120_triangle)| Medium | Array, Dynamic_Programming | 194 | 97.87 #### Day 14 @@ -1446,6 +1384,7 @@ | | | | | | |-|-|-|-|-|- | 0709 |[To Lower Case](src/main/kotlin/g0701_0800/s0709_to_lower_case)| Easy | String | 142 | 98.68 +| 0953 |[Verifying an Alien Dictionary](src/main/kotlin/g0901_1000/s0953_verifying_an_alien_dictionary)| Easy | Array, String, Hash_Table | 137 | 100.00 #### Day 10 Linked List and Tree @@ -1640,6 +1579,7 @@ | | | | | | |-|-|-|-|-|- +| 0934 |[Shortest Bridge](src/main/kotlin/g0901_1000/s0934_shortest_bridge)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix | 301 | 80.95 #### Day 7 Standard Traversal @@ -1692,12 +1632,109 @@ | 0886 |[Possible Bipartition](src/main/kotlin/g0801_0900/s0886_possible_bipartition)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 397 | 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 | 215 | 82.35 +### SQL I + +#### Day 1 Select + +| | | | | | +|-|-|-|-|-|- +| 0595 |[Big Countries](src/main/kotlin/g0501_0600/s0595_big_countries)| Easy | Database | 417 | 56.09 +| 0584 |[Find Customer Referee](src/main/kotlin/g0501_0600/s0584_find_customer_referee)| Easy | Database | 779 | 43.48 +| 0183 |[Customers Who Never Order](src/main/kotlin/g0101_0200/s0183_customers_who_never_order)| Easy | Database | 712 | 33.67 + +#### Day 2 Select and Order + +| | | | | | +|-|-|-|-|-|- +| 0627 |[Swap Salary](src/main/kotlin/g0601_0700/s0627_swap_salary)| Easy | Database | 400 | 51.04 +| 0196 |[Delete Duplicate Emails](src/main/kotlin/g0101_0200/s0196_delete_duplicate_emails)| Easy | Database | 593 | 94.17 + +#### Day 3 String Processing Functions + +| | | | | | +|-|-|-|-|-|- + +#### Day 4 Union and Select + +| | | | | | +|-|-|-|-|-|- +| 0608 |[Tree Node](src/main/kotlin/g0601_0700/s0608_tree_node)| Medium | LeetCode_Curated_SQL_70, Database | 794 | 48.38 +| 0176 |[Second Highest Salary](src/main/kotlin/g0101_0200/s0176_second_highest_salary)| Medium | Database | 219 | 92.54 + +#### Day 5 Union + +| | | | | | +|-|-|-|-|-|- +| 0175 |[Combine Two Tables](src/main/kotlin/g0101_0200/s0175_combine_two_tables)| Easy | Database | 473 | 54.97 + +#### Day 6 Union + +| | | | | | +|-|-|-|-|-|- +| 0197 |[Rising Temperature](src/main/kotlin/g0101_0200/s0197_rising_temperature)| Easy | Database | 394 | 94.15 +| 0607 |[Sales Person](src/main/kotlin/g0601_0700/s0607_sales_person)| Easy | LeetCode_Curated_SQL_70, Database | 2142 | 44.56 + +#### Day 7 Function + +| | | | | | +|-|-|-|-|-|- + +#### Day 8 Function + +| | | | | | +|-|-|-|-|-|- +| 0586 |[Customer Placing the Largest Number of Orders](src/main/kotlin/g0501_0600/s0586_customer_placing_the_largest_number_of_orders)| Easy | LeetCode_Curated_SQL_70, Database | 768 | 44.85 +| 0511 |[Game Play Analysis I](src/main/kotlin/g0501_0600/s0511_game_play_analysis_i)| Easy | LeetCode_Curated_SQL_70, Database | 790 | 45.04 + +#### Day 9 Control of Flow + +| | | | | | +|-|-|-|-|-|- + +#### Day 10 Where + +| | | | | | +|-|-|-|-|-|- +| 0182 |[Duplicate Emails](src/main/kotlin/g0101_0200/s0182_duplicate_emails)| Easy | Database | 396 | 68.40 + ## Algorithms | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- | 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 +| 0959 |[Regions Cut By Slashes](src/main/kotlin/g0901_1000/s0959_regions_cut_by_slashes)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 180 | 100.00 +| 0958 |[Check Completeness of a Binary Tree](src/main/kotlin/g0901_1000/s0958_check_completeness_of_a_binary_tree)| Medium | Breadth_First_Search, Tree, Binary_Tree | 142 | 96.04 +| 0957 |[Prison Cells After N Days](src/main/kotlin/g0901_1000/s0957_prison_cells_after_n_days)| Medium | Array, Hash_Table, Math, Bit_Manipulation | 172 | 100.00 +| 0956 |[Tallest Billboard](src/main/kotlin/g0901_1000/s0956_tallest_billboard)| Hard | Array, Dynamic_Programming | 182 | 100.00 +| 0955 |[Delete Columns to Make Sorted II](src/main/kotlin/g0901_1000/s0955_delete_columns_to_make_sorted_ii)| Medium | Array, String, Greedy | 190 | 100.00 +| 0954 |[Array of Doubled Pairs](src/main/kotlin/g0901_1000/s0954_array_of_doubled_pairs)| Medium | Array, Hash_Table, Sorting, Greedy | 462 | 100.00 +| 0953 |[Verifying an Alien Dictionary](src/main/kotlin/g0901_1000/s0953_verifying_an_alien_dictionary)| Easy | Array, String, Hash_Table, Programming_Skills_I_Day_9_String | 137 | 100.00 +| 0952 |[Largest Component Size by Common Factor](src/main/kotlin/g0901_1000/s0952_largest_component_size_by_common_factor)| Hard | Array, Math, Union_Find | 538 | 100.00 +| 0951 |[Flip Equivalent Binary Trees](src/main/kotlin/g0901_1000/s0951_flip_equivalent_binary_trees)| Medium | Depth_First_Search, Tree, Binary_Tree | 150 | 100.00 +| 0950 |[Reveal Cards In Increasing Order](src/main/kotlin/g0901_1000/s0950_reveal_cards_in_increasing_order)| Medium | Array, Sorting, Simulation, Queue | 176 | 100.00 +| 0949 |[Largest Time for Given Digits](src/main/kotlin/g0901_1000/s0949_largest_time_for_given_digits)| Medium | String, Enumeration | 171 | 100.00 +| 0948 |[Bag of Tokens](src/main/kotlin/g0901_1000/s0948_bag_of_tokens)| Medium | Array, Sorting, Greedy, Two_Pointers | 161 | 100.00 +| 0947 |[Most Stones Removed with Same Row or Column](src/main/kotlin/g0901_1000/s0947_most_stones_removed_with_same_row_or_column)| Medium | Depth_First_Search, Graph, Union_Find, Level_2_Day_19_Union_Find | 200 | 100.00 +| 0946 |[Validate Stack Sequences](src/main/kotlin/g0901_1000/s0946_validate_stack_sequences)| Medium | Array, Stack, Simulation | 180 | 74.91 +| 0945 |[Minimum Increment to Make Array Unique](src/main/kotlin/g0901_1000/s0945_minimum_increment_to_make_array_unique)| Medium | Array, Sorting, Greedy, Counting | 427 | 100.00 +| 0944 |[Delete Columns to Make Sorted](src/main/kotlin/g0901_1000/s0944_delete_columns_to_make_sorted)| Easy | Array, String | 221 | 75.00 +| 0943 |[Find the Shortest Superstring](src/main/kotlin/g0901_1000/s0943_find_the_shortest_superstring)| Hard | Array, String, Dynamic_Programming, Bit_Manipulation, Bitmask | 1290 | 100.00 +| 0942 |[DI String Match](src/main/kotlin/g0901_1000/s0942_di_string_match)| Easy | Array, String, Math, Greedy, Two_Pointers | 202 | 80.00 +| 0941 |[Valid Mountain Array](src/main/kotlin/g0901_1000/s0941_valid_mountain_array)| Easy | Array | 251 | 51.94 +| 0940 |[Distinct Subsequences II](src/main/kotlin/g0901_1000/s0940_distinct_subsequences_ii)| Hard | String, Dynamic_Programming | 177 | 100.00 +| 0939 |[Minimum Area Rectangle](src/main/kotlin/g0901_1000/s0939_minimum_area_rectangle)| Medium | Array, Hash_Table, Math, Sorting, Geometry | 461 | 100.00 +| 0938 |[Range Sum of BST](src/main/kotlin/g0901_1000/s0938_range_sum_of_bst)| Easy | Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree, Udemy_Tree_Stack_Queue | 356 | 55.36 +| 0937 |[Reorder Data in Log Files](src/main/kotlin/g0901_1000/s0937_reorder_data_in_log_files)| Easy | Array, String, Sorting | 205 | 81.82 +| 0936 |[Stamping The Sequence](src/main/kotlin/g0901_1000/s0936_stamping_the_sequence)| Hard | String, Greedy, Stack, Queue | 196 | 100.00 +| 0935 |[Knight Dialer](src/main/kotlin/g0901_1000/s0935_knight_dialer)| Medium | Dynamic_Programming | 160 | 100.00 +| 0934 |[Shortest Bridge](src/main/kotlin/g0901_1000/s0934_shortest_bridge)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Graph_Theory_I_Day_6_Matrix_Related_Problems | 301 | 80.95 +| 0933 |[Number of Recent Calls](src/main/kotlin/g0901_1000/s0933_number_of_recent_calls)| Easy | Design, Queue, Data_Stream | 476 | 82.50 +| 0932 |[Beautiful Array](src/main/kotlin/g0901_1000/s0932_beautiful_array)| Medium | Array, Math, Divide_and_Conquer | 145 | 100.00 +| 0931 |[Minimum Falling Path Sum](src/main/kotlin/g0901_1000/s0931_minimum_falling_path_sum)| Medium | Array, Dynamic_Programming, Matrix, Dynamic_Programming_I_Day_13 | 201 | 84.21 +| 0930 |[Binary Subarrays With Sum](src/main/kotlin/g0901_1000/s0930_binary_subarrays_with_sum)| Medium | Array, Hash_Table, Prefix_Sum, Sliding_Window | 250 | 93.75 +| 0929 |[Unique Email Addresses](src/main/kotlin/g0901_1000/s0929_unique_email_addresses)| Easy | Array, String, Hash_Table | 207 | 89.29 +| 0928 |[Minimize Malware Spread II](src/main/kotlin/g0901_1000/s0928_minimize_malware_spread_ii)| Hard | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 716 | 100.00 | 0927 |[Three Equal Parts](src/main/kotlin/g0901_1000/s0927_three_equal_parts)| Hard | Array, Math | 303 | 100.00 | 0926 |[Flip String to Monotone Increasing](src/main/kotlin/g0901_1000/s0926_flip_string_to_monotone_increasing)| Medium | String, Dynamic_Programming | 199 | 100.00 | 0925 |[Long Pressed Name](src/main/kotlin/g0901_1000/s0925_long_pressed_name)| Easy | String, Two_Pointers | 126 | 92.31 diff --git a/src/main/kotlin/g0201_0300/s0211_design_add_and_search_words_data_structure/readme.md b/src/main/kotlin/g0201_0300/s0211_design_add_and_search_words_data_structure/readme.md index d7ce0cea..f3b0b293 100644 --- a/src/main/kotlin/g0201_0300/s0211_design_add_and_search_words_data_structure/readme.md +++ b/src/main/kotlin/g0201_0300/s0211_design_add_and_search_words_data_structure/readme.md @@ -66,16 +66,16 @@ class WordDictionary { fun dfs(p: TrieNode?, start: Int): Boolean { if (p == null) return false if (start == word.length) return p.isWord - if (word[start] == '.') { + return if (word[start] == '.') { for (i in 0..25) { if (dfs(p.children[i], start + 1)) { return true } } - return false + false } else { val i = word[start] - 'a' - return dfs(p.children[i], start + 1) + dfs(p.children[i], start + 1) } } return dfs(trieTree, 0) diff --git a/src/main/kotlin/g0301_0400/s0347_top_k_frequent_elements/readme.md b/src/main/kotlin/g0301_0400/s0347_top_k_frequent_elements/readme.md index 17f34bb2..e554c523 100644 --- a/src/main/kotlin/g0301_0400/s0347_top_k_frequent_elements/readme.md +++ b/src/main/kotlin/g0301_0400/s0347_top_k_frequent_elements/readme.md @@ -34,6 +34,7 @@ Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequen import java.util.PriorityQueue import java.util.Queue +@Suppress("kotlin:S6518") class Solution { fun topKFrequent(nums: IntArray, k: Int): IntArray { nums.sort() diff --git a/src/main/kotlin/g0301_0400/s0381_insert_delete_getrandom_o1_duplicates_allowed/readme.md b/src/main/kotlin/g0301_0400/s0381_insert_delete_getrandom_o1_duplicates_allowed/readme.md index 0189e121..20bf0fb9 100644 --- a/src/main/kotlin/g0301_0400/s0381_insert_delete_getrandom_o1_duplicates_allowed/readme.md +++ b/src/main/kotlin/g0301_0400/s0381_insert_delete_getrandom_o1_duplicates_allowed/readme.md @@ -62,13 +62,13 @@ class RandomizedCollection() { fun insert(x: Int): Boolean { a2m.add(x) val pos = a2m.size - 1 - if (x in m2a) { + return if (x in m2a) { m2a[x]!!.add(pos) - return false + false } else { m2a[x] = HashSet() m2a[x]!!.add(pos) - return true + true } } diff --git a/src/main/kotlin/g0301_0400/s0399_evaluate_division/readme.md b/src/main/kotlin/g0301_0400/s0399_evaluate_division/readme.md index 5cb92eb4..62768ca3 100644 --- a/src/main/kotlin/g0301_0400/s0399_evaluate_division/readme.md +++ b/src/main/kotlin/g0301_0400/s0399_evaluate_division/readme.md @@ -48,9 +48,11 @@ Return _the answers to all queries_. If a single answer cannot be determined, re ## Solution ```kotlin +@Suppress("kotlin:S6518") class Solution { private var root: MutableMap? = null private var rate: MutableMap? = null + fun calcEquation( equations: List>, values: DoubleArray, diff --git a/src/main/kotlin/g0501_0600/s0508_most_frequent_subtree_sum/readme.md b/src/main/kotlin/g0501_0600/s0508_most_frequent_subtree_sum/readme.md index 83b55b0b..d06a1f93 100644 --- a/src/main/kotlin/g0501_0600/s0508_most_frequent_subtree_sum/readme.md +++ b/src/main/kotlin/g0501_0600/s0508_most_frequent_subtree_sum/readme.md @@ -58,12 +58,12 @@ class Solution { } private fun treeSum(node: TreeNode?): Int { - if (node == null) { - return 0 + return if (node == null) { + 0 } else { val sum = node.`val` + treeSum(node.left) + treeSum(node.right) cache[sum] = cache.getOrDefault(sum, 0) + 1 - return sum + sum } } } diff --git a/src/main/kotlin/g0601_0700/s0641_design_circular_deque/readme.md b/src/main/kotlin/g0601_0700/s0641_design_circular_deque/readme.md index 3a99cc89..365773b4 100644 --- a/src/main/kotlin/g0601_0700/s0641_design_circular_deque/readme.md +++ b/src/main/kotlin/g0601_0700/s0641_design_circular_deque/readme.md @@ -60,6 +60,7 @@ myCircularDeque.getFront(); // return 4 ## Solution ```kotlin +@Suppress("kotlin:S6512") class MyCircularDeque(k: Int) { private val data: IntArray private var front: Int diff --git a/src/main/kotlin/g0601_0700/s0692_top_k_frequent_words/readme.md b/src/main/kotlin/g0601_0700/s0692_top_k_frequent_words/readme.md index dabda6cf..a16ce7f7 100644 --- a/src/main/kotlin/g0601_0700/s0692_top_k_frequent_words/readme.md +++ b/src/main/kotlin/g0601_0700/s0692_top_k_frequent_words/readme.md @@ -50,10 +50,10 @@ class Solution { } val sortedset: SortedSet> = TreeSet( java.util.Comparator { (key, value): Map.Entry, (key1, value1): Map.Entry -> - if (value != value1) { - return@Comparator value1 - value + return@Comparator if (value != value1) { + value1 - value } else { - return@Comparator key.compareTo(key1, ignoreCase = true) + key.compareTo(key1, ignoreCase = true) } } ) diff --git a/src/main/kotlin/g0801_0900/s0843_guess_the_word/readme.md b/src/main/kotlin/g0801_0900/s0843_guess_the_word/readme.md index 906b6bdb..f48324c7 100644 --- a/src/main/kotlin/g0801_0900/s0843_guess_the_word/readme.md +++ b/src/main/kotlin/g0801_0900/s0843_guess_the_word/readme.md @@ -56,7 +56,7 @@ For each test case, you have exactly `10` guesses to guess the word. At the end * } */ class Solution { - interface Master { + fun interface Master { fun guess(word: String): Int } diff --git a/src/main/kotlin/g0901_1000/s0928_minimize_malware_spread_ii/readme.md b/src/main/kotlin/g0901_1000/s0928_minimize_malware_spread_ii/readme.md new file mode 100644 index 00000000..1a46ed2a --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0928_minimize_malware_spread_ii/readme.md @@ -0,0 +1,112 @@ +[![](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) + +## 928\. Minimize Malware Spread II + +Hard + +You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the ith node is directly connected to the jth node if `graph[i][j] == 1`. + +Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. + +Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. + +We will remove **exactly one node** from `initial`, **completely removing it and any connections from this node to any other node**. + +Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**. + +**Example 1:** + +**Input:** graph = \[\[1,1,0],[1,1,0],[0,0,1]], initial = [0,1] + +**Output:** 0 + +**Example 2:** + +**Input:** graph = \[\[1,1,0],[1,1,1],[0,1,1]], initial = [0,1] + +**Output:** 1 + +**Example 3:** + +**Input:** graph = \[\[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1] + +**Output:** 1 + +**Constraints:** + +* `n == graph.length` +* `n == graph[i].length` +* `2 <= n <= 300` +* `graph[i][j]` is `0` or `1`. +* `graph[i][j] == graph[j][i]` +* `graph[i][i] == 1` +* `1 <= initial.length < n` +* `0 <= initial[i] <= n - 1` +* All the integers in `initial` are **unique**. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + private val adj: MutableMap> = HashMap() + private var visited: MutableSet? = null + private var count = 0 + + private fun bfs(ind: Int, initial: IntArray) { + val q: Queue = LinkedList() + for (i in initial.indices) { + if (i != ind) { + q.add(initial[i]) + visited!!.add(initial[i]) + } + } + while (!q.isEmpty()) { + val curr = q.poll() + if (curr != initial[ind]) { + count++ + } + val children = adj[curr] + if (children != null) { + for (child in children) { + if (!visited!!.contains(child)) { + q.add(child) + visited!!.add(child) + } + } + } + } + } + + fun minMalwareSpread(graph: Array, initial: IntArray): Int { + val n = graph.size + for (i in 0 until n) { + adj.putIfAbsent(i, ArrayList()) + for (j in 0 until n) { + if (graph[i][j] == 1) { + adj[i]!!.add(j) + } + } + } + var min = n + 1 + initial.sort() + var node = initial[0] + for (i in initial.indices) { + visited = HashSet() + val children = adj[initial[i]]!! + adj.remove(initial[i]) + bfs(i, initial) + if (count < min) { + min = count + node = initial[i] + } + count = 0 + adj[initial[i]] = children + } + return node + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0929_unique_email_addresses/readme.md b/src/main/kotlin/g0901_1000/s0929_unique_email_addresses/readme.md new file mode 100644 index 00000000..fbac8a04 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0929_unique_email_addresses/readme.md @@ -0,0 +1,74 @@ +[![](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) + +## 929\. Unique Email Addresses + +Easy + +Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. + +* For example, in `"alice@leetcode.com"`, `"alice"` is the **local name**, and `"leetcode.com"` is the **domain name**. + +If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. + +* For example, `"alice.z@leetcode.com"` and `"alicez@leetcode.com"` forward to the same email address. + +If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. + +* For example, `"m.y+name@email.com"` will be forwarded to `"my@email.com"`. + +It is possible to use both of these rules at the same time. + +Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. + +**Example 1:** + +**Input:** emails = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"] + +**Output:** 2 + +**Explanation:** "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails. + +**Example 2:** + +**Input:** emails = ["a@leetcode.com","b@leetcode.com","c@leetcode.com"] + +**Output:** 3 + +**Constraints:** + +* `1 <= emails.length <= 100` +* `1 <= emails[i].length <= 100` +* `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. +* Each `emails[i]` contains exactly one `'@'` character. +* All local and domain names are non-empty. +* Local names do not start with a `'+'` character. +* Domain names end with the `".com"` suffix. + +## Solution + +```kotlin +class Solution { + fun numUniqueEmails(emails: Array): Int { + val set: MutableSet = HashSet() + for (s in emails) { + val sb = StringBuilder() + var i = 0 + while (i < s.length) { + val c = s[i] + if (c == '+' || c == '@') { + sb.append('@') + i = s.indexOf("@") + 1 + sb.append(s.substring(i)) + break + } else if (c != '.') { + sb.append(c) + } + i++ + } + set.add(sb.toString()) + } + return set.size + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0930_binary_subarrays_with_sum/readme.md b/src/main/kotlin/g0901_1000/s0930_binary_subarrays_with_sum/readme.md new file mode 100644 index 00000000..1ef34672 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0930_binary_subarrays_with_sum/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) + +## 930\. Binary Subarrays With Sum + +Medium + +Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`. + +A **subarray** is a contiguous part of the array. + +**Example 1:** + +**Input:** nums = [1,0,1,0,1], goal = 2 + +**Output:** 4 + +**Explanation:** The 4 subarrays are bolded and underlined below: + +[**1,0,1**,0,1] + +[**1,0,1,0**,1] + +[1,**0,1,0,1**] + +[1,0,**1,0,1**] + +**Example 2:** + +**Input:** nums = [0,0,0,0,0], goal = 0 + +**Output:** 15 + +**Constraints:** + +* 1 <= nums.length <= 3 * 104 +* `nums[i]` is either `0` or `1`. +* `0 <= goal <= nums.length` + +## Solution + +```kotlin +class Solution { + fun numSubarraysWithSum(nums: IntArray, goal: Int): Int { + return atmostK(nums, goal) - atmostK(nums, goal - 1) + } + + fun atmostK(arr: IntArray, k: Int): Int { + var cnt = 0 + var i = 0 + var j = 0 + var sum = 0 + while (j < arr.size) { + sum += arr[j] + if (sum > k) { + while (i <= j && sum > k) { + sum -= arr[i] + i++ + } + } + cnt += j - i + 1 + j++ + } + return cnt + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0931_minimum_falling_path_sum/readme.md b/src/main/kotlin/g0901_1000/s0931_minimum_falling_path_sum/readme.md new file mode 100644 index 00000000..ce695e0b --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0931_minimum_falling_path_sum/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) + +## 931\. Minimum Falling Path Sum + +Medium + +Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`. + +A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(row, col)` will be `(row + 1, col - 1)`, `(row + 1, col)`, or `(row + 1, col + 1)`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/11/03/failing1-grid.jpg) + +**Input:** matrix = \[\[2,1,3],[6,5,4],[7,8,9]] + +**Output:** 13 + +**Explanation:** There are two falling paths with a minimum sum as shown. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/11/03/failing2-grid.jpg) + +**Input:** matrix = \[\[-19,57],[-40,-5]] + +**Output:** -59 + +**Explanation:** The falling path with a minimum sum is shown. + +**Constraints:** + +* `n == matrix.length == matrix[i].length` +* `1 <= n <= 100` +* `-100 <= matrix[i][j] <= 100` + +## Solution + +```kotlin +class Solution { + fun minFallingPathSum(matrix: Array): Int { + val l = matrix[0].size + var arr = matrix[0] + for (i in 1 until matrix.size) { + val cur = IntArray(l) + for (j in 0 until l) { + var left = Int.MAX_VALUE + var right = Int.MAX_VALUE + val curCell = arr[j] + if (j > 0) { + left = arr[j - 1] + } + if (j < l - 1) { + right = arr[j + 1] + } + cur[j] = matrix[i][j] + left.coerceAtMost(right.coerceAtMost(curCell)) + } + arr = cur + } + var min = Int.MAX_VALUE + for (i in 0 until l) { + if (arr[i] < min) { + min = arr[i] + } + } + return min + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0932_beautiful_array/readme.md b/src/main/kotlin/g0901_1000/s0932_beautiful_array/readme.md new file mode 100644 index 00000000..bdc6cc4d --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0932_beautiful_array/readme.md @@ -0,0 +1,63 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 932\. Beautiful Array + +Medium + +An array `nums` of length `n` is **beautiful** if: + +* `nums` is a permutation of the integers in the range `[1, n]`. +* For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`. + +Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There will be at least one valid answer for the given `n`. + +**Example 1:** + +**Input:** n = 4 + +**Output:** [2,1,4,3] + +**Example 2:** + +**Input:** n = 5 + +**Output:** [3,1,2,5,4] + +**Constraints:** + +* `1 <= n <= 1000` + +## Solution + +```kotlin +class Solution { + private var memo: MutableMap? = null + fun beautifulArray(n: Int): IntArray? { + memo = HashMap() + return helper(n) + } + + private fun helper(n: Int): IntArray? { + if (n == 1) { + memo!![1] = intArrayOf(1) + return intArrayOf(1) + } + if (memo!!.containsKey(n)) { + return memo!![n] + } + val mid = (n + 1) / 2 + val left = helper(mid) + val right = helper(n - mid) + val rst = IntArray(n) + for (i in 0 until mid) { + rst[i] = left!![i] * 2 - 1 + } + for (i in mid until n) { + rst[i] = right!![i - mid] * 2 + } + memo!![n] = rst + return rst + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0933_number_of_recent_calls/readme.md b/src/main/kotlin/g0901_1000/s0933_number_of_recent_calls/readme.md new file mode 100644 index 00000000..7c0db7e4 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0933_number_of_recent_calls/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) + +## 933\. Number of Recent Calls + +Easy + +You have a `RecentCounter` class which counts the number of recent requests within a certain time frame. + +Implement the `RecentCounter` class: + +* `RecentCounter()` Initializes the counter with zero recent requests. +* `int ping(int t)` Adds a new request at time `t`, where `t` represents some time in milliseconds, and returns the number of requests that has happened in the past `3000` milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range `[t - 3000, t]`. + +It is **guaranteed** that every call to `ping` uses a strictly larger value of `t` than the previous call. + +**Example 1:** + +**Input** ["RecentCounter", "ping", "ping", "ping", "ping"] [[], [1], [100], [3001], [3002]] + +**Output:** [null, 1, 2, 3, 3] + +**Explanation:** + +RecentCounter recentCounter = new RecentCounter(); + +recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1 + +recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2 + +recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3 + +recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3 + +**Constraints:** + +* 1 <= t <= 109 +* Each test case will call `ping` with **strictly increasing** values of `t`. +* At most 104 calls will be made to `ping`. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class RecentCounter { + private val q: Queue + + init { + q = LinkedList() + } + + fun ping(t: Int): Int { + q.offer(t) + val min = t - 3000 + while (min > q.peek()) { + q.poll() + } + return q.size + } +} + +/* + * Your RecentCounter object will be instantiated and called as such: + * var obj = RecentCounter() + * var param_1 = obj.ping(t) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0934_shortest_bridge/readme.md b/src/main/kotlin/g0901_1000/s0934_shortest_bridge/readme.md new file mode 100644 index 00000000..3d902658 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0934_shortest_bridge/readme.md @@ -0,0 +1,107 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 934\. Shortest Bridge + +Medium + +You are given an `n x n` binary matrix `grid` where `1` represents land and `0` represents water. + +An **island** is a 4-directionally connected group of `1`'s not connected to any other `1`'s. There are **exactly two islands** in `grid`. + +You may change `0`'s to `1`'s to connect the two islands to form **one island**. + +Return _the smallest number of_ `0`_'s you must flip to connect the two islands_. + +**Example 1:** + +**Input:** grid = \[\[0,1],[1,0]] + +**Output:** 1 + +**Example 2:** + +**Input:** grid = \[\[0,1,0],[0,0,0],[0,0,1]] + +**Output:** 2 + +**Example 3:** + +**Input:** grid = \[\[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]] + +**Output:** 1 + +**Constraints:** + +* `n == grid.length == grid[i].length` +* `2 <= n <= 100` +* `grid[i][j]` is either `0` or `1`. +* There are exactly two islands in `grid`. + +## Solution + +```kotlin +class Solution { + private class Pair(var x: Int, var y: Int) + + private val dirs = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(-1, 0), intArrayOf(0, -1)) + + fun shortestBridge(grid: Array): Int { + val q: ArrayDeque = ArrayDeque() + var flag = false + val visited = Array(grid.size) { + BooleanArray( + grid[0].size + ) + } + var i = 0 + while (i < grid.size && !flag) { + var j = 0 + while (j < grid[i].size && !flag) { + if (grid[i][j] == 1) { + dfs(grid, i, j, visited, q) + flag = true + } + j++ + } + i++ + } + var level = -1 + while (!q.isEmpty()) { + var size: Int = q.size + level++ + while (size-- > 0) { + val rem = q.removeFirst() + for (dir in dirs) { + val newrow = rem.x + dir[0] + val newcol = rem.y + dir[1] + if (newrow >= 0 && newcol >= 0 && newrow < grid.size && newcol < grid[0].size && + !visited[newrow][newcol] + ) { + if (grid[newrow][newcol] == 1) { + return level + } + q.add(Pair(newrow, newcol)) + visited[newrow][newcol] = true + } + } + } + } + return -1 + } + + private fun dfs(grid: Array, row: Int, col: Int, visited: Array, q: ArrayDeque) { + visited[row][col] = true + q.add(Pair(row, col)) + for (dir in dirs) { + val newrow = row + dir[0] + val newcol = col + dir[1] + if (newrow >= 0 && newcol >= 0 && newrow < grid.size && newcol < grid[0].size && + !visited[newrow][newcol] && grid[newrow][newcol] == 1 + ) { + dfs(grid, newrow, newcol, visited, q) + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0935_knight_dialer/readme.md b/src/main/kotlin/g0901_1000/s0935_knight_dialer/readme.md new file mode 100644 index 00000000..bffba0cf --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0935_knight_dialer/readme.md @@ -0,0 +1,97 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 935\. Knight Dialer + +Medium + +The chess knight has a **unique movement**, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an **L**). The possible movements of chess knight are shown in this diagaram: + +A chess knight can move as indicated in the chess diagram below: + +![](https://assets.leetcode.com/uploads/2020/08/18/chess.jpg) + +We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell). + +![](https://assets.leetcode.com/uploads/2020/08/18/phone.jpg) + +Given an integer `n`, return how many distinct phone numbers of length `n` we can dial. + +You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps. + +As the answer may be very large, **return the answer modulo** 109 + 7. + +**Example 1:** + +**Input:** n = 1 + +**Output:** 10 + +**Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient. + +**Example 2:** + +**Input:** n = 2 + +**Output:** 20 + +**Explanation:** All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94] + +**Example 3:** + +**Input:** n = 3131 + +**Output:** 136006598 + +**Explanation:** Please take care of the mod. + +**Constraints:** + +* `1 <= n <= 5000` + +## Solution + +```kotlin +class Solution { + fun knightDialer(n: Int): Int { + if (n == 1) { + return 10 + } + val mod = 1000000007 + while (MEMO.size < n) { + val cur = MEMO[MEMO.size - 1] + val next = IntArray(10) + for (i in 0..9) { + for (d in MAP[i]!!) { + next[d] = (next[d] + cur[i]) % mod + } + } + MEMO.add(next) + } + var sum = 0 + for (x in MEMO[n - 1]) { + sum = (sum + x) % mod + } + return sum + } + + companion object { + private val MAP = arrayOfNulls(10) + private val MEMO: MutableList = ArrayList() + + init { + MAP[0] = intArrayOf(4, 6) + MAP[1] = intArrayOf(6, 8) + MAP[2] = intArrayOf(7, 9) + MAP[3] = intArrayOf(4, 8) + MAP[4] = intArrayOf(3, 9, 0) + MAP[5] = IntArray(0) + MAP[6] = intArrayOf(1, 7, 0) + MAP[7] = intArrayOf(2, 6) + MAP[8] = intArrayOf(1, 3) + MAP[9] = intArrayOf(2, 4) + MEMO.add(intArrayOf(1, 1, 1, 1, 1, 0, 1, 1, 1, 1)) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0936_stamping_the_sequence/readme.md b/src/main/kotlin/g0901_1000/s0936_stamping_the_sequence/readme.md new file mode 100644 index 00000000..6a032b73 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0936_stamping_the_sequence/readme.md @@ -0,0 +1,112 @@ +[![](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) + +## 936\. Stamping The Sequence + +Hard + +You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`. + +In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`. + +* For example, if `stamp = "abc"` and `target = "abcba"`, then `s` is `"?????"` initially. In one turn you can: + + * place `stamp` at index `0` of `s` to obtain `"abc??"`, + * place `stamp` at index `1` of `s` to obtain `"?abc?"`, or + * place `stamp` at index `2` of `s` to obtain `"??abc"`. + + Note that `stamp` must be fully contained in the boundaries of `s` in order to stamp (i.e., you cannot place `stamp` at index `3` of `s`). + +We want to convert `s` to `target` using **at most** `10 * target.length` turns. + +Return _an array of the index of the left-most letter being stamped at each turn_. If we cannot obtain `target` from `s` within `10 * target.length` turns, return an empty array. + +**Example 1:** + +**Input:** stamp = "abc", target = "ababc" + +**Output:** [0,2] + +**Explanation:** Initially s = "?????". + +- Place stamp at index 0 to get "abc??". + +- Place stamp at index 2 to get "ababc". + +[1,0,2] would also be accepted as an answer, as well as some other answers. + +**Example 2:** + +**Input:** stamp = "abca", target = "aabcaca" + +**Output:** [3,0,1] + +**Explanation:** Initially s = "???????". + +- Place stamp at index 3 to get "???abca". + +- Place stamp at index 0 to get "abcabca". + +- Place stamp at index 1 to get "aabcaca". + +**Constraints:** + +* `1 <= stamp.length <= target.length <= 1000` +* `stamp` and `target` consist of lowercase English letters. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun movesToStamp(stamp: String, target: String): IntArray { + val moves: MutableList = ArrayList() + val s = stamp.toCharArray() + val t = target.toCharArray() + var stars = 0 + val visited = BooleanArray(target.length) + while (stars < target.length) { + var doneReplace = false + for (i in 0..target.length - stamp.length) { + if (!visited[i] && canReplace(t, i, s)) { + stars = doReplace(t, i, s, stars) + doneReplace = true + visited[i] = true + moves.add(i) + if (stars == t.size) { + break + } + } + } + if (!doneReplace) { + return IntArray(0) + } + } + val result = IntArray(moves.size) + for (i in moves.indices) { + result[i] = moves[moves.size - i - 1] + } + return result + } + + private fun canReplace(t: CharArray, i: Int, s: CharArray): Boolean { + for (j in s.indices) { + if (t[i + j] != '*' && t[i + j] != s[j]) { + return false + } + } + return true + } + + private fun doReplace(t: CharArray, i: Int, s: CharArray, stars: Int): Int { + var stars = stars + for (j in s.indices) { + if (t[i + j] != '*') { + t[i + j] = '*' + stars++ + } + } + return stars + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0937_reorder_data_in_log_files/readme.md b/src/main/kotlin/g0901_1000/s0937_reorder_data_in_log_files/readme.md new file mode 100644 index 00000000..ad42fb68 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0937_reorder_data_in_log_files/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) + +## 937\. Reorder Data in Log Files + +Medium + +You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. + +There are two types of logs: + +* **Letter-logs**: All words (except the identifier) consist of lowercase English letters. +* **Digit-logs**: All words (except the identifier) consist of digits. + +Reorder these logs so that: + +1. The **letter-logs** come before all **digit-logs**. +2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers. +3. The **digit-logs** maintain their relative ordering. + +Return _the final order of the logs_. + +**Example 1:** + +**Input:** logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"] + +**Output:** ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"] + +**Explanation:** + +The letter-log contents are all different, so their ordering is "art can", "art zero", "own kit dig". + +The digit-logs have a relative order of "dig1 8 1 5 1", "dig2 3 6". + +**Example 2:** + +**Input:** logs = ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"] + +**Output:** ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"] + +**Constraints:** + +* `1 <= logs.length <= 100` +* `3 <= logs[i].length <= 100` +* All the tokens of `logs[i]` are separated by a **single** space. +* `logs[i]` is guaranteed to have an identifier and at least one word after the identifier. + +## Solution + +```kotlin +import java.util.Collections + +class Solution { + fun reorderLogFiles(logs: Array): Array { + val digi: MutableList = ArrayList() + val word: MutableList = ArrayList() + for (s in logs) { + if (Character.isDigit(s[s.length - 1])) digi.add(s) else word.add(s) + } + Collections.sort( + word, + Comparator { s1, s2 -> + val firstSpacePosition = s1.indexOf(" ") + val firstWord = s1.substring(firstSpacePosition, s1.length) + val secondSpacePosition = s2.indexOf(" ") + val secondWord = s2.substring(secondSpacePosition, s2.length) + if (firstWord.compareTo(secondWord) == 0) { + val firstSpacePosition1 = s1.indexOf(" ") + val firstWord1 = s1.substring(0, firstSpacePosition1) + val secondSpacePosition1 = s2.indexOf(" ") + val secondWord1 = s2.substring(0, secondSpacePosition1) + return@Comparator firstWord1.compareTo(secondWord1) + } + firstWord.compareTo(secondWord) + } + ) + val result = arrayOfNulls(digi.size + word.size) + var `in` = 0 + for (s in word) result[`in`++] = s + for (s in digi) result[`in`++] = s + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0938_range_sum_of_bst/readme.md b/src/main/kotlin/g0901_1000/s0938_range_sum_of_bst/readme.md new file mode 100644 index 00000000..3804d188 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0938_range_sum_of_bst/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) + +## 938\. Range Sum of BST + +Easy + +Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/05/bst1.jpg) + +**Input:** root = [10,5,15,3,7,null,18], low = 7, high = 15 + +**Output:** 32 + +**Explanation:** Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/11/05/bst2.jpg) + +**Input:** root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 + +**Output:** 23 + +**Explanation:** Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23. + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 2 * 104]. +* 1 <= Node.val <= 105 +* 1 <= low <= high <= 105 +* All `Node.val` 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 + * } + */ +internal class Solution { + fun rangeSumBST(root: TreeNode?, low: Int, high: Int): Int { + var ans = 0 + if (root == null) return 0 + if (root.`val` in low..high) { + ans += root.`val` + } + if (root.`val` in low..high) { + ans += rangeSumBST(root.left, low, high) + ans += rangeSumBST(root.right, low, high) + } else if (root.`val` >= low && root.`val` >= high) { + ans += rangeSumBST(root.left, low, high) + } else { + ans += rangeSumBST(root.right, low, high) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0939_minimum_area_rectangle/readme.md b/src/main/kotlin/g0901_1000/s0939_minimum_area_rectangle/readme.md new file mode 100644 index 00000000..01f01ee6 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0939_minimum_area_rectangle/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) + +## 939\. Minimum Area Rectangle + +Medium + +You are given an array of points in the **X-Y** plane `points` where points[i] = [xi, yi]. + +Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/08/03/rec1.JPG) + +**Input:** points = \[\[1,1],[1,3],[3,1],[3,3],[2,2]] + +**Output:** 4 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/08/03/rec2.JPG) + +**Input:** points = \[\[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]] + +**Output:** 2 + +**Constraints:** + +* `1 <= points.length <= 500` +* `points[i].length == 2` +* 0 <= xi, yi <= 4 * 104 +* All the given points are **unique**. + +## Solution + +```kotlin +import java.util.Arrays +import kotlin.math.abs + +class Solution { + fun minAreaRect(points: Array): Int { + if (points.size < 4) { + return 0 + } + val map: MutableMap> = HashMap() + for (p in points) { + map.putIfAbsent(p[0], HashSet()) + map[p[0]]!!.add(p[1]) + } + Arrays.sort( + points + ) { a: IntArray, b: IntArray -> + if (a[0] == b[0]) Integer.compare( + a[1], + b[1] + ) else Integer.compare(a[0], b[0]) + } + var min = Int.MAX_VALUE + for (i in 0 until points.size - 2) { + for (j in i + 1 until points.size - 1) { + val p1 = points[i] + val p2 = points[j] + val area = abs((p1[0] - p2[0]) * (p1[1] - p2[1])) + if (area >= min || area == 0) { + continue + } + if (map[p1[0]]!!.contains(p2[1]) && map[p2[0]]!!.contains(p1[1])) { + min = area + } + } + } + return if (min == Int.MAX_VALUE) 0 else min + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0940_distinct_subsequences_ii/readme.md b/src/main/kotlin/g0901_1000/s0940_distinct_subsequences_ii/readme.md new file mode 100644 index 00000000..1e9961a0 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0940_distinct_subsequences_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) + +## 940\. Distinct Subsequences II + +Hard + +Given a string s, return _the number of **distinct non-empty subsequences** of_ `s`. Since the answer may be very large, return it **modulo** 109 + 7. + +A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace"` is a subsequence of "abcde" while `"aec"` is not. + +**Example 1:** + +**Input:** s = "abc" + +**Output:** 7 + +**Explanation:** The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc". + +**Example 2:** + +**Input:** s = "aba" + +**Output:** 6 + +**Explanation:** The 6 distinct subsequences are "a", "b", "ab", "aa", "ba", and "aba". + +**Example 3:** + +**Input:** s = "aaa" + +**Output:** 3 + +**Explanation:** The 3 distinct subsequences are "a", "aa" and "aaa". + +**Constraints:** + +* `1 <= s.length <= 2000` +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun distinctSubseqII(s: String): Int { + val n = s.length + val mod = 1000000007 + val arr = IntArray(26) + for (i in 0 until n) { + val x = s[i].code - 'a'.code + var sum: Long = 0 + arr[x] += 1 + for (j in 0..25) { + sum = (sum + arr[j]) % mod + } + arr[x] = sum.toInt() + } + var total: Long = 0 + for (x in arr) { + total = (total + x) % mod + } + return total.toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0941_valid_mountain_array/readme.md b/src/main/kotlin/g0901_1000/s0941_valid_mountain_array/readme.md new file mode 100644 index 00000000..1cf3348e --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0941_valid_mountain_array/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) + +## 941\. Valid Mountain Array + +Easy + +Given an array of integers `arr`, return _`true` if and only if it is a valid mountain array_. + +Recall that arr is a mountain array if and only if: + +* `arr.length >= 3` +* There exists some `i` with `0 < i < arr.length - 1` such that: + * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` + * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` + +![](https://assets.leetcode.com/uploads/2019/10/20/hint_valid_mountain_array.png) + +**Example 1:** + +**Input:** arr = [2,1] + +**Output:** false + +**Example 2:** + +**Input:** arr = [3,5,5] + +**Output:** false + +**Example 3:** + +**Input:** arr = [0,3,2,1] + +**Output:** true + +**Constraints:** + +* 1 <= arr.length <= 104 +* 0 <= arr[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun validMountainArray(arr: IntArray): Boolean { + var i = 0 + var flag1 = false + var flag2 = false + while (i < arr.size - 1 && arr[i] < arr[i + 1]) { + flag1 = true + i++ + } + while (i < arr.size - 1 && arr[i] > arr[i + 1]) { + flag2 = true + i++ + } + if (i < arr.size - 1) { + return false + } + return !(!flag1 || !flag2) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0942_di_string_match/readme.md b/src/main/kotlin/g0901_1000/s0942_di_string_match/readme.md new file mode 100644 index 00000000..f6887f2d --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0942_di_string_match/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) + +## 942\. DI String Match + +Easy + +A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: + +* `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and +* `s[i] == 'D'` if `perm[i] > perm[i + 1]`. + +Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. + +**Example 1:** + +**Input:** s = "IDID" + +**Output:** [0,4,1,3,2] + +**Example 2:** + +**Input:** s = "III" + +**Output:** [0,1,2,3] + +**Example 3:** + +**Input:** s = "DDI" + +**Output:** [3,2,0,1] + +**Constraints:** + +* 1 <= s.length <= 105 +* `s[i]` is either `'I'` or `'D'`. + +## Solution + +```kotlin +class Solution { + fun diStringMatch(s: String): IntArray { + val arr = IntArray(s.length + 1) + var max = s.length + for (i in s.indices) { + if (s[i] == 'D') { + arr[i] = max + max-- + } + } + run { + var i = s.length - 1 + while (i >= 0 && max > 0) { + if (s[i] == 'I' && arr[i + 1] == 0) { + arr[i + 1] = max + max-- + } + i-- + } + } + var i = 0 + while (i < arr.size && max > 0) { + if (arr[i] == 0) { + arr[i] = max + max-- + } + i++ + } + return arr + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0943_find_the_shortest_superstring/readme.md b/src/main/kotlin/g0901_1000/s0943_find_the_shortest_superstring/readme.md new file mode 100644 index 00000000..bcdec693 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0943_find_the_shortest_superstring/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) + +## 943\. Find the Shortest Superstring + +Hard + +Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. + +You may assume that no string in `words` is a substring of another string in `words`. + +**Example 1:** + +**Input:** words = ["alex","loves","leetcode"] + +**Output:** "alexlovesleetcode" + +**Explanation:** All permutations of "alex","loves","leetcode" would also be accepted. + +**Example 2:** + +**Input:** words = ["catg","ctaagt","gcta","ttca","atgcatc"] + +**Output:** "gctaagttcatgcatc" + +**Constraints:** + +* `1 <= words.length <= 12` +* `1 <= words[i].length <= 20` +* `words[i]` consists of lowercase English letters. +* All the strings of `words` are **unique**. + +## Solution + +```kotlin +class Solution { + fun shortestSuperstring(words: Array): String? { + val l = words.size + var state = 0 + for (i in 0 until l) { + state = state or (1 shl i) + } + val map: MutableMap = HashMap() + return solveTPS(words, state, "", map, l) + } + + private fun solveTPS( + words: Array, + state: Int, + startWord: String, + map: MutableMap, + l: Int + ): String? { + val key = "$startWord|$state" + if (state == 0) { + return startWord + } + if (map[key] != null) { + return map[key] + } + var minLenWord: String? = "" + for (i in 0 until l) { + if (state shr i and 1 == 1) { + val takenState = state and (1 shl i).inv() + val result = solveTPS(words, takenState, words[i], map, l) + val tmp = mergeAndGet(startWord, result) + if (minLenWord!!.isEmpty() || minLenWord.length > tmp.length) { + minLenWord = tmp + } + } + } + map[key] = minLenWord + return minLenWord + } + + private fun mergeAndGet(word: String, result: String?): String { + val l = word.length + val t = result!!.length + if (result.contains(word)) { + return result + } + if (word.contains(result)) { + return word + } + var found = l + for (k in 0 until l) { + var i = k + var j = 0 + while (i < l && j < t) { + if (word[i] == result[j]) { + i++ + j++ + } else break + } + if (i == l) { + found = k + break + } + } + return word.substring(0, found) + result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0944_delete_columns_to_make_sorted/readme.md b/src/main/kotlin/g0901_1000/s0944_delete_columns_to_make_sorted/readme.md new file mode 100644 index 00000000..fc1e16d7 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0944_delete_columns_to_make_sorted/readme.md @@ -0,0 +1,92 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 944\. Delete Columns to Make Sorted + +Easy + +You are given an array of `n` strings `strs`, all of the same length. + +The strings can be arranged such that there is one on each line, making a grid. + +* For example, `strs = ["abc", "bce", "cae"]` can be arranged as follows: + +abc bce cae + +You want to **delete** the columns that are **not sorted lexicographically**. In the above example (**0-indexed**), columns 0 (`'a'`, `'b'`, `'c'`) and 2 (`'c'`, `'e'`, `'e'`) are sorted, while column 1 (`'b'`, `'c'`, `'a'`) is not, so you would delete column 1. + +Return _the number of columns that you will delete_. + +**Example 1:** + +**Input:** strs = ["cba","daf","ghi"] + +**Output:** 1 + +**Explanation:** The grid looks as follows: + +cba + +daf + +ghi + +Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. + +**Example 2:** + +**Input:** strs = ["a","b"] + +**Output:** 0 + +**Explanation:** The grid looks as follows: + +a + +b + +Column 0 is the only column and is sorted, so you will not delete any columns. + +**Example 3:** + +**Input:** strs = ["zyx","wvu","tsr"] + +**Output:** 3 + +**Explanation:** The grid looks as follows: + +zyx + +wvu + +tsr + +All 3 columns are not sorted, so you will delete all 3. + +**Constraints:** + +* `n == strs.length` +* `1 <= n <= 100` +* `1 <= strs[i].length <= 1000` +* `strs[i]` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun minDeletionSize(strs: Array): Int { + var deleted = 0 + for (i in 0 until strs[0].length) { + var last = ' ' + for (str in strs) { + if (str[i] < last) { + deleted++ + break + } + last = str[i] + } + } + return deleted + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0945_minimum_increment_to_make_array_unique/readme.md b/src/main/kotlin/g0901_1000/s0945_minimum_increment_to_make_array_unique/readme.md new file mode 100644 index 00000000..2b8ecf13 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0945_minimum_increment_to_make_array_unique/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) + +## 945\. Minimum Increment to Make Array Unique + +Medium + +You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`. + +Return _the minimum number of moves to make every value in_ `nums` _**unique**_. + +The test cases are generated so that the answer fits in a 32-bit integer. + +**Example 1:** + +**Input:** nums = [1,2,2] + +**Output:** 1 + +**Explanation:** After 1 move, the array could be [1, 2, 3]. + +**Example 2:** + +**Input:** nums = [3,2,1,2,1,7] + +**Output:** 6 + +**Explanation:** After 6 moves, the array could be [3, 4, 1, 2, 5, 7]. It can be shown with 5 or less moves that it is impossible for the array to have all unique values. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 0 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun minIncrementForUnique(nums: IntArray): Int { + var max = 0 + for (num in nums) { + max = Math.max(max, num) + } + val counts = IntArray(nums.size + max) + for (num in nums) { + counts[num]++ + } + var minMoves = 0 + for (i in counts.indices) { + if (counts[i] <= 1) { + continue + } + val remaining = counts[i] - 1 + minMoves += remaining + counts[i + 1] = counts[i + 1] + remaining + } + return minMoves + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0946_validate_stack_sequences/readme.md b/src/main/kotlin/g0901_1000/s0946_validate_stack_sequences/readme.md new file mode 100644 index 00000000..011a0236 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0946_validate_stack_sequences/readme.md @@ -0,0 +1,81 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 946\. Validate Stack Sequences + +Medium + +Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ + +**Example 1:** + +**Input:** pushed = [1,2,3,4,5], popped = [4,5,3,2,1] + +**Output:** true + +**Explanation:** We might do the following sequence: + +push(1), push(2), push(3), push(4), + +pop() -> 4, + +push(5), + +pop() -> 5, + +pop() -> 3, + +pop() -> 2, + +pop() -> 1 + +**Example 2:** + +**Input:** pushed = [1,2,3,4,5], popped = [4,3,5,1,2] + +**Output:** false + +**Explanation:** 1 cannot be popped before 2. + +**Constraints:** + +* `1 <= pushed.length <= 1000` +* `0 <= pushed[i] <= 1000` +* All the elements of `pushed` are **unique**. +* `popped.length == pushed.length` +* `popped` is a permutation of `pushed`. + +## Solution + +```kotlin +import java.util.Deque +import java.util.LinkedList + +class Solution { + fun validateStackSequences(pushed: IntArray, popped: IntArray): Boolean { + val stack: Deque = LinkedList() + var i = 0 + var j = 0 + val len = pushed.size + while (i < len) { + if (pushed[i] == popped[j]) { + i++ + j++ + } else if (!stack.isEmpty() && stack.peek() == popped[j]) { + stack.pop() + j++ + } else { + stack.push(pushed[i++]) + } + } + while (j < len) { + if (!stack.isEmpty() && stack.peek() != popped[j++]) { + return false + } else { + stack.pop() + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0947_most_stones_removed_with_same_row_or_column/readme.md b/src/main/kotlin/g0901_1000/s0947_most_stones_removed_with_same_row_or_column/readme.md new file mode 100644 index 00000000..643a1a93 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0947_most_stones_removed_with_same_row_or_column/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) + +## 947\. Most Stones Removed with Same Row or Column + +Medium + +On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. + +A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. + +Given an array `stones` of length `n` where stones[i] = [xi, yi] represents the location of the ith stone, return _the largest possible number of stones that can be removed_. + +**Example 1:** + +**Input:** stones = \[\[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]] + +**Output:** 5 + +**Explanation:** One way to remove 5 stones is as follows: + +1. Remove stone [2,2] because it shares the same row as [2,1]. +2. Remove stone [2,1] because it shares the same column as [0,1]. +3. Remove stone [1,2] because it shares the same row as [1,0]. +4. Remove stone [1,0] because it shares the same column as [0,0]. +5. Remove stone [0,1] because it shares the same row as [0,0]. + +Stone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane. + +**Example 2:** + +**Input:** stones = \[\[0,0],[0,2],[1,1],[2,0],[2,2]] + +**Output:** 3 + +**Explanation:** One way to make 3 moves is as follows: + +1. Remove stone [2,2] because it shares the same row as [2,0]. + +2. Remove stone [2,0] because it shares the same column as [0,0]. + +3. Remove stone [0,2] because it shares the same row as [0,0]. + +Stones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane. + +**Example 3:** + +**Input:** stones = \[\[0,0]] + +**Output:** 0 + +**Explanation:** [0,0] is the only stone on the plane, so you cannot remove it. + +**Constraints:** + +* `1 <= stones.length <= 1000` +* 0 <= xi, yi <= 104 +* No two stones are at the same coordinate point. + +## Solution + +```kotlin +class Solution { + private val roots = IntArray(20002) + fun removeStones(stones: Array): Int { + for (stone in stones) { + init(stone[0] + 1, roots) + init(stone[1] + 10000, roots) + union(stone[0] + 1, stone[1] + 10000) + } + val set: HashSet = HashSet() + for (n in roots) { + if (n == 0) { + continue + } + set.add(find(n)) + } + return stones.size - set.size + } + + private fun init(i: Int, roots: IntArray) { + if (roots[i] != 0) { + return + } + roots[i] = i + } + + private fun union(i: Int, j: Int) { + val ri = find(i) + val rj = find(j) + if (ri == rj) { + return + } + roots[ri] = rj + } + + private fun find(i: Int): Int { + var cur = i + while (cur != roots[cur]) { + cur = roots[roots[cur]] + } + return cur + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0948_bag_of_tokens/readme.md b/src/main/kotlin/g0901_1000/s0948_bag_of_tokens/readme.md new file mode 100644 index 00000000..fe73ee75 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0948_bag_of_tokens/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) + +## 948\. Bag of Tokens + +Medium + +You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the ith token (0-indexed). + +Your goal is to maximize your total **score** by potentially playing each token in one of two ways: + +* If your current **power** is at least `tokens[i]`, you may play the ith token face up, losing `tokens[i]` **power** and gaining `1` **score**. +* If your current **score** is at least `1`, you may play the ith token face down, gaining `tokens[i]` **power** and losing `1` **score**. + +Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens. + +Return _the largest possible **score** you can achieve after playing any number of tokens_. + +**Example 1:** + +**Input:** tokens = [100], power = 50 + +**Output:** 0 + +**Explanation:****:** Playing the only token in the bag is impossible because you either have too little power or too little score. + +**Example 2:** + +**Input:** tokens = [100,200], power = 150 + +**Output:** 1 + +**Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. + +**Example 3:** + +**Input:** tokens = [100,200,300,400], power = 200 + +**Output:** 2 + +**Explanation:** Play the tokens in this order to get a score of 2: +1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. +2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. +3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. +4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. + +**Constraints:** + +* `0 <= tokens.length <= 1000` +* 0 <= tokens[i], power < 104 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun bagOfTokensScore(tokens: IntArray, power: Int): Int { + var power = power + tokens.sort() + var score = 0 + var l = 0 + var r = tokens.size - 1 + while (l <= r) { + if (tokens[l] <= power) { + power -= tokens[l] + score++ + l++ + } else { + if (r - l == 0) { + return score + } + if (score >= 1) { + power += tokens[r] + score-- + r-- + } else { + return 0 + } + } + } + return score + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0949_largest_time_for_given_digits/readme.md b/src/main/kotlin/g0901_1000/s0949_largest_time_for_given_digits/readme.md new file mode 100644 index 00000000..fa370989 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0949_largest_time_for_given_digits/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) + +## 949\. Largest Time for Given Digits + +Medium + +Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. + +24-hour times are formatted as `"HH:MM"`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. + +Return _the latest 24-hour time in `"HH:MM"` format_. If no valid time can be made, return an empty string. + +**Example 1:** + +**Input:** arr = [1,2,3,4] + +**Output:** "23:41" + +**Explanation:** The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of these times, "23:41" is the latest. + +**Example 2:** + +**Input:** arr = [5,5,5,5] + +**Output:** "" + +**Explanation:** There are no valid 24-hour times as "55:55" is not valid. + +**Constraints:** + +* `arr.length == 4` +* `0 <= arr[i] <= 9` + +## Solution + +```kotlin +class Solution { + fun largestTimeFromDigits(arr: IntArray): String { + val buf = StringBuilder() + var maxHour: String? = "" + for (i in 0..3) { + for (j in 0..3) { + if (i != j) { + val hour = getTime(arr, i, j, 23, false) + val min = getTime(arr, i, j, 59, true) + if (hour != null && min != null && hour > maxHour!!) { + buf.setLength(0) + buf.append(hour).append(':').append(min) + maxHour = hour + } + } + } + } + return buf.toString() + } + + private fun getTime(arr: IntArray, i: Int, j: Int, limit: Int, exclude: Boolean): String? { + var n1 = -1 + var n2 = -1 + for (k in 0..3) { + if (exclude && k != i && k != j || !exclude && (k == i || k == j)) { + if (n1 == -1) { + n1 = arr[k] + } else { + n2 = arr[k] + } + } + } + var s1: String? = n1.toString() + n2 + var s2: String? = n2.toString() + n1 + var v1 = s1!!.toInt() + if (v1 > limit) { + v1 = -1 + s1 = null + } + var v2 = s2!!.toInt() + if (v2 > limit) { + v2 = -1 + s2 = null + } + return if (v1 >= v2) s1 else s2 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0950_reveal_cards_in_increasing_order/readme.md b/src/main/kotlin/g0901_1000/s0950_reveal_cards_in_increasing_order/readme.md new file mode 100644 index 00000000..ff412faa --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0950_reveal_cards_in_increasing_order/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) + +## 950\. Reveal Cards In Increasing Order + +Medium + +You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the ith card is `deck[i]`. + +You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. + +You will do the following steps repeatedly until all cards are revealed: + +1. Take the top card of the deck, reveal it, and take it out of the deck. +2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. +3. If there are still unrevealed cards, go back to step 1. Otherwise, stop. + +Return _an ordering of the deck that would reveal the cards in increasing order_. + +**Note** that the first entry in the answer is considered to be the top of the deck. + +**Example 1:** + +**Input:** deck = [17,13,11,2,3,5,7] + +**Output:** [2,13,3,11,5,17,7] + +**Explanation:** + +We get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it. + +After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck. + +We reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13]. + +We reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11]. + +We reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17]. + +We reveal 7, and move 13 to the bottom. The deck is now [11,17,13]. + +We reveal 11, and move 17 to the bottom. The deck is now [13,17]. + +We reveal 13, and move 17 to the bottom. The deck is now [17]. + +We reveal 17. Since all the cards revealed are in increasing order, the answer is correct. + +**Example 2:** + +**Input:** deck = [1,1000] + +**Output:** [1,1000] + +**Constraints:** + +* `1 <= deck.length <= 1000` +* 1 <= deck[i] <= 106 +* All the values of `deck` are **unique**. + +## Solution + +```kotlin +class Solution { + fun deckRevealedIncreasing(deck: IntArray): IntArray { + deck.sort() + val n = deck.size + val result = IntArray(n * 2) + var idx = result.size - 1 + var lastIdx = result.size - 1 + var i = n - 1 + while (idx >= 0 && i >= 0) { + if (i != n - 1) { + result[idx--] = result[lastIdx--] + } + result[idx--] = deck[i--] + } + return result.copyOfRange(idx + 1, lastIdx + 1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0951_flip_equivalent_binary_trees/readme.md b/src/main/kotlin/g0901_1000/s0951_flip_equivalent_binary_trees/readme.md new file mode 100644 index 00000000..67cc4df7 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0951_flip_equivalent_binary_trees/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) + +## 951\. Flip Equivalent Binary Trees + +Medium + +For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. + +A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. + +Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise. + +**Example 1:** + +![Flipped Trees Diagram](https://assets.leetcode.com/uploads/2018/11/29/tree_ex.png) + +**Input:** root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7] + +**Output:** true + +**Explanation:** We flipped at nodes with values 1, 3, and 5. + +**Example 2:** + +**Input:** root1 = [], root2 = [] + +**Output:** true + +**Example 3:** + +**Input:** root1 = [], root2 = [1] + +**Output:** false + +**Constraints:** + +* The number of nodes in each tree is in the range `[0, 100]`. +* Each tree will have **unique node values** in the range `[0, 99]`. + +## 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 flipEquiv(root1: TreeNode?, root2: TreeNode?): Boolean { + if (root1 == null && root2 == null) { + return true + } + if (root1 == null || root2 == null) { + return false + } + return if (root1.`val` != root2.`val`) { + false + } else flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right) || + flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0952_largest_component_size_by_common_factor/readme.md b/src/main/kotlin/g0901_1000/s0952_largest_component_size_by_common_factor/readme.md new file mode 100644 index 00000000..6a1d4e8f --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0952_largest_component_size_by_common_factor/readme.md @@ -0,0 +1,104 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 952\. Largest Component Size by Common Factor + +Hard + +You are given an integer array of unique positive integers `nums`. Consider the following graph: + +* There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, +* There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. + +Return _the size of the largest connected component in the graph_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2018/12/01/ex1.png) + +**Input:** nums = [4,6,15,35] + +**Output:** 4 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2018/12/01/ex2.png) + +**Input:** nums = [20,50,9,63] + +**Output:** 2 + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2018/12/01/ex3.png) + +**Input:** nums = [2,3,6,7,4,12,21,39] + +**Output:** 8 + +**Constraints:** + +* 1 <= nums.length <= 2 * 104 +* 1 <= nums[i] <= 105 +* All the values of `nums` are **unique**. + +## Solution + +```kotlin +import kotlin.math.sqrt + +class Solution { + fun largestComponentSize(nums: IntArray): Int { + var max = 0 + for (a in nums) { + max = Math.max(max, a) + } + val roots = IntArray(max + 1) + val sizes = IntArray(max + 1) + for (idx in 1..max) { + roots[idx] = idx + } + for (a in nums) { + if (a == 1) { + sizes[a] = 1 + continue + } + val sqrt = sqrt(a.toDouble()).toInt() + val thisRoot = getRoot(roots, a) + sizes[thisRoot]++ + for (factor in 1..sqrt) { + if (a % factor == 0) { + val otherFactor = a / factor + val otherFactorRoot = getRoot(roots, otherFactor) + if (factor != 1) { + union(roots, thisRoot, factor, sizes) + } + union(roots, thisRoot, otherFactorRoot, sizes) + } + } + } + var maxConnection = 0 + for (size in sizes) { + maxConnection = Math.max(maxConnection, size) + } + return maxConnection + } + + private fun union(roots: IntArray, a: Int, b: Int, sizes: IntArray) { + val rootA = getRoot(roots, a) + val rootB = getRoot(roots, b) + if (rootA != rootB) { + sizes[rootA] += sizes[rootB] + roots[rootB] = rootA + } + } + + private fun getRoot(roots: IntArray, a: Int): Int { + if (roots[a] == a) { + return a + } + roots[a] = getRoot(roots, roots[a]) + return roots[a] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0953_verifying_an_alien_dictionary/readme.md b/src/main/kotlin/g0901_1000/s0953_verifying_an_alien_dictionary/readme.md new file mode 100644 index 00000000..be362446 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0953_verifying_an_alien_dictionary/readme.md @@ -0,0 +1,74 @@ +[![](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) + +## 953\. Verifying an Alien Dictionary + +Easy + +In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters. + +Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `words` are sorted lexicographically in this alien language. + +**Example 1:** + +**Input:** words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" + +**Output:** true + +**Explanation:** As 'h' comes before 'l' in this language, then the sequence is sorted. + +**Example 2:** + +**Input:** words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" + +**Output:** false + +**Explanation:** As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted. + +**Example 3:** + +**Input:** words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" + +**Output:** false + +**Explanation:** The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ([More info](https://en.wikipedia.org/wiki/Lexicographical_order)). + +**Constraints:** + +* `1 <= words.length <= 100` +* `1 <= words[i].length <= 20` +* `order.length == 26` +* All characters in `words[i]` and `order` are English lowercase letters. + +## Solution + +```kotlin +class Solution { + fun isAlienSorted(words: Array, order: String): Boolean { + val map = IntArray(26) + for (i in order.indices) { + map[order[i].code - 'a'.code] = i + } + for (i in 0 until words.size - 1) { + if (!isSmaller(words[i], words[i + 1], map)) { + return false + } + } + return true + } + + private fun isSmaller(str1: String, str2: String, map: IntArray): Boolean { + val len1 = str1.length + val len2 = str2.length + val minLength = len1.coerceAtMost(len2) + for (i in 0 until minLength) { + if (map[str1[i].code - 'a'.code] > map[str2[i].code - 'a'.code]) { + return false + } else if (map[str1[i].code - 'a'.code] < map[str2[i].code - 'a'.code]) { + return true + } + } + return len1 <= len2 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0954_array_of_doubled_pairs/readme.md b/src/main/kotlin/g0901_1000/s0954_array_of_doubled_pairs/readme.md new file mode 100644 index 00000000..365027c0 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0954_array_of_doubled_pairs/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) + +## 954\. Array of Doubled Pairs + +Medium + +Given an integer array of even length `arr`, return `true` _if it is possible to reorder_ `arr` _such that_ `arr[2 * i + 1] = 2 * arr[2 * i]` _for every_ `0 <= i < len(arr) / 2`_, or_ `false` _otherwise_. + +**Example 1:** + +**Input:** arr = [3,1,3,6] + +**Output:** false + +**Example 2:** + +**Input:** arr = [2,1,2,6] + +**Output:** false + +**Example 3:** + +**Input:** arr = [4,-2,2,-4] + +**Output:** true + +**Explanation:** We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4]. + +**Constraints:** + +* 2 <= arr.length <= 3 * 104 +* `arr.length` is even. +* -105 <= arr[i] <= 105 + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun canReorderDoubled(arr: IntArray): Boolean { + val max = 0.coerceAtLeast(Arrays.stream(arr).max().asInt) + val min = 0.coerceAtMost(Arrays.stream(arr).min().asInt) + val positive = IntArray(max + 1) + val negative = IntArray(-min + 1) + for (a in arr) { + if (a < 0) { + negative[-a]++ + } else { + positive[a]++ + } + } + return if (positive[0] % 2 != 0) { + false + } else validateFrequencies(positive, max) && validateFrequencies(negative, -min) + } + + private fun validateFrequencies(frequencies: IntArray, limit: Int): Boolean { + for (i in 0..limit) { + if (frequencies[i] == 0) { + continue + } + if (2 * i > limit || frequencies[2 * i] < frequencies[i]) { + return false + } + frequencies[2 * i] -= frequencies[i] + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0955_delete_columns_to_make_sorted_ii/readme.md b/src/main/kotlin/g0901_1000/s0955_delete_columns_to_make_sorted_ii/readme.md new file mode 100644 index 00000000..d100c6f1 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0955_delete_columns_to_make_sorted_ii/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) + +## 955\. Delete Columns to Make Sorted II + +Medium + +You are given an array of `n` strings `strs`, all of the same length. + +We may choose any deletion indices, and we delete all the characters in those indices for each string. + +For example, if we have `strs = ["abcdef","uvwxyz"]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `["bef", "vyz"]`. + +Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has its elements in **lexicographic** order (i.e., `strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]`). Return _the minimum possible value of_ `answer.length`. + +**Example 1:** + +**Input:** strs = ["ca","bb","ac"] + +**Output:** 1 + +**Explanation:** After deleting the first column, strs = ["a", "b", "c"]. Now strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]). We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1. + +**Example 2:** + +**Input:** strs = ["xc","yb","za"] + +**Output:** 0 + +**Explanation:** strs is already in lexicographic order, so we do not need to delete anything. Note that the rows of strs are not necessarily in lexicographic order: i.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...) + +**Example 3:** + +**Input:** strs = ["zyx","wvu","tsr"] + +**Output:** 3 + +**Explanation:** We have to delete every column. + +**Constraints:** + +* `n == strs.length` +* `1 <= n <= 100` +* `1 <= strs[i].length <= 100` +* `strs[i]` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun minDeletionSize(strs: Array): Int { + val sorted = BooleanArray(strs.size) + var res = 0 + for (i in 0 until strs[0].length) { + var j = 0 + while (j < strs.size - 1) { + if (!sorted[j] && strs[j][i] > strs[j + 1][i]) { + res++ + break + } + j++ + } + if (j < strs.size - 1) { + continue + } + j = 0 + while (j < strs.size - 1) { + if (strs[j][i] < strs[j + 1][i]) { + sorted[j] = true + } + j++ + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0956_tallest_billboard/readme.md b/src/main/kotlin/g0901_1000/s0956_tallest_billboard/readme.md new file mode 100644 index 00000000..e6536ad6 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0956_tallest_billboard/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) + +## 956\. Tallest Billboard + +Hard + +You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. + +You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`. + +Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`. + +**Example 1:** + +**Input:** rods = [1,2,3,6] + +**Output:** 6 + +**Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6. + +**Example 2:** + +**Input:** rods = [1,2,3,4,5,6] + +**Output:** 10 + +**Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10. + +**Example 3:** + +**Input:** rods = [1,2] + +**Output:** 0 + +**Explanation:** The billboard cannot be supported, so we return 0. + +**Constraints:** + +* `1 <= rods.length <= 20` +* `1 <= rods[i] <= 1000` +* `sum(rods[i]) <= 5000` + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun tallestBillboard(rods: IntArray): Int { + var maxDiff = 0 + for (rod in rods) { + maxDiff += rod + } + val dp = IntArray(maxDiff + 1) + Arrays.fill(dp, -1) + dp[0] = 0 + for (l in rods) { + val dpOld = IntArray(maxDiff + 1) + System.arraycopy(dp, 0, dpOld, 0, maxDiff + 1) + for (diff in 0 until maxDiff + 1) { + if (dpOld[diff] == -1) { + continue + } + if (diff + l <= maxDiff) { + dp[diff + l] = dp[diff + l].coerceAtLeast(dpOld[diff] + l) + } + if (l - diff >= 0) { + dp[l - diff] = dp[l - diff].coerceAtLeast(l + dpOld[diff] - diff) + } else { + dp[diff - l] = dp[diff - l].coerceAtLeast(dpOld[diff]) + } + } + } + return dp[0] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0957_prison_cells_after_n_days/readme.md b/src/main/kotlin/g0901_1000/s0957_prison_cells_after_n_days/readme.md new file mode 100644 index 00000000..96124ec1 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0957_prison_cells_after_n_days/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) + +## 957\. Prison Cells After N Days + +Medium + +There are `8` prison cells in a row and each cell is either occupied or vacant. + +Each day, whether the cell is occupied or vacant changes according to the following rules: + +* If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. +* Otherwise, it becomes vacant. + +**Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors. + +You are given an integer array `cells` where `cells[i] == 1` if the ith cell is occupied and `cells[i] == 0` if the ith cell is vacant, and you are given an integer `n`. + +Return the state of the prison after `n` days (i.e., `n` such changes described above). + +**Example 1:** + +**Input:** cells = [0,1,0,1,1,0,0,1], n = 7 + +**Output:** [0,0,1,1,0,0,0,0] + +**Explanation:** The following table summarizes the state of the prison on each day: + +Day 0: [0, 1, 0, 1, 1, 0, 0, 1] + +Day 1: [0, 1, 1, 0, 0, 0, 0, 0] + +Day 2: [0, 0, 0, 0, 1, 1, 1, 0] + +Day 3: [0, 1, 1, 0, 0, 1, 0, 0] + +Day 4: [0, 0, 0, 0, 0, 1, 0, 0] + +Day 5: [0, 1, 1, 1, 0, 1, 0, 0] + +Day 6: [0, 0, 1, 0, 1, 1, 0, 0] + +Day 7: [0, 0, 1, 1, 0, 0, 0, 0] + +**Example 2:** + +**Input:** cells = [1,0,0,1,0,0,1,0], n = 1000000000 + +**Output:** [0,0,1,1,1,1,1,0] + +**Constraints:** + +* `cells.length == 8` +* `cells[i]` is either `0` or `1`. +* 1 <= n <= 109 + +## Solution + +```kotlin +import java.util.Arrays + +@Suppress("NAME_SHADOWING") +class Solution { + fun prisonAfterNDays(cells: IntArray, n: Int): IntArray { + var n = n + if (n == 0) { + return cells + } + var first: IntArray? = null + var prev = cells + var period: Int + var day = 0 + while (n > 0) { + day++ + n-- + val next = getNextDay(prev) + if (Arrays.equals(next, first)) { + period = day - 1 + n %= period + } + if (day == 1) { + first = next + } + prev = next + } + return prev + } + + private fun getNextDay(arr: IntArray): IntArray { + val ret = IntArray(8) + for (i in 1..6) { + if (arr[i - 1] == arr[i + 1]) { + ret[i] = 1 + } + } + return ret + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0958_check_completeness_of_a_binary_tree/readme.md b/src/main/kotlin/g0901_1000/s0958_check_completeness_of_a_binary_tree/readme.md new file mode 100644 index 00000000..f1c7be04 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0958_check_completeness_of_a_binary_tree/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) + +## 958\. Check Completeness of a Binary Tree + +Medium + +Given the `root` of a binary tree, determine if it is a _complete binary tree_. + +In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between `1` and 2h nodes inclusive at the last level `h`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-1.png) + +**Input:** root = [1,2,3,4,5,6] + +**Output:** true + +**Explanation:** Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-2.png) + +**Input:** root = [1,2,3,4,5,null,7] + +**Output:** false + +**Explanation:** The node with value 7 isn't as far left as possible. + +**Constraints:** + +* The number of nodes in the tree is in the range `[1, 100]`. +* `1 <= Node.val <= 1000` + +## Solution + +```kotlin +import com_github_leetcode.TreeNode +import java.util.LinkedList + +/* + * 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 isCompleteTree(root: TreeNode?): Boolean { + if (root == null) { + return true + } + val queue: LinkedList = LinkedList() + queue.add(root.left) + queue.add(root.right) + var seenNull = false + while (!queue.isEmpty()) { + val node: TreeNode? = queue.poll() + if (node == null) { + seenNull = true + } else { + if (seenNull) { + return false + } + queue.add(node.left) + queue.add(node.right) + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0959_regions_cut_by_slashes/readme.md b/src/main/kotlin/g0901_1000/s0959_regions_cut_by_slashes/readme.md new file mode 100644 index 00000000..664c6b2b --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0959_regions_cut_by_slashes/readme.md @@ -0,0 +1,121 @@ +[![](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) + +## 959\. Regions Cut By Slashes + +Medium + +An `n x n` grid is composed of `1 x 1` squares where each `1 x 1` square consists of a `'/'`, `'\'`, or blank space `' '`. These characters divide the square into contiguous regions. + +Given the grid `grid` represented as a string array, return _the number of regions_. + +Note that backslash characters are escaped, so a `'\'` is represented as `'\\'`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2018/12/15/1.png) + +**Input:** grid = [" /","/ "] + +**Output:** 2 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2018/12/15/2.png) + +**Input:** grid = [" /"," "] + +**Output:** 1 + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2018/12/15/4.png) + +**Input:** grid = ["/\\\\","\\\\/"] + +**Output:** 5 + +**Explanation:** Recall that because \\ characters are escaped, "\\\\/" refers to \\/, and "/\\\\" refers to /\\. + +**Constraints:** + +* `n == grid.length == grid[i].length` +* `1 <= n <= 30` +* `grid[i][j]` is either `'/'`, `'\'`, or `' '`. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + private var regions = 0 + private lateinit var parent: IntArray + fun regionsBySlashes(grid: Array): Int { + val n = grid.size + regions = n * n * 4 + unionFind(regions) + for (row in grid.indices) { + val str = grid[row] + val ch = str.toCharArray() + for ((col, c) in ch.withIndex()) { + val index = row * n * 4 + col * 4 + when (c) { + '/' -> { + union(index, index + 3) + union(index + 1, index + 2) + } + ' ' -> { + union(index, index + 1) + union(index + 1, index + 2) + union(index + 2, index + 3) + } else -> { + union(index, index + 1) + union(index + 2, index + 3) + } + } + if (row != n - 1) { + union(index + 2, index + 4 * n) + } + if (col != n - 1) { + union(index + 1, index + 7) + } + } + } + return regions + } + + private fun unionFind(n: Int) { + parent = IntArray(n) + for (i in 0 until n) { + parent[i] = i + } + } + + private fun union(p: Int, q: Int) { + if (connected(p, q)) { + return + } + --regions + val i = root(p) + val j = root(q) + if (i > j) { + parent[i] = j + } else { + parent[j] = i + } + } + + private fun connected(p: Int, q: Int): Boolean { + return root(p) == root(q) + } + + private fun root(index: Int): Int { + var index = index + while (index != parent[index]) { + parent[index] = parent[parent[index]] + index = parent[index] + } + return index + } +} +``` \ No newline at end of file