From f468accc22642233555e0236945474386300b0e7 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 30 Jan 2023 06:53:56 +0200 Subject: [PATCH] Added tasks 526-587 --- README.md | 53 ++++++++ .../s0526_beautiful_arrangement/readme.md | 70 +++++++++++ .../s0528_random_pick_with_weight/readme.md | 91 ++++++++++++++ .../g0501_0600/s0529_minesweeper/readme.md | 115 ++++++++++++++++++ .../readme.md | 63 ++++++++++ .../s0532_k_diff_pairs_in_an_array/readme.md | 77 ++++++++++++ .../s0535_encode_and_decode_tinyurl/readme.md | 65 ++++++++++ .../readme.md | 54 ++++++++ .../readme.md | 75 ++++++++++++ .../s0539_minimum_time_difference/readme.md | 92 ++++++++++++++ .../readme.md | 53 ++++++++ .../s0541_reverse_string_ii/readme.md | 66 ++++++++++ .../g0501_0600/s0542_01_matrix/readme.md | 75 ++++++++++++ .../g0501_0600/s0546_remove_boxes/readme.md | 90 ++++++++++++++ .../s0547_number_of_provinces/readme.md | 79 ++++++++++++ .../readme.md | 71 +++++++++++ .../readme.md | 103 ++++++++++++++++ .../s0553_optimal_division/readme.md | 81 ++++++++++++ .../g0501_0600/s0554_brick_wall/readme.md | 59 +++++++++ .../s0556_next_greater_element_iii/readme.md | 98 +++++++++++++++ .../readme.md | 62 ++++++++++ .../readme.md | 115 ++++++++++++++++++ .../readme.md | 73 +++++++++++ .../s0561_array_partition_i/readme.md | 50 ++++++++ .../s0563_binary_tree_tilt/readme.md | 91 ++++++++++++++ .../readme.md | 86 +++++++++++++ .../g0501_0600/s0565_array_nesting/readme.md | 63 ++++++++++ .../s0566_reshape_the_matrix/readme.md | 65 ++++++++++ .../s0567_permutation_in_string/readme.md | 71 +++++++++++ .../s0572_subtree_of_another_tree/readme.md | 77 ++++++++++++ .../s0575_distribute_candies/readme.md | 64 ++++++++++ .../s0576_out_of_boundary_paths/readme.md | 85 +++++++++++++ .../readme.md | 63 ++++++++++ .../readme.md | 50 ++++++++ .../s0584_find_customer_referee/readme.md | 60 +++++++++ .../readme.md | 62 ++++++++++ .../s0587_erect_the_fence/readme.md | 108 ++++++++++++++++ 37 files changed, 2775 insertions(+) create mode 100644 src/main/kotlin/g0501_0600/s0526_beautiful_arrangement/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0528_random_pick_with_weight/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0529_minesweeper/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0530_minimum_absolute_difference_in_bst/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0532_k_diff_pairs_in_an_array/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0535_encode_and_decode_tinyurl/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0537_complex_number_multiplication/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0538_convert_bst_to_greater_tree/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0539_minimum_time_difference/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0540_single_element_in_a_sorted_array/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0541_reverse_string_ii/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0542_01_matrix/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0546_remove_boxes/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0547_number_of_provinces/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0551_student_attendance_record_i/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0552_student_attendance_record_ii/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0553_optimal_division/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0554_brick_wall/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0556_next_greater_element_iii/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0557_reverse_words_in_a_string_iii/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0558_logical_or_of_two_binary_grids_represented_as_quad_trees/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0559_maximum_depth_of_n_ary_tree/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0561_array_partition_i/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0563_binary_tree_tilt/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0564_find_the_closest_palindrome/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0565_array_nesting/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0566_reshape_the_matrix/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0567_permutation_in_string/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0572_subtree_of_another_tree/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0575_distribute_candies/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0576_out_of_boundary_paths/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0581_shortest_unsorted_continuous_subarray/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0583_delete_operation_for_two_strings/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0584_find_customer_referee/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0586_customer_placing_the_largest_number_of_orders/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0587_erect_the_fence/readme.md diff --git a/README.md b/README.md index 84d8f81f..9bf7ce19 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ | | | | | | |-|-|-|-|-|- +| 0566 |[Reshape the Matrix](src/main/kotlin/g0501_0600/s0566_reshape_the_matrix)| Easy | Array, Matrix, Simulation | 239 | 99.05 #### Day 8 String @@ -154,6 +155,7 @@ | | | | | | |-|-|-|-|-|- | 0503 |[Next Greater Element II](src/main/kotlin/g0501_0600/s0503_next_greater_element_ii)| Medium | Array, Stack, Monotonic_Stack | 331 | 92.68 +| 0556 |[Next Greater Element III](src/main/kotlin/g0501_0600/s0556_next_greater_element_iii)| Medium | String, Math, Two_Pointers | 137 | 80.00 #### Day 11 @@ -245,6 +247,7 @@ | | | | | | |-|-|-|-|-|- +| 0542 |[01 Matrix](src/main/kotlin/g0501_0600/s0542_01_matrix)| Medium | Array, Dynamic_Programming, Breadth_First_Search, Matrix | 441 | 94.06 #### Day 6 Matrix Related Problems @@ -260,6 +263,7 @@ | | | | | | |-|-|-|-|-|- +| 0547 |[Number of Provinces](src/main/kotlin/g0501_0600/s0547_number_of_provinces)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 229 | 79.73 #### Day 9 Standard Traversal @@ -300,6 +304,7 @@ | | | | | | |-|-|-|-|-|- +| 0584 |[Find Customer Referee](src/main/kotlin/g0501_0600/s0584_find_customer_referee)| Easy | Database | 779 | 43.48 | 0183 |[Customers Who Never Order](src/main/kotlin/g0101_0200/s0183_customers_who_never_order)| Easy | Database | 712 | 33.67 #### Day 2 Select and Order @@ -340,6 +345,7 @@ | | | | | | |-|-|-|-|-|- +| 0586 |[Customer Placing the Largest Number of Orders](src/main/kotlin/g0501_0600/s0586_customer_placing_the_largest_number_of_orders)| Easy | LeetCode_Curated_SQL_70, Database | 768 | 44.85 | 0511 |[Game Play Analysis I](src/main/kotlin/g0501_0600/s0511_game_play_analysis_i)| Easy | LeetCode_Curated_SQL_70, Database | 790 | 45.04 #### Day 9 Control of Flow @@ -582,6 +588,7 @@ | | | | | | |-|-|-|-|-|- +| 0547 |[Number of Provinces](src/main/kotlin/g0501_0600/s0547_number_of_provinces)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 229 | 79.73 #### Day 20 Brute Force/Backtracking @@ -645,6 +652,7 @@ | 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 +| 0532 |[K-diff Pairs in an Array](src/main/kotlin/g0501_0600/s0532_k_diff_pairs_in_an_array)| Medium | Array, Hash_Table, Sorting, Binary_Search, Two_Pointers | 230 | 84.62 | 0456 |[132 Pattern](src/main/kotlin/g0401_0500/s0456_132_pattern)| Medium | Array, Binary_Search, Stack, Ordered_Set, Monotonic_Stack | 434 | 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 @@ -812,6 +820,7 @@ | | | | | | |-|-|-|-|-|- +| 0566 |[Reshape the Matrix](src/main/kotlin/g0501_0600/s0566_reshape_the_matrix)| Easy | Array, Matrix, Simulation | 239 | 99.05 | 0118 |[Pascal's Triangle](src/main/kotlin/g0101_0200/s0118_pascals_triangle)| Easy | Top_Interview_Questions, Array, Dynamic_Programming | 277 | 33.22 #### Day 5 Array @@ -1062,6 +1071,7 @@ | | | | | | |-|-|-|-|-|- | 0344 |[Reverse String](src/main/kotlin/g0301_0400/s0344_reverse_string)| Easy | Top_Interview_Questions, String, Two_Pointers, Recursion | 445 | 69.75 +| 0557 |[Reverse Words in a String III](src/main/kotlin/g0501_0600/s0557_reverse_words_in_a_string_iii)| Easy | String, Two_Pointers | 215 | 98.10 #### Day 5 Two Pointers @@ -1074,6 +1084,7 @@ | | | | | | |-|-|-|-|-|- | 0003 |[Longest Substring Without Repeating Characters](src/main/kotlin/g0001_0100/s0003_longest_substring_without_repeating_characters)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Sliding_Window | 258 | 91.09 +| 0567 |[Permutation in String](src/main/kotlin/g0501_0600/s0567_permutation_in_string)| Medium | String, Hash_Table, Two_Pointers, Sliding_Window | 169 | 100.00 #### Day 7 Breadth First Search Depth First Search @@ -1090,6 +1101,7 @@ | | | | | | |-|-|-|-|-|- +| 0542 |[01 Matrix](src/main/kotlin/g0501_0600/s0542_01_matrix)| Medium | Array, Dynamic_Programming, Breadth_First_Search, Matrix | 441 | 94.06 | 0994 |[Rotting Oranges](src/main/kotlin/g0901_1000/s0994_rotting_oranges)| Medium | Array, Breadth_First_Search, Matrix | 308 | 57.93 #### Day 10 Recursion Backtracking @@ -1170,12 +1182,14 @@ | | | | | | |-|-|-|-|-|- | 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 +| 0547 |[Number of Provinces](src/main/kotlin/g0501_0600/s0547_number_of_provinces)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 229 | 79.73 #### Day 7 Breadth First Search Depth First Search | | | | | | |-|-|-|-|-|- | 0117 |[Populating Next Right Pointers in Each Node II](src/main/kotlin/g0101_0200/s0117_populating_next_right_pointers_in_each_node_ii)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Linked_List | 199 | 94.67 +| 0572 |[Subtree of Another Tree](src/main/kotlin/g0501_0600/s0572_subtree_of_another_tree)| Easy | Depth_First_Search, Tree, Binary_Tree, Hash_Function, String_Matching | 214 | 92.39 #### Day 8 Breadth First Search Depth First Search @@ -1245,6 +1259,7 @@ | | | | | | |-|-|-|-|-|- | 1143 |[Longest Common Subsequence](src/main/kotlin/g1101_1200/s1143_longest_common_subsequence)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming | 307 | 38.36 +| 0583 |[Delete Operation for Two Strings](src/main/kotlin/g0501_0600/s0583_delete_operation_for_two_strings)| Medium | String, Dynamic_Programming | 197 | 100.00 #### Day 18 Dynamic Programming @@ -1398,6 +1413,7 @@ | | | | | | |-|-|-|-|-|- +| 0540 |[Single Element in a Sorted Array](src/main/kotlin/g0501_0600/s0540_single_element_in_a_sorted_array)| Medium | Array, Binary_Search | 274 | 86.67 #### Day 10 @@ -1423,6 +1439,7 @@ | | | | | | |-|-|-|-|-|- | 0154 |[Find Minimum in Rotated Sorted Array II](src/main/kotlin/g0101_0200/s0154_find_minimum_in_rotated_sorted_array_ii)| Hard | Array, Binary_Search | 275 | 84.00 +| 0528 |[Random Pick with Weight](src/main/kotlin/g0501_0600/s0528_random_pick_with_weight)| Medium | Math, Binary_Search, Prefix_Sum, Randomized | 393 | 91.38 #### Day 14 @@ -1613,8 +1630,44 @@ | 0763 |[Partition Labels](src/main/kotlin/g0701_0800/s0763_partition_labels)| Medium | Top_100_Liked_Questions, String, Hash_Table, Greedy, Two_Pointers, Data_Structure_II_Day_7_String | 235 | 84.75 | 0739 |[Daily Temperatures](src/main/kotlin/g0701_0800/s0739_daily_temperatures)| Medium | Top_100_Liked_Questions, Array, Stack, Monotonic_Stack, Programming_Skills_II_Day_6 | 936 | 80.54 | 0647 |[Palindromic Substrings](src/main/kotlin/g0601_0700/s0647_palindromic_substrings)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming | 266 | 67.83 +| 0587 |[Erect the Fence](src/main/kotlin/g0501_0600/s0587_erect_the_fence)| Hard | Array, Math, Geometry | 470 | 100.00 +| 0586 |[Customer Placing the Largest Number of Orders](src/main/kotlin/g0501_0600/s0586_customer_placing_the_largest_number_of_orders)| Easy | LeetCode_Curated_SQL_70, Database, SQL_I_Day_8_Function | 768 | 44.85 +| 0584 |[Find Customer Referee](src/main/kotlin/g0501_0600/s0584_find_customer_referee)| Easy | Database, SQL_I_Day_1_Select | 779 | 43.48 +| 0583 |[Delete Operation for Two Strings](src/main/kotlin/g0501_0600/s0583_delete_operation_for_two_strings)| Medium | String, Dynamic_Programming, Algorithm_II_Day_17_Dynamic_Programming | 197 | 100.00 +| 0581 |[Shortest Unsorted Continuous Subarray](src/main/kotlin/g0501_0600/s0581_shortest_unsorted_continuous_subarray)| Medium | Array, Sorting, Greedy, Two_Pointers, Stack, Monotonic_Stack | 246 | 100.00 +| 0576 |[Out of Boundary Paths](src/main/kotlin/g0501_0600/s0576_out_of_boundary_paths)| Medium | Dynamic_Programming | 153 | 100.00 +| 0575 |[Distribute Candies](src/main/kotlin/g0501_0600/s0575_distribute_candies)| Easy | Array, Hash_Table | 538 | 76.92 +| 0572 |[Subtree of Another Tree](src/main/kotlin/g0501_0600/s0572_subtree_of_another_tree)| Easy | Depth_First_Search, Tree, Binary_Tree, Hash_Function, String_Matching, Algorithm_II_Day_7_Breadth_First_Search_Depth_First_Search | 214 | 92.39 +| 0567 |[Permutation in String](src/main/kotlin/g0501_0600/s0567_permutation_in_string)| Medium | String, Hash_Table, Two_Pointers, Sliding_Window, Algorithm_I_Day_6_Sliding_Window | 169 | 100.00 +| 0566 |[Reshape the Matrix](src/main/kotlin/g0501_0600/s0566_reshape_the_matrix)| Easy | Array, Matrix, Simulation, Data_Structure_I_Day_4_Array, Programming_Skills_I_Day_7_Array | 239 | 99.05 +| 0565 |[Array Nesting](src/main/kotlin/g0501_0600/s0565_array_nesting)| Medium | Array, Depth_First_Search | 553 | 100.00 +| 0564 |[Find the Closest Palindrome](src/main/kotlin/g0501_0600/s0564_find_the_closest_palindrome)| Hard | String, Math | 179 | 100.00 +| 0563 |[Binary Tree Tilt](src/main/kotlin/g0501_0600/s0563_binary_tree_tilt)| Easy | Depth_First_Search, Tree, Binary_Tree | 197 | 100.00 +| 0561 |[Array Partition](src/main/kotlin/g0501_0600/s0561_array_partition_i)| Easy | Array, Sorting, Greedy, Counting_Sort | 337 | 90.48 | 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 +| 0559 |[Maximum Depth of N-ary Tree](src/main/kotlin/g0501_0600/s0559_maximum_depth_of_n_ary_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree | 196 | 100.00 +| 0558 |[Logical OR of Two Binary Grids Represented as Quad-Trees](src/main/kotlin/g0501_0600/s0558_logical_or_of_two_binary_grids_represented_as_quad_trees)| Medium | Tree, Divide_and_Conquer | 268 | 100.00 +| 0557 |[Reverse Words in a String III](src/main/kotlin/g0501_0600/s0557_reverse_words_in_a_string_iii)| Easy | String, Two_Pointers, Algorithm_I_Day_4_Two_Pointers | 215 | 98.10 +| 0556 |[Next Greater Element III](src/main/kotlin/g0501_0600/s0556_next_greater_element_iii)| Medium | String, Math, Two_Pointers, Programming_Skills_II_Day_10 | 137 | 80.00 +| 0554 |[Brick Wall](src/main/kotlin/g0501_0600/s0554_brick_wall)| Medium | Array, Hash_Table | 307 | 100.00 +| 0553 |[Optimal Division](src/main/kotlin/g0501_0600/s0553_optimal_division)| Medium | Array, Dynamic_Programming, Math | 154 | 100.00 +| 0552 |[Student Attendance Record II](src/main/kotlin/g0501_0600/s0552_student_attendance_record_ii)| Hard | Dynamic_Programming | 151 | 100.00 +| 0551 |[Student Attendance Record I](src/main/kotlin/g0501_0600/s0551_student_attendance_record_i)| Easy | String | 151 | 95.00 +| 0547 |[Number of Provinces](src/main/kotlin/g0501_0600/s0547_number_of_provinces)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find, Algorithm_II_Day_6_Breadth_First_Search_Depth_First_Search, Graph_Theory_I_Day_8_Standard_Traversal, Level_2_Day_19_Union_Find | 229 | 79.73 +| 0546 |[Remove Boxes](src/main/kotlin/g0501_0600/s0546_remove_boxes)| Hard | Array, Dynamic_Programming, Memoization | 283 | 100.00 | 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 +| 0542 |[01 Matrix](src/main/kotlin/g0501_0600/s0542_01_matrix)| Medium | Array, Dynamic_Programming, Breadth_First_Search, Matrix, Algorithm_I_Day_9_Breadth_First_Search_Depth_First_Search, Graph_Theory_I_Day_5_Matrix_Related_Problems | 441 | 94.06 +| 0541 |[Reverse String II](src/main/kotlin/g0501_0600/s0541_reverse_string_ii)| Easy | String, Two_Pointers | 200 | 83.33 +| 0540 |[Single Element in a Sorted Array](src/main/kotlin/g0501_0600/s0540_single_element_in_a_sorted_array)| Medium | Array, Binary_Search, Binary_Search_II_Day_9 | 274 | 86.67 +| 0539 |[Minimum Time Difference](src/main/kotlin/g0501_0600/s0539_minimum_time_difference)| Medium | Array, String, Math, Sorting | 183 | 100.00 +| 0538 |[Convert BST to Greater Tree](src/main/kotlin/g0501_0600/s0538_convert_bst_to_greater_tree)| Medium | Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 252 | 77.78 +| 0537 |[Complex Number Multiplication](src/main/kotlin/g0501_0600/s0537_complex_number_multiplication)| Medium | String, Math, Simulation | 171 | 75.00 +| 0535 |[Encode and Decode TinyURL](src/main/kotlin/g0501_0600/s0535_encode_and_decode_tinyurl)| Medium | String, Hash_Table, Design, Hash_Function | 183 | 81.25 +| 0532 |[K-diff Pairs in an Array](src/main/kotlin/g0501_0600/s0532_k_diff_pairs_in_an_array)| Medium | Array, Hash_Table, Sorting, Binary_Search, Two_Pointers, Udemy_Arrays | 230 | 84.62 +| 0530 |[Minimum Absolute Difference in BST](src/main/kotlin/g0501_0600/s0530_minimum_absolute_difference_in_bst)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 209 | 86.96 +| 0529 |[Minesweeper](src/main/kotlin/g0501_0600/s0529_minesweeper)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix | 243 | 87.50 +| 0528 |[Random Pick with Weight](src/main/kotlin/g0501_0600/s0528_random_pick_with_weight)| Medium | Math, Binary_Search, Prefix_Sum, Randomized, Binary_Search_II_Day_13 | 393 | 91.38 +| 0526 |[Beautiful Arrangement](src/main/kotlin/g0501_0600/s0526_beautiful_arrangement)| Medium | Array, Dynamic_Programming, Bit_Manipulation, Backtracking, Bitmask | 107 | 100.00 | 0525 |[Contiguous Array](src/main/kotlin/g0501_0600/s0525_contiguous_array)| Medium | Array, Hash_Table, Prefix_Sum | 471 | 100.00 | 0524 |[Longest Word in Dictionary through Deleting](src/main/kotlin/g0501_0600/s0524_longest_word_in_dictionary_through_deleting)| Medium | Array, String, Sorting, Two_Pointers | 307 | 100.00 | 0523 |[Continuous Subarray Sum](src/main/kotlin/g0501_0600/s0523_continuous_subarray_sum)| Medium | Array, Hash_Table, Math, Prefix_Sum | 682 | 95.45 diff --git a/src/main/kotlin/g0501_0600/s0526_beautiful_arrangement/readme.md b/src/main/kotlin/g0501_0600/s0526_beautiful_arrangement/readme.md new file mode 100644 index 00000000..4f37e63f --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0526_beautiful_arrangement/readme.md @@ -0,0 +1,70 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 526\. Beautiful Arrangement + +Medium + +Suppose you have `n` integers labeled `1` through `n`. A permutation of those `n` integers `perm` (**1-indexed**) is considered a **beautiful arrangement** if for every `i` (`1 <= i <= n`), **either** of the following is true: + +* `perm[i]` is divisible by `i`. +* `i` is divisible by `perm[i]`. + +Given an integer `n`, return _the **number** of the **beautiful arrangements** that you can construct_. + +**Example 1:** + +**Input:** n = 2 + +**Output:** 2 + +**Explanation:** + +The first beautiful arrangement is [1,2]: + +- perm[1] = 1 is divisible by i = 1 + +- perm[2] = 2 is divisible by i = 2 + +The second beautiful arrangement is [2,1]: + +- perm[1] = 2 is divisible by i = 1 + +- i = 2 is divisible by perm[2] = 1 + +**Example 2:** + +**Input:** n = 1 + +**Output:** 1 + +**Constraints:** + +* `1 <= n <= 15` + +## Solution + +```kotlin +class Solution { + fun countArrangement(n: Int): Int { + return backtrack(n, n, arrayOfNulls(1 shl n + 1), 0) + } + + private fun backtrack(n: Int, index: Int, cache: Array, cacheindex: Int): Int { + if (index == 0) { + return 1 + } + var result = 0 + if (cache[cacheindex] != null) { + return cache[cacheindex]!! + } + for (i in n downTo 1) { + if (cacheindex and (1 shl i) == 0 && (i % index == 0 || index % i == 0)) { + result += backtrack(n, index - 1, cache, cacheindex or (1 shl i)) + } + } + cache[cacheindex] = result + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0528_random_pick_with_weight/readme.md b/src/main/kotlin/g0501_0600/s0528_random_pick_with_weight/readme.md new file mode 100644 index 00000000..7c3e4d8d --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0528_random_pick_with_weight/readme.md @@ -0,0 +1,91 @@ +[![](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) + +## 528\. Random Pick with Weight + +Medium + +You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the ith index. + +You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`. + +* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`). + +**Example 1:** + +**Input** ["Solution","pickIndex"] [[[1]],[]] + +**Output:** [null,0] + +**Explanation:** + + Solution solution = new Solution([1]); + solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. + +**Example 2:** + +**Input** + + ["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"] + [[[1,3]],[],[],[],[],[]] + +**Output:** [null,1,1,1,1,0] + +**Explanation:** + + Solution solution = new Solution([1, 3]); + solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. + solution.pickIndex(); // return 1 + solution.pickIndex(); // return 1 + solution.pickIndex(); // return 1 + solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. + + Since this is a randomization problem, multiple answers are allowed. + All of the following outputs can be considered correct: + [null,1,1,1,1,0] + [null,1,1,1,1,1] + [null,1,1,1,0,0] + [null,1,1,1,0,1] + [null,1,0,1,0,0] + ...... + and so on. + +**Constraints:** + +* 1 <= w.length <= 104 +* 1 <= w[i] <= 105 +* `pickIndex` will be called at most 104 times. + +## Solution + +```kotlin +import java.util.Random +import java.util.TreeMap + +@Suppress("kotlin:S2245") +class Solution(val w: IntArray) { + + var x: IntArray = IntArray(w.size) { 0 } + val rand = Random() + val tree = TreeMap() + var sum = 0 + + init { + for (i in w.indices) { + tree.put(sum, i) + sum += w[i] + } + } + + fun pickIndex(): Int { + val r = rand.nextInt(sum) + return tree.floorEntry(r).value!! + } +} + +/* + * Your Solution object will be instantiated and called as such: + * var obj = Solution(w) + * var param_1 = obj.pickIndex() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0529_minesweeper/readme.md b/src/main/kotlin/g0501_0600/s0529_minesweeper/readme.md new file mode 100644 index 00000000..5ffdcbb8 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0529_minesweeper/readme.md @@ -0,0 +1,115 @@ +[![](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) + +## 529\. Minesweeper + +Medium + +Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))! + +You are given an `m x n` char matrix `board` representing the game board where: + +* `'M'` represents an unrevealed mine, +* `'E'` represents an unrevealed empty square, +* `'B'` represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals), +* digit (`'1'` to `'8'`) represents how many mines are adjacent to this revealed square, and +* `'X'` represents a revealed mine. + +You are also given an integer array `click` where click = [clickr, clickc] represents the next click position among all the unrevealed squares (`'M'` or `'E'`). + +Return _the board after revealing this position according to the following rules_: + +1. If a mine `'M'` is revealed, then the game is over. You should change it to `'X'`. +2. If an empty square `'E'` with no adjacent mines is revealed, then change it to a revealed blank `'B'` and all of its adjacent unrevealed squares should be revealed recursively. +3. If an empty square `'E'` with at least one adjacent mine is revealed, then change it to a digit (`'1'` to `'8'`) representing the number of adjacent mines. +4. Return the board when no more squares will be revealed. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2018/10/12/minesweeper_example_1.png) + +**Input:** board = \[\["E","E","E","E","E"],["E","E","M","E","E"],["E","E","E","E","E"],["E","E","E","E","E"]], click = [3,0] + +**Output:** [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2018/10/12/minesweeper_example_2.png) + +**Input:** board = \[\["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]], click = [1,2] + +**Output:** [["B","1","E","1","B"],["B","1","X","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]] + +**Constraints:** + +* `m == board.length` +* `n == board[i].length` +* `1 <= m, n <= 50` +* `board[i][j]` is either `'M'`, `'E'`, `'B'`, or a digit from `'1'` to `'8'`. +* `click.length == 2` +* 0 <= clickr < m +* 0 <= clickc < n +* board[clickr][clickc] is either `'M'` or `'E'`. + +## Solution + +```kotlin +class Solution { + private var row = 0 + private var col = 0 + private fun dfs(board: Array, row: Int, col: Int) { + if (row < 0 || row >= this.row || col < 0 || col >= this.col) { + return + } + if (board[row][col] == 'E') { + val numOfMine = bfs(board, row, col) + if (numOfMine != 0) { + board[row][col] = (numOfMine + '0'.code).toChar() + return + } else { + board[row][col] = 'B' + } + for (i in DIRECTION) { + dfs(board, row + i[0], col + i[1]) + } + } + } + + private fun bfs(board: Array, row: Int, col: Int): Int { + var numOfMine = 0 + for (i in DIRECTION) { + val newRow = row + i[0] + val newCol = col + i[1] + if (newRow >= 0 && newRow < this.row && newCol >= 0 && newCol < this.col && board[newRow][newCol] == 'M') { + numOfMine++ + } + } + return numOfMine + } + + fun updateBoard(board: Array, c: IntArray): Array { + if (board[c[0]][c[1]] == 'M') { + board[c[0]][c[1]] = 'X' + return board + } else { + row = board.size + col = board[0].size + dfs(board, c[0], c[1]) + } + return board + } + + companion object { + private val DIRECTION = arrayOf( + intArrayOf(1, 0), + intArrayOf(-1, 0), + intArrayOf(0, 1), + intArrayOf(0, -1), + intArrayOf(-1, -1), + intArrayOf(-1, 1), + intArrayOf(1, -1), + intArrayOf(1, 1) + ) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0530_minimum_absolute_difference_in_bst/readme.md b/src/main/kotlin/g0501_0600/s0530_minimum_absolute_difference_in_bst/readme.md new file mode 100644 index 00000000..b8c23f6b --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0530_minimum_absolute_difference_in_bst/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) + +## 530\. Minimum Absolute Difference in BST + +Easy + +Given the `root` of a Binary Search Tree (BST), return _the minimum absolute difference between the values of any two different nodes in the tree_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/05/bst1.jpg) + +**Input:** root = [4,2,6,1,3] + +**Output:** 1 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/02/05/bst2.jpg) + +**Input:** root = [1,0,48,null,null,12,49] + +**Output:** 1 + +**Constraints:** + +* The number of nodes in the tree is in the range [2, 104]. +* 0 <= Node.val <= 105 + +**Note:** This question is the same as 783: [https://leetcode.com/problems/minimum-distance-between-bst-nodes/](https://leetcode.com/problems/minimum-distance-between-bst-nodes/) + +## 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 { + private var ans = Int.MAX_VALUE + private var prev = Int.MAX_VALUE + fun getMinimumDifference(root: TreeNode?): Int { + if (root == null) { + return ans + } + getMinimumDifference(root.left) + ans = Math.min(ans, Math.abs(root.`val` - prev)) + prev = root.`val` + getMinimumDifference(root.right) + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0532_k_diff_pairs_in_an_array/readme.md b/src/main/kotlin/g0501_0600/s0532_k_diff_pairs_in_an_array/readme.md new file mode 100644 index 00000000..adc05045 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0532_k_diff_pairs_in_an_array/readme.md @@ -0,0 +1,77 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 532\. K-diff Pairs in an Array + +Medium + +Given an array of integers `nums` and an integer `k`, return _the number of **unique** k-diff pairs in the array_. + +A **k-diff** pair is an integer pair `(nums[i], nums[j])`, where the following are true: + +* `0 <= i, j < nums.length` +* `i != j` +* `nums[i] - nums[j] == k` + +**Notice** that `|val|` denotes the absolute value of `val`. + +**Example 1:** + +**Input:** nums = [3,1,4,1,5], k = 2 + +**Output:** 2 + +**Explanation:** There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of **unique** pairs. + +**Example 2:** + +**Input:** nums = [1,2,3,4,5], k = 1 + +**Output:** 4 + +**Explanation:** There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). + +**Example 3:** + +**Input:** nums = [1,3,1,5,4], k = 0 + +**Output:** 1 + +**Explanation:** There is one 0-diff pair in the array, (1, 1). + +**Constraints:** + +* 1 <= nums.length <= 104 +* -107 <= nums[i] <= 107 +* 0 <= k <= 107 + +## Solution + +```kotlin +class Solution { + fun findPairs(nums: IntArray, k: Int): Int { + var res = 0 + val set: HashSet = HashSet() + val twice: HashSet = HashSet() + for (n in nums) { + if (set.contains(n)) { + if (k == 0 && !twice.contains(n)) { + res++ + twice.add(n) + } else { + continue + } + } else { + if (set.contains(n - k)) { + res++ + } + if (set.contains(n + k)) { + res++ + } + } + set.add(n) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0535_encode_and_decode_tinyurl/readme.md b/src/main/kotlin/g0501_0600/s0535_encode_and_decode_tinyurl/readme.md new file mode 100644 index 00000000..865064e8 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0535_encode_and_decode_tinyurl/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) + +## 535\. Encode and Decode TinyURL + +Medium + +> Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/). + +TinyURL is a URL shortening service where you enter a URL such as `https://leetcode.com/problems/design-tinyurl` and it returns a short URL such as `http://tinyurl.com/4e9iAk`. Design a class to encode a URL and decode a tiny URL. + +There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. + +Implement the `Solution` class: + +* `Solution()` Initializes the object of the system. +* `String encode(String longUrl)` Returns a tiny URL for the given `longUrl`. +* `String decode(String shortUrl)` Returns the original long URL for the given `shortUrl`. It is guaranteed that the given `shortUrl` was encoded by the same object. + +**Example 1:** + +**Input:** url = "https://leetcode.com/problems/design-tinyurl" + +**Output:** "https://leetcode.com/problems/design-tinyurl" + +**Explanation:** + + Solution obj = new Solution(); + string tiny = obj.encode(url); // returns the encoded tiny url. + string ans = obj.decode(tiny); // returns the original url after deconding it. + +**Constraints:** + +* 1 <= url.length <= 104 +* `url` is guranteed to be a valid URL. + +## Solution + +```kotlin +class Codec { + private val map: MutableMap = HashMap() + private var n = 0 + + // Encodes a URL to a shortened URL. + fun encode(longUrl: String): String { + n++ + var ans = "http://tinyurl.com/" + ans += n.toString() + map[ans] = longUrl + return ans + } + + // Decodes a shortened URL to its original URL. + fun decode(shortUrl: String): String? { + return map[shortUrl] + } +} + +/* + * Your Codec object will be instantiated and called as such: + * var obj = Codec() + * var url = obj.encode(longUrl) + * var ans = obj.decode(url) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0537_complex_number_multiplication/readme.md b/src/main/kotlin/g0501_0600/s0537_complex_number_multiplication/readme.md new file mode 100644 index 00000000..22532354 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0537_complex_number_multiplication/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) + +## 537\. Complex Number Multiplication + +Medium + +A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form "**real**+**imaginary**i" where: + +* `real` is the real part and is an integer in the range `[-100, 100]`. +* `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`. +* i2 == -1. + +Given two complex numbers `num1` and `num2` as strings, return _a string of the complex number that represents their multiplications_. + +**Example 1:** + +**Input:** num1 = "1+1i", num2 = "1+1i" + +**Output:** "0+2i" + +**Explanation:** (1 + i) \* (1 + i) = 1 + i2 + 2 \* i = 2i, and you need convert it to the form of 0+2i. + +**Example 2:** + +**Input:** num1 = "1+-1i", num2 = "1+-1i" + +**Output:** "0+-2i" + +**Explanation:** (1 - i) \* (1 - i) = 1 + i2 - 2 \* i = -2i, and you need convert it to the form of 0+-2i. + +**Constraints:** + +* `num1` and `num2` are valid complex numbers. + +## Solution + +```kotlin +class Solution { + fun complexNumberMultiply(num1: String, num2: String): String { + val countReal: Int + val countImagine: Int + val arr1 = IntArray(2) + val arr2 = IntArray(2) + arr1[0] = num1.substring(0, num1.indexOf("+")).toInt() + arr1[1] = num1.substring(num1.indexOf("+") + 1, num1.length - 1).toInt() + arr2[0] = num2.substring(0, num2.indexOf("+")).toInt() + arr2[1] = num2.substring(num2.indexOf("+") + 1, num2.length - 1).toInt() + countReal = arr1[0] * arr2[0] - arr1[1] * arr2[1] + countImagine = arr1[0] * arr2[1] + arr1[1] * arr2[0] + return countReal.toString() + "+" + countImagine + "i" + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0538_convert_bst_to_greater_tree/readme.md b/src/main/kotlin/g0501_0600/s0538_convert_bst_to_greater_tree/readme.md new file mode 100644 index 00000000..c9875897 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0538_convert_bst_to_greater_tree/readme.md @@ -0,0 +1,75 @@ +[![](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) + +## 538\. Convert BST to Greater Tree + +Medium + +Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. + +As a reminder, a _binary search tree_ is a tree that satisfies these constraints: + +* The left subtree of a node contains only nodes with keys **less than** the node's key. +* The right subtree of a node contains only nodes with keys **greater than** the node's key. +* Both the left and right subtrees must also be binary search trees. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/05/02/tree.png) + +**Input:** root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] + +**Output:** [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] + +**Example 2:** + +**Input:** root = [0,null,1] + +**Output:** [1,null,1] + +**Constraints:** + +* The number of nodes in the tree is in the range [0, 104]. +* -104 <= Node.val <= 104 +* All the values in the tree are **unique**. +* `root` is guaranteed to be a valid binary search tree. + +**Note:** This question is the same as 1038: [https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/](https://leetcode.com/problems/binary-search-tree-to-greater-sum-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 convertBST(root: TreeNode?): TreeNode? { + if (root != null) { + postOrder(root, 0) + } + return root + } + + private fun postOrder(node: TreeNode, `val`: Int): Int { + var newVal = 0 + if (node.right != null) { + newVal += postOrder(node.right!!, `val`) + } + newVal += if (newVal == 0) `val` + node.`val` else node.`val` + node.`val` = newVal + if (node.left != null) { + newVal = postOrder(node.left!!, newVal) + } + return newVal + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0539_minimum_time_difference/readme.md b/src/main/kotlin/g0501_0600/s0539_minimum_time_difference/readme.md new file mode 100644 index 00000000..b4cb2bfb --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0539_minimum_time_difference/readme.md @@ -0,0 +1,92 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 539\. Minimum Time Difference + +Medium + +Given a list of 24-hour clock time points in **"HH:MM"** format, return _the minimum **minutes** difference between any two time-points in the list_. + +**Example 1:** + +**Input:** timePoints = ["23:59","00:00"] + +**Output:** 1 + +**Example 2:** + +**Input:** timePoints = ["00:00","23:59","00:00"] + +**Output:** 0 + +**Constraints:** + +* 2 <= timePoints.length <= 2 * 104 +* `timePoints[i]` is in the format **"HH:MM"**. + +## Solution + +```kotlin +class Solution { + fun findMinDifference(timePoints: List): Int { + return if (timePoints.size < 300) { + smallInputSize(timePoints) + } else largeInputSize(timePoints) + } + + private fun largeInputSize(timePoints: List): Int { + val times = BooleanArray(60 * 24) + for (time in timePoints) { + val hours = time.substring(0, 2).toInt() + val minutes = time.substring(3, 5).toInt() + if (times[hours * 60 + minutes]) { + return 0 + } + times[hours * 60 + minutes] = true + } + var prev = -1 + var min = 60 * 24 + for (i in 0 until times.size + times.size / 2) { + if (i < times.size) { + if (times[i] && prev == -1) { + prev = i + } else if (times[i]) { + min = Math.min(min, i - prev) + prev = i + } + } else { + if (times[i - times.size] && prev == -1) { + prev = i + } else if (times[i - times.size]) { + min = Math.min(min, i - prev) + prev = i + } + } + } + return min + } + + private fun smallInputSize(timePoints: List): Int { + val times = IntArray(timePoints.size) + var j = 0 + for (time in timePoints) { + val hours = time.substring(0, 2).toInt() + val minutes = time.substring(3, 5).toInt() + times[j++] = hours * 60 + minutes + } + times.sort() + var min = 60 * 24 + for (i in 1..times.size) { + min = if (i == times.size) { + Math.min(min, times[0] + 60 * 24 - times[times.size - 1]) + } else { + Math.min(min, times[i] - times[i - 1]) + } + if (min == 0) { + return 0 + } + } + return min + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0540_single_element_in_a_sorted_array/readme.md b/src/main/kotlin/g0501_0600/s0540_single_element_in_a_sorted_array/readme.md new file mode 100644 index 00000000..81b8f47f --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0540_single_element_in_a_sorted_array/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) + +## 540\. Single Element in a Sorted Array + +Medium + +You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. + +Return _the single element that appears only once_. + +Your solution must run in `O(log n)` time and `O(1)` space. + +**Example 1:** + +**Input:** nums = [1,1,2,3,3,4,4,8,8] + +**Output:** 2 + +**Example 2:** + +**Input:** nums = [3,3,7,7,10,11,11] + +**Output:** 10 + +**Constraints:** + +* 1 <= nums.length <= 105 +* 0 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun singleNonDuplicate(nums: IntArray): Int { + var start = 0 + var end = nums.size - 1 + while (start < end) { + val mid = start + (end - start) / 2 + if (mid + 1 < nums.size && nums[mid] != nums[mid + 1] && mid - 1 >= 0 && nums[mid] != nums[mid - 1]) { + return nums[mid] + } else if (mid + 1 < nums.size && nums[mid] == nums[mid + 1] && mid % 2 == 0) { + start = mid + 1 + } else if (mid - 1 >= 0 && nums[mid] == nums[mid - 1] && mid % 2 == 1) { + start = mid + 1 + } else { + end = mid - 1 + } + } + return nums[start] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0541_reverse_string_ii/readme.md b/src/main/kotlin/g0501_0600/s0541_reverse_string_ii/readme.md new file mode 100644 index 00000000..956506de --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0541_reverse_string_ii/readme.md @@ -0,0 +1,66 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 541\. Reverse String II + +Easy + +Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. + +If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. + +**Example 1:** + +**Input:** s = "abcdefg", k = 2 + +**Output:** "bacdfeg" + +**Example 2:** + +**Input:** s = "abcd", k = 2 + +**Output:** "bacd" + +**Constraints:** + +* 1 <= s.length <= 104 +* `s` consists of only lowercase English letters. +* 1 <= k <= 104 + +## Solution + +```kotlin +class Solution { + fun reverseStr(s: String, k: Int): String { + val res = StringBuilder() + var p1 = 0 + var p2 = 2 * k - 1 + if (s.length < k) { + res.append(reverse(s)) + return res.toString() + } + while (p1 < s.length) { + if (s.length < p1 + k) { + res.append(reverse(s.substring(p1))) + } else { + res.append(reverse(s.substring(p1, p1 + k))) + if (s.length < p2 + 1) { + res.append(s.substring(p1 + k)) + } else { + res.append(s, p1 + k, p2 + 1) + } + } + p1 = p1 + 2 * k + p2 = p2 + 2 * k + } + return res.toString() + } + + private fun reverse(s: String): String { + val sb = StringBuilder() + sb.append(s) + sb.reverse() + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0542_01_matrix/readme.md b/src/main/kotlin/g0501_0600/s0542_01_matrix/readme.md new file mode 100644 index 00000000..949adf4f --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0542_01_matrix/readme.md @@ -0,0 +1,75 @@ +[![](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) + +## 542\. 01 Matrix + +Medium + +Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_. + +The distance between two adjacent cells is `1`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/24/01-1-grid.jpg) + +**Input:** mat = \[\[0,0,0],[0,1,0],[0,0,0]] + +**Output:** [[0,0,0],[0,1,0],[0,0,0]] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/04/24/01-2-grid.jpg) + +**Input:** mat = \[\[0,0,0],[0,1,0],[1,1,1]] + +**Output:** [[0,0,0],[0,1,0],[1,2,1]] + +**Constraints:** + +* `m == mat.length` +* `n == mat[i].length` +* 1 <= m, n <= 104 +* 1 <= m * n <= 104 +* `mat[i][j]` is either `0` or `1`. +* There is at least one `0` in `mat`. + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun updateMatrix(mat: Array): Array { + val dist = Array(mat.size) { IntArray(mat[0].size) } + for (i in mat.indices) { + Arrays.fill(dist[i], Int.MAX_VALUE - 100000) + } + for (i in mat.indices) { + for (j in mat[0].indices) { + if (mat[i][j] == 0) { + dist[i][j] = 0 + } else { + if (i > 0) { + dist[i][j] = Math.min(dist[i][j], dist[i - 1][j] + 1) + } + if (j > 0) { + dist[i][j] = Math.min(dist[i][j], dist[i][j - 1] + 1) + } + } + } + } + for (i in mat.indices.reversed()) { + for (j in mat[0].indices.reversed()) { + if (i < mat.size - 1) { + dist[i][j] = Math.min(dist[i][j], dist[i + 1][j] + 1) + } + if (j < mat[0].size - 1) { + dist[i][j] = Math.min(dist[i][j], dist[i][j + 1] + 1) + } + } + } + return dist + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0546_remove_boxes/readme.md b/src/main/kotlin/g0501_0600/s0546_remove_boxes/readme.md new file mode 100644 index 00000000..2dd9945a --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0546_remove_boxes/readme.md @@ -0,0 +1,90 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 546\. Remove Boxes + +Hard + +You are given several `boxes` with different colors represented by different positive numbers. + +You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points. + +Return _the maximum points you can get_. + +**Example 1:** + +**Input:** boxes = [1,3,2,2,2,3,4,3,1] + +**Output:** 23 + +**Explanation:** [1, 3, 2, 2, 2, 3, 4, 3, 1] ----> [1, 3, 3, 4, 3, 1] (3\*3=9 points) ----> [1, 3, 3, 3, 1] (1\*1=1 points) ----> [1, 1] (3\*3=9 points) ----> [] (2\*2=4 points) + +**Example 2:** + +**Input:** boxes = [1,1,1] + +**Output:** 9 + +**Example 3:** + +**Input:** boxes = [1] + +**Output:** 1 + +**Constraints:** + +* `1 <= boxes.length <= 100` +* `1 <= boxes[i] <= 100` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + // dp for memoization + lateinit var dp: Array> + fun removeBoxes(boxes: IntArray): Int { + val n = boxes.size + dp = Array(n + 1) { + Array(n + 1) { + IntArray( + n + 1 + ) + } + } + return get(boxes, 0, boxes.size - 1, 0) + } + + operator fun get(boxes: IntArray, i: Int, j: Int, streak: Int): Int { + var i = i + var streak = streak + if (i > j) { + return 0 + } + + // first we traverse till the adjacent values are different + while (i + 1 <= j && boxes[i] == boxes[i + 1]) { + i++ + streak++ + } + // memoization + if (dp[i][j][streak] > 0) { + return dp[i][j][streak] + } + // we calculate the ans here which is streak (length of similar elements) and move + // forward to the remaining block through recursion + var ans = (streak + 1) * (streak + 1) + get(boxes, i + 1, j, 0) + // also another way we can choose is to choose the inner elements first then the outer similar elements can be combined to get even + // larger value + for (k in i + 1..j) { + // we traverse from k (i has moved from 0 to just before the beginning of different elements) and keep searching for same value as + // in i. after that the middle elements (between i+1 and k-1) are sent to differnt partition and from k to j(ending) we send the updated streak + if (boxes[i] == boxes[k]) { + ans = Math.max(ans, get(boxes, i + 1, k - 1, 0) + get(boxes, k, j, streak + 1)) + } + } + // return ans here + return ans.also { dp[i][j][streak] = it } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0547_number_of_provinces/readme.md b/src/main/kotlin/g0501_0600/s0547_number_of_provinces/readme.md new file mode 100644 index 00000000..99cc3c67 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0547_number_of_provinces/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) + +## 547\. Number of Provinces + +Medium + +There are `n` cities. Some of them are connected, while some are not. If city `a` is connected directly with city `b`, and city `b` is connected directly with city `c`, then city `a` is connected indirectly with city `c`. + +A **province** is a group of directly or indirectly connected cities and no other cities outside of the group. + +You are given an `n x n` matrix `isConnected` where `isConnected[i][j] = 1` if the ith city and the jth city are directly connected, and `isConnected[i][j] = 0` otherwise. + +Return _the total number of **provinces**_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/12/24/graph1.jpg) + +**Input:** isConnected = \[\[1,1,0],[1,1,0],[0,0,1]] + +**Output:** 2 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/12/24/graph2.jpg) + +**Input:** isConnected = \[\[1,0,0],[0,1,0],[0,0,1]] + +**Output:** 3 + +**Constraints:** + +* `1 <= n <= 200` +* `n == isConnected.length` +* `n == isConnected[i].length` +* `isConnected[i][j]` is `1` or `0`. +* `isConnected[i][i] == 1` +* `isConnected[i][j] == isConnected[j][i]` + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun findCircleNum(arr: Array): Int { + val parent = IntArray(arr.size) + Arrays.fill(parent, -1) + var ans = 0 + for (i in 0 until arr.size - 1) { + for (j in i + 1 until arr[i].size) { + if (arr[i][j] == 1) { + ans += union(i, j, parent) + } + } + } + return arr.size - ans + } + + private fun union(a: Int, b: Int, arr: IntArray): Int { + val ga = find(a, arr) + val gb = find(b, arr) + if (ga != gb) { + arr[gb] = ga + return 1 + } + return 0 + } + + private fun find(a: Int, arr: IntArray): Int { + if (arr[a] == -1) { + return a + } + arr[a] = find(arr[a], arr) + return arr[a] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0551_student_attendance_record_i/readme.md b/src/main/kotlin/g0501_0600/s0551_student_attendance_record_i/readme.md new file mode 100644 index 00000000..8f3e596a --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0551_student_attendance_record_i/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 551\. Student Attendance Record I + +Easy + +You are given a string `s` representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: + +* `'A'`: Absent. +* `'L'`: Late. +* `'P'`: Present. + +The student is eligible for an attendance award if they meet **both** of the following criteria: + +* The student was absent (`'A'`) for **strictly** fewer than 2 days **total**. +* The student was **never** late (`'L'`) for 3 or more **consecutive** days. + +Return `true` _if the student is eligible for an attendance award, or_ `false` _otherwise_. + +**Example 1:** + +**Input:** s = "PPALLP" + +**Output:** true + +**Explanation:** The student has fewer than 2 absences and was never late 3 or more consecutive days. + +**Example 2:** + +**Input:** s = "PPALLL" + +**Output:** false + +**Explanation:** The student was late 3 consecutive days in the last 3 days, so is not eligible for the award. + +**Constraints:** + +* `1 <= s.length <= 1000` +* `s[i]` is either `'A'`, `'L'`, or `'P'`. + +## Solution + +```kotlin +class Solution { + fun checkRecord(s: String): Boolean { + var aCount = 0 + var i = 0 + while (i < s.length) { + if (s[i] == 'A') { + aCount++ + if (aCount > 1) { + return false + } + } else if (s[i] == 'L') { + var continuousLCount = 0 + while (i < s.length && s[i] == 'L') { + i++ + continuousLCount++ + if (continuousLCount > 2) { + return false + } + } + i-- + } + i++ + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0552_student_attendance_record_ii/readme.md b/src/main/kotlin/g0501_0600/s0552_student_attendance_record_ii/readme.md new file mode 100644 index 00000000..9a7e2d1d --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0552_student_attendance_record_ii/readme.md @@ -0,0 +1,103 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 552\. Student Attendance Record II + +Hard + +An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: + +* `'A'`: Absent. +* `'L'`: Late. +* `'P'`: Present. + +Any student is eligible for an attendance award if they meet **both** of the following criteria: + +* The student was absent (`'A'`) for **strictly** fewer than 2 days **total**. +* The student was **never** late (`'L'`) for 3 or more **consecutive** days. + +Given an integer `n`, return _the **number** of possible attendance records of length_ `n` _that make a student eligible for an attendance award. The answer may be very large, so return it **modulo**_ 109 + 7. + +**Example 1:** + +**Input:** n = 2 + +**Output:** 8 + +**Explanation:** There are 8 records with length 2 that are eligible for an award: "PP", "AP", "PA", "LP", "PL", "AL", "LA", "LL" Only "AA" is not eligible because there are 2 absences (there need to be fewer than 2). + +**Example 2:** + +**Input:** n = 1 + +**Output:** 3 + +**Example 3:** + +**Input:** n = 10101 + +**Output:** 183236316 + +**Constraints:** + +* 1 <= n <= 105 + +## Solution + +```kotlin +import java.util.Arrays + +@Suppress("NAME_SHADOWING") +class Solution { + fun checkRecord(n: Int): Int { + if (n == 0 || n == 1 || n == 2) { + return n * 3 + n * (n - 1) + } + val mod: Long = 1000000007 + val matrix = arrayOf( + longArrayOf(1, 1, 0, 1, 0, 0), + longArrayOf(1, 0, 1, 1, 0, 0), + longArrayOf(1, 0, 0, 1, 0, 0), + longArrayOf(0, 0, 0, 1, 1, 0), + longArrayOf(0, 0, 0, 1, 0, 1), + longArrayOf(0, 0, 0, 1, 0, 0) + ) + val e = quickPower(matrix, n - 1) + return ( + (Arrays.stream(e[0]).sum() + Arrays.stream(e[1]).sum() + Arrays.stream(e[3]).sum()) % + mod + ).toInt() + } + + private fun quickPower(a: Array, times: Int): Array { + var a = a + var times = times + val n = a.size + var e = Array(n) { LongArray(n) } + for (i in 0 until n) { + e[i][i] = 1 + } + while (times != 0) { + if (times % 2 == 1) { + e = multiple(e, a, n) + } + times = times shr 1 + a = multiple(a, a, n) + } + return e + } + + private fun multiple(a: Array, b: Array, n: Int): Array { + val target = Array(n) { LongArray(n) } + for (j in 0 until n) { + for (k in 0 until n) { + for (l in 0 until n) { + target[j][k] += a[j][l] * b[l][k] + target[j][k] = target[j][k] % 1000000007 + } + } + } + return target + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0553_optimal_division/readme.md b/src/main/kotlin/g0501_0600/s0553_optimal_division/readme.md new file mode 100644 index 00000000..cc2070b9 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0553_optimal_division/readme.md @@ -0,0 +1,81 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 553\. Optimal Division + +Medium + +You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division. + +* For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4"`. + +However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum. + +Return _the corresponding expression that has the maximum value in string format_. + +**Note:** your expression should not contain redundant parenthesis. + +**Example 1:** + +**Input:** nums = [1000,100,10,2] + +**Output:** "1000/(100/10/2)" + +**Explanation:** + + 1000/(100/10/2) = 1000/((100/10)/2) = 200 + However, the bold parenthesis in "1000/((100/10)/2)" are redundant, since they don't influence the operation priority. + So you should return "1000/(100/10/2)". + Other cases: + 1000/(100/10)/2 = 50 + 1000/(100/(10/2)) = 50 + 1000/100/10/2 = 0.5 + 1000/100/(10/2) = 2 + +**Example 2:** + +**Input:** nums = [2,3,4] + +**Output:** "2/(3/4)" + +**Example 3:** + +**Input:** nums = [2] + +**Output:** "2" + +**Constraints:** + +* `1 <= nums.length <= 10` +* `2 <= nums[i] <= 1000` +* There is only one optimal division for the given iput. + +## Solution + +```kotlin +class Solution { + fun optimalDivision(nums: IntArray): String { + val sb = StringBuilder() + if (nums.size == 1) { + sb.append(nums[0]) + return sb.toString() + } + if (nums.size == 2) { + sb.append(nums[0]) + sb.append("/") + sb.append(nums[1]) + return sb.toString() + } + sb.append(nums[0]) + sb.append("/") + sb.append("(") + for (i in 1 until nums.size - 1) { + sb.append(nums[i]) + sb.append('/') + } + sb.append(nums[nums.size - 1]) + sb.append(")") + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0554_brick_wall/readme.md b/src/main/kotlin/g0501_0600/s0554_brick_wall/readme.md new file mode 100644 index 00000000..4a3c6a8f --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0554_brick_wall/readme.md @@ -0,0 +1,59 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 554\. Brick Wall + +Medium + +There is a rectangular brick wall in front of you with `n` rows of bricks. The ith row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same. + +Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks. + +Given the 2D array `wall` that contains the information about the wall, return _the minimum number of crossed bricks after drawing such a vertical line_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/24/cutwall-grid.jpg) + +**Input:** wall = \[\[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]] + +**Output:** 2 + +**Example 2:** + +**Input:** wall = \[\[1],[1],[1]] + +**Output:** 3 + +**Constraints:** + +* `n == wall.length` +* 1 <= n <= 104 +* 1 <= wall[i].length <= 104 +* 1 <= sum(wall[i].length) <= 2 * 104 +* `sum(wall[i])` is the same for each row `i`. +* 1 <= wall[i][j] <= 231 - 1 + +## Solution + +```kotlin +class Solution { + fun leastBricks(wall: List>): Int { + val gapMap = mutableMapOf() + + wall.forEach { row -> + var pos = 0 + for (brickId in 0 until row.lastIndex) { + pos += row[brickId] + gapMap[pos] = gapMap.getOrDefault(pos, 0) + 1 + } + } + var value = 0 + + if (gapMap.size > 0) { + value = gapMap.values.max() + } + return wall.size - value + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0556_next_greater_element_iii/readme.md b/src/main/kotlin/g0501_0600/s0556_next_greater_element_iii/readme.md new file mode 100644 index 00000000..f01dcfc9 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0556_next_greater_element_iii/readme.md @@ -0,0 +1,98 @@ +[![](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) + +## 556\. Next Greater Element III + +Medium + +Given a positive integer `n`, find _the smallest integer which has exactly the same digits existing in the integer_ `n` _and is greater in value than_ `n`. If no such positive integer exists, return `-1`. + +**Note** that the returned integer should fit in **32-bit integer**, if there is a valid answer but it does not fit in **32-bit integer**, return `-1`. + +**Example 1:** + +**Input:** n = 12 + +**Output:** 21 + +**Example 2:** + +**Input:** n = 21 + +**Output:** -1 + +**Constraints:** + +* 1 <= n <= 231 - 1 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + /* + - What this problem wants is finding the next permutation of n + - Steps to find the next permuation: + find largest index k such that inp[k] < inp[k+1]; + if k == -1: return -1 + else: + look for largest index l such that inp[l] > inp[k] + swap the two index + reverse from k+1 to n.length + */ + fun nextGreaterElement(n: Int): Int { + val inp = n.toString().toCharArray() + // Find k + var k = -1 + for (i in inp.size - 2 downTo 0) { + if (inp[i] < inp[i + 1]) { + k = i + break + } + } + if (k == -1) { + return -1 + } + // Find l + var largerIdx = inp.size - 1 + for (i in inp.indices.reversed()) { + if (inp[i] > inp[k]) { + largerIdx = i + break + } + } + swap(inp, k, largerIdx) + reverse(inp, k + 1, inp.size - 1) + // Build result + var ret = 0 + for (c in inp) { + val digit = c.code - '0'.code + // Handle the case if ret > Integer.MAX_VALUE - This idea is borrowed from problem 8. + // String to Integer (atoi) + if (ret > Int.MAX_VALUE / 10 || ret == Int.MAX_VALUE / 10 && digit > Int.MAX_VALUE % 10) { + return -1 + } + ret = ret * 10 + (c.code - '0'.code) + } + return ret + } + + private fun swap(inp: CharArray, i: Int, j: Int) { + val temp = inp[i] + inp[i] = inp[j] + inp[j] = temp + } + + private fun reverse(inp: CharArray, start: Int, end: Int) { + var start = start + var end = end + while (start < end) { + val temp = inp[start] + inp[start] = inp[end] + inp[end] = temp + start++ + end-- + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0557_reverse_words_in_a_string_iii/readme.md b/src/main/kotlin/g0501_0600/s0557_reverse_words_in_a_string_iii/readme.md new file mode 100644 index 00000000..763dc438 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0557_reverse_words_in_a_string_iii/readme.md @@ -0,0 +1,62 @@ +[![](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) + +## 557\. Reverse Words in a String III + +Easy + +Given a string `s`, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. + +**Example 1:** + +**Input:** s = "Let's take LeetCode contest" + +**Output:** "s'teL ekat edoCteeL tsetnoc" + +**Example 2:** + +**Input:** s = "God Ding" + +**Output:** "doG gniD" + +**Constraints:** + +* 1 <= s.length <= 5 * 104 +* `s` contains printable **ASCII** characters. +* `s` does not contain any leading or trailing spaces. +* There is **at least one** word in `s`. +* All the words in `s` are separated by a single space. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun reverseWords(s: String): String { + var l: Int + var r = 0 + val len = s.length + val ch = s.toCharArray() + for (i in 0..len) { + if (i == len || ch[i] == ' ') { + l = r + r = i + reverse(ch, l, r - 1) + r++ + } + } + return String(ch) + } + + private fun reverse(s: CharArray, l: Int, r: Int) { + var l = l + var r = r + var c: Char + while (r > l) { + c = s[l] + s[l++] = s[r] + s[r--] = c + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0558_logical_or_of_two_binary_grids_represented_as_quad_trees/readme.md b/src/main/kotlin/g0501_0600/s0558_logical_or_of_two_binary_grids_represented_as_quad_trees/readme.md new file mode 100644 index 00000000..7b7ea782 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0558_logical_or_of_two_binary_grids_represented_as_quad_trees/readme.md @@ -0,0 +1,115 @@ +[![](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) + +## 558\. Logical OR of Two Binary Grids Represented as Quad-Trees + +Medium + +A Binary Matrix is a matrix in which all the elements are either **0** or **1**. + +Given `quadTree1` and `quadTree2`. `quadTree1` represents a `n * n` binary matrix and `quadTree2` represents another `n * n` binary matrix. + +Return _a Quad-Tree_ representing the `n * n` binary matrix which is the result of **logical bitwise OR** of the two binary matrixes represented by `quadTree1` and `quadTree2`. + +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 input/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/qt1.png) ![](https://assets.leetcode.com/uploads/2020/02/11/qt2.png) + +**Input:** quadTree1 = \[\[0,1],[1,1],[1,1],[1,0],[1,0]] , quadTree2 = \[\[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]] + +**Output:** [[0,0],[1,1],[1,1],[1,1],[1,0]] + +**Explanation:** quadTree1 and quadTree2 are shown above. You can see the binary matrix which is represented by each Quad-Tree. If we apply logical bitwise OR on the two binary matrices we get the binary matrix below which is represented by the result Quad-Tree. Notice that the binary matrices shown are only for illustration, you don't have to construct the binary matrix to get the result tree. ![](https://assets.leetcode.com/uploads/2020/02/11/qtr.png) + +**Example 2:** + +**Input:** quadTree1 = \[\[1,0]], quadTree2 = \[\[1,0]] + +**Output:** [[1,0]] + +**Explanation:** Each tree represents a binary matrix of size 1\*1. Each matrix contains only zero. The resulting matrix is of size 1\*1 with also zero. + +**Constraints:** + +* `quadTree1` and `quadTree2` are both **valid** Quad-Trees each representing a `n * n` grid. +* n == 2x where `0 <= x <= 9`. + +## 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 intersect(quadTree1: Node?, quadTree2: Node?): Node? { + if (quadTree1!!.isLeaf) { + return if (quadTree1.`val`) quadTree1 else quadTree2 + } + if (quadTree2!!.isLeaf) { + return if (quadTree2.`val`) quadTree2 else quadTree1 + } + val out = Node() + val tl: Node? = intersect(quadTree1.topLeft, quadTree2.topLeft) + val tr: Node? = intersect(quadTree1.topRight, quadTree2.topRight) + val bl: Node? = intersect(quadTree1.bottomLeft, quadTree2.bottomLeft) + val br: Node? = intersect(quadTree1.bottomRight, quadTree2.bottomRight) + if (( + tl!!.isLeaf && + tr!!.isLeaf && + bl!!.isLeaf && + br!!.isLeaf && tl.`val` == tr.`val` + ) && tr.`val` == bl.`val` && br.`val` == bl.`val` + ) { + out.isLeaf = true + out.`val` = tl.`val` + } else { + out.topLeft = tl + out.topRight = tr + out.bottomLeft = bl + out.bottomRight = br + } + return out + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0559_maximum_depth_of_n_ary_tree/readme.md b/src/main/kotlin/g0501_0600/s0559_maximum_depth_of_n_ary_tree/readme.md new file mode 100644 index 00000000..96297511 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0559_maximum_depth_of_n_ary_tree/readme.md @@ -0,0 +1,73 @@ +[![](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) + +## 559\. Maximum Depth of N-ary Tree + +Easy + +Given a n-ary tree, find its maximum depth. + +The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. + +_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:** 3 + +**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:** 5 + +**Constraints:** + +* The total number of nodes is in the range [0, 104]. +* The depth of the n-ary tree is less than or equal to `1000`. + +## Solution + +```kotlin +import com_github_leetcode.Node + +/* + * Definition for a Node. + * class Node(var `val`: Int) { + * var neighbors: List = listOf() + * } + */ + +class Solution { + private var max = 0 + + fun maxDepth(root: Node?): Int { + if (root == null) { + return 0 + } + if (root.neighbors.isEmpty()) { + return 1 + } + for (child in root.neighbors) { + findDepth(child, 1) + } + return max + } + + private fun findDepth(n: Node?, d: Int) { + if (!n!!.neighbors.isEmpty()) { + for (no in n.neighbors) { + findDepth(no, d + 1) + } + } else { + max = Math.max(max, d + 1) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0561_array_partition_i/readme.md b/src/main/kotlin/g0501_0600/s0561_array_partition_i/readme.md new file mode 100644 index 00000000..d6c12d55 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0561_array_partition_i/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) + +## 561\. Array Partition + +Easy + +Given an integer array `nums` of `2n` integers, group these integers into `n` pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all `i` is **maximized**. Return _the maximized sum_. + +**Example 1:** + +**Input:** nums = [1,4,3,2] + +**Output:** 4 + +**Explanation:** All possible pairings (ignoring the ordering of elements) are: +1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3 +2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3 +3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4 So the maximum possible sum is 4. + +**Example 2:** + +**Input:** nums = [6,2,6,5,1,2] + +**Output:** 9 + +**Explanation:** The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9. + +**Constraints:** + +* 1 <= n <= 104 +* `nums.length == 2 * n` +* -104 <= nums[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun arrayPairSum(nums: IntArray): Int { + nums.sort() + var sum = 0 + var i = 0 + while (i < nums.size - 1) { + sum += Math.min(nums[i], nums[i + 1]) + i = i + 2 + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0563_binary_tree_tilt/readme.md b/src/main/kotlin/g0501_0600/s0563_binary_tree_tilt/readme.md new file mode 100644 index 00000000..7dcdb32b --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0563_binary_tree_tilt/readme.md @@ -0,0 +1,91 @@ +[![](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) + +## 563\. Binary Tree Tilt + +Easy + +Given the `root` of a binary tree, return _the sum of every tree node's **tilt**._ + +The **tilt** of a tree node is the **absolute difference** between the sum of all left subtree node **values** and all right subtree node **values**. If a node does not have a left child, then the sum of the left subtree node **values** is treated as `0`. The rule is similar if the node does not have a right child. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/20/tilt1.jpg) + +**Input:** root = [1,2,3] + +**Output:** 1 + +**Explanation:** + + Tilt of node 2 : |0-0| = 0 (no children) + Tilt of node 3 : |0-0| = 0 (no children) + Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3) + Sum of every tilt : 0 + 0 + 1 = 1 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/10/20/tilt2.jpg) + +**Input:** root = [4,2,9,3,5,null,7] + +**Output:** 15 + +**Explanation:** + + Tilt of node 3 : |0-0| = 0 (no children) + Tilt of node 5 : |0-0| = 0 (no children) + Tilt of node 7 : |0-0| = 0 (no children) + Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5) + Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7) + Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16) + Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15 + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2020/10/20/tilt3.jpg) + +**Input:** root = [21,7,14,1,1,2,2,3,3] + +**Output:** 9 + +**Constraints:** + +* The number of nodes in the tree is in the range [0, 104]. +* `-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 { + private var sum = 0 + private fun sumTilt(root: TreeNode?): Int { + if (root == null) { + return 0 + } + val ls = sumTilt(root.left) + val rs = sumTilt(root.right) + sum += Math.abs(ls - rs) + return ls + rs + root.`val` + } + + fun findTilt(root: TreeNode?): Int { + sum = 0 + sumTilt(root) + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0564_find_the_closest_palindrome/readme.md b/src/main/kotlin/g0501_0600/s0564_find_the_closest_palindrome/readme.md new file mode 100644 index 00000000..1e0b45f8 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0564_find_the_closest_palindrome/readme.md @@ -0,0 +1,86 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 564\. Find the Closest Palindrome + +Hard + +Given a string `n` representing an integer, return _the closest integer (not including itself), which is a palindrome_. If there is a tie, return _**the smaller one**_. + +The closest is defined as the absolute difference minimized between two integers. + +**Example 1:** + +**Input:** n = "123" + +**Output:** "121" + +**Example 2:** + +**Input:** n = "1" + +**Output:** "0" + +**Explanation:** 0 and 2 are the closest palindromes but we return the smallest which is 0. + +**Constraints:** + +* `1 <= n.length <= 18` +* `n` consists of only digits. +* `n` does not have leading zeros. +* `n` is representing an integer in the range [1, 1018 - 1]. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun nearestPalindromic(n: String): String { + if (n.length == 1) { + return (n.toInt() - 1).toString() + } + val num = n.toLong() + val offset = Math.pow(10.0, (n.length / 2).toDouble()).toInt() + val first = + if (isPalindrome(n)) palindromeGenerator(num + offset, n.length) else palindromeGenerator(num, n.length) + val second = if (first < num) palindromeGenerator(num + offset, n.length) else palindromeGenerator( + num - offset, + n.length + ) + if (first + second == 2 * num) { + return if (first < second) first.toString() else second.toString() + } + return if (Math.abs(num - first) > Math.abs(num - second)) second.toString() else first.toString() + } + + private fun palindromeGenerator(num: Long, length: Int): Long { + var num = num + if (num < 10) { + return 9 + } + val numOfDigits = num.toString().length + if (numOfDigits > length) { + return Math.pow(10.0, (numOfDigits - 1).toDouble()).toLong() + 1 + } else if (numOfDigits < length) { + return Math.pow(10.0, numOfDigits.toDouble()).toLong() - 1 + } + num = num - num % Math.pow(10.0, (numOfDigits / 2).toDouble()).toLong() + var temp = num + for (j in 0 until numOfDigits / 2) { + val digit = Math.pow(10.0, (numOfDigits - j - 1).toDouble()).toLong() + num += (temp / digit * Math.pow(10.0, j.toDouble())).toInt().toLong() + temp = temp % digit + } + return num + } + + private fun isPalindrome(str: String): Boolean { + for (i in 0 until str.length / 2) { + if (str[i] != str[str.length - 1 - i]) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0565_array_nesting/readme.md b/src/main/kotlin/g0501_0600/s0565_array_nesting/readme.md new file mode 100644 index 00000000..bfa95251 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0565_array_nesting/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) + +## 565\. Array Nesting + +Medium + +You are given an integer array `nums` of length `n` where `nums` is a permutation of the numbers in the range `[0, n - 1]`. + +You should build a set `s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... }` subjected to the following rule: + +* The first element in `s[k]` starts with the selection of the element `nums[k]` of `index = k`. +* The next element in `s[k]` should be `nums[nums[k]]`, and then `nums[nums[nums[k]]]`, and so on. +* We stop adding right before a duplicate element occurs in `s[k]`. + +Return _the longest length of a set_ `s[k]`. + +**Example 1:** + +**Input:** nums = [5,4,0,3,1,6,2] + +**Output:** 4 + +**Explanation:** nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2. One of the longest sets s[k]: s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0} + +**Example 2:** + +**Input:** nums = [0,1,2] + +**Output:** 1 + +**Constraints:** + +* 1 <= nums.length <= 105 +* `0 <= nums[i] < nums.length` +* All the values of `nums` are **unique**. + +## Solution + +```kotlin +class Solution { + fun arrayNesting(nums: IntArray): Int { + var index: Int + var value: Int + var maxLen = 0 + var len: Int + for (i in nums.indices) { + if (nums[i] != -1) { + index = i + len = 0 + while (nums[index] != -1) { + value = nums[index] + nums[index] = -1 + index = value + len++ + } + maxLen = Math.max(len, maxLen) + } + } + return maxLen + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0566_reshape_the_matrix/readme.md b/src/main/kotlin/g0501_0600/s0566_reshape_the_matrix/readme.md new file mode 100644 index 00000000..d9220561 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0566_reshape_the_matrix/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) + +## 566\. Reshape the Matrix + +Easy + +In MATLAB, there is a handy function called `reshape` which can reshape an `m x n` matrix into a new one with a different size `r x c` keeping its original data. + +You are given an `m x n` matrix `mat` and two integers `r` and `c` representing the number of rows and the number of columns of the wanted reshaped matrix. + +The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were. + +If the `reshape` operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/24/reshape1-grid.jpg) + +**Input:** mat = \[\[1,2],[3,4]], r = 1, c = 4 + +**Output:** [[1,2,3,4]] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/04/24/reshape2-grid.jpg) + +**Input:** mat = \[\[1,2],[3,4]], r = 2, c = 4 + +**Output:** [[1,2],[3,4]] + +**Constraints:** + +* `m == mat.length` +* `n == mat[i].length` +* `1 <= m, n <= 100` +* `-1000 <= mat[i][j] <= 1000` +* `1 <= r, c <= 300` + +## Solution + +```kotlin +class Solution { + fun matrixReshape(mat: Array, r: Int, c: Int): Array { + if (mat.size * mat[0].size != r * c) { + return mat + } + var p = 0 + val flatArr = IntArray(mat.size * mat[0].size) + for (ints in mat) { + for (anInt in ints) { + flatArr[p++] = anInt + } + } + val ansMat = Array(r) { IntArray(c) } + var k = 0 + for (i in ansMat.indices) { + for (j in ansMat[i].indices) { + ansMat[i][j] = flatArr[k++] + } + } + return ansMat + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0567_permutation_in_string/readme.md b/src/main/kotlin/g0501_0600/s0567_permutation_in_string/readme.md new file mode 100644 index 00000000..df965606 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0567_permutation_in_string/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 567\. Permutation in String + +Medium + +Given two strings `s1` and `s2`, return `true` _if_ `s2` _contains a permutation of_ `s1`_, or_ `false` _otherwise_. + +In other words, return `true` if one of `s1`'s permutations is the substring of `s2`. + +**Example 1:** + +**Input:** s1 = "ab", s2 = "eidbaooo" + +**Output:** true + +**Explanation:** s2 contains one permutation of s1 ("ba"). + +**Example 2:** + +**Input:** s1 = "ab", s2 = "eidboaoo" + +**Output:** false + +**Constraints:** + +* 1 <= s1.length, s2.length <= 104 +* `s1` and `s2` consist of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun checkInclusion(s1: String, s2: String): Boolean { + val n = s1.length + val m = s2.length + if (n > m) { + return false + } + val cntS1 = IntArray(26) + val cntS2 = IntArray(26) + for (i in 0 until n) { + cntS1[s1[i].code - 'a'.code]++ + } + for (i in 0 until n) { + cntS2[s2[i].code - 'a'.code]++ + } + if (check(cntS1, cntS2)) { + return true + } + for (i in n until m) { + cntS2[s2[i - n].code - 'a'.code]-- + cntS2[s2[i].code - 'a'.code]++ + if (check(cntS1, cntS2)) { + return true + } + } + return false + } + + private fun check(cnt1: IntArray, cnt2: IntArray): Boolean { + for (i in 0..25) { + if (cnt1[i] != cnt2[i]) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0572_subtree_of_another_tree/readme.md b/src/main/kotlin/g0501_0600/s0572_subtree_of_another_tree/readme.md new file mode 100644 index 00000000..b0964822 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0572_subtree_of_another_tree/readme.md @@ -0,0 +1,77 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 572\. Subtree of Another Tree + +Easy + +Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. + +A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/28/subtree1-tree.jpg) + +**Input:** root = [3,4,5,1,2], subRoot = [4,1,2] + +**Output:** true + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/04/28/subtree2-tree.jpg) + +**Input:** root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2] + +**Output:** false + +**Constraints:** + +* The number of nodes in the `root` tree is in the range `[1, 2000]`. +* The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. +* -104 <= root.val <= 104 +* -104 <= subRoot.val <= 104 + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private fun isSubtreeFound(root: TreeNode?, subRoot: TreeNode?): Boolean { + if (root == null && subRoot == null) { + return true + } + if (root == null || subRoot == null) { + return false + } + return if (root.`val` == subRoot.`val`) { + isSubtreeFound(root.left, subRoot.left) && isSubtree(root.right, subRoot.right) + } else { + false + } + } + + fun isSubtree(root: TreeNode?, subRoot: TreeNode?): Boolean { + if (root == null && subRoot == null) { + return true + } + return if (root == null || subRoot == null) { + false + } else isSubtreeFound(root, subRoot) || + isSubtree(root.left, subRoot) || + isSubtree(root.right, subRoot) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0575_distribute_candies/readme.md b/src/main/kotlin/g0501_0600/s0575_distribute_candies/readme.md new file mode 100644 index 00000000..daee8079 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0575_distribute_candies/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) + +## 575\. Distribute Candies + +Easy + +Alice has `n` candies, where the ith candy is of type `candyType[i]`. Alice noticed that she started to gain weight, so she visited a doctor. + +The doctor advised Alice to only eat `n / 2` of the candies she has (`n` is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. + +Given the integer array `candyType` of length `n`, return _the **maximum** number of different types of candies she can eat if she only eats_ `n / 2` _of them_. + +**Example 1:** + +**Input:** candyType = [1,1,2,2,3,3] + +**Output:** 3 + +**Explanation:** Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type. + +**Example 2:** + +**Input:** candyType = [1,1,2,3] + +**Output:** 2 + +**Explanation:** Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types. + +**Example 3:** + +**Input:** candyType = [6,6,6,6] + +**Output:** 1 + +**Explanation:** Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type. + +**Constraints:** + +* `n == candyType.length` +* 2 <= n <= 104 +* `n` is even. +* -105 <= candyType[i] <= 105 + +## Solution + +```kotlin +internal class Solution { + fun distributeCandies(candyType: IntArray): Int { + val s: MutableSet = HashSet() + for (i in candyType) { + if (!s.contains(i)) { + s.add(i) + } + } + val canEat = candyType.size / 2 + return if (s.size >= canEat) { + canEat + } else { + s.size + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0576_out_of_boundary_paths/readme.md b/src/main/kotlin/g0501_0600/s0576_out_of_boundary_paths/readme.md new file mode 100644 index 00000000..dd9969da --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0576_out_of_boundary_paths/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) + +## 576\. Out of Boundary Paths + +Medium + +There is an `m x n` grid with a ball. The ball is initially at the position `[startRow, startColumn]`. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply **at most** `maxMove` moves to the ball. + +Given the five integers `m`, `n`, `maxMove`, `startRow`, `startColumn`, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it **modulo** 109 + 7. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_1.png) + +**Input:** m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 + +**Output:** 6 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_2.png) + +**Input:** m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1 + +**Output:** 12 + +**Constraints:** + +* `1 <= m, n <= 50` +* `0 <= maxMove <= 50` +* `0 <= startRow < m` +* `0 <= startColumn < n` + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + private val dRowCol = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1)) + private fun dfs( + m: Int, + n: Int, + remainingMoves: Int, + currRow: Int, + currCol: Int, + cache: Array> + ): Int { + if (currRow < 0 || currRow == m || currCol < 0 || currCol == n) { + return 1 + } + if (remainingMoves == 0) { + return 0 + } + if (cache[currRow][currCol][remainingMoves] == -1) { + var paths = 0 + for (i in 0..3) { + val newRow = currRow + dRowCol[i][0] + val newCol = currCol + dRowCol[i][1] + val m1 = 1000000007 + paths = (paths + dfs(m, n, remainingMoves - 1, newRow, newCol, cache)) % m1 + } + cache[currRow][currCol][remainingMoves] = paths + } + return cache[currRow][currCol][remainingMoves] + } + + fun findPaths(m: Int, n: Int, maxMoves: Int, startRow: Int, startCol: Int): Int { + val cache = Array(m) { + Array(n) { + IntArray( + maxMoves + 1 + ) + } + } + for (c1 in cache) { + for (c2 in c1) { + Arrays.fill(c2, -1) + } + } + return dfs(m, n, maxMoves, startRow, startCol, cache) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0581_shortest_unsorted_continuous_subarray/readme.md b/src/main/kotlin/g0501_0600/s0581_shortest_unsorted_continuous_subarray/readme.md new file mode 100644 index 00000000..9753d8da --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0581_shortest_unsorted_continuous_subarray/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) + +## 581\. Shortest Unsorted Continuous Subarray + +Medium + +Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. + +Return _the shortest such subarray and output its length_. + +**Example 1:** + +**Input:** nums = [2,6,4,8,10,9,15] + +**Output:** 5 + +**Explanation:** You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. + +**Example 2:** + +**Input:** nums = [1,2,3,4] + +**Output:** 0 + +**Example 3:** + +**Input:** nums = [1] + +**Output:** 0 + +**Constraints:** + +* 1 <= nums.length <= 104 +* -105 <= nums[i] <= 105 + +**Follow up:** Can you solve it in `O(n)` time complexity? + +## Solution + +```kotlin +class Solution { + fun findUnsortedSubarray(nums: IntArray): Int { + var end = -2 + var max = Int.MIN_VALUE + for (i in nums.indices) { + max = Math.max(max, nums[i]) + if (nums[i] < max) { + end = i + } + } + var start = -1 + var min = Int.MAX_VALUE + for (i in nums.indices.reversed()) { + min = Math.min(min, nums[i]) + if (nums[i] > min) { + start = i + } + } + return end - start + 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0583_delete_operation_for_two_strings/readme.md b/src/main/kotlin/g0501_0600/s0583_delete_operation_for_two_strings/readme.md new file mode 100644 index 00000000..bfab6200 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0583_delete_operation_for_two_strings/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) + +## 583\. Delete Operation for Two Strings + +Medium + +Given two strings `word1` and `word2`, return _the minimum number of **steps** required to make_ `word1` _and_ `word2` _the same_. + +In one **step**, you can delete exactly one character in either string. + +**Example 1:** + +**Input:** word1 = "sea", word2 = "eat" + +**Output:** 2 + +**Explanation:** You need one step to make "sea" to "ea" and another step to make "eat" to "ea". + +**Example 2:** + +**Input:** word1 = "leetcode", word2 = "etco" + +**Output:** 4 + +**Constraints:** + +* `1 <= word1.length, word2.length <= 500` +* `word1` and `word2` consist of only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun minDistance(word1: String, word2: String): Int { + val m = word1.length + val n = word2.length + val dp = Array(m + 1) { IntArray(n + 1) } + for (i in 1..m) { + for (j in 1..n) { + dp[i][j] = if (word1[i - 1] == word2[j - 1]) dp[i - 1][j - 1] + 1 else Math.max( + dp[i - 1][j], + dp[i][j - 1] + ) + } + } + return m + n - 2 * dp[m][n] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0584_find_customer_referee/readme.md b/src/main/kotlin/g0501_0600/s0584_find_customer_referee/readme.md new file mode 100644 index 00000000..19f41531 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0584_find_customer_referee/readme.md @@ -0,0 +1,60 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 584\. Find Customer Referee + +Easy + +SQL Schema + +Table: `Customer` + + +-------------+---------+ + | Column Name | Type | + +-------------+---------+ + | id | int | + | name | varchar | + | referee_id | int | + +-------------+---------+ + id is the primary key column for this table. + Each row of this table indicates the id of a customer, their name, and the id of the customer who referred them. + +Write an SQL query to report the IDs of the customer that are **not referred by** the customer with `id = 2`. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Customer table: + +----+------+------------+ + | id | name | referee_id | + +----+------+------------+ + | 1 | Will | null | + | 2 | Jane | null | + | 3 | Alex | 2 | + | 4 | Bill | null | + | 5 | Zack | 1 | + | 6 | Mark | 2 | + +----+------+------------+ + +**Output:** + + +------+ + | name | + +------+ + | Will | + | Jane | + | Bill | + | Zack | + +------+ + +## Solution + +```sql +# Write your MySQL query statement below +SELECT name FROM customer where referee_id != 2 or referee_id is null; +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0586_customer_placing_the_largest_number_of_orders/readme.md b/src/main/kotlin/g0501_0600/s0586_customer_placing_the_largest_number_of_orders/readme.md new file mode 100644 index 00000000..71ba0c77 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0586_customer_placing_the_largest_number_of_orders/readme.md @@ -0,0 +1,62 @@ +[![](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) + +## 586\. Customer Placing the Largest Number of Orders + +Easy + +SQL Schema + +Table: `Orders` + + +-----------------+----------+ + | Column Name | Type | + +-----------------+----------+ + | order_number | int | + | customer_number | int | + +-----------------+----------+ + order_number is the primary key for this table. + This table contains information about the order ID and the customer ID. + +Write an SQL query to find the `customer_number` for the customer who has placed **the largest number of orders**. + +The test cases are generated so that **exactly one customer** will have placed more orders than any other customer. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Orders table: + +--------------+-----------------+ + | order_number | customer_number | + +--------------+-----------------+ + | 1 | 1 | + | 2 | 2 | + | 3 | 3 | + | 4 | 3 | + +--------------+-----------------+ + +**Output:** + + +-----------------+ + | customer_number | + +-----------------+ + | 3 | + +-----------------+ + +**Explanation:** + +The customer with number 3 has two orders, which is greater than either customer 1 or 2 because each of them only has one order. + +So the result is customer\_number 3. + +**Follow up:** What if more than one customer has the largest number of orders, can you find all the `customer_number` in this case? + +## Solution + +```sql +# Write your MySQL query statement below +select customer_number from orders group by customer_number order by count(customer_number) desc limit 1 +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0587_erect_the_fence/readme.md b/src/main/kotlin/g0501_0600/s0587_erect_the_fence/readme.md new file mode 100644 index 00000000..73e26197 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0587_erect_the_fence/readme.md @@ -0,0 +1,108 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 587\. Erect the Fence + +Hard + +You are given an array `trees` where trees[i] = [xi, yi] represents the location of a tree in the garden. + +Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if **all the trees are enclosed**. + +Return _the coordinates of trees that are exactly located on the fence perimeter_. You may return the answer in **any order**. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/24/erect2-plane.jpg) + +**Input:** trees = \[\[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] + +**Output:** [[1,1],[2,0],[4,2],[3,3],[2,4]] + +**Explanation:** All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/04/24/erect1-plane.jpg) + +**Input:** trees = \[\[1,2],[2,2],[4,2]] + +**Output:** [[4,2],[2,2],[1,2]] + +**Explanation:** The fence forms a line that passes through all the trees. + +**Constraints:** + +* `1 <= trees.length <= 3000` +* `trees[i].length == 2` +* 0 <= xi, yi <= 100 +* All the given positions are **unique**. + +## Solution + +```kotlin +import kotlin.math.abs +import kotlin.math.atan2 +import kotlin.math.pow +import kotlin.math.sqrt + + +class Solution { + private fun dist(p1: Pair, p2: Pair): Double { + return sqrt((p2.second - p1.second).toDouble().pow(2.0) + Math.pow((p2.first - p1.first).toDouble(), 2.0)) + } + + private fun angle(p1: Pair, p2: Pair): Double { + return atan2((p2.second - p1.second).toDouble(), (p2.first - p1.first).toDouble()).let { + if (it < 0) return (2.0 * Math.PI + it) else it + } + } + + fun outerTrees(trees: Array): Array { + if (trees.size < 3) { + return trees + } + val left = trees.asSequence().map { it[0] to it[1] }.toMutableList() + left.sortWith(compareBy> { it.second }.thenBy { it.first }) + val firstPoint = left[0] + var nowPoint = firstPoint + val pointList = mutableListOf(nowPoint) + var prevAngle = 0.0 + while (true) { + val nowList = mutableListOf, Double>>() + var nowMinAngleDiff = 7.0 + var nowMinAngle = 7.0 + left.forEach { + if (it != nowPoint) { + val angle = angle(nowPoint, it) + if (abs(angle - nowMinAngle) < 0.0000001) { + nowList.add(it to dist(it, nowPoint)) + } else { + val diff = if (angle >= prevAngle) (angle - prevAngle) else 2.0 * Math.PI - (angle - prevAngle) + if ((diff) < nowMinAngleDiff) { + nowMinAngle = angle + nowMinAngleDiff = (diff) + nowList.clear() + nowList.add(it to dist(it, nowPoint)) + } + } + } + } + prevAngle = nowMinAngle + nowList.sortBy { it.second } + val nowListOnlyPoints = nowList.map { it.first }.toMutableList() + if (nowListOnlyPoints.last() == firstPoint) { + nowListOnlyPoints.removeAt(nowListOnlyPoints.size - 1) + left.removeAll(nowListOnlyPoints) + pointList.addAll(nowListOnlyPoints) + break + } else { + nowPoint = nowListOnlyPoints.last() + left.removeAll(nowListOnlyPoints) + pointList.addAll(nowListOnlyPoints) + } + } + return pointList.asSequence().map { intArrayOf(it.first, it.second) }.toList().toTypedArray() + } +} +``` \ No newline at end of file