diff --git a/README.md b/README.md index 3dd8d02a..4ff9f1c5 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) -* [Binary Search II](#binary-search-ii) * [Dynamic Programming I](#dynamic-programming-i) * [Programming Skills I](#programming-skills-i) * [Programming Skills II](#programming-skills-ii) @@ -16,117 +15,7 @@ * [Algorithm I](#algorithm-i) * [Algorithm II](#algorithm-ii) * [Binary Search I](#binary-search-i) - -### Binary Search II - -#### Day 1 - -| | | | | | -|-|-|-|-|-|- -| 0209 |[Minimum Size Subarray Sum](src/main/kotlin/g0201_0300/s0209_minimum_size_subarray_sum)| Medium | Array, Binary_Search, Prefix_Sum, Sliding_Window | 315 | 96.73 - -#### Day 2 - -| | | | | | -|-|-|-|-|-|- - -#### Day 3 - -| | | | | | -|-|-|-|-|-|- -| 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search | 318 | 82.28 - -#### Day 4 - -| | | | | | -|-|-|-|-|-|- - -#### Day 5 - -| | | | | | -|-|-|-|-|-|- -| 0287 |[Find the Duplicate Number](src/main/kotlin/g0201_0300/s0287_find_the_duplicate_number)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search, Two_Pointers, Bit_Manipulation | 656 | 66.21 - -#### Day 6 - -| | | | | | -|-|-|-|-|-|- - -#### Day 7 - -| | | | | | -|-|-|-|-|-|- - -#### Day 8 - -| | | | | | -|-|-|-|-|-|- -| 0240 |[Search a 2D Matrix II](src/main/kotlin/g0201_0300/s0240_search_a_2d_matrix_ii)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search, Matrix, Divide_and_Conquer | 460 | 66.08 -| 0275 |[H-Index II](src/main/kotlin/g0201_0300/s0275_h_index_ii)| Medium | Array, Binary_Search | 398 | 81.82 - -#### Day 9 - -| | | | | | -|-|-|-|-|-|- - -#### Day 10 - -| | | | | | -|-|-|-|-|-|- -| 0222 |[Count Complete Tree Nodes](src/main/kotlin/g0201_0300/s0222_count_complete_tree_nodes)| ||| - -#### Day 11 - -| | | | | | -|-|-|-|-|-|- - -#### Day 12 - -| | | | | | -|-|-|-|-|-|- -| 0081 |[Search in Rotated Sorted Array II](src/main/kotlin/g0001_0100/s0081_search_in_rotated_sorted_array_ii)| Medium | Array, Binary_Search | 352 | 42.31 -| 0162 |[Find Peak Element](src/main/kotlin/g0101_0200/s0162_find_peak_element)| Medium | Top_Interview_Questions, Array, Binary_Search | 297 | 53.85 - -#### Day 13 - -| | | | | | -|-|-|-|-|-|- -| 0154 |[Find Minimum in Rotated Sorted Array II](src/main/kotlin/g0101_0200/s0154_find_minimum_in_rotated_sorted_array_ii)| Hard | Array, Binary_Search | 275 | 84.00 - -#### Day 14 - -| | | | | | -|-|-|-|-|-|- - -#### Day 15 - -| | | | | | -|-|-|-|-|-|- - -#### Day 16 - -| | | | | | -|-|-|-|-|-|- - -#### Day 17 - -| | | | | | -|-|-|-|-|-|- - -#### Day 18 - -| | | | | | -|-|-|-|-|-|- - -#### Day 19 - -| | | | | | -|-|-|-|-|-|- - -#### Day 20 - -| | | | | | -|-|-|-|-|-|- +* [Binary Search II](#binary-search-ii) ### Dynamic Programming I @@ -172,7 +61,7 @@ | | | | | | |-|-|-|-|-|- | 0121 |[Best Time to Buy and Sell Stock](src/main/kotlin/g0101_0200/s0121_best_time_to_buy_and_sell_stock)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 609 | 94.06 -| 0122 |[Best Time to Buy and Sell Stock II](src/main/kotlin/g0101_0200/s0122_best_time_to_buy_and_sell_stock_ii)| Medium | Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 370 | 16.98 +| 0122 |[Best Time to Buy and Sell Stock II](src/main/kotlin/g0101_0200/s0122_best_time_to_buy_and_sell_stock_ii)| Medium | Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 197 | 95.10 #### Day 8 @@ -205,7 +94,7 @@ | | | | | | |-|-|-|-|-|- | 0118 |[Pascal's Triangle](src/main/kotlin/g0101_0200/s0118_pascals_triangle)| Easy | Top_Interview_Questions, Array, Dynamic_Programming | 277 | 33.22 -| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming | 296 | 19.15 +| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming | 157 | 97.27 #### Day 13 @@ -244,11 +133,13 @@ | | | | | | |-|-|-|-|-|- | 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search | 318 | 82.28 +| 0376 |[Wiggle Subsequence](src/main/kotlin/g0301_0400/s0376_wiggle_subsequence)| Medium | Array, Dynamic_Programming, Greedy | 162 | 88.89 #### Day 19 | | | | | | |-|-|-|-|-|- +| 0392 |[Is Subsequence](src/main/kotlin/g0301_0400/s0392_is_subsequence)| Easy | String, Dynamic_Programming, Two_Pointers | 156 | 87.74 | 1143 |[Longest Common Subsequence](src/main/kotlin/g1101_1200/s1143_longest_common_subsequence)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming | 307 | 38.36 | 0072 |[Edit Distance](src/main/kotlin/g0001_0100/s0072_edit_distance)| Hard | Top_100_Liked_Questions, String, Dynamic_Programming | 320 | 63.53 @@ -262,6 +153,7 @@ | | | | | | |-|-|-|-|-|- +| 0377 |[Combination Sum IV](src/main/kotlin/g0301_0400/s0377_combination_sum_iv)| Medium | Array, Dynamic_Programming | 217 | 72.41 | 0343 |[Integer Break](src/main/kotlin/g0301_0400/s0343_integer_break)| Medium | Dynamic_Programming, Math | 218 | 63.89 | 0279 |[Perfect Squares](src/main/kotlin/g0201_0300/s0279_perfect_squares)| Medium | Top_Interview_Questions, Dynamic_Programming, Math, Breadth_First_Search | 176 | 98.80 @@ -309,6 +201,7 @@ | | | | | | |-|-|-|-|-|- +| 0389 |[Find the Difference](src/main/kotlin/g0301_0400/s0389_find_the_difference)| Easy | String, Hash_Table, Sorting, Bit_Manipulation | 256 | 64.81 #### Day 9 String @@ -445,6 +338,7 @@ | | | | | | |-|-|-|-|-|- | 0155 |[Min Stack](src/main/kotlin/g0101_0200/s0155_min_stack)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Stack, Design | 331 | 84.88 +| 0341 |[Flatten Nested List Iterator](src/main/kotlin/g0301_0400/s0341_flatten_nested_list_iterator)| Medium | Top_Interview_Questions, Depth_First_Search, Tree, Stack, Design, Queue, Iterator | 210 | 100.00 #### Day 19 @@ -455,6 +349,7 @@ | | | | | | |-|-|-|-|-|- +| 0380 |[Insert Delete GetRandom O(1)](src/main/kotlin/g0301_0400/s0380_insert_delete_getrandom_o1)| Medium | Top_Interview_Questions, Array, Hash_Table, Math, Design, Randomized | 1326 | 68.23 ### Graph Theory I @@ -601,6 +496,7 @@ | | | | | | |-|-|-|-|-|- | 0205 |[Isomorphic Strings](src/main/kotlin/g0201_0300/s0205_isomorphic_strings)| Easy | String, Hash_Table | 278 | 79.96 +| 0392 |[Is Subsequence](src/main/kotlin/g0301_0400/s0392_is_subsequence)| Easy | String, Dynamic_Programming, Two_Pointers | 156 | 87.74 #### Day 3 Linked List @@ -625,7 +521,7 @@ | | | | | | |-|-|-|-|-|- -| 0102 |[Binary Tree Level Order Traversal](src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 355 | 29.37 +| 0102 |[Binary Tree Level Order Traversal](src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 332 | 67.53 #### Day 7 Binary Search @@ -785,7 +681,7 @@ | | | | | | |-|-|-|-|-|- | 0100 |[Same Tree](src/main/kotlin/g0001_0100/s0100_same_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 208 | 72.24 -| 0101 |[Symmetric Tree](src/main/kotlin/g0101_0200/s0101_symmetric_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 290 | 26.98 +| 0101 |[Symmetric Tree](src/main/kotlin/g0101_0200/s0101_symmetric_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 190 | 91.36 | 0199 |[Binary Tree Right Side View](src/main/kotlin/g0101_0200/s0199_binary_tree_right_side_view)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 194 | 92.89 #### Day 16 Design @@ -865,7 +761,7 @@ | 0001 |[Two Sum](src/main/kotlin/g0001_0100/s0001_two_sum)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table | 234 | 92.75 | 0217 |[Contains Duplicate](src/main/kotlin/g0201_0300/s0217_contains_duplicate)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting | 719 | 73.49 | 0058 |[Length of Last Word](src/main/kotlin/g0001_0100/s0058_length_of_last_word)| Easy | String | 243 | 63.33 -| 0122 |[Best Time to Buy and Sell Stock II](src/main/kotlin/g0101_0200/s0122_best_time_to_buy_and_sell_stock_ii)| Medium | Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 370 | 16.98 +| 0122 |[Best Time to Buy and Sell Stock II](src/main/kotlin/g0101_0200/s0122_best_time_to_buy_and_sell_stock_ii)| Medium | Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 197 | 95.10 | 0080 |[Remove Duplicates from Sorted Array II](src/main/kotlin/g0001_0100/s0080_remove_duplicates_from_sorted_array_ii)| Medium | Array, Two_Pointers | 357 | 44.78 | 0189 |[Rotate Array](src/main/kotlin/g0101_0200/s0189_rotate_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Two_Pointers | 483 | 86.95 | 0055 |[Jump Game](src/main/kotlin/g0001_0100/s0055_jump_game)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 670 | 66.67 @@ -879,6 +775,7 @@ | | | | | | |-|-|-|-|-|- +| 0392 |[Is Subsequence](src/main/kotlin/g0301_0400/s0392_is_subsequence)| Easy | String, Dynamic_Programming, Two_Pointers | 156 | 87.74 | 0125 |[Valid Palindrome](src/main/kotlin/g0101_0200/s0125_valid_palindrome)| Easy | Top_Interview_Questions, String, Two_Pointers | 353 | 52.06 | 0026 |[Remove Duplicates from Sorted Array](src/main/kotlin/g0001_0100/s0026_remove_duplicates_from_sorted_array)| Easy | Top_Interview_Questions, Array, Two_Pointers | 361 | 77.19 | 0042 |[Trapping Rain Water](src/main/kotlin/g0001_0100/s0042_trapping_rain_water)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Two_Pointers, Stack, Monotonic_Stack | 196 | 100.00 @@ -932,7 +829,7 @@ | 0144 |[Binary Tree Preorder Traversal](src/main/kotlin/g0101_0200/s0144_binary_tree_preorder_traversal)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack | 277 | 37.90 | 0094 |[Binary Tree Inorder Traversal](src/main/kotlin/g0001_0100/s0094_binary_tree_inorder_traversal)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Stack | 269 | 38.80 | 0145 |[Binary Tree Postorder Traversal](src/main/kotlin/g0101_0200/s0145_binary_tree_postorder_traversal)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack | 211 | 80.00 -| 0102 |[Binary Tree Level Order Traversal](src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 355 | 29.37 +| 0102 |[Binary Tree Level Order Traversal](src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 332 | 67.53 | 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 @@ -966,7 +863,7 @@ |-|-|-|-|-|- | 0120 |[Triangle](src/main/kotlin/g0101_0200/s0120_triangle)| Medium | Array, Dynamic_Programming | 194 | 97.87 | 0118 |[Pascal's Triangle](src/main/kotlin/g0101_0200/s0118_pascals_triangle)| Easy | Top_Interview_Questions, Array, Dynamic_Programming | 277 | 33.22 -| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming | 296 | 19.15 +| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming | 157 | 97.27 | 0139 |[Word Break](src/main/kotlin/g0101_0200/s0139_word_break)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Dynamic_Programming, Trie, Memoization | 197 | 87.17 | 0152 |[Maximum Product Subarray](src/main/kotlin/g0101_0200/s0152_maximum_product_subarray)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 253 | 88.42 | 0198 |[House Robber](src/main/kotlin/g0101_0200/s0198_house_robber)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 156 | 92.24 @@ -986,7 +883,7 @@ | 0022 |[Generate Parentheses](src/main/kotlin/g0001_0100/s0022_generate_parentheses)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming, Backtracking | 210 | 78.51 | 0039 |[Combination Sum](src/main/kotlin/g0001_0100/s0039_combination_sum)| Medium | Top_100_Liked_Questions, Array, Backtracking | 317 | 86.85 | 0216 |[Combination Sum III](src/main/kotlin/g0201_0300/s0216_combination_sum_iii)| Medium | Array, Backtracking | 175 | 90.91 -| 0078 |[Subsets](src/main/kotlin/g0001_0100/s0078_subsets)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation, Backtracking | 353 | 30.14 +| 0078 |[Subsets](src/main/kotlin/g0001_0100/s0078_subsets)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation, Backtracking | 191 | 97.44 | 0017 |[Letter Combinations of a Phone Number](src/main/kotlin/g0001_0100/s0017_letter_combinations_of_a_phone_number)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Backtracking | 262 | 73.59 | 0046 |[Permutations](src/main/kotlin/g0001_0100/s0046_permutations)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Backtracking | 186 | 100.00 @@ -995,8 +892,10 @@ | | | | | | |-|-|-|-|-|- | 0191 |[Number of 1 Bits](src/main/kotlin/g0101_0200/s0191_number_of_1_bits)| Easy | Top_Interview_Questions, Bit_Manipulation | 237 | 68.44 +| 0389 |[Find the Difference](src/main/kotlin/g0301_0400/s0389_find_the_difference)| Easy | String, Hash_Table, Sorting, Bit_Manipulation | 256 | 64.81 | 0190 |[Reverse Bits](src/main/kotlin/g0101_0200/s0190_reverse_bits)| Easy | Top_Interview_Questions, Bit_Manipulation, Divide_and_Conquer | 198 | 81.82 | 0338 |[Counting Bits](src/main/kotlin/g0301_0400/s0338_counting_bits)| Easy | Top_100_Liked_Questions, Dynamic_Programming, Bit_Manipulation | 186 | 99.26 +| 0371 |[Sum of Two Integers](src/main/kotlin/g0301_0400/s0371_sum_of_two_integers)| Medium | Top_Interview_Questions, Math, Bit_Manipulation | 129 | 95.45 | 0029 |[Divide Two Integers](src/main/kotlin/g0001_0100/s0029_divide_two_integers)| Medium | Top_Interview_Questions, Math, Bit_Manipulation | 281 | 31.67 #### Udemy Design @@ -1045,6 +944,8 @@ | | | | | | |-|-|-|-|-|- +| 0387 |[First Unique Character in a String](src/main/kotlin/g0301_0400/s0387_first_unique_character_in_a_string)| Easy | Top_Interview_Questions, String, Hash_Table, Counting, Queue | 369 | 82.68 +| 0383 |[Ransom Note](src/main/kotlin/g0301_0400/s0383_ransom_note)| Easy | String, Hash_Table, Counting | 333 | 79.58 | 0242 |[Valid Anagram](src/main/kotlin/g0201_0300/s0242_valid_anagram)| Easy | Top_Interview_Questions, String, Hash_Table, Sorting | 251 | 87.65 #### Day 7 Linked List @@ -1081,9 +982,9 @@ | | | | | | |-|-|-|-|-|- -| 0102 |[Binary Tree Level Order Traversal](src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 355 | 29.37 +| 0102 |[Binary Tree Level Order Traversal](src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 332 | 67.53 | 0104 |[Maximum Depth of Binary Tree](src/main/kotlin/g0101_0200/s0104_maximum_depth_of_binary_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 236 | 83.39 -| 0101 |[Symmetric Tree](src/main/kotlin/g0101_0200/s0101_symmetric_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 290 | 26.98 +| 0101 |[Symmetric Tree](src/main/kotlin/g0101_0200/s0101_symmetric_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 190 | 91.36 #### Day 12 Tree @@ -1125,7 +1026,7 @@ | | | | | | |-|-|-|-|-|- -| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming | 296 | 19.15 +| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming | 157 | 97.27 | 0048 |[Rotate Image](src/main/kotlin/g0001_0100/s0048_rotate_image)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Matrix | 287 | 46.50 | 0059 |[Spiral Matrix II](src/main/kotlin/g0001_0100/s0059_spiral_matrix_ii)| Medium | Array, Matrix, Simulation | 153 | 100.00 @@ -1400,7 +1301,7 @@ | | | | | | |-|-|-|-|-|- -| 0078 |[Subsets](src/main/kotlin/g0001_0100/s0078_subsets)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation, Backtracking | 353 | 30.14 +| 0078 |[Subsets](src/main/kotlin/g0001_0100/s0078_subsets)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation, Backtracking | 191 | 97.44 | 0090 |[Subsets II](src/main/kotlin/g0001_0100/s0090_subsets_ii)| Medium | Array, Bit_Manipulation, Backtracking | 366 | 58.09 #### Day 10 Recursion Backtracking @@ -1476,6 +1377,7 @@ | | | | | | |-|-|-|-|-|- +| 0384 |[Shuffle an Array](src/main/kotlin/g0301_0400/s0384_shuffle_an_array)| Medium | Top_Interview_Questions, Array, Math, Randomized | 940 | 72.09 #### Day 21 Others @@ -1490,6 +1392,7 @@ | | | | | | |-|-|-|-|-|- +| 0374 |[Guess Number Higher or Lower](src/main/kotlin/g0301_0400/s0374_guess_number_higher_or_lower)| Easy | Binary_Search, Interactive | 134 | 94.19 #### Day 2 @@ -1556,6 +1459,117 @@ |-|-|-|-|-|- | 0153 |[Find Minimum in Rotated Sorted Array](src/main/kotlin/g0101_0200/s0153_find_minimum_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Array, Binary_Search | 262 | 60.96 +### Binary Search II + +#### Day 1 + +| | | | | | +|-|-|-|-|-|- +| 0209 |[Minimum Size Subarray Sum](src/main/kotlin/g0201_0300/s0209_minimum_size_subarray_sum)| Medium | Array, Binary_Search, Prefix_Sum, Sliding_Window | 315 | 96.73 + +#### Day 2 + +| | | | | | +|-|-|-|-|-|- + +#### Day 3 + +| | | | | | +|-|-|-|-|-|- +| 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search | 318 | 82.28 + +#### Day 4 + +| | | | | | +|-|-|-|-|-|- + +#### Day 5 + +| | | | | | +|-|-|-|-|-|- +| 0287 |[Find the Duplicate Number](src/main/kotlin/g0201_0300/s0287_find_the_duplicate_number)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search, Two_Pointers, Bit_Manipulation | 656 | 66.21 + +#### Day 6 + +| | | | | | +|-|-|-|-|-|- + +#### Day 7 + +| | | | | | +|-|-|-|-|-|- + +#### Day 8 + +| | | | | | +|-|-|-|-|-|- +| 0240 |[Search a 2D Matrix II](src/main/kotlin/g0201_0300/s0240_search_a_2d_matrix_ii)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search, Matrix, Divide_and_Conquer | 460 | 66.08 +| 0275 |[H-Index II](src/main/kotlin/g0201_0300/s0275_h_index_ii)| Medium | Array, Binary_Search | 398 | 81.82 + +#### Day 9 + +| | | | | | +|-|-|-|-|-|- + +#### Day 10 + +| | | | | | +|-|-|-|-|-|- +| 0222 |[Count Complete Tree Nodes](src/main/kotlin/g0201_0300/s0222_count_complete_tree_nodes)| ||| + +#### Day 11 + +| | | | | | +|-|-|-|-|-|- + +#### Day 12 + +| | | | | | +|-|-|-|-|-|- +| 0081 |[Search in Rotated Sorted Array II](src/main/kotlin/g0001_0100/s0081_search_in_rotated_sorted_array_ii)| Medium | Array, Binary_Search | 352 | 42.31 +| 0162 |[Find Peak Element](src/main/kotlin/g0101_0200/s0162_find_peak_element)| Medium | Top_Interview_Questions, Array, Binary_Search | 297 | 53.85 + +#### Day 13 + +| | | | | | +|-|-|-|-|-|- +| 0154 |[Find Minimum in Rotated Sorted Array II](src/main/kotlin/g0101_0200/s0154_find_minimum_in_rotated_sorted_array_ii)| Hard | Array, Binary_Search | 275 | 84.00 + +#### Day 14 + +| | | | | | +|-|-|-|-|-|- + +#### Day 15 + +| | | | | | +|-|-|-|-|-|- + +#### Day 16 + +| | | | | | +|-|-|-|-|-|- + +#### Day 17 + +| | | | | | +|-|-|-|-|-|- + +#### Day 18 + +| | | | | | +|-|-|-|-|-|- + +#### Day 19 + +| | | | | | +|-|-|-|-|-|- + +#### Day 20 + +| | | | | | +|-|-|-|-|-|- + ## Algorithms | # | Title | Difficulty | Tag | Time, ms | Time, % @@ -1572,8 +1586,35 @@ | 0438 |[Find All Anagrams in a String](src/main/kotlin/g0401_0500/s0438_find_all_anagrams_in_a_string)| Medium | Top_100_Liked_Questions, String, Hash_Table, Sliding_Window, Algorithm_II_Day_5_Sliding_Window, Programming_Skills_II_Day_12, Level_1_Day_12_Sliding_Window/Two_Pointer | 561 | 54.68 | 0437 |[Path Sum III](src/main/kotlin/g0401_0500/s0437_path_sum_iii)| Medium | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree, Level_2_Day_7_Tree | 403 | 54.12 | 0416 |[Partition Equal Subset Sum](src/main/kotlin/g0401_0500/s0416_partition_equal_subset_sum)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Level_2_Day_13_Dynamic_Programming | 509 | 57.56 +| 0400 |[Nth Digit](src/main/kotlin/g0301_0400/s0400_nth_digit)| Medium | Math, Binary_Search | 271 | 50.00 +| 0399 |[Evaluate Division](src/main/kotlin/g0301_0400/s0399_evaluate_division)| Medium | Array, Depth_First_Search, Breadth_First_Search, Graph, Union_Find, Shortest_Path | 183 | 91.49 +| 0398 |[Random Pick Index](src/main/kotlin/g0301_0400/s0398_random_pick_index)| Medium | Hash_Table, Math, Randomized, Reservoir_Sampling | 1091 | 75.00 +| 0397 |[Integer Replacement](src/main/kotlin/g0301_0400/s0397_integer_replacement)| Medium | Dynamic_Programming, Greedy, Bit_Manipulation, Memoization | 145 | 87.50 +| 0396 |[Rotate Function](src/main/kotlin/g0301_0400/s0396_rotate_function)| Medium | Array, Dynamic_Programming, Math | 571 | 87.50 +| 0395 |[Longest Substring with At Least K Repeating Characters](src/main/kotlin/g0301_0400/s0395_longest_substring_with_at_least_k_repeating_characters)| Medium | Top_Interview_Questions, String, Hash_Table, Sliding_Window, Divide_and_Conquer | 274 | 66.67 | 0394 |[Decode String](src/main/kotlin/g0301_0400/s0394_decode_string)| Medium | Top_100_Liked_Questions, String, Stack, Recursion, Level_1_Day_14_Stack, Udemy_Strings | 224 | 64.86 +| 0393 |[UTF-8 Validation](src/main/kotlin/g0301_0400/s0393_utf_8_validation)| Medium | Array, Bit_Manipulation | 219 | 100.00 +| 0392 |[Is Subsequence](src/main/kotlin/g0301_0400/s0392_is_subsequence)| Easy | String, Dynamic_Programming, Two_Pointers, Dynamic_Programming_I_Day_19, Level_1_Day_2_String, Udemy_Two_Pointers | 156 | 87.74 +| 0391 |[Perfect Rectangle](src/main/kotlin/g0301_0400/s0391_perfect_rectangle)| Hard | Array, Line_Sweep | 897 | 100.00 +| 0390 |[Elimination Game](src/main/kotlin/g0301_0400/s0390_elimination_game)| Medium | Math, Recursion | 319 | 55.56 +| 0389 |[Find the Difference](src/main/kotlin/g0301_0400/s0389_find_the_difference)| Easy | String, Hash_Table, Sorting, Bit_Manipulation, Programming_Skills_I_Day_8_String, Udemy_Bit_Manipulation | 256 | 64.81 +| 0388 |[Longest Absolute File Path](src/main/kotlin/g0301_0400/s0388_longest_absolute_file_path)| Medium | String, Depth_First_Search, Stack | 150 | 100.00 +| 0387 |[First Unique Character in a String](src/main/kotlin/g0301_0400/s0387_first_unique_character_in_a_string)| Easy | Top_Interview_Questions, String, Hash_Table, Counting, Queue, Data_Structure_I_Day_6_String | 369 | 82.68 +| 0386 |[Lexicographical Numbers](src/main/kotlin/g0301_0400/s0386_lexicographical_numbers)| Medium | Depth_First_Search, Trie | 463 | 83.33 +| 0385 |[Mini Parser](src/main/kotlin/g0301_0400/s0385_mini_parser)| Medium | String, Depth_First_Search, Stack | 210 | 100.00 +| 0384 |[Shuffle an Array](src/main/kotlin/g0301_0400/s0384_shuffle_an_array)| Medium | Top_Interview_Questions, Array, Math, Randomized, Algorithm_II_Day_20_Others | 940 | 72.09 +| 0383 |[Ransom Note](src/main/kotlin/g0301_0400/s0383_ransom_note)| Easy | String, Hash_Table, Counting, Data_Structure_I_Day_6_String | 333 | 79.58 +| 0382 |[Linked List Random Node](src/main/kotlin/g0301_0400/s0382_linked_list_random_node)| Medium | Math, Linked_List, Randomized, Reservoir_Sampling | 283 | 100.00 +| 0381 |[Insert Delete GetRandom O(1) - Duplicates allowed](src/main/kotlin/g0301_0400/s0381_insert_delete_getrandom_o1_duplicates_allowed)| Hard | Array, Hash_Table, Math, Design, Randomized | 1313 | 50.00 +| 0380 |[Insert Delete GetRandom O(1)](src/main/kotlin/g0301_0400/s0380_insert_delete_getrandom_o1)| Medium | Top_Interview_Questions, Array, Hash_Table, Math, Design, Randomized, Programming_Skills_II_Day_20 | 1326 | 68.23 | 0378 |[Kth Smallest Element in a Sorted Matrix](src/main/kotlin/g0301_0400/s0378_kth_smallest_element_in_a_sorted_matrix)| Medium | Top_Interview_Questions, Array, Sorting, Binary_Search, Matrix, Heap_Priority_Queue | 522 | 59.78 +| 0377 |[Combination Sum IV](src/main/kotlin/g0301_0400/s0377_combination_sum_iv)| Medium | Array, Dynamic_Programming, Dynamic_Programming_I_Day_21 | 217 | 72.41 +| 0376 |[Wiggle Subsequence](src/main/kotlin/g0301_0400/s0376_wiggle_subsequence)| Medium | Array, Dynamic_Programming, Greedy, Dynamic_Programming_I_Day_18 | 162 | 88.89 +| 0375 |[Guess Number Higher or Lower II](src/main/kotlin/g0301_0400/s0375_guess_number_higher_or_lower_ii)| Medium | Dynamic_Programming, Math, Game_Theory | 235 | 75.00 +| 0374 |[Guess Number Higher or Lower](src/main/kotlin/g0301_0400/s0374_guess_number_higher_or_lower)| Easy | Binary_Search, Interactive, Binary_Search_I_Day_1 | 134 | 94.19 +| 0373 |[Find K Pairs with Smallest Sums](src/main/kotlin/g0301_0400/s0373_find_k_pairs_with_smallest_sums)| Medium | Array, Heap_Priority_Queue | 1809 | 80.95 +| 0372 |[Super Pow](src/main/kotlin/g0301_0400/s0372_super_pow)| Medium | Math, Divide_and_Conquer | 196 | 100.00 +| 0371 |[Sum of Two Integers](src/main/kotlin/g0301_0400/s0371_sum_of_two_integers)| Medium | Top_Interview_Questions, Math, Bit_Manipulation, Udemy_Bit_Manipulation | 129 | 95.45 | 0368 |[Largest Divisible Subset](src/main/kotlin/g0301_0400/s0368_largest_divisible_subset)| Medium | Array, Dynamic_Programming, Math, Sorting | 412 | 73.33 | 0367 |[Valid Perfect Square](src/main/kotlin/g0301_0400/s0367_valid_perfect_square)| Easy | Math, Binary_Search, Binary_Search_I_Day_3 | 137 | 94.55 | 0365 |[Water and Jug Problem](src/main/kotlin/g0301_0400/s0365_water_and_jug_problem)| Medium | Math, Depth_First_Search, Breadth_First_Search, Graph_Theory_I_Day_11_Breadth_First_Search | 130 | 100.00 @@ -1589,6 +1630,7 @@ | 0344 |[Reverse String](src/main/kotlin/g0301_0400/s0344_reverse_string)| Easy | Top_Interview_Questions, String, Two_Pointers, Recursion, Algorithm_I_Day_4_Two_Pointers, Udemy_Strings | 445 | 69.75 | 0343 |[Integer Break](src/main/kotlin/g0301_0400/s0343_integer_break)| Medium | Dynamic_Programming, Math, Algorithm_II_Day_18_Dynamic_Programming, Dynamic_Programming_I_Day_21 | 218 | 63.89 | 0342 |[Power of Four](src/main/kotlin/g0301_0400/s0342_power_of_four)| Easy | Math, Bit_Manipulation, Recursion | 150 | 92.11 +| 0341 |[Flatten Nested List Iterator](src/main/kotlin/g0301_0400/s0341_flatten_nested_list_iterator)| Medium | Top_Interview_Questions, Depth_First_Search, Tree, Stack, Design, Queue, Iterator, Programming_Skills_II_Day_18 | 210 | 100.00 | 0338 |[Counting Bits](src/main/kotlin/g0301_0400/s0338_counting_bits)| Easy | Top_100_Liked_Questions, Dynamic_Programming, Bit_Manipulation, Udemy_Bit_Manipulation | 186 | 99.26 | 0337 |[House Robber III](src/main/kotlin/g0301_0400/s0337_house_robber_iii)| Medium | Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree, Udemy_Tree_Stack_Queue | 282 | 84.62 | 0336 |[Palindrome Pairs](src/main/kotlin/g0301_0400/s0336_palindrome_pairs)| Hard | Array, String, Hash_Table, Trie | 2451 | 67.33 @@ -1613,7 +1655,7 @@ | 0310 |[Minimum Height Trees](src/main/kotlin/g0301_0400/s0310_minimum_height_trees)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Topological_Sort | 521 | 97.56 | 0309 |[Best Time to Buy and Sell Stock with Cooldown](src/main/kotlin/g0301_0400/s0309_best_time_to_buy_and_sell_stock_with_cooldown)| Medium | Array, Dynamic_Programming, Dynamic_Programming_I_Day_8 | 272 | 73.33 | 0307 |[Range Sum Query - Mutable](src/main/kotlin/g0301_0400/s0307_range_sum_query_mutable)| Medium | Array, Design, Segment_Tree, Binary_Indexed_Tree | 1729 | 78.79 -| 0306 |[Additive Number](src/main/kotlin/g0301_0400/s0306_additive_number)| Medium | String, Backtracking | 289 | 22.22 +| 0306 |[Additive Number](src/main/kotlin/g0301_0400/s0306_additive_number)| Medium | String, Backtracking | 261 | 63.16 | 0304 |[Range Sum Query 2D - Immutable](src/main/kotlin/g0301_0400/s0304_range_sum_query_2d_immutable)| Medium | Array, Matrix, Design, Prefix_Sum, Dynamic_Programming_I_Day_14, Programming_Skills_II_Day_13, Udemy_2D_Arrays/Matrix | 1373 | 85.71 | 0303 |[Range Sum Query - Immutable](src/main/kotlin/g0301_0400/s0303_range_sum_query_immutable)| Easy | Array, Design, Prefix_Sum, Programming_Skills_I_Day_12_Class_and_Object | 472 | 63.64 | 0301 |[Remove Invalid Parentheses](src/main/kotlin/g0301_0400/s0301_remove_invalid_parentheses)| Hard | String, Breadth_First_Search, Backtracking | 312 | 100.00 @@ -1688,7 +1730,7 @@ | 0197 |[Rising Temperature](src/main/kotlin/g0101_0200/s0197_rising_temperature)| Easy | Database, SQL_I_Day_6_Union | 394 | 94.15 | 0196 |[Delete Duplicate Emails](src/main/kotlin/g0101_0200/s0196_delete_duplicate_emails)| Easy | Database, SQL_I_Day_2_Select_and_Order | 593 | 94.17 | 0195 |[Tenth Line](src/main/kotlin/g0101_0200/s0195_tenth_line)| Easy | Shell | 36 | 87.50 -| 0194 |[Transpose File](src/main/kotlin/g0101_0200/s0194_transpose_file)| Medium | Shell | 477 | 28.60 +| 0194 |[Transpose File](src/main/kotlin/g0101_0200/s0194_transpose_file)| Medium | Shell | 461 | 33.47 | 0193 |[Valid Phone Numbers](src/main/kotlin/g0101_0200/s0193_valid_phone_numbers)| Easy | Shell | 98 | 88.64 | 0192 |[Word Frequency](src/main/kotlin/g0101_0200/s0192_word_frequency)| Medium | Shell | 114 | 73.60 | 0191 |[Number of 1 Bits](src/main/kotlin/g0101_0200/s0191_number_of_1_bits)| Easy | Top_Interview_Questions, Bit_Manipulation, Algorithm_I_Day_13_Bit_Manipulation, Programming_Skills_I_Day_2_Operator, Udemy_Bit_Manipulation | 237 | 68.44 @@ -1712,7 +1754,7 @@ | 0172 |[Factorial Trailing Zeroes](src/main/kotlin/g0101_0200/s0172_factorial_trailing_zeroes)| Medium | Top_Interview_Questions, Math, Udemy_Integers | 220 | 67.65 | 0171 |[Excel Sheet Column Number](src/main/kotlin/g0101_0200/s0171_excel_sheet_column_number)| Easy | Top_Interview_Questions, String, Math | 310 | 30.68 | 0169 |[Majority Element](src/main/kotlin/g0101_0200/s0169_majority_element)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table, Sorting, Counting, Divide_and_Conquer, Data_Structure_II_Day_1_Array, Udemy_Famous_Algorithm | 460 | 51.25 -| 0168 |[Excel Sheet Column Title](src/main/kotlin/g0101_0200/s0168_excel_sheet_column_title)| Easy | String, Math | 246 | 30.12 +| 0168 |[Excel Sheet Column Title](src/main/kotlin/g0101_0200/s0168_excel_sheet_column_title)| Easy | String, Math | 208 | 66.07 | 0167 |[Two Sum II - Input Array Is Sorted](src/main/kotlin/g0101_0200/s0167_two_sum_ii_input_array_is_sorted)| Medium | Array, Binary_Search, Two_Pointers, Algorithm_I_Day_3_Two_Pointers, Binary_Search_I_Day_7 | 403 | 68.74 | 0166 |[Fraction to Recurring Decimal](src/main/kotlin/g0101_0200/s0166_fraction_to_recurring_decimal)| Medium | Top_Interview_Questions, String, Hash_Table, Math | 147 | 90.91 | 0165 |[Compare Version Numbers](src/main/kotlin/g0101_0200/s0165_compare_version_numbers)| Medium | String, Two_Pointers | 144 | 100.00 @@ -1745,17 +1787,17 @@ | 0132 |[Palindrome Partitioning II](src/main/kotlin/g0101_0200/s0132_palindrome_partitioning_ii)| Hard | String, Dynamic_Programming | 290 | 100.00 | 0131 |[Palindrome Partitioning](src/main/kotlin/g0101_0200/s0131_palindrome_partitioning)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming, Backtracking | 820 | 87.27 | 0130 |[Surrounded Regions](src/main/kotlin/g0101_0200/s0130_surrounded_regions)| Medium | Top_Interview_Questions, Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find, Algorithm_II_Day_8_Breadth_First_Search_Depth_First_Search | 355 | 84.42 -| 0129 |[Sum Root to Leaf Numbers](src/main/kotlin/g0101_0200/s0129_sum_root_to_leaf_numbers)| Medium | Depth_First_Search, Tree, Binary_Tree | 269 | 29.63 +| 0129 |[Sum Root to Leaf Numbers](src/main/kotlin/g0101_0200/s0129_sum_root_to_leaf_numbers)| Medium | Depth_First_Search, Tree, Binary_Tree | 237 | 52.50 | 0128 |[Longest Consecutive Sequence](src/main/kotlin/g0101_0200/s0128_longest_consecutive_sequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table, Union_Find | 460 | 97.77 | 0127 |[Word Ladder](src/main/kotlin/g0101_0200/s0127_word_ladder)| Hard | Top_Interview_Questions, String, Hash_Table, Breadth_First_Search, Graph_Theory_I_Day_12_Breadth_First_Search | 396 | 98.68 | 0126 |[Word Ladder II](src/main/kotlin/g0101_0200/s0126_word_ladder_ii)| Hard | String, Hash_Table, Breadth_First_Search, Backtracking | 418 | 51.45 | 0125 |[Valid Palindrome](src/main/kotlin/g0101_0200/s0125_valid_palindrome)| Easy | Top_Interview_Questions, String, Two_Pointers, Udemy_Two_Pointers | 353 | 52.06 | 0124 |[Binary Tree Maximum Path Sum](src/main/kotlin/g0101_0200/s0124_binary_tree_maximum_path_sum)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree, Udemy_Tree_Stack_Queue | 331 | 74.42 | 0123 |[Best Time to Buy and Sell Stock III](src/main/kotlin/g0101_0200/s0123_best_time_to_buy_and_sell_stock_iii)| Hard | Array, Dynamic_Programming | 585 | 95.24 -| 0122 |[Best Time to Buy and Sell Stock II](src/main/kotlin/g0101_0200/s0122_best_time_to_buy_and_sell_stock_ii)| Medium | Top_Interview_Questions, Array, Dynamic_Programming, Greedy, Dynamic_Programming_I_Day_7, Udemy_Arrays | 370 | 16.98 +| 0122 |[Best Time to Buy and Sell Stock II](src/main/kotlin/g0101_0200/s0122_best_time_to_buy_and_sell_stock_ii)| Medium | Top_Interview_Questions, Array, Dynamic_Programming, Greedy, Dynamic_Programming_I_Day_7, Udemy_Arrays | 197 | 95.10 | 0121 |[Best Time to Buy and Sell Stock](src/main/kotlin/g0101_0200/s0121_best_time_to_buy_and_sell_stock)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Data_Structure_I_Day_3_Array, Dynamic_Programming_I_Day_7, Level_1_Day_5_Greedy, Udemy_Arrays | 609 | 94.06 | 0120 |[Triangle](src/main/kotlin/g0101_0200/s0120_triangle)| Medium | Array, Dynamic_Programming, Algorithm_I_Day_12_Dynamic_Programming, Dynamic_Programming_I_Day_13, Udemy_Dynamic_Programming | 194 | 97.87 -| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming, Data_Structure_II_Day_3_Array, Dynamic_Programming_I_Day_12, Udemy_Dynamic_Programming | 296 | 19.15 +| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming, Data_Structure_II_Day_3_Array, Dynamic_Programming_I_Day_12, Udemy_Dynamic_Programming | 157 | 97.27 | 0118 |[Pascal's Triangle](src/main/kotlin/g0101_0200/s0118_pascals_triangle)| Easy | Top_Interview_Questions, Array, Dynamic_Programming, Data_Structure_I_Day_4_Array, Dynamic_Programming_I_Day_12, Udemy_Dynamic_Programming | 277 | 33.22 | 0117 |[Populating Next Right Pointers in Each Node II](src/main/kotlin/g0101_0200/s0117_populating_next_right_pointers_in_each_node_ii)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Linked_List, Algorithm_II_Day_7_Breadth_First_Search_Depth_First_Search | 199 | 94.67 | 0116 |[Populating Next Right Pointers in Each Node](src/main/kotlin/g0101_0200/s0116_populating_next_right_pointers_in_each_node)| Medium | Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Linked_List, Algorithm_I_Day_8_Breadth_First_Search_Depth_First_Search | 355 | 69.02 @@ -1772,8 +1814,8 @@ | 0105 |[Construct Binary Tree from Preorder and Inorder Traversal](src/main/kotlin/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table, Tree, Binary_Tree, Divide_and_Conquer, Data_Structure_II_Day_15_Tree | 370 | 58.31 | 0104 |[Maximum Depth of Binary Tree](src/main/kotlin/g0101_0200/s0104_maximum_depth_of_binary_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Data_Structure_I_Day_11_Tree, Programming_Skills_I_Day_10_Linked_List_and_Tree, Udemy_Tree_Stack_Queue | 236 | 83.39 | 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, Data_Structure_II_Day_15_Tree, Udemy_Tree_Stack_Queue | 316 | 34.25 -| 0102 |[Binary Tree Level Order Traversal](src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree, Data_Structure_I_Day_11_Tree, Level_1_Day_6_Tree, Udemy_Tree_Stack_Queue | 355 | 29.37 -| 0101 |[Symmetric Tree](src/main/kotlin/g0101_0200/s0101_symmetric_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Data_Structure_I_Day_11_Tree, Level_2_Day_15_Tree | 290 | 26.98 +| 0102 |[Binary Tree Level Order Traversal](src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree, Data_Structure_I_Day_11_Tree, Level_1_Day_6_Tree, Udemy_Tree_Stack_Queue | 332 | 67.53 +| 0101 |[Symmetric Tree](src/main/kotlin/g0101_0200/s0101_symmetric_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Data_Structure_I_Day_11_Tree, Level_2_Day_15_Tree | 190 | 91.36 | 0100 |[Same Tree](src/main/kotlin/g0001_0100/s0100_same_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Level_2_Day_15_Tree, Udemy_Tree_Stack_Queue | 208 | 72.24 | 0099 |[Recover Binary Search Tree](src/main/kotlin/g0001_0100/s0099_recover_binary_search_tree)| Medium | Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 492 | 39.39 | 0098 |[Validate Binary Search Tree](src/main/kotlin/g0001_0100/s0098_validate_binary_search_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree, Data_Structure_I_Day_14_Tree, Level_1_Day_8_Binary_Search_Tree, Udemy_Tree_Stack_Queue | 330 | 41.38 @@ -1796,7 +1838,7 @@ | 0081 |[Search in Rotated Sorted Array II](src/main/kotlin/g0001_0100/s0081_search_in_rotated_sorted_array_ii)| Medium | Array, Binary_Search, Binary_Search_II_Day_12 | 352 | 42.31 | 0080 |[Remove Duplicates from Sorted Array II](src/main/kotlin/g0001_0100/s0080_remove_duplicates_from_sorted_array_ii)| Medium | Array, Two_Pointers, Udemy_Arrays | 357 | 44.78 | 0079 |[Word Search](src/main/kotlin/g0001_0100/s0079_word_search)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Matrix, Backtracking, Algorithm_II_Day_11_Recursion_Backtracking | 463 | 68.49 -| 0078 |[Subsets](src/main/kotlin/g0001_0100/s0078_subsets)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation, Backtracking, Algorithm_II_Day_9_Recursion_Backtracking, Udemy_Backtracking/Recursion | 353 | 30.14 +| 0078 |[Subsets](src/main/kotlin/g0001_0100/s0078_subsets)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation, Backtracking, Algorithm_II_Day_9_Recursion_Backtracking, Udemy_Backtracking/Recursion | 191 | 97.44 | 0077 |[Combinations](src/main/kotlin/g0001_0100/s0077_combinations)| Medium | Backtracking, Algorithm_I_Day_11_Recursion_Backtracking | 244 | 100.00 | 0076 |[Minimum Window Substring](src/main/kotlin/g0001_0100/s0076_minimum_window_substring)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Sliding_Window, Level_2_Day_14_Sliding_Window/Two_Pointer | 346 | 85.20 | 0075 |[Sort Colors](src/main/kotlin/g0001_0100/s0075_sort_colors)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Data_Structure_II_Day_2_Array, Udemy_Arrays | 198 | 85.66 @@ -1814,7 +1856,7 @@ | 0063 |[Unique Paths II](src/main/kotlin/g0001_0100/s0063_unique_paths_ii)| Medium | Array, Dynamic_Programming, Matrix, Dynamic_Programming_I_Day_15 | 187 | 84.62 | 0062 |[Unique Paths](src/main/kotlin/g0001_0100/s0062_unique_paths)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Combinatorics, Algorithm_II_Day_13_Dynamic_Programming, Dynamic_Programming_I_Day_15, Level_1_Day_11_Dynamic_Programming | 209 | 49.18 | 0061 |[Rotate List](src/main/kotlin/g0001_0100/s0061_rotate_list)| Medium | Two_Pointers, Linked_List, Programming_Skills_II_Day_16, Udemy_Linked_List | 193 | 92.16 -| 0060 |[Permutation Sequence](src/main/kotlin/g0001_0100/s0060_permutation_sequence)| Hard | Math, Recursion | 293 | 27.78 +| 0060 |[Permutation Sequence](src/main/kotlin/g0001_0100/s0060_permutation_sequence)| Hard | Math, Recursion | 146 | 100.00 | 0059 |[Spiral Matrix II](src/main/kotlin/g0001_0100/s0059_spiral_matrix_ii)| Medium | Array, Matrix, Simulation, Data_Structure_II_Day_3_Array | 153 | 100.00 | 0058 |[Length of Last Word](src/main/kotlin/g0001_0100/s0058_length_of_last_word)| Easy | String, Programming_Skills_II_Day_6, Udemy_Arrays | 243 | 63.33 | 0057 |[Insert Interval](src/main/kotlin/g0001_0100/s0057_insert_interval)| Medium | Array, Level_2_Day_17_Interval | 257 | 99.52 diff --git a/src/main/kotlin/g0101_0200/s0129_sum_root_to_leaf_numbers/readme.md b/src/main/kotlin/g0101_0200/s0129_sum_root_to_leaf_numbers/readme.md index 1f686449..57645825 100644 --- a/src/main/kotlin/g0101_0200/s0129_sum_root_to_leaf_numbers/readme.md +++ b/src/main/kotlin/g0101_0200/s0129_sum_root_to_leaf_numbers/readme.md @@ -72,6 +72,7 @@ import com_github_leetcode.TreeNode */ class Solution { private var sum = 0 + fun sumNumbers(root: TreeNode): Int { recurseSum(root, 0) return sum diff --git a/src/main/kotlin/g0101_0200/s0168_excel_sheet_column_title/readme.md b/src/main/kotlin/g0101_0200/s0168_excel_sheet_column_title/readme.md index 86c798a6..13d53c0a 100644 --- a/src/main/kotlin/g0101_0200/s0168_excel_sheet_column_title/readme.md +++ b/src/main/kotlin/g0101_0200/s0168_excel_sheet_column_title/readme.md @@ -37,8 +37,8 @@ A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... ```kotlin class Solution { - fun convertToTitle(n: Int): String { - var num = n + fun convertToTitle(columnNumber: Int): String { + var num = columnNumber val sb = StringBuilder() while (num != 0) { var remainder = num % 26 diff --git a/src/main/kotlin/g0301_0400/s0341_flatten_nested_list_iterator/readme.md b/src/main/kotlin/g0301_0400/s0341_flatten_nested_list_iterator/readme.md new file mode 100644 index 00000000..f56846f6 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0341_flatten_nested_list_iterator/readme.md @@ -0,0 +1,109 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 341\. Flatten Nested List Iterator + +Medium + +You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. + +Implement the `NestedIterator` class: + +* `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`. +* `int next()` Returns the next integer in the nested list. +* `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise. + +Your code will be tested with the following pseudocode: + + initialize iterator with nestedList + res = [] + while iterator.hasNext() + append iterator.next() to the end of res + return res + +If `res` matches the expected flattened list, then your code will be judged as correct. + +**Example 1:** + +**Input:** nestedList = \[\[1,1],2,[1,1]] + +**Output:** [1,1,2,1,1] + +**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. + +**Example 2:** + +**Input:** nestedList = [1,[4,[6]]] + +**Output:** [1,4,6] + +**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. + +**Constraints:** + +* `1 <= nestedList.length <= 500` +* The values of the integers in the nested list is in the range [-106, 106]. + +## Solution + +```kotlin +import com_github_leetcode.NestedInteger + +/* + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * // Constructor initializes an empty nested list. + * constructor() + * + * // Constructor initializes a single integer. + * constructor(value: Int) + * + * // @return true if this NestedInteger holds a single integer, rather than a nested list. + * fun isInteger(): Boolean + * + * // @return the single integer that this NestedInteger holds, if it holds a single integer + * // Return null if this NestedInteger holds a nested list + * fun getInteger(): Int? + * + * // Set this NestedInteger to hold a single integer. + * fun setInteger(value: Int): Unit + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * fun add(ni: NestedInteger): Unit + * + * // @return the nested list that this NestedInteger holds, if it holds a nested list + * // Return null if this NestedInteger holds a single integer + * fun getList(): List? + * } + */ +class NestedIterator(nestedList: List) { + private var flattenList = mutableListOf() + private var index = 0 + + init { + flatten(nestedList, flattenList) + } + + private fun flatten(nestedList: List, flattenList: MutableList) { + nestedList.forEach { nestedInteger -> + if (nestedInteger.isInteger()) { + flattenList.add(nestedInteger.getInteger()!!) + } else { + flatten(nestedInteger.getList()!!, flattenList) + } + } + } + + fun next(): Int = flattenList[index++] + + fun hasNext(): Boolean = index < flattenList.size +} + +/* + * Your NestedIterator object will be instantiated and called as such: + * var obj = NestedIterator(nestedList) + * var param_1 = obj.next() + * var param_2 = obj.hasNext() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0371_sum_of_two_integers/readme.md b/src/main/kotlin/g0301_0400/s0371_sum_of_two_integers/readme.md new file mode 100644 index 00000000..45018882 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0371_sum_of_two_integers/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 371\. Sum of Two Integers + +Medium + +Given two integers `a` and `b`, return _the sum of the two integers without using the operators_ `+` _and_ `-`. + +**Example 1:** + +**Input:** a = 1, b = 2 + +**Output:** 3 + +**Example 2:** + +**Input:** a = 2, b = 3 + +**Output:** 5 + +**Constraints:** + +* `-1000 <= a, b <= 1000` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun getSum(a: Int, b: Int): Int { + var a = a + var b = b + var ans = 0 + var memo = 0 + var exp = 0 + var count = 0 + while (count < 32) { + val val1 = a and 1 + val val2 = b and 1 + var `val` = sum(val1, val2, memo) + memo = `val` shr 1 + `val` = `val` and 1 + a = a shr 1 + b = b shr 1 + ans = ans or (`val` shl exp) + exp = plusOne(exp) + count = plusOne(count) + } + return ans + } + + private fun sum(val1: Int, val2: Int, val3: Int): Int { + var count = 0 + if (val1 == 1) { + count = plusOne(count) + } + if (val2 == 1) { + count = plusOne(count) + } + if (val3 == 1) { + count = plusOne(count) + } + return count + } + + private fun plusOne(`val`: Int): Int { + return -`val`.inv() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0372_super_pow/readme.md b/src/main/kotlin/g0301_0400/s0372_super_pow/readme.md new file mode 100644 index 00000000..37d4baee --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0372_super_pow/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) + +## 372\. Super Pow + +Medium + +Your task is to calculate ab mod `1337` where `a` is a positive integer and `b` is an extremely large positive integer given in the form of an array. + +**Example 1:** + +**Input:** a = 2, b = [3] + +**Output:** 8 + +**Example 2:** + +**Input:** a = 2, b = [1,0] + +**Output:** 1024 + +**Example 3:** + +**Input:** a = 1, b = [4,3,3,8,5,2] + +**Output:** 1 + +**Constraints:** + +* 1 <= a <= 231 - 1 +* `1 <= b.length <= 2000` +* `0 <= b[i] <= 9` +* `b` does not contain leading zeros. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun superPow(a: Int, b: IntArray): Int { + val phi = phi(MOD) + val arrMod = arrMod(b, phi) + return if (isGreaterOrEqual(b, phi)) { + // Cycle has started + // cycle starts at phi with length phi + exp(a % MOD, phi + arrMod) + } else exp(a % MOD, arrMod) + } + + private fun phi(n: Int): Int { + var n = n + var result = n.toDouble() + var p = 2 + while (p * p <= n) { + if (n % p > 0) { + p++ + continue + } + while (n % p == 0) { + n /= p + } + result *= 1.0 - 1.0 / p + p++ + } + if (n > 1) { + // if starting n was also prime (so it was greater than sqrt(n)) + result *= 1.0 - 1.0 / n + } + return result.toInt() + } + + // Returns true if number in array is greater than integer named phi + private fun isGreaterOrEqual(b: IntArray, phi: Int): Boolean { + var cur = 0 + for (j in b) { + cur = cur * 10 + j + if (cur >= phi) { + return true + } + } + return false + } + + // Returns number in array mod phi + private fun arrMod(b: IntArray, phi: Int): Int { + var res = 0 + for (j in b) { + res = (res * 10 + j) % phi + } + return res + } + + // Binary exponentiation + private fun exp(a: Int, b: Int): Int { + var a = a + var b = b + var y = 1 + while (b > 0) { + if (b % 2 == 1) { + y = y * a % MOD + } + a = a * a % MOD + b /= 2 + } + return y + } + + companion object { + private const val MOD = 1337 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0373_find_k_pairs_with_smallest_sums/readme.md b/src/main/kotlin/g0301_0400/s0373_find_k_pairs_with_smallest_sums/readme.md new file mode 100644 index 00000000..7692f233 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0373_find_k_pairs_with_smallest_sums/readme.md @@ -0,0 +1,90 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 373\. Find K Pairs with Smallest Sums + +Medium + +You are given two integer arrays `nums1` and `nums2` sorted in **ascending order** and an integer `k`. + +Define a pair `(u, v)` which consists of one element from the first array and one element from the second array. + +Return _the_ `k` _pairs_ (u1, v1), (u2, v2), ..., (uk, vk) _with the smallest sums_. + +**Example 1:** + +**Input:** nums1 = [1,7,11], nums2 = [2,4,6], k = 3 + +**Output:** [[1,2],[1,4],[1,6]] + +**Explanation:** The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] + +**Example 2:** + +**Input:** nums1 = [1,1,2], nums2 = [1,2,3], k = 2 + +**Output:** [[1,1],[1,1]] + +**Explanation:** The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] + +**Example 3:** + +**Input:** nums1 = [1,2], nums2 = [3], k = 3 + +**Output:** [[1,3],[2,3]] + +**Explanation:** All possible pairs are returned from the sequence: [1,3],[2,3] + +**Constraints:** + +* 1 <= nums1.length, nums2.length <= 105 +* -109 <= nums1[i], nums2[i] <= 109 +* `nums1` and `nums2` both are sorted in **ascending order**. +* 1 <= k <= 104 + +## Solution + +```kotlin +import java.util.PriorityQueue +import kotlin.collections.ArrayList + +class Solution { + private class Node(index: Int, num1: Int, num2: Int) { + var sum: Long + var al: MutableList + var index: Int + + init { + sum = num1.toLong() + num2.toLong() + al = ArrayList() + al.add(num1) + al.add(num2) + this.index = index + } + } + + fun kSmallestPairs(nums1: IntArray, nums2: IntArray, k: Int): List> { + val queue = PriorityQueue { a: Node, b: Node -> if (a.sum < b.sum) -1 else 1 } + val res: MutableList> = ArrayList() + run { + var i = 0 + while (i < nums1.size && i < k) { + queue.add(Node(0, nums1[i], nums2[0])) + i++ + } + } + var i = 1 + while (i <= k && !queue.isEmpty()) { + val cur = queue.poll() + res.add(cur.al) + val next = cur.index + val lastNum1 = cur.al[0] + if (next + 1 < nums2.size) { + queue.add(Node(next + 1, lastNum1, nums2[next + 1])) + } + i++ + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0374_guess_number_higher_or_lower/readme.md b/src/main/kotlin/g0301_0400/s0374_guess_number_higher_or_lower/readme.md new file mode 100644 index 00000000..bc151732 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0374_guess_number_higher_or_lower/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) + +## 374\. Guess Number Higher or Lower + +Easy + +We are playing the Guess Game. The game is as follows: + +I pick a number from `1` to `n`. You have to guess which number I picked. + +Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. + +You call a pre-defined API `int guess(int num)`, which returns three possible results: + +* `-1`: Your guess is higher than the number I picked (i.e. `num > pick`). +* `1`: Your guess is lower than the number I picked (i.e. `num < pick`). +* `0`: your guess is equal to the number I picked (i.e. `num == pick`). + +Return _the number that I picked_. + +**Example 1:** + +**Input:** n = 10, pick = 6 + +**Output:** 6 + +**Example 2:** + +**Input:** n = 1, pick = 1 + +**Output:** 1 + +**Example 3:** + +**Input:** n = 2, pick = 1 + +**Output:** 1 + +**Constraints:** + +* 1 <= n <= 231 - 1 +* `1 <= pick <= n` + +## Solution + +```kotlin +/* + * The API guess is defined in the parent class. + * @param num your guess + * @return -1 if num is higher than the picked number + * 1 if num is lower than the picked number + * otherwise return 0 + * fun guess(num:Int):Int {} + */ + +class Solution : GuessGame() { + fun guessNumber(n: Int): Int { + var start = 0 + var end = n + while (start <= end) { + val mid = start + (end - start) / 2 + if (guess(mid) == 0) { + return mid + } else if (guess(mid) == -1) { + end = mid - 1 + } else { + start = mid + 1 + } + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0375_guess_number_higher_or_lower_ii/readme.md b/src/main/kotlin/g0301_0400/s0375_guess_number_higher_or_lower_ii/readme.md new file mode 100644 index 00000000..60e1a3cd --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0375_guess_number_higher_or_lower_ii/readme.md @@ -0,0 +1,114 @@ +[![](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) + +## 375\. Guess Number Higher or Lower II + +Medium + +We are playing the Guessing Game. The game will work as follows: + +1. I pick a number between `1` and `n`. +2. You guess a number. +3. If you guess the right number, **you win the game**. +4. If you guess the wrong number, then I will tell you whether the number I picked is **higher or lower**, and you will continue guessing. +5. Every time you guess a wrong number `x`, you will pay `x` dollars. If you run out of money, **you lose the game**. + +Given a particular `n`, return _the minimum amount of money you need to **guarantee a win regardless of what number I pick**_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/10/graph.png) + +**Input:** n = 10 + +**Output:** 16 + +**Explanation:** + + The winning strategy is as follows: + - The range is [1,10]. Guess 7. + - If this is my number, your total is $0. Otherwise, you pay $7. + - If my number is higher, the range is [8,10]. Guess 9. + - If this is my number, your total is $7. Otherwise, you pay $9. + - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16. + - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16. + - If my number is lower, the range is [1,6]. Guess 3. + - If this is my number, your total is $7. Otherwise, you pay $3. + - If my number is higher, the range is [4,6]. Guess 5. + - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5. + - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15. + - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15. + - If my number is lower, the range is [1,2]. Guess 1. + - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1. + - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11. + The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win. + +**Example 2:** + +**Input:** n = 1 + +**Output:** 0 + +**Explanation:** There is only one possible number, so you can guess 1 and not have to pay anything. + +**Example 3:** + +**Input:** n = 2 + +**Output:** 1 + +**Explanation:** + + There are two possible numbers, 1 and 2. + - Guess 1. + - If this is my number, your total is $0. Otherwise, you pay $1. + - If my number is higher, it must be 2. Guess 2. Your total is $1. + The worst case is that you pay $1. + +**Constraints:** + +* `1 <= n <= 200` + +## Solution + +```kotlin +class Solution { + lateinit var matrix: Array + fun getMoneyAmount(n: Int): Int { + matrix = Array(n + 1) { IntArray(n + 1) } + return get(1, n) + } + + private operator fun get(min: Int, max: Int): Int { + if (max - min < 3) { + return if (max - min <= 0) 0 else max - 1 + } + if (matrix[min][max] != 0) { + return matrix[min][max] + } + var select = max - 3 + var minRes = Int.MAX_VALUE + var res: Int + val end = min + (max - min shr 1) - 1 + var cnt = 0 + while (true) { + res = select + Math.max(get(min, select - 1), get(select + 1, max)) + if (res > minRes) { + cnt++ + if (cnt >= 3) { + break + } + } + if (res < minRes) { + minRes = res + } + select-- + if (select <= end) { + break + } + } + matrix[min][max] = minRes + return minRes + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0376_wiggle_subsequence/readme.md b/src/main/kotlin/g0301_0400/s0376_wiggle_subsequence/readme.md new file mode 100644 index 00000000..6fa8bdfe --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0376_wiggle_subsequence/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) + +## 376\. Wiggle Subsequence + +Medium + +A **wiggle sequence** is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. + +* For example, `[1, 7, 4, 9, 2, 5]` is a **wiggle sequence** because the differences `(6, -3, 5, -7, 3)` alternate between positive and negative. +* In contrast, `[1, 4, 7, 2, 5]` and `[1, 7, 4, 5, 5]` are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero. + +A **subsequence** is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. + +Given an integer array `nums`, return _the length of the longest **wiggle subsequence** of_ `nums`. + +**Example 1:** + +**Input:** nums = [1,7,4,9,2,5] + +**Output:** 6 + +**Explanation:** The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3). + +**Example 2:** + +**Input:** nums = [1,17,5,10,13,15,10,5,16,8] + +**Output:** 7 + +**Explanation:** There are several subsequences that achieve this length. One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8). + +**Example 3:** + +**Input:** nums = [1,2,3,4,5,6,7,8,9] + +**Output:** 2 + +**Constraints:** + +* `1 <= nums.length <= 1000` +* `0 <= nums[i] <= 1000` + +**Follow up:** Could you solve this in `O(n)` time? + +## Solution + +```kotlin +class Solution { + fun wiggleMaxLength(nums: IntArray): Int { + var lt = 1 + var gt = 1 + for (i in 1 until nums.size) { + if (nums[i - 1] < nums[i]) { + lt = gt + 1 + } else if (nums[i - 1] > nums[i]) { + gt = lt + 1 + } + } + return Math.max(lt, gt) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0377_combination_sum_iv/readme.md b/src/main/kotlin/g0301_0400/s0377_combination_sum_iv/readme.md new file mode 100644 index 00000000..1dcd4c2a --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0377_combination_sum_iv/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) + +## 377\. Combination Sum IV + +Medium + +Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`. + +The test cases are generated so that the answer can fit in a **32-bit** integer. + +**Example 1:** + +**Input:** nums = [1,2,3], target = 4 + +**Output:** 7 + +**Explanation:** + + The possible combination ways are: + (1, 1, 1, 1) + (1, 1, 2) + (1, 2, 1) + (1, 3) + (2, 1, 1) + (2, 2) + (3, 1) + Note that different sequences are counted as different combinations. + +**Example 2:** + +**Input:** nums = [9], target = 3 + +**Output:** 0 + +**Constraints:** + +* `1 <= nums.length <= 200` +* `1 <= nums[i] <= 1000` +* All the elements of `nums` are **unique**. +* `1 <= target <= 1000` + +**Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers? + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + private lateinit var storage: IntArray + + fun combinationSum4(nums: IntArray, target: Int): Int { + storage = IntArray(target + 1) + Arrays.fill(storage, -1) + return result(nums, target) + } + + private fun result(nums: IntArray, target: Int): Int { + if (target < 0) { + return 0 + } + if (target == 0) { + return 1 + } + if (storage[target] != -1) { + return storage[target] + } + var count = 0 + for (i in nums) { + count += result(nums, target - i) + } + storage[target] = count + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0380_insert_delete_getrandom_o1/readme.md b/src/main/kotlin/g0301_0400/s0380_insert_delete_getrandom_o1/readme.md new file mode 100644 index 00000000..06c51d6c --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0380_insert_delete_getrandom_o1/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) + +## 380\. Insert Delete GetRandom O(1) + +Medium + +Implement the `RandomizedSet` class: + +* `RandomizedSet()` Initializes the `RandomizedSet` object. +* `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. +* `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. +* `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. + +You must implement the functions of the class such that each function works in **average** `O(1)` time complexity. + +**Example 1:** + +**Input** + + ["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"] + [[], [1], [2], [2], [], [1], [2], []] + +**Output:** [null, true, false, true, 2, true, false, 2] + +**Explanation:** + + RandomizedSet randomizedSet = new RandomizedSet(); + randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. + randomizedSet.remove(2); // Returns false as 2 does not exist in the set. + randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. + randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. + randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2]. + randomizedSet.insert(2); // 2 was already in the set, so return false. + randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. + +**Constraints:** + +* -231 <= val <= 231 - 1 +* At most `2 * `105 calls will be made to `insert`, `remove`, and `getRandom`. +* There will be **at least one** element in the data structure when `getRandom` is called. + +## Solution + +```kotlin +import kotlin.random.Random + +@Suppress("kotlin:S2245") +class RandomizedSet { + private val list: MutableList + private val map: MutableMap + + /* Initialize your data structure here. */ + init { + list = ArrayList() + map = HashMap() + } + + /* Inserts a value to the set. Returns true if the set did not already contain the specified element. */ + fun insert(`val`: Int): Boolean { + if (map.containsKey(`val`)) { + return false + } + map[`val`] = list.size + list.add(`val`) + return true + } + + /* Removes a value from the set. Returns true if the set contained the specified element. */ + fun remove(`val`: Int): Boolean { + if (!map.containsKey(`val`)) { + return false + } + val swap1 = map[`val`]!! + val swap2 = list.size - 1 + val val2 = list[swap2] + map[val2] = swap1 + map.remove(`val`) + list[swap1] = val2 + list.removeAt(list.size - 1) + return true + } + + /* Get a random element from the set. */ + fun getRandom(): Int { + return list[Random.nextInt(list.size)] + } +} + +/* + * Your RandomizedSet object will be instantiated and called as such: + * var obj = RandomizedSet() + * var param_1 = obj.insert(`val`) + * var param_2 = obj.remove(`val`) + * var param_3 = obj.getRandom() + */ +``` \ No newline at end of file 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 new file mode 100644 index 00000000..0189e121 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0381_insert_delete_getrandom_o1_duplicates_allowed/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) + +## 381\. Insert Delete GetRandom O(1) - Duplicates allowed + +Hard + +`RandomizedCollection` is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also removing a random element. + +Implement the `RandomizedCollection` class: + +* `RandomizedCollection()` Initializes the empty `RandomizedCollection` object. +* `bool insert(int val)` Inserts an item `val` into the multiset, even if the item is already present. Returns `true` if the item is not present, `false` otherwise. +* `bool remove(int val)` Removes an item `val` from the multiset if present. Returns `true` if the item is present, `false` otherwise. Note that if `val` has multiple occurrences in the multiset, we only remove one of them. +* `int getRandom()` Returns a random element from the current multiset of elements. The probability of each element being returned is **linearly related** to the number of same values the multiset contains. + +You must implement the functions of the class such that each function works on **average** `O(1)` time complexity. + +**Note:** The test cases are generated such that `getRandom` will only be called if there is **at least one** item in the `RandomizedCollection`. + +**Example 1:** + +**Input** + + ["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"] + [[], [1], [1], [2], [], [1], []] + +**Output:** [null, true, false, true, 2, true, 1] + +**Explanation:** + + RandomizedCollection randomizedCollection = new RandomizedCollection(); + randomizedCollection.insert(1); // return true since the collection does not contain 1. + // Inserts 1 into the collection. + randomizedCollection.insert(1); // return false since the collection contains 1. + // Inserts another 1 into the collection. Collection now contains [1,1]. + randomizedCollection.insert(2); // return true since the collection does not contain 2. + // Inserts 2 into the collection. Collection now contains [1,1,2]. + randomizedCollection.getRandom(); // getRandom should: + // - return 1 with probability 2/3, or + // - return 2 with probability 1/3. + randomizedCollection.remove(1); // return true since the collection contains 1. + // Removes 1 from the collection. Collection now contains [1,2]. + randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely. + +**Constraints:** + +* -231 <= val <= 231 - 1 +* At most 2 * 105 calls **in total** will be made to `insert`, `remove`, and `getRandom`. +* There will be **at least one** element in the data structure when `getRandom` is called. + +## Solution + +```kotlin +@Suppress("kotlin:S2245") +class RandomizedCollection() { + val m2a = HashMap>() + val a2m = ArrayList() + /** Initialize your data structure here. */ + + /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ + fun insert(x: Int): Boolean { + a2m.add(x) + val pos = a2m.size - 1 + if (x in m2a) { + m2a[x]!!.add(pos) + return false + } else { + m2a[x] = HashSet() + m2a[x]!!.add(pos) + return true + } + } + + /** Removes a value from the collection. Returns true if the collection contained the specified element. */ + fun remove(x: Int): Boolean { + if (x !in m2a) + return false + val pos = m2a[x]!!.iterator().next() + if (m2a[x]!!.size == 1) + m2a.remove(x) + else + m2a[x]!!.remove(pos) + if (pos != a2m.size - 1) { + m2a[a2m[a2m.size - 1]]!!.remove(a2m.size - 1) + m2a[a2m[a2m.size - 1]]!!.add(pos) + a2m[pos] = a2m[a2m.size - 1] + } + a2m.removeAt(a2m.size - 1) + return true + } + + /** Get a random element from the collection. */ + fun getRandom(): Int { + val pos = Math.floor(Math.random() * a2m.size).toInt() + return a2m[pos] + } +} + +/* + * Your RandomizedCollection object will be instantiated and called as such: + * var obj = RandomizedCollection() + * var param_1 = obj.insert(`val`) + * var param_2 = obj.remove(`val`) + * var param_3 = obj.getRandom() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0382_linked_list_random_node/readme.md b/src/main/kotlin/g0301_0400/s0382_linked_list_random_node/readme.md new file mode 100644 index 00000000..e1894356 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0382_linked_list_random_node/readme.md @@ -0,0 +1,94 @@ +[![](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) + +## 382\. Linked List Random Node + +Medium + +Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen. + +Implement the `Solution` class: + +* `Solution(ListNode head)` Initializes the object with the integer array nums. +* `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be choosen. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/16/getrand-linked-list.jpg) + +**Input** + + ["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"] + [[[1, 2, 3]], [], [], [], [], []] + +**Output:** + + [null, 1, 3, 2, 2, 3] + +**Explanation:** + + Solution solution = new Solution([1, 2, 3]); + solution.getRandom(); // return 1 + solution.getRandom(); // return 3 + solution.getRandom(); // return 2 + solution.getRandom(); // return 2 + solution.getRandom(); // return 3 + // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. + +**Constraints:** + +* The number of nodes in the linked list will be in the range [1, 104]. +* -104 <= Node.val <= 104 +* At most 104 calls will be made to `getRandom`. + +**Follow up:** + +* What if the linked list is extremely large and its length is unknown to you? +* Could you solve this efficiently without using extra space? + +## Solution + +```kotlin +import com_github_leetcode.ListNode +import kotlin.random.Random + +/* + * Example: + * var li = ListNode(5) + * var v = li.`val` + * Definition for singly-linked list. + * class ListNode(var `val`: Int) { + * var next: ListNode? = null + * } + */ +@Suppress("NAME_SHADOWING", "kotlin:S2245") +class Solution(head: ListNode?) { + private val al: MutableList + + init { + var head = head + al = ArrayList() + while (head != null) { + al.add(head.`val`) + head = head.next + } + } + + fun getRandom(): Int { + /* + Math.random() will generate a random number b/w 0 & 1. + then multiply it with the array size. + take only the integer part which is a random index. + return the element at that random index. + */ + val ind = Random.nextInt(al.size) + return al[ind] + } +} + +/* + * Your Solution object will be instantiated and called as such: + * var obj = Solution(head) + * var param_1 = obj.getRandom() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0383_ransom_note/readme.md b/src/main/kotlin/g0301_0400/s0383_ransom_note/readme.md new file mode 100644 index 00000000..35bbaa80 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0383_ransom_note/readme.md @@ -0,0 +1,56 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 383\. Ransom Note + +Easy + +Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_. + +Each letter in `magazine` can only be used once in `ransomNote`. + +**Example 1:** + +**Input:** ransomNote = "a", magazine = "b" + +**Output:** false + +**Example 2:** + +**Input:** ransomNote = "aa", magazine = "ab" + +**Output:** false + +**Example 3:** + +**Input:** ransomNote = "aa", magazine = "aab" + +**Output:** true + +**Constraints:** + +* 1 <= ransomNote.length, magazine.length <= 105 +* `ransomNote` and `magazine` consist of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun canConstruct(ransomNote: String, magazine: String): Boolean { + val a = IntArray(26) + var n = ransomNote.length + for (i in 0 until n) { + a[ransomNote[i].code - 97]++ + } + var i = 0 + while (i < magazine.length && n != 0) { + if (a[magazine[i].code - 97] > 0) { + n-- + a[magazine[i].code - 97]-- + } + i++ + } + return n == 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0384_shuffle_an_array/readme.md b/src/main/kotlin/g0301_0400/s0384_shuffle_an_array/readme.md new file mode 100644 index 00000000..97d46391 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0384_shuffle_an_array/readme.md @@ -0,0 +1,66 @@ +[![](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) + +## 384\. Shuffle an Array + +Medium + +Given an integer array `nums`, design an algorithm to randomly shuffle the array. All permutations of the array should be **equally likely** as a result of the shuffling. + +Implement the `Solution` class: + +* `Solution(int[] nums)` Initializes the object with the integer array `nums`. +* `int[] reset()` Resets the array to its original configuration and returns it. +* `int[] shuffle()` Returns a random shuffling of the array. + +**Example 1:** + +**Input** ["Solution", "shuffle", "reset", "shuffle"] [[[1, 2, 3]], [], [], []] + +**Output:** [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]] + +**Explanation:** Solution solution = new Solution([1, 2, 3]); solution.shuffle(); // Shuffle the array [1,2,3] and return its result. // Any permutation of [1,2,3] must be equally likely to be returned. // Example: return [3, 1, 2] solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2] + +**Constraints:** + +* `1 <= nums.length <= 50` +* -106 <= nums[i] <= 106 +* All the elements of `nums` are **unique**. +* At most 104 calls **in total** will be made to `reset` and `shuffle`. + +## Solution + +```kotlin +import kotlin.random.Random + +@Suppress("kotlin:S2245") +class Solution(private val nums: IntArray) { + // Resets the array to its original configuration and return it. + fun reset(): IntArray { + return nums + } + + // Returns a random shuffling of the array. + fun shuffle(): IntArray { + val shuffled = nums.clone() + for (i in nums.size - 1 downTo 1) { + val j: Int = Random.nextInt(i + 1) + swap(shuffled, i, j) + } + return shuffled + } + + private fun swap(shuffled: IntArray, i: Int, j: Int) { + val tmp = shuffled[i] + shuffled[i] = shuffled[j] + shuffled[j] = tmp + } +} + +/* + * Your Solution object will be instantiated and called as such: + * var obj = Solution(nums) + * var param_1 = obj.reset() + * var param_2 = obj.shuffle() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0385_mini_parser/readme.md b/src/main/kotlin/g0301_0400/s0385_mini_parser/readme.md new file mode 100644 index 00000000..bf507345 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0385_mini_parser/readme.md @@ -0,0 +1,110 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 385\. Mini Parser + +Medium + +Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return _the deserialized_ `NestedInteger`. + +Each element is either an integer or a list whose elements may also be integers or other lists. + +**Example 1:** + +**Input:** s = "324" + +**Output:** 324 + +**Explanation:** You should return a NestedInteger object which contains a single integer 324. + +**Example 2:** + +**Input:** s = "[123,[456,[789]]]" + +**Output:** [123,[456,[789]]] + +**Explanation:** +Return a NestedInteger object containing a nested list with 2 elements: +1. An integer containing value 123. +2. A nested list containing two elements: + + i. An integer containing value 456. + + ii. A nested list with one element: + + a. An integer containing value 789 + +**Constraints:** + +* 1 <= s.length <= 5 * 104 +* `s` consists of digits, square brackets `"[]"`, negative sign `'-'`, and commas `','`. +* `s` is the serialization of valid `NestedInteger`. +* All the values in the input are in the range [-106, 106]. + +## Solution + +```kotlin +import com_github_leetcode.NestedInteger + +/* + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * // Constructor initializes an empty nested list. + * constructor() + * + * // Constructor initializes a single integer. + * constructor(value: Int) + * + * // @return true if this NestedInteger holds a single integer, rather than a nested list. + * fun isInteger(): Boolean + * + * // @return the single integer that this NestedInteger holds, if it holds a single integer + * // Return null if this NestedInteger holds a nested list + * fun getInteger(): Int? + * + * // Set this NestedInteger to hold a single integer. + * fun setInteger(value: Int): Unit + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * fun add(ni: NestedInteger): Unit + * + * // @return the nested list that this NestedInteger holds, if it holds a nested list + * // Return null if this NestedInteger holds a single integer + * fun getList(): List? + * } + */ +class Solution { + private var i = 0 + fun deserialize(s: String): NestedInteger { + return getAns(s) + } + + private fun getAns(s: String): NestedInteger { + return if (s[i] == '[') { + val ni = NestedInteger() + i++ + while (i < s.length && s[i] != ']') { + ni.add(getAns(s)) + } + i++ + ni + } else if (s[i] == ',') { + i++ + getAns(s) + } else { + var x = 0 + var m = 1 + if (s[i] == '-') { + i++ + m = -1 + } + while (i < s.length && Character.isDigit(s[i])) { + x = x * 10 + s[i++].code - '0'.code + } + x *= m + NestedInteger(x) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0386_lexicographical_numbers/readme.md b/src/main/kotlin/g0301_0400/s0386_lexicographical_numbers/readme.md new file mode 100644 index 00000000..8581b19d --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0386_lexicographical_numbers/readme.md @@ -0,0 +1,47 @@ +[![](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) + +## 386\. Lexicographical Numbers + +Medium + +Given an integer `n`, return all the numbers in the range `[1, n]` sorted in lexicographical order. + +You must write an algorithm that runs in `O(n)` time and uses `O(1)` extra space. + +**Example 1:** + +**Input:** n = 13 + +**Output:** [1,10,11,12,13,2,3,4,5,6,7,8,9] + +**Example 2:** + +**Input:** n = 2 + +**Output:** [1,2] + +**Constraints:** + +* 1 <= n <= 5 * 104 + +## Solution + +```kotlin +class Solution { + fun lexicalOrder(n: Int): List { + val list = ArrayList() + fun recursion(x: Int) { + if (x > n) return + list.add(x) + for (i in 0..9) { + recursion(x * 10 + i) + } + } + for (i in 1..9) { + recursion(i) + } + return list + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0387_first_unique_character_in_a_string/readme.md b/src/main/kotlin/g0301_0400/s0387_first_unique_character_in_a_string/readme.md new file mode 100644 index 00000000..dd53c196 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0387_first_unique_character_in_a_string/readme.md @@ -0,0 +1,52 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 387\. First Unique Character in a String + +Easy + +Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`. + +**Example 1:** + +**Input:** s = "leetcode" + +**Output:** 0 + +**Example 2:** + +**Input:** s = "loveleetcode" + +**Output:** 2 + +**Example 3:** + +**Input:** s = "aabb" + +**Output:** -1 + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` consists of only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun firstUniqChar(s: String): Int { + var ans = Int.MAX_VALUE + var i = 'a' + while (i <= 'z') { + val ind = s.indexOf(i) + if (ind != -1 && ind == s.lastIndexOf(i)) { + ans = Math.min(ans, ind) + } + i++ + } + return if (ans == Int.MAX_VALUE) { + -1 + } else ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0388_longest_absolute_file_path/readme.md b/src/main/kotlin/g0301_0400/s0388_longest_absolute_file_path/readme.md new file mode 100644 index 00000000..e0825c15 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0388_longest_absolute_file_path/readme.md @@ -0,0 +1,142 @@ +[![](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) + +## 388\. Longest Absolute File Path + +Medium + +Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: + +![](https://assets.leetcode.com/uploads/2020/08/28/mdir.jpg) + +Here, we have `dir` as the only directory in the root. `dir` contains two subdirectories, `subdir1` and `subdir2`. `subdir1` contains a file `file1.ext` and subdirectory `subsubdir1`. `subdir2` contains a subdirectory `subsubdir2`, which contains a file `file2.ext`. + +In text form, it looks like this (with ⟶ representing the tab character): + + dir + ⟶ subdir1 + ⟶ ⟶ file1.ext + ⟶ ⟶ subsubdir1 + ⟶ subdir2 + ⟶ ⟶ subsubdir2 + ⟶ ⟶ ⟶ file2.ext + +If we were to write this representation in code, it will look like this: +`"dir\tsubdir1\t\tfile1.ext\t\tsubsubdir1\tsubdir2\t\tsubsubdir2\t\t\tfile2.ext"`. Note that the `' +'` and `'\t'` are the new-line and tab characters. + +Every file and directory has a unique **absolute path** in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by `'/'s`. Using the above example, the **absolute path** to `file2.ext` is `"dir/subdir2/subsubdir2/file2.ext"`. Each directory name consists of letters, digits, and/or spaces. Each file name is of the form `name.extension`, where `name` and `extension` consist of letters, digits, and/or spaces. + +Given a string `input` representing the file system in the explained format, return _the length of the **longest absolute path** to a **file** in the abstracted file system_. If there is no file in the system, return `0`. + +**Note** that the testcases are generated such that the file system is valid and no file or directory name has length 0. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/08/28/dir1.jpg) + +**Input:** input = "dir\n\\tsubdir1\n\\tsubdir2\n\\t\\tfile.ext" + +**Output:** 20 + +**Explanation:** We have only one file, and the absolute path is "dir/subdir2/file.ext" of length 20. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/08/28/dir2.jpg) + +**Input:** input = "dir\n\\tsubdir1\n\\t\\tfile1.ext\n\\t\\tsubsubdir1\n\\tsubdir2\n\\t\\tsubsubdir2\n\\t\\t\\tfile2.ext" + +**Output:** 32 + +**Explanation:** We have two files: + +"dir/subdir1/file1.ext" of length 21 + +"dir/subdir2/subsubdir2/file2.ext" of length 32. + +We return 32 since it is the longest absolute path to a file. + +**Example 3:** + +**Input:** input = "a" + +**Output:** 0 + +**Explanation:** We do not have any files, just a single directory named "a". + +**Constraints:** + +* 1 <= input.length <= 104 +* `input` may contain lowercase or uppercase English letters, a new line character `' + '`, a tab character `'\t'`, a dot `'.'`, a space `' '`, and digits. +* All file and directory names have **positive** length. + +## Solution + +```kotlin +import java.util.ArrayDeque +import java.util.Deque + +class Solution { + fun lengthLongestPath(input: String): Int { + val stack: Deque = ArrayDeque() + var longestLen = 0 + var currDirLen = 0 + var i = 0 + var currLevel: Int + var nextLevel = 0 + var isFile = false + val period = '.' + val space = ' ' + while (i < input.length) { + currLevel = nextLevel + var currStrLen = 0 + while (i < input.length && + (Character.isLetterOrDigit(input[i]) || period == input[i] || space == input[i]) + ) { + if (period == input[i]) { + isFile = true + } + i++ + currStrLen++ + } + if (isFile) { + longestLen = Math.max(longestLen, currDirLen + currStrLen) + } else { + currDirLen += currStrLen + 1 + stack.push(currStrLen + 1) + } + nextLevel = 0 + // increment one to let it pass "\n" and start from "\t" + i = i + 1 + while (i < input.length - 1 && input[i] == '\t') { + nextLevel++ + i = i + 1 + } + if (nextLevel < currLevel) { + var j = 0 + if (isFile) { + while (!stack.isEmpty() && j < currLevel - nextLevel) { + currDirLen -= stack.pop() + j++ + } + } else { + while (!stack.isEmpty() && j <= currLevel - nextLevel) { + currDirLen -= stack.pop() + j++ + } + } + } else if (nextLevel == currLevel && !isFile && !stack.isEmpty()) { + currDirLen -= stack.pop() + } + if (nextLevel == 0) { + currDirLen = 0 + stack.clear() + } + isFile = false + } + return longestLen + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0389_find_the_difference/readme.md b/src/main/kotlin/g0301_0400/s0389_find_the_difference/readme.md new file mode 100644 index 00000000..ae2a7921 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0389_find_the_difference/readme.md @@ -0,0 +1,49 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 389\. Find the Difference + +Easy + +You are given two strings `s` and `t`. + +String `t` is generated by random shuffling string `s` and then add one more letter at a random position. + +Return the letter that was added to `t`. + +**Example 1:** + +**Input:** s = "abcd", t = "abcde" + +**Output:** "e" + +**Explanation:** 'e' is the letter that was added. + +**Example 2:** + +**Input:** s = "", t = "y" + +**Output:** "y" + +**Constraints:** + +* `0 <= s.length <= 1000` +* `t.length == s.length + 1` +* `s` and `t` consist of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun findTheDifference(s: String, t: String): Char { + var c = 0.toChar() + for (cs in s.toCharArray()) { + c = (c.code xor cs.code).toChar() + } + for (ct in t.toCharArray()) { + c = (c.code xor ct.code).toChar() + } + return c + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0390_elimination_game/readme.md b/src/main/kotlin/g0301_0400/s0390_elimination_game/readme.md new file mode 100644 index 00000000..6d02cf57 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0390_elimination_game/readme.md @@ -0,0 +1,47 @@ +[![](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) + +## 390\. Elimination Game + +Medium + +You have a list `arr` of all integers in the range `[1, n]` sorted in a strictly increasing order. Apply the following algorithm on `arr`: + +* Starting from left to right, remove the first number and every other number afterward until you reach the end of the list. +* Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers. +* Keep repeating the steps again, alternating left to right and right to left, until a single number remains. + +Given the integer `n`, return _the last number that remains in_ `arr`. + +**Example 1:** + +**Input:** n = 9 + +**Output:** 6 + +**Explanation:** + + arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] + arr = [2, 4, 6, 8] + arr = [2, 6] + arr = [6] + +**Example 2:** + +**Input:** n = 1 + +**Output:** 1 + +**Constraints:** + +* 1 <= n <= 109 + +## Solution + +```kotlin +class Solution { + fun lastRemaining(n: Int): Int { + return if (n == 1) 1 else 2 * (n / 2 - lastRemaining(n / 2) + 1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0391_perfect_rectangle/readme.md b/src/main/kotlin/g0301_0400/s0391_perfect_rectangle/readme.md new file mode 100644 index 00000000..9a065f44 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0391_perfect_rectangle/readme.md @@ -0,0 +1,123 @@ +[![](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) + +## 391\. Perfect Rectangle + +Hard + +Given an array `rectangles` where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi). + +Return `true` _if all the rectangles together form an exact cover of a rectangular region_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/27/perectrec1-plane.jpg) + +**Input:** rectangles = \[\[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]] + +**Output:** true + +**Explanation:** All 5 rectangles together form an exact cover of a rectangular region. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/03/27/perfectrec2-plane.jpg) + +**Input:** rectangles = \[\[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]] + +**Output:** false + +**Explanation:** Because there is a gap between the two rectangular regions. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/03/27/perfecrrec4-plane.jpg) + +**Input:** rectangles = \[\[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]] + +**Output:** false + +**Explanation:** Because two of the rectangles overlap with each other. + +**Constraints:** + +* 1 <= rectangles.length <= 2 * 104 +* `rectangles[i].length == 4` +* -105 <= xi, yi, ai, bi <= 105 + +## Solution + +```kotlin +import java.util.Objects + +class Solution { + fun isRectangleCover(rectangles: Array): Boolean { + val container: MutableSet = HashSet() + // add each rectangle area to totalArea + var totalArea = 0 + // A rectangle has four points, if a point appears twice, it will be deleted it from the set + for (rectangle in rectangles) { + totalArea += (rectangle[2] - rectangle[0]) * (rectangle[3] - rectangle[1]) + val p1 = Point(rectangle[0], rectangle[1]) + val p2 = Point(rectangle[2], rectangle[1]) + val p3 = Point(rectangle[2], rectangle[3]) + val p4 = Point(rectangle[0], rectangle[3]) + if (container.contains(p1)) { + container.remove(p1) + } else { + container.add(p1) + } + if (container.contains(p2)) { + container.remove(p2) + } else { + container.add(p2) + } + if (container.contains(p3)) { + container.remove(p3) + } else { + container.add(p3) + } + if (container.contains(p4)) { + container.remove(p4) + } else { + container.add(p4) + } + } + // A perfect rectangle must has four points + if (container.size != 4) { + return false + } + + // these four points represent the last perfect rectangle, check this rectangle area to the + // totalArea + var minX = Int.MAX_VALUE + var maxX = Int.MIN_VALUE + var minY = Int.MAX_VALUE + var maxY = Int.MIN_VALUE + for (p in container) { + minX = Math.min(minX, p.x) + maxX = Math.max(maxX, p.x) + minY = Math.min(minY, p.y) + maxY = Math.max(maxY, p.y) + } + return totalArea == (maxX - minX) * (maxY - minY) + } + + private class Point(val x: Int, val y: Int) { + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + if (other == null || javaClass != other.javaClass) { + return false + } + val point = other as Point + return x == point.x && y == point.y + } + + override fun hashCode(): Int { + return Objects.hash(x, y) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0392_is_subsequence/readme.md b/src/main/kotlin/g0301_0400/s0392_is_subsequence/readme.md new file mode 100644 index 00000000..434dcd7f --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0392_is_subsequence/readme.md @@ -0,0 +1,46 @@ +[![](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) + +## 392\. Is Subsequence + +Easy + +Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_. + +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", t = "ahbgdc" + +**Output:** true + +**Example 2:** + +**Input:** s = "axc", t = "ahbgdc" + +**Output:** false + +**Constraints:** + +* `0 <= s.length <= 100` +* 0 <= t.length <= 104 +* `s` and `t` consist only of lowercase English letters. + +**Follow up:** Suppose there are lots of incoming `s`, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code? + +## Solution + +```kotlin +class Solution { + fun isSubsequence(s: String, t: String): Boolean { + var i = 0 + var j = 0 + while (i < s.length && j < t.length) { + if (s[i] == t[j]) i++ + j++ + } + return i == s.length + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0393_utf_8_validation/readme.md b/src/main/kotlin/g0301_0400/s0393_utf_8_validation/readme.md new file mode 100644 index 00000000..85664c15 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0393_utf_8_validation/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) + +## 393\. UTF-8 Validation + +Medium + +Given an integer array `data` representing the data, return whether it is a valid **UTF-8** encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters). + +A character in **UTF8** can be from **1 to 4 bytes** long, subjected to the following rules: + +1. For a **1-byte** character, the first bit is a `0`, followed by its Unicode code. +2. For an **n-bytes** character, the first `n` bits are all one's, the `n + 1` bit is `0`, followed by `n - 1` bytes with the most significant `2` bits being `10`. + +This is how the UTF-8 encoding would work: + +Number of Bytes \| UTF-8 Octet Sequence \| (binary) --------------------+----------------------------------------- 1 \| 0xxxxxxx 2 \| 110xxxxx 10xxxxxx 3 \| 1110xxxx 10xxxxxx 10xxxxxx 4 \| 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + +`x` denotes a bit in the binary form of a byte that may be either `0` or `1`. + +**Note:** The input is an array of integers. Only the **least significant 8 bits** of each integer is used to store the data. This means each integer represents only 1 byte of data. + +**Example 1:** + +**Input:** data = [197,130,1] + +**Output:** true + +**Explanation:** data represents the octet sequence: 11000101 10000010 00000001. It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. + +**Example 2:** + +**Input:** data = [235,140,4] + +**Output:** false + +**Explanation:** data represented the octet sequence: 11101011 10001100 00000100. The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. The next byte is a continuation byte which starts with 10 and that's correct. But the second continuation byte does not start with 10, so it is invalid. + +**Constraints:** + +* 1 <= data.length <= 2 * 104 +* `0 <= data[i] <= 255` + +## Solution + +```kotlin +class Solution { + fun validUtf8(data: IntArray): Boolean { + var count = 0 + for (d in data) { + if (count == 0) { + if (d shr 5 == 6) { + count = 1 + } else if (d shr 4 == 14) { + count = 2 + } else if (d shr 3 == 30) { + count = 3 + } else if (d shr 7 == 1) { + return false + } + } else { + if (d shr 6 != 2) { + return false + } else { + count-- + } + } + } + return count == 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0395_longest_substring_with_at_least_k_repeating_characters/readme.md b/src/main/kotlin/g0301_0400/s0395_longest_substring_with_at_least_k_repeating_characters/readme.md new file mode 100644 index 00000000..0e067df0 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0395_longest_substring_with_at_least_k_repeating_characters/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) + +## 395\. Longest Substring with At Least K Repeating Characters + +Medium + +Given a string `s` and an integer `k`, return _the length of the longest substring of_ `s` _such that the frequency of each character in this substring is greater than or equal to_ `k`. + +**Example 1:** + +**Input:** s = "aaabb", k = 3 + +**Output:** 3 + +**Explanation:** The longest substring is "aaa", as 'a' is repeated 3 times. + +**Example 2:** + +**Input:** s = "ababbc", k = 2 + +**Output:** 5 + +**Explanation:** The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times. + +**Constraints:** + +* 1 <= s.length <= 104 +* `s` consists of only lowercase English letters. +* 1 <= k <= 105 + +## Solution + +```kotlin +class Solution { + fun longestSubstring(s: String, k: Int): Int { + return helper(s, k, 0, s.length) + } + + private fun helper(s: String, k: Int, start: Int, end: Int): Int { + if (end - start < k) { + return 0 + } + val nums = IntArray(26) + for (i in start until end) { + nums[s[i].code - 'a'.code]++ + } + for (i in start until end) { + if (nums[s[i].code - 'a'.code] < k) { + var j = i + 1 + while (j < s.length && nums[s[j].code - 'a'.code] < k) { + j++ + } + return Math.max(helper(s, k, start, i), helper(s, k, j, end)) + } + } + return end - start + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0396_rotate_function/readme.md b/src/main/kotlin/g0301_0400/s0396_rotate_function/readme.md new file mode 100644 index 00000000..e4de18fc --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0396_rotate_function/readme.md @@ -0,0 +1,68 @@ +[![](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) + +## 396\. Rotate Function + +Medium + +You are given an integer array `nums` of length `n`. + +Assume arrk to be an array obtained by rotating `nums` by `k` positions clock-wise. We define the **rotation function** `F` on `nums` as follow: + +* F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1]. + +Return _the maximum value of_ `F(0), F(1), ..., F(n-1)`. + +The test cases are generated so that the answer fits in a **32-bit** integer. + +**Example 1:** + +**Input:** nums = [4,3,2,6] + +**Output:** 26 + +**Explanation:** + +F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 + +F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 + +F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 + +F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 + +So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. + +**Example 2:** + +**Input:** nums = [100] + +**Output:** 0 + +**Constraints:** + +* `n == nums.length` +* 1 <= n <= 105 +* `-100 <= nums[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun maxRotateFunction(nums: IntArray): Int { + var allSum = 0 + val len = nums.size + var f = 0 + for (i in 0 until len) { + f += i * nums[i] + allSum += nums[i] + } + var max = f + for (i in len - 1 downTo 1) { + f += allSum - len * nums[i] + max = Math.max(f, max) + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0397_integer_replacement/readme.md b/src/main/kotlin/g0301_0400/s0397_integer_replacement/readme.md new file mode 100644 index 00000000..65e67807 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0397_integer_replacement/readme.md @@ -0,0 +1,88 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 397\. Integer Replacement + +Medium + +Given a positive integer `n`, you can apply one of the following operations: + +1. If `n` is even, replace `n` with `n / 2`. +2. If `n` is odd, replace `n` with either `n + 1` or `n - 1`. + +Return _the minimum number of operations needed for_ `n` _to become_ `1`. + +**Example 1:** + +**Input:** n = 8 + +**Output:** 3 + +**Explanation:** 8 -> 4 -> 2 -> 1 + +**Example 2:** + +**Input:** n = 7 + +**Output:** 4 + +**Explanation:** 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1 + +**Example 3:** + +**Input:** n = 4 + +**Output:** 2 + +**Constraints:** + +* 1 <= n <= 231 - 1 + +## Solution + +```kotlin +import java.util.LinkedList + +class Solution { + fun integerReplacement(n: Int): Int { + if (n == 1) return 0 + val num = n.toLong() + val queue = LinkedList() + val seen = HashSet() + if (n % 2 == 0) { + queue.offer(num / 2) + seen.add(num / 2) + } else { + queue.offer(num + 1) + seen.add(num + 1) + queue.offer(num - 1) + seen.add(num - 1) + } + var steps = 1 + while (queue.isNotEmpty()) { + val size = queue.size + for (sz in 0 until size) { + val cur = queue.poll() + if (cur == 1L) return steps + if (cur % 2 == 0L) { + val next = cur / 2 + if (seen.add(next)) { + queue.offer(next) + } + } else { + val next1 = cur + 1 + if (seen.add(next1)) { + queue.offer(next1) + } + val next2 = cur - 1 + if (seen.add(next2)) { + queue.offer(next2) + } + } + } + ++steps + } + return steps + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0398_random_pick_index/readme.md b/src/main/kotlin/g0301_0400/s0398_random_pick_index/readme.md new file mode 100644 index 00000000..abc53360 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0398_random_pick_index/readme.md @@ -0,0 +1,68 @@ +[![](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) + +## 398\. Random Pick Index + +Medium + +Given an integer array `nums` with possible **duplicates**, randomly output the index of a given `target` number. You can assume that the given target number must exist in the array. + +Implement the `Solution` class: + +* `Solution(int[] nums)` Initializes the object with the array `nums`. +* `int pick(int target)` Picks a random index `i` from `nums` where `nums[i] == target`. If there are multiple valid i's, then each index should have an equal probability of returning. + +**Example 1:** + +**Input** + + ["Solution", "pick", "pick", "pick"] + [[[1, 2, 3, 3, 3]], [3], [1], [3]] + +**Output:** [null, 4, 0, 2] + +**Explanation:** + + Solution solution = new Solution([1, 2, 3, 3, 3]); + solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. + solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1. + solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. + +**Constraints:** + +* 1 <= nums.length <= 2 * 104 +* -231 <= nums[i] <= 231 - 1 +* `target` is an integer from `nums`. +* At most 104 calls will be made to `pick`. + +## Solution + +```kotlin +import kotlin.random.Random + +@Suppress("kotlin:S2245") +class Solution(nums: IntArray) { + // O(n) time | O(n) space + private val map: MutableMap> + + init { + map = HashMap() + for (i in nums.indices) { + map.computeIfAbsent( + nums[i] + ) { ArrayList() }.add(i) + } + } + + fun pick(target: Int): Int { + val list: List = map[target]!! + return list[Random.nextInt(list.size)] + } +} + +/* + * Your Solution object will be instantiated and called as such: + * var obj = Solution(nums) + * var param_1 = obj.pick(target) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0399_evaluate_division/readme.md b/src/main/kotlin/g0301_0400/s0399_evaluate_division/readme.md new file mode 100644 index 00000000..5cb92eb4 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0399_evaluate_division/readme.md @@ -0,0 +1,111 @@ +[![](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) + +## 399\. Evaluate Division + +Medium + +You are given an array of variable pairs `equations` and an array of real numbers `values`, where equations[i] = [Ai, Bi] and `values[i]` represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable. + +You are also given some `queries`, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?. + +Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`. + +**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction. + +**Example 1:** + +**Input:** equations = \[\["a","b"],["b","c"]], values = [2.0,3.0], queries = \[\["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]] + +**Output:** [6.00000,0.50000,-1.00000,1.00000,-1.00000] + +**Explanation:** Given: _a / b = 2.0_, _b / c = 3.0_ queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_ return: [6.0, 0.5, -1.0, 1.0, -1.0 ] + +**Example 2:** + +**Input:** equations = \[\["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = \[\["a","c"],["c","b"],["bc","cd"],["cd","bc"]] + +**Output:** [3.75000,0.40000,5.00000,0.20000] + +**Example 3:** + +**Input:** equations = \[\["a","b"]], values = [0.5], queries = \[\["a","b"],["b","a"],["a","c"],["x","y"]] + +**Output:** [0.50000,2.00000,-1.00000,-1.00000] + +**Constraints:** + +* `1 <= equations.length <= 20` +* `equations[i].length == 2` +* 1 <= Ai.length, Bi.length <= 5 +* `values.length == equations.length` +* `0.0 < values[i] <= 20.0` +* `1 <= queries.length <= 20` +* `queries[i].length == 2` +* 1 <= Cj.length, Dj.length <= 5 +* Ai, Bi, Cj, Dj consist of lower case English letters and digits. + +## Solution + +```kotlin +class Solution { + private var root: MutableMap? = null + private var rate: MutableMap? = null + fun calcEquation( + equations: List>, + values: DoubleArray, + queries: List> + ): DoubleArray { + root = HashMap() + rate = HashMap() + val n = equations.size + for (equation in equations) { + val x = equation[0] + val y = equation[1] + (root as HashMap)[x] = x + (root as HashMap)[y] = y + (rate as HashMap)[x] = 1.0 + (rate as HashMap)[y] = 1.0 + } + for (i in 0 until n) { + val x = equations[i][0] + val y = equations[i][1] + union(x, y, values[i]) + } + val result = DoubleArray(queries.size) + for (i in queries.indices) { + val x = queries[i][0] + val y = queries[i][1] + if (!(root as HashMap).containsKey(x) || + !(root as HashMap).containsKey(y) + ) { + result[i] = -1.0 + continue + } + val rootX = findRoot(x, x, 1.0) + val rootY = findRoot(y, y, 1.0) + result[i] = if (rootX == rootY) (rate as HashMap).get(x)!! / + (rate as HashMap).get(y)!! else -1.0 + } + return result + } + + private fun union(x: String?, y: String?, v: Double) { + val rootX = findRoot(x, x, 1.0) + val rootY = findRoot(y, y, 1.0) + root!![rootX] = rootY + val r1 = rate!![x]!! + val r2 = rate!![y]!! + rate!![rootX] = v * r2 / r1 + } + + private fun findRoot(originalX: String?, x: String?, r: Double): String? { + if (root!![x] == x) { + root!![originalX] = x + rate!![originalX] = r * rate!![x]!! + return x + } + return findRoot(originalX, root!![x], r * rate!![x]!!) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0400_nth_digit/readme.md b/src/main/kotlin/g0301_0400/s0400_nth_digit/readme.md new file mode 100644 index 00000000..a36e2880 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0400_nth_digit/readme.md @@ -0,0 +1,54 @@ +[![](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) + +## 400\. Nth Digit + +Medium + +Given an integer `n`, return the nth digit of the infinite integer sequence `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]`. + +**Example 1:** + +**Input:** n = 3 + +**Output:** 3 + +**Example 2:** + +**Input:** n = 11 + +**Output:** 0 + +**Explanation:** The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. + +**Constraints:** + +* 1 <= n <= 231 - 1 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + /* + * 1. find the length of the number where the nth digit is from + * 2. find the actual number where the nth digit is from + * 3. find the nth digit and return + */ + fun findNthDigit(n: Int): Int { + var n = n + var len = 1 + var count: Long = 9 + var start = 1 + while (n > len * count) { + n -= (len * count).toInt() + len += 1 + count *= 10 + start *= 10 + } + start += (n - 1) / len + val s = Integer.toString(start) + return Character.getNumericValue(s[(n - 1) % len]) + } +} +``` \ No newline at end of file