From 6eb30aad4b524bb3b5a3b77a81bb634d36984529 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 17 Apr 2023 09:34:13 +0300 Subject: [PATCH] Added task 871-923 --- README.md | 64 ++++++ .../s0814_binary_tree_pruning/readme.md | 2 +- .../g0801_0900/s0815_bus_routes/readme.md | 3 - .../s0817_linked_list_components/readme.md | 3 +- .../s0819_most_common_word/readme.md | 6 +- .../readme.md | 4 +- .../g0801_0900/s0843_guess_the_word/readme.md | 12 +- .../g0801_0900/s0855_exam_room/readme.md | 4 +- .../readme.md | 6 +- .../readme.md | 90 +++++++++ .../s0872_leaf_similar_trees/readme.md | 82 ++++++++ .../readme.md | 69 +++++++ .../s0874_walking_robot_simulation/readme.md | 186 ++++++++++++++++++ .../s0875_koko_eating_bananas/readme.md | 73 +++++++ .../s0876_middle_of_the_linked_list/readme.md | 62 ++++++ .../g0801_0900/s0877_stone_game/readme.md | 65 ++++++ .../s0878_nth_magical_number/readme.md | 72 +++++++ .../s0879_profitable_schemes/readme.md | 64 ++++++ .../s0880_decoded_string_at_index/readme.md | 79 ++++++++ .../s0881_boats_to_save_people/readme.md | 65 ++++++ .../readme.md | 105 ++++++++++ .../readme.md | 79 ++++++++ .../readme.md | 61 ++++++ .../s0885_spiral_matrix_iii/readme.md | 127 ++++++++++++ .../s0886_possible_bipartition/readme.md | 93 +++++++++ .../g0801_0900/s0887_super_egg_drop/readme.md | 70 +++++++ .../s0888_fair_candy_swap/readme.md | 68 +++++++ .../readme.md | 100 ++++++++++ .../s0890_find_and_replace_pattern/readme.md | 77 ++++++++ .../s0891_sum_of_subsequence_widths/readme.md | 75 +++++++ .../s0892_surface_area_of_3d_shapes/readme.md | 81 ++++++++ .../readme.md | 80 ++++++++ .../readme.md | 91 +++++++++ .../s0895_maximum_frequency_stack/readme.md | 117 +++++++++++ .../s0896_monotonic_array/readme.md | 62 ++++++ .../readme.md | 66 +++++++ .../s0898_bitwise_ors_of_subarrays/readme.md | 66 +++++++ .../g0801_0900/s0899_orderly_queue/readme.md | 75 +++++++ .../g0801_0900/s0900_rle_iterator/readme.md | 79 ++++++++ .../s0901_online_stock_span/readme.md | 82 ++++++++ .../readme.md | 74 +++++++ .../readme.md | 74 +++++++ .../s0904_fruit_into_baskets/readme.md | 84 ++++++++ .../s0905_sort_array_by_parity/readme.md | 49 +++++ .../s0906_super_palindromes/readme.md | 96 +++++++++ .../s0907_sum_of_subarray_minimums/readme.md | 82 ++++++++ .../s0908_smallest_range_i/readme.md | 62 ++++++ .../s0909_snakes_and_ladders/readme.md | 111 +++++++++++ .../s0910_smallest_range_ii/readme.md | 66 +++++++ .../s0911_online_election/readme.md | 92 +++++++++ .../g0901_1000/s0912_sort_an_array/readme.md | 74 +++++++ .../g0901_1000/s0913_cat_and_mouse/readme.md | 136 +++++++++++++ .../readme.md | 65 ++++++ .../readme.md | 59 ++++++ .../g0901_1000/s0916_word_subsets/readme.md | 73 +++++++ .../s0917_reverse_only_letters/readme.md | 64 ++++++ .../readme.md | 75 +++++++ .../readme.md | 122 ++++++++++++ .../s0920_number_of_music_playlists/readme.md | 77 ++++++++ .../readme.md | 60 ++++++ .../s0922_sort_array_by_parity_ii/readme.md | 62 ++++++ .../s0923_3sum_with_multiplicity/readme.md | 80 ++++++++ 62 files changed, 4375 insertions(+), 27 deletions(-) create mode 100644 src/main/kotlin/g0801_0900/s0871_minimum_number_of_refueling_stops/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0872_leaf_similar_trees/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0873_length_of_longest_fibonacci_subsequence/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0874_walking_robot_simulation/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0875_koko_eating_bananas/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0876_middle_of_the_linked_list/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0877_stone_game/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0878_nth_magical_number/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0879_profitable_schemes/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0880_decoded_string_at_index/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0881_boats_to_save_people/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0882_reachable_nodes_in_subdivided_graph/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0883_projection_area_of_3d_shapes/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0884_uncommon_words_from_two_sentences/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0885_spiral_matrix_iii/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0886_possible_bipartition/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0887_super_egg_drop/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0888_fair_candy_swap/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0889_construct_binary_tree_from_preorder_and_postorder_traversal/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0890_find_and_replace_pattern/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0891_sum_of_subsequence_widths/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0892_surface_area_of_3d_shapes/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0893_groups_of_special_equivalent_strings/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0894_all_possible_full_binary_trees/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0895_maximum_frequency_stack/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0896_monotonic_array/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0897_increasing_order_search_tree/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0898_bitwise_ors_of_subarrays/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0899_orderly_queue/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0900_rle_iterator/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0901_online_stock_span/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0902_numbers_at_most_n_given_digit_set/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0903_valid_permutations_for_di_sequence/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0904_fruit_into_baskets/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0905_sort_array_by_parity/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0906_super_palindromes/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0907_sum_of_subarray_minimums/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0908_smallest_range_i/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0909_snakes_and_ladders/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0910_smallest_range_ii/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0911_online_election/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0912_sort_an_array/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0913_cat_and_mouse/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0914_x_of_a_kind_in_a_deck_of_cards/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0915_partition_array_into_disjoint_intervals/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0916_word_subsets/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0917_reverse_only_letters/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0919_complete_binary_tree_inserter/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0920_number_of_music_playlists/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0921_minimum_add_to_make_parentheses_valid/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0922_sort_array_by_parity_ii/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0923_3sum_with_multiplicity/readme.md diff --git a/README.md b/README.md index 6590ec42..3f31322a 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,7 @@ | | | | | | |-|-|-|-|-|- +| 0876 |[Middle of the Linked List](src/main/kotlin/g0801_0900/s0876_middle_of_the_linked_list)| Easy | Two_Pointers, Linked_List | 136 | 76.52 | 0142 |[Linked List Cycle II](src/main/kotlin/g0101_0200/s0142_linked_list_cycle_ii)| Medium | Top_100_Liked_Questions, Hash_Table, Two_Pointers, Linked_List | 192 | 63.39 #### Day 5 Greedy @@ -414,6 +415,7 @@ | | | | | | |-|-|-|-|-|- +| 0912 |[Sort an Array](src/main/kotlin/g0901_1000/s0912_sort_an_array)| Medium | Array, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Merge_Sort, Bucket_Sort, Counting_Sort, Radix_Sort | 606 | 98.48 #### Udemy 2D Arrays/Matrix @@ -435,6 +437,7 @@ | 0328 |[Odd Even Linked List](src/main/kotlin/g0301_0400/s0328_odd_even_linked_list)| Medium | Top_Interview_Questions, Linked_List | 216 | 86.96 | 0061 |[Rotate List](src/main/kotlin/g0001_0100/s0061_rotate_list)| Medium | Two_Pointers, Linked_List | 193 | 92.16 | 0024 |[Swap Nodes in Pairs](src/main/kotlin/g0001_0100/s0024_swap_nodes_in_pairs)| Medium | Top_100_Liked_Questions, Linked_List, Recursion | 149 | 99.39 +| 0876 |[Middle of the Linked List](src/main/kotlin/g0801_0900/s0876_middle_of_the_linked_list)| Easy | Two_Pointers, Linked_List | 136 | 76.52 | 0142 |[Linked List Cycle II](src/main/kotlin/g0101_0200/s0142_linked_list_cycle_ii)| Medium | Top_100_Liked_Questions, Hash_Table, Two_Pointers, Linked_List | 192 | 63.39 | 0141 |[Linked List Cycle](src/main/kotlin/g0101_0200/s0141_linked_list_cycle)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Two_Pointers, Linked_List | 223 | 91.85 | 0206 |[Reverse Linked List](src/main/kotlin/g0201_0300/s0206_reverse_linked_list)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 279 | 45.78 @@ -824,6 +827,7 @@ | | | | | | |-|-|-|-|-|- +| 0876 |[Middle of the Linked List](src/main/kotlin/g0801_0900/s0876_middle_of_the_linked_list)| Easy | Two_Pointers, Linked_List | 136 | 76.52 | 0019 |[Remove Nth Node From End of List](src/main/kotlin/g0001_0100/s0019_remove_nth_node_from_end_of_list)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Two_Pointers, Linked_List | 180 | 91.58 #### Day 6 Sliding Window @@ -1146,6 +1150,7 @@ | | | | | | |-|-|-|-|-|- +| 0875 |[Koko Eating Bananas](src/main/kotlin/g0801_0900/s0875_koko_eating_bananas)| Medium | Array, Binary_Search | 267 | 93.85 #### Day 5 @@ -1237,6 +1242,7 @@ | | | | | | |-|-|-|-|-|- +| 0911 |[Online Election](src/main/kotlin/g0901_1000/s0911_online_election)| Medium | Array, Hash_Table, Binary_Search, Design | 766 | 83.33 ### Dynamic Programming I @@ -1273,6 +1279,7 @@ | | | | | | |-|-|-|-|-|- | 0053 |[Maximum Subarray](src/main/kotlin/g0001_0100/s0053_maximum_subarray)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer | 662 | 82.48 +| 0918 |[Maximum Sum Circular Subarray](src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray)| Medium | Array, Dynamic_Programming, Divide_and_Conquer, Queue, Monotonic_Queue | 339 | 86.96 #### Day 6 @@ -1444,6 +1451,7 @@ | | | | | | |-|-|-|-|-|- +| 0876 |[Middle of the Linked List](src/main/kotlin/g0801_0900/s0876_middle_of_the_linked_list)| Easy | Two_Pointers, Linked_List | 136 | 76.52 | 0104 |[Maximum Depth of Binary Tree](src/main/kotlin/g0101_0200/s0104_maximum_depth_of_binary_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 236 | 83.39 | 0404 |[Sum of Left Leaves](src/main/kotlin/g0401_0500/s0404_sum_of_left_leaves)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 173 | 86.05 @@ -1467,6 +1475,7 @@ | | | | | | |-|-|-|-|-|- +| 0896 |[Monotonic Array](src/main/kotlin/g0801_0900/s0896_monotonic_array)| Easy | Array | 576 | 90.91 | 0028 |[Find the Index of the First Occurrence in a String](src/main/kotlin/g0001_0100/s0028_implement_strstr)| Easy | Top_Interview_Questions, String, Two_Pointers, String_Matching | 257 | 32.35 #### Day 2 @@ -1545,6 +1554,7 @@ | | | | | | |-|-|-|-|-|- | 0304 |[Range Sum Query 2D - Immutable](src/main/kotlin/g0301_0400/s0304_range_sum_query_2d_immutable)| Medium | Array, Matrix, Design, Prefix_Sum | 1373 | 85.71 +| 0910 |[Smallest Range II](src/main/kotlin/g0901_1000/s0910_smallest_range_ii)| Medium | Array, Math, Sorting, Greedy | 234 | 100.00 #### Day 14 @@ -1679,6 +1689,7 @@ | | | | | | |-|-|-|-|-|- +| 0886 |[Possible Bipartition](src/main/kotlin/g0801_0900/s0886_possible_bipartition)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 397 | 100.00 | 0785 |[Is Graph Bipartite?](src/main/kotlin/g0701_0800/s0785_is_graph_bipartite)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 215 | 82.35 ## Algorithms @@ -1687,6 +1698,59 @@ |------|----------------|-------------|-------------|----------|-------- | 1143 |[Longest Common Subsequence](src/main/kotlin/g1101_1200/s1143_longest_common_subsequence)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming, Algorithm_II_Day_17_Dynamic_Programming, Dynamic_Programming_I_Day_19, Udemy_Dynamic_Programming | 307 | 38.36 | 0994 |[Rotting Oranges](src/main/kotlin/g0901_1000/s0994_rotting_oranges)| Medium | Array, Breadth_First_Search, Matrix, Algorithm_I_Day_9_Breadth_First_Search_Depth_First_Search, Level_2_Day_10_Graph/BFS/DFS | 308 | 57.93 +| 0923 |[3Sum With Multiplicity](src/main/kotlin/g0901_1000/s0923_3sum_with_multiplicity)| Medium | Array, Hash_Table, Sorting, Two_Pointers, Counting | 190 | 100.00 +| 0922 |[Sort Array By Parity II](src/main/kotlin/g0901_1000/s0922_sort_array_by_parity_ii)| Easy | Array, Sorting, Two_Pointers | 257 | 87.50 +| 0921 |[Minimum Add to Make Parentheses Valid](src/main/kotlin/g0901_1000/s0921_minimum_add_to_make_parentheses_valid)| Medium | String, Greedy, Stack | 131 | 92.59 +| 0920 |[Number of Music Playlists](src/main/kotlin/g0901_1000/s0920_number_of_music_playlists)| Hard | Dynamic_Programming, Math, Combinatorics | 136 | 100.00 +| 0919 |[Complete Binary Tree Inserter](src/main/kotlin/g0901_1000/s0919_complete_binary_tree_inserter)| Medium | Breadth_First_Search, Tree, Binary_Tree, Design | 225 | 100.00 +| 0918 |[Maximum Sum Circular Subarray](src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray)| Medium | Array, Dynamic_Programming, Divide_and_Conquer, Queue, Monotonic_Queue, Dynamic_Programming_I_Day_5 | 339 | 86.96 +| 0917 |[Reverse Only Letters](src/main/kotlin/g0901_1000/s0917_reverse_only_letters)| Easy | String, Two_Pointers | 126 | 100.00 +| 0916 |[Word Subsets](src/main/kotlin/g0901_1000/s0916_word_subsets)| Medium | Array, String, Hash_Table | 397 | 88.89 +| 0915 |[Partition Array into Disjoint Intervals](src/main/kotlin/g0901_1000/s0915_partition_array_into_disjoint_intervals)| Medium | Array | 510 | 76.92 +| 0914 |[X of a Kind in a Deck of Cards](src/main/kotlin/g0901_1000/s0914_x_of_a_kind_in_a_deck_of_cards)| Easy | Array, Hash_Table, Math, Counting, Number_Theory | 238 | 70.00 +| 0913 |[Cat and Mouse](src/main/kotlin/g0901_1000/s0913_cat_and_mouse)| Hard | Dynamic_Programming, Math, Graph, Memoization, Topological_Sort, Game_Theory | 211 | 100.00 +| 0912 |[Sort an Array](src/main/kotlin/g0901_1000/s0912_sort_an_array)| Medium | Array, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Merge_Sort, Bucket_Sort, Counting_Sort, Radix_Sort, Udemy_Sorting_Algorithms | 606 | 98.48 +| 0911 |[Online Election](src/main/kotlin/g0901_1000/s0911_online_election)| Medium | Array, Hash_Table, Binary_Search, Design, Binary_Search_II_Day_20 | 766 | 83.33 +| 0910 |[Smallest Range II](src/main/kotlin/g0901_1000/s0910_smallest_range_ii)| Medium | Array, Math, Sorting, Greedy, Programming_Skills_II_Day_13 | 234 | 100.00 +| 0909 |[Snakes and Ladders](src/main/kotlin/g0901_1000/s0909_snakes_and_ladders)| Medium | Array, Breadth_First_Search, Matrix | 203 | 100.00 +| 0908 |[Smallest Range I](src/main/kotlin/g0901_1000/s0908_smallest_range_i)| Easy | Array, Math | 202 | 87.50 +| 0907 |[Sum of Subarray Minimums](src/main/kotlin/g0901_1000/s0907_sum_of_subarray_minimums)| Medium | Array, Dynamic_Programming, Stack, Monotonic_Stack | 341 | 100.00 +| 0906 |[Super Palindromes](src/main/kotlin/g0901_1000/s0906_super_palindromes)| Hard | Math, Enumeration | 153 | 100.00 +| 0905 |[Sort Array By Parity](src/main/kotlin/g0901_1000/s0905_sort_array_by_parity)| Easy | Array, Sorting, Two_Pointers | 219 | 75.00 +| 0904 |[Fruit Into Baskets](src/main/kotlin/g0901_1000/s0904_fruit_into_baskets)| Medium | Array, Hash_Table, Sliding_Window | 371 | 100.00 +| 0903 |[Valid Permutations for DI Sequence](src/main/kotlin/g0901_1000/s0903_valid_permutations_for_di_sequence)| Hard | Dynamic_Programming | 140 | 100.00 +| 0902 |[Numbers At Most N Given Digit Set](src/main/kotlin/g0901_1000/s0902_numbers_at_most_n_given_digit_set)| Hard | Array, Dynamic_Programming, Math, Binary_Search | 138 | 100.00 +| 0901 |[Online Stock Span](src/main/kotlin/g0901_1000/s0901_online_stock_span)| Medium | Stack, Design, Monotonic_Stack, Data_Stream | 641 | 75.00 +| 0900 |[RLE Iterator](src/main/kotlin/g0801_0900/s0900_rle_iterator)| Medium | Array, Design, Counting, Iterator | 175 | 83.33 +| 0899 |[Orderly Queue](src/main/kotlin/g0801_0900/s0899_orderly_queue)| Hard | String, Math, Sorting | 148 | 100.00 +| 0898 |[Bitwise ORs of Subarrays](src/main/kotlin/g0801_0900/s0898_bitwise_ors_of_subarrays)| Medium | Array, Dynamic_Programming, Bit_Manipulation | 812 | 100.00 +| 0897 |[Increasing Order Search Tree](src/main/kotlin/g0801_0900/s0897_increasing_order_search_tree)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack, Binary_Search_Tree | 128 | 85.71 +| 0896 |[Monotonic Array](src/main/kotlin/g0801_0900/s0896_monotonic_array)| Easy | Array, Programming_Skills_II_Day_1 | 576 | 90.91 +| 0895 |[Maximum Frequency Stack](src/main/kotlin/g0801_0900/s0895_maximum_frequency_stack)| Hard | Hash_Table, Stack, Design, Ordered_Set | 617 | 100.00 +| 0894 |[All Possible Full Binary Trees](src/main/kotlin/g0801_0900/s0894_all_possible_full_binary_trees)| Medium | Dynamic_Programming, Tree, Binary_Tree, Recursion, Memoization | 257 | 100.00 +| 0893 |[Groups of Special-Equivalent Strings](src/main/kotlin/g0801_0900/s0893_groups_of_special_equivalent_strings)| Medium | Array, String, Hash_Table | 141 | 100.00 +| 0892 |[Surface Area of 3D Shapes](src/main/kotlin/g0801_0900/s0892_surface_area_of_3d_shapes)| Easy | Array, Math, Matrix, Geometry | 180 | 100.00 +| 0891 |[Sum of Subsequence Widths](src/main/kotlin/g0801_0900/s0891_sum_of_subsequence_widths)| Hard | Array, Math, Sorting | 481 | 100.00 +| 0890 |[Find and Replace Pattern](src/main/kotlin/g0801_0900/s0890_find_and_replace_pattern)| Medium | Array, String, Hash_Table | 150 | 100.00 +| 0889 |[Construct Binary Tree from Preorder and Postorder Traversal](src/main/kotlin/g0801_0900/s0889_construct_binary_tree_from_preorder_and_postorder_traversal)| Medium | Array, Hash_Table, Tree, Binary_Tree, Divide_and_Conquer | 168 | 100.00 +| 0888 |[Fair Candy Swap](src/main/kotlin/g0801_0900/s0888_fair_candy_swap)| Easy | Array, Hash_Table, Sorting, Binary_Search | 318 | 100.00 +| 0887 |[Super Egg Drop](src/main/kotlin/g0801_0900/s0887_super_egg_drop)| Hard | Dynamic_Programming, Math, Binary_Search | 119 | 100.00 +| 0886 |[Possible Bipartition](src/main/kotlin/g0801_0900/s0886_possible_bipartition)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find, Graph_Theory_I_Day_14_Graph_Theory | 397 | 100.00 +| 0885 |[Spiral Matrix III](src/main/kotlin/g0801_0900/s0885_spiral_matrix_iii)| Medium | Array, Matrix, Simulation | 265 | 100.00 +| 0884 |[Uncommon Words from Two Sentences](src/main/kotlin/g0801_0900/s0884_uncommon_words_from_two_sentences)| Easy | String, Hash_Table | 171 | 100.00 +| 0883 |[Projection Area of 3D Shapes](src/main/kotlin/g0801_0900/s0883_projection_area_of_3d_shapes)| Easy | Array, Math, Matrix, Geometry | 173 | 100.00 +| 0882 |[Reachable Nodes In Subdivided Graph](src/main/kotlin/g0801_0900/s0882_reachable_nodes_in_subdivided_graph)| Hard | Heap_Priority_Queue, Graph, Shortest_Path | 434 | 100.00 +| 0881 |[Boats to Save People](src/main/kotlin/g0801_0900/s0881_boats_to_save_people)| Medium | Array, Sorting, Greedy, Two_Pointers | 370 | 96.07 +| 0880 |[Decoded String at Index](src/main/kotlin/g0801_0900/s0880_decoded_string_at_index)| Medium | String, Stack | 134 | 100.00 +| 0879 |[Profitable Schemes](src/main/kotlin/g0801_0900/s0879_profitable_schemes)| Hard | Array, Dynamic_Programming | 198 | 75.00 +| 0878 |[Nth Magical Number](src/main/kotlin/g0801_0900/s0878_nth_magical_number)| Hard | Math, Binary_Search | 124 | 100.00 +| 0877 |[Stone Game](src/main/kotlin/g0801_0900/s0877_stone_game)| Medium | Array, Dynamic_Programming, Math, Game_Theory | 136 | 88.24 +| 0876 |[Middle of the Linked List](src/main/kotlin/g0801_0900/s0876_middle_of_the_linked_list)| Easy | Two_Pointers, Linked_List, Algorithm_I_Day_5_Two_Pointers, Programming_Skills_I_Day_10_Linked_List_and_Tree, Level_1_Day_4_Linked_List, Udemy_Linked_List | 136 | 76.52 +| 0875 |[Koko Eating Bananas](src/main/kotlin/g0801_0900/s0875_koko_eating_bananas)| Medium | Array, Binary_Search, Binary_Search_II_Day_4 | 267 | 93.85 +| 0874 |[Walking Robot Simulation](src/main/kotlin/g0801_0900/s0874_walking_robot_simulation)| Medium | Array, Simulation | 274 | 100.00 +| 0873 |[Length of Longest Fibonacci Subsequence](src/main/kotlin/g0801_0900/s0873_length_of_longest_fibonacci_subsequence)| Medium | Array, Hash_Table, Dynamic_Programming | 341 | 90.00 +| 0872 |[Leaf-Similar Trees](src/main/kotlin/g0801_0900/s0872_leaf_similar_trees)| Easy | Depth_First_Search, Tree, Binary_Tree | 140 | 100.00 +| 0871 |[Minimum Number of Refueling Stops](src/main/kotlin/g0801_0900/s0871_minimum_number_of_refueling_stops)| Hard | Array, Dynamic_Programming, Greedy, Heap_Priority_Queue | 203 | 92.86 | 0870 |[Advantage Shuffle](src/main/kotlin/g0801_0900/s0870_advantage_shuffle)| Medium | Array, Sorting, Greedy | 698 | 100.00 | 0869 |[Reordered Power of 2](src/main/kotlin/g0801_0900/s0869_reordered_power_of_2)| Medium | Math, Sorting, Counting, Enumeration | 145 | 87.50 | 0868 |[Binary Gap](src/main/kotlin/g0801_0900/s0868_binary_gap)| Easy | Bit_Manipulation | 142 | 100.00 diff --git a/src/main/kotlin/g0801_0900/s0814_binary_tree_pruning/readme.md b/src/main/kotlin/g0801_0900/s0814_binary_tree_pruning/readme.md index b1aac0a2..0ba97580 100644 --- a/src/main/kotlin/g0801_0900/s0814_binary_tree_pruning/readme.md +++ b/src/main/kotlin/g0801_0900/s0814_binary_tree_pruning/readme.md @@ -49,7 +49,7 @@ The diagram on the right represents the answer. ```kotlin import com_github_leetcode.TreeNode -/** +/* * Example: * var ti = TreeNode(5) * var v = ti.`val` diff --git a/src/main/kotlin/g0801_0900/s0815_bus_routes/readme.md b/src/main/kotlin/g0801_0900/s0815_bus_routes/readme.md index a2fad086..ab0749de 100644 --- a/src/main/kotlin/g0801_0900/s0815_bus_routes/readme.md +++ b/src/main/kotlin/g0801_0900/s0815_bus_routes/readme.md @@ -41,9 +41,6 @@ Return _the least number of buses you must take to travel from_ `source` _to_ `t ```kotlin import java.util.LinkedList import java.util.Queue -import kotlin.collections.ArrayList -import kotlin.collections.HashSet -import kotlin.collections.MutableSet class Solution { fun numBusesToDestination(routes: Array, source: Int, target: Int): Int { diff --git a/src/main/kotlin/g0801_0900/s0817_linked_list_components/readme.md b/src/main/kotlin/g0801_0900/s0817_linked_list_components/readme.md index 5778754e..c88ab2f8 100644 --- a/src/main/kotlin/g0801_0900/s0817_linked_list_components/readme.md +++ b/src/main/kotlin/g0801_0900/s0817_linked_list_components/readme.md @@ -44,7 +44,7 @@ Return _the number of connected components in_ `nums` _where two values are conn ```kotlin import com_github_leetcode.ListNode -/** +/* * Example: * var li = ListNode(5) * var v = li.`val` @@ -53,7 +53,6 @@ import com_github_leetcode.ListNode * var next: ListNode? = null * } */ - @Suppress("NAME_SHADOWING") class Solution { fun numComponents(head: ListNode?, nums: IntArray): Int { diff --git a/src/main/kotlin/g0801_0900/s0819_most_common_word/readme.md b/src/main/kotlin/g0801_0900/s0819_most_common_word/readme.md index 5bec2b32..e386370d 100644 --- a/src/main/kotlin/g0801_0900/s0819_most_common_word/readme.md +++ b/src/main/kotlin/g0801_0900/s0819_most_common_word/readme.md @@ -34,16 +34,14 @@ The words in `paragraph` are **case-insensitive** and the answer should be retur ## Solution ```kotlin -import java.util.Locale - @Suppress("NAME_SHADOWING") class Solution { fun mostCommonWord(paragraph: String, banned: Array): String { var paragraph = paragraph - paragraph = paragraph.replace("\\p{Punct}".toRegex(), " ").lowercase(Locale.getDefault()) + paragraph = paragraph.replace("\\p{Punct}".toRegex(), " ").lowercase() val a = paragraph.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() for (i in banned.indices) { - banned[i] = banned[i].lowercase(Locale.getDefault()) + banned[i] = banned[i].lowercase() } val map: MutableMap = HashMap() for (s in a) { diff --git a/src/main/kotlin/g0801_0900/s0831_masking_personal_information/readme.md b/src/main/kotlin/g0801_0900/s0831_masking_personal_information/readme.md index 92f1044c..372a0903 100644 --- a/src/main/kotlin/g0801_0900/s0831_masking_personal_information/readme.md +++ b/src/main/kotlin/g0801_0900/s0831_masking_personal_information/readme.md @@ -86,15 +86,13 @@ Thus, the resulting masked number is "\*\*\*-\*\*\*-7890". ## Solution ```kotlin -import java.util.Locale - class Solution { fun maskPII(s: String): String { val masked = StringBuilder() return if (Character.isAlphabetic(s[0].code)) { val locationOfAtSymbol = s.indexOf("@") - 1 masked.append(s[0]).append("*****").append(s.substring(locationOfAtSymbol)) - masked.toString().lowercase(Locale.getDefault()) + masked.toString().lowercase() } else { val allDigits = StringBuilder() var pointer = -1 diff --git a/src/main/kotlin/g0801_0900/s0843_guess_the_word/readme.md b/src/main/kotlin/g0801_0900/s0843_guess_the_word/readme.md index e5d6105d..906b6bdb 100644 --- a/src/main/kotlin/g0801_0900/s0843_guess_the_word/readme.md +++ b/src/main/kotlin/g0801_0900/s0843_guess_the_word/readme.md @@ -48,8 +48,6 @@ For each test case, you have exactly `10` guesses to guess the word. At the end ## Solution ```kotlin -import java.util.Collections - /* * // This is the Master's API interface. * // You should not implement it, or speculate about its implementation @@ -65,8 +63,8 @@ class Solution { private var next = 0 fun findSecretWord(wordlist: Array, master: Master) { - val list = listOf(*wordlist) - Collections.shuffle(list) + val list = wordlist.copyOf() + list.shuffle() val test = BooleanArray(wordlist.size) while (true) { val num = master.guess(list[next]) @@ -77,7 +75,7 @@ class Solution { } } - private fun updateList(list: List, test: BooleanArray, num: Int) { + private fun updateList(list: Array, test: BooleanArray, num: Int) { val index = next for (i in index + 1 until test.size) { if (test[i]) { @@ -92,10 +90,10 @@ class Solution { } } - private fun getSame(word1: String?, word2: String?): Int { + private fun getSame(word1: String, word2: String): Int { var ret = 0 for (i in 0..5) { - if (word1!![i] == word2!![i]) { + if (word1[i] == word2[i]) { ret++ } } diff --git a/src/main/kotlin/g0801_0900/s0855_exam_room/readme.md b/src/main/kotlin/g0801_0900/s0855_exam_room/readme.md index db739a73..a29bec01 100644 --- a/src/main/kotlin/g0801_0900/s0855_exam_room/readme.md +++ b/src/main/kotlin/g0801_0900/s0855_exam_room/readme.md @@ -42,8 +42,6 @@ Implement the `ExamRoom` class: ## Solution ```kotlin -import java.util.Objects - class ExamRoom() { private class Node(var `val`: Int, map: MutableMap) { var pre: Node? = null @@ -107,7 +105,7 @@ class ExamRoom() { } return if (right > max) { Node(n - 1, map).insert(tail.pre) - } else Node(maxAt, map).insert(Objects.requireNonNull(maxAtLeft)) + } else Node(maxAt, map).insert(maxAtLeft) } fun leave(p: Int) { diff --git a/src/main/kotlin/g0801_0900/s0857_minimum_cost_to_hire_k_workers/readme.md b/src/main/kotlin/g0801_0900/s0857_minimum_cost_to_hire_k_workers/readme.md index 615a4c6a..29d7142e 100644 --- a/src/main/kotlin/g0801_0900/s0857_minimum_cost_to_hire_k_workers/readme.md +++ b/src/main/kotlin/g0801_0900/s0857_minimum_cost_to_hire_k_workers/readme.md @@ -49,10 +49,8 @@ class Solution { workers[i] = Worker(wage[i], quality[i]) } workers.sortBy { it!!.ratio() } - val maxHeap = PriorityQueue { a: Int?, b: Int? -> - Integer.compare( - b!!, a!! - ) + val maxHeap = PriorityQueue { a: Int, b: Int -> + b.compareTo(a) } var sumQuality = 0 var result = Double.MAX_VALUE diff --git a/src/main/kotlin/g0801_0900/s0871_minimum_number_of_refueling_stops/readme.md b/src/main/kotlin/g0801_0900/s0871_minimum_number_of_refueling_stops/readme.md new file mode 100644 index 00000000..ab99aff1 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0871_minimum_number_of_refueling_stops/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) + +## 871\. Minimum Number of Refueling Stops + +Hard + +A car travels from a starting position to a destination which is `target` miles east of the starting position. + +There are gas stations along the way. The gas stations are represented as an array `stations` where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas. + +The car starts with an infinite tank of gas, which initially has `startFuel` liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car. + +Return _the minimum number of refueling stops the car must make in order to reach its destination_. If it cannot reach the destination, return `-1`. + +Note that if the car reaches a gas station with `0` fuel left, the car can still refuel there. If the car reaches the destination with `0` fuel left, it is still considered to have arrived. + +**Example 1:** + +**Input:** target = 1, startFuel = 1, stations = [] + +**Output:** 0 + +**Explanation:** We can reach the target without refueling. + +**Example 2:** + +**Input:** target = 100, startFuel = 1, stations = \[\[10,100]] + +**Output:** -1 + +**Explanation:** We can not reach the target (or even the first gas station). + +**Example 3:** + +**Input:** target = 100, startFuel = 10, stations = \[\[10,60],[20,30],[30,30],[60,40]] + +**Output:** 2 + +**Explanation:** We start with 10 liters of fuel. We drive to position 10, expending 10 liters of fuel. + +We refuel from 0 liters to 60 liters of gas. + +Then, we drive from position 10 to position 60 (expending 50 liters of fuel), + +and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target. + +We made 2 refueling stops along the way, so we return 2. + +**Constraints:** + +* 1 <= target, startFuel <= 109 +* `0 <= stations.length <= 500` +* 0 <= positioni <= positioni+1 < target +* 1 <= fueli < 109 + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + fun minRefuelStops(target: Int, startFuel: Int, stations: Array?): Int { + if (startFuel >= target) { + return 0 + } else if (stations.isNullOrEmpty()) { + return -1 + } + val pq = PriorityQueue { a: IntArray, b: IntArray -> + b[1] - a[1] + } + var start = 0 + val end = stations.size + var currentFuel = startFuel + var stops = 0 + while (currentFuel < target) { + while (start < end && currentFuel >= stations[start][0]) { + pq.add(stations[start++]) + } + if (pq.isEmpty()) { + return -1 + } + val current = pq.poll() + currentFuel += current[1] + stops++ + } + return stops + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0872_leaf_similar_trees/readme.md b/src/main/kotlin/g0801_0900/s0872_leaf_similar_trees/readme.md new file mode 100644 index 00000000..7bbbb2b8 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0872_leaf_similar_trees/readme.md @@ -0,0 +1,82 @@ +[![](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) + +## 872\. Leaf-Similar Trees + +Easy + +Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._ + +![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/16/tree.png) + +For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`. + +Two binary trees are considered _leaf-similar_ if their leaf value sequence is the same. + +Return `true` if and only if the two given trees with head nodes `root1` and `root2` are leaf-similar. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-1.jpg) + +**Input:** root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8] + +**Output:** true + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-2.jpg) + +**Input:** root1 = [1,2,3], root2 = [1,3,2] + +**Output:** false + +**Constraints:** + +* The number of nodes in each tree will be in the range `[1, 200]`. +* Both of the given trees will have values in the range `[0, 200]`. + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun leafSimilar(root1: TreeNode?, root2: TreeNode?): Boolean { + val list1: MutableList = ArrayList() + val list2: MutableList = ArrayList() + preOrder(root1, list1) + preOrder(root2, list2) + // compare the lists + if (list1.size != list2.size) { + return false + } + for (i in list1.indices) { + if (list1[i] != list2[i]) { + return false + } + } + return true + } + + private fun preOrder(root: TreeNode?, list: MutableList) { + if (root != null) { + if (root.left == null && root.right == null) { + list.add(root.`val`) + } + preOrder(root.left, list) + preOrder(root.right, list) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0873_length_of_longest_fibonacci_subsequence/readme.md b/src/main/kotlin/g0801_0900/s0873_length_of_longest_fibonacci_subsequence/readme.md new file mode 100644 index 00000000..a840c9cb --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0873_length_of_longest_fibonacci_subsequence/readme.md @@ -0,0 +1,69 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 873\. Length of Longest Fibonacci Subsequence + +Medium + +A sequence x1, x2, ..., xn is _Fibonacci-like_ if: + +* `n >= 3` +* xi + xi+1 == xi+2 for all `i + 2 <= n` + +Given a **strictly increasing** array `arr` of positive integers forming a sequence, return _the **length** of the longest Fibonacci-like subsequence of_ `arr`. If one does not exist, return `0`. + +A **subsequence** is derived from another sequence `arr` by deleting any number of elements (including none) from `arr`, without changing the order of the remaining elements. For example, `[3, 5, 8]` is a subsequence of `[3, 4, 5, 6, 7, 8]`. + +**Example 1:** + +**Input:** arr = [1,2,3,4,5,6,7,8] + +**Output:** 5 + +**Explanation:** The longest subsequence that is fibonacci-like: [1,2,3,5,8]. + +**Example 2:** + +**Input:** arr = [1,3,7,11,12,14,18] + +**Output:** 3 + +**Explanation:**: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18]. + +**Constraints:** + +* `3 <= arr.length <= 1000` +* 1 <= arr[i] < arr[i + 1] <= 109 + +## Solution + +```kotlin +class Solution { + fun lenLongestFibSubseq(arr: IntArray?): Int { + if (arr == null || arr.size < 3) { + return 0 + } + val len = arr.size + val dp = Array(len) { IntArray(len) } + var ans = 0 + for (i in 2 until len) { + var left = 0 + var right = i - 1 + while (left < right) { + if (arr[left] + arr[right] < arr[i]) { + left++ + } else if (arr[left] + arr[right] > arr[i]) { + right-- + } else { + // dp[right][i] = Math.max(dp[right][i], dp[left][right] + 1); + dp[right][i] = dp[left][right] + 1 + ans = Math.max(ans, dp[right][i]) + left++ + right-- + } + } + } + return if (ans > 0) ans + 2 else 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0874_walking_robot_simulation/readme.md b/src/main/kotlin/g0801_0900/s0874_walking_robot_simulation/readme.md new file mode 100644 index 00000000..8f3e5b64 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0874_walking_robot_simulation/readme.md @@ -0,0 +1,186 @@ +[![](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) + +## 874\. Walking Robot Simulation + +Medium + +A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`: + +* `-2`: Turn left `90` degrees. +* `-1`: Turn right `90` degrees. +* `1 <= k <= 9`: Move forward `k` units, one unit at a time. + +Some of the grid squares are `obstacles`. The ith obstacle is at grid point obstacles[i] = (xi, yi). If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command. + +Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_. + +**Note:** + +* North means +Y direction. +* East means +X direction. +* South means -Y direction. +* West means -X direction. + +**Example 1:** + +**Input:** commands = [4,-1,3], obstacles = [] + +**Output:** 25 + +**Explanation:** + +The robot starts at (0, 0): + +1. Move north 4 units to (0, 4). + +2. Turn right. + +3. Move east 3 units to (3, 4). + +The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away. + +**Example 2:** + +**Input:** commands = [4,-1,4,-2,4], obstacles = \[\[2,4]] + +**Output:** 65 + +**Explanation:** + +The robot starts at (0, 0): + +1. Move north 4 units to (0, 4). + +2. Turn right. + +3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4). + +4. Turn left. + +5. Move north 4 units to (1, 8). + +The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away. + +**Example 3:** + +**Input:** commands = [6,-1,-1,6], obstacles = [] + +**Output:** 36 + +**Explanation:** + +The robot starts at (0, 0): + +1. Move north 6 units to (0, 6). + +2. Turn right. + +3. Turn right. + +4. Move south 6 units to (0, 0). + +The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away. + +**Constraints:** + +* 1 <= commands.length <= 104 +* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`. +* 0 <= obstacles.length <= 104 +* -3 * 104 <= xi, yi <= 3 * 104 +* The answer is guaranteed to be less than 231. + +## Solution + +```kotlin +class Solution { + internal class Point(var row: Int, var column: Int) { + override fun equals(other: Any?): Boolean { + if (other !is Point) { + return false + } + return other.row == row && other.column == column + } + + override fun hashCode(): Int { + return row * column * 31 + } + } + + internal enum class Direction(val x: Int, val y: Int) { + NORTH(0, 1) { + override fun turnLeft(): Direction { + return WEST + } + + override fun turnRight(): Direction { + return EAST + } + }, + EAST(1, 0) { + override fun turnLeft(): Direction { + return NORTH + } + + override fun turnRight(): Direction { + return SOUTH + } + }, + SOUTH(0, -1) { + override fun turnLeft(): Direction { + return EAST + } + + override fun turnRight(): Direction { + return WEST + } + }, + WEST(-1, 0) { + override fun turnLeft(): Direction { + return SOUTH + } + + override fun turnRight(): Direction { + return NORTH + } + }; + + abstract fun turnLeft(): Direction + abstract fun turnRight(): Direction + fun next(p: Point): Point { + return Point(p.row + x, p.column + y) + } + } + + fun robotSim(commands: IntArray, obstacles: Array): Int { + val set: MutableSet = HashSet() + for (i in obstacles.indices) { + val p = Point(obstacles[i][0], obstacles[i][1]) + set.add(p) + } + var direction = Direction.NORTH + var p = Point(0, 0) + var maxDistance = 0 + for (i in commands.indices) { + val command = commands[i] + if (command == -1) { + direction = direction.turnRight() + continue + } + if (command == -2) { + direction = direction.turnLeft() + continue + } + for (j in 0 until command) { + val destination = direction.next(p) + if (set.contains(destination)) { + break + } + p = destination + } + maxDistance = maxDistance.coerceAtLeast(p.row * p.row + p.column * p.column) + } + return maxDistance + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0875_koko_eating_bananas/readme.md b/src/main/kotlin/g0801_0900/s0875_koko_eating_bananas/readme.md new file mode 100644 index 00000000..12a5d635 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0875_koko_eating_bananas/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) + +## 875\. Koko Eating Bananas + +Medium + +Koko loves to eat bananas. There are `n` piles of bananas, the ith pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours. + +Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k` bananas, she eats all of them instead and will not eat any more bananas during this hour. + +Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. + +Return _the minimum integer_ `k` _such that she can eat all the bananas within_ `h` _hours_. + +**Example 1:** + +**Input:** piles = [3,6,7,11], h = 8 + +**Output:** 4 + +**Example 2:** + +**Input:** piles = [30,11,23,4,20], h = 5 + +**Output:** 30 + +**Example 3:** + +**Input:** piles = [30,11,23,4,20], h = 6 + +**Output:** 23 + +**Constraints:** + +* 1 <= piles.length <= 104 +* piles.length <= h <= 109 +* 1 <= piles[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun minEatingSpeed(piles: IntArray, h: Int): Int { + var maxP = piles[0] + var sumP = 0L + for (pile in piles) { + maxP = maxP.coerceAtLeast(pile) + sumP += pile.toLong() + } + // binary search + var low = ((sumP - 1) / h + 1).toInt() + var high = maxP + while (low < high) { + val mid = low + (high - low) / 2 + if (isPossible(piles, mid, h)) { + high = mid + } else { + low = mid + 1 + } + } + return low + } + + private fun isPossible(piles: IntArray, k: Int, h: Int): Boolean { + var sum = 0 + for (pile in piles) { + sum += (pile - 1) / k + 1 + } + return sum <= h + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0876_middle_of_the_linked_list/readme.md b/src/main/kotlin/g0801_0900/s0876_middle_of_the_linked_list/readme.md new file mode 100644 index 00000000..39221089 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0876_middle_of_the_linked_list/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) + +## 876\. Middle of the Linked List + +Easy + +Given the `head` of a singly linked list, return _the middle node of the linked list_. + +If there are two middle nodes, return **the second middle** node. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/07/23/lc-midlist1.jpg) + +**Input:** head = [1,2,3,4,5] + +**Output:** [3,4,5] + +**Explanation:** The middle node of the list is node 3. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/07/23/lc-midlist2.jpg) + +**Input:** head = [1,2,3,4,5,6] + +**Output:** [4,5,6] + +**Explanation:** Since the list has two middle nodes with values 3 and 4, we return the second one. + +**Constraints:** + +* The number of nodes in the list is in the range `[1, 100]`. +* `1 <= Node.val <= 100` + +## Solution + +```kotlin +import com_github_leetcode.ListNode + +/* + * Example: + * var li = ListNode(5) + * var v = li.`val` + * Definition for singly-linked list. + * class ListNode(var `val`: Int) { + * var next: ListNode? = null + * } + */ +class Solution { + fun middleNode(head: ListNode?): ListNode? { + var fast = head + var slow = head + while (fast?.next != null) { + fast = fast.next!!.next + slow = slow!!.next + } + return slow + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0877_stone_game/readme.md b/src/main/kotlin/g0801_0900/s0877_stone_game/readme.md new file mode 100644 index 00000000..f8d2e7ea --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0877_stone_game/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) + +## 877\. Stone Game + +Medium + +Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`. + +The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties. + +Alice and Bob take turns, with **Alice starting first**. Each turn, a player takes the entire pile of stones either from the **beginning** or from the **end** of the row. This continues until there are no more piles left, at which point the person with the **most stones wins**. + +Assuming Alice and Bob play optimally, return `true` _if Alice wins the game, or_ `false` _if Bob wins_. + +**Example 1:** + +**Input:** piles = [5,3,4,5] + +**Output:** true + +**Explanation:** + +Alice starts first, and can only take the first 5 or the last 5. + +Say she takes the first 5, so that the row becomes [3, 4, 5]. + +If Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points. + +If Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points. + +This demonstrated that taking the first 5 was a winning move for Alice, so we return true. + +**Example 2:** + +**Input:** piles = [3,7,2,3] + +**Output:** true + +**Constraints:** + +* `2 <= piles.length <= 500` +* `piles.length` is **even**. +* `1 <= piles[i] <= 500` +* `sum(piles[i])` is **odd**. + +## Solution + +```kotlin +class Solution { + fun stoneGame(piles: IntArray): Boolean { + var low = 0 + var high = piles.size - 1 + var alice = 0 + var bob = 0 + while (low < high) { + alice += piles[low].coerceAtLeast(piles[high]) + bob += piles[low].coerceAtMost(piles[high]) + low++ + high-- + } + return alice > bob + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0878_nth_magical_number/readme.md b/src/main/kotlin/g0801_0900/s0878_nth_magical_number/readme.md new file mode 100644 index 00000000..e5d2b8a9 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0878_nth_magical_number/readme.md @@ -0,0 +1,72 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 878\. Nth Magical Number + +Hard + +A positive integer is _magical_ if it is divisible by either `a` or `b`. + +Given the three integers `n`, `a`, and `b`, return the nth magical number. Since the answer may be very large, **return it modulo** 109 + 7. + +**Example 1:** + +**Input:** n = 1, a = 2, b = 3 + +**Output:** 2 + +**Example 2:** + +**Input:** n = 4, a = 2, b = 3 + +**Output:** 6 + +**Constraints:** + +* 1 <= n <= 109 +* 2 <= a, b <= 4 * 104 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun nthMagicalNumber(n: Int, a: Int, b: Int): Int { + val c = lcm(a.toLong(), b.toLong()) + var l: Long = 2 + var r = n * c + var ans = r + while (l <= r) { + val mid = l + (r - l) / 2 + val cnt = mid / a + mid / b - mid / c + if (cnt < n) { + l = mid + 1 + } else { + ans = mid + r = mid - 1 + } + } + return (ans % MOD).toInt() + } + + private fun lcm(a: Long, b: Long): Long { + return a * b / gcd(a, b) + } + + private fun gcd(a: Long, b: Long): Long { + var a = a + var b = b + var t: Long + while (b != 0L) { + t = b + b = a % b + a = t + } + return a + } + + companion object { + private const val MOD = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0879_profitable_schemes/readme.md b/src/main/kotlin/g0801_0900/s0879_profitable_schemes/readme.md new file mode 100644 index 00000000..548dbe14 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0879_profitable_schemes/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) + +## 879\. Profitable Schemes + +Hard + +There is a group of `n` members, and a list of various crimes they could commit. The ith crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime. + +Let's call a **profitable scheme** any subset of these crimes that generates at least `minProfit` profit, and the total number of members participating in that subset of crimes is at most `n`. + +Return the number of schemes that can be chosen. Since the answer may be very large, **return it modulo** 109 + 7. + +**Example 1:** + +**Input:** n = 5, minProfit = 3, group = [2,2], profit = [2,3] + +**Output:** 2 + +**Explanation:** To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1. In total, there are 2 schemes. + +**Example 2:** + +**Input:** n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8] + +**Output:** 7 + +**Explanation:** To make a profit of at least 5, the group could commit any crimes, as long as they commit one. There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2). + +**Constraints:** + +* `1 <= n <= 100` +* `0 <= minProfit <= 100` +* `1 <= group.length <= 100` +* `1 <= group[i] <= 100` +* `profit.length == group.length` +* `0 <= profit[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun profitableSchemes(n: Int, minProfit: Int, group: IntArray, profit: IntArray): Int { + val dp = Array(n + 1) { LongArray(minProfit + 1) } + val modulus = 1000000007L + for (i in dp.indices) { + dp[i][0] = 1 + } + for (i in group.indices) { + val currWorker = group[i] + val currProfit = profit[i] + for (j in dp.size - 1 downTo currWorker) { + for (k in dp[j].indices.reversed()) { + dp[j][k] = ( + (dp[j][k] + dp[j - currWorker][(k - currProfit).coerceAtLeast(0)]) % + modulus + ) + } + } + } + return dp[n][minProfit].toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0880_decoded_string_at_index/readme.md b/src/main/kotlin/g0801_0900/s0880_decoded_string_at_index/readme.md new file mode 100644 index 00000000..569c6ab7 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0880_decoded_string_at_index/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) + +## 880\. Decoded String at Index + +Medium + +You are given an encoded string `s`. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: + +* If the character read is a letter, that letter is written onto the tape. +* If the character read is a digit `d`, the entire current tape is repeatedly written `d - 1` more times in total. + +Given an integer `k`, return _the_ kth _letter (**1-indexed)** in the decoded string_. + +**Example 1:** + +**Input:** s = "leet2code3", k = 10 + +**Output:** "o" + +**Explanation:** The decoded string is "leetleetcodeleetleetcodeleetleetcode". The 10th letter in the string is "o". + +**Example 2:** + +**Input:** s = "ha22", k = 5 + +**Output:** "h" + +**Explanation:** The decoded string is "hahahaha". The 5th letter is "h". + +**Example 3:** + +**Input:** s = "a2345678999999999999999", k = 1 + +**Output:** "a" + +**Explanation:** The decoded string is "a" repeated 8301530446056247680 times. The 1st letter is "a". + +**Constraints:** + +* `2 <= s.length <= 100` +* `s` consists of lowercase English letters and digits `2` through `9`. +* `s` starts with a letter. +* 1 <= k <= 109 +* It is guaranteed that `k` is less than or equal to the length of the decoded string. +* The decoded string is guaranteed to have less than 263 letters. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun decodeAtIndex(s: String, k: Int): String { + var k = k + var i = 0 + var count: Long = 0 + while (i < s.length && count <= k) { + val c = s[i] + count = if (Character.isDigit(c)) count * (c.code - '0'.code) else count + 1 + i++ + } + i-- + while (i < s.length) { + val c = s[i] + if (Character.isDigit(c)) { + count /= (c.code - '0'.code).toLong() + k %= count.toInt() + } else { + if (k % count == 0L) { + break + } + --count + } + i-- + } + return s[i].toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0881_boats_to_save_people/readme.md b/src/main/kotlin/g0801_0900/s0881_boats_to_save_people/readme.md new file mode 100644 index 00000000..2ab0f7b2 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0881_boats_to_save_people/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) + +## 881\. Boats to Save People + +Medium + +You are given an array `people` where `people[i]` is the weight of the ith person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. + +Return _the minimum number of boats to carry every given person_. + +**Example 1:** + +**Input:** people = [1,2], limit = 3 + +**Output:** 1 + +**Explanation:** 1 boat (1, 2) + +**Example 2:** + +**Input:** people = [3,2,2,1], limit = 3 + +**Output:** 3 + +**Explanation:** 3 boats (1, 2), (2) and (3) + +**Example 3:** + +**Input:** people = [3,5,3,4], limit = 5 + +**Output:** 4 + +**Explanation:** 4 boats (3), (3), (4), (5) + +**Constraints:** + +* 1 <= people.length <= 5 * 104 +* 1 <= people[i] <= limit <= 3 * 104 + +## Solution + +```kotlin +class Solution { + fun numRescueBoats(people: IntArray, limit: Int): Int { + people.sort() + var i = 0 + var j = people.size - 1 + var boats = 0 + while (i < j) { + if (people[i] + people[j] <= limit) { + boats++ + i++ + j-- + } else if (people[i] + people[j] > limit) { + boats++ + j-- + } + } + return if (i == j) { + boats + 1 + } else boats + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0882_reachable_nodes_in_subdivided_graph/readme.md b/src/main/kotlin/g0801_0900/s0882_reachable_nodes_in_subdivided_graph/readme.md new file mode 100644 index 00000000..c25e15f3 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0882_reachable_nodes_in_subdivided_graph/readme.md @@ -0,0 +1,105 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 882\. Reachable Nodes In Subdivided Graph + +Hard + +You are given an undirected graph (the **"original graph"**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. + +The graph is given as a 2D array of `edges` where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will **subdivide** the edge into. Note that cnti == 0 means you will not subdivide the edge. + +To **subdivide** the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi]. + +In this **new graph**, you want to know how many nodes are **reachable** from the node `0`, where a node is **reachable** if the distance is `maxMoves` or less. + +Given the original graph and `maxMoves`, return _the number of nodes that are **reachable** from node_ `0` _in the new graph_. + +**Example 1:** + +![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/01/origfinal.png) + +**Input:** edges = \[\[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3 + +**Output:** 13 + +**Explanation:** The edge subdivisions are shown in the image above. The nodes that are reachable are highlighted in yellow. + +**Example 2:** + +**Input:** edges = \[\[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4 + +**Output:** 23 + +**Example 3:** + +**Input:** edges = \[\[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5 + +**Output:** 1 + +**Explanation:** Node 0 is disconnected from the rest of the graph, so only node 0 is reachable. + +**Constraints:** + +* 0 <= edges.length <= min(n * (n - 1) / 2, 104) +* `edges[i].length == 3` +* 0 <= ui < vi < n +* There are **no multiple edges** in the graph. +* 0 <= cnti <= 104 +* 0 <= maxMoves <= 109 +* `1 <= n <= 3000` + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + fun reachableNodes(edges: Array, maxMoves: Int, n: Int): Int { + val adList = getAdList(edges, n) + val pQueue = PriorityQueue { a: IntArray, b: IntArray -> + a[1] - b[1] + } + val minDis = IntArray(n) + var res = 0 + pQueue.add(intArrayOf(0, 0)) + while (pQueue.size > 0) { + val poll = pQueue.poll() + val node = poll[0] + val dist = poll[1] + if (minDis[node] > 0) continue + res++ + minDis[node] = dist + for (child in adList[node]!!) { + val cNode = child!![0] + val weight = child[1] + if (cNode != 0 && minDis[cNode] == 0) { + res += (maxMoves - dist).coerceAtMost(weight) + val cNodeDist = dist + weight + 1 + if (cNodeDist <= maxMoves) pQueue.add(intArrayOf(cNode, cNodeDist)) + } else { + res += (weight - (maxMoves - minDis[cNode]).coerceAtMost(weight)).coerceAtMost( + (maxMoves - dist).coerceAtMost(weight) + ) + } + } + } + return res + } + + private fun getAdList(edges: Array, n: Int): Array?> { + val adList: Array?> = arrayOfNulls?>(n) + adList[0] = ArrayList() + for (edge in edges) { + val s = edge[0] + val d = edge[1] + val w = edge[2] + if (adList[s] == null) adList[s] = ArrayList() + if (adList[d] == null) adList[d] = ArrayList() + adList[s]?.add(intArrayOf(d, w)) + adList[d]?.add(intArrayOf(s, w)) + } + return adList + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0883_projection_area_of_3d_shapes/readme.md b/src/main/kotlin/g0801_0900/s0883_projection_area_of_3d_shapes/readme.md new file mode 100644 index 00000000..0f658617 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0883_projection_area_of_3d_shapes/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) + +## 883\. Projection Area of 3D Shapes + +Easy + +You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. + +Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. + +We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. + +A **projection** is like a shadow, that maps our **3-dimensional** figure to a **2-dimensional** plane. We are viewing the "shadow" when looking at the cubes from the top, the front, and the side. + +Return _the total area of all three projections_. + +**Example 1:** + +![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/02/shadow.png) + +**Input:** grid = \[\[1,2],[3,4]] + +**Output:** 17 + +**Explanation:** Here are the three projections ("shadows") of the shape made with each axis-aligned plane. + +**Example 2:** + +**Input:** grid = \[\[2]] + +**Output:** 5 + +**Example 3:** + +**Input:** grid = \[\[1,0],[0,2]] + +**Output:** 8 + +**Constraints:** + +* `n == grid.length == grid[i].length` +* `1 <= n <= 50` +* `0 <= grid[i][j] <= 50` + +## Solution + +```kotlin +class Solution { + fun projectionArea(grid: Array): Int { + val n = grid.size + val m = grid[0].size + var sum = n * m + var count = 0 + for (ints in grid) { + var max = Int.MIN_VALUE + for (j in 0 until m) { + if (ints[j] == 0) { + count++ + } + if (max < ints[j]) { + max = ints[j] + } + } + sum += max + } + for (i in 0 until n) { + var max = Int.MIN_VALUE + for (j in 0 until m) { + if (max < grid[j][i]) { + max = grid[j][i] + } + } + sum += max + } + return sum - count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0884_uncommon_words_from_two_sentences/readme.md b/src/main/kotlin/g0801_0900/s0884_uncommon_words_from_two_sentences/readme.md new file mode 100644 index 00000000..698917c2 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0884_uncommon_words_from_two_sentences/readme.md @@ -0,0 +1,61 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 884\. Uncommon Words from Two Sentences + +Easy + +A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. + +A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. + +Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_. You may return the answer in **any order**. + +**Example 1:** + +**Input:** s1 = "this apple is sweet", s2 = "this apple is sour" + +**Output:** ["sweet","sour"] + +**Example 2:** + +**Input:** s1 = "apple apple", s2 = "banana" + +**Output:** ["banana"] + +**Constraints:** + +* `1 <= s1.length, s2.length <= 200` +* `s1` and `s2` consist of lowercase English letters and spaces. +* `s1` and `s2` do not have leading or trailing spaces. +* All the words in `s1` and `s2` are separated by a single space. + +## Solution + +```kotlin +class Solution { + fun uncommonFromSentences(s1: String, s2: String): Array { + val visited = HashSet() + val uniques = HashSet() + for (word in s1.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) { + if (!visited.add(word)) { + uniques.remove(word) + } else { + uniques.add(word) + } + } + for (word in s2.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) { + if (!visited.add(word)) { + uniques.remove(word) + } else { + uniques.add(word) + } + } + val arr = arrayOfNulls(uniques.size) + for ((i, word) in uniques.withIndex()) { + arr[i] = word + } + return arr + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0885_spiral_matrix_iii/readme.md b/src/main/kotlin/g0801_0900/s0885_spiral_matrix_iii/readme.md new file mode 100644 index 00000000..9ecfd32f --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0885_spiral_matrix_iii/readme.md @@ -0,0 +1,127 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 885\. Spiral Matrix III + +Medium + +You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. + +You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all `rows * cols` spaces of the grid. + +Return _an array of coordinates representing the positions of the grid in the order you visited them_. + +**Example 1:** + +![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/24/example_1.png) + +**Input:** rows = 1, cols = 4, rStart = 0, cStart = 0 + +**Output:** [[0,0],[0,1],[0,2],[0,3]] + +**Example 2:** + +![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/24/example_2.png) + +**Input:** rows = 5, cols = 6, rStart = 1, cStart = 4 + +**Output:** [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]] + +**Constraints:** + +* `1 <= rows, cols <= 100` +* `0 <= rStart < rows` +* `0 <= cStart < cols` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun spiralMatrixIII(rows: Int, cols: Int, y: Int, x: Int): Array { + var y = y + var x = x + var j: Int + var i = 0 + var moves = 0 + val result = Array(rows * cols) { IntArray(2) } + result[0][0] = y + result[0][1] = x + i++ + while (i < result.size) { + moves++ + // Move right + if (y < 0 || y >= rows) { + x += moves + } else { + j = 0 + while (j < moves) { + x++ + if (x in 0 until cols) { + result[i][0] = y + result[i][1] = x + i++ + } + j++ + } + } + if (i >= result.size) { + break + } + // Move down + if (x < 0 || x >= cols) { + y += moves + } else { + j = 0 + while (j < moves) { + y++ + if (y in 0 until rows) { + result[i][0] = y + result[i][1] = x + i++ + } + j++ + } + } + if (i >= result.size) { + break + } + moves++ + // Move left + if (y < 0 || y >= rows) { + x -= moves + } else { + j = 0 + while (j < moves) { + x-- + if (x in 0 until cols) { + result[i][0] = y + result[i][1] = x + i++ + } + j++ + } + } + if (i >= result.size) { + break + } + // Move up + if (x < 0 || x >= cols) { + y -= moves + } else { + j = 0 + while (j < moves) { + y-- + if (y in 0 until rows) { + result[i][0] = y + result[i][1] = x + i++ + } + j++ + } + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0886_possible_bipartition/readme.md b/src/main/kotlin/g0801_0900/s0886_possible_bipartition/readme.md new file mode 100644 index 00000000..e89bcce0 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0886_possible_bipartition/readme.md @@ -0,0 +1,93 @@ +[![](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) + +## 886\. Possible Bipartition + +Medium + +We want to split a group of `n` people (labeled from `1` to `n`) into two groups of **any size**. Each person may dislike some other people, and they should not go into the same group. + +Given the integer `n` and the array `dislikes` where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return `true` _if it is possible to split everyone into two groups in this way_. + +**Example 1:** + +**Input:** n = 4, dislikes = \[\[1,2],[1,3],[2,4]] + +**Output:** true + +**Explanation:** The first group has [1,4], and the second group has [2,3]. + +**Example 2:** + +**Input:** n = 3, dislikes = \[\[1,2],[1,3],[2,3]] + +**Output:** false + +**Explanation:** We need at least 3 groups to divide them. We cannot put them in two groups. + +**Constraints:** + +* `1 <= n <= 2000` +* 0 <= dislikes.length <= 104 +* `dislikes[i].length == 2` +* 1 <= ai < bi <= n +* All the pairs of `dislikes` are **unique**. + +## Solution + +```kotlin +class Solution { + fun possibleBipartition(n: Int, dislikes: Array): Boolean { + // build graph + val g = Graph(n) + for (dislike in dislikes) { + g.addEdge(dislike[0] - 1, dislike[1] - 1) + } + val marked = BooleanArray(n) + val colors = BooleanArray(n) + for (v in 0 until n) { + if (!marked[v] && !checkBipartiteDFS(g, marked, colors, v)) { + // No need to run on other connected components if one component has failed. + return false + } + } + return true + } + + private fun checkBipartiteDFS(g: Graph, marked: BooleanArray, colors: BooleanArray, v: Int): Boolean { + marked[v] = true + for (w in g.adj(v)) { + if (!marked[w]) { + colors[w] = !colors[v] + if (!checkBipartiteDFS(g, marked, colors, w)) { + // this is to break for other neighbours + return false + } + } else if (colors[v] == colors[w]) { + return false + } + } + return true + } + + private class Graph(v: Int) { + private val adj: Array?> + + init { + adj = arrayOfNulls(v) + for (i in 0 until v) { + adj[i] = ArrayList() + } + } + + fun addEdge(v: Int, w: Int) { + adj[v]!!.add(w) + adj[w]!!.add(v) + } + + fun adj(v: Int): List { + return adj[v]!! + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0887_super_egg_drop/readme.md b/src/main/kotlin/g0801_0900/s0887_super_egg_drop/readme.md new file mode 100644 index 00000000..dfc8f116 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0887_super_egg_drop/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) + +## 887\. Super Egg Drop + +Hard + +You are given `k` identical eggs and you have access to a building with `n` floors labeled from `1` to `n`. + +You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. + +Each move, you may take an unbroken egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may **reuse** it in future moves. + +Return _the **minimum number of moves** that you need to determine **with certainty** what the value of_ `f` is. + +**Example 1:** + +**Input:** k = 1, n = 2 + +**Output:** 2 + +**Explanation:** + +Drop the egg from floor 1. If it breaks, we know that f = 0. + +Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1. + +If it does not break, then we know f = 2. + +Hence, we need at minimum 2 moves to determine with certainty what the value of f is. + +**Example 2:** + +**Input:** k = 2, n = 6 + +**Output:** 3 + +**Example 3:** + +**Input:** k = 3, n = 14 + +**Output:** 4 + +**Constraints:** + +* `1 <= k <= 100` +* 1 <= n <= 104 + +## Solution + +```kotlin +class Solution { + fun superEggDrop(k: Int, n: Int): Int { + val dp = IntArray(k + 1) + var counter = 1 + while (true) { + var temp = dp[0] + for (i in 1 until dp.size) { + val localValue = dp[i] + temp + 1 + temp = dp[i] + dp[i] = localValue + if (localValue >= n) { + return counter + } + } + counter += 1 + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0888_fair_candy_swap/readme.md b/src/main/kotlin/g0801_0900/s0888_fair_candy_swap/readme.md new file mode 100644 index 00000000..70db2676 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0888_fair_candy_swap/readme.md @@ -0,0 +1,68 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 888\. Fair Candy Swap + +Easy + +Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the ith box of candy that Alice has and `bobSizes[j]` is the number of candies of the jth box of candy that Bob has. + +Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. + +Return a_n integer array_ `answer` _where_ `answer[0]` _is the number of candies in the box that Alice must exchange, and_ `answer[1]` _is the number of candies in the box that Bob must exchange_. If there are multiple answers, you may **return any** one of them. It is guaranteed that at least one answer exists. + +**Example 1:** + +**Input:** aliceSizes = [1,1], bobSizes = [2,2] + +**Output:** [1,2] + +**Example 2:** + +**Input:** aliceSizes = [1,2], bobSizes = [2,3] + +**Output:** [1,2] + +**Example 3:** + +**Input:** aliceSizes = [2], bobSizes = [1,3] + +**Output:** [2,3] + +**Constraints:** + +* 1 <= aliceSizes.length, bobSizes.length <= 104 +* 1 <= aliceSizes[i], bobSizes[j] <= 105 +* Alice and Bob have a different total number of candies. +* There will be at least one valid answer for the given input. + +## Solution + +```kotlin +class Solution { + fun fairCandySwap(aliceSizes: IntArray, bobSizes: IntArray): IntArray { + var aSum = 0 + var bSum = 0 + val ans = IntArray(2) + for (bar in aliceSizes) { + aSum += bar + } + for (bar in bobSizes) { + bSum += bar + } + val diff: Int = aSum - bSum + val set: HashSet = HashSet() + for (bar in aliceSizes) { + set.add(bar) + } + for (bar in bobSizes) { + if (set.contains(bar + diff / 2)) { + ans[0] = bar + diff / 2 + ans[1] = bar + break + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0889_construct_binary_tree_from_preorder_and_postorder_traversal/readme.md b/src/main/kotlin/g0801_0900/s0889_construct_binary_tree_from_preorder_and_postorder_traversal/readme.md new file mode 100644 index 00000000..51ff6e10 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0889_construct_binary_tree_from_preorder_and_postorder_traversal/readme.md @@ -0,0 +1,100 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 889\. Construct Binary Tree from Preorder and Postorder Traversal + +Medium + +Given two integer arrays, `preorder` and `postorder` where `preorder` is the preorder traversal of a binary tree of **distinct** values and `postorder` is the postorder traversal of the same tree, reconstruct and return _the binary tree_. + +If there exist multiple answers, you can **return any** of them. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/07/24/lc-prepost.jpg) + +**Input:** preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1] + +**Output:** [1,2,3,4,5,6,7] + +**Example 2:** + +**Input:** preorder = [1], postorder = [1] + +**Output:** [1] + +**Constraints:** + +* `1 <= preorder.length <= 30` +* `1 <= preorder[i] <= preorder.length` +* All the values of `preorder` are **unique**. +* `postorder.length == preorder.length` +* `1 <= postorder[i] <= postorder.length` +* All the values of `postorder` are **unique**. +* It is guaranteed that `preorder` and `postorder` are the preorder traversal and postorder traversal of the same binary 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 constructFromPrePost(preorder: IntArray, postorder: IntArray): TreeNode? { + return if (preorder.isEmpty() || preorder.size != postorder.size) { + null + } else buildTree(preorder, 0, preorder.size - 1, postorder, 0, postorder.size - 1) + } + + private fun buildTree( + preorder: IntArray, + preStart: Int, + preEnd: Int, + postorder: IntArray, + postStart: Int, + postEnd: Int + ): TreeNode? { + if (preStart > preEnd || postStart > postEnd) { + return null + } + val data = preorder[preStart] + val root = TreeNode(data) + if (preStart == preEnd) { + return root + } + var offset = postStart + while (offset <= preEnd) { + if (postorder[offset] == preorder[preStart + 1]) { + break + } + offset++ + } + root.left = buildTree( + preorder, + preStart + 1, + preStart + offset - postStart + 1, + postorder, + postStart, + offset + ) + root.right = buildTree( + preorder, + preStart + offset - postStart + 2, + preEnd, + postorder, + offset + 1, + postEnd - 1 + ) + return root + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0890_find_and_replace_pattern/readme.md b/src/main/kotlin/g0801_0900/s0890_find_and_replace_pattern/readme.md new file mode 100644 index 00000000..e1338e29 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0890_find_and_replace_pattern/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) + +## 890\. Find and Replace Pattern + +Medium + +Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**. + +A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word. + +Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter. + +**Example 1:** + +**Input:** words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" + +**Output:** ["mee","aqq"] + +**Explanation:** "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. "ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter. + +**Example 2:** + +**Input:** words = ["a","b","c"], pattern = "a" + +**Output:** ["a","b","c"] + +**Constraints:** + +* `1 <= pattern.length <= 20` +* `1 <= words.length <= 50` +* `words[i].length == pattern.length` +* `pattern` and `words[i]` are lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun findAndReplacePattern(words: Array, pattern: String): List { + val finalans: MutableList = ArrayList() + if (pattern.length == 1) { + finalans.addAll(words) + return finalans + } + for (word in words) { + val check = CharArray(26) + check.fill('1') + val ans: HashMap = HashMap() + for (j in word.indices) { + val pat = pattern[j] + val wor = word[j] + if (ans.containsKey(pat)) { + if (ans[pat] == wor) { + if (j == word.length - 1) { + finalans.add(word) + } + } else { + break + } + } else { + if (j == word.length - 1 && check[wor.code - 'a'.code] == '1') { + finalans.add(word) + } + if (check[wor.code - 'a'.code] != '1' && check[wor.code - 'a'.code] != pat) { + break + } + if (check[wor.code - 'a'.code] == '1') { + ans[pat] = wor + check[wor.code - 'a'.code] = pat + } + } + } + } + return finalans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0891_sum_of_subsequence_widths/readme.md b/src/main/kotlin/g0801_0900/s0891_sum_of_subsequence_widths/readme.md new file mode 100644 index 00000000..847130eb --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0891_sum_of_subsequence_widths/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) + +## 891\. Sum of Subsequence Widths + +Hard + +The **width** of a sequence is the difference between the maximum and minimum elements in the sequence. + +Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the answer may be very large, return it **modulo** 109 + 7. + +A **subsequence** is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, `[3,6,2,7]` is a subsequence of the array `[0,3,1,6,2,2,7]`. + +**Example 1:** + +**Input:** nums = [2,1,3] + +**Output:** 6 Explanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3]. The corresponding widths are 0, 0, 0, 1, 1, 2, 2. The sum of these widths is 6. + +**Example 2:** + +**Input:** nums = [2] + +**Output:** 0 + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + // 1-6 (number of elements in between 1 and 6) = (6-1-1) = 4 + // length of sub seq 2 -> 4C0 3 -> 4C1 ; 4 -> 4c2 ; 5 -> 4C3 6 -> 4C4 4c0 + 4c1 + 4c2 + 4c3 + + // 4c4 1+4+6+4+1=16 + // 1-5 3c0 + 3c1 + 3c2 + 3c3 = 8 + // 1-4 2c0 + 2c1 2c2 = 4 + // 1-3 1c0 + 1c1 = 2 + // 1-2 1c0 = 1 + /* + 16+8+4+2+1(for 1 as min) 8+4+2+1(for 2 as min) 4+2+1(for 3 as min) 2+1(for 4 as min) 1(for 5 as min) + -1*nums[0]*31 + nums[1]*1 + nums[2]*2 + nums[3]*4 + nums[4]*8 + nums[5]*16 + -1*nums[1]*15 + nums[2]*1 +nums[3]*2 + nums[4]*4 + nums[5]*8 + -1*nums[2]*7 + nums[3]*1 + nums[4]*2 + nums[5]*4 + -1*nums[3]*3 + nums[4]*1 + nums[5]*2 + -1*nums[4]*1 + nums[5]*1 + + -nums[0]*31 + -nums[1]*15 - nums[2]*7 - nums[3]*3 - nums[4]*1 + nums[1]*1 + nums[2]*3 + nums[3]*7 + nums[4]*15 + nums[5]*31 + + (-1)*nums[0]*(pow[6-1-0]-1) + (-1)*nums[1]*(pow[6-1-1]-1) + (-1)*nums[2]*(pow[6-1-2]-1) + ... (-1)* nums[5]*(pow[6-1-5]-1) + + nums[1]*(pow[1]-1) + nums[2]*(pow[2]-1) + .... + nums[5]*(pow[5]-1) + + (-1)*A[i]*(pow[l-1-i]-1) + A[i]*(pow[i]-1) + */ + fun sumSubseqWidths(nums: IntArray): Int { + val mod = 1000000007 + nums.sort() + val l = nums.size + val pow = LongArray(l) + pow[0] = 1 + for (i in 1 until l) { + pow[i] = pow[i - 1] * 2 % mod + } + var res: Long = 0 + for (i in 0 until l) { + res = (res + -1 * nums[i] * (pow[l - 1 - i] - 1) + nums[i] * (pow[i] - 1)) % mod + } + return res.toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0892_surface_area_of_3d_shapes/readme.md b/src/main/kotlin/g0801_0900/s0892_surface_area_of_3d_shapes/readme.md new file mode 100644 index 00000000..945288b4 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0892_surface_area_of_3d_shapes/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) + +## 892\. Surface Area of 3D Shapes + +Easy + +You are given an `n x n` `grid` where you have placed some `1 x 1 x 1` cubes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of cell `(i, j)`. + +After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. + +Return _the total surface area of the resulting shapes_. + +**Note:** The bottom face of each shape counts toward its surface area. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/01/08/tmp-grid2.jpg) + +**Input:** grid = \[\[1,2],[3,4]] + +**Output:** 34 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/01/08/tmp-grid4.jpg) + +**Input:** grid = \[\[1,1,1],[1,0,1],[1,1,1]] + +**Output:** 32 + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/01/08/tmp-grid5.jpg) + +**Input:** grid = \[\[2,2,2],[2,1,2],[2,2,2]] + +**Output:** 46 + +**Constraints:** + +* `n == grid.length == grid[i].length` +* `1 <= n <= 50` +* `0 <= grid[i][j] <= 50` + +## Solution + +```kotlin +class Solution { + fun surfaceArea(grid: Array): Int { + var surfaceArea = 0 + for (i in grid.indices) { + for (j in grid[i].indices) { + if (grid[i][j] > 0) { + surfaceArea += 4 * grid[i][j] + 2 + surfaceArea -= hiddenSides(i, j, grid) + } + } + } + return surfaceArea + } + + private fun hiddenSides(i: Int, j: Int, grid: Array): Int { + var hidden = 0 + val tower = grid[i][j] + if (j + 1 < grid[i].size && grid[i][j + 1] > 0) { + hidden += tower.coerceAtMost(grid[i][j + 1]) + } + if (j - 1 >= 0 && grid[i][j - 1] > 0) { + hidden += tower.coerceAtMost(grid[i][j - 1]) + } + if (i + 1 < grid.size && grid[i + 1][j] > 0) { + hidden += tower.coerceAtMost(grid[i + 1][j]) + } + if (i - 1 >= 0 && grid[i - 1][j] > 0) { + hidden += tower.coerceAtMost(grid[i - 1][j]) + } + return hidden + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0893_groups_of_special_equivalent_strings/readme.md b/src/main/kotlin/g0801_0900/s0893_groups_of_special_equivalent_strings/readme.md new file mode 100644 index 00000000..1a21953b --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0893_groups_of_special_equivalent_strings/readme.md @@ -0,0 +1,80 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 893\. Groups of Special-Equivalent Strings + +Medium + +You are given an array of strings of the same length `words`. + +In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. + +Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. + +* For example, `words[i] = "zzxy"` and `words[j] = "xyzz"` are **special-equivalent** because we may make the moves `"zzxy" -> "xzzy" -> "xyzz"`. + +A **group of special-equivalent strings** from `words` is a non-empty subset of words such that: + +* Every pair of strings in the group are special equivalent, and +* The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group). + +Return _the number of **groups of special-equivalent strings** from_ `words`. + +**Example 1:** + +**Input:** words = ["abcd","cdab","cbad","xyzz","zzxy","zzyx"] + +**Output:** 3 + +**Explanation:** + +One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. + +The other two groups are ["xyzz", "zzxy"] and ["zzyx"]. + +Note that in particular, "zzxy" is not special equivalent to "zzyx". + +**Example 2:** + +**Input:** words = ["abc","acb","bac","bca","cab","cba"] + +**Output:** 3 + +**Constraints:** + +* `1 <= words.length <= 1000` +* `1 <= words[i].length <= 20` +* `words[i]` consist of lowercase English letters. +* All the strings are of the same length. + +## Solution + +```kotlin +class Solution { + fun numSpecialEquivGroups(words: Array): Int { + val set: HashSet = HashSet() + var result = 0 + for (str in words) { + if (set.add(getHashBySwap(str.toCharArray()))) { + result++ + } + } + return result + } + + private fun getHashBySwap(chars: CharArray): String { + for (i in chars.indices) { + var j = i + 2 + while (j < chars.size) { + if (chars[i] > chars[j]) { + val temp = chars[j] + chars[j] = chars[i] + chars[i] = temp + } + j += 2 + } + } + return String(chars) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0894_all_possible_full_binary_trees/readme.md b/src/main/kotlin/g0801_0900/s0894_all_possible_full_binary_trees/readme.md new file mode 100644 index 00000000..e40f3657 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0894_all_possible_full_binary_trees/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) + +## 894\. All Possible Full Binary Trees + +Medium + +Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`. + +Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**. + +A **full binary tree** is a binary tree where each node has exactly `0` or `2` children. + +**Example 1:** + +![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/22/fivetrees.png) + +**Input:** n = 7 + +**Output:** [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]] + +**Example 2:** + +**Input:** n = 3 + +**Output:** [[0,0,0]] + +**Constraints:** + +* `1 <= n <= 20` + +## 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 allPossibleFBT(n: Int): List { + if (n % 2 == 0) { + // no complete binary tree possible + return ArrayList() + } + val dp: Array?> = arrayOfNulls(n + 1) + // form left to right + var i = 1 + while (i <= n) { + helper(i, dp) + i += 2 + } + return dp[n]!! + } + + // Using tabulation + private fun helper(n: Int, dp: Array?>) { + if (n <= 0) { + return + } + if (n == 1) { + dp[1] = ArrayList() + dp[1]!!.add(TreeNode(0)) + return + } + dp[n] = ArrayList() + var i = 1 + while (i < n) { + // left + for (nodeL in dp[i]!!) { + // right + for (nodeR in dp[n - i - 1]!!) { + // 1 node used here + val root = TreeNode(0) + root.left = nodeL + root.right = nodeR + dp[n]!!.add(root) + } + } + i += 2 + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0895_maximum_frequency_stack/readme.md b/src/main/kotlin/g0801_0900/s0895_maximum_frequency_stack/readme.md new file mode 100644 index 00000000..76b0527c --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0895_maximum_frequency_stack/readme.md @@ -0,0 +1,117 @@ +[![](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) + +## 895\. Maximum Frequency Stack + +Hard + +Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. + +Implement the `FreqStack` class: + +* `FreqStack()` constructs an empty frequency stack. +* `void push(int val)` pushes an integer `val` onto the top of the stack. +* `int pop()` removes and returns the most frequent element in the stack. + * If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned. + +**Example 1:** + +**Input** + +["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"] + +[[], [5], [7], [5], [7], [4], [5], [], [], [], []] + +**Output:** [null, null, null, null, null, null, null, 5, 7, 5, 4] + +**Explanation:** + + FreqStack freqStack = new FreqStack(); + freqStack.push(5); // The stack is [5] + freqStack.push(7); // The stack is [5,7] + freqStack.push(5); // The stack is [5,7,5] + freqStack.push(7); // The stack is [5,7,5,7] + freqStack.push(4); // The stack is [5,7,5,7,4] + freqStack.push(5); // The stack is [5,7,5,7,4,5] + freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4]. + freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4]. + freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4]. + freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7]. + +**Constraints:** + +* 0 <= val <= 109 +* At most 2 * 104 calls will be made to `push` and `pop`. +* It is guaranteed that there will be at least one element in the stack before calling `pop`. + +## Solution + +```kotlin +class FreqStack { + private class Node { + var next: Node? + var `val` = 0 + + constructor(`val`: Int) { + this.`val` = `val` + next = null + } + + constructor() { + next = null + } + } + + private class DLL { + var head: Node = Node() + var size: Int = 0 + + fun addNode(x: Int) { + val node = Node(x) + node.next = head.next + head.next = node + size++ + } + + fun removeNode(): Node? { + val node = head.next + if (node != null) { + head.next = node.next + node.next = null + size-- + } + return node + } + } + + private var max = 0 + private val freqMap: HashMap = HashMap() + private val freqListMap: HashMap = HashMap() + + fun push(`val`: Int) { + val count = freqMap.getOrDefault(`val`, 0) + 1 + max = max.coerceAtLeast(count) + freqMap[`val`] = count + val dll = freqListMap.getOrDefault(count, DLL()) + dll.addNode(`val`) + freqListMap[count] = dll + } + + fun pop(): Int { + val dll = freqListMap[max] + val node = dll!!.removeNode() + freqMap[node!!.`val`] = max - 1 + if (dll.size == 0) { + max-- + } + return node.`val` + } +} + +/* + * Your FreqStack object will be instantiated and called as such: + * var obj = FreqStack() + * obj.push(`val`) + * var param_2 = obj.pop() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0896_monotonic_array/readme.md b/src/main/kotlin/g0801_0900/s0896_monotonic_array/readme.md new file mode 100644 index 00000000..c88c6ead --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0896_monotonic_array/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) + +## 896\. Monotonic Array + +Easy + +An array is **monotonic** if it is either monotone increasing or monotone decreasing. + +An array `nums` is monotone increasing if for all `i <= j`, `nums[i] <= nums[j]`. An array `nums` is monotone decreasing if for all `i <= j`, `nums[i] >= nums[j]`. + +Given an integer array `nums`, return `true` _if the given array is monotonic, or_ `false` _otherwise_. + +**Example 1:** + +**Input:** nums = [1,2,2,3] + +**Output:** true + +**Example 2:** + +**Input:** nums = [6,5,4,4] + +**Output:** true + +**Example 3:** + +**Input:** nums = [1,3,2] + +**Output:** false + +**Constraints:** + +* 1 <= nums.length <= 105 +* -105 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun isMonotonic(nums: IntArray): Boolean { + var i = 0 + while (i < nums.size - 1) { + if (nums[i] > nums[i + 1]) { + break + } + i++ + } + if (i == nums.size - 1) { + return true + } + i = 0 + while (i < nums.size - 1) { + if (nums[i] < nums[i + 1]) { + break + } + i++ + } + return i == nums.size - 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0897_increasing_order_search_tree/readme.md b/src/main/kotlin/g0801_0900/s0897_increasing_order_search_tree/readme.md new file mode 100644 index 00000000..16af7cf9 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0897_increasing_order_search_tree/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) + +## 897\. Increasing Order Search Tree + +Easy + +Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/17/ex1.jpg) + +**Input:** root = [5,3,6,2,4,null,8,1,null,null,null,7,9] + +**Output:** [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/11/17/ex2.jpg) + +**Input:** root = [5,1,7] + +**Output:** [1,null,5,null,7] + +**Constraints:** + +* The number of nodes in the given tree will be in the range `[1, 100]`. +* `0 <= Node.val <= 1000` + +## Solution + +```kotlin +import com_github_leetcode.TreeNode +import java.util.LinkedList + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun increasingBST(root: TreeNode?): TreeNode { + val list: MutableList = LinkedList() + traverse(root, list) + for (i in 1 until list.size) { + list[i - 1].right = list[i] + list[i].left = null + } + return list[0] + } + + private fun traverse(root: TreeNode?, list: MutableList) { + if (root != null) { + traverse(root.left, list) + list.add(root) + traverse(root.right, list) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0898_bitwise_ors_of_subarrays/readme.md b/src/main/kotlin/g0801_0900/s0898_bitwise_ors_of_subarrays/readme.md new file mode 100644 index 00000000..263a649d --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0898_bitwise_ors_of_subarrays/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) + +## 898\. Bitwise ORs of Subarrays + +Medium + +Given an integer array `arr`, return _the number of distinct bitwise ORs of all the non-empty subarrays of_ `arr`. + +The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. + +A **subarray** is a contiguous non-empty sequence of elements within an array. + +**Example 1:** + +**Input:** arr = [0] + +**Output:** 1 + +**Explanation:** There is only one possible result: 0. + +**Example 2:** + +**Input:** arr = [1,1,2] + +**Output:** 3 + +**Explanation:** The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2]. + +These yield the results 1, 1, 2, 1, 3, 3. + +There are 3 unique values, so the answer is 3. + +**Example 3:** + +**Input:** arr = [1,2,4] + +**Output:** 6 + +**Explanation:** The possible results are 1, 2, 3, 4, 6, and 7. + +**Constraints:** + +* 1 <= arr.length <= 5 * 104 +* 0 <= arr[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun subarrayBitwiseORs(arr: IntArray): Int { + val set: MutableSet = HashSet() + for (i in arr.indices) { + set.add(arr[i]) + for (j in i - 1 downTo 0) { + if (arr[i] or arr[j] == arr[j]) { + break + } + arr[j] = arr[j] or arr[i] + set.add(arr[j]) + } + } + return set.size + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0899_orderly_queue/readme.md b/src/main/kotlin/g0801_0900/s0899_orderly_queue/readme.md new file mode 100644 index 00000000..1660d09e --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0899_orderly_queue/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) + +## 899\. Orderly Queue + +Hard + +You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string.. + +Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_. + +**Example 1:** + +**Input:** s = "cba", k = 1 + +**Output:** "acb" + +**Explanation:** + +In the first move, we move the 1st character 'c' to the end, obtaining the string "bac". + +In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb". + +**Example 2:** + +**Input:** s = "baaca", k = 3 + +**Output:** "aaabc" + +**Explanation:** + +In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab". + +In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc". + +**Constraints:** + +* `1 <= k <= s.length <= 1000` +* `s` consist of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun orderlyQueue(s: String, k: Int): String { + if (k > 1) { + val ans = s.toCharArray() + ans.sort() + return String(ans) + } + var min = 'z' + val list = ArrayList() + for (element in s) { + if (element < min) { + min = element + } + } + for (i in s.indices) { + if (s[i] == min) { + list.add(i) + } + } + var ans = s + for (integer in list) { + val after = s.substring(0, integer) + val before = s.substring(integer) + val f = before + after + if (f < ans) { + ans = f + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0900_rle_iterator/readme.md b/src/main/kotlin/g0801_0900/s0900_rle_iterator/readme.md new file mode 100644 index 00000000..9f60adfe --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0900_rle_iterator/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) + +## 900\. RLE Iterator + +Medium + +We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. + +* For example, the sequence `arr = [8,8,8,5,5]` can be encoded to be `encoding = [3,8,2,5]`. `encoding = [3,8,0,9,2,5]` and `encoding = [2,8,1,8,2,5]` are also valid **RLE** of `arr`. + +Given a run-length encoded array, design an iterator that iterates through it. + +Implement the `RLEIterator` class: + +* `RLEIterator(int[] encoded)` Initializes the object with the encoded array `encoded`. +* `int next(int n)` Exhausts the next `n` elements and returns the last element exhausted in this way. If there is no element left to exhaust, return `-1` instead. + +**Example 1:** + +**Input** + +["RLEIterator", "next", "next", "next", "next"] + +[[[3, 8, 0, 9, 2, 5]], [2], [1], [1], [2]] + +**Output:** [null, 8, 8, 5, -1] + +**Explanation:** + + RLEIterator rLEIterator = new RLEIterator([3, 8, 0, 9, 2, 5]); // This maps to the sequence [8,8,8,5,5]. + rLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now [8, 5, 5]. + rLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now [5, 5]. + rLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now [5]. + rLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5, + // but the second term did not exist. Since the last term exhausted does not exist, we return -1. + +**Constraints:** + +* `2 <= encoding.length <= 1000` +* `encoding.length` is even. +* 0 <= encoding[i] <= 109 +* 1 <= n <= 109 +* At most `1000` calls will be made to `next`. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class RLEIterator(private val array: IntArray) { + private var index = 0 + fun next(n: Int): Int { + var n = n + var lastElement = -1 + while (n > 0 && index < array.size) { + if (array[index] > n) { + array[index] -= n + lastElement = array[index + 1] + break + } else if (array[index] == n) { + array[index] = 0 + lastElement = array[index + 1] + index += 2 + break + } else { + n -= array[index] + index += 2 + } + } + return lastElement + } +} + +/* + * Your RLEIterator object will be instantiated and called as such: + * var obj = RLEIterator(encoding) + * var param_1 = obj.next(n) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0901_online_stock_span/readme.md b/src/main/kotlin/g0901_1000/s0901_online_stock_span/readme.md new file mode 100644 index 00000000..ff217c50 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0901_online_stock_span/readme.md @@ -0,0 +1,82 @@ +[![](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) + +## 901\. Online Stock Span + +Medium + +Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day. + +The **span** of the stock's price today is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today's price. + +* For example, if the price of a stock over the next `7` days were `[100,80,60,70,60,75,85]`, then the stock spans would be `[1,1,1,2,1,4,6]`. + +Implement the `StockSpanner` class: + +* `StockSpanner()` Initializes the object of the class. +* `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`. + +**Example 1:** + +**Input** + +["StockSpanner", "next", "next", "next", "next", "next", "next", "next"] + +[[], [100], [80], [60], [70], [60], [75], [85]] + +**Output:** [null, 1, 1, 1, 2, 1, 4, 6] + +**Explanation:** + + StockSpanner stockSpanner = new StockSpanner(); + stockSpanner.next(100); // return 1 + stockSpanner.next(80); // return 1 + stockSpanner.next(60); // return 1 + stockSpanner.next(70); // return 2 + stockSpanner.next(60); // return 1 + stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price. + stockSpanner.next(85); // return 6 + +**Constraints:** + +* 1 <= price <= 105 +* At most 104 calls will be made to `next`. + +## Solution + +```kotlin +import java.util.Deque +import java.util.LinkedList + +class StockSpanner { + private val map: MutableMap + private val stocks: Deque + private var index: Int + + init { + stocks = LinkedList() + index = -1 + map = HashMap() + stocks.push(-1) + } + + fun next(price: Int): Int { + if (index != -1) { + stocks.push(index) + } + map[++index] = price + if (stocks.size == 1) { + return index - stocks.peek() + } + while (stocks.size > 1 && map[stocks.peek()]!! <= price) { + stocks.pop() + } + return index - stocks.peek() + } +} +/* + * Your StockSpanner object will be instantiated and called as such: + * var obj = StockSpanner() + * var param_1 = obj.next(price) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0902_numbers_at_most_n_given_digit_set/readme.md b/src/main/kotlin/g0901_1000/s0902_numbers_at_most_n_given_digit_set/readme.md new file mode 100644 index 00000000..01a9a32a --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0902_numbers_at_most_n_given_digit_set/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 902\. Numbers At Most N Given Digit Set + +Hard + +Given an array of `digits` which is sorted in **non-decreasing** order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`. + +Return _the number of positive integers that can be generated_ that are less than or equal to a given integer `n`. + +**Example 1:** + +**Input:** digits = ["1","3","5","7"], n = 100 + +**Output:** 20 + +**Explanation:** The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. + +**Example 2:** + +**Input:** digits = ["1","4","9"], n = 1000000000 + +**Output:** 29523 + +**Explanation:** We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. + +**Example 3:** + +**Input:** digits = ["7"], n = 8 + +**Output:** 1 + +**Constraints:** + +* `1 <= digits.length <= 9` +* `digits[i].length == 1` +* `digits[i]` is a digit from `'1'` to `'9'`. +* All the values in `digits` are **unique**. +* `digits` is sorted in **non-decreasing** order. +* 1 <= n <= 109 + +## Solution + +```kotlin +import kotlin.math.pow + +class Solution { + fun atMostNGivenDigitSet(digits: Array, n: Int): Int { + var ans = 0 + val num = "" + n + val d = digits.size + val l = num.length + for (i in 1 until l) { + ans += d.toDouble().pow(i.toDouble()).toInt() + } + for (i in 0 until l) { + var flag = false + for (digit in digits) { + if (digit[0] < num[i]) { + ans += d.toDouble().pow((l - i - 1) * 1.0).toInt() + } else if (num[i] == digit[0]) { + flag = true + break + } + } + if (!flag) { + return ans + } + } + return ans + 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0903_valid_permutations_for_di_sequence/readme.md b/src/main/kotlin/g0901_1000/s0903_valid_permutations_for_di_sequence/readme.md new file mode 100644 index 00000000..67f8ff5e --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0903_valid_permutations_for_di_sequence/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 903\. Valid Permutations for DI Sequence + +Hard + +You are given a string `s` of length `n` where `s[i]` is either: + +* `'D'` means decreasing, or +* `'I'` means increasing. + +A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` is called a **valid permutation** if for all valid `i`: + +* If `s[i] == 'D'`, then `perm[i] > perm[i + 1]`, and +* If `s[i] == 'I'`, then `perm[i] < perm[i + 1]`. + +Return _the number of **valid permutations**_ `perm`. Since the answer may be large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** s = "DID" + +**Output:** 5 + +**Explanation:** The 5 valid permutations of (0, 1, 2, 3) are: + + (1, 0, 3, 2) + (2, 0, 3, 1) + (2, 1, 3, 0) + (3, 0, 2, 1) + (3, 1, 2, 0) + +**Example 2:** + +**Input:** s = "D" + +**Output:** 1 + +**Constraints:** + +* `n == s.length` +* `1 <= n <= 200` +* `s[i]` is either `'I'` or `'D'`. + +## Solution + +```kotlin +class Solution { + fun numPermsDISequence(s: String): Int { + val n = s.length + val mod = 1e9.toInt() + 7 + val dp = Array(n + 1) { IntArray(n + 1) } + for (j in 0..n) { + dp[0][j] = 1 + } + for (i in 0 until n) { + var cur = 0 + if (s[i] == 'I') { + for (j in 0 until n - i) { + cur = (cur + dp[i][j]) % mod + dp[i + 1][j] = cur + } + } else { + for (j in n - i - 1 downTo 0) { + cur = (cur + dp[i][j + 1]) % mod + dp[i + 1][j] = cur + } + } + } + return dp[n][0] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0904_fruit_into_baskets/readme.md b/src/main/kotlin/g0901_1000/s0904_fruit_into_baskets/readme.md new file mode 100644 index 00000000..f81ef8ee --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0904_fruit_into_baskets/readme.md @@ -0,0 +1,84 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 904\. Fruit Into Baskets + +Medium + +You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the ith tree produces. + +You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: + +* You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold. +* Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. +* Once you reach a tree with fruit that cannot fit in your baskets, you must stop. + +Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_. + +**Example 1:** + +**Input:** fruits = [1,2,1] + +**Output:** 3 + +**Explanation:** We can pick from all 3 trees. + +**Example 2:** + +**Input:** fruits = [0,1,2,2] + +**Output:** 3 + +**Explanation:** We can pick from trees [1,2,2]. If we had started at the first tree, we would only pick from trees [0,1]. + +**Example 3:** + +**Input:** fruits = [1,2,3,2,2] + +**Output:** 4 + +**Explanation:** We can pick from trees [2,3,2,2]. If we had started at the first tree, we would only pick from trees [1,2]. + +**Constraints:** + +* 1 <= fruits.length <= 105 +* `0 <= fruits[i] < fruits.length` + +## Solution + +```kotlin +class Solution { + fun totalFruit(fruits: IntArray): Int { + var end = 1 + var basket1 = fruits[0] + var basket2 = -1 + var secondFruitIndex = -1 + var maxTotal = 1 + var counter = 1 + while (end < fruits.size) { + if (fruits[end - 1] != fruits[end]) { + if (basket2 == -1) { + basket2 = fruits[end] + secondFruitIndex = end + counter++ + } else if (fruits[end] == basket1) { + basket1 = basket2 + basket2 = fruits[end] + secondFruitIndex = end + counter++ + } else { + counter = end - secondFruitIndex + 1 + basket1 = basket2 + basket2 = fruits[end] + secondFruitIndex = end + } + } else { + counter++ + } + end++ + maxTotal = maxTotal.coerceAtLeast(counter) + } + return maxTotal + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0905_sort_array_by_parity/readme.md b/src/main/kotlin/g0901_1000/s0905_sort_array_by_parity/readme.md new file mode 100644 index 00000000..2ff6624f --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0905_sort_array_by_parity/readme.md @@ -0,0 +1,49 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 905\. Sort Array By Parity + +Easy + +Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers. + +Return _**any array** that satisfies this condition_. + +**Example 1:** + +**Input:** nums = [3,1,2,4] + +**Output:** [2,4,3,1] + +**Explanation:** The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. + +**Example 2:** + +**Input:** nums = [0] + +**Output:** [0] + +**Constraints:** + +* `1 <= nums.length <= 5000` +* `0 <= nums[i] <= 5000` + +## Solution + +```kotlin +class Solution { + fun sortArrayByParity(nums: IntArray): IntArray { + var temp: Int + var i = 0 + for (k in nums.indices) { + if (nums[k] % 2 == 0) { + temp = nums[k] + nums[k] = nums[i] + nums[i] = temp + i++ + } + } + return nums + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0906_super_palindromes/readme.md b/src/main/kotlin/g0901_1000/s0906_super_palindromes/readme.md new file mode 100644 index 00000000..4772d371 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0906_super_palindromes/readme.md @@ -0,0 +1,96 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 906\. Super Palindromes + +Hard + +Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome. + +Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`. + +**Example 1:** + +**Input:** left = "4", right = "1000" + +**Output:** 4 + +**Explanation:**: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome. + +**Example 2:** + +**Input:** left = "1", right = "2" + +**Output:** 1 + +**Constraints:** + +* `1 <= left.length, right.length <= 18` +* `left` and `right` consist of only digits. +* `left` and `right` cannot have leading zeros. +* `left` and `right` represent integers in the range [1, 1018 - 1]. +* `left` is less than or equal to `right`. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun superpalindromesInRange(left: String, right: String): Int { + val l = left.toLong() + val r = right.toLong() + var cnt = 0 + var cur: Long = 1 + while (true) { + val p1 = getPalindromeIncLastDigit(cur) + val p2 = getPalindromeExcLastDigit(cur) + val sq1 = p1 * p1 + val sq2 = p2 * p2 + if (sq2 > r) { + break + } + if (sq1 in l..r && isPalindrome(sq1)) { + cnt++ + } + if (sq2 >= l && isPalindrome(sq2)) { + cnt++ + } + cur++ + } + return cnt + } + + private fun isPalindrome(`val`: Long): Boolean { + var `val` = `val` + var construct: Long = 0 + if (`val` % 10 == 0L && `val` >= 10) { + return false + } + while (construct < `val`) { + construct = construct * 10 + `val` % 10 + `val` /= 10 + } + return construct == `val` || construct / 10 == `val` + } + + private fun getPalindromeIncLastDigit(`val`: Long): Long { + var `val` = `val` + var copy = `val` + while (copy != 0L) { + `val` = `val` * 10 + copy % 10 + copy /= 10 + } + return `val` + } + + private fun getPalindromeExcLastDigit(`val`: Long): Long { + var `val` = `val` + var copy = `val` / 10 + while (copy != 0L) { + `val` = `val` * 10 + copy % 10 + copy /= 10 + } + return `val` + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0907_sum_of_subarray_minimums/readme.md b/src/main/kotlin/g0901_1000/s0907_sum_of_subarray_minimums/readme.md new file mode 100644 index 00000000..f28f0235 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0907_sum_of_subarray_minimums/readme.md @@ -0,0 +1,82 @@ +[![](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) + +## 907\. Sum of Subarray Minimums + +Medium + +Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** 109 + 7. + +**Example 1:** + +**Input:** arr = [3,1,2,4] + +**Output:** 17 + +**Explanation:** + +Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. + +Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. + +Sum is 17. + +**Example 2:** + +**Input:** arr = [11,81,94,43,3] + +**Output:** 444 + +**Constraints:** + +* 1 <= arr.length <= 3 * 104 +* 1 <= arr[i] <= 3 * 104 + +## Solution + +```kotlin +class Solution { + private fun calculateRight(i: Int, start: Int, right: IntArray, arr: IntArray, len: Int): Int { + if (start >= len) { + return 0 + } + return if (arr[start] < arr[i]) { + 0 + } else (1 + right[start] + calculateRight(i, start + right[start] + 1, right, arr, len)) % MOD + } + + private fun calculateLeft(i: Int, start: Int, left: IntArray, arr: IntArray, len: Int): Int { + if (start < 0) { + return 0 + } + return if (arr[start] <= arr[i]) { + 0 + } else (1 + left[start] + calculateLeft(i, start - left[start] - 1, left, arr, len)) % MOD + } + + fun sumSubarrayMins(arr: IntArray): Int { + val len = arr.size + val right = IntArray(len) + val left = IntArray(len) + right[len - 1] = 0 + for (i in len - 2 downTo 0) { + right[i] = calculateRight(i, i + 1, right, arr, len) + } + left[0] = 0 + for (i in 1 until len) { + left[i] = calculateLeft(i, i - 1, left, arr, len) + } + var answer = 0 + for (i in 0 until len) { + val model: Long = 1000000007 + answer += ((1 + left[i]) * (1 + right[i]).toLong() % model * arr[i] % model).toInt() + answer %= MOD + } + return answer + } + + companion object { + private const val MOD = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0908_smallest_range_i/readme.md b/src/main/kotlin/g0901_1000/s0908_smallest_range_i/readme.md new file mode 100644 index 00000000..de5a729e --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0908_smallest_range_i/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) + +## 908\. Smallest Range I + +Easy + +You are given an integer array `nums` and an integer `k`. + +In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index `i`. + +The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. + +Return _the minimum **score** of_ `nums` _after applying the mentioned operation at most once for each index in it_. + +**Example 1:** + +**Input:** nums = [1], k = 0 + +**Output:** 0 + +**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. + +**Example 2:** + +**Input:** nums = [0,10], k = 2 + +**Output:** 6 + +**Explanation:** Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6. + +**Example 3:** + +**Input:** nums = [1,3,6], k = 3 + +**Output:** 0 + +**Explanation:** Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0. + +**Constraints:** + +* 1 <= nums.length <= 104 +* 0 <= nums[i] <= 104 +* 0 <= k <= 104 + +## Solution + +```kotlin +class Solution { + fun smallestRangeI(nums: IntArray, k: Int): Int { + var min = Int.MAX_VALUE + var max = Int.MIN_VALUE + for (num in nums) { + min = min.coerceAtMost(num) + max = max.coerceAtLeast(num) + } + return if (min + k >= max - k) { + 0 + } else max - k - (min + k) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0909_snakes_and_ladders/readme.md b/src/main/kotlin/g0901_1000/s0909_snakes_and_ladders/readme.md new file mode 100644 index 00000000..269eebf3 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0909_snakes_and_ladders/readme.md @@ -0,0 +1,111 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 909\. Snakes and Ladders + +Medium + +You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to n2 in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row. + +You start on square `1` of the board. In each move, starting from square `curr`, do the following: + +* Choose a destination square `next` with a label in the range [curr + 1, min(curr + 6, n2)]. + * This choice simulates the result of a standard **6-sided die roll**: i.e., there are always at most 6 destinations, regardless of the size of the board. +* If `next` has a snake or ladder, you **must** move to the destination of that snake or ladder. Otherwise, you move to `next`. +* The game ends when you reach the square n2. + +A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and n2 do not have a snake or ladder. + +Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do **not** follow the subsequent snake or ladder. + +* For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do **not** follow the subsequent ladder to `4`. + +Return _the least number of moves required to reach the square_ n2_. If it is not possible to reach the square, return_ `-1`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2018/09/23/snakes.png) + +**Input:** board = \[\[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]] + +**Output:** 4 + +**Explanation:** + +In the beginning, you start at square 1 (at row 5, column 0). + +You decide to move to square 2 and must take the ladder to square 15. + +You then decide to move to square 17 and must take the snake to square 13. + +You then decide to move to square 14 and must take the ladder to square 35. + +You then decide to move to square 36, ending the game. + +This is the lowest possible number of moves to reach the last square, so return 4. + +**Example 2:** + +**Input:** board = \[\[-1,-1],[-1,3]] + +**Output:** 1 + +**Constraints:** + +* `n == board.length == board[i].length` +* `2 <= n <= 20` +* `grid[i][j]` is either `-1` or in the range [1, n2]. +* The squares labeled `1` and n2 do not have any ladders or snakes. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + private var size = 0 + fun snakesAndLadders(board: Array): Int { + val queue: Queue = LinkedList() + size = board.size + val target = size * size + val visited = BooleanArray(target) + queue.add(1) + visited[0] = true + var step = 0 + while (!queue.isEmpty()) { + val queueSize = queue.size + for (i in 0 until queueSize) { + val previousLabel = queue.poll() + if (previousLabel == target) { + return step + } + for (currentLabel in previousLabel + 1..Math.min(target, previousLabel + 6)) { + if (visited[currentLabel - 1]) { + continue + } + visited[currentLabel - 1] = true + val position = indexToPosition(currentLabel) + if (board[position[0]][position[1]] == -1) { + queue.add(currentLabel) + } else { + queue.add(board[position[0]][position[1]]) + } + } + } + step++ + } + return -1 + } + + private fun indexToPosition(index: Int): IntArray { + val vertical = size - 1 - (index - 1) / size + val horizontal: Int = if ((size - vertical) % 2 == 1) { + (index - 1) % size + } else { + size - 1 - (index - 1) % size + } + return intArrayOf(vertical, horizontal) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0910_smallest_range_ii/readme.md b/src/main/kotlin/g0901_1000/s0910_smallest_range_ii/readme.md new file mode 100644 index 00000000..5e4b9487 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0910_smallest_range_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) + +## 910\. Smallest Range II + +Medium + +You are given an integer array `nums` and an integer `k`. + +For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`. + +The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. + +Return _the minimum **score** of_ `nums` _after changing the values at each index_. + +**Example 1:** + +**Input:** nums = [1], k = 0 + +**Output:** 0 + +**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. + +**Example 2:** + +**Input:** nums = [0,10], k = 2 + +**Output:** 6 + +**Explanation:** Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6. + +**Example 3:** + +**Input:** nums = [1,3,6], k = 3 + +**Output:** 3 + +**Explanation:** Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3. + +**Constraints:** + +* 1 <= nums.length <= 104 +* 0 <= nums[i] <= 104 +* 0 <= k <= 104 + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun smallestRangeII(nums: IntArray, k: Int): Int { + Arrays.sort(nums) + val n = nums.size + var ans = nums[n - 1] - nums[0] + val min = nums[0] + k + val max = nums[n - 1] - k + for (i in 0 until n - 1) { + val mx = max.coerceAtLeast(nums[i] + k) + val mi = min.coerceAtMost(nums[i + 1] - k) + ans = ans.coerceAtMost(mx - mi) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0911_online_election/readme.md b/src/main/kotlin/g0901_1000/s0911_online_election/readme.md new file mode 100644 index 00000000..5af5f269 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0911_online_election/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) + +## 911\. Online Election + +Medium + +You are given two integer arrays `persons` and `times`. In an election, the ith vote was cast for `persons[i]` at time `times[i]`. + +For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast at time `t` will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. + +Implement the `TopVotedCandidate` class: + +* `TopVotedCandidate(int[] persons, int[] times)` Initializes the object with the `persons` and `times` arrays. +* `int q(int t)` Returns the number of the person that was leading the election at time `t` according to the mentioned rules. + +**Example 1:** + +**Input** ["TopVotedCandidate", "q", "q", "q", "q", "q", "q"] [[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]] + +**Output:** [null, 0, 1, 1, 0, 0, 1] + +**Explanation:** + + TopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]); + topVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading. + topVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading. + topVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.) + topVotedCandidate.q(15); // return 0 + topVotedCandidate.q(24); // return 0 + topVotedCandidate.q(8); // return 1 + +**Constraints:** + +* `1 <= persons.length <= 5000` +* `times.length == persons.length` +* `0 <= persons[i] < persons.length` +* 0 <= times[i] <= 109 +* `times` is sorted in a strictly increasing order. +* times[0] <= t <= 109 +* At most 104 calls will be made to `q`. + +## Solution + +```kotlin +class TopVotedCandidate(persons: IntArray, private val times: IntArray) { + private val winnersAtTimeT: IntArray = IntArray(times.size) + + init { + val counterArray = IntArray(persons.size) + var maxVote = 0 + var maxVotedPerson = 0 + for (i in persons.indices) { + val person = persons[i] + val voteCount = counterArray[person] + if (voteCount + 1 >= maxVote) { + maxVote = voteCount + 1 + maxVotedPerson = person + } + winnersAtTimeT[i] = maxVotedPerson + counterArray[persons[i]] = voteCount + 1 + } + } + + fun q(t: Int): Int { + var lo = 0 + var hi = times.size - 1 + if (t >= times[hi]) { + lo = hi + } else { + while (lo < hi - 1) { + val mid = lo + (hi - lo) / 2 + if (times[mid] == t) { + lo = mid + break + } else if (times[mid] > t) { + hi = mid + } else { + lo = mid + } + } + } + return winnersAtTimeT[lo] + } +} + +/** + * Your TopVotedCandidate object will be instantiated and called as such: + * var obj = TopVotedCandidate(persons, times) + * var param_1 = obj.q(t) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0912_sort_an_array/readme.md b/src/main/kotlin/g0901_1000/s0912_sort_an_array/readme.md new file mode 100644 index 00000000..2644e2b7 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0912_sort_an_array/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 912\. Sort an Array + +Medium + +Given an array of integers `nums`, sort the array in ascending order and return it. + +You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible. + +**Example 1:** + +**Input:** nums = [5,2,3,1] + +**Output:** [1,2,3,5] + +**Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5). + +**Example 2:** + +**Input:** nums = [5,1,1,2,0,0] + +**Output:** [0,0,1,1,2,5] + +**Explanation:** Note that the values of nums are not necessairly unique. + +**Constraints:** + +* 1 <= nums.length <= 5 * 104 +* -5 * 104 <= nums[i] <= 5 * 104 + +## Solution + +```kotlin +class Solution { + fun sortArray(nums: IntArray): IntArray { + return mergeSort(nums, 0, nums.size - 1) + } + + private fun mergeSort(arr: IntArray, lo: Int, hi: Int): IntArray { + if (lo == hi) { + val sortedArr = IntArray(1) + sortedArr[0] = arr[lo] + return sortedArr + } + val mid = (lo + hi) / 2 + val leftArray = mergeSort(arr, lo, mid) + val rightArray = mergeSort(arr, mid + 1, hi) + return mergeSortedArray(leftArray, rightArray) + } + + private fun mergeSortedArray(a: IntArray, b: IntArray): IntArray { + val ans = IntArray(a.size + b.size) + var i = 0 + var j = 0 + var k = 0 + while (i < a.size && j < b.size) { + if (a[i] < b[j]) { + ans[k++] = a[i++] + } else { + ans[k++] = b[j++] + } + } + while (i < a.size) { + ans[k++] = a[i++] + } + while (j < b.size) { + ans[k++] = b[j++] + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0913_cat_and_mouse/readme.md b/src/main/kotlin/g0901_1000/s0913_cat_and_mouse/readme.md new file mode 100644 index 00000000..94d99a18 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0913_cat_and_mouse/readme.md @@ -0,0 +1,136 @@ +[![](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) + +## 913\. Cat and Mouse + +Hard + +A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns. + +The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph. + +The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`. + +During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`. + +Additionally, it is not allowed for the Cat to travel to the Hole (node 0.) + +Then, the game can end in three ways: + +* If ever the Cat occupies the same node as the Mouse, the Cat wins. +* If ever the Mouse reaches the Hole, the Mouse wins. +* If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw. + +Given a `graph`, and assuming both players play optimally, return + +* `1` if the mouse wins the game, +* `2` if the cat wins the game, or +* `0` if the game is a draw. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/17/cat1.jpg) + +**Input:** graph = \[\[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]] + +**Output:** 0 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/11/17/cat2.jpg) + +**Input:** graph = \[\[1,3],[0],[3],[0,2]] + +**Output:** 1 + +**Constraints:** + +* `3 <= graph.length <= 50` +* `1 <= graph[i].length < graph.length` +* `0 <= graph[i][j] < graph.length` +* `graph[i][j] != i` +* `graph[i]` is unique. +* The mouse and the cat can always move. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + fun catMouseGame(graph: Array): Int { + val n = graph.size + val states = Array(n) { + Array(n) { + IntArray( + 2 + ) + } + } + val degree = Array(n) { + Array(n) { + IntArray( + 2 + ) + } + } + for (m in 0 until n) { + for (c in 0 until n) { + degree[m][c][MOUSE] = graph[m].size + degree[m][c][CAT] = graph[c].size + for (node in graph[c]) { + if (node == 0) { + --degree[m][c][CAT] + break + } + } + } + } + val q: Queue = LinkedList() + for (i in 1 until n) { + states[0][i][MOUSE] = MOUSE_WIN + states[0][i][CAT] = MOUSE_WIN + states[i][i][MOUSE] = CAT_WIN + states[i][i][CAT] = CAT_WIN + q.offer(intArrayOf(0, i, MOUSE, MOUSE_WIN)) + q.offer(intArrayOf(i, i, MOUSE, CAT_WIN)) + q.offer(intArrayOf(0, i, CAT, MOUSE_WIN)) + q.offer(intArrayOf(i, i, CAT, CAT_WIN)) + } + while (!q.isEmpty()) { + val state = q.poll() + val mouse = state[0] + val cat = state[1] + val turn = state[2] + val result = state[3] + if (mouse == 1 && cat == 2 && turn == MOUSE) { + return result + } + val prevTurn = 1 - turn + for (prev in graph[if (prevTurn == MOUSE) mouse else cat]) { + val prevMouse = if (prevTurn == MOUSE) prev else mouse + val prevCat = if (prevTurn == CAT) prev else cat + if (prevCat != 0 && states[prevMouse][prevCat][prevTurn] == DRAW && + ( + prevTurn == MOUSE && result == MOUSE_WIN || prevTurn == CAT && result == CAT_WIN || + --degree[prevMouse][prevCat][prevTurn] == 0 + ) + ) { + states[prevMouse][prevCat][prevTurn] = result + q.offer(intArrayOf(prevMouse, prevCat, prevTurn, result)) + } + } + } + return DRAW + } + + companion object { + private const val DRAW = 0 + private const val MOUSE_WIN = 1 + private const val CAT_WIN = 2 + private const val MOUSE = 0 + private const val CAT = 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0914_x_of_a_kind_in_a_deck_of_cards/readme.md b/src/main/kotlin/g0901_1000/s0914_x_of_a_kind_in_a_deck_of_cards/readme.md new file mode 100644 index 00000000..cf18cbc7 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0914_x_of_a_kind_in_a_deck_of_cards/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) + +## 914\. X of a Kind in a Deck of Cards + +Easy + +You are given an integer array `deck` where `deck[i]` represents the number written on the ith card. + +Partition the cards into **one or more groups** such that: + +* Each group has **exactly** `x` cards where `x > 1`, and +* All the cards in one group have the same integer written on them. + +Return `true` _if such partition is possible, or_ `false` _otherwise_. + +**Example 1:** + +**Input:** deck = [1,2,3,4,4,3,2,1] + +**Output:** true + +**Explanation:**: Possible partition [1,1],[2,2],[3,3],[4,4]. + +**Example 2:** + +**Input:** deck = [1,1,1,2,2,2,3,3] + +**Output:** false + +**Explanation:**: No possible partition. + +**Constraints:** + +* 1 <= deck.length <= 104 +* 0 <= deck[i] < 104 + +## Solution + +```kotlin +class Solution { + fun hasGroupsSizeX(deck: IntArray): Boolean { + val map: HashMap = HashMap() + for (j in deck) { + if (map.containsKey(j)) { + map[j] = map[j]!! + 1 + } else { + map[j] = 1 + } + } + var x = map[deck[0]]!! + + for (entry in map.entries.iterator()) { + x = gcd(x, entry.value) + } + return x >= 2 + } + + private fun gcd(a: Int, b: Int): Int { + return if (b == 0) { + a + } else gcd(b, a % b) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0915_partition_array_into_disjoint_intervals/readme.md b/src/main/kotlin/g0901_1000/s0915_partition_array_into_disjoint_intervals/readme.md new file mode 100644 index 00000000..612712ad --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0915_partition_array_into_disjoint_intervals/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) + +## 915\. Partition Array into Disjoint Intervals + +Medium + +Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: + +* Every element in `left` is less than or equal to every element in `right`. +* `left` and `right` are non-empty. +* `left` has the smallest possible size. + +Return _the length of_ `left` _after such a partitioning_. + +Test cases are generated such that partitioning exists. + +**Example 1:** + +**Input:** nums = [5,0,3,8,6] + +**Output:** 3 + +**Explanation:** left = [5,0,3], right = [8,6] + +**Example 2:** + +**Input:** nums = [1,1,1,0,6,12] + +**Output:** 4 + +**Explanation:** left = [1,1,1,0], right = [6,12] + +**Constraints:** + +* 2 <= nums.length <= 105 +* 0 <= nums[i] <= 106 +* There is at least one valid answer for the given input. + +## Solution + +```kotlin +class Solution { + fun partitionDisjoint(nums: IntArray): Int { + var res = 0 + var leftMax = nums[0] + var greater = nums[0] + for (i in 1 until nums.size) { + if (greater <= nums[i]) { + greater = nums[i] + } else if (nums[i] < leftMax) { + res = i + leftMax = greater + } + } + return res + 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0916_word_subsets/readme.md b/src/main/kotlin/g0901_1000/s0916_word_subsets/readme.md new file mode 100644 index 00000000..c2be7acc --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0916_word_subsets/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) + +## 916\. Word Subsets + +Medium + +You are given two string arrays `words1` and `words2`. + +A string `b` is a **subset** of string `a` if every letter in `b` occurs in `a` including multiplicity. + +* For example, `"wrr"` is a subset of `"warrior"` but is not a subset of `"world"`. + +A string `a` from `words1` is **universal** if for every string `b` in `words2`, `b` is a subset of `a`. + +Return an array of all the **universal** strings in `words1`. You may return the answer in **any order**. + +**Example 1:** + +**Input:** words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"] + +**Output:** ["facebook","google","leetcode"] + +**Example 2:** + +**Input:** words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["l","e"] + +**Output:** ["apple","google","leetcode"] + +**Constraints:** + +* 1 <= words1.length, words2.length <= 104 +* `1 <= words1[i].length, words2[i].length <= 10` +* `words1[i]` and `words2[i]` consist only of lowercase English letters. +* All the strings of `words1` are **unique**. + +## Solution + +```kotlin +class Solution { + fun wordSubsets(words1: Array, words2: Array): List { + val l1: MutableList = ArrayList() + val target = IntArray(26) + for (s1 in words2) { + val temp = IntArray(26) + for (ch1 in s1.toCharArray()) { + temp[ch1.code - 'a'.code]++ + target[ch1.code - 'a'.code] = + target[ch1.code - 'a'.code].coerceAtLeast(temp[ch1.code - 'a'.code]) + } + } + for (s1 in words1) { + val count = IntArray(26) + for (ch1 in s1.toCharArray()) { + count[ch1.code - 'a'.code]++ + } + if (checkIt(target, count)) { + l1.add(s1) + } + } + return l1 + } + + private fun checkIt(target: IntArray, count: IntArray): Boolean { + for (i in 0..25) { + if (count[i] < target[i]) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0917_reverse_only_letters/readme.md b/src/main/kotlin/g0901_1000/s0917_reverse_only_letters/readme.md new file mode 100644 index 00000000..dae3568c --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0917_reverse_only_letters/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) + +## 917\. Reverse Only Letters + +Easy + +Given a string `s`, reverse the string according to the following rules: + +* All the characters that are not English letters remain in the same position. +* All the English letters (lowercase or uppercase) should be reversed. + +Return `s` _after reversing it_. + +**Example 1:** + +**Input:** s = "ab-cd" + +**Output:** "dc-ba" + +**Example 2:** + +**Input:** s = "a-bC-dEf-ghIj" + +**Output:** "j-Ih-gfE-dCba" + +**Example 3:** + +**Input:** s = "Test1ng-Leet=code-Q!" + +**Output:** "Qedo1ct-eeLg=ntse-T!" + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` consists of characters with ASCII values in the range `[33, 122]`. +* `s` does not contain `'\"'` or `'\\'`. + +## Solution + +```kotlin +class Solution { + fun reverseOnlyLetters(s: String): String { + val array = s.toCharArray() + var i = 0 + var j = array.size - 1 + while (i < j) { + if (Character.isLetter(array[i]) && Character.isLetter(array[j])) { + val temp = array[i] + array[i++] = array[j] + array[j--] = temp + } else if (Character.isLetter(array[i])) { + j-- + } else if (Character.isLetter(array[j])) { + i++ + } else { + i++ + j-- + } + } + return String(array) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray/readme.md b/src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray/readme.md new file mode 100644 index 00000000..8f26384b --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray/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) + +## 918\. Maximum Sum Circular Subarray + +Medium + +Given a **circular integer array** `nums` of length `n`, return _the maximum possible sum of a non-empty **subarray** of_ `nums`. + +A **circular array** means the end of the array connects to the beginning of the array. Formally, the next element of `nums[i]` is `nums[(i + 1) % n]` and the previous element of `nums[i]` is `nums[(i - 1 + n) % n]`. + +A **subarray** may only include each element of the fixed buffer `nums` at most once. Formally, for a subarray `nums[i], nums[i + 1], ..., nums[j]`, there does not exist `i <= k1`, `k2 <= j` with `k1 % n == k2 % n`. + +**Example 1:** + +**Input:** nums = [1,-2,3,-2] + +**Output:** 3 + +**Explanation:** Subarray [3] has maximum sum 3. + +**Example 2:** + +**Input:** nums = [5,-3,5] + +**Output:** 10 + +**Explanation:** Subarray [5,5] has maximum sum 5 + 5 = 10. + +**Example 3:** + +**Input:** nums = [-3,-2,-3] + +**Output:** -2 + +**Explanation:** Subarray [-2] has maximum sum -2. + +**Constraints:** + +* `n == nums.length` +* 1 <= n <= 3 * 104 +* -3 * 104 <= nums[i] <= 3 * 104 + +## Solution + +```kotlin +class Solution { + private fun kadane(nums: IntArray, sign: Int): Int { + var currSum = Int.MIN_VALUE + var maxSum = Int.MIN_VALUE + for (i in nums) { + currSum = sign * i + currSum.coerceAtLeast(0) + maxSum = maxSum.coerceAtLeast(currSum) + } + return maxSum + } + + fun maxSubarraySumCircular(nums: IntArray): Int { + if (nums.size == 1) { + return nums[0] + } + var sumOfArray = 0 + for (i in nums) { + sumOfArray += i + } + val maxSumSubarray = kadane(nums, 1) + val minSumSubarray = kadane(nums, -1) * -1 + return if (sumOfArray == minSumSubarray) { + maxSumSubarray + } else { + maxSumSubarray.coerceAtLeast(sumOfArray - minSumSubarray) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0919_complete_binary_tree_inserter/readme.md b/src/main/kotlin/g0901_1000/s0919_complete_binary_tree_inserter/readme.md new file mode 100644 index 00000000..b2ec288a --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0919_complete_binary_tree_inserter/readme.md @@ -0,0 +1,122 @@ +[![](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) + +## 919\. Complete Binary Tree Inserter + +Medium + +A **complete binary tree** is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. + +Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion. + +Implement the `CBTInserter` class: + +* `CBTInserter(TreeNode root)` Initializes the data structure with the `root` of the complete binary tree. +* `int insert(int v)` Inserts a `TreeNode` into the tree with value `Node.val == val` so that the tree remains complete, and returns the value of the parent of the inserted `TreeNode`. +* `TreeNode get_root()` Returns the root node of the tree. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/08/03/lc-treeinsert.jpg) + +**Input** ["CBTInserter", "insert", "insert", "get\_root"] [[[1, 2]], [3], [4], []] + +**Output:** [null, 1, 2, [1, 2, 3, 4]] + +**Explanation:** + + CBTInserter cBTInserter = new CBTInserter([1, 2]); + cBTInserter.insert(3); // return 1 + cBTInserter.insert(4); // return 2 + cBTInserter.get\_root(); // return [1, 2, 3, 4] + +**Constraints:** + +* The number of nodes in the tree will be in the range `[1, 1000]`. +* `0 <= Node.val <= 5000` +* `root` is a complete binary tree. +* `0 <= val <= 5000` +* At most 104 calls will be made to `insert` and `get_root`. + +## Solution + +```kotlin +import com_github_leetcode.TreeNode +import java.util.LinkedList +import java.util.Queue + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class CBTInserter(root: TreeNode?) { + private val q: Queue + private val head: TreeNode + + init { + q = LinkedList() + head = root!! + addToQueue() + } + + private fun addToQueue() { + val hlq: Queue = LinkedList() + hlq.add(head) + while (!hlq.isEmpty()) { + var size = hlq.size + while (size-- > 0) { + val poll: TreeNode = hlq.poll() + q.add(poll) + if (poll.left != null) { + hlq.add(poll.left) + } + if (poll.right != null) { + hlq.add(poll.right) + } + } + } + } + + fun insert(`val`: Int): Int { + val nn = TreeNode(`val`) + deleteFullNode() + val peek: TreeNode = q.peek() + if (peek.left == null) { + peek.left = nn + } else { + peek.right = nn + } + q.add(nn) + return peek.`val` + } + + private fun deleteFullNode() { + while (!q.isEmpty()) { + val peek: TreeNode = q.peek() + if (peek.left != null && peek.right != null) { + q.poll() + } else { + break + } + } + } + + // get_root() + fun getRoot(): TreeNode { + return head + } +} + +/* + * Your CBTInserter object will be instantiated and called as such: + * var obj = CBTInserter(root) + * var param_1 = obj.insert(`val`) + * var param_2 = obj.get_root() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0920_number_of_music_playlists/readme.md b/src/main/kotlin/g0901_1000/s0920_number_of_music_playlists/readme.md new file mode 100644 index 00000000..c84b44b0 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0920_number_of_music_playlists/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) + +## 920\. Number of Music Playlists + +Hard + +Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: + +* Every song is played **at least once**. +* A song can only be played again only if `k` other songs have been played. + +Given `n`, `goal`, and `k`, return _the number of possible playlists that you can create_. Since the answer can be very large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** n = 3, goal = 3, k = 1 + +**Output:** 6 + +**Explanation:** There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1]. + +**Example 2:** + +**Input:** n = 2, goal = 3, k = 0 + +**Output:** 6 + +**Explanation:** There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2]. + +**Example 3:** + +**Input:** n = 2, goal = 3, k = 1 + +**Output:** 2 + +**Explanation:** There are 2 possible playlists: [1, 2, 1] and [2, 1, 2]. + +**Constraints:** + +* `0 <= k < n <= goal <= 100` + +## Solution + +```kotlin +class Solution { + fun numMusicPlaylists(n: Int, l: Int, k: Int): Int { + val dp = Array(l) { LongArray(n + 1) } + for (i in 0 until l) { + dp[i].fill(-1) + } + return helper(0, l, 0, n, k, dp).toInt() + } + + private fun helper(songNumber: Int, l: Int, usedSong: Int, n: Int, k: Int, dp: Array): Long { + if (songNumber == l) { + return if (usedSong == n) 1 else 0 + } + if (dp[songNumber][usedSong] != -1L) { + return dp[songNumber][usedSong] + } + val ans: Long = if (songNumber < k) { + (n - usedSong) * helper(songNumber + 1, l, usedSong + 1, n, k, dp) + } else if (usedSong == n) { + (usedSong - k) * helper(songNumber + 1, l, usedSong, n, k, dp) + } else { + ( + (n - usedSong) * helper(songNumber + 1, l, usedSong + 1, n, k, dp) + + (usedSong - k) * helper(songNumber + 1, l, usedSong, n, k, dp) + ) + } + val mod = 1e9.toInt() + 7 + dp[songNumber][usedSong] = ans % mod + return ans % mod + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0921_minimum_add_to_make_parentheses_valid/readme.md b/src/main/kotlin/g0901_1000/s0921_minimum_add_to_make_parentheses_valid/readme.md new file mode 100644 index 00000000..64005918 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0921_minimum_add_to_make_parentheses_valid/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) + +## 921\. Minimum Add to Make Parentheses Valid + +Medium + +A parentheses string is valid if and only if: + +* It is the empty string, +* It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or +* It can be written as `(A)`, where `A` is a valid string. + +You are given a parentheses string `s`. In one move, you can insert a parenthesis at any position of the string. + +* For example, if `s = "()))"`, you can insert an opening parenthesis to be "(**(**)))" or a closing parenthesis to be "())**)**)". + +Return _the minimum number of moves required to make_ `s` _valid_. + +**Example 1:** + +**Input:** s = "())" + +**Output:** 1 + +**Example 2:** + +**Input:** s = "(((" + +**Output:** 3 + +**Constraints:** + +* `1 <= s.length <= 1000` +* `s[i]` is either `'('` or `')'`. + +## Solution + +```kotlin +import java.util.Deque +import java.util.LinkedList + +class Solution { + fun minAddToMakeValid(s: String): Int { + val stack: Deque = LinkedList() + for (c in s.toCharArray()) { + if (c == ')') { + if (!stack.isEmpty() && stack.peek() == '(') { + stack.pop() + } else { + stack.push(c) + } + } else { + stack.push(c) + } + } + return stack.size + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0922_sort_array_by_parity_ii/readme.md b/src/main/kotlin/g0901_1000/s0922_sort_array_by_parity_ii/readme.md new file mode 100644 index 00000000..83e2f50a --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0922_sort_array_by_parity_ii/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) + +## 922\. Sort Array By Parity II + +Easy + +Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**. + +Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**. + +Return _any answer array that satisfies this condition_. + +**Example 1:** + +**Input:** nums = [4,2,5,7] + +**Output:** [4,5,2,7] + +**Explanation:** [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. + +**Example 2:** + +**Input:** nums = [2,3] + +**Output:** [2,3] + +**Constraints:** + +* 2 <= nums.length <= 2 * 104 +* `nums.length` is even. +* Half of the integers in `nums` are even. +* `0 <= nums[i] <= 1000` + +**Follow Up:** Could you solve it in-place? + +## Solution + +```kotlin +class Solution { + fun sortArrayByParityII(nums: IntArray): IntArray { + var i = 0 + var j = 1 + while (i < nums.size - 1 && j < nums.size) { + if (nums[i] % 2 != 0 && nums[j] % 2 == 0) { + val tmp = nums[i] + nums[i] = nums[j] + nums[j] = tmp + i += 2 + j += 2 + } + while (i < nums.size - 1 && nums[i] % 2 == 0) { + i += 2 + } + while (j < nums.size && nums[j] % 2 != 0) { + j += 2 + } + } + return nums + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0923_3sum_with_multiplicity/readme.md b/src/main/kotlin/g0901_1000/s0923_3sum_with_multiplicity/readme.md new file mode 100644 index 00000000..fbafee21 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0923_3sum_with_multiplicity/readme.md @@ -0,0 +1,80 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 923\. 3Sum With Multiplicity + +Medium + +Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`. + +As the answer can be very large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** arr = [1,1,2,2,3,3,4,4,5,5], target = 8 + +**Output:** 20 + +**Explanation:** + + Enumerating by the values (arr[i], arr[j], arr[k]): + (1, 2, 5) occurs 8 times; + (1, 3, 4) occurs 8 times; + (2, 2, 4) occurs 2 times; + (2, 3, 3) occurs 2 times. + +**Example 2:** + +**Input:** arr = [1,1,2,2,2,2], target = 5 + +**Output:** 12 + +**Explanation:** + +arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times: + +We choose one 1 from [1,1] in 2 ways, + +and two 2s from [2,2,2,2] in 6 ways. + +**Constraints:** + +* `3 <= arr.length <= 3000` +* `0 <= arr[i] <= 100` +* `0 <= target <= 300` + +## Solution + +```kotlin +class Solution { + fun threeSumMulti(arr: IntArray, target: Int): Int { + var answer = 0 + val countRight = IntArray(MAX + 1) + for (num in arr) { + ++countRight[num] + } + val countLeft = IntArray(MAX + 1) + for (j in 0 until arr.size - 1) { + --countRight[arr[j]] + val remains = target - arr[j] + if (remains <= 2 * MAX) { + for (v in 0..remains.coerceAtMost(MAX)) { + if (remains - v <= MAX) { + val count = countRight[v] * countLeft[remains - v] + if (count > 0) { + answer = (answer + count) % MOD + } + } + } + } + ++countLeft[arr[j]] + } + return answer + } + + companion object { + private const val MOD = 1e9.toInt() + 7 + private const val MAX = 100 + } +} +``` \ No newline at end of file