From bdbffa84853a6db39664edbf18282259a1216b74 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Tue, 16 May 2023 05:55:30 +0300 Subject: [PATCH] Added tasks 960-1012 --- README.md | 66 ++++++++ .../s0901_online_stock_span/readme.md | 2 +- .../s0909_snakes_and_ladders/readme.md | 2 +- .../g0901_1000/s0913_cat_and_mouse/readme.md | 2 +- .../readme.md | 5 +- .../readme.md | 4 +- .../readme.md | 2 +- .../readme.md | 6 +- .../s0934_shortest_bridge/readme.md | 2 +- .../s0939_minimum_area_rectangle/readme.md | 4 +- .../s0946_validate_stack_sequences/readme.md | 4 +- .../readme.md | 2 +- .../readme.md | 76 +++++++++ .../readme.md | 57 +++++++ .../s0962_maximum_width_ramp/readme.md | 56 +++++++ .../s0963_minimum_area_rectangle_ii/readme.md | 103 ++++++++++++ .../readme.md | 98 ++++++++++++ .../s0965_univalued_binary_tree/readme.md | 69 ++++++++ .../s0966_vowel_spellchecker/readme.md | 99 ++++++++++++ .../readme.md | 75 +++++++++ .../s0968_binary_tree_cameras/readme.md | 87 ++++++++++ .../s0969_pancake_sorting/readme.md | 84 ++++++++++ .../s0970_powerful_integers/readme.md | 69 ++++++++ .../readme.md | 109 +++++++++++++ .../s0972_equal_rational_numbers/readme.md | 74 +++++++++ .../readme.md | 69 ++++++++ .../readme.md | 52 ++++++ .../g0901_1000/s0975_odd_even_jump/readme.md | 142 +++++++++++++++++ .../readme.md | 53 +++++++ .../s0977_squares_of_a_sorted_array/readme.md | 58 +++++++ .../readme.md | 79 ++++++++++ .../readme.md | 74 +++++++++ .../s0980_unique_paths_iii/readme.md | 113 +++++++++++++ .../readme.md | 67 ++++++++ .../readme.md | 99 ++++++++++++ .../s0983_minimum_cost_for_tickets/readme.md | 92 +++++++++++ .../s0984_string_without_aaa_or_bbb/readme.md | 66 ++++++++ .../readme.md | 65 ++++++++ .../readme.md | 62 ++++++++ .../readme.md | 123 +++++++++++++++ .../readme.md | 87 ++++++++++ .../readme.md | 73 +++++++++ .../readme.md | 92 +++++++++++ .../s0991_broken_calculator/readme.md | 66 ++++++++ .../readme.md | 69 ++++++++ .../s0993_cousins_in_binary_tree/readme.md | 101 ++++++++++++ .../s0994_rotting_oranges/readme.md | 4 +- .../readme.md | 77 +++++++++ .../readme.md | 79 ++++++++++ .../s0997_find_the_town_judge/readme.md | 61 ++++++++ .../s0998_maximum_binary_tree_ii/readme.md | 94 +++++++++++ .../readme.md | 148 ++++++++++++++++++ .../readme.md | 110 +++++++++++++ .../s1001_grid_illumination/readme.md | 119 ++++++++++++++ .../s1002_find_common_characters/readme.md | 75 +++++++++ .../readme.md | 69 ++++++++ .../s1004_max_consecutive_ones_iii/readme.md | 55 +++++++ .../readme.md | 74 +++++++++ .../s1006_clumsy_factorial/readme.md | 63 ++++++++ .../readme.md | 110 +++++++++++++ .../readme.md | 67 ++++++++ .../readme.md | 72 +++++++++ .../readme.md | 58 +++++++ .../readme.md | 108 +++++++++++++ .../readme.md | 117 ++++++++++++++ 65 files changed, 4399 insertions(+), 20 deletions(-) create mode 100644 src/main/kotlin/g0901_1000/s0960_delete_columns_to_make_sorted_iii/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0961_n_repeated_element_in_size_2n_array/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0962_maximum_width_ramp/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0963_minimum_area_rectangle_ii/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0964_least_operators_to_express_number/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0965_univalued_binary_tree/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0966_vowel_spellchecker/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0967_numbers_with_same_consecutive_differences/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0968_binary_tree_cameras/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0969_pancake_sorting/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0970_powerful_integers/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0971_flip_binary_tree_to_match_preorder_traversal/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0972_equal_rational_numbers/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0973_k_closest_points_to_origin/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0974_subarray_sums_divisible_by_k/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0975_odd_even_jump/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0976_largest_perimeter_triangle/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0977_squares_of_a_sorted_array/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0978_longest_turbulent_subarray/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0979_distribute_coins_in_binary_tree/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0980_unique_paths_iii/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0981_time_based_key_value_store/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0982_triples_with_bitwise_and_equal_to_zero/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0983_minimum_cost_for_tickets/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0984_string_without_aaa_or_bbb/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0985_sum_of_even_numbers_after_queries/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0986_interval_list_intersections/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0987_vertical_order_traversal_of_a_binary_tree/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0988_smallest_string_starting_from_leaf/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0989_add_to_array_form_of_integer/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0990_satisfiability_of_equality_equations/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0991_broken_calculator/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0992_subarrays_with_k_different_integers/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0993_cousins_in_binary_tree/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0995_minimum_number_of_k_consecutive_bit_flips/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0996_number_of_squareful_arrays/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0997_find_the_town_judge/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0998_maximum_binary_tree_ii/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0999_available_captures_for_rook/readme.md create mode 100644 src/main/kotlin/g0901_1000/s1000_minimum_cost_to_merge_stones/readme.md create mode 100644 src/main/kotlin/g1001_1100/s1001_grid_illumination/readme.md create mode 100644 src/main/kotlin/g1001_1100/s1002_find_common_characters/readme.md create mode 100644 src/main/kotlin/g1001_1100/s1003_check_if_word_is_valid_after_substitutions/readme.md create mode 100644 src/main/kotlin/g1001_1100/s1004_max_consecutive_ones_iii/readme.md create mode 100644 src/main/kotlin/g1001_1100/s1005_maximize_sum_of_array_after_k_negations/readme.md create mode 100644 src/main/kotlin/g1001_1100/s1006_clumsy_factorial/readme.md create mode 100644 src/main/kotlin/g1001_1100/s1007_minimum_domino_rotations_for_equal_row/readme.md create mode 100644 src/main/kotlin/g1001_1100/s1008_construct_binary_search_tree_from_preorder_traversal/readme.md create mode 100644 src/main/kotlin/g1001_1100/s1009_complement_of_base_10_integer/readme.md create mode 100644 src/main/kotlin/g1001_1100/s1010_pairs_of_songs_with_total_durations_divisible_by_60/readme.md create mode 100644 src/main/kotlin/g1001_1100/s1011_capacity_to_ship_packages_within_d_days/readme.md create mode 100644 src/main/kotlin/g1001_1100/s1012_numbers_with_repeated_digits/readme.md diff --git a/README.md b/README.md index 4259860b..35b584b9 100644 --- a/README.md +++ b/README.md @@ -327,6 +327,7 @@ | 0697 |[Degree of an Array](src/main/kotlin/g0601_0700/s0697_degree_of_an_array)| Easy | Array, Hash_Table | 289 | 84.62 | 0532 |[K-diff Pairs in an Array](src/main/kotlin/g0501_0600/s0532_k_diff_pairs_in_an_array)| Medium | Array, Hash_Table, Sorting, Binary_Search, Two_Pointers | 230 | 84.62 | 0713 |[Subarray Product Less Than K](src/main/kotlin/g0701_0800/s0713_subarray_product_less_than_k)| Medium | Array, Sliding_Window | 336 | 92.11 +| 1007 |[Minimum Domino Rotations For Equal Row](src/main/kotlin/g1001_1100/s1007_minimum_domino_rotations_for_equal_row)| Medium | Array, Greedy | 421 | 50.00 | 0456 |[132 Pattern](src/main/kotlin/g0401_0500/s0456_132_pattern)| Medium | Array, Binary_Search, Stack, Ordered_Set, Monotonic_Stack | 434 | 100.00 | 0239 |[Sliding Window Maximum](src/main/kotlin/g0201_0300/s0239_sliding_window_maximum)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Heap_Priority_Queue, Sliding_Window, Queue, Monotonic_Queue | 1059 | 86.14 @@ -336,6 +337,7 @@ |-|-|-|-|-|- | 0392 |[Is Subsequence](src/main/kotlin/g0301_0400/s0392_is_subsequence)| Easy | String, Dynamic_Programming, Two_Pointers | 156 | 87.74 | 0125 |[Valid Palindrome](src/main/kotlin/g0101_0200/s0125_valid_palindrome)| Easy | Top_Interview_Questions, String, Two_Pointers | 353 | 52.06 +| 0977 |[Squares of a Sorted Array](src/main/kotlin/g0901_1000/s0977_squares_of_a_sorted_array)| Easy | Array, Sorting, Two_Pointers | 375 | 18.43 | 0026 |[Remove Duplicates from Sorted Array](src/main/kotlin/g0001_0100/s0026_remove_duplicates_from_sorted_array)| Easy | Top_Interview_Questions, Array, Two_Pointers | 361 | 77.19 | 0042 |[Trapping Rain Water](src/main/kotlin/g0001_0100/s0042_trapping_rain_water)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Two_Pointers, Stack, Monotonic_Stack | 196 | 100.00 | 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers | 761 | 90.55 @@ -395,6 +397,7 @@ | 0102 |[Binary Tree Level Order Traversal](src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 332 | 67.53 | 0103 |[Binary Tree Zigzag Level Order Traversal](src/main/kotlin/g0101_0200/s0103_binary_tree_zigzag_level_order_traversal)| Medium | Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 316 | 34.25 | 0108 |[Convert Sorted Array to Binary Search Tree](src/main/kotlin/g0101_0200/s0108_convert_sorted_array_to_binary_search_tree)| Easy | Top_Interview_Questions, Array, Tree, Binary_Tree, Binary_Search_Tree, Divide_and_Conquer | 334 | 35.39 +| 1008 |[Construct Binary Search Tree from Preorder Traversal](src/main/kotlin/g1001_1100/s1008_construct_binary_search_tree_from_preorder_traversal)| Medium | Array, Tree, Binary_Tree, Stack, Monotonic_Stack, Binary_Search_Tree | 145 | 100.00 | 0543 |[Diameter of Binary Tree](src/main/kotlin/g0501_0600/s0543_diameter_of_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree | 307 | 43.93 | 0938 |[Range Sum of BST](src/main/kotlin/g0901_1000/s0938_range_sum_of_bst)| Easy | Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 356 | 55.36 | 0100 |[Same Tree](src/main/kotlin/g0001_0100/s0100_same_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 208 | 72.24 @@ -408,6 +411,7 @@ | 0098 |[Validate Binary Search Tree](src/main/kotlin/g0001_0100/s0098_validate_binary_search_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 330 | 41.38 | 0337 |[House Robber III](src/main/kotlin/g0301_0400/s0337_house_robber_iii)| Medium | Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree | 282 | 84.62 | 0236 |[Lowest Common Ancestor of a Binary Tree](src/main/kotlin/g0201_0300/s0236_lowest_common_ancestor_of_a_binary_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree | 386 | 45.21 +| 0968 |[Binary Tree Cameras](src/main/kotlin/g0901_1000/s0968_binary_tree_cameras)| Hard | Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree | 176 | 100.00 #### Udemy Trie and Heap @@ -463,6 +467,7 @@ | 0389 |[Find the Difference](src/main/kotlin/g0301_0400/s0389_find_the_difference)| Easy | String, Hash_Table, Sorting, Bit_Manipulation | 256 | 64.81 | 0190 |[Reverse Bits](src/main/kotlin/g0101_0200/s0190_reverse_bits)| Easy | Top_Interview_Questions, Bit_Manipulation, Divide_and_Conquer | 198 | 81.82 | 0461 |[Hamming Distance](src/main/kotlin/g0401_0500/s0461_hamming_distance)| Easy | Bit_Manipulation | 150 | 96.15 +| 1009 |[Complement of Base 10 Integer](src/main/kotlin/g1001_1100/s1009_complement_of_base_10_integer)| Easy | Bit_Manipulation | 126 | 72.73 | 0338 |[Counting Bits](src/main/kotlin/g0301_0400/s0338_counting_bits)| Easy | Top_100_Liked_Questions, Dynamic_Programming, Bit_Manipulation | 186 | 99.26 | 0371 |[Sum of Two Integers](src/main/kotlin/g0301_0400/s0371_sum_of_two_integers)| Medium | Top_Interview_Questions, Math, Bit_Manipulation | 129 | 95.45 | 0029 |[Divide Two Integers](src/main/kotlin/g0001_0100/s0029_divide_two_integers)| Medium | Top_Interview_Questions, Math, Bit_Manipulation | 281 | 31.67 @@ -715,6 +720,7 @@ | | | | | | |-|-|-|-|-|- +| 0997 |[Find the Town Judge](src/main/kotlin/g0901_1000/s0997_find_the_town_judge)| Easy | Array, Hash_Table, Graph | 475 | 58.62 | 0841 |[Keys and Rooms](src/main/kotlin/g0801_0900/s0841_keys_and_rooms)| Medium | Depth_First_Search, Breadth_First_Search, Graph | 189 | 69.23 #### Day 20 Heap Priority Queue @@ -729,6 +735,7 @@ | | | | | | |-|-|-|-|-|- | 0451 |[Sort Characters By Frequency](src/main/kotlin/g0401_0500/s0451_sort_characters_by_frequency)| Medium | String, Hash_Table, Sorting, Heap_Priority_Queue, Counting, Bucket_Sort | 288 | 81.72 +| 0973 |[K Closest Points to Origin](src/main/kotlin/g0901_1000/s0973_k_closest_points_to_origin)| Medium | Array, Math, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Geometry, Quickselect | 800 | 37.89 ### Algorithm I @@ -744,6 +751,7 @@ | | | | | | |-|-|-|-|-|- +| 0977 |[Squares of a Sorted Array](src/main/kotlin/g0901_1000/s0977_squares_of_a_sorted_array)| Easy | Array, Sorting, Two_Pointers | 375 | 18.43 | 0189 |[Rotate Array](src/main/kotlin/g0101_0200/s0189_rotate_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Two_Pointers | 483 | 86.95 #### Day 3 Two Pointers @@ -861,6 +869,7 @@ | | | | | | |-|-|-|-|-|- | 0844 |[Backspace String Compare](src/main/kotlin/g0801_0900/s0844_backspace_string_compare)| Easy | String, Two_Pointers, Stack, Simulation | 126 | 98.31 +| 0986 |[Interval List Intersections](src/main/kotlin/g0901_1000/s0986_interval_list_intersections)| Medium | Array, Two_Pointers | 318 | 60.98 | 0011 |[Container With Most Water](src/main/kotlin/g0001_0100/s0011_container_with_most_water)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Greedy, Two_Pointers | 474 | 89.18 #### Day 5 Sliding Window @@ -1159,6 +1168,7 @@ | | | | | | |-|-|-|-|-|- +| 0981 |[Time Based Key-Value Store](src/main/kotlin/g0901_1000/s0981_time_based_key_value_store)| Medium | String, Hash_Table, Binary_Search, Design | 1555 | 10.00 #### Day 17 @@ -1347,6 +1357,7 @@ | | | | | | |-|-|-|-|-|- +| 0976 |[Largest Perimeter Triangle](src/main/kotlin/g0901_1000/s0976_largest_perimeter_triangle)| Easy | Array, Math, Sorting, Greedy | 304 | 33.33 #### Day 4 Loop @@ -1442,6 +1453,7 @@ | | | | | | |-|-|-|-|-|- | 0067 |[Add Binary](src/main/kotlin/g0001_0100/s0067_add_binary)| Easy | String, Math, Bit_Manipulation, Simulation | 327 | 32.67 +| 0989 |[Add to Array-Form of Integer](src/main/kotlin/g0901_1000/s0989_add_to_array_form_of_integer)| Easy | Array, Math | 350 | 70.00 #### Day 6 @@ -1461,6 +1473,7 @@ | | | | | | |-|-|-|-|-|- | 0054 |[Spiral Matrix](src/main/kotlin/g0001_0100/s0054_spiral_matrix)| Medium | Top_Interview_Questions, Array, Matrix, Simulation | 224 | 62.50 +| 0973 |[K Closest Points to Origin](src/main/kotlin/g0901_1000/s0973_k_closest_points_to_origin)| Medium | Array, Math, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Geometry, Quickselect | 800 | 37.89 #### Day 9 @@ -1624,6 +1637,7 @@ | | | | | | |-|-|-|-|-|- +| 0997 |[Find the Town Judge](src/main/kotlin/g0901_1000/s0997_find_the_town_judge)| Easy | Array, Hash_Table, Graph | 475 | 58.62 #### Day 14 Graph Theory @@ -1702,7 +1716,59 @@ | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- | 1143 |[Longest Common Subsequence](src/main/kotlin/g1101_1200/s1143_longest_common_subsequence)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming, Algorithm_II_Day_17_Dynamic_Programming, Dynamic_Programming_I_Day_19, Udemy_Dynamic_Programming | 307 | 38.36 +| 1012 |[Numbers With Repeated Digits](src/main/kotlin/g1001_1100/s1012_numbers_with_repeated_digits)| Hard | Dynamic_Programming, Math | 123 | 100.00 +| 1011 |[Capacity To Ship Packages Within D Days](src/main/kotlin/g1001_1100/s1011_capacity_to_ship_packages_within_d_days)| Medium | Array, Binary_Search | 325 | 66.67 +| 1010 |[Pairs of Songs With Total Durations Divisible by 60](src/main/kotlin/g1001_1100/s1010_pairs_of_songs_with_total_durations_divisible_by_60)| Medium | Array, Hash_Table, Counting | 287 | 77.78 +| 1009 |[Complement of Base 10 Integer](src/main/kotlin/g1001_1100/s1009_complement_of_base_10_integer)| Easy | Bit_Manipulation, Udemy_Bit_Manipulation | 126 | 72.73 +| 1008 |[Construct Binary Search Tree from Preorder Traversal](src/main/kotlin/g1001_1100/s1008_construct_binary_search_tree_from_preorder_traversal)| Medium | Array, Tree, Binary_Tree, Stack, Monotonic_Stack, Binary_Search_Tree, Udemy_Tree_Stack_Queue | 145 | 100.00 +| 1007 |[Minimum Domino Rotations For Equal Row](src/main/kotlin/g1001_1100/s1007_minimum_domino_rotations_for_equal_row)| Medium | Array, Greedy, Udemy_Arrays | 421 | 50.00 +| 1006 |[Clumsy Factorial](src/main/kotlin/g1001_1100/s1006_clumsy_factorial)| Medium | Math, Stack, Simulation | 127 | 100.00 +| 1005 |[Maximize Sum Of Array After K Negations](src/main/kotlin/g1001_1100/s1005_maximize_sum_of_array_after_k_negations)| Easy | Array, Sorting, Greedy | 167 | 100.00 +| 1004 |[Max Consecutive Ones III](src/main/kotlin/g1001_1100/s1004_max_consecutive_ones_iii)| Medium | Array, Binary_Search, Prefix_Sum, Sliding_Window | 318 | 30.95 +| 1003 |[Check If Word Is Valid After Substitutions](src/main/kotlin/g1001_1100/s1003_check_if_word_is_valid_after_substitutions)| Medium | String, Stack | 216 | 100.00 +| 1002 |[Find Common Characters](src/main/kotlin/g1001_1100/s1002_find_common_characters)| Easy | Array, String, Hash_Table | 181 | 100.00 +| 1001 |[Grid Illumination](src/main/kotlin/g1001_1100/s1001_grid_illumination)| Hard | Array, Hash_Table | 801 | 100.00 +| 1000 |[Minimum Cost to Merge Stones](src/main/kotlin/g0901_1000/s1000_minimum_cost_to_merge_stones)| Hard | Array, Dynamic_Programming | 152 | 75.00 +| 0999 |[Available Captures for Rook](src/main/kotlin/g0901_1000/s0999_available_captures_for_rook)| Easy | Array, Matrix, Simulation | 143 | 80.00 +| 0998 |[Maximum Binary Tree II](src/main/kotlin/g0901_1000/s0998_maximum_binary_tree_ii)| Medium | Tree, Binary_Tree | 157 | 100.00 +| 0997 |[Find the Town Judge](src/main/kotlin/g0901_1000/s0997_find_the_town_judge)| Easy | Array, Hash_Table, Graph, Data_Structure_II_Day_19_Graph, Graph_Theory_I_Day_13_Graph_Theory | 475 | 58.62 +| 0996 |[Number of Squareful Arrays](src/main/kotlin/g0901_1000/s0996_number_of_squareful_arrays)| Hard | Array, Dynamic_Programming, Math, Bit_Manipulation, Backtracking, Bitmask | 139 | 100.00 +| 0995 |[Minimum Number of K Consecutive Bit Flips](src/main/kotlin/g0901_1000/s0995_minimum_number_of_k_consecutive_bit_flips)| Hard | Array, Bit_Manipulation, Prefix_Sum, Sliding_Window | 480 | 100.00 | 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 +| 0993 |[Cousins in Binary Tree](src/main/kotlin/g0901_1000/s0993_cousins_in_binary_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 152 | 71.43 +| 0992 |[Subarrays with K Different Integers](src/main/kotlin/g0901_1000/s0992_subarrays_with_k_different_integers)| Hard | Array, Hash_Table, Counting, Sliding_Window | 341 | 87.50 +| 0991 |[Broken Calculator](src/main/kotlin/g0901_1000/s0991_broken_calculator)| Medium | Math, Greedy | 127 | 100.00 +| 0990 |[Satisfiability of Equality Equations](src/main/kotlin/g0901_1000/s0990_satisfiability_of_equality_equations)| Medium | Array, String, Graph, Union_Find | 163 | 100.00 +| 0989 |[Add to Array-Form of Integer](src/main/kotlin/g0901_1000/s0989_add_to_array_form_of_integer)| Easy | Array, Math, Programming_Skills_II_Day_5 | 350 | 70.00 +| 0988 |[Smallest String Starting From Leaf](src/main/kotlin/g0901_1000/s0988_smallest_string_starting_from_leaf)| Medium | String, Depth_First_Search, Tree, Binary_Tree | 180 | 100.00 +| 0987 |[Vertical Order Traversal of a Binary Tree](src/main/kotlin/g0901_1000/s0987_vertical_order_traversal_of_a_binary_tree)| Hard | Hash_Table, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 189 | 66.67 +| 0986 |[Interval List Intersections](src/main/kotlin/g0901_1000/s0986_interval_list_intersections)| Medium | Array, Two_Pointers, Algorithm_II_Day_4_Two_Pointers | 318 | 60.98 +| 0985 |[Sum of Even Numbers After Queries](src/main/kotlin/g0901_1000/s0985_sum_of_even_numbers_after_queries)| Medium | Array, Simulation | 497 | 71.43 +| 0984 |[String Without AAA or BBB](src/main/kotlin/g0901_1000/s0984_string_without_aaa_or_bbb)| Medium | String, Greedy | 132 | 66.67 +| 0983 |[Minimum Cost For Tickets](src/main/kotlin/g0901_1000/s0983_minimum_cost_for_tickets)| Medium | Array, Dynamic_Programming | 147 | 92.80 +| 0982 |[Triples with Bitwise AND Equal To Zero](src/main/kotlin/g0901_1000/s0982_triples_with_bitwise_and_equal_to_zero)| Hard | Array, Hash_Table, Bit_Manipulation | 227 | 100.00 +| 0981 |[Time Based Key-Value Store](src/main/kotlin/g0901_1000/s0981_time_based_key_value_store)| Medium | String, Hash_Table, Binary_Search, Design, Binary_Search_II_Day_16 | 1555 | 10.00 +| 0980 |[Unique Paths III](src/main/kotlin/g0901_1000/s0980_unique_paths_iii)| Hard | Array, Matrix, Bit_Manipulation, Backtracking | 134 | 100.00 +| 0979 |[Distribute Coins in Binary Tree](src/main/kotlin/g0901_1000/s0979_distribute_coins_in_binary_tree)| Medium | Depth_First_Search, Tree, Binary_Tree | 165 | 80.00 +| 0978 |[Longest Turbulent Subarray](src/main/kotlin/g0901_1000/s0978_longest_turbulent_subarray)| Medium | Array, Dynamic_Programming, Sliding_Window | 395 | 40.00 +| 0977 |[Squares of a Sorted Array](src/main/kotlin/g0901_1000/s0977_squares_of_a_sorted_array)| Easy | Array, Sorting, Two_Pointers, Algorithm_I_Day_2_Two_Pointers, Udemy_Two_Pointers | 375 | 18.43 +| 0976 |[Largest Perimeter Triangle](src/main/kotlin/g0901_1000/s0976_largest_perimeter_triangle)| Easy | Array, Math, Sorting, Greedy, Programming_Skills_I_Day_3_Conditional_Statements | 304 | 33.33 +| 0975 |[Odd Even Jump](src/main/kotlin/g0901_1000/s0975_odd_even_jump)| Hard | Array, Dynamic_Programming, Stack, Ordered_Set, Monotonic_Stack | 326 | 100.00 +| 0974 |[Subarray Sums Divisible by K](src/main/kotlin/g0901_1000/s0974_subarray_sums_divisible_by_k)| Medium | Array, Hash_Table, Prefix_Sum | 334 | 66.67 +| 0973 |[K Closest Points to Origin](src/main/kotlin/g0901_1000/s0973_k_closest_points_to_origin)| Medium | Array, Math, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Geometry, Quickselect, Data_Structure_II_Day_21_Heap_Priority_Queue, Programming_Skills_II_Day_8 | 800 | 37.89 +| 0972 |[Equal Rational Numbers](src/main/kotlin/g0901_1000/s0972_equal_rational_numbers)| Hard | String, Math | 130 | 100.00 +| 0971 |[Flip Binary Tree To Match Preorder Traversal](src/main/kotlin/g0901_1000/s0971_flip_binary_tree_to_match_preorder_traversal)| Medium | Depth_First_Search, Tree, Binary_Tree | 173 | 66.67 +| 0970 |[Powerful Integers](src/main/kotlin/g0901_1000/s0970_powerful_integers)| Medium | Hash_Table, Math | 136 | 100.00 +| 0969 |[Pancake Sorting](src/main/kotlin/g0901_1000/s0969_pancake_sorting)| Medium | Array, Sorting, Greedy, Two_Pointers | 169 | 100.00 +| 0968 |[Binary Tree Cameras](src/main/kotlin/g0901_1000/s0968_binary_tree_cameras)| Hard | Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree, Udemy_Tree_Stack_Queue | 176 | 100.00 +| 0967 |[Numbers With Same Consecutive Differences](src/main/kotlin/g0901_1000/s0967_numbers_with_same_consecutive_differences)| Medium | Breadth_First_Search, Backtracking | 144 | 100.00 +| 0966 |[Vowel Spellchecker](src/main/kotlin/g0901_1000/s0966_vowel_spellchecker)| Medium | Array, String, Hash_Table | 371 | 100.00 +| 0965 |[Univalued Binary Tree](src/main/kotlin/g0901_1000/s0965_univalued_binary_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 138 | 90.91 +| 0964 |[Least Operators to Express Number](src/main/kotlin/g0901_1000/s0964_least_operators_to_express_number)| Hard | Dynamic_Programming, Math | 160 | 100.00 +| 0963 |[Minimum Area Rectangle II](src/main/kotlin/g0901_1000/s0963_minimum_area_rectangle_ii)| Medium | Array, Math, Geometry | 183 | 100.00 +| 0962 |[Maximum Width Ramp](src/main/kotlin/g0901_1000/s0962_maximum_width_ramp)| Medium | Array, Stack, Monotonic_Stack | 324 | 100.00 +| 0961 |[N-Repeated Element in Size 2N Array](src/main/kotlin/g0901_1000/s0961_n_repeated_element_in_size_2n_array)| Easy | Array, Hash_Table | 264 | 75.00 +| 0960 |[Delete Columns to Make Sorted III](src/main/kotlin/g0901_1000/s0960_delete_columns_to_make_sorted_iii)| Hard | Array, String, Dynamic_Programming | 200 | 100.00 | 0959 |[Regions Cut By Slashes](src/main/kotlin/g0901_1000/s0959_regions_cut_by_slashes)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 180 | 100.00 | 0958 |[Check Completeness of a Binary Tree](src/main/kotlin/g0901_1000/s0958_check_completeness_of_a_binary_tree)| Medium | Breadth_First_Search, Tree, Binary_Tree | 142 | 96.04 | 0957 |[Prison Cells After N Days](src/main/kotlin/g0901_1000/s0957_prison_cells_after_n_days)| Medium | Array, Hash_Table, Math, Bit_Manipulation | 172 | 100.00 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 index ff217c50..7892ab38 100644 --- a/src/main/kotlin/g0901_1000/s0901_online_stock_span/readme.md +++ b/src/main/kotlin/g0901_1000/s0901_online_stock_span/readme.md @@ -68,7 +68,7 @@ class StockSpanner { if (stocks.size == 1) { return index - stocks.peek() } - while (stocks.size > 1 && map[stocks.peek()]!! <= price) { + while (stocks.size > 1 && map.getValue(stocks.peek()) <= price) { stocks.pop() } return index - stocks.peek() 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 index 269eebf3..8d21d44f 100644 --- a/src/main/kotlin/g0901_1000/s0909_snakes_and_ladders/readme.md +++ b/src/main/kotlin/g0901_1000/s0909_snakes_and_ladders/readme.md @@ -73,7 +73,7 @@ class Solution { queue.add(1) visited[0] = true var step = 0 - while (!queue.isEmpty()) { + while (queue.isNotEmpty()) { val queueSize = queue.size for (i in 0 until queueSize) { val previousLabel = queue.poll() 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 index 94d99a18..79f690aa 100644 --- a/src/main/kotlin/g0901_1000/s0913_cat_and_mouse/readme.md +++ b/src/main/kotlin/g0901_1000/s0913_cat_and_mouse/readme.md @@ -98,7 +98,7 @@ class Solution { q.offer(intArrayOf(0, i, CAT, MOUSE_WIN)) q.offer(intArrayOf(i, i, CAT, CAT_WIN)) } - while (!q.isEmpty()) { + while (q.isNotEmpty()) { val state = q.poll() val mouse = state[0] val cat = state[1] 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 index cf18cbc7..08530086 100644 --- 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 @@ -43,13 +43,12 @@ class Solution { val map: HashMap = HashMap() for (j in deck) { if (map.containsKey(j)) { - map[j] = map[j]!! + 1 + map[j] = map.getValue(j) + 1 } else { map[j] = 1 } } - var x = map[deck[0]]!! - + var x = map.getValue(deck[0]) for (entry in map.entries.iterator()) { x = gcd(x, entry.value) } 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 index b2ec288a..9a17d0d6 100644 --- 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 @@ -68,7 +68,7 @@ class CBTInserter(root: TreeNode?) { private fun addToQueue() { val hlq: Queue = LinkedList() hlq.add(head) - while (!hlq.isEmpty()) { + while (hlq.isNotEmpty()) { var size = hlq.size while (size-- > 0) { val poll: TreeNode = hlq.poll() @@ -97,7 +97,7 @@ class CBTInserter(root: TreeNode?) { } private fun deleteFullNode() { - while (!q.isEmpty()) { + while (q.isNotEmpty()) { val peek: TreeNode = q.peek() if (peek.left != null && peek.right != null) { q.poll() 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 index 64005918..826a8665 100644 --- 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 @@ -45,7 +45,7 @@ class Solution { val stack: Deque = LinkedList() for (c in s.toCharArray()) { if (c == ')') { - if (!stack.isEmpty() && stack.peek() == '(') { + if (stack.isNotEmpty() && stack.peek() == '(') { stack.pop() } else { stack.push(c) diff --git a/src/main/kotlin/g0901_1000/s0928_minimize_malware_spread_ii/readme.md b/src/main/kotlin/g0901_1000/s0928_minimize_malware_spread_ii/readme.md index 1a46ed2a..f46489c2 100644 --- a/src/main/kotlin/g0901_1000/s0928_minimize_malware_spread_ii/readme.md +++ b/src/main/kotlin/g0901_1000/s0928_minimize_malware_spread_ii/readme.md @@ -64,7 +64,7 @@ class Solution { visited!!.add(initial[i]) } } - while (!q.isEmpty()) { + while (q.isNotEmpty()) { val curr = q.poll() if (curr != initial[ind]) { count++ @@ -87,7 +87,7 @@ class Solution { adj.putIfAbsent(i, ArrayList()) for (j in 0 until n) { if (graph[i][j] == 1) { - adj[i]!!.add(j) + adj.getValue(i).add(j) } } } @@ -96,7 +96,7 @@ class Solution { var node = initial[0] for (i in initial.indices) { visited = HashSet() - val children = adj[initial[i]]!! + val children = adj.getValue(initial[i]) adj.remove(initial[i]) bfs(i, initial) if (count < min) { diff --git a/src/main/kotlin/g0901_1000/s0934_shortest_bridge/readme.md b/src/main/kotlin/g0901_1000/s0934_shortest_bridge/readme.md index 3d902658..3178ede7 100644 --- a/src/main/kotlin/g0901_1000/s0934_shortest_bridge/readme.md +++ b/src/main/kotlin/g0901_1000/s0934_shortest_bridge/readme.md @@ -67,7 +67,7 @@ class Solution { i++ } var level = -1 - while (!q.isEmpty()) { + while (q.isNotEmpty()) { var size: Int = q.size level++ while (size-- > 0) { diff --git a/src/main/kotlin/g0901_1000/s0939_minimum_area_rectangle/readme.md b/src/main/kotlin/g0901_1000/s0939_minimum_area_rectangle/readme.md index 01f01ee6..eaf14e24 100644 --- a/src/main/kotlin/g0901_1000/s0939_minimum_area_rectangle/readme.md +++ b/src/main/kotlin/g0901_1000/s0939_minimum_area_rectangle/readme.md @@ -46,7 +46,7 @@ class Solution { val map: MutableMap> = HashMap() for (p in points) { map.putIfAbsent(p[0], HashSet()) - map[p[0]]!!.add(p[1]) + map.getValue(p[0]).add(p[1]) } Arrays.sort( points @@ -65,7 +65,7 @@ class Solution { if (area >= min || area == 0) { continue } - if (map[p1[0]]!!.contains(p2[1]) && map[p2[0]]!!.contains(p1[1])) { + if (map.getValue(p1[0]).contains(p2[1]) && map.getValue(p2[0]).contains(p1[1])) { min = area } } diff --git a/src/main/kotlin/g0901_1000/s0946_validate_stack_sequences/readme.md b/src/main/kotlin/g0901_1000/s0946_validate_stack_sequences/readme.md index 011a0236..ef3ce43f 100644 --- a/src/main/kotlin/g0901_1000/s0946_validate_stack_sequences/readme.md +++ b/src/main/kotlin/g0901_1000/s0946_validate_stack_sequences/readme.md @@ -61,7 +61,7 @@ class Solution { if (pushed[i] == popped[j]) { i++ j++ - } else if (!stack.isEmpty() && stack.peek() == popped[j]) { + } else if (stack.isNotEmpty() && stack.peek() == popped[j]) { stack.pop() j++ } else { @@ -69,7 +69,7 @@ class Solution { } } while (j < len) { - if (!stack.isEmpty() && stack.peek() != popped[j++]) { + if (stack.isNotEmpty() && stack.peek() != popped[j++]) { return false } else { stack.pop() diff --git a/src/main/kotlin/g0901_1000/s0958_check_completeness_of_a_binary_tree/readme.md b/src/main/kotlin/g0901_1000/s0958_check_completeness_of_a_binary_tree/readme.md index f1c7be04..245bbc61 100644 --- a/src/main/kotlin/g0901_1000/s0958_check_completeness_of_a_binary_tree/readme.md +++ b/src/main/kotlin/g0901_1000/s0958_check_completeness_of_a_binary_tree/readme.md @@ -59,7 +59,7 @@ class Solution { queue.add(root.left) queue.add(root.right) var seenNull = false - while (!queue.isEmpty()) { + while (queue.isNotEmpty()) { val node: TreeNode? = queue.poll() if (node == null) { seenNull = true diff --git a/src/main/kotlin/g0901_1000/s0960_delete_columns_to_make_sorted_iii/readme.md b/src/main/kotlin/g0901_1000/s0960_delete_columns_to_make_sorted_iii/readme.md new file mode 100644 index 00000000..acd2c058 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0960_delete_columns_to_make_sorted_iii/readme.md @@ -0,0 +1,76 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 960\. Delete Columns to Make Sorted III + +Hard + +You are given an array of `n` strings `strs`, all of the same length. + +We may choose any deletion indices, and we delete all the characters in those indices for each string. + +For example, if we have `strs = ["abcdef","uvwxyz"]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `["bef", "vyz"]`. + +Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has **every string (row) in lexicographic** order. (i.e., `(strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])`, and `(strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])`, and so on). Return _the minimum possible value of_ `answer.length`. + +**Example 1:** + +**Input:** strs = ["babca","bbazb"] + +**Output:** 3 + +**Explanation:** After deleting columns 0, 1, and 4, the final array is strs = ["bc", "az"]. Both these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]). Note that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order. + +**Example 2:** + +**Input:** strs = ["edcba"] + +**Output:** 4 + +**Explanation:** If we delete less than 4 columns, the only row will not be lexicographically sorted. + +**Example 3:** + +**Input:** strs = ["ghi","def","abc"] + +**Output:** 0 + +**Explanation:** All rows are already lexicographically sorted. + +**Constraints:** + +* `n == strs.length` +* `1 <= n <= 100` +* `1 <= strs[i].length <= 100` +* `strs[i]` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun minDeletionSize(strs: Array): Int { + val n = strs[0].length + val dp = Array(n + 1) { IntArray(2) } + for (i in 1..n) { + dp[i][0] = 1 + dp[i - 1][0].coerceAtMost(dp[i - 1][1]) + var min = i - 1 + var j: Int = i - 1 + while (j > 0) { + var lexico = true + for (str in strs) { + if (str[i - 1] < str[j - 1]) { + lexico = false + break + } + } + if (lexico) { + min = min.coerceAtMost(dp[j][1] + i - j - 1) + } + j-- + } + dp[i][1] = min + } + return dp[n][0].coerceAtMost(dp[n][1]) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0961_n_repeated_element_in_size_2n_array/readme.md b/src/main/kotlin/g0901_1000/s0961_n_repeated_element_in_size_2n_array/readme.md new file mode 100644 index 00000000..103294a9 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0961_n_repeated_element_in_size_2n_array/readme.md @@ -0,0 +1,57 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 961\. N-Repeated Element in Size 2N Array + +Easy + +You are given an integer array `nums` with the following properties: + +* `nums.length == 2 * n`. +* `nums` contains `n + 1` **unique** elements. +* Exactly one element of `nums` is repeated `n` times. + +Return _the element that is repeated_ `n` _times_. + +**Example 1:** + +**Input:** nums = [1,2,3,3] + +**Output:** 3 + +**Example 2:** + +**Input:** nums = [2,1,2,5,3,2] + +**Output:** 2 + +**Example 3:** + +**Input:** nums = [5,1,5,2,5,3,5,4] + +**Output:** 5 + +**Constraints:** + +* `2 <= n <= 5000` +* `nums.length == 2 * n` +* 0 <= nums[i] <= 104 +* `nums` contains `n + 1` **unique** elements and one of them is repeated exactly `n` times. + +## Solution + +```kotlin +class Solution { + fun repeatedNTimes(nums: IntArray): Int { + val hs: HashSet = HashSet() + for (x in nums) { + if (!hs.contains(x)) { + hs.add(x) + } else { + return x + } + } + return 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0962_maximum_width_ramp/readme.md b/src/main/kotlin/g0901_1000/s0962_maximum_width_ramp/readme.md new file mode 100644 index 00000000..196ba152 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0962_maximum_width_ramp/readme.md @@ -0,0 +1,56 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 962\. Maximum Width Ramp + +Medium + +A **ramp** in an integer array `nums` is a pair `(i, j)` for which `i < j` and `nums[i] <= nums[j]`. The **width** of such a ramp is `j - i`. + +Given an integer array `nums`, return _the maximum width of a **ramp** in_ `nums`. If there is no **ramp** in `nums`, return `0`. + +**Example 1:** + +**Input:** nums = [6,0,8,2,1,5] + +**Output:** 4 + +**Explanation:** The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5. + +**Example 2:** + +**Input:** nums = [9,8,1,0,1,9,4,0,4,1] + +**Output:** 7 + +**Explanation:** The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1. + +**Constraints:** + +* 2 <= nums.length <= 5 * 104 +* 0 <= nums[i] <= 5 * 104 + +## Solution + +```kotlin +class Solution { + fun maxWidthRamp(nums: IntArray): Int { + val m = nums.size + val dp = IntArray(m) + var minInd = 0 + var ramp = 0 + for (i in 0 until m) { + var prInd = minInd + while (prInd > 0 && nums[i] >= nums[dp[prInd]]) { + prInd = dp[prInd] + } + dp[i] = prInd + if (nums[i] >= nums[prInd]) { + ramp = ramp.coerceAtLeast(i - prInd) + } + minInd = if (nums[i] < nums[minInd]) i else minInd + } + return ramp + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0963_minimum_area_rectangle_ii/readme.md b/src/main/kotlin/g0901_1000/s0963_minimum_area_rectangle_ii/readme.md new file mode 100644 index 00000000..8c0cbd33 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0963_minimum_area_rectangle_ii/readme.md @@ -0,0 +1,103 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 963\. Minimum Area Rectangle II + +Medium + +You are given an array of points in the **X-Y** plane `points` where points[i] = [xi, yi]. + +Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`. + +Answers within 10-5 of the actual answer will be accepted. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2018/12/21/1a.png) + +**Input:** points = \[\[1,2],[2,1],[1,0],[0,1]] + +**Output:** 2.00000 + +**Explanation:** The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2018/12/22/2.png) + +**Input:** points = \[\[0,1],[2,1],[1,1],[1,0],[2,0]] + +**Output:** 1.00000 + +**Explanation:** The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2018/12/22/3.png) + +**Input:** points = \[\[0,3],[1,2],[3,1],[1,3],[2,1]] + +**Output:** 0 + +**Explanation:** There is no possible rectangle to form from these points. + +**Constraints:** + +* `1 <= points.length <= 50` +* `points[i].length == 2` +* 0 <= xi, yi <= 4 * 104 +* All the given points are **unique**. + +## Solution + +```kotlin +import kotlin.math.abs + +class Solution { + fun minAreaFreeRect(points: Array): Double { + val map: MutableMap> = HashMap() + var area: Double + for (point in points) { + map.putIfAbsent(point[0], HashSet()) + map.getValue(point[0]).add(point[1]) + } + var minArea = Double.MAX_VALUE + val n = points.size + for (i in 0 until n - 2) { + for (j in i + 1 until n - 1) { + val dx1 = points[j][0] - points[i][0] + val dy1 = points[j][1] - points[i][1] + // get the 3rd point + for (k in j + 1 until n) { + val dx2 = points[k][0] - points[i][0] + val dy2 = points[k][1] - points[i][1] + if (dx1 * dx2 + dy1 * dy2 != 0) { + continue + } + // find the 4th point + val x = dx1 + points[k][0] + val y = dy1 + points[k][1] + area = calculateArea(points, i, j, k) + if (area >= minArea) { + continue + } + // 4th point exists + if (map[x] != null && map.getValue(x).contains(y)) { + minArea = area + } + } + } + } + return if (minArea == Double.MAX_VALUE) 0.0 else minArea + } + + private fun calculateArea(points: Array, i: Int, j: Int, k: Int): Double { + val first = points[i] + val second = points[j] + val third = points[k] + return abs( + first[0] * (second[1] - third[1]) + second[0] * (third[1] - first[1]) + third[0] * (first[1] - second[1]) + ).toDouble() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0964_least_operators_to_express_number/readme.md b/src/main/kotlin/g0901_1000/s0964_least_operators_to_express_number/readme.md new file mode 100644 index 00000000..8bd3b817 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0964_least_operators_to_express_number/readme.md @@ -0,0 +1,98 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 964\. Least Operators to Express Number + +Hard + +Given a single positive integer `x`, we will write an expression of the form `x (op1) x (op2) x (op3) x ...` where each operator `op1`, `op2`, etc. is either addition, subtraction, multiplication, or division (`+`, `-`, `*`, or `/)`. For example, with `x = 3`, we might write `3 * 3 / 3 + 3 - 3` which is a value of 3. + +When writing such an expression, we adhere to the following conventions: + +* The division operator (`/`) returns rational numbers. +* There are no parentheses placed anywhere. +* We use the usual order of operations: multiplication and division happen before addition and subtraction. +* It is not allowed to use the unary negation operator (`-`). For example, "`x - x`" is a valid expression as it only uses subtraction, but "`-x + x`" is not because it uses negation. + +We would like to write an expression with the least number of operators such that the expression equals the given `target`. Return the least number of operators used. + +**Example 1:** + +**Input:** x = 3, target = 19 + +**Output:** 5 + +**Explanation:** 3 \* 3 + 3 \* 3 + 3 / 3. The expression contains 5 operations. + +**Example 2:** + +**Input:** x = 5, target = 501 + +**Output:** 8 + +**Explanation:** 5 \* 5 \* 5 \* 5 - 5 \* 5 \* 5 + 5 / 5. The expression contains 8 operations. + +**Example 3:** + +**Input:** x = 100, target = 100000000 + +**Output:** 3 + +**Explanation:** 100 \* 100 \* 100 \* 100. The expression contains 3 operations. + +**Constraints:** + +* `2 <= x <= 100` +* 1 <= target <= 2 * 108 + +## Solution + +```kotlin +class Solution { + private val map: MutableMap = HashMap() + private var x = 0 + fun leastOpsExpressTarget(x: Int, target: Int): Int { + this.x = x + return if (x == target) { + 0 + } else dfs(0, target.toLong()) - 1 + } + + // ax^0 + bx^1 + cx^2 +.... + // think it as base x problem + private fun dfs(ex: Int, target: Long): Int { + if (target == 0L) { + return 0 + } + if (ex > 40) { + return 10000000 + } + val state = "$ex,$target" + if (map.containsKey(state)) { + return map.getValue(state) + } + var res = Int.MAX_VALUE + val mod = (target % x).toInt() + if (mod == 0) { + res = if (ex == 0) { + // not use + res.coerceAtMost(dfs(ex + 1, target)) + } else { + // not use + res.coerceAtMost(dfs(ex + 1, target / x)) + } + } else { + // division is needed + if (ex == 0) { + res = res.coerceAtMost(2 * mod + dfs(ex + 1, target - mod)) + res = res.coerceAtMost(2 * (x - mod) + dfs(ex + 1, target - mod + x)) + } else { + res = res.coerceAtMost((ex - 1) * mod + dfs(ex + 1, (target - mod) / x)) + res = res.coerceAtMost((ex - 1) * (x - mod) + dfs(ex + 1, (target - mod + x) / x)) + } + } + map[state] = res + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0965_univalued_binary_tree/readme.md b/src/main/kotlin/g0901_1000/s0965_univalued_binary_tree/readme.md new file mode 100644 index 00000000..0070991f --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0965_univalued_binary_tree/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) + +## 965\. Univalued Binary Tree + +Easy + +A binary tree is **uni-valued** if every node in the tree has the same value. + +Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2018/12/28/unival_bst_1.png) + +**Input:** root = [1,1,1,1,1,null,1] + +**Output:** true + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2018/12/28/unival_bst_2.png) + +**Input:** root = [2,2,2,5,2] + +**Output:** false + +**Constraints:** + +* The number of nodes in the tree is in the range `[1, 100]`. +* `0 <= Node.val < 100` + +## 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 isUnivalTree(root: TreeNode?): Boolean { + val `val`: Int = root!!.`val` + val queue: LinkedList = LinkedList() + queue.add(root) + while (queue.isNotEmpty()) { + val node: TreeNode? = queue.poll() + if (node!!.`val` != `val`) { + return false + } + if (node.left != null) { + queue.add(node.left) + } + if (node.right != null) { + queue.add(node.right) + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0966_vowel_spellchecker/readme.md b/src/main/kotlin/g0901_1000/s0966_vowel_spellchecker/readme.md new file mode 100644 index 00000000..79b582a9 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0966_vowel_spellchecker/readme.md @@ -0,0 +1,99 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 966\. Vowel Spellchecker + +Medium + +Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word. + +For a given `query` word, the spell checker handles two categories of spelling mistakes: + +* Capitalization: If the query matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the case in the wordlist. + * Example: `wordlist = ["yellow"]`, `query = "YellOw"`: `correct = "yellow"` + * Example: `wordlist = ["Yellow"]`, `query = "yellow"`: `correct = "Yellow"` + * Example: `wordlist = ["yellow"]`, `query = "yellow"`: `correct = "yellow"` +* Vowel Errors: If after replacing the vowels `('a', 'e', 'i', 'o', 'u')` of the query word with any vowel individually, it matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the match in the wordlist. + * Example: `wordlist = ["YellOw"]`, `query = "yollow"`: `correct = "YellOw"` + * Example: `wordlist = ["YellOw"]`, `query = "yeellow"`: `correct = ""` (no match) + * Example: `wordlist = ["YellOw"]`, `query = "yllw"`: `correct = ""` (no match) + +In addition, the spell checker operates under the following precedence rules: + +* When the query exactly matches a word in the wordlist (**case-sensitive**), you should return the same word back. +* When the query matches a word up to capitlization, you should return the first such match in the wordlist. +* When the query matches a word up to vowel errors, you should return the first such match in the wordlist. +* If the query has no matches in the wordlist, you should return the empty string. + +Given some `queries`, return a list of words `answer`, where `answer[i]` is the correct word for `query = queries[i]`. + +**Example 1:** + +**Input:** wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"] + +**Output:** ["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"] + +**Example 2:** + +**Input:** wordlist = ["yellow"], queries = ["YellOw"] + +**Output:** ["yellow"] + +**Constraints:** + +* `1 <= wordlist.length, queries.length <= 5000` +* `1 <= wordlist[i].length, queries[i].length <= 7` +* `wordlist[i]` and `queries[i]` consist only of only English letters. + +## Solution + +```kotlin +class Solution { + private var matched: HashSet? = null + private var capitalizations: HashMap? = null + private var vowelErrors: HashMap? = null + private fun isVowel(w: Char): Boolean { + return w == 'a' || w == 'e' || w == 'i' || w == 'o' || w == 'u' + } + + private fun removeVowels(word: String): String { + val s = StringBuilder() + for (w in word.toCharArray()) { + s.append(if (isVowel(w)) '*' else w) + } + return s.toString() + } + + private fun solveQuery(query: String): String? { + if (matched!!.contains(query)) { + return query + } + var word = query.lowercase() + if (capitalizations!!.containsKey(word)) { + return capitalizations!![word] + } + word = removeVowels(word) + return if (vowelErrors!!.containsKey(word)) { + vowelErrors!![word] + } else "" + } + + fun spellchecker(wordlist: Array, queries: Array): Array { + val answer = arrayOfNulls(queries.size) + matched = HashSet() + capitalizations = HashMap() + vowelErrors = HashMap() + for (word in wordlist) { + matched!!.add(word) + var s = word.lowercase() + capitalizations!!.putIfAbsent(s, word) + s = removeVowels(s) + vowelErrors!!.putIfAbsent(s, word) + } + for (i in queries.indices) { + answer[i] = solveQuery(queries[i]) + } + return answer + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0967_numbers_with_same_consecutive_differences/readme.md b/src/main/kotlin/g0901_1000/s0967_numbers_with_same_consecutive_differences/readme.md new file mode 100644 index 00000000..6120d2fc --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0967_numbers_with_same_consecutive_differences/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) + +## 967\. Numbers With Same Consecutive Differences + +Medium + +Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**. + +Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed. + +**Example 1:** + +**Input:** n = 3, k = 7 + +**Output:** [181,292,707,818,929] + +**Explanation:** Note that 070 is not a valid number, because it has leading zeroes. + +**Example 2:** + +**Input:** n = 2, k = 1 + +**Output:** [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98] + +**Constraints:** + +* `2 <= n <= 9` +* `0 <= k <= 9` + +## Solution + +```kotlin +import kotlin.math.abs + +@Suppress("NAME_SHADOWING") +class Solution { + fun numsSameConsecDiff(n: Int, k: Int): IntArray { + var k = k + k = abs(k) + val list: MutableList = ArrayList() + dfs(list, 100000, 0, n, k) + val res = IntArray(list.size) + for (i in res.indices) { + res[i] = list[i] + } + return res + } + + private fun dfs(list: MutableList, can: Int, len: Int, n: Int, k: Int) { + if (len == n) { + list.add(can) + return + } + if (can == 0) { + return + } + if (len == 0) { + for (i in 0..9) { + dfs(list, i, 1, n, k) + } + } else { + val last = can % 10 + val a = last + k + val b = last - k + if (b >= 0) { + dfs(list, can * 10 + b, len + 1, n, k) + } + if (k != 0 && a < 10) { + dfs(list, can * 10 + a, len + 1, n, k) + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0968_binary_tree_cameras/readme.md b/src/main/kotlin/g0901_1000/s0968_binary_tree_cameras/readme.md new file mode 100644 index 00000000..a96785f2 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0968_binary_tree_cameras/readme.md @@ -0,0 +1,87 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 968\. Binary Tree Cameras + +Hard + +You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. + +Return _the minimum number of cameras needed to monitor all nodes of the tree_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_01.png) + +**Input:** root = [0,0,null,0,0] + +**Output:** 1 + +**Explanation:** One camera is enough to monitor all nodes if placed as shown. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_02.png) + +**Input:** root = [0,0,null,0,null,0,null,null,0] + +**Output:** 2 + +**Explanation:** At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement. + +**Constraints:** + +* The number of nodes in the tree is in the range `[1, 1000]`. +* `Node.val == 0` + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private var cameras = 0 + fun minCameraCover(root: TreeNode?): Int { + cameras = 0 + if (minCameras(root) == -1) { + // root needs a camera + cameras++ + } + return cameras + } + + // States => + // -1 : Node needs a camera + // 0 : Node has a camera placed + // 1 : Node is covered somehow + private fun minCameras(root: TreeNode?): Int { + if (root == null) { + return 1 + } + val leftChildState = minCameras(root.left) + val rightChildState = minCameras(root.right) + // One of the two or both children need a camera + if (leftChildState == -1 || rightChildState == -1) { + // installed + cameras++ + return 0 + } + // One of the two or both children have a camera placed + return if (leftChildState == 0 || rightChildState == 0) { + // gets covered by the children + 1 + } else -1 + // needs a camera + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0969_pancake_sorting/readme.md b/src/main/kotlin/g0901_1000/s0969_pancake_sorting/readme.md new file mode 100644 index 00000000..d3c072a4 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0969_pancake_sorting/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) + +## 969\. Pancake Sorting + +Medium + +Given an array of integers `arr`, sort the array by performing a series of **pancake flips**. + +In one pancake flip we do the following steps: + +* Choose an integer `k` where `1 <= k <= arr.length`. +* Reverse the sub-array `arr[0...k-1]` (**0-indexed**). + +For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so arr = [1,2,3,4] after the pancake flip at `k = 3`. + +Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct. + +**Example 1:** + +**Input:** arr = [3,2,4,1] + +**Output:** [4,2,4,3] + +**Explanation:** + +We perform 4 pancake flips, with k values 4, 2, 4, and 3. + +Starting state: arr = [3, 2, 4, 1] + +After 1st flip (k = 4): arr = [1, 4, 2, 3] + +After 2nd flip (k = 2): arr = [4, 1, 2, 3] + +After 3rd flip (k = 4): arr = [3, 2, 1, 4] + +After 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted. + +**Example 2:** + +**Input:** arr = [1,2,3] + +**Output:** [] + +**Explanation:** The input is already sorted, so there is no need to flip anything. Note that other answers, such as [3, 3], would also be accepted. + +**Constraints:** + +* `1 <= arr.length <= 100` +* `1 <= arr[i] <= arr.length` +* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`). + +## Solution + +```kotlin +class Solution { + fun pancakeSort(arr: IntArray): List { + val result: MutableList = ArrayList() + for (i in arr.size downTo 1) { + var max = Int.MIN_VALUE + var index = 0 + for (j in 0 until i) { + if (max < arr[j]) { + index = j + 1 + max = arr[j] + } + } + result.add(index) + reverse(arr, index - 1) + result.add(i) + reverse(arr, i - 1) + } + return result + } + + private fun reverse(arr: IntArray, index: Int) { + for (i in 0..(index - 1) / 2) { + val temp = arr[i] + arr[i] = arr[index - i] + arr[index - i] = temp + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0970_powerful_integers/readme.md b/src/main/kotlin/g0901_1000/s0970_powerful_integers/readme.md new file mode 100644 index 00000000..65ed8582 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0970_powerful_integers/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) + +## 970\. Powerful Integers + +Medium + +Given three integers `x`, `y`, and `bound`, return _a list of all the **powerful integers** that have a value less than or equal to_ `bound`. + +An integer is **powerful** if it can be represented as xi + yj for some integers `i >= 0` and `j >= 0`. + +You may return the answer in **any order**. In your answer, each value should occur **at most once**. + +**Example 1:** + +**Input:** x = 2, y = 3, bound = 10 + +**Output:** [2,3,4,5,7,9,10] + +**Explanation:** + +2 = 20 + 30 + +3 = 21 + 30 + +4 = 20 + 31 + +5 = 21 + 31 + +7 = 22 + 31 + +9 = 23 + 30 + +10 = 20 + 32 + +**Example 2:** + +**Input:** x = 3, y = 5, bound = 15 + +**Output:** [2,4,6,8,10,14] + +**Constraints:** + +* `1 <= x, y <= 100` +* 0 <= bound <= 106 + +## Solution + +```kotlin +import kotlin.math.log10 +import kotlin.math.pow + +class Solution { + fun powerfulIntegers(x: Int, y: Int, bound: Int): List { + val iBound = if (x == 1) 1 else (log10(bound.toDouble()) / log10(x.toDouble())).toInt() + val jBound = if (y == 1) 1 else (log10(bound.toDouble()) / log10(y.toDouble())).toInt() + val set: HashSet = HashSet() + for (i in 0..iBound) { + for (j in 0..jBound) { + val number = (x.toDouble().pow(i.toDouble()) + y.toDouble().pow(j.toDouble())).toInt() + if (number <= bound) { + set.add(number) + } + } + } + return ArrayList(set) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0971_flip_binary_tree_to_match_preorder_traversal/readme.md b/src/main/kotlin/g0901_1000/s0971_flip_binary_tree_to_match_preorder_traversal/readme.md new file mode 100644 index 00000000..35d283f3 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0971_flip_binary_tree_to_match_preorder_traversal/readme.md @@ -0,0 +1,109 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 971\. Flip Binary Tree To Match Preorder Traversal + +Medium + +You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. + +Any node in the binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: + +![](https://assets.leetcode.com/uploads/2021/02/15/fliptree.jpg) + +Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`. + +Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/01/02/1219-01.png) + +**Input:** root = [1,2], voyage = [2,1] + +**Output:** [-1] + +**Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2019/01/02/1219-02.png) + +**Input:** root = [1,2,3], voyage = [1,3,2] + +**Output:** [1] + +**Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2019/01/02/1219-02.png) + +**Input:** root = [1,2,3], voyage = [1,2,3] + +**Output:** [] + +**Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped. + +**Constraints:** + +* The number of nodes in the tree is `n`. +* `n == voyage.length` +* `1 <= n <= 100` +* `1 <= Node.val, voyage[i] <= n` +* All the values in the tree are **unique**. +* All the values in `voyage` are **unique**. + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private val list: MutableList = ArrayList() + private var preIndex = 0 + private var isFlipPossible = true + + fun flipMatchVoyage(root: TreeNode?, voyage: IntArray): List { + list.clear() + preIndex = 0 + isFlipPossible = true + traverse(root, voyage) + if (!isFlipPossible) { + list.clear() + list.add(-1) + } + return list + } + + private fun traverse(root: TreeNode?, voyage: IntArray) { + if (root == null) { + return + } + if (root.`val` != voyage[preIndex]) { + isFlipPossible = false + } else { + if (preIndex + 1 < voyage.size && root.left != null && root.left!!.`val` != voyage[preIndex + 1]) { + // swap + list.add(root.`val`) + val temp = root.right + root.right = root.left + root.left = temp + } + preIndex++ + traverse(root.left, voyage) + traverse(root.right, voyage) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0972_equal_rational_numbers/readme.md b/src/main/kotlin/g0901_1000/s0972_equal_rational_numbers/readme.md new file mode 100644 index 00000000..17686a42 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0972_equal_rational_numbers/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) + +## 972\. Equal Rational Numbers + +Hard + +Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. + +A **rational number** can be represented using up to three parts: ``, ``, and a ``. The number will be represented in one of the following three ways: + +* `` + * For example, `12`, `0`, and `123`. +* **<.>** + * For example, `0.5`, `1.`, `2.12`, and `123.0001`. +* **<.>****<(>****<)>** + * For example, `0.1(6)`, `1.(9)`, `123.00(1212)`. + +The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: + +* `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`. + +**Example 1:** + +**Input:** s = "0.(52)", t = "0.5(25)" + +**Output:** true + +**Explanation:** Because "0.(52)" represents 0.52525252..., and "0.5(25)" represents 0.52525252525..... , the strings represent the same number. + +**Example 2:** + +**Input:** s = "0.1666(6)", t = "0.166(66)" + +**Output:** true + +**Example 3:** + +**Input:** s = "0.9(9)", t = "1." + +**Output:** true + +**Explanation:** "0.9(9)" represents 0.999999999... repeated forever, which equals 1. [[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)] "1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = "". + +**Constraints:** + +* Each part consists only of digits. +* The `` does not have leading zeros (except for the zero itself). +* `1 <= .length <= 4` +* `0 <= .length <= 4` +* `1 <= .length <= 4` + +## Solution + +```kotlin +import kotlin.math.abs +import kotlin.math.pow + +class Solution { + fun isRationalEqual(s: String, t: String): Boolean { + return abs(valueOf(s) - valueOf(t)) < 1e-9 + } + private val ratios = doubleArrayOf(1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999) + private fun valueOf(s: String): Double { + if (!s.contains("(")) return java.lang.Double.valueOf(s) + val integerNonRepeating = java.lang.Double.valueOf(s.substring(0, s.indexOf('('))) + val nonRepeatingLength = s.indexOf('(') - s.indexOf('.') - 1 + val repeating = s.substring(s.indexOf('(') + 1, s.indexOf(')')).toInt() + val repeatingLength = s.indexOf(')') - s.indexOf('(') - 1 + return integerNonRepeating + + repeating * 0.1.pow(nonRepeatingLength.toDouble()) * ratios[repeatingLength] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0973_k_closest_points_to_origin/readme.md b/src/main/kotlin/g0901_1000/s0973_k_closest_points_to_origin/readme.md new file mode 100644 index 00000000..e601808f --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0973_k_closest_points_to_origin/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) + +## 973\. K Closest Points to Origin + +Medium + +Given an array of `points` where points[i] = [xi, yi] represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`. + +The distance between two points on the **X-Y** plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). + +You may return the answer in **any order**. The answer is **guaranteed** to be **unique** (except for the order that it is in). + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/03/closestplane1.jpg) + +**Input:** points = \[\[1,3],[-2,2]], k = 1 + +**Output:** [[-2,2]] + +**Explanation:** + +The distance between (1, 3) and the origin is sqrt(10). + +The distance between (-2, 2) and the origin is sqrt(8). + +Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. + +We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. + +**Example 2:** + +**Input:** points = \[\[3,3],[5,-1],[-2,4]], k = 2 + +**Output:** [[3,3],[-2,4]] + +**Explanation:** The answer [[-2,4],[3,3]] would also be accepted. + +**Constraints:** + +* 1 <= k <= points.length <= 104 +* -104 < xi, yi < 104 + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + internal inner class Points(var x: Int, var y: Int) { + var distanceFromO: Int = x * x + y * y + } + + fun kClosest(points: Array, k: Int): Array { + val p = PriorityQueue { a: Points, b: Points -> a.distanceFromO - b.distanceFromO } + for (pi in points) { + p.add(Points(pi[0], pi[1])) + } + val n = Array(k) { IntArray(2) } + var i = 0 + while (i < k) { + val po = p.remove() + n[i++] = intArrayOf(po.x, po.y) + } + return n + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0974_subarray_sums_divisible_by_k/readme.md b/src/main/kotlin/g0901_1000/s0974_subarray_sums_divisible_by_k/readme.md new file mode 100644 index 00000000..ac288295 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0974_subarray_sums_divisible_by_k/readme.md @@ -0,0 +1,52 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 974\. Subarray Sums Divisible by K + +Medium + +Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. + +A **subarray** is a **contiguous** part of an array. + +**Example 1:** + +**Input:** nums = [4,5,0,-2,-3,1], k = 5 + +**Output:** 7 + +**Explanation:** There are 7 subarrays with a sum divisible by k = 5: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] + +**Example 2:** + +**Input:** nums = [5], k = 9 + +**Output:** 0 + +**Constraints:** + +* 1 <= nums.length <= 3 * 104 +* -104 <= nums[i] <= 104 +* 2 <= k <= 104 + +## Solution + +```kotlin +class Solution { + fun subarraysDivByK(nums: IntArray, k: Int): Int { + val map = IntArray(k) + var ans = 0 + var sum = 0 + map[0] = 1 + for (num in nums) { + sum += num + var temp = sum % k + if (temp < 0) { + temp += k + } + ans += map[temp]++ + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0975_odd_even_jump/readme.md b/src/main/kotlin/g0901_1000/s0975_odd_even_jump/readme.md new file mode 100644 index 00000000..e8d741f5 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0975_odd_even_jump/readme.md @@ -0,0 +1,142 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 975\. Odd Even Jump + +Hard + +You are given an integer array `arr`. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called **odd-numbered jumps**, and the (2nd, 4th, 6th, ...) jumps in the series are called **even-numbered jumps**. Note that the **jumps** are numbered, not the indices. + +You may jump forward from index `i` to index `j` (with `i < j`) in the following way: + +* During **odd-numbered jumps** (i.e., jumps 1, 3, 5, ...), you jump to the index `j` such that `arr[i] <= arr[j]` and `arr[j]` is the smallest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`. +* During **even-numbered jumps** (i.e., jumps 2, 4, 6, ...), you jump to the index `j` such that `arr[i] >= arr[j]` and `arr[j]` is the largest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`. +* It may be the case that for some index `i`, there are no legal jumps. + +A starting index is **good** if, starting from that index, you can reach the end of the array (index `arr.length - 1`) by jumping some number of times (possibly 0 or more than once). + +Return _the number of **good** starting indices_. + +**Example 1:** + +**Input:** arr = [10,13,12,14,15] + +**Output:** 2 + +**Explanation:** + +From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], + +arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more. + +From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more. + +From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end. + +From starting index i = 4, we have reached the end already. + +In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of jumps. + +**Example 2:** + +**Input:** arr = [2,3,1,1,4] + +**Output:** 3 + +**Explanation:** + +From starting index i = 0, we make jumps to i = 1, i = 2, i = 3: + +During our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], + +arr[2], arr[3], arr[4]] that is greater than or equal to arr[0]. + +During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in + +[arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a + +smaller index, so we can only jump to i = 2 and not i = 3 + +During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in + +[arr[3], arr[4]] that is greater than or equal to arr[2]. + +We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good. + +In a similar manner, we can deduce that: From starting index i = 1, we jump to i = 4, so we reach the end. + +From starting index i = 2, we jump to i = 3, and then we can't jump anymore. + +From starting index i = 3, we jump to i = 4, so we reach the end. + +From starting index i = 4, we are already at the end. + +In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with + +some number of jumps. + +**Example 3:** + +**Input:** arr = [5,1,3,4,2] + +**Output:** 3 + +**Explanation:** We can reach the end from starting indices 1, 2, and 4. + +**Constraints:** + +* 1 <= arr.length <= 2 * 104 +* 0 <= arr[i] < 105 + +## Solution + +```kotlin +class Solution { + private lateinit var valToPos: IntArray + + fun oddEvenJumps(arr: IntArray): Int { + val size = arr.size + val odd = BooleanArray(size) + val even = BooleanArray(size) + valToPos = IntArray(100001) + valToPos.fill(-1) + valToPos[arr[size - 1]] = size - 1 + even[size - 1] = true + odd[size - 1] = even[size - 1] + var count = 1 + for (i in size - 2 downTo 0) { + val curVal = arr[i] + val maxS = findMaxS(curVal) + val minL = findMinL(curVal) + if (minL != -1 && even[minL]) { + // System.out.println("find minL is true at: "+minL+" start from "+i); + odd[i] = even[minL] + count++ + } + if (maxS != -1) { + even[i] = odd[maxS] + } + valToPos[arr[i]] = i + } + return count + } + + private fun findMaxS(`val`: Int): Int { + for (i in `val` downTo 0) { + if (valToPos[i] != -1) { + return valToPos[i] + } + } + return -1 + } + + private fun findMinL(`val`: Int): Int { + for (i in `val`..100000) { + if (valToPos[i] != -1) { + return valToPos[i] + } + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0976_largest_perimeter_triangle/readme.md b/src/main/kotlin/g0901_1000/s0976_largest_perimeter_triangle/readme.md new file mode 100644 index 00000000..bbf3c5fb --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0976_largest_perimeter_triangle/readme.md @@ -0,0 +1,53 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 976\. Largest Perimeter Triangle + +Easy + +Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`. + +**Example 1:** + +**Input:** nums = [2,1,2] + +**Output:** 5 + +**Explanation:** You can form a triangle with three side lengths: 1, 2, and 2. + +**Example 2:** + +**Input:** nums = [1,2,1,10] + +**Output:** 0 + +**Explanation:** + +You cannot use the side lengths 1, 1, and 2 to form a triangle. + +You cannot use the side lengths 1, 1, and 10 to form a triangle. + +You cannot use the side lengths 1, 2, and 10 to form a triangle. + +As we cannot use any three side lengths to form a triangle of non-zero area, we return 0. + +**Constraints:** + +* 3 <= nums.length <= 104 +* 1 <= nums[i] <= 106 + +## Solution + +```kotlin +class Solution { + fun largestPerimeter(nums: IntArray): Int { + nums.sort() + for (i in nums.size - 1 downTo 2) { + if (nums[i] < nums[i - 1] + nums[i - 2]) { + return nums[i] + nums[i - 1] + nums[i - 2] + } + } + return 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0977_squares_of_a_sorted_array/readme.md b/src/main/kotlin/g0901_1000/s0977_squares_of_a_sorted_array/readme.md new file mode 100644 index 00000000..b1a222c6 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0977_squares_of_a_sorted_array/readme.md @@ -0,0 +1,58 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 977\. Squares of a Sorted Array + +Easy + +Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. + +**Example 1:** + +**Input:** nums = [-4,-1,0,3,10] + +**Output:** [0,1,9,16,100] + +**Explanation:** After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. + +**Example 2:** + +**Input:** nums = [-7,-3,2,3,11] + +**Output:** [4,9,9,49,121] + +**Constraints:** + +* 1 <= nums.length <= 104 +* -104 <= nums[i] <= 104 +* `nums` is sorted in **non-decreasing** order. + +**Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach? + +## Solution + +```kotlin +import kotlin.math.abs + +class Solution { + fun sortedSquares(nums: IntArray): IntArray { + var l = 0 + var r = nums.size - 1 + val res = IntArray(nums.size) + // Iterate res from back to front. put the bigger of abs(l) * abs(l) and abs(r) * abs(r) at + // res[i] and increment respectively + for (i in nums.indices.reversed()) { + // If the negative is larger, put it at the end and increment left ptr to next lower + // negative + if (abs(nums[l]) > nums[r]) { + res[i] = nums[l] * nums[l] + l++ + } else { + res[i] = nums[r] * nums[r] + r-- + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0978_longest_turbulent_subarray/readme.md b/src/main/kotlin/g0901_1000/s0978_longest_turbulent_subarray/readme.md new file mode 100644 index 00000000..d850a5cf --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0978_longest_turbulent_subarray/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) + +## 978\. Longest Turbulent Subarray + +Medium + +Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`. + +A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray. + +More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only if: + +* For `i <= k < j`: + * `arr[k] > arr[k + 1]` when `k` is odd, and + * `arr[k] < arr[k + 1]` when `k` is even. +* Or, for `i <= k < j`: + * `arr[k] > arr[k + 1]` when `k` is even, and + * `arr[k] < arr[k + 1]` when `k` is odd. + +**Example 1:** + +**Input:** arr = [9,4,2,10,7,8,8,1,9] + +**Output:** 5 + +**Explanation:** arr[1] > arr[2] < arr[3] > arr[4] < arr[5] + +**Example 2:** + +**Input:** arr = [4,8,12,16] + +**Output:** 2 + +**Example 3:** + +**Input:** arr = [100] + +**Output:** 1 + +**Constraints:** + +* 1 <= arr.length <= 4 * 104 +* 0 <= arr[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun maxTurbulenceSize(arr: IntArray): Int { + val n = arr.size + var ans = 1 + var l: Int + if (n == 1) { + return 1 + } + if (n == 2) { + return if (arr[0] == arr[1]) 1 else 2 + } + l = 0 + var r = 1 + while (r < n - 1) { + val difL = arr[r] - arr[r - 1] + val difR = arr[r] - arr[r + 1] + if (difL == 0 && difR == 0) { + l = r + 1 + } else if (difL == 0) { + ans = ans.coerceAtLeast(r - l) + l = r + } else if (!(difL < 0 && difR < 0 || difL > 0 && difR > 0)) { + ans = ans.coerceAtLeast(r - l + 1) + l = r + } + r++ + } + return ans.coerceAtLeast(r - l + 1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0979_distribute_coins_in_binary_tree/readme.md b/src/main/kotlin/g0901_1000/s0979_distribute_coins_in_binary_tree/readme.md new file mode 100644 index 00000000..c359ac82 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0979_distribute_coins_in_binary_tree/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) + +## 979\. Distribute Coins in Binary Tree + +Medium + +You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. + +In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. + +Return _the **minimum** number of moves required to make every node have **exactly** one coin_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/01/18/tree1.png) + +**Input:** root = [3,0,0] + +**Output:** 2 + +**Explanation:** From the root of the tree, we move one coin to its left child, and one coin to its right child. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2019/01/18/tree2.png) + +**Input:** root = [0,3,0] + +**Output:** 3 + +**Explanation:** From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child. + +**Constraints:** + +* The number of nodes in the tree is `n`. +* `1 <= n <= 100` +* `0 <= Node.val <= n` +* The sum of all `Node.val` is `n`. + +## Solution + +```kotlin +import com_github_leetcode.TreeNode +import kotlin.math.abs + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private var num = 0 + fun distributeCoins(root: TreeNode?): Int { + helper(root) + return num + } + + private fun helper(node: TreeNode?): Int { + if (node == null) { + return 0 + } + val total: Int = node.`val` + helper(node.left) + helper(node.right) + val leftover = total - 1 + num += abs(leftover) + return leftover + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0980_unique_paths_iii/readme.md b/src/main/kotlin/g0901_1000/s0980_unique_paths_iii/readme.md new file mode 100644 index 00000000..cd0916a9 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0980_unique_paths_iii/readme.md @@ -0,0 +1,113 @@ +[![](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) + +## 980\. Unique Paths III + +Hard + +You are given an `m x n` integer array `grid` where `grid[i][j]` could be: + +* `1` representing the starting square. There is exactly one starting square. +* `2` representing the ending square. There is exactly one ending square. +* `0` representing empty squares we can walk over. +* `-1` representing obstacles that we cannot walk over. + +Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/08/02/lc-unique1.jpg) + +**Input:** grid = \[\[1,0,0,0],[0,0,0,0],[0,0,2,-1]] + +**Output:** 2 + +**Explanation:** We have the following two paths: +1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) +2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/08/02/lc-unique2.jpg) + +**Input:** grid = \[\[1,0,0,0],[0,0,0,0],[0,0,0,2]] + +**Output:** 4 + +**Explanation:** We have the following four paths: +1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) +2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) +3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) +4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/08/02/lc-unique3-.jpg) + +**Input:** grid = \[\[0,1],[2,0]] + +**Output:** 0 + +**Explanation:** There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `1 <= m, n <= 20` +* `1 <= m * n <= 20` +* `-1 <= grid[i][j] <= 2` +* There is exactly one starting cell and one ending cell. + +## Solution + +```kotlin +class Solution { + private val row = intArrayOf(0, 0, 1, -1) + private val col = intArrayOf(1, -1, 0, 0) + + private fun isSafe(grid: Array, rows: Int, cols: Int, i: Int, j: Int): Int { + if (i < 0 || j < 0 || i >= rows || j >= cols || grid[i][j] == -1) { + return 0 + } + if (grid[i][j] == 2) { + for (l in 0 until rows) { + for (m in 0 until cols) { + if (grid[l][m] == 0) { + /* Return 0 if all zeros in the path are not covered */ + return 0 + } + } + } + /* Return 1, as we covered all zeros in the path */ + return 1 + } + /* mark as visited */ + grid[i][j] = -1 + var result = 0 + for (k in 0..3) { + /* travel in all four directions (up,down,right,left) */ + result += isSafe(grid, rows, cols, i + row[k], j + col[k]) + } + /* Mark unvisited again to backtrack */ + grid[i][j] = 0 + return result + } + + fun uniquePathsIII(grid: Array): Int { + val rows = grid.size + val cols = grid[0].size + var result = 0 + for (k in 0 until rows) { + for (m in 0 until cols) { + if (grid[k][m] == 1) { + /* find indexes where 1 is located and start covering paths */ + result = isSafe(grid, rows, cols, k, m) + break + } + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0981_time_based_key_value_store/readme.md b/src/main/kotlin/g0901_1000/s0981_time_based_key_value_store/readme.md new file mode 100644 index 00000000..f542b2a8 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0981_time_based_key_value_store/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 981\. Time Based Key-Value Store + +Medium + +Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp. + +Implement the `TimeMap` class: + +* `TimeMap()` Initializes the object of the data structure. +* `void set(String key, String value, int timestamp)` Stores the key `key` with the value `value` at the given time `timestamp`. +* `String get(String key, int timestamp)` Returns a value such that `set` was called previously, with `timestamp_prev <= timestamp`. If there are multiple such values, it returns the value associated with the largest `timestamp_prev`. If there are no values, it returns `""`. + +**Example 1:** + +**Input** + +["TimeMap", "set", "get", "get", "set", "get", "get"] + +[[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]] + +**Output:** [null, null, "bar", "bar", null, "bar2", "bar2"] + +**Explanation:** + + TimeMap timeMap = new TimeMap(); + timeMap.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1. + timeMap.get("foo", 1); // return "bar" + timeMap.get("foo", 3); // return "bar", since there is no value corresponding to foo at timestamp 3 + // and timestamp 2, then the only value is at timestamp 1 is "bar". + timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4. + timeMap.get("foo", 4); // return "bar2" timeMap.get("foo", 5); // return "bar2" + +**Constraints:** + +* `1 <= key.length, value.length <= 100` +* `key` and `value` consist of lowercase English letters and digits. +* 1 <= timestamp <= 107 +* All the timestamps `timestamp` of `set` are strictly increasing. +* At most 2 * 105 calls will be made to `set` and `get`. + +## Solution + +```kotlin +import java.util.TreeMap + +class TimeMap { + private val map = hashMapOf>() + + fun set(key: String, value: String, timestamp: Int) { + map.getOrPut(key, ::TreeMap)[timestamp] = value + } + + fun get(key: String, timestamp: Int): String { + return map[key]?.floorEntry(timestamp)?.value ?: "" + } +} + +/* + * Your TimeMap object will be instantiated and called as such: + * var obj = TimeMap() + * obj.set(key,value,timestamp) + * var param_2 = obj.get(key,timestamp) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0982_triples_with_bitwise_and_equal_to_zero/readme.md b/src/main/kotlin/g0901_1000/s0982_triples_with_bitwise_and_equal_to_zero/readme.md new file mode 100644 index 00000000..2c9e29d8 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0982_triples_with_bitwise_and_equal_to_zero/readme.md @@ -0,0 +1,99 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 982\. Triples with Bitwise AND Equal To Zero + +Hard + +Given an integer array nums, return _the number of **AND triples**_. + +An **AND triple** is a triple of indices `(i, j, k)` such that: + +* `0 <= i < nums.length` +* `0 <= j < nums.length` +* `0 <= k < nums.length` +* `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator. + +**Example 1:** + +**Input:** nums = [2,1,3] + +**Output:** 12 + +**Explanation:** We could choose the following i, j, k triples: + +(i=0, j=0, k=1) : 2 & 2 & 1 + +(i=0, j=1, k=0) : 2 & 1 & 2 + +(i=0, j=1, k=1) : 2 & 1 & 1 + +(i=0, j=1, k=2) : 2 & 1 & 3 + +(i=0, j=2, k=1) : 2 & 3 & 1 + +(i=1, j=0, k=0) : 1 & 2 & 2 + +(i=1, j=0, k=1) : 1 & 2 & 1 + +(i=1, j=0, k=2) : 1 & 2 & 3 + +(i=1, j=1, k=0) : 1 & 1 & 2 + +(i=1, j=2, k=0) : 1 & 3 & 2 + +(i=2, j=0, k=1) : 3 & 2 & 1 + +(i=2, j=1, k=0) : 3 & 1 & 2 + +**Example 2:** + +**Input:** nums = [0,0,0] + +**Output:** 27 + +**Constraints:** + +* `1 <= nums.length <= 1000` +* 0 <= nums[i] < 216 + +## Solution + +```kotlin +class Solution { + fun countTriplets(nums: IntArray): Int { + val arr = IntArray(1 shl 17) + for (num in nums) { + var mask = 0 + for (i in 0..15) { + if (num and (1 shl i) == 0) { + mask = mask or (1 shl i) + } + } + var s = mask + while (s > 0) { + arr[s]++ + s = s - 1 and mask + } + } + var count = 0 + for (j in nums) { + for (num in nums) { + val `val` = j and num + if (`val` == 0) { + count += nums.size + } else { + var mask = 0 + for (k in 0..15) { + if (`val` and (1 shl k) > 0) { + mask = mask or (1 shl k) + } + } + count += arr[mask] + } + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0983_minimum_cost_for_tickets/readme.md b/src/main/kotlin/g0901_1000/s0983_minimum_cost_for_tickets/readme.md new file mode 100644 index 00000000..19a6b714 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0983_minimum_cost_for_tickets/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) + +## 983\. Minimum Cost For Tickets + +Medium + +You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. + +Train tickets are sold in **three different ways**: + +* a **1-day** pass is sold for `costs[0]` dollars, +* a **7-day** pass is sold for `costs[1]` dollars, and +* a **30-day** pass is sold for `costs[2]` dollars. + +The passes allow that many days of consecutive travel. + +* For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`. + +Return _the minimum number of dollars you need to travel every day in the given list of days_. + +**Example 1:** + +**Input:** days = [1,4,6,7,8,20], costs = [2,7,15] + +**Output:** 11 + +**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: + +On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1. + +On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9. + +On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20. + +In total, you spent $11 and covered all the days of your travel. + +**Example 2:** + +**Input:** days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15] + +**Output:** 17 + +**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: + +On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30. + +On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31. + +In total, you spent $17 and covered all the days of your travel. + +**Constraints:** + +* `1 <= days.length <= 365` +* `1 <= days[i] <= 365` +* `days` is in strictly increasing order. +* `costs.length == 3` +* `1 <= costs[i] <= 1000` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun mincostTickets(days: IntArray, costs: IntArray): Int { + val memo = IntArray(days.size + 1) + memo[memo.size - 1] = 0 + for (i in days.indices.reversed()) { + memo[i] = (costs[0] + memo[getNext(days, i, days[i])]).coerceAtMost( + costs[1] + memo[ + getNext( + days, + i, + days[i] + 6 + ) + ] + ).coerceAtMost(costs[2] + memo[getNext(days, i, days[i] + 29)]) + } + return memo[0] + } + + companion object { + fun getNext(days: IntArray, index: Int, goodUntil: Int): Int { + var index = index + while (index < days.size && days[index] <= goodUntil) { + index++ + } + return index + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0984_string_without_aaa_or_bbb/readme.md b/src/main/kotlin/g0901_1000/s0984_string_without_aaa_or_bbb/readme.md new file mode 100644 index 00000000..7dbbea1e --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0984_string_without_aaa_or_bbb/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) + +## 984\. String Without AAA or BBB + +Medium + +Given two integers `a` and `b`, return **any** string `s` such that: + +* `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters, +* The substring `'aaa'` does not occur in `s`, and +* The substring `'bbb'` does not occur in `s`. + +**Example 1:** + +**Input:** a = 1, b = 2 + +**Output:** "abb" + +**Explanation:** "abb", "bab" and "bba" are all correct answers. + +**Example 2:** + +**Input:** a = 4, b = 1 + +**Output:** "aabaa" + +**Constraints:** + +* `0 <= a, b <= 100` +* It is guaranteed such an `s` exists for the given `a` and `b`. + +## Solution + +```kotlin +class Solution { + fun strWithout3a3b(a: Int, b: Int): String { + val first = if (a > b) "a" else "b" + val second = if (first == "a") "b" else "a" + var firstLen = a.coerceAtLeast(b) + var secondLen = a.coerceAtMost(b) + val ans = StringBuilder() + // Case 1 : A and B count are unequal. + while (firstLen > 0 && secondLen > 0 && firstLen != secondLen) { + ans.append(first) + ans.append(first) + firstLen = firstLen - 2 + ans.append(second) + secondLen-- + } + // Case 2: A and B count are equal + while (firstLen > 0 && secondLen > 0) { + ans.append(first) + ans.append(second) + firstLen-- + secondLen-- + } + // left over, just append + while (firstLen > 0) { + ans.append(first) + firstLen-- + } + return ans.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0985_sum_of_even_numbers_after_queries/readme.md b/src/main/kotlin/g0901_1000/s0985_sum_of_even_numbers_after_queries/readme.md new file mode 100644 index 00000000..7e86e48b --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0985_sum_of_even_numbers_after_queries/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) + +## 985\. Sum of Even Numbers After Queries + +Medium + +You are given an integer array `nums` and an array `queries` where queries[i] = [vali, indexi]. + +For each query `i`, first, apply nums[indexi] = nums[indexi] + vali, then print the sum of the even values of `nums`. + +Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ ith _query_. + +**Example 1:** + +**Input:** nums = [1,2,3,4], queries = \[\[1,0],[-3,1],[-4,0],[2,3]] + +**Output:** [8,6,2,4] + +**Explanation:** At the beginning, the array is [1,2,3,4]. + +After adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8. + +After adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6. + +After adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2. + +After adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4. + +**Example 2:** + +**Input:** nums = [1], queries = \[\[4,0]] + +**Output:** [0] + +**Constraints:** + +* 1 <= nums.length <= 104 +* -104 <= nums[i] <= 104 +* 1 <= queries.length <= 104 +* -104 <= vali <= 104 +* 0 <= indexi < nums.length + +## Solution + +```kotlin +class Solution { + fun sumEvenAfterQueries(nums: IntArray, queries: Array): IntArray { + val result = IntArray(queries.size) + var res = 0 + for (num in nums) { + res += if (num and 1 == 0) num else 0 + } + for ((k, query) in queries.withIndex()) { + res -= if (nums[query[1]] and 1 == 0) nums[query[1]] else 0 + nums[query[1]] += query[0] + if (nums[query[1]] and 1 == 0) { + res += nums[query[1]] + } + result[k] = res + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0986_interval_list_intersections/readme.md b/src/main/kotlin/g0901_1000/s0986_interval_list_intersections/readme.md new file mode 100644 index 00000000..d0a0e74c --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0986_interval_list_intersections/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) + +## 986\. Interval List Intersections + +Medium + +You are given two lists of closed intervals, `firstList` and `secondList`, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise **disjoint** and in **sorted order**. + +Return _the intersection of these two interval lists_. + +A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`. + +The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/01/30/interval1.png) + +**Input:** firstList = \[\[0,2],[5,10],[13,23],[24,25]], secondList = \[\[1,5],[8,12],[15,24],[25,26]] + +**Output:** [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]] + +**Example 2:** + +**Input:** firstList = \[\[1,3],[5,9]], secondList = [] + +**Output:** [] + +**Constraints:** + +* `0 <= firstList.length, secondList.length <= 1000` +* `firstList.length + secondList.length >= 1` +* 0 <= starti < endi <= 109 +* endi < starti+1 +* 0 <= startj < endj <= 109 +* endj < startj+1 + +## Solution + +```kotlin +class Solution { + fun intervalIntersection(firstList: Array, secondList: Array): Array { + val list = ArrayList() + var i = 0 + var j = 0 + while (i < firstList.size && j < secondList.size) { + val start = firstList[i][0].coerceAtLeast(secondList[j][0]) + val end = firstList[i][1].coerceAtMost(secondList[j][1]) + if (start <= end) { + list.add(intArrayOf(start, end)) + } + if (firstList[i][1] > end) { + j++ + } else { + i++ + } + } + return list.toTypedArray() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0987_vertical_order_traversal_of_a_binary_tree/readme.md b/src/main/kotlin/g0901_1000/s0987_vertical_order_traversal_of_a_binary_tree/readme.md new file mode 100644 index 00000000..23bb8d18 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0987_vertical_order_traversal_of_a_binary_tree/readme.md @@ -0,0 +1,123 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 987\. Vertical Order Traversal of a Binary Tree + +Hard + +Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree. + +For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`. + +The **vertical order traversal** of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. + +Return _the **vertical order traversal** of the binary tree_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/01/29/vtree1.jpg) + +**Input:** root = [3,9,20,null,null,15,7] + +**Output:** [[9],[3,15],[20],[7]] + +**Explanation:** + +Column -1: Only node 9 is in this column. + +Column 0: Nodes 3 and 15 are in this column in that order from top to bottom. + +Column 1: Only node 20 is in this column. + +Column 2: Only node 7 is in this column. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/01/29/vtree2.jpg) + +**Input:** root = [1,2,3,4,5,6,7] + +**Output:** [[4],[2],[1,5,6],[3],[7]] + +**Explanation:** + +Column -2: Only node 4 is in this column. + +Column -1: Only node 2 is in this column. + +Column 0: Nodes 1, 5, and 6 are in this column. + +1 is at the top, so it comes first. +5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6. + +Column 1: Only node 3 is in this column. + +Column 2: Only node 7 is in this column. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/01/29/vtree3.jpg) + +**Input:** root = [1,2,3,4,6,5,7] + +**Output:** [[4],[2],[1,5,6],[3],[7]] + +**Explanation:** + +This case is the exact same as example 2, but with nodes 5 and 6 swapped. + +Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values. + +**Constraints:** + +* The number of nodes in the tree is in the range `[1, 1000]`. +* `0 <= Node.val <= 1000` + +## Solution + +```kotlin +import com_github_leetcode.TreeNode +import java.util.PriorityQueue +import java.util.Queue +import java.util.TreeMap + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private class Node internal constructor(var row: Int, var `val`: Int) + + fun verticalTraversal(root: TreeNode?): List> { + val map = TreeMap>() + helper(root, map, 0, 0) + val ret: MutableList> = ArrayList() + for (entry in map.iterator()) { + val list: MutableList = ArrayList() + ret.add(list) + while (entry.value.isNotEmpty()) { + list.add(entry.value.poll().`val`) + } + } + return ret + } + + private fun helper(cur: TreeNode?, map: TreeMap>, r: Int, c: Int) { + if (cur == null) { + return + } + map.putIfAbsent( + c, PriorityQueue { a: Node, b: Node -> if (a.row != b.row) a.row - b.row else a.`val` - b.`val` } + ) + map.getValue(c).add(Node(r, cur.`val`)) + helper(cur.left, map, r + 1, c - 1) + helper(cur.right, map, r + 1, c + 1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0988_smallest_string_starting_from_leaf/readme.md b/src/main/kotlin/g0901_1000/s0988_smallest_string_starting_from_leaf/readme.md new file mode 100644 index 00000000..4e12624f --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0988_smallest_string_starting_from_leaf/readme.md @@ -0,0 +1,87 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 988\. Smallest String Starting From Leaf + +Medium + +You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. + +Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. + +As a reminder, any shorter prefix of a string is **lexicographically smaller**. + +* For example, `"ab"` is lexicographically smaller than `"aba"`. + +A leaf of a node is a node that has no children. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/01/30/tree1.png) + +**Input:** root = [0,1,2,3,4,3,4] + +**Output:** "dba" + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2019/01/30/tree2.png) + +**Input:** root = [25,1,3,1,3,0,2] + +**Output:** "adz" + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2019/02/01/tree3.png) + +**Input:** root = [2,2,1,null,1,0,null,0] + +**Output:** "abc" + +**Constraints:** + +* The number of nodes in the tree is in the range `[1, 8500]`. +* `0 <= Node.val <= 25` + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private var res = "" + fun smallestFromLeaf(root: TreeNode?): String { + dfs(root, StringBuilder()) + return res + } + + private fun dfs(root: TreeNode?, currStr: StringBuilder) { + if (root == null) { + return + } + currStr.insert(0, (root.`val` + 97).toChar()) + if (root.left == null && root.right == null) { + res = if (res == "") { + currStr.toString() + } else { + if (res > currStr.toString()) currStr.toString() else res + } + } else { + dfs(root.left, currStr) + dfs(root.right, currStr) + } + currStr.deleteCharAt(0) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0989_add_to_array_form_of_integer/readme.md b/src/main/kotlin/g0901_1000/s0989_add_to_array_form_of_integer/readme.md new file mode 100644 index 00000000..2ad07db9 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0989_add_to_array_form_of_integer/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) + +## 989\. Add to Array-Form of Integer + +Easy + +The **array-form** of an integer `num` is an array representing its digits in left to right order. + +* For example, for `num = 1321`, the array form is `[1,3,2,1]`. + +Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. + +**Example 1:** + +**Input:** num = [1,2,0,0], k = 34 + +**Output:** [1,2,3,4] + +**Explanation:** 1200 + 34 = 1234 + +**Example 2:** + +**Input:** num = [2,7,4], k = 181 + +**Output:** [4,5,5] + +**Explanation:** 274 + 181 = 455 + +**Example 3:** + +**Input:** num = [2,1,5], k = 806 + +**Output:** [1,0,2,1] + +**Explanation:** 215 + 806 = 1021 + +**Constraints:** + +* 1 <= num.length <= 104 +* `0 <= num[i] <= 9` +* `num` does not contain any leading zeros except for the zero itself. +* 1 <= k <= 104 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun addToArrayForm(num: IntArray, k: Int): List { + var k = k + val result = ArrayList() + var carry = 0 + for (i in num.indices.reversed()) { + val temp = num[i] + k % 10 + carry + result.add(temp % 10) + carry = temp / 10 + k /= 10 + } + while (k > 0) { + val t = k % 10 + carry + result.add(t % 10) + carry = t / 10 + k /= 10 + } + if (carry == 1) { + result.add(1) + } + result.reverse() + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0990_satisfiability_of_equality_equations/readme.md b/src/main/kotlin/g0901_1000/s0990_satisfiability_of_equality_equations/readme.md new file mode 100644 index 00000000..ab3c2835 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0990_satisfiability_of_equality_equations/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) + +## 990\. Satisfiability of Equality Equations + +Medium + +You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: "xi==yi" or "xi!=yi".Here, xi and yi are lowercase letters (not necessarily different) that represent one-letter variable names. + +Return `true` _if it is possible to assign integers to variable names so as to satisfy all the given equations, or_ `false` _otherwise_. + +**Example 1:** + +**Input:** equations = ["a==b","b!=a"] + +**Output:** false + +**Explanation:** If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second. There is no way to assign the variables to satisfy both equations. + +**Example 2:** + +**Input:** equations = ["b==a","a==b"] + +**Output:** true + +**Explanation:** We could assign a = 1 and b = 1 to satisfy both equations. + +**Constraints:** + +* `1 <= equations.length <= 500` +* `equations[i].length == 4` +* `equations[i][0]` is a lowercase letter. +* `equations[i][1]` is either `'='` or `'!'`. +* `equations[i][2]` is `'='`. +* `equations[i][3]` is a lowercase letter. + +## Solution + +```kotlin +class Solution { + private lateinit var par: IntArray + fun equationsPossible(equations: Array): Boolean { + var counter = 0 + val map: HashMap = HashMap() + for (str in equations) { + var ch = str[0] + if (!map.containsKey(ch)) { + map[ch] = counter + counter++ + } + ch = str[3] + if (!map.containsKey(ch)) { + map[ch] = counter + counter++ + } + } + par = IntArray(counter) + for (i in par.indices) { + par[i] = i + } + for (str in equations) { + val oper = str.substring(1, 3) + if (oper == "==") { + val px = find(map[str[0]]) + val py = find(map[str[3]]) + if (px != py) { + par[px] = py + } + } + } + for (str in equations) { + val oper = str.substring(1, 3) + if (oper == "!=") { + val px = find(map[str[0]]) + val py = find(map[str[3]]) + if (px == py) { + return false + } + } + } + return true + } + + private fun find(x: Int?): Int { + if (par[x!!] == x) { + return x + } + par[x] = find(par[x]) + return par[x] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0991_broken_calculator/readme.md b/src/main/kotlin/g0901_1000/s0991_broken_calculator/readme.md new file mode 100644 index 00000000..2dafee84 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0991_broken_calculator/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) + +## 991\. Broken Calculator + +Medium + +There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can: + +* multiply the number on display by `2`, or +* subtract `1` from the number on display. + +Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `target` _on the calculator_. + +**Example 1:** + +**Input:** startValue = 2, target = 3 + +**Output:** 2 + +**Explanation:** Use double operation and then decrement operation {2 -> 4 -> 3}. + +**Example 2:** + +**Input:** startValue = 5, target = 8 + +**Output:** 2 + +**Explanation:** Use decrement and then double {5 -> 4 -> 8}. + +**Example 3:** + +**Input:** startValue = 3, target = 10 + +**Output:** 3 + +**Explanation:** Use double, decrement and double {3 -> 6 -> 5 -> 10}. + +**Constraints:** + +* 1 <= startValue, target <= 109 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun brokenCalc(startValue: Int, target: Int): Int { + var target = target + var result = 0 + while (startValue != target) { + if (target > startValue && target % 2 != 0) { + target += 1 + result++ + } else if (target > startValue) { + target /= 2 + result++ + } else { + result += startValue - target + break + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0992_subarrays_with_k_different_integers/readme.md b/src/main/kotlin/g0901_1000/s0992_subarrays_with_k_different_integers/readme.md new file mode 100644 index 00000000..8b003747 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0992_subarrays_with_k_different_integers/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) + +## 992\. Subarrays with K Different Integers + +Hard + +Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`. + +A **good array** is an array where the number of different integers in that array is exactly `k`. + +* For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`. + +A **subarray** is a **contiguous** part of an array. + +**Example 1:** + +**Input:** nums = [1,2,1,2,3], k = 2 + +**Output:** 7 + +**Explanation:** Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2] + +**Example 2:** + +**Input:** nums = [1,2,1,3,4], k = 3 + +**Output:** 3 + +**Explanation:** Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4]. + +**Constraints:** + +* 1 <= nums.length <= 2 * 104 +* `1 <= nums[i], k <= nums.length` + +## Solution + +```kotlin +class Solution { + fun subarraysWithKDistinct(nums: IntArray, k: Int): Int { + var res = 0 + var prefix = 0 + val cnt = IntArray(nums.size + 1) + var i = 0 + var j = 0 + var uniqueCount = 0 + while (i < nums.size) { + if (cnt[nums[i]]++ == 0) { + uniqueCount++ + } + if (uniqueCount > k) { + --cnt[nums[j++]] + prefix = 0 + uniqueCount-- + } + while (cnt[nums[j]] > 1) { + ++prefix + --cnt[nums[j++]] + } + if (uniqueCount == k) { + res += prefix + 1 + } + i++ + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0993_cousins_in_binary_tree/readme.md b/src/main/kotlin/g0901_1000/s0993_cousins_in_binary_tree/readme.md new file mode 100644 index 00000000..0c6f45df --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0993_cousins_in_binary_tree/readme.md @@ -0,0 +1,101 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 993\. Cousins in Binary Tree + +Easy + +Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._ + +Two nodes of a binary tree are **cousins** if they have the same depth with different parents. + +Note that in a binary tree, the root node is at the depth `0`, and children of each depth `k` node are at the depth `k + 1`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/02/12/q1248-01.png) + +**Input:** root = [1,2,3,4], x = 4, y = 3 + +**Output:** false + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2019/02/12/q1248-02.png) + +**Input:** root = [1,2,3,null,4,null,5], x = 5, y = 4 + +**Output:** true + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2019/02/13/q1248-03.png) + +**Input:** root = [1,2,3,null,4], x = 2, y = 3 + +**Output:** false + +**Constraints:** + +* The number of nodes in the tree is in the range `[2, 100]`. +* `1 <= Node.val <= 100` +* Each node has a **unique** value. +* `x != y` +* `x` and `y` are exist in the 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 isCousins(root: TreeNode?, x: Int, y: Int): Boolean { + return !isSiblings(root, x, y) && isSameLevels(root, x, y) + } + + private fun isSameLevels(root: TreeNode?, x: Int, y: Int): Boolean { + return findLevel(root, x, 0) == findLevel(root, y, 0) + } + + private fun findLevel(root: TreeNode?, x: Int, level: Int): Int { + if (root == null) { + return -1 + } + if (root.`val` == x) { + return level + } + val leftLevel = findLevel(root.left, x, level + 1) + return if (leftLevel == -1) { + findLevel(root.right, x, level + 1) + } else { + leftLevel + } + } + + private fun isSiblings(root: TreeNode?, x: Int, y: Int): Boolean { + if (root == null) { + return false + } + // Check children first + val leftSubTreeContainsCousins = isSiblings(root.left, x, y) + val rightSubTreeContainsCousins = isSiblings(root.right, x, y) + if (leftSubTreeContainsCousins || rightSubTreeContainsCousins) { + return true + } + return if (root.left == null || root.right == null) { + false + } else root.left!!.`val` == x && root.right!!.`val` == y || + root.right!!.`val` == x && root.left!!.`val` == y + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0994_rotting_oranges/readme.md b/src/main/kotlin/g0901_1000/s0994_rotting_oranges/readme.md index bfa1a123..6b745f4c 100644 --- a/src/main/kotlin/g0901_1000/s0994_rotting_oranges/readme.md +++ b/src/main/kotlin/g0901_1000/s0994_rotting_oranges/readme.md @@ -75,7 +75,7 @@ class Solution { var count = 0 val dx = intArrayOf(0, 0, 1, -1) val dy = intArrayOf(1, -1, 0, 0) - while (!queue.isEmpty()) { + while (queue.isNotEmpty()) { val size: Int = queue.size count += size for (i in 0 until size) { @@ -90,7 +90,7 @@ class Solution { queue.add(intArrayOf(x, y)) } } - if (!queue.isEmpty()) { + if (queue.isNotEmpty()) { countCurrent++ } } diff --git a/src/main/kotlin/g0901_1000/s0995_minimum_number_of_k_consecutive_bit_flips/readme.md b/src/main/kotlin/g0901_1000/s0995_minimum_number_of_k_consecutive_bit_flips/readme.md new file mode 100644 index 00000000..e29f1f46 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0995_minimum_number_of_k_consecutive_bit_flips/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) + +## 995\. Minimum Number of K Consecutive Bit Flips + +Hard + +You are given a binary array `nums` and an integer `k`. + +A **k-bit flip** is choosing a **subarray** of length `k` from `nums` and simultaneously changing every `0` in the subarray to `1`, and every `1` in the subarray to `0`. + +Return _the minimum number of **k-bit flips** required so that there is no_ `0` _in the array_. If it is not possible, return `-1`. + +A **subarray** is a **contiguous** part of an array. + +**Example 1:** + +**Input:** nums = [0,1,0], k = 1 + +**Output:** 2 + +**Explanation:** Flip nums[0], then flip nums[2]. + +**Example 2:** + +**Input:** nums = [1,1,0], k = 2 + +**Output:** -1 + +**Explanation:** No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1]. + +**Example 3:** + +**Input:** nums = [0,0,0,1,0,1,1,0], k = 3 + +**Output:** 3 + +**Explanation:** + +Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0] + +Flip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0] + +Flip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1] + +**Constraints:** + +* 1 <= nums.length <= 105 +* `1 <= k <= nums.length` + +## Solution + +```kotlin +class Solution { + fun minKBitFlips(nums: IntArray, k: Int): Int { + val n = nums.size + val pref = IntArray(n) + for (i in 0 until n) { + if (i == 0) { + if (nums[i] == 0) { + pref[i]++ + } + } else { + pref[i] = pref[i - 1] + val flips = pref[i] - if (i - k >= 0) pref[i - k] else 0 + if (flips % 2 == nums[i]) { + if (i + k > n) { + return -1 + } + pref[i]++ + } + } + } + return pref[n - 1] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0996_number_of_squareful_arrays/readme.md b/src/main/kotlin/g0901_1000/s0996_number_of_squareful_arrays/readme.md new file mode 100644 index 00000000..6968a4fb --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0996_number_of_squareful_arrays/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) + +## 996\. Number of Squareful Arrays + +Hard + +An array is **squareful** if the sum of every pair of adjacent elements is a **perfect square**. + +Given an integer array nums, return _the number of permutations of_ `nums` _that are **squareful**_. + +Two permutations `perm1` and `perm2` are different if there is some index `i` such that `perm1[i] != perm2[i]`. + +**Example 1:** + +**Input:** nums = [1,17,8] + +**Output:** 2 + +**Explanation:** [1,8,17] and [17,8,1] are the valid permutations. + +**Example 2:** + +**Input:** nums = [2,2,2] + +**Output:** 1 + +**Constraints:** + +* `1 <= nums.length <= 12` +* 0 <= nums[i] <= 109 + +## Solution + +```kotlin +import kotlin.math.sqrt + +class Solution { + var count = 0 + fun numSquarefulPerms(nums: IntArray): Int { + val n = nums.size + if (n < 2) { + return count + } + backtrack(nums, n, 0) + return count + } + + private fun backtrack(nums: IntArray, n: Int, start: Int) { + if (start == n) { + count++ + } + val set: MutableSet = HashSet() + for (i in start until n) { + if (set.contains(nums[i])) { + continue + } + swap(nums, start, i) + if (start == 0 || isPerfectSq(nums[start], nums[start - 1])) { + backtrack(nums, n, start + 1) + } + swap(nums, start, i) + set.add(nums[i]) + } + } + + private fun swap(array: IntArray, a: Int, b: Int) { + val temp = array[a] + array[a] = array[b] + array[b] = temp + } + + private fun isPerfectSq(a: Int, b: Int): Boolean { + val x = a + b + val sqrt = sqrt(x.toDouble()) + return sqrt - sqrt.toInt() == 0.0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0997_find_the_town_judge/readme.md b/src/main/kotlin/g0901_1000/s0997_find_the_town_judge/readme.md new file mode 100644 index 00000000..e0b948a8 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0997_find_the_town_judge/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) + +## 997\. Find the Town Judge + +Easy + +In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge. + +If the town judge exists, then: + +1. The town judge trusts nobody. +2. Everybody (except for the town judge) trusts the town judge. +3. There is exactly one person that satisfies properties **1** and **2**. + +You are given an array `trust` where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi. If a trust relationship does not exist in `trust` array, then such a trust relationship does not exist. + +Return _the label of the town judge if the town judge exists and can be identified, or return_ `-1` _otherwise_. + +**Example 1:** + +**Input:** n = 2, trust = \[\[1,2]] + +**Output:** 2 + +**Example 2:** + +**Input:** n = 3, trust = \[\[1,3],[2,3]] + +**Output:** 3 + +**Example 3:** + +**Input:** n = 3, trust = \[\[1,3],[2,3],[3,1]] + +**Output:** -1 + +**Constraints:** + +* `1 <= n <= 1000` +* 0 <= trust.length <= 104 +* `trust[i].length == 2` +* All the pairs of `trust` are **unique**. +* ai != bi +* 1 <= ai, bi <= n + +## Solution + +```kotlin +class Solution { + fun findJudge(n: Int, trust: Array): Int { + val count = IntArray(n + 1) + for (t in trust) { + --count[t[0]] + ++count[t[1]] + } + for (i in 1 until n + 1) if (count[i] == n - 1) return i + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0998_maximum_binary_tree_ii/readme.md b/src/main/kotlin/g0901_1000/s0998_maximum_binary_tree_ii/readme.md new file mode 100644 index 00000000..1d9871a1 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0998_maximum_binary_tree_ii/readme.md @@ -0,0 +1,94 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 998\. Maximum Binary Tree II + +Medium + +A **maximum tree** is a tree where every node has a value greater than any other value in its subtree. + +You are given the `root` of a maximum binary tree and an integer `val`. + +Just as in the [previous problem](https://leetcode.com/problems/maximum-binary-tree/), the given tree was constructed from a list `a` (`root = Construct(a)`) recursively with the following `Construct(a)` routine: + +* If `a` is empty, return `null`. +* Otherwise, let `a[i]` be the largest element of `a`. Create a `root` node with the value `a[i]`. +* The left child of `root` will be `Construct([a[0], a[1], ..., a[i - 1]])`. +* The right child of `root` will be `Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]])`. +* Return `root`. + +Note that we were not given `a` directly, only a root node `root = Construct(a)`. + +Suppose `b` is a copy of `a` with the value `val` appended to it. It is guaranteed that `b` has unique values. + +Return `Construct(b)`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/08/09/maxtree1.JPG) + +**Input:** root = [4,1,3,null,null,2], val = 5 + +**Output:** [5,4,null,1,3,null,null,2] + +**Explanation:** a = [1,4,2,3], b = [1,4,2,3,5] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/08/09/maxtree21.JPG) + +**Input:** root = [5,2,4,null,1], val = 3 + +**Output:** [5,2,4,null,1,null,3] + +**Explanation:** a = [2,1,5,4], b = [2,1,5,4,3] + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/08/09/maxtree3.JPG) + +**Input:** root = [5,2,3,null,1], val = 4 + +**Output:** [5,2,4,null,1,3] + +**Explanation:** a = [2,1,5,3], b = [2,1,5,3,4] + +**Constraints:** + +* The number of nodes in the tree is in the range `[1, 100]`. +* `1 <= Node.val <= 100` +* All the values of the tree are **unique**. +* `1 <= val <= 100` + +## 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 insertIntoMaxTree(root: TreeNode?, `val`: Int): TreeNode? { + return insertIntoMaxTree2(root, `val`) + } + + private fun insertIntoMaxTree2(root: TreeNode?, `val`: Int): TreeNode { + if (root == null) { + return TreeNode(`val`) + } + if (root.`val` < `val`) { + return TreeNode(`val`, root, null) + } + root.right = insertIntoMaxTree2(root.right, `val`) + return root + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0999_available_captures_for_rook/readme.md b/src/main/kotlin/g0901_1000/s0999_available_captures_for_rook/readme.md new file mode 100644 index 00000000..8fad58bf --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0999_available_captures_for_rook/readme.md @@ -0,0 +1,148 @@ +[![](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) + +## 999\. Available Captures for Rook + +Easy + +On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`. + +When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered **attacking** a pawn if the rook can capture the pawn on the rook's turn. The **number of available captures** for the white rook is the number of pawns that the rook is **attacking**. + +Return _the **number of available captures** for the white rook_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/02/20/1253_example_1_improved.PNG) + +**Input:** board = \[\[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]] + +**Output:** 3 + +**Explanation:** In this example, the rook is attacking all the pawns. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2019/02/19/1253_example_2_improved.PNG) + +**Input:** board = \[\[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]] + +**Output:** 0 + +**Explanation:** The bishops are blocking the rook from attacking any of the pawns. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2019/02/20/1253_example_3_improved.PNG) + +**Input:** board = \[\[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]] + +**Output:** 3 + +**Explanation:** The rook is attacking the pawns at positions b5, d6, and f5. + +**Constraints:** + +* `board.length == 8` +* `board[i].length == 8` +* `board[i][j]` is either `'R'`, `'.'`, `'B'`, or `'p'` +* There is exactly one cell with `board[i][j] == 'R'` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + private val directions = intArrayOf(0, 1, 0, -1, 0) + fun numRookCaptures(board: Array): Int { + val m = board.size + val n = board[0].size + var rowR = -1 + var colR = -1 + for (i in 0 until m) { + for (j in 0 until n) { + if (board[i][j] == 'R') { + rowR = i + colR = j + break + } + } + } + val count = intArrayOf(0) + for (i in 0..3) { + val neighborRow = rowR + directions[i] + val neighborCol = colR + directions[i + 1] + if (neighborRow in 0 until m && neighborCol >= 0 && neighborCol < n && + board[neighborRow][neighborCol] != 'B' + ) { + if (directions[i] == 0 && directions[i + 1] == 1) { + extracted(board, n, count, neighborRow, neighborCol) + } else if (directions[i] == 1 && directions[i + 1] == 0) { + extracted1(board, m, count, neighborRow, neighborCol) + } else if (directions[i] == 0 && directions[i + 1] == -1) { + extracted(board, count, neighborRow, neighborCol) + } else { + extracted1(board, count, neighborRow, neighborCol) + } + } + } + return count[0] + } + + private fun extracted(board: Array, count: IntArray, neighborRow: Int, neighborCol: Int) { + var neighborCol = neighborCol + while (neighborCol >= 0) { + if (board[neighborRow][neighborCol] == 'p') { + count[0]++ + break + } else if (board[neighborRow][neighborCol] == 'B') { + break + } else { + neighborCol-- + } + } + } + + private fun extracted(board: Array, n: Int, count: IntArray, neighborRow: Int, neighborCol: Int) { + var neighborCol = neighborCol + while (neighborCol < n) { + if (board[neighborRow][neighborCol] == 'p') { + count[0]++ + break + } else if (board[neighborRow][neighborCol] == 'B') { + break + } else { + neighborCol++ + } + } + } + + private fun extracted1(board: Array, count: IntArray, neighborRow: Int, neighborCol: Int) { + var neighborRow = neighborRow + while (neighborRow >= 0) { + if (board[neighborRow][neighborCol] == 'p') { + count[0]++ + break + } else if (board[neighborRow][neighborCol] == 'B') { + break + } else { + neighborRow-- + } + } + } + + private fun extracted1(board: Array, m: Int, count: IntArray, neighborRow: Int, neighborCol: Int) { + var neighborRow = neighborRow + while (neighborRow < m) { + if (board[neighborRow][neighborCol] == 'p') { + count[0]++ + break + } else if (board[neighborRow][neighborCol] == 'B') { + break + } else { + neighborRow++ + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s1000_minimum_cost_to_merge_stones/readme.md b/src/main/kotlin/g0901_1000/s1000_minimum_cost_to_merge_stones/readme.md new file mode 100644 index 00000000..bc64514f --- /dev/null +++ b/src/main/kotlin/g0901_1000/s1000_minimum_cost_to_merge_stones/readme.md @@ -0,0 +1,110 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1000\. Minimum Cost to Merge Stones + +Hard + +There are `n` piles of `stones` arranged in a row. The ith pile has `stones[i]` stones. + +A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles. + +Return _the minimum cost to merge all piles of stones into one pile_. If it is impossible, return `-1`. + +**Example 1:** + +**Input:** stones = [3,2,4,1], k = 2 + +**Output:** 20 + +**Explanation:** + +We start with [3, 2, 4, 1]. + +We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1]. + +We merge [4, 1] for a cost of 5, and we are left with [5, 5]. + +We merge [5, 5] for a cost of 10, and we are left with [10]. + +The total cost was 20, and this is the minimum possible. + +**Example 2:** + +**Input:** stones = [3,2,4,1], k = 3 + +**Output:** -1 + +**Explanation:** After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible. + +**Example 3:** + +**Input:** stones = [3,5,1,2,6], k = 3 + +**Output:** 25 + +**Explanation:** + +We start with [3, 5, 1, 2, 6]. + +We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6]. + +We merge [3, 8, 6] for a cost of 17, and we are left with [17]. + +The total cost was 25, and this is the minimum possible. + +**Constraints:** + +* `n == stones.length` +* `1 <= n <= 30` +* `1 <= stones[i] <= 100` +* `2 <= k <= 30` + +## Solution + +```kotlin +class Solution { + private lateinit var memo: Array + private lateinit var prefixSum: IntArray + fun mergeStones(stones: IntArray, k: Int): Int { + val n = stones.size + if ((n - 1) % (k - 1) != 0) { + return -1 + } + memo = Array(n) { IntArray(n) } + for (arr in memo) { + arr.fill(-1) + } + prefixSum = IntArray(n + 1) + for (i in 1 until n + 1) { + prefixSum[i] = prefixSum[i - 1] + stones[i - 1] + } + return dp(0, n - 1, k) + } + + private fun dp(left: Int, right: Int, k: Int): Int { + if (memo[left][right] > 0) { + return memo[left][right] + } + if (right - left + 1 < k) { + memo[left][right] = 0 + return memo[left][right] + } + if (right - left + 1 == k) { + memo[left][right] = prefixSum[right + 1] - prefixSum[left] + return memo[left][right] + } + var `val` = Int.MAX_VALUE + var i = 0 + while (left + i + 1 <= right) { + `val` = `val`.coerceAtMost(dp(left, left + i, k) + dp(left + i + 1, right, k)) + i += k - 1 + } + if ((right - left) % (k - 1) == 0) { + `val` += prefixSum[right + 1] - prefixSum[left] + } + memo[left][right] = `val` + return `val` + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1001_grid_illumination/readme.md b/src/main/kotlin/g1001_1100/s1001_grid_illumination/readme.md new file mode 100644 index 00000000..3673113a --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1001_grid_illumination/readme.md @@ -0,0 +1,119 @@ +[![](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) + +## 1001\. Grid Illumination + +Hard + +There is a 2D `grid` of size `n x n` where each cell of this grid has a lamp that is initially **turned off**. + +You are given a 2D array of lamp positions `lamps`, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is **turned on**. Even if the same lamp is listed more than once, it is turned on. + +When a lamp is turned on, it **illuminates its cell** and **all other cells** in the same **row, column, or diagonal**. + +You are also given another 2D array `queries`, where queries[j] = [rowj, colj]. For the jth query, determine whether grid[rowj][colj] is illuminated or not. After answering the jth query, **turn off** the lamp at grid[rowj][colj] and its **8 adjacent lamps** if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj]. + +Return _an array of integers_ `ans`_,_ _where_ `ans[j]` _should be_ `1` _if the cell in the_ jth _query was illuminated, or_ `0` _if the lamp was not._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/08/19/illu_1.jpg) + +**Input:** n = 5, lamps = \[\[0,0],[4,4]], queries = \[\[1,1],[1,0]] + +**Output:** [1,0] + +**Explanation:** We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4]. The 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square. ![](https://assets.leetcode.com/uploads/2020/08/19/illu_step1.jpg) The 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle. ![](https://assets.leetcode.com/uploads/2020/08/19/illu_step2.jpg) + +**Example 2:** + +**Input:** n = 5, lamps = \[\[0,0],[4,4]], queries = \[\[1,1],[1,1]] + +**Output:** [1,1] + +**Example 3:** + +**Input:** n = 5, lamps = \[\[0,0],[0,4]], queries = \[\[0,4],[0,1],[1,4]] + +**Output:** [1,1,0] + +**Constraints:** + +* 1 <= n <= 109 +* `0 <= lamps.length <= 20000` +* `0 <= queries.length <= 20000` +* `lamps[i].length == 2` +* 0 <= rowi, coli < n +* `queries[j].length == 2` +* 0 <= rowj, colj < n + +## Solution + +```kotlin +class Solution { + fun gridIllumination(n: Int, lamps: Array, queries: Array): IntArray { + val rowIlluminations: MutableMap = HashMap() + val colIlluminations: MutableMap = HashMap() + val posDiagIlluminations: MutableMap = HashMap() + val negDiagIlluminations: MutableMap = HashMap() + val lampPlacements: MutableSet = HashSet() + for (lamp in lamps) { + val row = lamp[0] + val col = lamp[1] + var key = row.toLong() + key = key * n + col + if (lampPlacements.contains(key)) { + continue + } + incr(rowIlluminations, row) + incr(colIlluminations, col) + incr(posDiagIlluminations, row + col) + incr(negDiagIlluminations, row + (n - 1 - col)) + lampPlacements.add(key) + } + val ans = IntArray(queries.size) + for (i in ans.indices) { + val row = queries[i][0] + val col = queries[i][1] + if (rowIlluminations.containsKey(row) || + colIlluminations.containsKey(col) || + posDiagIlluminations.containsKey(row + col) || + negDiagIlluminations.containsKey(row + (n - 1 - col)) + ) { + ans[i] = 1 + } + val topRow = 0.coerceAtLeast(row - 1) + val bottomRow = (n - 1).coerceAtMost(row + 1) + val leftCol = 0.coerceAtLeast(col - 1) + val rightCol = (n - 1).coerceAtMost(col + 1) + for (r in topRow..bottomRow) { + for (c in leftCol..rightCol) { + var key = r.toLong() + key = key * n + c + if (lampPlacements.contains(key)) { + decr(rowIlluminations, r) + decr(colIlluminations, c) + decr(posDiagIlluminations, r + c) + decr(negDiagIlluminations, r + (n - 1 - c)) + lampPlacements.remove(key) + } + } + } + } + return ans + } + + private fun incr(map: MutableMap, key: Int) { + map[key] = map.getOrDefault(key, 0) + 1 + } + + private fun decr(map: MutableMap, key: Int) { + val v = map.getValue(key) + if (map[key] == 1) { + map.remove(key) + } else { + map[key] = v - 1 + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1002_find_common_characters/readme.md b/src/main/kotlin/g1001_1100/s1002_find_common_characters/readme.md new file mode 100644 index 00000000..edf45c95 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1002_find_common_characters/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) + +## 1002\. Find Common Characters + +Easy + +Given a string array `words`, return _an array of all characters that show up in all strings within the_ `words` _(including duplicates)_. You may return the answer in **any order**. + +**Example 1:** + +**Input:** words = ["bella","label","roller"] + +**Output:** ["e","l","l"] + +**Example 2:** + +**Input:** words = ["cool","lock","cook"] + +**Output:** ["c","o"] + +**Constraints:** + +* `1 <= words.length <= 100` +* `1 <= words[i].length <= 100` +* `words[i]` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun commonChars(words: Array?): List { + if (words == null) { + throw RuntimeException("words null") + } + if (words.isEmpty()) { + return ArrayList() + } + var tmp = words[0] + for (i in 1 until words.size) { + tmp = getCommon(tmp, words[i]) + } + val result: MutableList = ArrayList() + for (element in tmp) { + result.add(element.toString()) + } + return result + } + + private fun getCommon(s1: String, s2: String): String { + if (s1.isEmpty() || s2.isEmpty()) { + return "" + } + val c1c = countChars(s1) + val c2c = countChars(s2) + val sb = StringBuilder() + for (i in c1c.indices) { + var m = c1c[i].coerceAtMost(c2c[i]) + while (m > 0) { + sb.append(('a'.code + i).toChar()) + m-- + } + } + return sb.toString() + } + + private fun countChars(str: String): IntArray { + val result = IntArray(26) + for (element in str) { + result[element.code - 'a'.code]++ + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1003_check_if_word_is_valid_after_substitutions/readme.md b/src/main/kotlin/g1001_1100/s1003_check_if_word_is_valid_after_substitutions/readme.md new file mode 100644 index 00000000..b4b539bd --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1003_check_if_word_is_valid_after_substitutions/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) + +## 1003\. Check If Word Is Valid After Substitutions + +Medium + +Given a string `s`, determine if it is **valid**. + +A string `s` is **valid** if, starting with an empty string `t = ""`, you can **transform** `t` **into** `s` after performing the following operation **any number of times**: + +* Insert string `"abc"` into any position in `t`. More formally, `t` becomes tleft + "abc" + tright, where t == tleft + tright. Note that tleft and tright may be **empty**. + +Return `true` _if_ `s` _is a **valid** string, otherwise, return_ `false`. + +**Example 1:** + +**Input:** s = "aabcbc" + +**Output:** true + +**Explanation:** "" -> "abc" -> "aabcbc" Thus, "aabcbc" is valid. + +**Example 2:** + +**Input:** s = "abcabcababcc" + +**Output:** true + +**Explanation:** "" -> "abc" -> "abcabc" -> "abcabcabc" -> "abcabcababcc" Thus, "abcabcababcc" is valid. + +**Example 3:** + +**Input:** s = "abccba" + +**Output:** false + +**Explanation:** It is impossible to get "abccba" using the operation. + +**Constraints:** + +* 1 <= s.length <= 2 * 104 +* `s` consists of letters `'a'`, `'b'`, and `'c'` + +## Solution + +```kotlin +import java.util.Deque +import java.util.LinkedList + +class Solution { + fun isValid(s: String): Boolean { + val stack: Deque = LinkedList() + for (c in s.toCharArray()) { + if (c == 'c') { + if (stack.isEmpty() || stack.pop() != 'b') { + return false + } + if (stack.isEmpty() || stack.pop() != 'a') { + return false + } + } else { + stack.push(c) + } + } + return stack.isEmpty() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1004_max_consecutive_ones_iii/readme.md b/src/main/kotlin/g1001_1100/s1004_max_consecutive_ones_iii/readme.md new file mode 100644 index 00000000..a90d6bcb --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1004_max_consecutive_ones_iii/readme.md @@ -0,0 +1,55 @@ +[![](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) + +## 1004\. Max Consecutive Ones III + +Medium + +Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s. + +**Example 1:** + +**Input:** nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2 + +**Output:** 6 + +**Explanation:** [1,1,1,0,0,**1**,1,1,1,1,**1**] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. + +**Example 2:** + +**Input:** nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3 + +**Output:** 10 + +**Explanation:** [0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. + +**Constraints:** + +* 1 <= nums.length <= 105 +* `nums[i]` is either `0` or `1`. +* `0 <= k <= nums.length` + +## Solution + +```kotlin +class Solution { + fun longestOnes(nums: IntArray, k: Int): Int { + var onesCount = 0 + var max = 0 + var start = 0 + for (end in nums.indices) { + if (nums[end] == 1) { + onesCount++ + } + if (end - start + 1 > onesCount + k) { + if (nums[start] == 1) { + onesCount-- + } + start++ + } + max = max.coerceAtLeast(end - start + 1) + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1005_maximize_sum_of_array_after_k_negations/readme.md b/src/main/kotlin/g1001_1100/s1005_maximize_sum_of_array_after_k_negations/readme.md new file mode 100644 index 00000000..b3ef16a0 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1005_maximize_sum_of_array_after_k_negations/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) + +## 1005\. Maximize Sum Of Array After K Negations + +Easy + +Given an integer array `nums` and an integer `k`, modify the array in the following way: + +* choose an index `i` and replace `nums[i]` with `-nums[i]`. + +You should apply this process exactly `k` times. You may choose the same index `i` multiple times. + +Return _the largest possible sum of the array after modifying it in this way_. + +**Example 1:** + +**Input:** nums = [4,2,3], k = 1 + +**Output:** 5 + +**Explanation:** Choose index 1 and nums becomes [4,-2,3]. + +**Example 2:** + +**Input:** nums = [3,-1,0,2], k = 3 + +**Output:** 6 + +**Explanation:** Choose indices (1, 2, 2) and nums becomes [3,1,0,2]. + +**Example 3:** + +**Input:** nums = [2,-3,-1,5,-4], k = 2 + +**Output:** 13 + +**Explanation:** Choose indices (1, 4) and nums becomes [2,3,-1,5,4]. + +**Constraints:** + +* 1 <= nums.length <= 104 +* `-100 <= nums[i] <= 100` +* 1 <= k <= 104 + +## Solution + +```kotlin +import java.util.Arrays + +@Suppress("NAME_SHADOWING") +class Solution { + fun largestSumAfterKNegations(nums: IntArray, k: Int): Int { + var k = k + nums.sort() + var minIndex = 0 + var i = 0 + while (i < nums.size && k > 0) { + if (nums[i] < 0) { + nums[i] *= -1 + k-- + } + if (nums[minIndex] > nums[i]) { + minIndex = i + } + i++ + } + if (k and 1 == 1) { + nums[minIndex] *= -1 + } + return Arrays.stream(nums).sum() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1006_clumsy_factorial/readme.md b/src/main/kotlin/g1001_1100/s1006_clumsy_factorial/readme.md new file mode 100644 index 00000000..e4cbea4b --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1006_clumsy_factorial/readme.md @@ -0,0 +1,63 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1006\. Clumsy Factorial + +Medium + +The **factorial** of a positive integer `n` is the product of all positive integers less than or equal to `n`. + +* For example, `factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1`. + +We make a **clumsy factorial** using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply `'*'`, divide `'/'`, add `'+'`, and subtract `'-'` in this order. + +* For example, `clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1`. + +However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right. + +Additionally, the division that we use is floor division such that `10 * 9 / 8 = 90 / 8 = 11`. + +Given an integer `n`, return _the clumsy factorial of_ `n`. + +**Example 1:** + +**Input:** n = 4 + +**Output:** 7 + +**Explanation:** 7 = 4 \* 3 / 2 + 1 + +**Example 2:** + +**Input:** n = 10 + +**Output:** 12 + +**Explanation:** 12 = 10 \* 9 / 8 + 7 - 6 \* 5 / 4 + 3 - 2 \* 1 + +**Constraints:** + +* 1 <= n <= 104 + +## Solution + +```kotlin +class Solution { + private var m = 1 + fun clumsy(n: Int): Int { + val num: Int = if (n >= 4) { + m * n * (n - 1) / (n - 2) + (n - 3) + } else if (n == 3) { + m * n * (n - 1) / (n - 2) + } else if (n == 2) { + m * n * (n - 1) + } else if (n == 1) { + m * n + } else { + return 0 + } + m = -1 + return num + clumsy(n - 4) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1007_minimum_domino_rotations_for_equal_row/readme.md b/src/main/kotlin/g1001_1100/s1007_minimum_domino_rotations_for_equal_row/readme.md new file mode 100644 index 00000000..6148018f --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1007_minimum_domino_rotations_for_equal_row/readme.md @@ -0,0 +1,110 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1007\. Minimum Domino Rotations For Equal Row + +Medium + +In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) + +We may rotate the ith domino, so that `tops[i]` and `bottoms[i]` swap values. + +Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same. + +If it cannot be done, return `-1`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/05/14/domino.png) + +**Input:** tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2] + +**Output:** 2 + +**Explanation:** The first figure represents the dominoes as given by tops and bottoms: before we do any rotations. If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure. + +**Example 2:** + +**Input:** tops = [3,5,1,2,3], bottoms = [3,6,3,3,4] + +**Output:** -1 + +**Explanation:** In this case, it is not possible to rotate the dominoes to make one row of values equal. + +**Constraints:** + +* 2 <= tops.length <= 2 * 104 +* `bottoms.length == tops.length` +* `1 <= tops[i], bottoms[i] <= 6` + +## Solution + +```kotlin +class Solution { + fun minDominoRotations(tops: IntArray, bottoms: IntArray): Int { + val top = tops[0] + var tCount = 0 + var bCount = 0 + val tSwaps: Int + val bSwaps: Int + var swaps = 0 + var valid = true + for (i in tops.indices) { + if (tops[i] == top) { + tCount++ + } + if (bottoms[i] == top) { + bCount++ + } + if (tops[i] != top && bottoms[i] != top) { + valid = false + swaps = -1 + break + } + } + if (valid) { + tSwaps = tops.size - tCount + bSwaps = bottoms.size - bCount + swaps = Math.min(tSwaps, bSwaps) + } + val bottom = bottoms[0] + var tCount1 = 0 + var bCount1 = 0 + val tSwaps1: Int + val bSwaps1: Int + var swaps1 = 0 + var valid1 = true + for (i in bottoms.indices) { + if (tops[i] == bottom) { + tCount1++ + } + if (bottoms[i] == bottom) { + bCount1++ + } + if (tops[i] != bottom && bottoms[i] != bottom) { + valid1 = false + swaps1 = -1 + break + } + } + if (valid1) { + tSwaps1 = tops.size - tCount1 + bSwaps1 = bottoms.size - bCount1 + swaps1 = Math.min(tSwaps1, bSwaps1) + } + val ans = IntArray(2) + if (swaps1 < swaps) { + ans[0] = swaps1 + ans[1] = swaps + } else { + ans[0] = swaps + ans[1] = swaps1 + } + return if (ans[0] != -1) { + ans[0] + } else { + ans[1] + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1008_construct_binary_search_tree_from_preorder_traversal/readme.md b/src/main/kotlin/g1001_1100/s1008_construct_binary_search_tree_from_preorder_traversal/readme.md new file mode 100644 index 00000000..69887f8e --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1008_construct_binary_search_tree_from_preorder_traversal/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1008\. Construct Binary Search Tree from Preorder Traversal + +Medium + +Given an array of integers preorder, which represents the **preorder traversal** of a BST (i.e., **binary search tree**), construct the tree and return _its root_. + +It is **guaranteed** that there is always possible to find a binary search tree with the given requirements for the given test cases. + +A **binary search tree** is a binary tree where for every node, any descendant of `Node.left` has a value **strictly less than** `Node.val`, and any descendant of `Node.right` has a value **strictly greater than** `Node.val`. + +A **preorder traversal** of a binary tree displays the value of the node first, then traverses `Node.left`, then traverses `Node.right`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/03/06/1266.png) + +**Input:** preorder = [8,5,1,7,10,12] + +**Output:** [8,5,10,1,7,null,12] + +**Example 2:** + +**Input:** preorder = [1,3] + +**Output:** [1,null,3] + +**Constraints:** + +* `1 <= preorder.length <= 100` +* `1 <= preorder[i] <= 1000` +* All the values of `preorder` are **unique**. + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private var i = 0 + fun bstFromPreorder(preorder: IntArray): TreeNode? { + return bstFromPreorder(preorder, Int.MAX_VALUE) + } + + private fun bstFromPreorder(preorder: IntArray, bound: Int): TreeNode? { + if (i == preorder.size || preorder[i] > bound) { + return null + } + val root = TreeNode(preorder[i++]) + root.left = bstFromPreorder(preorder, root.`val`) + root.right = bstFromPreorder(preorder, bound) + return root + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1009_complement_of_base_10_integer/readme.md b/src/main/kotlin/g1001_1100/s1009_complement_of_base_10_integer/readme.md new file mode 100644 index 00000000..8fc1ba32 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1009_complement_of_base_10_integer/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) + +## 1009\. Complement of Base 10 Integer + +Easy + +The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. + +* For example, The integer `5` is `"101"` in binary and its **complement** is `"010"` which is the integer `2`. + +Given an integer `n`, return _its complement_. + +**Example 1:** + +**Input:** n = 5 + +**Output:** 2 + +**Explanation:** 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10. + +**Example 2:** + +**Input:** n = 7 + +**Output:** 0 + +**Explanation:** 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10. + +**Example 3:** + +**Input:** n = 10 + +**Output:** 5 + +**Explanation:** 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10. + +**Constraints:** + +* 0 <= n < 109 + +**Note:** This question is the same as 476: [https://leetcode.com/problems/number-complement/](https://leetcode.com/problems/number-complement/) + +## Solution + +```kotlin +import kotlin.math.pow + +@Suppress("NAME_SHADOWING") +class Solution { + fun bitwiseComplement(n: Int): Int { + var n = n + if (n == 0) { + return 1 + } + val list: MutableList = ArrayList() + while (n != 0) { + list.add(n and 1) + n = n shr 1 + } + var result = 0 + var exp = list.size - 1 + for (i in list.indices.reversed()) { + if (list[i] == 0) { + result += 2.0.pow(exp.toDouble()).toInt() + } + exp-- + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1010_pairs_of_songs_with_total_durations_divisible_by_60/readme.md b/src/main/kotlin/g1001_1100/s1010_pairs_of_songs_with_total_durations_divisible_by_60/readme.md new file mode 100644 index 00000000..173c1744 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1010_pairs_of_songs_with_total_durations_divisible_by_60/readme.md @@ -0,0 +1,58 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1010\. Pairs of Songs With Total Durations Divisible by 60 + +Medium + +You are given a list of songs where the ith song has a duration of `time[i]` seconds. + +Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`. + +**Example 1:** + +**Input:** time = [30,20,150,100,40] + +**Output:** 3 + +**Explanation:** Three pairs have a total duration divisible by 60: + +(time[0] = 30, time[2] = 150): total duration 180 + +(time[1] = 20, time[3] = 100): total duration 120 + +(time[1] = 20, time[4] = 40): total duration 60 + +**Example 2:** + +**Input:** time = [60,60,60] + +**Output:** 3 + +**Explanation:** All three pairs have a total duration of 120, which is divisible by 60. + +**Constraints:** + +* 1 <= time.length <= 6 * 104 +* `1 <= time[i] <= 500` + +## Solution + +```kotlin +class Solution { + fun numPairsDivisibleBy60(time: IntArray): Int { + val remainder = IntArray(60) + var ans = 0 + for (j in time) { + val rem = j % 60 + ans += if (rem == 0) { + remainder[0] + } else { + remainder[60 - rem] + } + remainder[rem]++ + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1011_capacity_to_ship_packages_within_d_days/readme.md b/src/main/kotlin/g1001_1100/s1011_capacity_to_ship_packages_within_d_days/readme.md new file mode 100644 index 00000000..13e3ac74 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1011_capacity_to_ship_packages_within_d_days/readme.md @@ -0,0 +1,108 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1011\. Capacity To Ship Packages Within D Days + +Medium + +A conveyor belt has packages that must be shipped from one port to another within `days` days. + +The ith package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship. + +Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days. + +**Example 1:** + +**Input:** weights = [1,2,3,4,5,6,7,8,9,10], days = 5 + +**Output:** 15 + +**Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: + +1st day: 1, 2, 3, 4, 5 + +2nd day: 6, 7 + +3rd day: 8 + +4th day: 9 + +5th day: 10 + +Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. + +**Example 2:** + +**Input:** weights = [3,2,2,4,1,4], days = 3 + +**Output:** 6 + +**Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: + +1st day: 3, 2 + +2nd day: 2, 4 + +3rd day: 1, 4 + +**Example 3:** + +**Input:** weights = [1,2,3,1,1], days = 4 + +**Output:** 3 + +**Explanation:** + +1st day: 1 + +2nd day: 2 + +3rd day: 3 + +4th day: 1, 1 + +**Constraints:** + +* 1 <= days <= weights.length <= 5 * 104 +* `1 <= weights[i] <= 500` + +## Solution + +```kotlin +class Solution { + fun shipWithinDays(weights: IntArray, days: Int): Int { + var max = weights[0] + var sum = 0 + for (`val` in weights) { + sum += `val` + max = max.coerceAtLeast(`val`) + } + var lo = max + var hi = sum + var ans = 0 + while (lo <= hi) { + val mid = lo + (hi - lo) / 2 + if (isPossible(weights, mid, days)) { + ans = mid + hi = mid - 1 + } else { + lo = mid + 1 + } + } + return ans + } + + private fun isPossible(arr: IntArray, mid: Int, days: Int): Boolean { + var capacity = 1 + var sum = 0 + for (j in arr) { + sum += j + if (sum > mid) { + capacity++ + sum = j + } + } + return capacity <= days + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1012_numbers_with_repeated_digits/readme.md b/src/main/kotlin/g1001_1100/s1012_numbers_with_repeated_digits/readme.md new file mode 100644 index 00000000..6b50fd8b --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1012_numbers_with_repeated_digits/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) + +## 1012\. Numbers With Repeated Digits + +Hard + +Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_. + +**Example 1:** + +**Input:** n = 20 + +**Output:** 1 + +**Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11. + +**Example 2:** + +**Input:** n = 100 + +**Output:** 10 + +**Explanation:** The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100. + +**Example 3:** + +**Input:** n = 1000 + +**Output:** 262 + +**Constraints:** + +* 1 <= n <= 109 + +## Solution + +```kotlin +import kotlin.math.pow + +class Solution { + private var noRepeatCount = 0 + fun numDupDigitsAtMostN(n: Int): Int { + val nStrLength = n.toString().length + val allNineLength: Int = if (n < 0 || nStrLength < 2) { + return 0 + } else if (10.0.pow(nStrLength.toDouble()) - 1 == n.toDouble()) { + nStrLength + } else { + nStrLength - 1 + } + for (numberOfDigits in 1..allNineLength) { + noRepeatCount += calcNumberOfNoRepeat(numberOfDigits) + } + if (10.0.pow(nStrLength.toDouble()) - 1 > n) { + val mutations = 10 + val hs: HashSet = HashSet() + for (index1 in 0 until nStrLength) { + var noRepeatCountLocal = 0 + hs.clear() + for (index2 in 0 until nStrLength) { + val index2Digit = ( + n / + 10.0.pow(n.toString().length - (index2 + 1.0)) % + 10 + ).toInt() + if (index2 < index1) { + if (hs.contains(index2Digit)) { + noRepeatCountLocal = 0 + break + } else { + hs.add(index2Digit) + } + } else if (index2 == index1) { + noRepeatCountLocal = if (index2 == 0) { + index2Digit - 1 + } else { + var inIndex2Range = 0 + for (j in hs) { + if (index2 < nStrLength - 1 && j <= index2Digit - 1 || + index2 == nStrLength - 1 && j <= index2Digit + ) { + inIndex2Range++ + } + } + if (index2 == nStrLength - 1) { + index2Digit + 1 - inIndex2Range + } else { + index2Digit - inIndex2Range + } + } + } else { + noRepeatCountLocal *= mutations - index2 + } + } + if (noRepeatCountLocal > 0) { + noRepeatCount += noRepeatCountLocal + } + } + } + return n - noRepeatCount + } + + private fun calcNumberOfNoRepeat(numberOfDigits: Int): Int { + var repeatCount = 0 + var mutations = 9 + for (i in 0 until numberOfDigits) { + if (i == 0) { + repeatCount = mutations + } else { + repeatCount *= mutations-- + } + } + return repeatCount + } +} +``` \ No newline at end of file