diff --git a/README.md b/README.md index 4ff9f1c5..7f7d2759 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,7 @@ | | | | | | |-|-|-|-|-|- +| 0413 |[Arithmetic Slices](src/main/kotlin/g0401_0500/s0413_arithmetic_slices)| Medium | Array, Dynamic_Programming | 156 | 100.00 | 0091 |[Decode Ways](src/main/kotlin/g0001_0100/s0091_decode_ways)| Medium | Top_Interview_Questions, String, Dynamic_Programming | 237 | 76.88 #### Day 11 @@ -213,6 +214,7 @@ | | | | | | |-|-|-|-|-|- | 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 +| 0404 |[Sum of Left Leaves](src/main/kotlin/g0401_0500/s0404_sum_of_left_leaves)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 173 | 86.05 #### Day 11 Containers and Libraries @@ -284,6 +286,7 @@ | | | | | | |-|-|-|-|-|- +| 0429 |[N-ary Tree Level Order Traversal](src/main/kotlin/g0401_0500/s0429_n_ary_tree_level_order_traversal)| Medium | Breadth_First_Search, Tree | 278 | 75.00 #### Day 10 @@ -320,6 +323,7 @@ | | | | | | |-|-|-|-|-|- | 0002 |[Add Two Numbers](src/main/kotlin/g0001_0100/s0002_add_two_numbers)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Math, Linked_List, Recursion | 417 | 50.44 +| 0445 |[Add Two Numbers II](src/main/kotlin/g0401_0500/s0445_add_two_numbers_ii)| Medium | Math, Stack, Linked_List | 240 | 82.61 #### Day 16 @@ -373,6 +377,7 @@ | | | | | | |-|-|-|-|-|- +| 0417 |[Pacific Atlantic Water Flow](src/main/kotlin/g0401_0500/s0417_pacific_atlantic_water_flow)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix | 319 | 100.00 #### Day 5 Matrix Related Problems @@ -414,6 +419,7 @@ | | | | | | |-|-|-|-|-|- +| 0433 |[Minimum Genetic Mutation](src/main/kotlin/g0401_0500/s0433_minimum_genetic_mutation)| Medium | String, Hash_Table, Breadth_First_Search | 204 | 82.08 | 0127 |[Word Ladder](src/main/kotlin/g0101_0200/s0127_word_ladder)| Hard | Top_Interview_Questions, String, Hash_Table, Breadth_First_Search | 396 | 98.68 #### Day 13 Graph Theory @@ -516,6 +522,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 +| 0409 |[Longest Palindrome](src/main/kotlin/g0401_0500/s0409_longest_palindrome)| Easy | String, Hash_Table, Greedy | 259 | 60.71 #### Day 6 Tree @@ -559,6 +566,7 @@ | | | | | | |-|-|-|-|-|- | 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 | 561 | 54.68 +| 0424 |[Longest Repeating Character Replacement](src/main/kotlin/g0401_0500/s0424_longest_repeating_character_replacement)| Medium | String, Hash_Table, Sliding_Window | 288 | 84.38 #### Day 13 Hashmap @@ -647,6 +655,7 @@ | | | | | | |-|-|-|-|-|- | 0994 |[Rotting Oranges](src/main/kotlin/g0901_1000/s0994_rotting_oranges)| Medium | Array, Breadth_First_Search, Matrix | 308 | 57.93 +| 0417 |[Pacific Atlantic Water Flow](src/main/kotlin/g0401_0500/s0417_pacific_atlantic_water_flow)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix | 319 | 100.00 #### Day 11 Graph/BFS/DFS @@ -723,6 +732,7 @@ | | | | | | |-|-|-|-|-|- +| 0412 |[Fizz Buzz](src/main/kotlin/g0401_0500/s0412_fizz_buzz)| Easy | Top_Interview_Questions, String, Math, Simulation | 307 | 71.81 | 0136 |[Single Number](src/main/kotlin/g0101_0200/s0136_single_number)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation | 344 | 83.63 | 0007 |[Reverse Integer](src/main/kotlin/g0001_0100/s0007_reverse_integer)| Medium | Top_Interview_Questions, Math | 245 | 60.32 | 0009 |[Palindrome Number](src/main/kotlin/g0001_0100/s0009_palindrome_number)| Easy | Math | 238 | 96.24 @@ -768,6 +778,8 @@ | 0075 |[Sort Colors](src/main/kotlin/g0001_0100/s0075_sort_colors)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers | 198 | 85.66 | 0066 |[Plus One](src/main/kotlin/g0001_0100/s0066_plus_one)| Easy | Top_Interview_Questions, Array, Math | 303 | 35.18 | 0238 |[Product of Array Except Self](src/main/kotlin/g0201_0300/s0238_product_of_array_except_self)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Prefix_Sum | 669 | 48.96 +| 0448 |[Find All Numbers Disappeared in an Array](src/main/kotlin/g0401_0500/s0448_find_all_numbers_disappeared_in_an_array)| Easy | Array, Hash_Table | 394 | 100.00 +| 0442 |[Find All Duplicates in an Array](src/main/kotlin/g0401_0500/s0442_find_all_duplicates_in_an_array)| Medium | Array, Hash_Table | 480 | 73.81 | 0041 |[First Missing Positive](src/main/kotlin/g0001_0100/s0041_first_missing_positive)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table | 345 | 100.00 | 0239 |[Sliding Window Maximum](src/main/kotlin/g0201_0300/s0239_sliding_window_maximum)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Heap_Priority_Queue, Sliding_Window, Queue, Monotonic_Queue | 1059 | 86.14 @@ -809,6 +821,7 @@ | | | | | | |-|-|-|-|-|- | 0114 |[Flatten Binary Tree to Linked List](src/main/kotlin/g0101_0200/s0114_flatten_binary_tree_to_linked_list)| Medium | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree, Stack, Linked_List | 191 | 93.10 +| 0445 |[Add Two Numbers II](src/main/kotlin/g0401_0500/s0445_add_two_numbers_ii)| Medium | Math, Stack, Linked_List | 240 | 82.61 | 0328 |[Odd Even Linked List](src/main/kotlin/g0301_0400/s0328_odd_even_linked_list)| Medium | Top_Interview_Questions, Linked_List | 216 | 86.96 | 0061 |[Rotate List](src/main/kotlin/g0001_0100/s0061_rotate_list)| Medium | Two_Pointers, Linked_List | 193 | 92.16 | 0024 |[Swap Nodes in Pairs](src/main/kotlin/g0001_0100/s0024_swap_nodes_in_pairs)| Medium | Top_100_Liked_Questions, Linked_List, Recursion | 149 | 99.39 @@ -856,6 +869,7 @@ |-|-|-|-|-|- | 0200 |[Number of Islands](src/main/kotlin/g0101_0200/s0200_number_of_islands)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 252 | 95.41 | 0133 |[Clone Graph](src/main/kotlin/g0101_0200/s0133_clone_graph)| Medium | Hash_Table, Depth_First_Search, Breadth_First_Search, Graph | 351 | 60.91 +| 0417 |[Pacific Atlantic Water Flow](src/main/kotlin/g0401_0500/s0417_pacific_atlantic_water_flow)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix | 319 | 100.00 #### Udemy Dynamic Programming @@ -1035,6 +1049,7 @@ | | | | | | |-|-|-|-|-|- | 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 +| 0435 |[Non-overlapping Intervals](src/main/kotlin/g0401_0500/s0435_non_overlapping_intervals)| Medium | Array, Dynamic_Programming, Sorting, Greedy | 1040 | 85.07 #### Day 5 Array @@ -1048,6 +1063,8 @@ | | | | | | |-|-|-|-|-|- +| 0415 |[Add Strings](src/main/kotlin/g0401_0500/s0415_add_strings)| Easy | String, Math, Simulation | 296 | 76.00 +| 0409 |[Longest Palindrome](src/main/kotlin/g0401_0500/s0409_longest_palindrome)| Easy | String, Hash_Table, Greedy | 259 | 60.71 #### Day 7 String @@ -1117,6 +1134,7 @@ |-|-|-|-|-|- | 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 | 0113 |[Path Sum II](src/main/kotlin/g0101_0200/s0113_path_sum_ii)| Medium | Depth_First_Search, Tree, Binary_Tree, Backtracking | 364 | 78.67 +| 0450 |[Delete Node in a BST](src/main/kotlin/g0401_0500/s0450_delete_node_in_a_bst)| Medium | Tree, Binary_Tree, Binary_Search_Tree | 257 | 84.62 #### Day 17 Tree @@ -1148,6 +1166,7 @@ | | | | | | |-|-|-|-|-|- +| 0451 |[Sort Characters By Frequency](src/main/kotlin/g0401_0500/s0451_sort_characters_by_frequency)| Medium | String, Hash_Table, Sorting, Heap_Priority_Queue, Counting, Bucket_Sort | 288 | 81.72 ### Algorithm I @@ -1339,6 +1358,7 @@ | | | | | | |-|-|-|-|-|- | 0005 |[Longest Palindromic Substring](src/main/kotlin/g0001_0100/s0005_longest_palindromic_substring)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming | 323 | 75.48 +| 0413 |[Arithmetic Slices](src/main/kotlin/g0401_0500/s0413_arithmetic_slices)| Medium | Array, Dynamic_Programming | 156 | 100.00 #### Day 15 Dynamic Programming @@ -1423,6 +1443,7 @@ | | | | | | |-|-|-|-|-|- +| 0441 |[Arranging Coins](src/main/kotlin/g0401_0500/s0441_arranging_coins)| Easy | Math, Binary_Search | 150 | 84.21 #### Day 7 @@ -1521,6 +1542,7 @@ | | | | | | |-|-|-|-|-|- +| 0436 |[Find Right Interval](src/main/kotlin/g0401_0500/s0436_find_right_interval)| Medium | Array, Sorting, Binary_Search | 333 | 100.00 #### Day 12 @@ -1583,9 +1605,49 @@ | 0560 |[Subarray Sum Equals K](src/main/kotlin/g0501_0600/s0560_subarray_sum_equals_k)| Medium | Top_100_Liked_Questions, Array, Hash_Table, Prefix_Sum, Data_Structure_II_Day_5_Array | 692 | 53.27 | 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, Level_2_Day_7_Tree, Udemy_Tree_Stack_Queue | 307 | 43.93 | 0494 |[Target Sum](src/main/kotlin/g0401_0500/s0494_target_sum)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Backtracking | 308 | 89.61 +| 0453 |[Minimum Moves to Equal Array Elements](src/main/kotlin/g0401_0500/s0453_minimum_moves_to_equal_array_elements)| Medium | Array, Math | 282 | 100.00 +| 0452 |[Minimum Number of Arrows to Burst Balloons](src/main/kotlin/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons)| Medium | Array, Sorting, Greedy | 934 | 100.00 +| 0451 |[Sort Characters By Frequency](src/main/kotlin/g0401_0500/s0451_sort_characters_by_frequency)| Medium | String, Hash_Table, Sorting, Heap_Priority_Queue, Counting, Bucket_Sort, Data_Structure_II_Day_21_Heap_Priority_Queue | 288 | 81.72 +| 0450 |[Delete Node in a BST](src/main/kotlin/g0401_0500/s0450_delete_node_in_a_bst)| Medium | Tree, Binary_Tree, Binary_Search_Tree, Data_Structure_II_Day_16_Tree | 257 | 84.62 +| 0449 |[Serialize and Deserialize BST](src/main/kotlin/g0401_0500/s0449_serialize_and_deserialize_bst)| Medium | String, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Design, Binary_Search_Tree | 233 | 100.00 +| 0448 |[Find All Numbers Disappeared in an Array](src/main/kotlin/g0401_0500/s0448_find_all_numbers_disappeared_in_an_array)| Easy | Array, Hash_Table, Udemy_Arrays | 394 | 100.00 +| 0447 |[Number of Boomerangs](src/main/kotlin/g0401_0500/s0447_number_of_boomerangs)| Medium | Array, Hash_Table, Math | 308 | 100.00 +| 0446 |[Arithmetic Slices II - Subsequence](src/main/kotlin/g0401_0500/s0446_arithmetic_slices_ii_subsequence)| Hard | Array, Dynamic_Programming | 312 | 100.00 +| 0445 |[Add Two Numbers II](src/main/kotlin/g0401_0500/s0445_add_two_numbers_ii)| Medium | Math, Stack, Linked_List, Programming_Skills_II_Day_15, Udemy_Linked_List | 240 | 82.61 +| 0443 |[String Compression](src/main/kotlin/g0401_0500/s0443_string_compression)| Medium | String, Two_Pointers | 198 | 92.68 +| 0442 |[Find All Duplicates in an Array](src/main/kotlin/g0401_0500/s0442_find_all_duplicates_in_an_array)| Medium | Array, Hash_Table, Udemy_Arrays | 480 | 73.81 +| 0441 |[Arranging Coins](src/main/kotlin/g0401_0500/s0441_arranging_coins)| Easy | Math, Binary_Search, Binary_Search_I_Day_6 | 150 | 84.21 +| 0440 |[K-th Smallest in Lexicographical Order](src/main/kotlin/g0401_0500/s0440_k_th_smallest_in_lexicographical_order)| Hard | Trie | 149 | 100.00 | 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 +| 0436 |[Find Right Interval](src/main/kotlin/g0401_0500/s0436_find_right_interval)| Medium | Array, Sorting, Binary_Search, Binary_Search_II_Day_11 | 333 | 100.00 +| 0435 |[Non-overlapping Intervals](src/main/kotlin/g0401_0500/s0435_non_overlapping_intervals)| Medium | Array, Dynamic_Programming, Sorting, Greedy, Data_Structure_II_Day_4_Array | 1040 | 85.07 +| 0434 |[Number of Segments in a String](src/main/kotlin/g0401_0500/s0434_number_of_segments_in_a_string)| Easy | String | 167 | 80.00 +| 0433 |[Minimum Genetic Mutation](src/main/kotlin/g0401_0500/s0433_minimum_genetic_mutation)| Medium | String, Hash_Table, Breadth_First_Search, Graph_Theory_I_Day_12_Breadth_First_Search | 204 | 82.08 +| 0432 |[All O\`one Data Structure](src/main/kotlin/g0401_0500/s0432_all_oone_data_structure)| Hard | Hash_Table, Design, Linked_List, Doubly_Linked_List | 1200 | 100.00 +| 0430 |[Flatten a Multilevel Doubly Linked List](src/main/kotlin/g0401_0500/s0430_flatten_a_multilevel_doubly_linked_list)| Medium | Depth_First_Search, Linked_List, Doubly_Linked_List | 194 | 97.44 +| 0429 |[N-ary Tree Level Order Traversal](src/main/kotlin/g0401_0500/s0429_n_ary_tree_level_order_traversal)| Medium | Breadth_First_Search, Tree, Programming_Skills_II_Day_9 | 278 | 75.00 +| 0427 |[Construct Quad Tree](src/main/kotlin/g0401_0500/s0427_construct_quad_tree)| Medium | Array, Tree, Matrix, Divide_and_Conquer | 221 | 94.74 +| 0424 |[Longest Repeating Character Replacement](src/main/kotlin/g0401_0500/s0424_longest_repeating_character_replacement)| Medium | String, Hash_Table, Sliding_Window, Level_1_Day_12_Sliding_Window/Two_Pointer | 288 | 84.38 +| 0423 |[Reconstruct Original Digits from English](src/main/kotlin/g0401_0500/s0423_reconstruct_original_digits_from_english)| Medium | String, Hash_Table, Math | 349 | 100.00 +| 0421 |[Maximum XOR of Two Numbers in an Array](src/main/kotlin/g0401_0500/s0421_maximum_xor_of_two_numbers_in_an_array)| Medium | Array, Hash_Table, Bit_Manipulation, Trie | 710 | 100.00 +| 0420 |[Strong Password Checker](src/main/kotlin/g0401_0500/s0420_strong_password_checker)| Hard | String, Greedy, Heap_Priority_Queue | 157 | 80.00 +| 0419 |[Battleships in a Board](src/main/kotlin/g0401_0500/s0419_battleships_in_a_board)| Medium | Array, Depth_First_Search, Matrix | 273 | 76.92 +| 0417 |[Pacific Atlantic Water Flow](src/main/kotlin/g0401_0500/s0417_pacific_atlantic_water_flow)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Graph_Theory_I_Day_4_Matrix_Related_Problems, Level_2_Day_10_Graph/BFS/DFS, Udemy_Graph | 319 | 100.00 | 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 +| 0415 |[Add Strings](src/main/kotlin/g0401_0500/s0415_add_strings)| Easy | String, Math, Simulation, Data_Structure_II_Day_6_String | 296 | 76.00 +| 0414 |[Third Maximum Number](src/main/kotlin/g0401_0500/s0414_third_maximum_number)| Easy | Array, Sorting | 317 | 73.00 +| 0413 |[Arithmetic Slices](src/main/kotlin/g0401_0500/s0413_arithmetic_slices)| Medium | Array, Dynamic_Programming, Algorithm_II_Day_14_Dynamic_Programming, Dynamic_Programming_I_Day_10 | 156 | 100.00 +| 0412 |[Fizz Buzz](src/main/kotlin/g0401_0500/s0412_fizz_buzz)| Easy | Top_Interview_Questions, String, Math, Simulation, Udemy_Integers | 307 | 71.81 +| 0410 |[Split Array Largest Sum](src/main/kotlin/g0401_0500/s0410_split_array_largest_sum)| Hard | Array, Dynamic_Programming, Greedy, Binary_Search | 165 | 100.00 +| 0409 |[Longest Palindrome](src/main/kotlin/g0401_0500/s0409_longest_palindrome)| Easy | String, Hash_Table, Greedy, Data_Structure_II_Day_6_String, Level_1_Day_5_Greedy | 259 | 60.71 +| 0407 |[Trapping Rain Water II](src/main/kotlin/g0401_0500/s0407_trapping_rain_water_ii)| Hard | Array, Breadth_First_Search, Matrix, Heap_Priority_Queue | 500 | 100.00 +| 0406 |[Queue Reconstruction by Height](src/main/kotlin/g0401_0500/s0406_queue_reconstruction_by_height)| Medium | Array, Sorting, Greedy, Segment_Tree, Binary_Indexed_Tree | 306 | 100.00 +| 0405 |[Convert a Number to Hexadecimal](src/main/kotlin/g0401_0500/s0405_convert_a_number_to_hexadecimal)| Easy | Math, Bit_Manipulation | 132 | 100.00 +| 0404 |[Sum of Left Leaves](src/main/kotlin/g0401_0500/s0404_sum_of_left_leaves)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Programming_Skills_I_Day_10_Linked_List_and_Tree | 173 | 86.05 +| 0403 |[Frog Jump](src/main/kotlin/g0401_0500/s0403_frog_jump)| Hard | Array, Dynamic_Programming | 240 | 100.00 +| 0402 |[Remove K Digits](src/main/kotlin/g0401_0500/s0402_remove_k_digits)| Medium | String, Greedy, Stack, Monotonic_Stack | 375 | 75.00 +| 0401 |[Binary Watch](src/main/kotlin/g0401_0500/s0401_binary_watch)| Easy | Bit_Manipulation, Backtracking | 266 | 71.43 | 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 diff --git a/src/main/kotlin/g0101_0200/s0138_copy_list_with_random_pointer/readme.md b/src/main/kotlin/g0101_0200/s0138_copy_list_with_random_pointer/readme.md index fae6bbd0..ac8af40e 100644 --- a/src/main/kotlin/g0101_0200/s0138_copy_list_with_random_pointer/readme.md +++ b/src/main/kotlin/g0101_0200/s0138_copy_list_with_random_pointer/readme.md @@ -53,7 +53,7 @@ Your code will **only** be given the `head` of the original linked list. ## Solution ```kotlin -import com_github_leetcode.Node +import com_github_leetcode.random.Node class Solution { fun copyRandomList(head: Node?): Node? { diff --git a/src/main/kotlin/g0401_0500/s0401_binary_watch/readme.md b/src/main/kotlin/g0401_0500/s0401_binary_watch/readme.md new file mode 100644 index 00000000..5918f95e --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0401_binary_watch/readme.md @@ -0,0 +1,101 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 401\. Binary Watch + +Easy + +A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. + +* For example, the below binary watch reads `"4:51"`. + +![](https://assets.leetcode.com/uploads/2021/04/08/binarywatch.jpg) + +Given an integer `turnedOn` which represents the number of LEDs that are currently on (ignoring the PM), return _all possible times the watch could represent_. You may return the answer in **any order**. + +The hour must not contain a leading zero. + +* For example, `"01:00"` is not valid. It should be `"1:00"`. + +The minute must be consist of two digits and may contain a leading zero. + +* For example, `"10:2"` is not valid. It should be `"10:02"`. + +**Example 1:** + +**Input:** turnedOn = 1 + +**Output:** ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"] + +**Example 2:** + +**Input:** turnedOn = 9 + +**Output:** [] + +**Constraints:** + +* `0 <= turnedOn <= 10` + +## Solution + +```kotlin +import java.util.ArrayList + +@Suppress("NAME_SHADOWING") +class Solution { + fun readBinaryWatch(turnedOn: Int): List { + val times: MutableList = ArrayList() + for (hour in 0..11) { + for (minutes in 0..59) { + readBinaryWatchHelper(turnedOn, times, hour, minutes) + } + } + return times + } + + private fun readBinaryWatchHelper( + turnedOn: Int, + selectedTimes: MutableList, + hour: Int, + minutes: Int + ) { + if (isValidTime(turnedOn, hour, minutes)) { + selectedTimes.add(getTimeString(hour, minutes)) + } + } + + private fun getTimeString(hour: Int, minutes: Int): String { + val time = StringBuilder() + time.append(hour) + time.append(':') + if (minutes < 10) { + time.append('0') + } + time.append(minutes) + return time.toString() + } + + private fun isValidTime(turnedOn: Int, hour: Int, minutes: Int): Boolean { + var hour = hour + var minutes = minutes + var counter = 0 + while (hour != 0) { + if (hour and 1 == 1) { + counter++ + } + hour = hour ushr 1 + } + if (counter > turnedOn) { + return false + } + while (minutes != 0) { + if (minutes and 1 == 1) { + counter++ + } + minutes = minutes ushr 1 + } + return counter == turnedOn + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0402_remove_k_digits/readme.md b/src/main/kotlin/g0401_0500/s0402_remove_k_digits/readme.md new file mode 100644 index 00000000..ff3a03e5 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0402_remove_k_digits/readme.md @@ -0,0 +1,64 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 402\. Remove K Digits + +Medium + +Given string num representing a non-negative integer `num`, and an integer `k`, return _the smallest possible integer after removing_ `k` _digits from_ `num`. + +**Example 1:** + +**Input:** num = "1432219", k = 3 + +**Output:** "1219" + +**Explanation:** Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. + +**Example 2:** + +**Input:** num = "10200", k = 1 + +**Output:** "200" + +**Explanation:** Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. + +**Example 3:** + +**Input:** num = "10", k = 2 + +**Output:** "0" + +**Explanation:** Remove all the digits from the number and it is left with nothing which is 0. + +**Constraints:** + +* 1 <= k <= num.length <= 105 +* `num` consists of only digits. +* `num` does not have any leading zeros except for the zero itself. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun removeKdigits(num: String, k: Int): String { + var k = k + val list = CharArray(num.length) + val len = num.length - k + var top = 0 + for (i in 0 until num.length) { + while (top > 0 && k > 0 && num[i] < list[top - 1]) { + top-- + k-- + } + list[top++] = num[i] + } + var number = 0 + while (number < len && list[number] == '0') { + number++ + } + return if (number == len) "0" else String(list, number, len - number) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0403_frog_jump/readme.md b/src/main/kotlin/g0401_0500/s0403_frog_jump/readme.md new file mode 100644 index 00000000..47e33eec --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0403_frog_jump/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) + +## 403\. Frog Jump + +Hard + +A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. + +Given a list of `stones`' positions (in units) in sorted **ascending order**, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be `1` unit. + +If the frog's last jump was `k` units, its next jump must be either `k - 1`, `k`, or `k + 1` units. The frog can only jump in the forward direction. + +**Example 1:** + +**Input:** stones = [0,1,3,5,6,8,12,17] + +**Output:** true + +**Explanation:** The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. + +**Example 2:** + +**Input:** stones = [0,1,2,3,4,8,9,11] + +**Output:** false + +**Explanation:** There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. + +**Constraints:** + +* `2 <= stones.length <= 2000` +* 0 <= stones[i] <= 231 - 1 +* `stones[0] == 0` +* `stones` is sorted in a strictly increasing order. + +## Solution + +```kotlin +import java.util.HashMap +import java.util.HashSet + +class Solution { + // global hashmap to store visited index -> set of jump lengths from that index + private val visited: HashMap> = HashMap() + fun canCross(stones: IntArray): Boolean { + // a mathematical check before going in the recursion + for (i in 3 until stones.size) { + if (stones[i] > stones[i - 1] * 2) { + return false + } + } + // map of values -> index to make sure we get the next index quickly + val rocks: HashMap = HashMap() + for (i in stones.indices) { + rocks.put(stones[i], i) + } + return jump(stones, 0, 1, 0, rocks) + } + + private fun jump( + stones: IntArray, + index: Int, + jumpLength: Int, + expectedVal: Int, + rocks: Map + ): Boolean { + // overshoot and going backwards not allowed + if (index >= stones.size || jumpLength <= 0) { + return false + } + // reached the last index + if (index == stones.size - 1) { + return expectedVal == stones[index] + } + // check if this index -> jumpLength pair was seen before, otherwise record it + val rememberJumps: HashSet = visited.getOrDefault(index, HashSet()) + if (stones[index] > expectedVal || rememberJumps.contains(jumpLength)) { + return false + } + rememberJumps.add(jumpLength) + visited.put(index, rememberJumps) + // check for jumpLength-1, jumpLength, jumpLength+1 for a new expected value + return ( + jump( + stones, + rocks[stones[index] + jumpLength] ?: stones.size, + jumpLength + 1, + stones[index] + jumpLength, + rocks + ) || + jump( + stones, + rocks[stones[index] + jumpLength] ?: stones.size, + jumpLength, + stones[index] + jumpLength, + rocks + ) || + jump( + stones, + rocks[stones[index] + jumpLength] ?: stones.size, + jumpLength - 1, + stones[index] + jumpLength, + rocks + ) + ) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0404_sum_of_left_leaves/readme.md b/src/main/kotlin/g0401_0500/s0404_sum_of_left_leaves/readme.md new file mode 100644 index 00000000..96bb741a --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0404_sum_of_left_leaves/readme.md @@ -0,0 +1,65 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 404\. Sum of Left Leaves + +Easy + +Given the `root` of a binary tree, return _the sum of all left leaves._ + +A **leaf** is a node with no children. A **left leaf** is a leaf that is the left child of another node. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/08/leftsum-tree.jpg) + +**Input:** root = [3,9,20,null,null,15,7] + +**Output:** 24 + +**Explanation:** There are two left leaves in the binary tree, with values 9 and 15 respectively. + +**Example 2:** + +**Input:** root = [1] + +**Output:** 0 + +**Constraints:** + +* The number of nodes in the tree is in the range `[1, 1000]`. +* `-1000 <= Node.val <= 1000` + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun sumOfLeftLeaves(root: TreeNode): Int { + fun dfs(root: TreeNode?, left: Boolean): Int { + root ?: return 0 + if (root.left == null && root.right == null) { + return if (left) { + root.`val` + } else { + 0 + } + } + return dfs(root.left, true) + dfs(root.right, false) + } + + return dfs(root, false) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0405_convert_a_number_to_hexadecimal/readme.md b/src/main/kotlin/g0401_0500/s0405_convert_a_number_to_hexadecimal/readme.md new file mode 100644 index 00000000..9a04485a --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0405_convert_a_number_to_hexadecimal/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) + +## 405\. Convert a Number to Hexadecimal + +Easy + +Given an integer `num`, return _a string representing its hexadecimal representation_. For negative integers, [two’s complement](https://en.wikipedia.org/wiki/Two%27s_complement) method is used. + +All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself. + +**Note:** You are not allowed to use any built-in library method to directly solve this problem. + +**Example 1:** + +**Input:** num = 26 + +**Output:** "1a" + +**Example 2:** + +**Input:** num = -1 + +**Output:** "ffffffff" + +**Constraints:** + +* -231 <= num <= 231 - 1 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun toHex(num: Int): String { + var num = num + if (num == 0) { + return "0" + } + val sb = StringBuilder() + var x: Int + while (num != 0) { + x = num and 0xf + if (x < 10) { + sb.append(x) + } else { + sb.append((x + 87).toChar()) + } + num = num ushr 4 + } + return sb.reverse().toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0406_queue_reconstruction_by_height/readme.md b/src/main/kotlin/g0401_0500/s0406_queue_reconstruction_by_height/readme.md new file mode 100644 index 00000000..ec9103bc --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0406_queue_reconstruction_by_height/readme.md @@ -0,0 +1,51 @@ +[![](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) + +## 406\. Queue Reconstruction by Height + +Medium + +You are given an array of people, `people`, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with **exactly** ki other people in front who have a height greater than or equal to hi. + +Reconstruct and return _the queue that is represented by the input array_ `people`. The returned queue should be formatted as an array `queue`, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (`queue[0]` is the person at the front of the queue). + +**Example 1:** + +**Input:** people = \[\[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] + +**Output:** [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] + +**Explanation:** + + Person 0 has height 5 with no other people taller or the same height in front. + Person 1 has height 7 with no other people taller or the same height in front. + Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1. + Person 3 has height 6 with one person taller or the same height in front, which is person 1. + Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3. + Person 5 has height 7 with one person taller or the same height in front, which is person 1. + Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue. + +**Example 2:** + +**Input:** people = \[\[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]] + +**Output:** [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]] + +**Constraints:** + +* `1 <= people.length <= 2000` +* 0 <= hi <= 106 +* 0 <= ki < people.length +* It is guaranteed that the queue can be reconstructed. + +## Solution + +```kotlin +class Solution { + fun reconstructQueue(people: Array): Array { + return people.sortedWith(compareBy({ -it[0] }, { it[1] })) + .fold(mutableListOf()) { output, p -> output.add(p[1], p); output } + .toTypedArray() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0407_trapping_rain_water_ii/readme.md b/src/main/kotlin/g0401_0500/s0407_trapping_rain_water_ii/readme.md new file mode 100644 index 00000000..d72a0750 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0407_trapping_rain_water_ii/readme.md @@ -0,0 +1,104 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 407\. Trapping Rain Water II + +Hard + +Given an `m x n` integer matrix `heightMap` representing the height of each unit cell in a 2D elevation map, return _the volume of water it can trap after raining_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/08/trap1-3d.jpg) + +**Input:** heightMap = \[\[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] + +**Output:** 4 + +**Explanation:** After the rain, water is trapped between the blocks. We have two small ponds 1 and 3 units trapped. The total volume of water trapped is 4. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/04/08/trap2-3d.jpg) + +**Input:** heightMap = \[\[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]] + +**Output:** 10 + +**Constraints:** + +* `m == heightMap.length` +* `n == heightMap[i].length` +* `1 <= m, n <= 200` +* 0 <= heightMap[i][j] <= 2 * 104 + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + private class Cell(val row: Int, val col: Int, val value: Int) : Comparable { + override operator fun compareTo(other: Cell?): Int { + return value - other!!.value + } + } + + private var water = 0 + private lateinit var visited1: Array + fun trapRainWater(heightMap: Array): Int { + if (heightMap.size == 0) { + return 0 + } + val walls = PriorityQueue() + water = 0 + visited1 = Array(heightMap.size) { BooleanArray(heightMap[0].size) } + val rows = heightMap.size + val cols = heightMap[0].size + // build wall + for (c in 0 until cols) { + walls.add(Cell(0, c, heightMap[0][c])) + walls.add(Cell(rows - 1, c, heightMap[rows - 1][c])) + visited1[0][c] = true + visited1[rows - 1][c] = true + } + for (r in 1 until rows - 1) { + walls.add(Cell(r, 0, heightMap[r][0])) + walls.add(Cell(r, cols - 1, heightMap[r][cols - 1])) + visited1[r][0] = true + visited1[r][cols - 1] = true + } + // end build wall + while (!walls.isEmpty()) { + val min = walls.poll() + visit(heightMap, min, walls) + } + return water + } + + private fun visit(height: Array, start: Cell, walls: PriorityQueue) { + fill(height, start.row + 1, start.col, walls, start.value) + fill(height, start.row - 1, start.col, walls, start.value) + fill(height, start.row, start.col + 1, walls, start.value) + fill(height, start.row, start.col - 1, walls, start.value) + } + + private fun fill(height: Array, row: Int, col: Int, walls: PriorityQueue, min: Int) { + if (row >= 0 && col >= 0 && row < height.size && col < height[0].size && + !visited1[row][col] + ) { + if (height[row][col] >= min) { + walls.add(Cell(row, col, height[row][col])) + visited1[row][col] = true + } else { + water += min - height[row][col] + visited1[row][col] = true + fill(height, row + 1, col, walls, min) + fill(height, row - 1, col, walls, min) + fill(height, row, col + 1, walls, min) + fill(height, row, col - 1, walls, min) + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0409_longest_palindrome/readme.md b/src/main/kotlin/g0401_0500/s0409_longest_palindrome/readme.md new file mode 100644 index 00000000..bae6e5b8 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0409_longest_palindrome/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) + +## 409\. Longest Palindrome + +Easy + +Given a string `s` which consists of lowercase or uppercase letters, return _the length of the **longest palindrome**_ that can be built with those letters. + +Letters are **case sensitive**, for example, `"Aa"` is not considered a palindrome here. + +**Example 1:** + +**Input:** s = "abccccdd" + +**Output:** 7 + +**Explanation:** One longest palindrome that can be built is "dccaccd", whose length is 7. + +**Example 2:** + +**Input:** s = "a" + +**Output:** 1 + +**Explanation:** The longest palindrome that can be built is "a", whose length is 1. + +**Constraints:** + +* `1 <= s.length <= 2000` +* `s` consists of lowercase **and/or** uppercase English letters only. + +## Solution + +```kotlin +import java.util.BitSet + +class Solution { + fun longestPalindrome(s: String): Int { + val set = BitSet(60) + for (c in s.toCharArray()) { + set.flip(c.code - 'A'.code) + } + return if (set.isEmpty()) { + s.length + } else s.length - set.cardinality() + 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0410_split_array_largest_sum/readme.md b/src/main/kotlin/g0401_0500/s0410_split_array_largest_sum/readme.md new file mode 100644 index 00000000..6af17196 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0410_split_array_largest_sum/readme.md @@ -0,0 +1,78 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 410\. Split Array Largest Sum + +Hard + +Given an integer array `nums` and an integer `k`, split `nums` into `k` non-empty subarrays such that the largest sum of any subarray is **minimized**. + +Return _the minimized largest sum of the split_. + +A **subarray** is a contiguous part of the array. + +**Example 1:** + +**Input:** nums = [7,2,5,10,8], k = 2 + +**Output:** 18 + +**Explanation:** There are four ways to split nums into two subarrays. The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18. + +**Example 2:** + +**Input:** nums = [1,2,3,4,5], k = 2 + +**Output:** 9 + +**Explanation:** There are four ways to split nums into two subarrays. The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9. + +**Constraints:** + +* `1 <= nums.length <= 1000` +* 0 <= nums[i] <= 106 +* `1 <= k <= min(50, nums.length)` + +## Solution + +```kotlin +class Solution { + fun splitArray(nums: IntArray, m: Int): Int { + var maxVal = 0 + var minVal = nums[0] + for (num in nums) { + maxVal += num + minVal = Math.max(minVal, num) + } + while (minVal < maxVal) { + val midVal = minVal + (maxVal - minVal) / 2 + // if we can split, try to reduce the midVal so decrease maxVal + if (canSplit(midVal, nums, m)) { + maxVal = midVal + } else { + // if we can't split, then try to increase midVal by increasing minVal + minVal = midVal + 1 + } + } + return minVal + } + + private fun canSplit(maxSubArrSum: Int, nums: IntArray, m: Int): Boolean { + var currSum = 0 + var currSplits = 1 + for (num in nums) { + currSum += num + if (currSum > maxSubArrSum) { + currSum = num + currSplits++ + // if maxSubArrSum was TOO high that we can split the array into more that 'm' parts + // then its not ideal + if (currSplits > m) { + return false + } + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0412_fizz_buzz/readme.md b/src/main/kotlin/g0401_0500/s0412_fizz_buzz/readme.md new file mode 100644 index 00000000..804b67a1 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0412_fizz_buzz/readme.md @@ -0,0 +1,51 @@ +[![](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) + +## 412\. Fizz Buzz + +Easy + +Given an integer `n`, return _a string array_ `answer` _(**1-indexed**) where_: + +* `answer[i] == "FizzBuzz"` if `i` is divisible by `3` and `5`. +* `answer[i] == "Fizz"` if `i` is divisible by `3`. +* `answer[i] == "Buzz"` if `i` is divisible by `5`. +* `answer[i] == i` (as a string) if none of the above conditions are true. + +**Example 1:** + +**Input:** n = 3 + +**Output:** ["1","2","Fizz"] + +**Example 2:** + +**Input:** n = 5 + +**Output:** ["1","2","Fizz","4","Buzz"] + +**Example 3:** + +**Input:** n = 15 + +**Output:** ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] + +**Constraints:** + +* 1 <= n <= 104 + +## Solution + +```kotlin +class Solution { + fun fizzBuzz(n: Int): Array = Array(n) { index -> + val value = index + 1 + when { + (value % 3 == 0 && value % 5 == 0) -> "FizzBuzz" + (value % 3 == 0) -> "Fizz" + (value % 5 == 0) -> "Buzz" + else -> "$value" + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0413_arithmetic_slices/readme.md b/src/main/kotlin/g0401_0500/s0413_arithmetic_slices/readme.md new file mode 100644 index 00000000..c7971661 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0413_arithmetic_slices/readme.md @@ -0,0 +1,53 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 413\. Arithmetic Slices + +Medium + +An integer array is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same. + +* For example, `[1,3,5,7,9]`, `[7,7,7,7]`, and `[3,-1,-5,-9]` are arithmetic sequences. + +Given an integer array `nums`, return _the number of arithmetic **subarrays** of_ `nums`. + +A **subarray** is a contiguous subsequence of the array. + +**Example 1:** + +**Input:** nums = [1,2,3,4] + +**Output:** 3 + +**Explanation:** We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself. + +**Example 2:** + +**Input:** nums = [1] + +**Output:** 0 + +**Constraints:** + +* `1 <= nums.length <= 5000` +* `-1000 <= nums[i] <= 1000` + +## Solution + +```kotlin +class Solution { + fun numberOfArithmeticSlices(nums: IntArray): Int { + var sum = 0 + var curr = 0 + for (i in 2 until nums.size) { + if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) { + curr++ + sum += curr + } else { + curr = 0 + } + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0414_third_maximum_number/readme.md b/src/main/kotlin/g0401_0500/s0414_third_maximum_number/readme.md new file mode 100644 index 00000000..6dfb4f40 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0414_third_maximum_number/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 414\. Third Maximum Number + +Easy + +Given an integer array `nums`, return _the **third distinct maximum** number in this array. If the third maximum does not exist, return the **maximum** number_. + +**Example 1:** + +**Input:** nums = [3,2,1] + +**Output:** 1 + +**Explanation:** The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1. + +**Example 2:** + +**Input:** nums = [1,2] + +**Output:** 2 + +**Explanation:** The first distinct maximum is 2. The second distinct maximum is 1. The third distinct maximum does not exist, so the maximum (2) is returned instead. + +**Example 3:** + +**Input:** nums = [2,2,3,1] + +**Output:** 1 + +**Explanation:** The first distinct maximum is 3. The second distinct maximum is 2 (both 2's are counted together since they have the same value). The third distinct maximum is 1. + +**Constraints:** + +* 1 <= nums.length <= 104 +* -231 <= nums[i] <= 231 - 1 + +**Follow up:** Can you find an `O(n)` solution? + +## Solution + +```kotlin +class Solution { + fun thirdMax(nums: IntArray): Int { + var max1 = Long.MIN_VALUE + var max2 = Long.MIN_VALUE + var max3 = Long.MIN_VALUE + for (i in nums) { + max1 = Math.max(max1, i.toLong()) + } + for (i in nums) { + if (i.toLong() == max1) { + continue + } + max2 = Math.max(max2, i.toLong()) + } + for (i in nums) { + if (i.toLong() == max1 || i.toLong() == max2) { + continue + } + max3 = Math.max(max3, i.toLong()) + } + return (if (max3 == Long.MIN_VALUE) max1 else max3).toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0415_add_strings/readme.md b/src/main/kotlin/g0401_0500/s0415_add_strings/readme.md new file mode 100644 index 00000000..8ebe317b --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0415_add_strings/readme.md @@ -0,0 +1,61 @@ +[![](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) + +## 415\. Add Strings + +Easy + +Given two non-negative integers, `num1` and `num2` represented as string, return _the sum of_ `num1` _and_ `num2` _as a string_. + +You must solve the problem without using any built-in library for handling large integers (such as `BigInteger`). You must also not convert the inputs to integers directly. + +**Example 1:** + +**Input:** num1 = "11", num2 = "123" + +**Output:** "134" + +**Example 2:** + +**Input:** num1 = "456", num2 = "77" + +**Output:** "533" + +**Example 3:** + +**Input:** num1 = "0", num2 = "0" + +**Output:** "0" + +**Constraints:** + +* 1 <= num1.length, num2.length <= 104 +* `num1` and `num2` consist of only digits. +* `num1` and `num2` don't have any leading zeros except for the zero itself. + +## Solution + +```kotlin +class Solution { + fun addStrings(num1: String, num2: String): String { + var endNum1 = num1.length - 1 + var endNum2 = num2.length - 1 + val res = StringBuilder() + var carry = 0 + var sum: Int + while (endNum1 >= 0 || endNum2 >= 0) { + val a = if (endNum1 >= 0) num1[endNum1] - '0' else 0 + val b = if (endNum2 >= 0) num2[endNum2] - '0' else 0 + sum = (a + b + carry) % 10 + carry = (a + b + carry) / 10 + res.append(sum) + endNum1-- + endNum2-- + } + if (carry != 0) { + res.append(carry) + } + return res.reverse().toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0417_pacific_atlantic_water_flow/readme.md b/src/main/kotlin/g0401_0500/s0417_pacific_atlantic_water_flow/readme.md new file mode 100644 index 00000000..be9987b0 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0417_pacific_atlantic_water_flow/readme.md @@ -0,0 +1,104 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 417\. Pacific Atlantic Water Flow + +Medium + +There is an `m x n` rectangular island that borders both the **Pacific Ocean** and **Atlantic Ocean**. The **Pacific Ocean** touches the island's left and top edges, and the **Atlantic Ocean** touches the island's right and bottom edges. + +The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `heights` where `heights[r][c]` represents the **height above sea level** of the cell at coordinate `(r, c)`. + +The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is **less than or equal to** the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. + +Return _a **2D list** of grid coordinates_ `result` _where_ result[i] = [ri, ci] _denotes that rain water can flow from cell_ (ri, ci) _to **both** the Pacific and Atlantic oceans_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/06/08/waterflow-grid.jpg) + +**Input:** heights = \[\[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] + +**Output:** [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]] + +**Explanation:** The following cells can flow to the Pacific and Atlantic oceans, as shown below: [0,4]: [0,4] -> Pacific Ocean [0,4] -> Atlantic Ocean [1,3]: [1,3] -> [0,3] -> Pacific Ocean [1,3] -> [1,4] -> Atlantic Ocean [1,4]: [1,4] -> [1,3] -> [0,3] -> Pacific Ocean [1,4] -> Atlantic Ocean [2,2]: [2,2] -> [1,2] -> [0,2] -> Pacific Ocean [2,2] -> [2,3] -> [2,4] -> Atlantic Ocean [3,0]: [3,0] -> Pacific Ocean [3,0] -> [4,0] -> Atlantic Ocean [3,1]: [3,1] -> [3,0] -> Pacific Ocean [3,1] -> [4,1] -> Atlantic Ocean [4,0]: [4,0] -> Pacific Ocean [4,0] -> Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. + +**Example 2:** + +**Input:** heights = \[\[1]] + +**Output:** [[0,0]] + +**Explanation:** The water can flow from the only cell to the Pacific and Atlantic oceans. + +**Constraints:** + +* `m == heights.length` +* `n == heights[r].length` +* `1 <= m, n <= 200` +* 0 <= heights[r][c] <= 105 + +## Solution + +```kotlin +class Solution { + private var col = 0 + private var row = 0 + fun pacificAtlantic(matrix: Array): List> { + val res: MutableList> = ArrayList() + if (matrix.size == 0) { + return res + } + col = matrix.size + row = matrix[0].size + val pacific = Array(col) { + BooleanArray( + row + ) + } + val atlantic = Array(col) { + BooleanArray( + row + ) + } + for (i in 0 until col) { + dfs(i, 0, matrix, pacific) + dfs(i, row - 1, matrix, atlantic) + } + for (i in 0 until row) { + dfs(0, i, matrix, pacific) + dfs(col - 1, i, matrix, atlantic) + } + for (i in 0 until col) { + for (j in 0 until row) { + if (pacific[i][j] && atlantic[i][j]) { + val temp: MutableList = ArrayList() + temp.add(i) + temp.add(j) + res.add(temp) + } + } + } + return res + } + + private fun dfs(i: Int, j: Int, matrix: Array, visited: Array) { + if (i < 0 || j < 0 || i >= matrix.size || j >= matrix[0].size || visited[i][j]) { + return + } + visited[i][j] = true + if (i < col - 1 && matrix[i][j] <= matrix[i + 1][j]) { + dfs(i + 1, j, matrix, visited) + } + if (i > 0 && matrix[i][j] <= matrix[i - 1][j]) { + dfs(i - 1, j, matrix, visited) + } + if (j < row - 1 && matrix[i][j] <= matrix[i][j + 1]) { + dfs(i, j + 1, matrix, visited) + } + if (j > 0 && matrix[i][j] <= matrix[i][j - 1]) { + dfs(i, j - 1, matrix, visited) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0419_battleships_in_a_board/readme.md b/src/main/kotlin/g0401_0500/s0419_battleships_in_a_board/readme.md new file mode 100644 index 00000000..a4f04183 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0419_battleships_in_a_board/readme.md @@ -0,0 +1,58 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 419\. Battleships in a Board + +Medium + +Given an `m x n` matrix `board` where each cell is a battleship `'X'` or empty `'.'`, return _the number of the **battleships** on_ `board`. + +**Battleships** can only be placed horizontally or vertically on `board`. In other words, they can only be made of the shape `1 x k` (`1` row, `k` columns) or `k x 1` (`k` rows, `1` column), where `k` can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships). + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/10/battelship-grid.jpg) + +**Input:** board = \[\["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]] + +**Output:** 2 + +**Example 2:** + +**Input:** board = \[\["."]] + +**Output:** 0 + +**Constraints:** + +* `m == board.length` +* `n == board[i].length` +* `1 <= m, n <= 200` +* `board[i][j]` is either `'.'` or `'X'`. + +**Follow up:** Could you do it in one-pass, using only `O(1)` extra memory and without modifying the values `board`? + +## Solution + +```kotlin +class Solution { + fun countBattleships(board: Array?): Int { + if (board == null || board.size == 0) { + return 0 + } + var count = 0 + val m = board.size + val n = board[0].size + for (i in 0 until m) { + for (j in 0 until n) { + if (board[i][j] != '.' && (j <= 0 || board[i][j - 1] != 'X') && + (i <= 0 || board[i - 1][j] != 'X') + ) { + count++ + } + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0420_strong_password_checker/readme.md b/src/main/kotlin/g0401_0500/s0420_strong_password_checker/readme.md new file mode 100644 index 00000000..d36fdc33 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0420_strong_password_checker/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) + +## 420\. Strong Password Checker + +Hard + +A password is considered strong if the below conditions are all met: + +* It has at least `6` characters and at most `20` characters. +* It contains at least **one lowercase** letter, at least **one uppercase** letter, and at least **one digit**. +* It does not contain three repeating characters in a row (i.e., "B**aaa**bb0" is weak, but "B**aa**b**a**0" is strong). + +Given a string `password`, return _the minimum number of steps required to make `password` strong. if `password` is already strong, return `0`._ + +In one step, you can: + +* Insert one character to `password`, +* Delete one character from `password`, or +* Replace one character of `password` with another character. + +**Example 1:** + +**Input:** password = "a" + +**Output:** 5 + +**Example 2:** + +**Input:** password = "aA1" + +**Output:** 3 + +**Example 3:** + +**Input:** password = "1337C0d3" + +**Output:** 0 + +**Constraints:** + +* `1 <= password.length <= 50` +* `password` consists of letters, digits, dot `'.'` or exclamation mark `'!'`. + +## Solution + +```kotlin +class Solution { + fun strongPasswordChecker(s: String): Int { + var res = 0 + var a1 = 1 + var a2 = 1 + var d = 1 + val carr = s.toCharArray() + val arr = IntArray(carr.size) + var i1 = 0 + while (i1 < arr.size) { + if (Character.isLowerCase(carr[i1])) { + a1 = 0 + } + if (Character.isUpperCase(carr[i1])) { + a2 = 0 + } + if (Character.isDigit(carr[i1])) { + d = 0 + } + val j = i1 + while (i1 < carr.size && carr[i1] == carr[j]) { + i1++ + } + arr[j] = i1 - j + } + val totalMissing = a1 + a2 + d + if (arr.size < 6) { + res += totalMissing + Math.max(0, 6 - (arr.size + totalMissing)) + } else { + var overLen = Math.max(arr.size - 20, 0) + var leftOver = 0 + res += overLen + for (k in 1..2) { + var i = 0 + while (i < arr.size && overLen > 0) { + if (arr[i] < 3 || arr[i] % 3 != k - 1) { + i++ + continue + } + arr[i] -= Math.min(overLen, k) + overLen -= k + i++ + } + } + for (i in arr.indices) { + if (arr[i] >= 3 && overLen > 0) { + val need = arr[i] - 2 + arr[i] -= overLen + overLen -= need + } + if (arr[i] >= 3) { + leftOver += arr[i] / 3 + } + } + res += Math.max(totalMissing, leftOver) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0421_maximum_xor_of_two_numbers_in_an_array/readme.md b/src/main/kotlin/g0401_0500/s0421_maximum_xor_of_two_numbers_in_an_array/readme.md new file mode 100644 index 00000000..8cd88835 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0421_maximum_xor_of_two_numbers_in_an_array/readme.md @@ -0,0 +1,57 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 421\. Maximum XOR of Two Numbers in an Array + +Medium + +Given an integer array `nums`, return _the maximum result of_ `nums[i] XOR nums[j]`, where `0 <= i <= j < n`. + +**Example 1:** + +**Input:** nums = [3,10,5,25,2,8] + +**Output:** 28 + +**Explanation:** The maximum result is 5 XOR 25 = 28. + +**Example 2:** + +**Input:** nums = [14,70,53,83,49,91,36,80,92,51,66,70] + +**Output:** 127 + +**Constraints:** + +* 1 <= nums.length <= 2 * 105 +* 0 <= nums[i] <= 231 - 1 + +## Solution + +```kotlin +class Solution { + fun findMaximumXOR(nums: IntArray): Int { + var max = 0 + var mask = 0 + val set: MutableSet = HashSet() + var maxNum = 0 + for (i in nums) { + maxNum = Math.max(maxNum, i) + } + for (i in 31 - Integer.numberOfLeadingZeros(maxNum) downTo 0) { + set.clear() + val bit = 1 shl i + mask = mask or bit + val temp = max or bit + for (prefix in nums) { + if (set.contains(prefix and mask xor temp)) { + max = temp + break + } + set.add(prefix and mask) + } + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0423_reconstruct_original_digits_from_english/readme.md b/src/main/kotlin/g0401_0500/s0423_reconstruct_original_digits_from_english/readme.md new file mode 100644 index 00000000..71fa3ee5 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0423_reconstruct_original_digits_from_english/readme.md @@ -0,0 +1,57 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 423\. Reconstruct Original Digits from English + +Medium + +Given a string `s` containing an out-of-order English representation of digits `0-9`, return _the digits in **ascending** order_. + +**Example 1:** + +**Input:** s = "owoztneoer" + +**Output:** "012" + +**Example 2:** + +**Input:** s = "fviefuro" + +**Output:** "45" + +**Constraints:** + +* 1 <= s.length <= 105 +* `s[i]` is one of the characters `["e","g","f","i","h","o","n","s","r","u","t","w","v","x","z"]`. +* `s` is **guaranteed** to be valid. + +## Solution + +```kotlin +class Solution { + fun originalDigits(s: String): String { + val count = IntArray(26) + val digits = IntArray(10) + val str = StringBuilder() + for (c in s.toCharArray()) { + ++count[c.code - 'a'.code] + } + digits[0] = count[25] + digits[2] = count[22] + digits[4] = count[20] + digits[6] = count[23] + digits[8] = count[6] + digits[1] = count[14] - digits[0] - digits[2] - digits[4] + digits[3] = count[7] - digits[8] + digits[5] = count[5] - digits[4] + digits[7] = count[18] - digits[6] + digits[9] = count[8] - digits[5] - digits[6] - digits[8] + for (i in 0..9) { + while (digits[i]-- != 0) { + str.append((i + 48).toChar()) + } + } + return str.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0424_longest_repeating_character_replacement/readme.md b/src/main/kotlin/g0401_0500/s0424_longest_repeating_character_replacement/readme.md new file mode 100644 index 00000000..7264f239 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0424_longest_repeating_character_replacement/readme.md @@ -0,0 +1,64 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 424\. Longest Repeating Character Replacement + +Medium + +You are given a string `s` and an integer `k`. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most `k` times. + +Return _the length of the longest substring containing the same letter you can get after performing the above operations_. + +**Example 1:** + +**Input:** s = "ABAB", k = 2 + +**Output:** 4 + +**Explanation:** Replace the two 'A's with two 'B's or vice versa. + +**Example 2:** + +**Input:** s = "AABABBA", k = 1 + +**Output:** 4 + +**Explanation:** Replace the one 'A' in the middle with 'B' and form "AABBBBA". The substring "BBBB" has the longest repeating letters, which is 4. + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` consists of only uppercase English letters. +* `0 <= k <= s.length` + +## Solution + +```kotlin +class Solution { + fun characterReplacement(s: String, k: Int): Int { + var left = 0 + var right = 0 + val len = s.length + val count = IntArray(256) + val sArr = s.toCharArray() + var currMax = 0 + var maxLen = 0 + var curr: Char + while (right < len) { + curr = sArr[right] + count[curr.code]++ + currMax = Math.max(currMax, count[curr.code]) + if (right - left + 1 <= currMax + k) { + maxLen = Math.max(maxLen, right - left + 1) + } + while (right - left + 1 > currMax + k) { + curr = sArr[left] + count[curr.code]-- + left++ + } + right++ + } + return maxLen + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0427_construct_quad_tree/readme.md b/src/main/kotlin/g0401_0500/s0427_construct_quad_tree/readme.md new file mode 100644 index 00000000..be081ac9 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0427_construct_quad_tree/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) + +## 427\. Construct Quad Tree + +Medium + +Given a `n * n` matrix `grid` of `0's` and `1's` only. We want to represent the `grid` with a Quad-Tree. + +Return _the root of the Quad-Tree_ representing the `grid`. + +Notice that you can assign the value of a node to **True** or **False** when `isLeaf` is **False**, and both are **accepted** in the answer. + +A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes: + +* `val`: True if the node represents a grid of 1's or False if the node represents a grid of 0's. +* `isLeaf`: True if the node is leaf node on the tree or False if the node has the four children. + +class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; } + +We can construct a Quad-Tree from a two-dimensional area using the following steps: + +1. If the current grid has the same value (i.e all `1's` or all `0's`) set `isLeaf` True and set `val` to the value of the grid and set the four children to Null and stop. +2. If the current grid has different values, set `isLeaf` to False and set `val` to any value and divide the current grid into four sub-grids as shown in the photo. +3. Recurse for each of the children with the proper sub-grid. + +![](https://assets.leetcode.com/uploads/2020/02/11/new_top.png) + +If you want to know more about the Quad-Tree, you can refer to the [wiki](https://en.wikipedia.org/wiki/Quadtree). + +**Quad-Tree format:** + +The output represents the serialized format of a Quad-Tree using level order traversal, where `null` signifies a path terminator where no node exists below. + +It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list `[isLeaf, val]`. + +If the value of `isLeaf` or `val` is True we represent it as **1** in the list `[isLeaf, val]` and if the value of `isLeaf` or `val` is False we represent it as **0**. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/02/11/grid1.png) + +**Input:** grid = \[\[0,1],[1,0]] + +**Output:** [[0,1],[1,0],[1,1],[1,1],[1,0]] + +**Explanation:** The explanation of this example is shown below: Notice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree. ![](https://assets.leetcode.com/uploads/2020/02/12/e1tree.png) + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/02/12/e2mat.png) + +**Input:** grid = + + [[1,1,1,1,0,0,0,0], + [1,1,1,1,0,0,0,0], + [1,1,1,1,1,1,1,1], + [1,1,1,1,1,1,1,1], + [1,1,1,1,0,0,0,0], + [1,1,1,1,0,0,0,0], + [1,1,1,1,0,0,0,0], + [1,1,1,1,0,0,0,0]] + +**Output:** [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]] + +**Explanation:** All values in the grid are not the same. We divide the grid into four sub-grids. The topLeft, bottomLeft and bottomRight each has the same value. The topRight have different values so we divide it into 4 sub-grids where each has the same value. Explanation is shown in the photo below: ![](https://assets.leetcode.com/uploads/2020/02/12/e2tree.png) + +**Constraints:** + +* `n == grid.length == grid[i].length` +* n == 2x where `0 <= x <= 6` + +## Solution + +```kotlin +/* + * Definition for a QuadTree node. + * class Node(var `val`: Boolean, var isLeaf: Boolean) { + * var topLeft: Node? = null + * var topRight: Node? = null + * var bottomLeft: Node? = null + * var bottomRight: Node? = null + * } + */ + +class Solution { + fun construct(grid: Array): Node? { + return construct(grid, 0, 0, grid.size) + } + + fun construct(grid: Array, x: Int, y: Int, len: Int): Node? { + val value: Int = grid[x][y] + if (len == 1) { return Node(value == 1, true) } + + var isLeaf = true + for (i in 0 until len) { + for (p in 0 until len) { + if (grid[x + i][y + p] != value) { + isLeaf = false + } + } + } + if (isLeaf) { return Node(value == 1, true) } + + return Node(true, false).apply { + val halfLength: Int = len / 2 + topLeft = construct(grid, x, y, halfLength) + topRight = construct(grid, x, y + halfLength, halfLength) + bottomLeft = construct(grid, x + halfLength, y, halfLength) + bottomRight = construct(grid, x + halfLength, y + halfLength, halfLength) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0429_n_ary_tree_level_order_traversal/readme.md b/src/main/kotlin/g0401_0500/s0429_n_ary_tree_level_order_traversal/readme.md new file mode 100644 index 00000000..30e5a02f --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0429_n_ary_tree_level_order_traversal/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) + +## 429\. N-ary Tree Level Order Traversal + +Medium + +Given an n-ary tree, return the _level order_ traversal of its nodes' values. + +_Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples)._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png) + +**Input:** root = [1,null,3,2,4,null,5,6] + +**Output:** [[1],[3,2,4],[5,6]] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png) + +**Input:** root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] + +**Output:** [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]] + +**Constraints:** + +* The height of the n-ary tree is less than or equal to `1000` +* The total number of nodes is between [0, 104] + +## Solution + +```kotlin +import com_github_leetcode.Node + +/* + * Definition for a Node. + * class Node(var `val`: Int) { + * var neighbors: List = listOf() + * } + */ + +class Solution { + fun levelOrder(root: Node?) = go(listOfNotNull(root), mutableListOf()) + + private tailrec fun go(level: List, acc: MutableList>): List> = + if (level.isEmpty()) acc else go( + level = level.flatMap(Node::neighbors).filterNotNull(), + acc = acc.apply { level.map(Node::`val`).also { add(it) } } + ) +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0430_flatten_a_multilevel_doubly_linked_list/readme.md b/src/main/kotlin/g0401_0500/s0430_flatten_a_multilevel_doubly_linked_list/readme.md new file mode 100644 index 00000000..fff3091e --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0430_flatten_a_multilevel_doubly_linked_list/readme.md @@ -0,0 +1,106 @@ +[![](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) + +## 430\. Flatten a Multilevel Doubly Linked List + +Medium + +You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional **child pointer**. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a **multilevel data structure** as shown in the example below. + +Given the `head` of the first level of the list, **flatten** the list so that all the nodes appear in a single-level, doubly linked list. Let `curr` be a node with a child list. The nodes in the child list should appear **after** `curr` and **before** `curr.next` in the flattened list. + +Return _the_ `head` _of the flattened list. The nodes in the list must have **all** of their child pointers set to_ `null`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/11/09/flatten11.jpg) + +**Input:** head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] + +**Output:** [1,2,3,7,8,11,12,9,10,4,5,6] + +**Explanation:** The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: ![](https://assets.leetcode.com/uploads/2021/11/09/flatten12.jpg) + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/11/09/flatten2.1jpg) + +**Input:** head = [1,2,null,3] + +**Output:** [1,3,2] + +**Explanation:** The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: ![](https://assets.leetcode.com/uploads/2021/11/24/list.jpg) + +**Example 3:** + +**Input:** head = [] + +**Output:** [] + +**Explanation:** There could be empty list in the input. + +**Constraints:** + +* The number of Nodes will not exceed `1000`. +* 1 <= Node.val <= 105 + +**How the multilevel linked list is represented in test cases:** + +We use the multilevel linked list from **Example 1** above: + +1---2---3---4---5---6--NULL \| 7---8---9---10--NULL \| 11--12--NULL + +The serialization of each level is as follows: + +[1,2,3,4,5,6,null] [7,8,9,10,null] [11,12,null] + +To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes: + +[1, 2, 3, 4, 5, 6, null] \| [null, null, 7, 8, 9, 10, null] \| [ null, 11, 12, null] + +Merging the serialization of each level and removing trailing nulls we obtain: + +[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] + +## Solution + +```kotlin +import com_github_leetcode.prev_next.Node + +/* + * Definition for a Node. + * class Node(var `val`: Int) { + * var prev: Node? = null + * var next: Node? = null + * var child: Node? = null + * } + */ + +class Solution { + fun flatten(root: Node?): Node? { + var currentNode = root + while (currentNode != null) { + if (currentNode.child != null) { + appendToParent(currentNode, currentNode.next) + } + currentNode = currentNode.next + } + return root + } + + private fun appendToParent(parent: Node, parentNext: Node?) { + var currentNode = parent.child + while (currentNode?.next != null) { + if (currentNode.child != null) { + appendToParent(currentNode, currentNode.next) + } + currentNode = currentNode.next + } + parent.next = parent.child + parent.child?.prev = parent + currentNode?.next = parentNext + parentNext?.prev = currentNode + parent.child = null + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0432_all_oone_data_structure/readme.md b/src/main/kotlin/g0401_0500/s0432_all_oone_data_structure/readme.md new file mode 100644 index 00000000..7a120445 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0432_all_oone_data_structure/readme.md @@ -0,0 +1,168 @@ +[![](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) + +## 432\. All O\`one Data Structure + +Hard + +Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. + +Implement the `AllOne` class: + +* `AllOne()` Initializes the object of the data structure. +* `inc(String key)` Increments the count of the string `key` by `1`. If `key` does not exist in the data structure, insert it with count `1`. +* `dec(String key)` Decrements the count of the string `key` by `1`. If the count of `key` is `0` after the decrement, remove it from the data structure. It is guaranteed that `key` exists in the data structure before the decrement. +* `getMaxKey()` Returns one of the keys with the maximal count. If no element exists, return an empty string `""`. +* `getMinKey()` Returns one of the keys with the minimum count. If no element exists, return an empty string `""`. + +**Example 1:** + +**Input** + + ["AllOne", "inc", "inc", "getMaxKey", "getMinKey", "inc", "getMaxKey", "getMinKey"] + [[], ["hello"], ["hello"], [], [], ["leet"], [], []] + +**Output:** [null, null, null, "hello", "hello", null, "hello", "leet"] + +**Explanation:** + + AllOne allOne = new AllOne(); + allOne.inc("hello"); + allOne.inc("hello"); + allOne.getMaxKey(); // return "hello" + allOne.getMinKey(); // return "hello" + allOne.inc("leet"); + allOne.getMaxKey(); // return "hello" + allOne.getMinKey(); // return "leet" + +**Constraints:** + +* `1 <= key.length <= 10` +* `key` consists of lowercase English letters. +* It is guaranteed that for each call to `dec`, `key` is existing in the data structure. +* At most 5 * 104 calls will be made to `inc`, `dec`, `getMaxKey`, and `getMinKey`. + +## Solution + +```kotlin +class AllOne { + // maintain a doubly linked list of Buckets + private val head: Bucket + private val tail: Bucket + + // for accessing a specific Bucket among the Bucket list in O(1) time + private val countBucketMap: MutableMap + + // keep track of count of keys + private val keyCountMap: MutableMap + + // each Bucket contains all the keys with the same count + private class Bucket(var count: Int) { + var keySet: MutableSet + var next: Bucket? = null + var pre: Bucket? = null + + init { + keySet = HashSet() + } + } + + /* Initialize your data structure here. */ + init { + head = Bucket(Int.MIN_VALUE) + tail = Bucket(Int.MAX_VALUE) + head.next = tail + tail.pre = head + countBucketMap = HashMap() + keyCountMap = HashMap() + } + + /* Inserts a new key with value 1. Or increments an existing key by 1. */ + fun inc(key: String) { + if (keyCountMap.containsKey(key)) { + changeKey(key, 1) + } else { + keyCountMap[key] = 1 + if (head.next!!.count != 1) { + addBucketAfter(Bucket(1), head) + } + head.next!!.keySet.add(key) + countBucketMap[1] = head.next + } + } + + /* Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */ + fun dec(key: String) { + if (keyCountMap.containsKey(key)) { + val count = keyCountMap[key]!! + if (count == 1) { + keyCountMap.remove(key) + removeKeyFromBucket(countBucketMap[count], key) + } else { + changeKey(key, -1) + } + } + } + + /* Returns one of the keys with maximal value. */ + fun getMaxKey(): String { + return if (tail.pre === head) "" else tail.pre!!.keySet.iterator().next() + } + + /* Returns one of the keys with Minimal value. */ + fun getMinKey(): String { + return if (head.next === tail) "" else head.next!!.keySet.iterator().next() + } + + // helper function to make change on given key according to offset + private fun changeKey(key: String, offset: Int) { + val count = keyCountMap[key]!! + keyCountMap[key] = count + offset + val curBucket = countBucketMap[count] + val newBucket: Bucket? + if (countBucketMap.containsKey(count + offset)) { + // target Bucket already exists + newBucket = countBucketMap[count + offset] + } else { + // add new Bucket + newBucket = Bucket(count + offset) + countBucketMap[count + offset] = newBucket + addBucketAfter(newBucket, if (offset == 1) curBucket else curBucket!!.pre) + } + newBucket!!.keySet.add(key) + removeKeyFromBucket(curBucket, key) + } + + private fun removeKeyFromBucket(bucket: Bucket?, key: String) { + bucket!!.keySet.remove(key) + if (bucket.keySet.isEmpty()) { + removeBucketFromList(bucket) + countBucketMap.remove(bucket.count) + } + } + + private fun removeBucketFromList(bucket: Bucket?) { + bucket!!.pre!!.next = bucket.next + bucket.next!!.pre = bucket.pre + bucket.next = null + bucket.pre = null + } + + // add newBucket after preBucket + private fun addBucketAfter(newBucket: Bucket, preBucket: Bucket?) { + newBucket.pre = preBucket + newBucket.next = preBucket!!.next + preBucket.next!!.pre = newBucket + preBucket.next = newBucket + } +} + +/* + * Your AllOne object will be instantiated and called as such: + * var obj = AllOne() + * obj.inc(key) + * obj.dec(key) + * var param_3 = obj.getMaxKey() + * var param_4 = obj.getMinKey() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0433_minimum_genetic_mutation/readme.md b/src/main/kotlin/g0401_0500/s0433_minimum_genetic_mutation/readme.md new file mode 100644 index 00000000..cb073d7e --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0433_minimum_genetic_mutation/readme.md @@ -0,0 +1,89 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 433\. Minimum Genetic Mutation + +Medium + +A gene string can be represented by an 8-character long string, with choices from `'A'`, `'C'`, `'G'`, and `'T'`. + +Suppose we need to investigate a mutation from a gene string `startGene` to a gene string `endGene` where one mutation is defined as one single character changed in the gene string. + +* For example, `"AACCGGTT" --> "AACCGGTA"` is one mutation. + +There is also a gene bank `bank` that records all the valid gene mutations. A gene must be in `bank` to make it a valid gene string. + +Given the two gene strings `startGene` and `endGene` and the gene bank `bank`, return _the minimum number of mutations needed to mutate from_ `startGene` _to_ `endGene`. If there is no such a mutation, return `-1`. + +Note that the starting point is assumed to be valid, so it might not be included in the bank. + +**Example 1:** + +**Input:** startGene = "AACCGGTT", endGene = "AACCGGTA", bank = ["AACCGGTA"] + +**Output:** 1 + +**Example 2:** + +**Input:** startGene = "AACCGGTT", endGene = "AAACGGTA", bank = ["AACCGGTA","AACCGCTA","AAACGGTA"] + +**Output:** 2 + +**Constraints:** + +* `0 <= bank.length <= 10` +* `startGene.length == endGene.length == bank[i].length == 8` +* `startGene`, `endGene`, and `bank[i]` consist of only the characters `['A', 'C', 'G', 'T']`. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + private fun isInBank(set: Set, cur: String): List { + val res: MutableList = ArrayList() + for (each in set) { + var diff = 0 + for (i in 0 until each.length) { + if (each[i] != cur[i]) { + diff++ + if (diff > 1) { + break + } + } + } + if (diff == 1) { + res.add(each) + } + } + return res + } + + fun minMutation(start: String, end: String, bank: Array): Int { + val set: MutableSet = HashSet() + for (s in bank) { + set.add(s) + } + val queue: Queue = LinkedList() + queue.offer(start) + var step = 0 + while (!queue.isEmpty()) { + var curSize = queue.size + while (curSize-- > 0) { + val cur = queue.poll() + if (cur == end) { + return step + } + for (next in isInBank(set, cur)) { + queue.offer(next) + set.remove(next) + } + } + step++ + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0434_number_of_segments_in_a_string/readme.md b/src/main/kotlin/g0401_0500/s0434_number_of_segments_in_a_string/readme.md new file mode 100644 index 00000000..b90a3352 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0434_number_of_segments_in_a_string/readme.md @@ -0,0 +1,53 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 434\. Number of Segments in a String + +Easy + +Given a string `s`, return _the number of segments in the string_. + +A **segment** is defined to be a contiguous sequence of **non-space characters**. + +**Example 1:** + +**Input:** s = "Hello, my name is John" + +**Output:** 5 + +**Explanation:** The five segments are ["Hello,", "my", "name", "is", "John"] + +**Example 2:** + +**Input:** s = "Hello" + +**Output:** 1 + +**Constraints:** + +* `0 <= s.length <= 300` +* `s` consists of lowercase and uppercase English letters, digits, or one of the following characters `"!@#$%^&*()_+-=',.:"`. +* The only space character in `s` is `' '`. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun countSegments(s: String): Int { + var s = s + s = s.trim { it <= ' ' } + if (s.length == 0) { + return 0 + } + val splitted = s.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + var result = 0 + for (value in splitted) { + if (value.length > 0) { + result++ + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0435_non_overlapping_intervals/readme.md b/src/main/kotlin/g0401_0500/s0435_non_overlapping_intervals/readme.md new file mode 100644 index 00000000..e2c753a5 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0435_non_overlapping_intervals/readme.md @@ -0,0 +1,64 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 435\. Non-overlapping Intervals + +Medium + +Given an array of intervals `intervals` where intervals[i] = [starti, endi], return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_. + +**Example 1:** + +**Input:** intervals = \[\[1,2],[2,3],[3,4],[1,3]] + +**Output:** 1 + +**Explanation:** [1,3] can be removed and the rest of the intervals are non-overlapping. + +**Example 2:** + +**Input:** intervals = \[\[1,2],[1,2],[1,2]] + +**Output:** 2 + +**Explanation:** You need to remove two [1,2] to make the rest of the intervals non-overlapping. + +**Example 3:** + +**Input:** intervals = \[\[1,2],[2,3]] + +**Output:** 0 + +**Explanation:** You don't need to remove any of the intervals since they're already non-overlapping. + +**Constraints:** + +* 1 <= intervals.length <= 105 +* `intervals[i].length == 2` +* -5 * 104 <= starti < endi <= 5 * 104 + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun eraseOverlapIntervals(intervals: Array): Int { + Arrays.sort(intervals) { a: IntArray, b: IntArray -> + if (a[0] != b[0] + ) a[0] - b[0] else a[1] - b[1] + } + var erasures = 0 + var end = intervals[0][1] + for (i in 1 until intervals.size) { + end = if (intervals[i][0] < end) { + erasures++ + Math.min(end, intervals[i][1]) + } else { + intervals[i][1] + } + } + return erasures + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0436_find_right_interval/readme.md b/src/main/kotlin/g0401_0500/s0436_find_right_interval/readme.md new file mode 100644 index 00000000..531ded42 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0436_find_right_interval/readme.md @@ -0,0 +1,85 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 436\. Find Right Interval + +Medium + +You are given an array of `intervals`, where intervals[i] = [starti, endi] and each starti is **unique**. + +The **right interval** for an interval `i` is an interval `j` such that startj >= endi and startj is **minimized**. Note that `i` may equal `j`. + +Return _an array of **right interval** indices for each interval `i`_. If no **right interval** exists for interval `i`, then put `-1` at index `i`. + +**Example 1:** + +**Input:** intervals = \[\[1,2]] + +**Output:** [-1] + +**Explanation:** There is only one interval in the collection, so it outputs -1. + +**Example 2:** + +**Input:** intervals = \[\[3,4],[2,3],[1,2]] + +**Output:** [-1,0,1] + +**Explanation:** There is no right interval for [3,4]. + +The right interval for [2,3] is [3,4] since start0 = 3 is the smallest start that is >= end1 = 3. + +The right interval for [1,2] is [2,3] since start1 = 2 is the smallest start that is >= end2 = 2. + +**Example 3:** + +**Input:** intervals = \[\[1,4],[2,3],[3,4]] + +**Output:** [-1,2,-1] + +**Explanation:** There is no right interval for [1,4] and [3,4]. The right interval for [2,3] is [3,4] since start2 = 3 is the smallest start that is >= end1 = 3. + +**Constraints:** + +* 1 <= intervals.length <= 2 * 104 +* `intervals[i].length == 2` +* -106 <= starti <= endi <= 106 +* The start point of each interval is **unique**. + +## Solution + +```kotlin +import java.util.function.Function + +class Solution { + private fun findminmax(num: Array): IntArray { + var min = num[0][0] + var max = num[0][0] + for (i in 1 until num.size) { + min = Math.min(min, num[i][0]) + max = Math.max(max, num[i][0]) + } + return intArrayOf(min, max) + } + + fun findRightInterval(intervals: Array): IntArray { + if (intervals.size <= 1) { + return intArrayOf(-1) + } + val n = intervals.size + val result = IntArray(n) + val map: MutableMap = HashMap() + for (i in 0 until n) { + map[intervals[i][0]] = i + } + val minmax = findminmax(intervals) + for (i in minmax[1] - 1 downTo minmax[0] + 1) { + map.computeIfAbsent(i, Function { k: Int -> map[k + 1] }) + } + for (i in 0 until n) { + result[i] = map.getOrDefault(intervals[i][1], -1)!! + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0440_k_th_smallest_in_lexicographical_order/readme.md b/src/main/kotlin/g0401_0500/s0440_k_th_smallest_in_lexicographical_order/readme.md new file mode 100644 index 00000000..cda85b94 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0440_k_th_smallest_in_lexicographical_order/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) + +## 440\. K-th Smallest in Lexicographical Order + +Hard + +Given two integers `n` and `k`, return _the_ kth _lexicographically smallest integer in the range_ `[1, n]`. + +**Example 1:** + +**Input:** n = 13, k = 2 + +**Output:** 10 + +**Explanation:** The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. + +**Example 2:** + +**Input:** n = 1, k = 1 + +**Output:** 1 + +**Constraints:** + +* 1 <= k <= n <= 109 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun findKthNumber(n: Int, k: Int): Int { + var k = k + var curr = 1 + k = k - 1 + while (k > 0) { + val steps = calSteps(n, curr.toLong(), curr + 1L) + if (steps <= k) { + curr += 1 + k -= steps + } else { + curr *= 10 + k -= 1 + } + } + return curr + } + + // use long in case of overflow + private fun calSteps(n: Int, n1: Long, n2: Long): Int { + var n1 = n1 + var n2 = n2 + var steps: Long = 0 + while (n1 <= n) { + steps += Math.min(n + 1L, n2) - n1 + n1 *= 10 + n2 *= 10 + } + return steps.toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0441_arranging_coins/readme.md b/src/main/kotlin/g0401_0500/s0441_arranging_coins/readme.md new file mode 100644 index 00000000..8e7b87bd --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0441_arranging_coins/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) + +## 441\. Arranging Coins + +Easy + +You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the ith row has exactly `i` coins. The last row of the staircase **may be** incomplete. + +Given the integer `n`, return _the number of **complete rows** of the staircase you will build_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/09/arrangecoins1-grid.jpg) + +**Input:** n = 5 + +**Output:** 2 + +**Explanation:** Because the 3rd row is incomplete, we return 2. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/04/09/arrangecoins2-grid.jpg) + +**Input:** n = 8 + +**Output:** 3 + +**Explanation:** Because the 4th row is incomplete, we return 3. + +**Constraints:** + +* 1 <= n <= 231 - 1 + +## Solution + +```kotlin +class Solution { + fun arrangeCoins(n: Int): Int { + var i = 1 + var x = n + while (x > 0) { + x -= ++i + } + return i - 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0442_find_all_duplicates_in_an_array/readme.md b/src/main/kotlin/g0401_0500/s0442_find_all_duplicates_in_an_array/readme.md new file mode 100644 index 00000000..3020019a --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0442_find_all_duplicates_in_an_array/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) + +## 442\. Find All Duplicates in an Array + +Medium + +Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_. + +You must write an algorithm that runs in `O(n) `time and uses only constant extra space. + +**Example 1:** + +**Input:** nums = [4,3,2,7,8,2,3,1] + +**Output:** [2,3] + +**Example 2:** + +**Input:** nums = [1,1,2] + +**Output:** [1] + +**Example 3:** + +**Input:** nums = [1] + +**Output:** [] + +**Constraints:** + +* `n == nums.length` +* 1 <= n <= 105 +* `1 <= nums[i] <= n` +* Each element in `nums` appears **once** or **twice**. + +## Solution + +```kotlin +class Solution { + fun findDuplicates(nums: IntArray): List { + val setToCheck: MutableSet = mutableSetOf() + val duplicates: MutableList = mutableListOf() + + nums.forEach { element -> + if (!setToCheck.add(element)) { + duplicates.add(element) + } + } + + return duplicates + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0443_string_compression/readme.md b/src/main/kotlin/g0401_0500/s0443_string_compression/readme.md new file mode 100644 index 00000000..36586f7e --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0443_string_compression/readme.md @@ -0,0 +1,87 @@ +[![](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) + +## 443\. String Compression + +Medium + +Given an array of characters `chars`, compress it using the following algorithm: + +Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`: + +* If the group's length is `1`, append the character to `s`. +* Otherwise, append the character followed by the group's length. + +The compressed string `s` **should not be returned separately**, but instead, be stored **in the input character array `chars`**. Note that group lengths that are `10` or longer will be split into multiple characters in `chars`. + +After you are done **modifying the input array,** return _the new length of the array_. + +You must write an algorithm that uses only constant extra space. + +**Example 1:** + +**Input:** chars = ["a","a","b","b","c","c","c"] + +**Output:** Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] + +**Explanation:** The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3". + +**Example 2:** + +**Input:** chars = ["a"] + +**Output:** Return 1, and the first character of the input array should be: ["a"] + +**Explanation:** The only group is "a", which remains uncompressed since it's a single character. + +**Example 3:** + +**Input:** chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"] + +**Output:** Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]. + +**Explanation:** The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12". + +**Constraints:** + +* `1 <= chars.length <= 2000` +* `chars[i]` is a lowercase English letter, uppercase English letter, digit, or symbol. + +## Solution + +```kotlin +class Solution { + /* This is breaking the rules, it's not in-place. */ + fun compress(chars: CharArray): Int { + if (chars.size == 0) { + return 0 + } + val sb = StringBuilder() + var count = 1 + var prev = chars[0] + for (i in 1 until chars.size) { + if (chars[i] == prev) { + count++ + } else { + if (count > 1) { + sb.append(prev) + sb.append(count) + } else if (count == 1) { + sb.append(prev) + } + prev = chars[i] + count = 1 + } + } + sb.append(prev) + if (count > 1) { + sb.append(count) + } + var i = 0 + for (c in sb.toString().toCharArray()) { + chars[i++] = c + } + return sb.length + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0445_add_two_numbers_ii/readme.md b/src/main/kotlin/g0401_0500/s0445_add_two_numbers_ii/readme.md new file mode 100644 index 00000000..243c82f9 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0445_add_two_numbers_ii/readme.md @@ -0,0 +1,112 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 445\. Add Two Numbers II + +Medium + +You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. + +You may assume the two numbers do not contain any leading zero, except the number 0 itself. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/09/sumii-linked-list.jpg) + +**Input:** l1 = [7,2,4,3], l2 = [5,6,4] + +**Output:** [7,8,0,7] + +**Example 2:** + +**Input:** l1 = [2,4,3], l2 = [5,6,4] + +**Output:** [8,0,7] + +**Example 3:** + +**Input:** l1 = [0], l2 = [0] + +**Output:** [0] + +**Constraints:** + +* The number of nodes in each linked list is in the range `[1, 100]`. +* `0 <= Node.val <= 9` +* It is guaranteed that the list represents a number that does not have leading zeros. + +**Follow up:** Could you solve it without reversing the input lists? + +## Solution + +```kotlin +import com_github_leetcode.ListNode + +/* + * 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") +class Solution { + private fun reverse(head: ListNode?): ListNode? { + if (head == null || head.next == null) { + return head + } + var prev: ListNode? = null + var curr: ListNode = head + var next = head.next + while (next != null) { + curr.next = prev + prev = curr + curr = next + next = next.next + } + curr.next = prev + return curr + } + + fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? { + var l1 = l1 + var l2 = l2 + l1 = reverse(l1) + l2 = reverse(l2) + var res: ListNode? = ListNode() + val head = res + var carry = 0 + while (l1 != null || l2 != null) { + var val1: Int + var val2: Int + if (l1 == null) { + val1 = 0 + } else { + val1 = l1.`val` + l1 = l1.next + } + if (l2 == null) { + val2 = 0 + } else { + val2 = l2.`val` + l2 = l2.next + } + var data = val1 + val2 + carry + if (data > 9) { + carry = data / 10 + data = data % 10 + } else { + carry = 0 + } + res!!.next = ListNode(data) + res = res.next + } + if (carry != 0) { + res!!.next = ListNode(carry) + } + return reverse(head!!.next) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0446_arithmetic_slices_ii_subsequence/readme.md b/src/main/kotlin/g0401_0500/s0446_arithmetic_slices_ii_subsequence/readme.md new file mode 100644 index 00000000..75901019 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0446_arithmetic_slices_ii_subsequence/readme.md @@ -0,0 +1,79 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 446\. Arithmetic Slices II - Subsequence + +Hard + +Given an integer array `nums`, return _the number of all the **arithmetic subsequences** of_ `nums`. + +A sequence of numbers is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same. + +* For example, `[1, 3, 5, 7, 9]`, `[7, 7, 7, 7]`, and `[3, -1, -5, -9]` are arithmetic sequences. +* For example, `[1, 1, 2, 5, 7]` is not an arithmetic sequence. + +A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array. + +* For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`. + +The test cases are generated so that the answer fits in **32-bit** integer. + +**Example 1:** + +**Input:** nums = [2,4,6,8,10] + +**Output:** 7 + +**Explanation:** All arithmetic subsequence slices are: + +[2,4,6] + +[4,6,8] + +[6,8,10] + +[2,4,6,8] + +[4,6,8,10] + +[2,4,6,8,10] + +[2,6,10] + +**Example 2:** + +**Input:** nums = [7,7,7,7,7] + +**Output:** 16 + +**Explanation:** Any subsequence of this array is arithmetic. + +**Constraints:** + +* `1 <= nums.length <= 1000` +* -231 <= nums[i] <= 231 - 1 + +## Solution + +```kotlin +class Solution { + fun numberOfArithmeticSlices(arr: IntArray): Int { + val indexes: MutableMap> = HashMap() + val length = Array(arr.size) { IntArray(arr.size) } + var count = 0 + for (i in arr.indices) { + for (j in i + 1 until arr.size) { + val ix = indexes[arr[i] - (arr[j] - arr[i].toLong())] ?: continue + for (k in ix) { + length[i][j] += length[k][i] + 1 + } + count += length[i][j] + } + indexes.computeIfAbsent( + arr[i].toLong() + ) { _: Long? -> ArrayList() }.add(i) + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0447_number_of_boomerangs/readme.md b/src/main/kotlin/g0401_0500/s0447_number_of_boomerangs/readme.md new file mode 100644 index 00000000..c1200cab --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0447_number_of_boomerangs/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) + +## 447\. Number of Boomerangs + +Medium + +You are given `n` `points` in the plane that are all **distinct**, where points[i] = [xi, yi]. A **boomerang** is a tuple of points `(i, j, k)` such that the distance between `i` and `j` equals the distance between `i` and `k` **(the order of the tuple matters)**. + +Return _the number of boomerangs_. + +**Example 1:** + +**Input:** points = \[\[0,0],[1,0],[2,0]] + +**Output:** 2 + +**Explanation:** The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]. + +**Example 2:** + +**Input:** points = \[\[1,1],[2,2],[3,3]] + +**Output:** 2 + +**Example 3:** + +**Input:** points = \[\[1,1]] + +**Output:** 0 + +**Constraints:** + +* `n == points.length` +* `1 <= n <= 500` +* `points[i].length == 2` +* -104 <= xi, yi <= 104 +* All the points are **unique**. + +## Solution + +```kotlin +class Solution { + fun numberOfBoomerangs(points: Array): Int { + val m: HashMap = HashMap() + var ans = 0 + for (i in points.indices) { + for (j in points.indices) { + if (i == j) { + continue + } + val dis = dist(points[i], points[j]) + val prev = m.getOrDefault(dis, 0) + if (prev >= 1) { + ans += prev * 2 + } + m[dis] = prev + 1 + } + m.clear() + } + return ans + } + + private fun dist(d1: IntArray, d2: IntArray): Int { + return (d1[0] - d2[0]) * (d1[0] - d2[0]) + (d1[1] - d2[1]) * (d1[1] - d2[1]) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0448_find_all_numbers_disappeared_in_an_array/readme.md b/src/main/kotlin/g0401_0500/s0448_find_all_numbers_disappeared_in_an_array/readme.md new file mode 100644 index 00000000..314218f2 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0448_find_all_numbers_disappeared_in_an_array/readme.md @@ -0,0 +1,50 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 448\. Find All Numbers Disappeared in an Array + +Easy + +Given an array `nums` of `n` integers where `nums[i]` is in the range `[1, n]`, return _an array of all the integers in the range_ `[1, n]` _that do not appear in_ `nums`. + +**Example 1:** + +**Input:** nums = [4,3,2,7,8,2,3,1] + +**Output:** [5,6] + +**Example 2:** + +**Input:** nums = [1,1] + +**Output:** [2] + +**Constraints:** + +* `n == nums.length` +* 1 <= n <= 105 +* `1 <= nums[i] <= n` + +**Follow up:** Could you do it without extra space and in `O(n)` runtime? You may assume the returned list does not count as extra space. + +## Solution + +```kotlin +class Solution { + fun findDisappearedNumbers(nums: IntArray): List { + val arr = IntArray(nums.size) + var counter = 0 + for (i in nums.indices) { + arr[nums[counter] - 1] = 1 + counter++ + } + val res: MutableList = ArrayList() + for (i in arr.indices) { + if (arr[i] == 0) { + res.add(i + 1) + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0449_serialize_and_deserialize_bst/readme.md b/src/main/kotlin/g0401_0500/s0449_serialize_and_deserialize_bst/readme.md new file mode 100644 index 00000000..f8e8474f --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0449_serialize_and_deserialize_bst/readme.md @@ -0,0 +1,96 @@ +[![](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) + +## 449\. Serialize and Deserialize BST + +Medium + +Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. + +Design an algorithm to serialize and deserialize a **binary search tree**. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure. + +**The encoded string should be as compact as possible.** + +**Example 1:** + +**Input:** root = [2,1,3] + +**Output:** [2,1,3] + +**Example 2:** + +**Input:** root = [] + +**Output:** [] + +**Constraints:** + +* The number of nodes in the tree is in the range [0, 104]. +* 0 <= Node.val <= 104 +* The input tree is **guaranteed** to be a binary search tree. + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ + +class Codec { + private var cur = 0 + + // Encodes a tree to a single string. + fun serialize(root: TreeNode?): String { + val sb = StringBuilder() + serializeDfs(root, sb) + return sb.toString() + } + + private fun serializeDfs(root: TreeNode?, sb: StringBuilder) { + if (root == null) { + sb.append(SPLIT) + return + } + sb.append((root.`val` + MIN).toChar()) + serializeDfs(root.left, sb) + serializeDfs(root.right, sb) + } + + // Decodes your encoded data to tree. + fun deserialize(data: String): TreeNode? { + cur = 0 + return deserializeDFS(data.toCharArray()) + } + + private fun deserializeDFS(data: CharArray): TreeNode? { + if (data[cur] == SPLIT) { + cur++ + return null + } + val node = TreeNode(data[cur++].code - MIN) + node.left = deserializeDFS(data) + node.right = deserializeDFS(data) + return node + } + + companion object { + private const val SPLIT = 0.toChar() + private const val MIN = 1 + } +} + +/* + * Your Codec object will be instantiated and called as such: + * val ser = Codec() + * val deser = Codec() + * val tree: String = ser.serialize(root) + * val ans = deser.deserialize(tree) + * return ans + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0450_delete_node_in_a_bst/readme.md b/src/main/kotlin/g0401_0500/s0450_delete_node_in_a_bst/readme.md new file mode 100644 index 00000000..5d26eb9d --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0450_delete_node_in_a_bst/readme.md @@ -0,0 +1,101 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 450\. Delete Node in a BST + +Medium + +Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return _the **root node reference** (possibly updated) of the BST_. + +Basically, the deletion can be divided into two stages: + +1. Search for a node to remove. +2. If the node is found, delete the node. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/04/del_node_1.jpg) + +**Input:** root = [5,3,6,2,4,null,7], key = 3 + +**Output:** [5,4,6,2,null,null,7] + +**Explanation:** Given key to delete is 3. So we find the node with value 3 and delete it. + +One valid answer is [5,4,6,2,null,null,7], shown in the above BST. + +Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted. + +![](https://assets.leetcode.com/uploads/2020/09/04/del_node_supp.jpg) + +**Example 2:** + +**Input:** root = [5,3,6,2,4,null,7], key = 0 + +**Output:** [5,3,6,2,4,null,7] + +**Explanation:** The tree does not contain a node with value = 0. + +**Example 3:** + +**Input:** root = [], key = 0 + +**Output:** [] + +**Constraints:** + +* The number of nodes in the tree is in the range [0, 104]. +* -105 <= Node.val <= 105 +* Each node has a **unique** value. +* `root` is a valid binary search tree. +* -105 <= key <= 105 + +**Follow up:** Could you solve it with time complexity `O(height of tree)`? + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun deleteNode(root: TreeNode?, key: Int): TreeNode? { + if (root == null) return root + // find the correct node + if (key < root.`val`) { + root.left = deleteNode(root.left, key) + } else if (key > root.`val`) { + root.right = deleteNode(root.right, key) + } else { + // case 1 - both children are null + if (root.left == null && root.right == null) { + return null + } else if (root.left != null && root.right != null) { // case 2 - both children are NOT null + val successor = minimum(root.right!!) // inorder successor + root.right = deleteNode(root.right, successor) + root.`val` = successor + } else { // case 3 - only one of the child is null + return root.left ?: root.right + } + } + return root + } + + private fun minimum(root: TreeNode): Int { + var node = root + while (node.left != null) { + node = node.left!! + } + return node.`val` + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0451_sort_characters_by_frequency/readme.md b/src/main/kotlin/g0401_0500/s0451_sort_characters_by_frequency/readme.md new file mode 100644 index 00000000..76e29f3c --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0451_sort_characters_by_frequency/readme.md @@ -0,0 +1,50 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 451\. Sort Characters By Frequency + +Medium + +Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string. + +Return _the sorted string_. If there are multiple answers, return _any of them_. + +**Example 1:** + +**Input:** s = "tree" + +**Output:** "eert" + +**Explanation:** 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. + +**Example 2:** + +**Input:** s = "cccaaa" + +**Output:** "aaaccc" + +**Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers. Note that "cacaca" is incorrect, as the same characters must be together. + +**Example 3:** + +**Input:** s = "Aabb" + +**Output:** "bbAa" + +**Explanation:** "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters. + +**Constraints:** + +* 1 <= s.length <= 5 * 105 +* `s` consists of uppercase and lowercase English letters and digits. + +## Solution + +```kotlin +class Solution { + fun frequencySort(s: String) = s.groupingBy { it }.eachCount().entries.sortedByDescending { it.value } + .joinToString("") { + StringBuilder().apply { for (i in 1..it.value) append(it.key) }.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/readme.md b/src/main/kotlin/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/readme.md new file mode 100644 index 00000000..5afb9d4d --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons/readme.md @@ -0,0 +1,89 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 452\. Minimum Number of Arrows to Burst Balloons + +Medium + +There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where points[i] = [xstart, xend] denotes a balloon whose **horizontal diameter** stretches between xstart and xend. You do not know the exact y-coordinates of the balloons. + +Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is **burst** by an arrow shot at `x` if xstart <= x <= xend. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. + +Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_. + +**Example 1:** + +**Input:** points = \[\[10,16],[2,8],[1,6],[7,12]] + +**Output:** 2 + +**Explanation:** The balloons can be burst by 2 arrows: + +- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. + +- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. + +**Example 2:** + +**Input:** points = \[\[1,2],[3,4],[5,6],[7,8]] + +**Output:** 4 + +**Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows. + +**Example 3:** + +**Input:** points = \[\[1,2],[2,3],[3,4],[4,5]] + +**Output:** 2 + +**Explanation:** The balloons can be burst by 2 arrows: + +- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. + +- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]. + +**Constraints:** + +* 1 <= points.length <= 105 +* `points[i].length == 2` +* -231 <= xstart < xend <= 231 - 1 + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + /* + * I'm glad to have come up with this solution on my own on 10/13/2021: + * we'll have to sort the + * balloons by its ending points, a counter case to this is below: + * { {0, 6}, {0, 9}, {7, 8}} + * if we sort by starting points, then it becomes: + * {0, 6}, {0, 9}, {7, 8} + * this way, if we shoot 9, + * {0, 6} won't be burst however, if we sort by ending points, then it becomes: + * {0, 6}, {7, 8}, {0, 9}, then we shoot at 6, then at 8, this gives us the result of bursting all balloons. + */ + fun findMinArrowShots(points: Array): Int { + Arrays.sort( + points + ) { a: IntArray, b: IntArray -> + Integer.compare( + a[1], + b[1] + ) + } + var minArrows = 1 + var end = points[0][1].toLong() + for (i in 1 until points.size) { + if (points[i][0] > end) { + minArrows++ + end = points[i][1].toLong() + } + } + return minArrows + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0453_minimum_moves_to_equal_array_elements/readme.md b/src/main/kotlin/g0401_0500/s0453_minimum_moves_to_equal_array_elements/readme.md new file mode 100644 index 00000000..cf7edfff --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0453_minimum_moves_to_equal_array_elements/readme.md @@ -0,0 +1,48 @@ +[![](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) + +## 453\. Minimum Moves to Equal Array Elements + +Medium + +Given an integer array `nums` of size `n`, return _the minimum number of moves required to make all array elements equal_. + +In one move, you can increment `n - 1` elements of the array by `1`. + +**Example 1:** + +**Input:** nums = [1,2,3] + +**Output:** 3 + +**Explanation:** Only three moves are needed (remember each move increments two elements): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] + +**Example 2:** + +**Input:** nums = [1,1,1] + +**Output:** 0 + +**Constraints:** + +* `n == nums.length` +* 1 <= nums.length <= 105 +* -109 <= nums[i] <= 109 +* The answer is guaranteed to fit in a **32-bit** integer. + +## Solution + +```kotlin +class Solution { + fun minMoves(nums: IntArray): Int { + var min = nums[0] + var sum = nums[0] + // determining the total sum and smallest element of the input array + for (i in 1..nums.size - 1) { + sum += nums[i] + min = Math.min(min, nums[i]) + } + return sum - min * nums.size + } +} +``` \ No newline at end of file