From dddb46b3e75be1b72fe65321a64dc0e44a03b5de Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Wed, 6 Mar 2024 11:40:44 +0200 Subject: [PATCH] Added tasks 3001-3049 --- README.md | 839 +++++++++--------- .../s2815_max_pair_sum_in_an_array/readme.md | 2 +- .../readme.md | 83 ++ .../readme.md | 86 ++ .../readme.md | 161 ++++ .../readme.md | 75 ++ .../readme.md | 153 ++++ .../readme.md | 83 ++ .../readme.md | 129 +++ .../readme.md | 70 ++ .../readme.md | 75 ++ .../readme.md | 101 +++ .../readme.md | 124 +++ .../readme.md | 109 +++ .../readme.md | 107 +++ .../readme.md | 130 +++ .../readme.md | 135 +++ .../s3019_number_of_changing_keys/readme.md | 64 ++ .../readme.md | 83 ++ .../readme.md | 56 ++ .../readme.md | 84 ++ .../s3024_type_of_triangle/readme.md | 64 ++ .../readme.md | 98 ++ .../s3026_maximum_good_subarray_sum/readme.md | 89 ++ .../readme.md | 94 ++ .../s3028_ant_on_the_boundary/readme.md | 72 ++ .../readme.md | 65 ++ .../readme.md | 116 +++ .../readme.md | 86 ++ .../s3033_modify_the_matrix/readme.md | 63 ++ .../readme.md | 73 ++ .../readme.md | 107 +++ .../readme.md | 77 ++ .../readme.md | 66 ++ .../readme.md | 71 ++ .../readme.md | 119 +++ .../readme.md | 79 ++ .../readme.md | 101 +++ .../readme.md | 107 +++ .../s3044_most_frequent_prime/readme.md | 167 ++++ .../readme.md | 93 ++ .../s3046_split_the_array/readme.md | 53 ++ .../readme.md | 91 ++ .../readme.md | 140 +++ .../readme.md | 157 ++++ 45 files changed, 4598 insertions(+), 399 deletions(-) create mode 100644 src/main/kotlin/g3001_3100/s3001_minimum_moves_to_capture_the_queen/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3002_maximum_size_of_a_set_after_removals/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3003_maximize_the_number_of_partitions_after_operations/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3005_count_elements_with_maximum_frequency/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3006_find_beautiful_indices_in_the_given_array_i/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3007_maximum_number_that_sum_of_the_prices_is_less_than_or_equal_to_k/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3008_find_beautiful_indices_in_the_given_array_ii/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3010_divide_an_array_into_subarrays_with_minimum_cost_i/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3011_find_if_array_can_be_sorted/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3012_minimize_length_of_array_using_operations/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3013_divide_an_array_into_subarrays_with_minimum_cost_ii/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3014_minimum_number_of_pushes_to_type_word_i/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3015_count_the_number_of_houses_at_a_certain_distance_i/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3016_minimum_number_of_pushes_to_type_word_ii/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3017_count_the_number_of_houses_at_a_certain_distance_ii/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3019_number_of_changing_keys/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3020_find_the_maximum_number_of_elements_in_subset/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3021_alice_and_bob_playing_flower_game/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3022_minimize_or_of_remaining_elements_using_operations/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3024_type_of_triangle/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3025_find_the_number_of_ways_to_place_people_i/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3026_maximum_good_subarray_sum/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3027_find_the_number_of_ways_to_place_people_ii/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3028_ant_on_the_boundary/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3029_minimum_time_to_revert_word_to_initial_state_i/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3030_find_the_grid_of_region_average/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3031_minimum_time_to_revert_word_to_initial_state_ii/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3033_modify_the_matrix/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3034_number_of_subarrays_that_match_a_pattern_i/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3035_maximum_palindromes_after_operations/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3036_number_of_subarrays_that_match_a_pattern_ii/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3038_maximum_number_of_operations_with_the_same_score_i/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3039_apply_operations_to_make_string_empty/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3040_maximum_number_of_operations_with_the_same_score_ii/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3041_maximize_consecutive_elements_in_an_array_after_modification/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3042_count_prefix_and_suffix_pairs_i/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3043_find_the_length_of_the_longest_common_prefix/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3044_most_frequent_prime/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3045_count_prefix_and_suffix_pairs_ii/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3046_split_the_array/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3047_find_the_largest_area_of_square_inside_two_rectangles/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3048_earliest_second_to_mark_indices_i/readme.md create mode 100644 src/main/kotlin/g3001_3100/s3049_earliest_second_to_mark_indices_ii/readme.md diff --git a/README.md b/README.md index 54244abc..0131dff1 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,6 @@ [![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) > ["For coding interview preparation, LeetCode is one of the best online resource providing a rich library of more than 300 real coding interview questions for you to practice from using one of the 7 supported languages - C, C++, Java, Python, C#, JavaScript, Ruby."](https://www.quora.com/How-effective-is-Leetcode-for-preparing-for-technical-interviews) -* [Binary Search II](#binary-search-ii) -* [Dynamic Programming I](#dynamic-programming-i) * [Programming Skills I](#programming-skills-i) * [Programming Skills II](#programming-skills-ii) * [Graph Theory I](#graph-theory-i) @@ -16,565 +14,272 @@ * [Algorithm I](#algorithm-i) * [Algorithm II](#algorithm-ii) * [Binary Search I](#binary-search-i) +* [Binary Search II](#binary-search-ii) +* [Dynamic Programming I](#dynamic-programming-i) -### Binary Search II - -#### Day 1 - -| | | | | | -|-|-|-|-|-|- -| 0209 |[Minimum Size Subarray Sum](src/main/kotlin/g0201_0300/s0209_minimum_size_subarray_sum)| Medium | Array, Binary_Search, Prefix_Sum, Sliding_Window | 315 | 96.73 -| 0611 |[Valid Triangle Number](src/main/kotlin/g0601_0700/s0611_valid_triangle_number)| Medium | Array, Sorting, Greedy, Binary_Search, Two_Pointers | 203 | 100.00 - -#### Day 2 - -| | | | | | -|-|-|-|-|-|- -| 0658 |[Find K Closest Elements](src/main/kotlin/g0601_0700/s0658_find_k_closest_elements)| Medium | Array, Sorting, Binary_Search, Two_Pointers, Heap_Priority_Queue | 375 | 95.16 -| 1894 |[Find the Student that Will Replace the Chalk](src/main/kotlin/g1801_1900/s1894_find_the_student_that_will_replace_the_chalk)| Medium | Array, Binary_Search, Simulation, Prefix_Sum | 520 | 50.00 - -#### Day 3 - -| | | | | | -|-|-|-|-|-|- -| 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search, Big_O_Time_O(n\*log_n)_Space_O(n) | 318 | 82.28 -| 1760 |[Minimum Limit of Balls in a Bag](src/main/kotlin/g1701_1800/s1760_minimum_limit_of_balls_in_a_bag)| Medium | Array, Binary_Search | 460 | 100.00 - -#### Day 4 - -| | | | | | -|-|-|-|-|-|- -| 0875 |[Koko Eating Bananas](src/main/kotlin/g0801_0900/s0875_koko_eating_bananas)| Medium | Array, Binary_Search | 267 | 93.85 -| 1552 |[Magnetic Force Between Two Balls](src/main/kotlin/g1501_1600/s1552_magnetic_force_between_two_balls)| Medium | Array, Sorting, Binary_Search | 636 | 100.00 - -#### Day 5 - -| | | | | | -|-|-|-|-|-|- -| 0287 |[Find the Duplicate Number](src/main/kotlin/g0201_0300/s0287_find_the_duplicate_number)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search, Two_Pointers, Bit_Manipulation, Big_O_Time_O(n)_Space_O(n) | 656 | 66.21 -| 1283 |[Find the Smallest Divisor Given a Threshold](src/main/kotlin/g1201_1300/s1283_find_the_smallest_divisor_given_a_threshold)| Medium | Array, Binary_Search | 255 | 100.00 - -#### Day 6 - -| | | | | | -|-|-|-|-|-|- -| 1898 |[Maximum Number of Removable Characters](src/main/kotlin/g1801_1900/s1898_maximum_number_of_removable_characters)| Medium | Array, String, Binary_Search | 636 | 100.00 -| 1870 |[Minimum Speed to Arrive on Time](src/main/kotlin/g1801_1900/s1870_minimum_speed_to_arrive_on_time)| Medium | Array, Binary_Search | 628 | 50.00 - -#### Day 7 - -| | | | | | -|-|-|-|-|-|- -| 1482 |[Minimum Number of Days to Make m Bouquets](src/main/kotlin/g1401_1500/s1482_minimum_number_of_days_to_make_m_bouquets)| Medium | Array, Binary_Search | 538 | 50.00 -| 1818 |[Minimum Absolute Sum Difference](src/main/kotlin/g1801_1900/s1818_minimum_absolute_sum_difference)| Medium | Array, Sorting, Binary_Search, Ordered_Set | 447 | 100.00 - -#### Day 8 - -| | | | | | -|-|-|-|-|-|- -| 0240 |[Search a 2D Matrix II](src/main/kotlin/g0201_0300/s0240_search_a_2d_matrix_ii)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search, Matrix, Divide_and_Conquer, Big_O_Time_O(n+m)_Space_O(1) | 460 | 66.08 -| 0275 |[H-Index II](src/main/kotlin/g0201_0300/s0275_h_index_ii)| Medium | Array, Binary_Search | 398 | 81.82 +### Programming Skills I -#### Day 9 +#### Day 1 Basic Data Type | | | | | | |-|-|-|-|-|- -| 1838 |[Frequency of the Most Frequent Element](src/main/kotlin/g1801_1900/s1838_frequency_of_the_most_frequent_element)| Medium | Array, Sorting, Greedy, Binary_Search, Prefix_Sum, Sliding_Window | 564 | 88.89 -| 0540 |[Single Element in a Sorted Array](src/main/kotlin/g0501_0600/s0540_single_element_in_a_sorted_array)| Medium | Array, Binary_Search | 274 | 86.67 +| 1523 |[Count Odd Numbers in an Interval Range](src/main/kotlin/g1501_1600/s1523_count_odd_numbers_in_an_interval_range)| Easy | Math | 114 | 97.22 +| 1491 |[Average Salary Excluding the Minimum and Maximum Salary](src/main/kotlin/g1401_1500/s1491_average_salary_excluding_the_minimum_and_maximum_salary)| Easy | Array, Sorting | 165 | 27.87 -#### Day 10 +#### Day 2 Operator | | | | | | |-|-|-|-|-|- -| 0222 |[Count Complete Tree Nodes](src/main/kotlin/g0201_0300/s0222_count_complete_tree_nodes)| ||| -| 1712 |[Ways to Split Array Into Three Subarrays](src/main/kotlin/g1701_1800/s1712_ways_to_split_array_into_three_subarrays)| Medium | Array, Binary_Search, Two_Pointers, Prefix_Sum | 486 | 100.00 +| 0191 |[Number of 1 Bits](src/main/kotlin/g0101_0200/s0191_number_of_1_bits)| Easy | Top_Interview_Questions, Bit_Manipulation | 237 | 68.44 +| 1281 |[Subtract the Product and Sum of Digits of an Integer](src/main/kotlin/g1201_1300/s1281_subtract_the_product_and_sum_of_digits_of_an_integer)| Easy | Math | 128 | 61.82 -#### Day 11 +#### Day 3 Conditional Statements | | | | | | |-|-|-|-|-|- -| 0826 |[Most Profit Assigning Work](src/main/kotlin/g0801_0900/s0826_most_profit_assigning_work)| Medium | Array, Sorting, Greedy, Binary_Search, Two_Pointers | 366 | 100.00 -| 0436 |[Find Right Interval](src/main/kotlin/g0401_0500/s0436_find_right_interval)| Medium | Array, Sorting, Binary_Search | 333 | 100.00 +| 0976 |[Largest Perimeter Triangle](src/main/kotlin/g0901_1000/s0976_largest_perimeter_triangle)| Easy | Array, Math, Sorting, Greedy | 304 | 33.33 +| 1779 |[Find Nearest Point That Has the Same X or Y Coordinate](src/main/kotlin/g1701_1800/s1779_find_nearest_point_that_has_the_same_x_or_y_coordinate)| Easy | Array | 364 | 100.00 -#### Day 12 +#### Day 4 Loop | | | | | | |-|-|-|-|-|- -| 0081 |[Search in Rotated Sorted Array II](src/main/kotlin/g0001_0100/s0081_search_in_rotated_sorted_array_ii)| Medium | Array, Binary_Search | 170 | 96.30 -| 0162 |[Find Peak Element](src/main/kotlin/g0101_0200/s0162_find_peak_element)| Medium | Top_Interview_Questions, Array, Binary_Search | 297 | 53.85 +| 1822 |[Sign of the Product of an Array](src/main/kotlin/g1801_1900/s1822_sign_of_the_product_of_an_array)| Easy | Array, Math | 170 | 92.51 +| 1502 |[Can Make Arithmetic Progression From Sequence](src/main/kotlin/g1501_1600/s1502_can_make_arithmetic_progression_from_sequence)| Easy | Array, Sorting | 156 | 94.82 +| 0202 |[Happy Number](src/main/kotlin/g0201_0300/s0202_happy_number)| Easy | Top_Interview_Questions, Hash_Table, Math, Two_Pointers | 261 | 45.08 +| 1790 |[Check if One String Swap Can Make Strings Equal](src/main/kotlin/g1701_1800/s1790_check_if_one_string_swap_can_make_strings_equal)| Easy | String, Hash_Table, Counting | 138 | 100.00 -#### Day 13 +#### Day 5 Function | | | | | | |-|-|-|-|-|- -| 0154 |[Find Minimum in Rotated Sorted Array II](src/main/kotlin/g0101_0200/s0154_find_minimum_in_rotated_sorted_array_ii)| Hard | Array, Binary_Search | 275 | 84.00 -| 0528 |[Random Pick with Weight](src/main/kotlin/g0501_0600/s0528_random_pick_with_weight)| Medium | Math, Binary_Search, Prefix_Sum, Randomized | 393 | 91.38 +| 0589 |[N-ary Tree Preorder Traversal](src/main/kotlin/g0501_0600/s0589_n_ary_tree_preorder_traversal)| Easy | Depth_First_Search, Tree, Stack | 233 | 84.02 +| 0496 |[Next Greater Element I](src/main/kotlin/g0401_0500/s0496_next_greater_element_i)| Easy | Array, Hash_Table, Stack, Monotonic_Stack | 171 | 100.00 +| 1232 |[Check If It Is a Straight Line](src/main/kotlin/g1201_1300/s1232_check_if_it_is_a_straight_line)| Easy | Array, Math, Geometry | 152 | 95.38 -#### Day 14 +#### Day 6 Array | | | | | | |-|-|-|-|-|- -| 1508 |[Range Sum of Sorted Subarray Sums](src/main/kotlin/g1501_1600/s1508_range_sum_of_sorted_subarray_sums)| Medium | Array, Sorting, Binary_Search, Two_Pointers | 378 | 66.67 -| 1574 |[Shortest Subarray to be Removed to Make Array Sorted](src/main/kotlin/g1501_1600/s1574_shortest_subarray_to_be_removed_to_make_array_sorted)| Medium | Array, Binary_Search, Two_Pointers, Stack, Monotonic_Stack | 477 | 50.00 +| 1588 |[Sum of All Odd Length Subarrays](src/main/kotlin/g1501_1600/s1588_sum_of_all_odd_length_subarrays)| Easy | Array, Math, Prefix_Sum | 157 | 64.00 +| 0283 |[Move Zeroes](src/main/kotlin/g0201_0300/s0283_move_zeroes)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Two_Pointers, Big_O_Time_O(n)_Space_O(1) | 516 | 79.07 +| 1672 |[Richest Customer Wealth](src/main/kotlin/g1601_1700/s1672_richest_customer_wealth)| Easy | Array, Matrix | 155 | 94.54 -#### Day 15 +#### Day 7 Array | | | | | | |-|-|-|-|-|- -| 1292 |[Maximum Side Length of a Square with Sum Less than or Equal to Threshold](src/main/kotlin/g1201_1300/s1292_maximum_side_length_of_a_square_with_sum_less_than_or_equal_to_threshold)| Medium | Array, Binary_Search, Matrix, Prefix_Sum | 376 | 100.00 -| 1498 |[Number of Subsequences That Satisfy the Given Sum Condition](src/main/kotlin/g1401_1500/s1498_number_of_subsequences_that_satisfy_the_given_sum_condition)| Medium | Array, Sorting, Binary_Search, Two_Pointers | 487 | 97.89 +| 1572 |[Matrix Diagonal Sum](src/main/kotlin/g1501_1600/s1572_matrix_diagonal_sum)| Easy | Array, Matrix | 221 | 67.61 +| 0566 |[Reshape the Matrix](src/main/kotlin/g0501_0600/s0566_reshape_the_matrix)| Easy | Array, Matrix, Simulation | 239 | 99.05 -#### Day 16 +#### Day 8 String | | | | | | |-|-|-|-|-|- -| 0981 |[Time Based Key-Value Store](src/main/kotlin/g0901_1000/s0981_time_based_key_value_store)| Medium | String, Hash_Table, Binary_Search, Design | 1011 | 65.56 -| 1300 |[Sum of Mutated Array Closest to Target](src/main/kotlin/g1201_1300/s1300_sum_of_mutated_array_closest_to_target)| Medium | Array, Sorting, Binary_Search | 217 | 100.00 +| 1768 |[Merge Strings Alternately](src/main/kotlin/g1701_1800/s1768_merge_strings_alternately)| Easy | String, Two_Pointers | 138 | 93.81 +| 1678 |[Goal Parser Interpretation](src/main/kotlin/g1601_1700/s1678_goal_parser_interpretation)| Easy | String | 136 | 88.24 +| 0389 |[Find the Difference](src/main/kotlin/g0301_0400/s0389_find_the_difference)| Easy | String, Hash_Table, Sorting, Bit_Manipulation | 256 | 64.81 -#### Day 17 +#### Day 9 String | | | | | | |-|-|-|-|-|- -| 1802 |[Maximum Value at a Given Index in a Bounded Array](src/main/kotlin/g1801_1900/s1802_maximum_value_at_a_given_index_in_a_bounded_array)| Medium | Greedy, Binary_Search | 118 | 100.00 -| 1901 |[Find a Peak Element II](src/main/kotlin/g1901_2000/s1901_find_a_peak_element_ii)| Medium | Array, Binary_Search, Matrix, Divide_and_Conquer | 726 | 100.00 +| 0709 |[To Lower Case](src/main/kotlin/g0701_0800/s0709_to_lower_case)| Easy | String | 142 | 98.68 +| 1309 |[Decrypt String from Alphabet to Integer Mapping](src/main/kotlin/g1301_1400/s1309_decrypt_string_from_alphabet_to_integer_mapping)| Easy | String | 129 | 95.45 +| 0953 |[Verifying an Alien Dictionary](src/main/kotlin/g0901_1000/s0953_verifying_an_alien_dictionary)| Easy | Array, String, Hash_Table | 137 | 100.00 -#### Day 18 +#### Day 10 Linked List and Tree | | | | | | |-|-|-|-|-|- -| 1146 |[Snapshot Array](src/main/kotlin/g1101_1200/s1146_snapshot_array)| Medium | Array, Hash_Table, Binary_Search, Design | 1064 | 57.14 -| 1488 |[Avoid Flood in The City](src/main/kotlin/g1401_1500/s1488_avoid_flood_in_the_city)| Medium | Array, Hash_Table, Greedy, Binary_Search, Heap_Priority_Queue | 823 | 66.67 +| 1290 |[Convert Binary Number in a Linked List to Integer](src/main/kotlin/g1201_1300/s1290_convert_binary_number_in_a_linked_list_to_integer)| Easy | Math, Linked_List | 145 | 25.93 +| 0876 |[Middle of the Linked List](src/main/kotlin/g0801_0900/s0876_middle_of_the_linked_list)| Easy | Two_Pointers, Linked_List | 136 | 76.52 +| 0104 |[Maximum Depth of Binary Tree](src/main/kotlin/g0101_0200/s0104_maximum_depth_of_binary_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Big_O_Time_O(N)_Space_O(H) | 166 | 83.53 +| 0404 |[Sum of Left Leaves](src/main/kotlin/g0401_0500/s0404_sum_of_left_leaves)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 173 | 86.05 -#### Day 19 +#### Day 11 Containers and Libraries | | | | | | |-|-|-|-|-|- -| 1562 |[Find Latest Group of Size M](src/main/kotlin/g1501_1600/s1562_find_latest_group_of_size_m)| Medium | Array, Binary_Search, Simulation | 534 | 100.00 -| 1648 |[Sell Diminishing-Valued Colored Balls](src/main/kotlin/g1601_1700/s1648_sell_diminishing_valued_colored_balls)| Medium | Array, Math, Sorting, Greedy, Binary_Search, Heap_Priority_Queue | 509 | 100.00 +| 1356 |[Sort Integers by The Number of 1 Bits](src/main/kotlin/g1301_1400/s1356_sort_integers_by_the_number_of_1_bits)| Easy | Array, Sorting, Bit_Manipulation, Counting | 236 | 92.31 +| 0232 |[Implement Queue using Stacks](src/main/kotlin/g0201_0300/s0232_implement_queue_using_stacks)| Easy | Stack, Design, Queue | 258 | 70.86 +| 0242 |[Valid Anagram](src/main/kotlin/g0201_0300/s0242_valid_anagram)| Easy | Top_Interview_Questions, String, Hash_Table, Sorting | 251 | 87.65 +| 0217 |[Contains Duplicate](src/main/kotlin/g0201_0300/s0217_contains_duplicate)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting | 719 | 73.49 -#### Day 20 +#### Day 12 Class and Object | | | | | | |-|-|-|-|-|- -| 1201 |[Ugly Number III](src/main/kotlin/g1201_1300/s1201_ugly_number_iii)| Medium | Math, Binary_Search, Number_Theory | 136 | 100.00 -| 0911 |[Online Election](src/main/kotlin/g0901_1000/s0911_online_election)| Medium | Array, Hash_Table, Binary_Search, Design | 766 | 83.33 +| 1603 |[Design Parking System](src/main/kotlin/g1601_1700/s1603_design_parking_system)| Easy | Design, Simulation, Counting | 376 | 31.83 +| 0303 |[Range Sum Query - Immutable](src/main/kotlin/g0301_0400/s0303_range_sum_query_immutable)| Easy | Array, Design, Prefix_Sum | 472 | 63.64 -### Dynamic Programming I +### Programming Skills II #### Day 1 | | | | | | |-|-|-|-|-|- -| 0509 |[Fibonacci Number](src/main/kotlin/g0501_0600/s0509_fibonacci_number)| Easy | Dynamic_Programming, Math, Recursion, Memoization | 139 | 82.72 -| 1137 |[N-th Tribonacci Number](src/main/kotlin/g1101_1200/s1137_n_th_tribonacci_number)| Easy | Dynamic_Programming, Math, Memoization | 122 | 69.35 +| 0896 |[Monotonic Array](src/main/kotlin/g0801_0900/s0896_monotonic_array)| Easy | Array | 576 | 90.91 +| 0028 |[Find the Index of the First Occurrence in a String](src/main/kotlin/g0001_0100/s0028_find_the_index_of_the_first_occurrence_in_a_string)| Easy | Top_Interview_Questions, String, Two_Pointers, String_Matching | 126 | 97.58 #### Day 2 | | | | | | |-|-|-|-|-|- -| 0070 |[Climbing Stairs](src/main/kotlin/g0001_0100/s0070_climbing_stairs)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Memoization, Big_O_Time_O(n)_Space_O(n) | 124 | 71.98 -| 0746 |[Min Cost Climbing Stairs](src/main/kotlin/g0701_0800/s0746_min_cost_climbing_stairs)| Easy | Array, Dynamic_Programming | 171 | 96.76 +| 0110 |[Balanced Binary Tree](src/main/kotlin/g0101_0200/s0110_balanced_binary_tree)| Easy | Depth_First_Search, Tree, Binary_Tree | 182 | 71.30 +| 0459 |[Repeated Substring Pattern](src/main/kotlin/g0401_0500/s0459_repeated_substring_pattern)| Easy | String, String_Matching | 201 | 100.00 #### Day 3 | | | | | | |-|-|-|-|-|- -| 0198 |[House Robber](src/main/kotlin/g0101_0200/s0198_house_robber)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Big_O_Time_O(n)_Space_O(n) | 156 | 92.24 -| 0213 |[House Robber II](src/main/kotlin/g0201_0300/s0213_house_robber_ii)| Medium | Array, Dynamic_Programming | 257 | 59.62 -| 0740 |[Delete and Earn](src/main/kotlin/g0701_0800/s0740_delete_and_earn)| Medium | Array, Hash_Table, Dynamic_Programming | 192 | 100.00 +| 0150 |[Evaluate Reverse Polish Notation](src/main/kotlin/g0101_0200/s0150_evaluate_reverse_polish_notation)| Medium | Top_Interview_Questions, Array, Math, Stack | 233 | 88.82 +| 0066 |[Plus One](src/main/kotlin/g0001_0100/s0066_plus_one)| Easy | Top_Interview_Questions, Array, Math | 148 | 98.75 #### Day 4 | | | | | | |-|-|-|-|-|- -| 0055 |[Jump Game](src/main/kotlin/g0001_0100/s0055_jump_game)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Greedy, Big_O_Time_O(n)_Space_O(1) | 332 | 89.35 -| 0045 |[Jump Game II](src/main/kotlin/g0001_0100/s0045_jump_game_ii)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Greedy, Big_O_Time_O(n)_Space_O(1) | 208 | 93.37 +| 1367 |[Linked List in Binary Tree](src/main/kotlin/g1301_1400/s1367_linked_list_in_binary_tree)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Linked_List | 237 | 92.86 +| 0043 |[Multiply Strings](src/main/kotlin/g0001_0100/s0043_multiply_strings)| Medium | String, Math, Simulation | 165 | 96.72 #### Day 5 | | | | | | |-|-|-|-|-|- -| 0053 |[Maximum Subarray](src/main/kotlin/g0001_0100/s0053_maximum_subarray)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer, Big_O_Time_O(n)_Space_O(1) | 510 | 78.81 -| 0918 |[Maximum Sum Circular Subarray](src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray)| Medium | Array, Dynamic_Programming, Divide_and_Conquer, Queue, Monotonic_Queue | 339 | 86.96 +| 0067 |[Add Binary](src/main/kotlin/g0001_0100/s0067_add_binary)| Easy | String, Math, Bit_Manipulation, Simulation | 164 | 90.60 +| 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 | | | | | | |-|-|-|-|-|- -| 0152 |[Maximum Product Subarray](src/main/kotlin/g0101_0200/s0152_maximum_product_subarray)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Big_O_Time_O(N)_Space_O(1) | 253 | 88.42 -| 1567 |[Maximum Length of Subarray With Positive Product](src/main/kotlin/g1501_1600/s1567_maximum_length_of_subarray_with_positive_product)| Medium | Array, Dynamic_Programming, Greedy | 468 | 33.33 +| 0739 |[Daily Temperatures](src/main/kotlin/g0701_0800/s0739_daily_temperatures)| Medium | Top_100_Liked_Questions, Array, Stack, Monotonic_Stack, Big_O_Time_O(n)_Space_O(n) | 936 | 80.54 +| 0058 |[Length of Last Word](src/main/kotlin/g0001_0100/s0058_length_of_last_word)| Easy | String | 135 | 93.67 #### Day 7 | | | | | | |-|-|-|-|-|- -| 1014 |[Best Sightseeing Pair](src/main/kotlin/g1001_1100/s1014_best_sightseeing_pair)| Medium | Array, Dynamic_Programming | 336 | 66.67 -| 0121 |[Best Time to Buy and Sell Stock](src/main/kotlin/g0101_0200/s0121_best_time_to_buy_and_sell_stock)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Big_O_Time_O(N)_Space_O(1) | 609 | 94.06 -| 0122 |[Best Time to Buy and Sell Stock II](src/main/kotlin/g0101_0200/s0122_best_time_to_buy_and_sell_stock_ii)| Medium | Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 197 | 95.10 +| 0048 |[Rotate Image](src/main/kotlin/g0001_0100/s0048_rotate_image)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Matrix, Big_O_Time_O(n^2)_Space_O(1) | 160 | 90.11 +| 1886 |[Determine Whether Matrix Can Be Obtained By Rotation](src/main/kotlin/g1801_1900/s1886_determine_whether_matrix_can_be_obtained_by_rotation)| Easy | Array, Matrix | 147 | 85.71 #### Day 8 | | | | | | |-|-|-|-|-|- -| 0309 |[Best Time to Buy and Sell Stock with Cooldown](src/main/kotlin/g0301_0400/s0309_best_time_to_buy_and_sell_stock_with_cooldown)| Medium | Array, Dynamic_Programming | 272 | 73.33 -| 0714 |[Best Time to Buy and Sell Stock with Transaction Fee](src/main/kotlin/g0701_0800/s0714_best_time_to_buy_and_sell_stock_with_transaction_fee)| Medium | Array, Dynamic_Programming, Greedy | 417 | 90.91 +| 0054 |[Spiral Matrix](src/main/kotlin/g0001_0100/s0054_spiral_matrix)| Medium | Top_Interview_Questions, Array, Matrix, Simulation | 132 | 95.12 +| 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 | | | | | | |-|-|-|-|-|- -| 0139 |[Word Break](src/main/kotlin/g0101_0200/s0139_word_break)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Dynamic_Programming, Trie, Memoization, Big_O_Time_O(M+max\*N)_Space_O(M+N+max) | 197 | 87.17 -| 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, Big_O_Time_O(n)_Space_O(1) | 189 | 99.37 +| 1630 |[Arithmetic Subarrays](src/main/kotlin/g1601_1700/s1630_arithmetic_subarrays)| Medium | Array, Sorting | 264 | 100.00 +| 0429 |[N-ary Tree Level Order Traversal](src/main/kotlin/g0401_0500/s0429_n_ary_tree_level_order_traversal)| Medium | Breadth_First_Search, Tree | 248 | 75.86 #### Day 10 | | | | | | |-|-|-|-|-|- -| 0413 |[Arithmetic Slices](src/main/kotlin/g0401_0500/s0413_arithmetic_slices)| Medium | Array, Dynamic_Programming | 156 | 100.00 -| 0091 |[Decode Ways](src/main/kotlin/g0001_0100/s0091_decode_ways)| Medium | Top_Interview_Questions, String, Dynamic_Programming | 148 | 79.07 +| 0503 |[Next Greater Element II](src/main/kotlin/g0501_0600/s0503_next_greater_element_ii)| Medium | Array, Stack, Monotonic_Stack | 331 | 92.68 +| 0556 |[Next Greater Element III](src/main/kotlin/g0501_0600/s0556_next_greater_element_iii)| Medium | String, Math, Two_Pointers | 137 | 80.00 #### Day 11 | | | | | | |-|-|-|-|-|- -| 0264 |[Ugly Number II](src/main/kotlin/g0201_0300/s0264_ugly_number_ii)| Medium | Hash_Table, Dynamic_Programming, Math, Heap_Priority_Queue | 182 | 95.45 -| 0096 |[Unique Binary Search Trees](src/main/kotlin/g0001_0100/s0096_unique_binary_search_trees)| Medium | Top_100_Liked_Questions, Dynamic_Programming, Math, Tree, Binary_Tree, Binary_Search_Tree, Big_O_Time_O(n)_Space_O(1) | 116 | 92.31 +| 1376 |[Time Needed to Inform All Employees](src/main/kotlin/g1301_1400/s1376_time_needed_to_inform_all_employees)| Medium | Depth_First_Search, Breadth_First_Search, Tree | 915 | 37.62 +| 0049 |[Group Anagrams](src/main/kotlin/g0001_0100/s0049_group_anagrams)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, String, Hash_Table, Sorting, Big_O_Time_O(n\*k_log_k)_Space_O(n) | 308 | 96.34 #### Day 12 | | | | | | |-|-|-|-|-|- -| 0118 |[Pascal's Triangle](src/main/kotlin/g0101_0200/s0118_pascals_triangle)| Easy | Top_Interview_Questions, Array, Dynamic_Programming | 277 | 33.22 -| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming | 157 | 97.27 +| 0438 |[Find All Anagrams in a String](src/main/kotlin/g0401_0500/s0438_find_all_anagrams_in_a_string)| Medium | Top_100_Liked_Questions, String, Hash_Table, Sliding_Window, Big_O_Time_O(n+m)_Space_O(1) | 561 | 54.68 +| 0713 |[Subarray Product Less Than K](src/main/kotlin/g0701_0800/s0713_subarray_product_less_than_k)| Medium | Array, Sliding_Window | 336 | 92.11 #### Day 13 | | | | | | |-|-|-|-|-|- -| 0931 |[Minimum Falling Path Sum](src/main/kotlin/g0901_1000/s0931_minimum_falling_path_sum)| Medium | Array, Dynamic_Programming, Matrix | 201 | 84.21 -| 0120 |[Triangle](src/main/kotlin/g0101_0200/s0120_triangle)| Medium | Array, Dynamic_Programming | 194 | 97.87 +| 0304 |[Range Sum Query 2D - Immutable](src/main/kotlin/g0301_0400/s0304_range_sum_query_2d_immutable)| Medium | Array, Matrix, Design, Prefix_Sum | 1373 | 85.71 +| 0910 |[Smallest Range II](src/main/kotlin/g0901_1000/s0910_smallest_range_ii)| Medium | Array, Math, Sorting, Greedy | 234 | 100.00 #### Day 14 | | | | | | |-|-|-|-|-|- -| 1314 |[Matrix Block Sum](src/main/kotlin/g1301_1400/s1314_matrix_block_sum)| Medium | Array, Matrix, Prefix_Sum | 235 | 100.00 -| 0304 |[Range Sum Query 2D - Immutable](src/main/kotlin/g0301_0400/s0304_range_sum_query_2d_immutable)| Medium | Array, Matrix, Design, Prefix_Sum | 1373 | 85.71 +| 0143 |[Reorder List](src/main/kotlin/g0101_0200/s0143_reorder_list)| Medium | Two_Pointers, Stack, Linked_List, Recursion | 395 | 82.26 +| 0138 |[Copy List with Random Pointer](src/main/kotlin/g0101_0200/s0138_copy_list_with_random_pointer)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Linked_List, Big_O_Time_O(N)_Space_O(N) | 274 | 80.58 #### Day 15 | | | | | | |-|-|-|-|-|- -| 0062 |[Unique Paths](src/main/kotlin/g0001_0100/s0062_unique_paths)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Combinatorics, Big_O_Time_O(m\*n)_Space_O(m\*n) | 118 | 94.65 -| 0063 |[Unique Paths II](src/main/kotlin/g0001_0100/s0063_unique_paths_ii)| Medium | Array, Dynamic_Programming, Matrix | 151 | 81.94 +| 0002 |[Add Two Numbers](src/main/kotlin/g0001_0100/s0002_add_two_numbers)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Math, Linked_List, Recursion, Big_O_Time_O(max(N,M))_Space_O(max(N,M)) | 203 | 96.13 +| 0445 |[Add Two Numbers II](src/main/kotlin/g0401_0500/s0445_add_two_numbers_ii)| Medium | Math, Stack, Linked_List | 240 | 82.61 #### Day 16 | | | | | | |-|-|-|-|-|- -| 0064 |[Minimum Path Sum](src/main/kotlin/g0001_0100/s0064_minimum_path_sum)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Matrix, Big_O_Time_O(m\*n)_Space_O(m\*n) | 164 | 100.00 -| 0221 |[Maximal Square](src/main/kotlin/g0201_0300/s0221_maximal_square)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Matrix, Big_O_Time_O(m\*n)_Space_O(m\*n) | 614 | 44.00 +| 0061 |[Rotate List](src/main/kotlin/g0001_0100/s0061_rotate_list)| Medium | Two_Pointers, Linked_List | 160 | 92.22 +| 0173 |[Binary Search Tree Iterator](src/main/kotlin/g0101_0200/s0173_binary_search_tree_iterator)| Medium | Tree, Binary_Tree, Stack, Design, Binary_Search_Tree, Iterator | 563 | 46.91 #### Day 17 | | | | | | |-|-|-|-|-|- -| 0005 |[Longest Palindromic Substring](src/main/kotlin/g0001_0100/s0005_longest_palindromic_substring)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming, Big_O_Time_O(n)_Space_O(n) | 162 | 99.00 -| 0516 |[Longest Palindromic Subsequence](src/main/kotlin/g0501_0600/s0516_longest_palindromic_subsequence)| Medium | String, Dynamic_Programming | 243 | 87.50 +| 1845 |[Seat Reservation Manager](src/main/kotlin/g1801_1900/s1845_seat_reservation_manager)| Medium | Design, Heap_Priority_Queue | 834 | 100.00 +| 0860 |[Lemonade Change](src/main/kotlin/g0801_0900/s0860_lemonade_change)| Easy | Array, Greedy | 413 | 86.96 #### Day 18 | | | | | | |-|-|-|-|-|- -| 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search, Big_O_Time_O(n\*log_n)_Space_O(n) | 318 | 82.28 -| 0376 |[Wiggle Subsequence](src/main/kotlin/g0301_0400/s0376_wiggle_subsequence)| Medium | Array, Dynamic_Programming, Greedy | 162 | 88.89 +| 0155 |[Min Stack](src/main/kotlin/g0101_0200/s0155_min_stack)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Stack, Design, Big_O_Time_O(1)_Space_O(N) | 331 | 84.88 +| 0341 |[Flatten Nested List Iterator](src/main/kotlin/g0301_0400/s0341_flatten_nested_list_iterator)| Medium | Top_Interview_Questions, Depth_First_Search, Tree, Stack, Design, Queue, Iterator | 210 | 100.00 #### Day 19 | | | | | | |-|-|-|-|-|- -| 0392 |[Is Subsequence](src/main/kotlin/g0301_0400/s0392_is_subsequence)| Easy | String, Dynamic_Programming, Two_Pointers | 156 | 87.74 -| 1143 |[Longest Common Subsequence](src/main/kotlin/g1101_1200/s1143_longest_common_subsequence)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming, Big_O_Time_O(n\*m)_Space_O(n\*m) | 307 | 38.36 -| 0072 |[Edit Distance](src/main/kotlin/g0001_0100/s0072_edit_distance)| Hard | Top_100_Liked_Questions, String, Dynamic_Programming, Big_O_Time_O(n^2)_Space_O(n2) | 182 | 92.16 +| 1797 |[Design Authentication Manager](src/main/kotlin/g1701_1800/s1797_design_authentication_manager)| Medium | Hash_Table, Design | 334 | 100.00 +| 0707 |[Design Linked List](src/main/kotlin/g0701_0800/s0707_design_linked_list)| Medium | Design, Linked_List | 243 | 100.00 #### Day 20 | | | | | | |-|-|-|-|-|- -| 0322 |[Coin Change](src/main/kotlin/g0301_0400/s0322_coin_change)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Breadth_First_Search, Big_O_Time_O(m\*n)_Space_O(amount) | 332 | 50.68 -| 0518 |[Coin Change II](src/main/kotlin/g0501_0600/s0518_coin_change_2)| Medium | Array, Dynamic_Programming | 139 | 100.00 +| 0380 |[Insert Delete GetRandom O(1)](src/main/kotlin/g0301_0400/s0380_insert_delete_getrandom_o1)| Medium | Top_Interview_Questions, Array, Hash_Table, Math, Design, Randomized | 1326 | 68.23 +| 0622 |[Design Circular Queue](src/main/kotlin/g0601_0700/s0622_design_circular_queue)| Medium | Array, Design, Linked_List, Queue | 234 | 92.68 +| 0729 |[My Calendar I](src/main/kotlin/g0701_0800/s0729_my_calendar_i)| Medium | Binary_Search, Design, Ordered_Set, Segment_Tree | 378 | 69.70 -#### Day 21 +### Graph Theory I + +#### Day 1 Matrix Related Problems | | | | | | |-|-|-|-|-|- -| 0377 |[Combination Sum IV](src/main/kotlin/g0301_0400/s0377_combination_sum_iv)| Medium | Array, Dynamic_Programming | 217 | 72.41 -| 0343 |[Integer Break](src/main/kotlin/g0301_0400/s0343_integer_break)| Medium | Dynamic_Programming, Math | 218 | 63.89 -| 0279 |[Perfect Squares](src/main/kotlin/g0201_0300/s0279_perfect_squares)| Medium | Top_Interview_Questions, Dynamic_Programming, Math, Breadth_First_Search | 176 | 98.80 - -### Programming Skills I +| 0733 |[Flood Fill](src/main/kotlin/g0701_0800/s0733_flood_fill)| Easy | Array, Depth_First_Search, Breadth_First_Search, Matrix | 230 | 97.76 +| 0200 |[Number of Islands](src/main/kotlin/g0101_0200/s0200_number_of_islands)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find, Big_O_Time_O(M\*N)_Space_O(M\*N) | 252 | 95.41 -#### Day 1 Basic Data Type +#### Day 2 Matrix Related Problems | | | | | | |-|-|-|-|-|- -| 1523 |[Count Odd Numbers in an Interval Range](src/main/kotlin/g1501_1600/s1523_count_odd_numbers_in_an_interval_range)| Easy | Math | 114 | 97.22 -| 1491 |[Average Salary Excluding the Minimum and Maximum Salary](src/main/kotlin/g1401_1500/s1491_average_salary_excluding_the_minimum_and_maximum_salary)| Easy | Array, Sorting | 165 | 27.87 +| 0695 |[Max Area of Island](src/main/kotlin/g0601_0700/s0695_max_area_of_island)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 324 | 24.06 +| 1254 |[Number of Closed Islands](src/main/kotlin/g1201_1300/s1254_number_of_closed_islands)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 177 | 89.47 -#### Day 2 Operator +#### Day 3 Matrix Related Problems | | | | | | |-|-|-|-|-|- -| 0191 |[Number of 1 Bits](src/main/kotlin/g0101_0200/s0191_number_of_1_bits)| Easy | Top_Interview_Questions, Bit_Manipulation | 237 | 68.44 -| 1281 |[Subtract the Product and Sum of Digits of an Integer](src/main/kotlin/g1201_1300/s1281_subtract_the_product_and_sum_of_digits_of_an_integer)| Easy | Math | 128 | 61.82 +| 1020 |[Number of Enclaves](src/main/kotlin/g1001_1100/s1020_number_of_enclaves)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 369 | 76.26 +| 1905 |[Count Sub Islands](src/main/kotlin/g1901_2000/s1905_count_sub_islands)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 866 | 100.00 -#### Day 3 Conditional Statements - -| | | | | | -|-|-|-|-|-|- -| 0976 |[Largest Perimeter Triangle](src/main/kotlin/g0901_1000/s0976_largest_perimeter_triangle)| Easy | Array, Math, Sorting, Greedy | 304 | 33.33 -| 1779 |[Find Nearest Point That Has the Same X or Y Coordinate](src/main/kotlin/g1701_1800/s1779_find_nearest_point_that_has_the_same_x_or_y_coordinate)| Easy | Array | 364 | 100.00 - -#### Day 4 Loop - -| | | | | | -|-|-|-|-|-|- -| 1822 |[Sign of the Product of an Array](src/main/kotlin/g1801_1900/s1822_sign_of_the_product_of_an_array)| Easy | Array, Math | 170 | 92.51 -| 1502 |[Can Make Arithmetic Progression From Sequence](src/main/kotlin/g1501_1600/s1502_can_make_arithmetic_progression_from_sequence)| Easy | Array, Sorting | 156 | 94.82 -| 0202 |[Happy Number](src/main/kotlin/g0201_0300/s0202_happy_number)| Easy | Top_Interview_Questions, Hash_Table, Math, Two_Pointers | 261 | 45.08 -| 1790 |[Check if One String Swap Can Make Strings Equal](src/main/kotlin/g1701_1800/s1790_check_if_one_string_swap_can_make_strings_equal)| Easy | String, Hash_Table, Counting | 138 | 100.00 - -#### Day 5 Function - -| | | | | | -|-|-|-|-|-|- -| 0589 |[N-ary Tree Preorder Traversal](src/main/kotlin/g0501_0600/s0589_n_ary_tree_preorder_traversal)| Easy | Depth_First_Search, Tree, Stack | 233 | 84.02 -| 0496 |[Next Greater Element I](src/main/kotlin/g0401_0500/s0496_next_greater_element_i)| Easy | Array, Hash_Table, Stack, Monotonic_Stack | 171 | 100.00 -| 1232 |[Check If It Is a Straight Line](src/main/kotlin/g1201_1300/s1232_check_if_it_is_a_straight_line)| Easy | Array, Math, Geometry | 152 | 95.38 - -#### Day 6 Array - -| | | | | | -|-|-|-|-|-|- -| 1588 |[Sum of All Odd Length Subarrays](src/main/kotlin/g1501_1600/s1588_sum_of_all_odd_length_subarrays)| Easy | Array, Math, Prefix_Sum | 157 | 64.00 -| 0283 |[Move Zeroes](src/main/kotlin/g0201_0300/s0283_move_zeroes)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Two_Pointers, Big_O_Time_O(n)_Space_O(1) | 516 | 79.07 -| 1672 |[Richest Customer Wealth](src/main/kotlin/g1601_1700/s1672_richest_customer_wealth)| Easy | Array, Matrix | 155 | 94.54 - -#### Day 7 Array - -| | | | | | -|-|-|-|-|-|- -| 1572 |[Matrix Diagonal Sum](src/main/kotlin/g1501_1600/s1572_matrix_diagonal_sum)| Easy | Array, Matrix | 221 | 67.61 -| 0566 |[Reshape the Matrix](src/main/kotlin/g0501_0600/s0566_reshape_the_matrix)| Easy | Array, Matrix, Simulation | 239 | 99.05 - -#### Day 8 String - -| | | | | | -|-|-|-|-|-|- -| 1768 |[Merge Strings Alternately](src/main/kotlin/g1701_1800/s1768_merge_strings_alternately)| Easy | String, Two_Pointers | 138 | 93.81 -| 1678 |[Goal Parser Interpretation](src/main/kotlin/g1601_1700/s1678_goal_parser_interpretation)| Easy | String | 136 | 88.24 -| 0389 |[Find the Difference](src/main/kotlin/g0301_0400/s0389_find_the_difference)| Easy | String, Hash_Table, Sorting, Bit_Manipulation | 256 | 64.81 - -#### Day 9 String - -| | | | | | -|-|-|-|-|-|- -| 0709 |[To Lower Case](src/main/kotlin/g0701_0800/s0709_to_lower_case)| Easy | String | 142 | 98.68 -| 1309 |[Decrypt String from Alphabet to Integer Mapping](src/main/kotlin/g1301_1400/s1309_decrypt_string_from_alphabet_to_integer_mapping)| Easy | String | 129 | 95.45 -| 0953 |[Verifying an Alien Dictionary](src/main/kotlin/g0901_1000/s0953_verifying_an_alien_dictionary)| Easy | Array, String, Hash_Table | 137 | 100.00 - -#### Day 10 Linked List and Tree - -| | | | | | -|-|-|-|-|-|- -| 1290 |[Convert Binary Number in a Linked List to Integer](src/main/kotlin/g1201_1300/s1290_convert_binary_number_in_a_linked_list_to_integer)| Easy | Math, Linked_List | 145 | 25.93 -| 0876 |[Middle of the Linked List](src/main/kotlin/g0801_0900/s0876_middle_of_the_linked_list)| Easy | Two_Pointers, Linked_List | 136 | 76.52 -| 0104 |[Maximum Depth of Binary Tree](src/main/kotlin/g0101_0200/s0104_maximum_depth_of_binary_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Big_O_Time_O(N)_Space_O(H) | 166 | 83.53 -| 0404 |[Sum of Left Leaves](src/main/kotlin/g0401_0500/s0404_sum_of_left_leaves)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 173 | 86.05 - -#### Day 11 Containers and Libraries - -| | | | | | -|-|-|-|-|-|- -| 1356 |[Sort Integers by The Number of 1 Bits](src/main/kotlin/g1301_1400/s1356_sort_integers_by_the_number_of_1_bits)| Easy | Array, Sorting, Bit_Manipulation, Counting | 236 | 92.31 -| 0232 |[Implement Queue using Stacks](src/main/kotlin/g0201_0300/s0232_implement_queue_using_stacks)| Easy | Stack, Design, Queue | 258 | 70.86 -| 0242 |[Valid Anagram](src/main/kotlin/g0201_0300/s0242_valid_anagram)| Easy | Top_Interview_Questions, String, Hash_Table, Sorting | 251 | 87.65 -| 0217 |[Contains Duplicate](src/main/kotlin/g0201_0300/s0217_contains_duplicate)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting | 719 | 73.49 - -#### Day 12 Class and Object - -| | | | | | -|-|-|-|-|-|- -| 1603 |[Design Parking System](src/main/kotlin/g1601_1700/s1603_design_parking_system)| Easy | Design, Simulation, Counting | 376 | 31.83 -| 0303 |[Range Sum Query - Immutable](src/main/kotlin/g0301_0400/s0303_range_sum_query_immutable)| Easy | Array, Design, Prefix_Sum | 472 | 63.64 - -### Programming Skills II - -#### Day 1 - -| | | | | | -|-|-|-|-|-|- -| 0896 |[Monotonic Array](src/main/kotlin/g0801_0900/s0896_monotonic_array)| Easy | Array | 576 | 90.91 -| 0028 |[Find the Index of the First Occurrence in a String](src/main/kotlin/g0001_0100/s0028_find_the_index_of_the_first_occurrence_in_a_string)| Easy | Top_Interview_Questions, String, Two_Pointers, String_Matching | 126 | 97.58 - -#### Day 2 - -| | | | | | -|-|-|-|-|-|- -| 0110 |[Balanced Binary Tree](src/main/kotlin/g0101_0200/s0110_balanced_binary_tree)| Easy | Depth_First_Search, Tree, Binary_Tree | 182 | 71.30 -| 0459 |[Repeated Substring Pattern](src/main/kotlin/g0401_0500/s0459_repeated_substring_pattern)| Easy | String, String_Matching | 201 | 100.00 - -#### Day 3 - -| | | | | | -|-|-|-|-|-|- -| 0150 |[Evaluate Reverse Polish Notation](src/main/kotlin/g0101_0200/s0150_evaluate_reverse_polish_notation)| Medium | Top_Interview_Questions, Array, Math, Stack | 233 | 88.82 -| 0066 |[Plus One](src/main/kotlin/g0001_0100/s0066_plus_one)| Easy | Top_Interview_Questions, Array, Math | 148 | 98.75 - -#### Day 4 - -| | | | | | -|-|-|-|-|-|- -| 1367 |[Linked List in Binary Tree](src/main/kotlin/g1301_1400/s1367_linked_list_in_binary_tree)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Linked_List | 237 | 92.86 -| 0043 |[Multiply Strings](src/main/kotlin/g0001_0100/s0043_multiply_strings)| Medium | String, Math, Simulation | 165 | 96.72 - -#### Day 5 - -| | | | | | -|-|-|-|-|-|- -| 0067 |[Add Binary](src/main/kotlin/g0001_0100/s0067_add_binary)| Easy | String, Math, Bit_Manipulation, Simulation | 164 | 90.60 -| 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 - -| | | | | | -|-|-|-|-|-|- -| 0739 |[Daily Temperatures](src/main/kotlin/g0701_0800/s0739_daily_temperatures)| Medium | Top_100_Liked_Questions, Array, Stack, Monotonic_Stack, Big_O_Time_O(n)_Space_O(n) | 936 | 80.54 -| 0058 |[Length of Last Word](src/main/kotlin/g0001_0100/s0058_length_of_last_word)| Easy | String | 135 | 93.67 - -#### Day 7 - -| | | | | | -|-|-|-|-|-|- -| 0048 |[Rotate Image](src/main/kotlin/g0001_0100/s0048_rotate_image)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Matrix, Big_O_Time_O(n^2)_Space_O(1) | 160 | 90.11 -| 1886 |[Determine Whether Matrix Can Be Obtained By Rotation](src/main/kotlin/g1801_1900/s1886_determine_whether_matrix_can_be_obtained_by_rotation)| Easy | Array, Matrix | 147 | 85.71 - -#### Day 8 - -| | | | | | -|-|-|-|-|-|- -| 0054 |[Spiral Matrix](src/main/kotlin/g0001_0100/s0054_spiral_matrix)| Medium | Top_Interview_Questions, Array, Matrix, Simulation | 132 | 95.12 -| 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 - -| | | | | | -|-|-|-|-|-|- -| 1630 |[Arithmetic Subarrays](src/main/kotlin/g1601_1700/s1630_arithmetic_subarrays)| Medium | Array, Sorting | 264 | 100.00 -| 0429 |[N-ary Tree Level Order Traversal](src/main/kotlin/g0401_0500/s0429_n_ary_tree_level_order_traversal)| Medium | Breadth_First_Search, Tree | 248 | 75.86 - -#### Day 10 - -| | | | | | -|-|-|-|-|-|- -| 0503 |[Next Greater Element II](src/main/kotlin/g0501_0600/s0503_next_greater_element_ii)| Medium | Array, Stack, Monotonic_Stack | 331 | 92.68 -| 0556 |[Next Greater Element III](src/main/kotlin/g0501_0600/s0556_next_greater_element_iii)| Medium | String, Math, Two_Pointers | 137 | 80.00 - -#### Day 11 - -| | | | | | -|-|-|-|-|-|- -| 1376 |[Time Needed to Inform All Employees](src/main/kotlin/g1301_1400/s1376_time_needed_to_inform_all_employees)| Medium | Depth_First_Search, Breadth_First_Search, Tree | 915 | 37.62 -| 0049 |[Group Anagrams](src/main/kotlin/g0001_0100/s0049_group_anagrams)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, String, Hash_Table, Sorting, Big_O_Time_O(n\*k_log_k)_Space_O(n) | 308 | 96.34 - -#### Day 12 - -| | | | | | -|-|-|-|-|-|- -| 0438 |[Find All Anagrams in a String](src/main/kotlin/g0401_0500/s0438_find_all_anagrams_in_a_string)| Medium | Top_100_Liked_Questions, String, Hash_Table, Sliding_Window, Big_O_Time_O(n+m)_Space_O(1) | 561 | 54.68 -| 0713 |[Subarray Product Less Than K](src/main/kotlin/g0701_0800/s0713_subarray_product_less_than_k)| Medium | Array, Sliding_Window | 336 | 92.11 - -#### Day 13 - -| | | | | | -|-|-|-|-|-|- -| 0304 |[Range Sum Query 2D - Immutable](src/main/kotlin/g0301_0400/s0304_range_sum_query_2d_immutable)| Medium | Array, Matrix, Design, Prefix_Sum | 1373 | 85.71 -| 0910 |[Smallest Range II](src/main/kotlin/g0901_1000/s0910_smallest_range_ii)| Medium | Array, Math, Sorting, Greedy | 234 | 100.00 - -#### Day 14 - -| | | | | | -|-|-|-|-|-|- -| 0143 |[Reorder List](src/main/kotlin/g0101_0200/s0143_reorder_list)| Medium | Two_Pointers, Stack, Linked_List, Recursion | 395 | 82.26 -| 0138 |[Copy List with Random Pointer](src/main/kotlin/g0101_0200/s0138_copy_list_with_random_pointer)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Linked_List, Big_O_Time_O(N)_Space_O(N) | 274 | 80.58 - -#### Day 15 - -| | | | | | -|-|-|-|-|-|- -| 0002 |[Add Two Numbers](src/main/kotlin/g0001_0100/s0002_add_two_numbers)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Math, Linked_List, Recursion, Big_O_Time_O(max(N,M))_Space_O(max(N,M)) | 203 | 96.13 -| 0445 |[Add Two Numbers II](src/main/kotlin/g0401_0500/s0445_add_two_numbers_ii)| Medium | Math, Stack, Linked_List | 240 | 82.61 - -#### Day 16 - -| | | | | | -|-|-|-|-|-|- -| 0061 |[Rotate List](src/main/kotlin/g0001_0100/s0061_rotate_list)| Medium | Two_Pointers, Linked_List | 160 | 92.22 -| 0173 |[Binary Search Tree Iterator](src/main/kotlin/g0101_0200/s0173_binary_search_tree_iterator)| Medium | Tree, Binary_Tree, Stack, Design, Binary_Search_Tree, Iterator | 563 | 46.91 - -#### Day 17 - -| | | | | | -|-|-|-|-|-|- -| 1845 |[Seat Reservation Manager](src/main/kotlin/g1801_1900/s1845_seat_reservation_manager)| Medium | Design, Heap_Priority_Queue | 834 | 100.00 -| 0860 |[Lemonade Change](src/main/kotlin/g0801_0900/s0860_lemonade_change)| Easy | Array, Greedy | 413 | 86.96 - -#### Day 18 - -| | | | | | -|-|-|-|-|-|- -| 0155 |[Min Stack](src/main/kotlin/g0101_0200/s0155_min_stack)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Stack, Design, Big_O_Time_O(1)_Space_O(N) | 331 | 84.88 -| 0341 |[Flatten Nested List Iterator](src/main/kotlin/g0301_0400/s0341_flatten_nested_list_iterator)| Medium | Top_Interview_Questions, Depth_First_Search, Tree, Stack, Design, Queue, Iterator | 210 | 100.00 - -#### Day 19 - -| | | | | | -|-|-|-|-|-|- -| 1797 |[Design Authentication Manager](src/main/kotlin/g1701_1800/s1797_design_authentication_manager)| Medium | Hash_Table, Design | 334 | 100.00 -| 0707 |[Design Linked List](src/main/kotlin/g0701_0800/s0707_design_linked_list)| Medium | Design, Linked_List | 243 | 100.00 - -#### Day 20 - -| | | | | | -|-|-|-|-|-|- -| 0380 |[Insert Delete GetRandom O(1)](src/main/kotlin/g0301_0400/s0380_insert_delete_getrandom_o1)| Medium | Top_Interview_Questions, Array, Hash_Table, Math, Design, Randomized | 1326 | 68.23 -| 0622 |[Design Circular Queue](src/main/kotlin/g0601_0700/s0622_design_circular_queue)| Medium | Array, Design, Linked_List, Queue | 234 | 92.68 -| 0729 |[My Calendar I](src/main/kotlin/g0701_0800/s0729_my_calendar_i)| Medium | Binary_Search, Design, Ordered_Set, Segment_Tree | 378 | 69.70 - -### Graph Theory I - -#### Day 1 Matrix Related Problems - -| | | | | | -|-|-|-|-|-|- -| 0733 |[Flood Fill](src/main/kotlin/g0701_0800/s0733_flood_fill)| Easy | Array, Depth_First_Search, Breadth_First_Search, Matrix | 230 | 97.76 -| 0200 |[Number of Islands](src/main/kotlin/g0101_0200/s0200_number_of_islands)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find, Big_O_Time_O(M\*N)_Space_O(M\*N) | 252 | 95.41 - -#### Day 2 Matrix Related Problems - -| | | | | | -|-|-|-|-|-|- -| 0695 |[Max Area of Island](src/main/kotlin/g0601_0700/s0695_max_area_of_island)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 324 | 24.06 -| 1254 |[Number of Closed Islands](src/main/kotlin/g1201_1300/s1254_number_of_closed_islands)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 177 | 89.47 - -#### Day 3 Matrix Related Problems - -| | | | | | -|-|-|-|-|-|- -| 1020 |[Number of Enclaves](src/main/kotlin/g1001_1100/s1020_number_of_enclaves)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 369 | 76.26 -| 1905 |[Count Sub Islands](src/main/kotlin/g1901_2000/s1905_count_sub_islands)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 866 | 100.00 - -#### Day 4 Matrix Related Problems +#### Day 4 Matrix Related Problems | | | | | | |-|-|-|-|-|- @@ -1812,10 +1517,348 @@ |-|-|-|-|-|- | 0153 |[Find Minimum in Rotated Sorted Array](src/main/kotlin/g0101_0200/s0153_find_minimum_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Array, Binary_Search, Big_O_Time_O(log_N)_Space_O(log_N) | 262 | 60.96 +### Binary Search II + +#### Day 1 + +| | | | | | +|-|-|-|-|-|- +| 0209 |[Minimum Size Subarray Sum](src/main/kotlin/g0201_0300/s0209_minimum_size_subarray_sum)| Medium | Array, Binary_Search, Prefix_Sum, Sliding_Window | 315 | 96.73 +| 0611 |[Valid Triangle Number](src/main/kotlin/g0601_0700/s0611_valid_triangle_number)| Medium | Array, Sorting, Greedy, Binary_Search, Two_Pointers | 203 | 100.00 + +#### Day 2 + +| | | | | | +|-|-|-|-|-|- +| 0658 |[Find K Closest Elements](src/main/kotlin/g0601_0700/s0658_find_k_closest_elements)| Medium | Array, Sorting, Binary_Search, Two_Pointers, Heap_Priority_Queue | 375 | 95.16 +| 1894 |[Find the Student that Will Replace the Chalk](src/main/kotlin/g1801_1900/s1894_find_the_student_that_will_replace_the_chalk)| Medium | Array, Binary_Search, Simulation, Prefix_Sum | 520 | 50.00 + +#### Day 3 + +| | | | | | +|-|-|-|-|-|- +| 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search, Big_O_Time_O(n\*log_n)_Space_O(n) | 318 | 82.28 +| 1760 |[Minimum Limit of Balls in a Bag](src/main/kotlin/g1701_1800/s1760_minimum_limit_of_balls_in_a_bag)| Medium | Array, Binary_Search | 460 | 100.00 + +#### Day 4 + +| | | | | | +|-|-|-|-|-|- +| 0875 |[Koko Eating Bananas](src/main/kotlin/g0801_0900/s0875_koko_eating_bananas)| Medium | Array, Binary_Search | 267 | 93.85 +| 1552 |[Magnetic Force Between Two Balls](src/main/kotlin/g1501_1600/s1552_magnetic_force_between_two_balls)| Medium | Array, Sorting, Binary_Search | 636 | 100.00 + +#### Day 5 + +| | | | | | +|-|-|-|-|-|- +| 0287 |[Find the Duplicate Number](src/main/kotlin/g0201_0300/s0287_find_the_duplicate_number)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search, Two_Pointers, Bit_Manipulation, Big_O_Time_O(n)_Space_O(n) | 656 | 66.21 +| 1283 |[Find the Smallest Divisor Given a Threshold](src/main/kotlin/g1201_1300/s1283_find_the_smallest_divisor_given_a_threshold)| Medium | Array, Binary_Search | 255 | 100.00 + +#### Day 6 + +| | | | | | +|-|-|-|-|-|- +| 1898 |[Maximum Number of Removable Characters](src/main/kotlin/g1801_1900/s1898_maximum_number_of_removable_characters)| Medium | Array, String, Binary_Search | 636 | 100.00 +| 1870 |[Minimum Speed to Arrive on Time](src/main/kotlin/g1801_1900/s1870_minimum_speed_to_arrive_on_time)| Medium | Array, Binary_Search | 628 | 50.00 + +#### Day 7 + +| | | | | | +|-|-|-|-|-|- +| 1482 |[Minimum Number of Days to Make m Bouquets](src/main/kotlin/g1401_1500/s1482_minimum_number_of_days_to_make_m_bouquets)| Medium | Array, Binary_Search | 538 | 50.00 +| 1818 |[Minimum Absolute Sum Difference](src/main/kotlin/g1801_1900/s1818_minimum_absolute_sum_difference)| Medium | Array, Sorting, Binary_Search, Ordered_Set | 447 | 100.00 + +#### Day 8 + +| | | | | | +|-|-|-|-|-|- +| 0240 |[Search a 2D Matrix II](src/main/kotlin/g0201_0300/s0240_search_a_2d_matrix_ii)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search, Matrix, Divide_and_Conquer, Big_O_Time_O(n+m)_Space_O(1) | 460 | 66.08 +| 0275 |[H-Index II](src/main/kotlin/g0201_0300/s0275_h_index_ii)| Medium | Array, Binary_Search | 398 | 81.82 + +#### Day 9 + +| | | | | | +|-|-|-|-|-|- +| 1838 |[Frequency of the Most Frequent Element](src/main/kotlin/g1801_1900/s1838_frequency_of_the_most_frequent_element)| Medium | Array, Sorting, Greedy, Binary_Search, Prefix_Sum, Sliding_Window | 564 | 88.89 +| 0540 |[Single Element in a Sorted Array](src/main/kotlin/g0501_0600/s0540_single_element_in_a_sorted_array)| Medium | Array, Binary_Search | 274 | 86.67 + +#### Day 10 + +| | | | | | +|-|-|-|-|-|- +| 0222 |[Count Complete Tree Nodes](src/main/kotlin/g0201_0300/s0222_count_complete_tree_nodes)| ||| +| 1712 |[Ways to Split Array Into Three Subarrays](src/main/kotlin/g1701_1800/s1712_ways_to_split_array_into_three_subarrays)| Medium | Array, Binary_Search, Two_Pointers, Prefix_Sum | 486 | 100.00 + +#### Day 11 + +| | | | | | +|-|-|-|-|-|- +| 0826 |[Most Profit Assigning Work](src/main/kotlin/g0801_0900/s0826_most_profit_assigning_work)| Medium | Array, Sorting, Greedy, Binary_Search, Two_Pointers | 366 | 100.00 +| 0436 |[Find Right Interval](src/main/kotlin/g0401_0500/s0436_find_right_interval)| Medium | Array, Sorting, Binary_Search | 333 | 100.00 + +#### Day 12 + +| | | | | | +|-|-|-|-|-|- +| 0081 |[Search in Rotated Sorted Array II](src/main/kotlin/g0001_0100/s0081_search_in_rotated_sorted_array_ii)| Medium | Array, Binary_Search | 170 | 96.30 +| 0162 |[Find Peak Element](src/main/kotlin/g0101_0200/s0162_find_peak_element)| Medium | Top_Interview_Questions, Array, Binary_Search | 297 | 53.85 + +#### Day 13 + +| | | | | | +|-|-|-|-|-|- +| 0154 |[Find Minimum in Rotated Sorted Array II](src/main/kotlin/g0101_0200/s0154_find_minimum_in_rotated_sorted_array_ii)| Hard | Array, Binary_Search | 275 | 84.00 +| 0528 |[Random Pick with Weight](src/main/kotlin/g0501_0600/s0528_random_pick_with_weight)| Medium | Math, Binary_Search, Prefix_Sum, Randomized | 393 | 91.38 + +#### Day 14 + +| | | | | | +|-|-|-|-|-|- +| 1508 |[Range Sum of Sorted Subarray Sums](src/main/kotlin/g1501_1600/s1508_range_sum_of_sorted_subarray_sums)| Medium | Array, Sorting, Binary_Search, Two_Pointers | 378 | 66.67 +| 1574 |[Shortest Subarray to be Removed to Make Array Sorted](src/main/kotlin/g1501_1600/s1574_shortest_subarray_to_be_removed_to_make_array_sorted)| Medium | Array, Binary_Search, Two_Pointers, Stack, Monotonic_Stack | 477 | 50.00 + +#### Day 15 + +| | | | | | +|-|-|-|-|-|- +| 1292 |[Maximum Side Length of a Square with Sum Less than or Equal to Threshold](src/main/kotlin/g1201_1300/s1292_maximum_side_length_of_a_square_with_sum_less_than_or_equal_to_threshold)| Medium | Array, Binary_Search, Matrix, Prefix_Sum | 376 | 100.00 +| 1498 |[Number of Subsequences That Satisfy the Given Sum Condition](src/main/kotlin/g1401_1500/s1498_number_of_subsequences_that_satisfy_the_given_sum_condition)| Medium | Array, Sorting, Binary_Search, Two_Pointers | 487 | 97.89 + +#### Day 16 + +| | | | | | +|-|-|-|-|-|- +| 0981 |[Time Based Key-Value Store](src/main/kotlin/g0901_1000/s0981_time_based_key_value_store)| Medium | String, Hash_Table, Binary_Search, Design | 1011 | 65.56 +| 1300 |[Sum of Mutated Array Closest to Target](src/main/kotlin/g1201_1300/s1300_sum_of_mutated_array_closest_to_target)| Medium | Array, Sorting, Binary_Search | 217 | 100.00 + +#### Day 17 + +| | | | | | +|-|-|-|-|-|- +| 1802 |[Maximum Value at a Given Index in a Bounded Array](src/main/kotlin/g1801_1900/s1802_maximum_value_at_a_given_index_in_a_bounded_array)| Medium | Greedy, Binary_Search | 118 | 100.00 +| 1901 |[Find a Peak Element II](src/main/kotlin/g1901_2000/s1901_find_a_peak_element_ii)| Medium | Array, Binary_Search, Matrix, Divide_and_Conquer | 726 | 100.00 + +#### Day 18 + +| | | | | | +|-|-|-|-|-|- +| 1146 |[Snapshot Array](src/main/kotlin/g1101_1200/s1146_snapshot_array)| Medium | Array, Hash_Table, Binary_Search, Design | 1064 | 57.14 +| 1488 |[Avoid Flood in The City](src/main/kotlin/g1401_1500/s1488_avoid_flood_in_the_city)| Medium | Array, Hash_Table, Greedy, Binary_Search, Heap_Priority_Queue | 823 | 66.67 + +#### Day 19 + +| | | | | | +|-|-|-|-|-|- +| 1562 |[Find Latest Group of Size M](src/main/kotlin/g1501_1600/s1562_find_latest_group_of_size_m)| Medium | Array, Binary_Search, Simulation | 534 | 100.00 +| 1648 |[Sell Diminishing-Valued Colored Balls](src/main/kotlin/g1601_1700/s1648_sell_diminishing_valued_colored_balls)| Medium | Array, Math, Sorting, Greedy, Binary_Search, Heap_Priority_Queue | 509 | 100.00 + +#### Day 20 + +| | | | | | +|-|-|-|-|-|- +| 1201 |[Ugly Number III](src/main/kotlin/g1201_1300/s1201_ugly_number_iii)| Medium | Math, Binary_Search, Number_Theory | 136 | 100.00 +| 0911 |[Online Election](src/main/kotlin/g0901_1000/s0911_online_election)| Medium | Array, Hash_Table, Binary_Search, Design | 766 | 83.33 + +### Dynamic Programming I + +#### Day 1 + +| | | | | | +|-|-|-|-|-|- +| 0509 |[Fibonacci Number](src/main/kotlin/g0501_0600/s0509_fibonacci_number)| Easy | Dynamic_Programming, Math, Recursion, Memoization | 139 | 82.72 +| 1137 |[N-th Tribonacci Number](src/main/kotlin/g1101_1200/s1137_n_th_tribonacci_number)| Easy | Dynamic_Programming, Math, Memoization | 122 | 69.35 + +#### Day 2 + +| | | | | | +|-|-|-|-|-|- +| 0070 |[Climbing Stairs](src/main/kotlin/g0001_0100/s0070_climbing_stairs)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Memoization, Big_O_Time_O(n)_Space_O(n) | 124 | 71.98 +| 0746 |[Min Cost Climbing Stairs](src/main/kotlin/g0701_0800/s0746_min_cost_climbing_stairs)| Easy | Array, Dynamic_Programming | 171 | 96.76 + +#### Day 3 + +| | | | | | +|-|-|-|-|-|- +| 0198 |[House Robber](src/main/kotlin/g0101_0200/s0198_house_robber)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Big_O_Time_O(n)_Space_O(n) | 156 | 92.24 +| 0213 |[House Robber II](src/main/kotlin/g0201_0300/s0213_house_robber_ii)| Medium | Array, Dynamic_Programming | 257 | 59.62 +| 0740 |[Delete and Earn](src/main/kotlin/g0701_0800/s0740_delete_and_earn)| Medium | Array, Hash_Table, Dynamic_Programming | 192 | 100.00 + +#### Day 4 + +| | | | | | +|-|-|-|-|-|- +| 0055 |[Jump Game](src/main/kotlin/g0001_0100/s0055_jump_game)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Greedy, Big_O_Time_O(n)_Space_O(1) | 332 | 89.35 +| 0045 |[Jump Game II](src/main/kotlin/g0001_0100/s0045_jump_game_ii)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Greedy, Big_O_Time_O(n)_Space_O(1) | 208 | 93.37 + +#### Day 5 + +| | | | | | +|-|-|-|-|-|- +| 0053 |[Maximum Subarray](src/main/kotlin/g0001_0100/s0053_maximum_subarray)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer, Big_O_Time_O(n)_Space_O(1) | 510 | 78.81 +| 0918 |[Maximum Sum Circular Subarray](src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray)| Medium | Array, Dynamic_Programming, Divide_and_Conquer, Queue, Monotonic_Queue | 339 | 86.96 + +#### Day 6 + +| | | | | | +|-|-|-|-|-|- +| 0152 |[Maximum Product Subarray](src/main/kotlin/g0101_0200/s0152_maximum_product_subarray)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Big_O_Time_O(N)_Space_O(1) | 253 | 88.42 +| 1567 |[Maximum Length of Subarray With Positive Product](src/main/kotlin/g1501_1600/s1567_maximum_length_of_subarray_with_positive_product)| Medium | Array, Dynamic_Programming, Greedy | 468 | 33.33 + +#### Day 7 + +| | | | | | +|-|-|-|-|-|- +| 1014 |[Best Sightseeing Pair](src/main/kotlin/g1001_1100/s1014_best_sightseeing_pair)| Medium | Array, Dynamic_Programming | 336 | 66.67 +| 0121 |[Best Time to Buy and Sell Stock](src/main/kotlin/g0101_0200/s0121_best_time_to_buy_and_sell_stock)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Big_O_Time_O(N)_Space_O(1) | 609 | 94.06 +| 0122 |[Best Time to Buy and Sell Stock II](src/main/kotlin/g0101_0200/s0122_best_time_to_buy_and_sell_stock_ii)| Medium | Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 197 | 95.10 + +#### Day 8 + +| | | | | | +|-|-|-|-|-|- +| 0309 |[Best Time to Buy and Sell Stock with Cooldown](src/main/kotlin/g0301_0400/s0309_best_time_to_buy_and_sell_stock_with_cooldown)| Medium | Array, Dynamic_Programming | 272 | 73.33 +| 0714 |[Best Time to Buy and Sell Stock with Transaction Fee](src/main/kotlin/g0701_0800/s0714_best_time_to_buy_and_sell_stock_with_transaction_fee)| Medium | Array, Dynamic_Programming, Greedy | 417 | 90.91 + +#### Day 9 + +| | | | | | +|-|-|-|-|-|- +| 0139 |[Word Break](src/main/kotlin/g0101_0200/s0139_word_break)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Dynamic_Programming, Trie, Memoization, Big_O_Time_O(M+max\*N)_Space_O(M+N+max) | 197 | 87.17 +| 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, Big_O_Time_O(n)_Space_O(1) | 189 | 99.37 + +#### Day 10 + +| | | | | | +|-|-|-|-|-|- +| 0413 |[Arithmetic Slices](src/main/kotlin/g0401_0500/s0413_arithmetic_slices)| Medium | Array, Dynamic_Programming | 156 | 100.00 +| 0091 |[Decode Ways](src/main/kotlin/g0001_0100/s0091_decode_ways)| Medium | Top_Interview_Questions, String, Dynamic_Programming | 148 | 79.07 + +#### Day 11 + +| | | | | | +|-|-|-|-|-|- +| 0264 |[Ugly Number II](src/main/kotlin/g0201_0300/s0264_ugly_number_ii)| Medium | Hash_Table, Dynamic_Programming, Math, Heap_Priority_Queue | 182 | 95.45 +| 0096 |[Unique Binary Search Trees](src/main/kotlin/g0001_0100/s0096_unique_binary_search_trees)| Medium | Top_100_Liked_Questions, Dynamic_Programming, Math, Tree, Binary_Tree, Binary_Search_Tree, Big_O_Time_O(n)_Space_O(1) | 116 | 92.31 + +#### Day 12 + +| | | | | | +|-|-|-|-|-|- +| 0118 |[Pascal's Triangle](src/main/kotlin/g0101_0200/s0118_pascals_triangle)| Easy | Top_Interview_Questions, Array, Dynamic_Programming | 277 | 33.22 +| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming | 157 | 97.27 + +#### Day 13 + +| | | | | | +|-|-|-|-|-|- +| 0931 |[Minimum Falling Path Sum](src/main/kotlin/g0901_1000/s0931_minimum_falling_path_sum)| Medium | Array, Dynamic_Programming, Matrix | 201 | 84.21 +| 0120 |[Triangle](src/main/kotlin/g0101_0200/s0120_triangle)| Medium | Array, Dynamic_Programming | 194 | 97.87 + +#### Day 14 + +| | | | | | +|-|-|-|-|-|- +| 1314 |[Matrix Block Sum](src/main/kotlin/g1301_1400/s1314_matrix_block_sum)| Medium | Array, Matrix, Prefix_Sum | 235 | 100.00 +| 0304 |[Range Sum Query 2D - Immutable](src/main/kotlin/g0301_0400/s0304_range_sum_query_2d_immutable)| Medium | Array, Matrix, Design, Prefix_Sum | 1373 | 85.71 + +#### Day 15 + +| | | | | | +|-|-|-|-|-|- +| 0062 |[Unique Paths](src/main/kotlin/g0001_0100/s0062_unique_paths)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Combinatorics, Big_O_Time_O(m\*n)_Space_O(m\*n) | 118 | 94.65 +| 0063 |[Unique Paths II](src/main/kotlin/g0001_0100/s0063_unique_paths_ii)| Medium | Array, Dynamic_Programming, Matrix | 151 | 81.94 + +#### Day 16 + +| | | | | | +|-|-|-|-|-|- +| 0064 |[Minimum Path Sum](src/main/kotlin/g0001_0100/s0064_minimum_path_sum)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Matrix, Big_O_Time_O(m\*n)_Space_O(m\*n) | 164 | 100.00 +| 0221 |[Maximal Square](src/main/kotlin/g0201_0300/s0221_maximal_square)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Matrix, Big_O_Time_O(m\*n)_Space_O(m\*n) | 614 | 44.00 + +#### Day 17 + +| | | | | | +|-|-|-|-|-|- +| 0005 |[Longest Palindromic Substring](src/main/kotlin/g0001_0100/s0005_longest_palindromic_substring)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming, Big_O_Time_O(n)_Space_O(n) | 162 | 99.00 +| 0516 |[Longest Palindromic Subsequence](src/main/kotlin/g0501_0600/s0516_longest_palindromic_subsequence)| Medium | String, Dynamic_Programming | 243 | 87.50 + +#### Day 18 + +| | | | | | +|-|-|-|-|-|- +| 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search, Big_O_Time_O(n\*log_n)_Space_O(n) | 318 | 82.28 +| 0376 |[Wiggle Subsequence](src/main/kotlin/g0301_0400/s0376_wiggle_subsequence)| Medium | Array, Dynamic_Programming, Greedy | 162 | 88.89 + +#### Day 19 + +| | | | | | +|-|-|-|-|-|- +| 0392 |[Is Subsequence](src/main/kotlin/g0301_0400/s0392_is_subsequence)| Easy | String, Dynamic_Programming, Two_Pointers | 156 | 87.74 +| 1143 |[Longest Common Subsequence](src/main/kotlin/g1101_1200/s1143_longest_common_subsequence)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming, Big_O_Time_O(n\*m)_Space_O(n\*m) | 307 | 38.36 +| 0072 |[Edit Distance](src/main/kotlin/g0001_0100/s0072_edit_distance)| Hard | Top_100_Liked_Questions, String, Dynamic_Programming, Big_O_Time_O(n^2)_Space_O(n2) | 182 | 92.16 + +#### Day 20 + +| | | | | | +|-|-|-|-|-|- +| 0322 |[Coin Change](src/main/kotlin/g0301_0400/s0322_coin_change)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Breadth_First_Search, Big_O_Time_O(m\*n)_Space_O(amount) | 332 | 50.68 +| 0518 |[Coin Change II](src/main/kotlin/g0501_0600/s0518_coin_change_2)| Medium | Array, Dynamic_Programming | 139 | 100.00 + +#### Day 21 + +| | | | | | +|-|-|-|-|-|- +| 0377 |[Combination Sum IV](src/main/kotlin/g0301_0400/s0377_combination_sum_iv)| Medium | Array, Dynamic_Programming | 217 | 72.41 +| 0343 |[Integer Break](src/main/kotlin/g0301_0400/s0343_integer_break)| Medium | Dynamic_Programming, Math | 218 | 63.89 +| 0279 |[Perfect Squares](src/main/kotlin/g0201_0300/s0279_perfect_squares)| Medium | Top_Interview_Questions, Dynamic_Programming, Math, Breadth_First_Search | 176 | 98.80 + ## Algorithms | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- +| 3049 |[Earliest Second to Mark Indices II](src/main/kotlin/g3001_3100/s3049_earliest_second_to_mark_indices_ii)| Hard | Array, Greedy, Binary_Search, Heap_Priority_Queue | 220 | 100.00 +| 3048 |[Earliest Second to Mark Indices I](src/main/kotlin/g3001_3100/s3048_earliest_second_to_mark_indices_i)| Medium | Array, Binary_Search | 223 | 75.00 +| 3047 |[Find the Largest Area of Square Inside Two Rectangles](src/main/kotlin/g3001_3100/s3047_find_the_largest_area_of_square_inside_two_rectangles)| Medium | Array, Math, Geometry | 753 | 40.42 +| 3046 |[Split the Array](src/main/kotlin/g3001_3100/s3046_split_the_array)| Easy | Array, Hash_Table, Counting | 173 | 75.00 +| 3045 |[Count Prefix and Suffix Pairs II](src/main/kotlin/g3001_3100/s3045_count_prefix_and_suffix_pairs_ii)| Hard | Array, String, Trie, Hash_Function, String_Matching, Rolling_Hash | 344 | 100.00 +| 3044 |[Most Frequent Prime](src/main/kotlin/g3001_3100/s3044_most_frequent_prime)| Medium | Array, Hash_Table, Math, Matrix, Counting, Enumeration, Number_Theory | 198 | 100.00 +| 3043 |[Find the Length of the Longest Common Prefix](src/main/kotlin/g3001_3100/s3043_find_the_length_of_the_longest_common_prefix)| Medium | Array, String, Hash_Table, Trie | 623 | 76.32 +| 3042 |[Count Prefix and Suffix Pairs I](src/main/kotlin/g3001_3100/s3042_count_prefix_and_suffix_pairs_i)| Easy | Array, String, Trie, Hash_Function, String_Matching, Rolling_Hash | 160 | 96.72 +| 3041 |[Maximize Consecutive Elements in an Array After Modification](src/main/kotlin/g3001_3100/s3041_maximize_consecutive_elements_in_an_array_after_modification)| Hard | Array, Dynamic_Programming, Sorting | 551 | 100.00 +| 3040 |[Maximum Number of Operations With the Same Score II](src/main/kotlin/g3001_3100/s3040_maximum_number_of_operations_with_the_same_score_ii)| Medium | Array, Dynamic_Programming, Memoization | 179 | 100.00 +| 3039 |[Apply Operations to Make String Empty](src/main/kotlin/g3001_3100/s3039_apply_operations_to_make_string_empty)| Medium | Array, Hash_Table, Sorting, Counting | 335 | 97.73 +| 3038 |[Maximum Number of Operations With the Same Score I](src/main/kotlin/g3001_3100/s3038_maximum_number_of_operations_with_the_same_score_i)| Easy | Array, Simulation | 142 | 100.00 +| 3036 |[Number of Subarrays That Match a Pattern II](src/main/kotlin/g3001_3100/s3036_number_of_subarrays_that_match_a_pattern_ii)| Hard | Array, Hash_Function, String_Matching, Rolling_Hash | 768 | 83.33 +| 3035 |[Maximum Palindromes After Operations](src/main/kotlin/g3001_3100/s3035_maximum_palindromes_after_operations)| Medium | Array, String, Hash_Table, Sorting, Greedy, Counting | 214 | 100.00 +| 3034 |[Number of Subarrays That Match a Pattern I](src/main/kotlin/g3001_3100/s3034_number_of_subarrays_that_match_a_pattern_i)| Medium | Array, Hash_Function, String_Matching, Rolling_Hash | 225 | 38.09 +| 3033 |[Modify the Matrix](src/main/kotlin/g3001_3100/s3033_modify_the_matrix)| Easy | Array, Matrix | 270 | 41.94 +| 3031 |[Minimum Time to Revert Word to Initial State II](src/main/kotlin/g3001_3100/s3031_minimum_time_to_revert_word_to_initial_state_ii)| Hard | String, Hash_Function, String_Matching, Rolling_Hash | 328 | 52.94 +| 3030 |[Find the Grid of Region Average](src/main/kotlin/g3001_3100/s3030_find_the_grid_of_region_average)| Medium | Array, Matrix | 1250 | 86.96 +| 3029 |[Minimum Time to Revert Word to Initial State I](src/main/kotlin/g3001_3100/s3029_minimum_time_to_revert_word_to_initial_state_i)| Medium | String, Hash_Function, String_Matching, Rolling_Hash | 160 | 82.05 +| 3028 |[Ant on the Boundary](src/main/kotlin/g3001_3100/s3028_ant_on_the_boundary)| Easy | Array, Simulation, Prefix_Sum | 155 | 87.32 +| 3027 |[Find the Number of Ways to Place People II](src/main/kotlin/g3001_3100/s3027_find_the_number_of_ways_to_place_people_ii)| Hard | Array, Math, Sorting, Enumeration, Geometry | 477 | 78.95 +| 3026 |[Maximum Good Subarray Sum](src/main/kotlin/g3001_3100/s3026_maximum_good_subarray_sum)| Medium | Array, Hash_Table, Prefix_Sum | 756 | 71.43 +| 3025 |[Find the Number of Ways to Place People I](src/main/kotlin/g3001_3100/s3025_find_the_number_of_ways_to_place_people_i)| Medium | Array, Math, Sorting, Enumeration, Geometry | 252 | 44.12 +| 3024 |[Type of Triangle](src/main/kotlin/g3001_3100/s3024_type_of_triangle)| Easy | Array, Math, Sorting | 163 | 81.03 +| 3022 |[Minimize OR of Remaining Elements Using Operations](src/main/kotlin/g3001_3100/s3022_minimize_or_of_remaining_elements_using_operations)| Hard | Array, Greedy, Bit_Manipulation | 516 | 77.78 +| 3021 |[Alice and Bob Playing Flower Game](src/main/kotlin/g3001_3100/s3021_alice_and_bob_playing_flower_game)| Medium | Math | 141 | 43.24 +| 3020 |[Find the Maximum Number of Elements in Subset](src/main/kotlin/g3001_3100/s3020_find_the_maximum_number_of_elements_in_subset)| Medium | Array, Hash_Table, Enumeration | 626 | 82.22 +| 3019 |[Number of Changing Keys](src/main/kotlin/g3001_3100/s3019_number_of_changing_keys)| Easy | String, Breadth_First_Search, Graph, Prefix_Sum | 157 | 80.52 +| 3017 |[Count the Number of Houses at a Certain Distance II](src/main/kotlin/g3001_3100/s3017_count_the_number_of_houses_at_a_certain_distance_ii)| Hard | Breadth_First_Search, Graph, Prefix_Sum | 414 | 50.00 +| 3016 |[Minimum Number of Pushes to Type Word II](src/main/kotlin/g3001_3100/s3016_minimum_number_of_pushes_to_type_word_ii)| Medium | String, Hash_Table, Sorting, Greedy, Breadth_First_Search, Graph, Prefix_Sum, Counting | 290 | 92.00 +| 3015 |[Count the Number of Houses at a Certain Distance I](src/main/kotlin/g3001_3100/s3015_count_the_number_of_houses_at_a_certain_distance_i)| Medium | Breadth_First_Search, Graph, Prefix_Sum | 203 | 90.91 +| 3014 |[Minimum Number of Pushes to Type Word I](src/main/kotlin/g3001_3100/s3014_minimum_number_of_pushes_to_type_word_i)| Easy | String, Math, Greedy | 152 | 58.67 +| 3013 |[Divide an Array Into Subarrays With Minimum Cost II](src/main/kotlin/g3001_3100/s3013_divide_an_array_into_subarrays_with_minimum_cost_ii)| Hard | Array, Hash_Table, Heap_Priority_Queue, Sliding_Window | 1165 | 100.00 +| 3012 |[Minimize Length of Array Using Operations](src/main/kotlin/g3001_3100/s3012_minimize_length_of_array_using_operations)| Medium | Array, Math, Greedy, Number_Theory | 533 | 86.36 +| 3011 |[Find if Array Can Be Sorted](src/main/kotlin/g3001_3100/s3011_find_if_array_can_be_sorted)| Medium | Array, Sorting, Bit_Manipulation | 199 | 79.49 +| 3010 |[Divide an Array Into Subarrays With Minimum Cost I](src/main/kotlin/g3001_3100/s3010_divide_an_array_into_subarrays_with_minimum_cost_i)| Easy | Array, Sorting, Enumeration | 170 | 94.23 +| 3008 |[Find Beautiful Indices in the Given Array II](src/main/kotlin/g3001_3100/s3008_find_beautiful_indices_in_the_given_array_ii)| Hard | String, Binary_Search, Two_Pointers, Hash_Function, String_Matching, Rolling_Hash | 730 | 96.67 +| 3007 |[Maximum Number That Sum of the Prices Is Less Than or Equal to K](src/main/kotlin/g3001_3100/s3007_maximum_number_that_sum_of_the_prices_is_less_than_or_equal_to_k)| Medium | Dynamic_Programming, Binary_Search, Bit_Manipulation | 133 | 100.00 +| 3006 |[Find Beautiful Indices in the Given Array I](src/main/kotlin/g3001_3100/s3006_find_beautiful_indices_in_the_given_array_i)| Medium | String, Binary_Search, Two_Pointers, Hash_Function, String_Matching, Rolling_Hash | 287 | 94.92 +| 3005 |[Count Elements With Maximum Frequency](src/main/kotlin/g3001_3100/s3005_count_elements_with_maximum_frequency)| Easy | Array, Hash_Table, Counting | 168 | 80.00 +| 3003 |[Maximize the Number of Partitions After Operations](src/main/kotlin/g3001_3100/s3003_maximize_the_number_of_partitions_after_operations)| Hard | String, Dynamic_Programming, Bit_Manipulation, Bitmask | 147 | 100.00 +| 3002 |[Maximum Size of a Set After Removals](src/main/kotlin/g3001_3100/s3002_maximum_size_of_a_set_after_removals)| Medium | Array, Hash_Table, Greedy | 467 | 100.00 +| 3001 |[Minimum Moves to Capture The Queen](src/main/kotlin/g3001_3100/s3001_minimum_moves_to_capture_the_queen)| Medium | Array, Enumeration | 128 | 94.59 | 3000 |[Maximum Area of Longest Diagonal Rectangle](src/main/kotlin/g2901_3000/s3000_maximum_area_of_longest_diagonal_rectangle)| Easy | Array | 167 | 94.44 | 2999 |[Count the Number of Powerful Integers](src/main/kotlin/g2901_3000/s2999_count_the_number_of_powerful_integers)| Hard | String, Dynamic_Programming, Math | 163 | 100.00 | 2998 |[Minimum Number of Operations to Make X and Y Equal](src/main/kotlin/g2901_3000/s2998_minimum_number_of_operations_to_make_x_and_y_equal)| Medium | Dynamic_Programming, Breadth_First_Search, Memoization | 149 | 100.00 diff --git a/src/main/kotlin/g2801_2900/s2815_max_pair_sum_in_an_array/readme.md b/src/main/kotlin/g2801_2900/s2815_max_pair_sum_in_an_array/readme.md index fd384e13..234149b6 100644 --- a/src/main/kotlin/g2801_2900/s2815_max_pair_sum_in_an_array/readme.md +++ b/src/main/kotlin/g2801_2900/s2815_max_pair_sum_in_an_array/readme.md @@ -60,7 +60,7 @@ class Solution { continue } val sum = value.poll() + value.poll() - maxSum = max(maxSum.toDouble(), sum.toDouble()).toInt() + maxSum = max(maxSum, sum) } return maxSum } diff --git a/src/main/kotlin/g3001_3100/s3001_minimum_moves_to_capture_the_queen/readme.md b/src/main/kotlin/g3001_3100/s3001_minimum_moves_to_capture_the_queen/readme.md new file mode 100644 index 00000000..63a544aa --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3001_minimum_moves_to_capture_the_queen/readme.md @@ -0,0 +1,83 @@ +[![](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) + +## 3001\. Minimum Moves to Capture The Queen + +Medium + +There is a **1-indexed** `8 x 8` chessboard containing `3` pieces. + +You are given `6` integers `a`, `b`, `c`, `d`, `e`, and `f` where: + +* `(a, b)` denotes the position of the white rook. +* `(c, d)` denotes the position of the white bishop. +* `(e, f)` denotes the position of the black queen. + +Given that you can only move the white pieces, return _the **minimum** number of moves required to capture the black queen_. + +**Note** that: + +* Rooks can move any number of squares either vertically or horizontally, but cannot jump over other pieces. +* Bishops can move any number of squares diagonally, but cannot jump over other pieces. +* A rook or a bishop can capture the queen if it is located in a square that they can move to. +* The queen does not move. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/12/21/ex1.png) + +**Input:** a = 1, b = 1, c = 8, d = 8, e = 2, f = 3 + +**Output:** 2 + +**Explanation:** We can capture the black queen in two moves by moving the white rook to (1, 3) then to (2, 3). + +It is impossible to capture the black queen in less than two moves since it is not being attacked by any of the pieces at the beginning. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/12/21/ex2.png) + +**Input:** a = 5, b = 3, c = 3, d = 4, e = 5, f = 2 + +**Output:** 1 + +**Explanation:** We can capture the black queen in a single move by doing one of the following: + +- Move the white rook to (5, 2). + +- Move the white bishop to (5, 2). + +**Constraints:** + +* `1 <= a, b, c, d, e, f <= 8` +* No two pieces are on the same square. + +## Solution + +```kotlin +import kotlin.math.abs + +class Solution { + fun minMovesToCaptureTheQueen(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int): Int { + if (a == e || b == f) { + if (a == c && (d > b && d < f || d > f && d < b)) { + return 2 + } + if (b == d && (c > a && c < e || c > e && c < a)) { + return 2 + } + return 1 + } else if (abs(c - e) == abs(d - f)) { + if (abs(a - c) == abs(b - d) && + abs(e - a) == abs(f - b) && + (a > e && a < c || a > c && a < e) + ) { + return 2 + } + return 1 + } + return 2 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3002_maximum_size_of_a_set_after_removals/readme.md b/src/main/kotlin/g3001_3100/s3002_maximum_size_of_a_set_after_removals/readme.md new file mode 100644 index 00000000..6d3a834d --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3002_maximum_size_of_a_set_after_removals/readme.md @@ -0,0 +1,86 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 3002\. Maximum Size of a Set After Removals + +Medium + +You are given two **0-indexed** integer arrays `nums1` and `nums2` of even length `n`. + +You must remove `n / 2` elements from `nums1` and `n / 2` elements from `nums2`. After the removals, you insert the remaining elements of `nums1` and `nums2` into a set `s`. + +Return _the **maximum** possible size of the set_ `s`. + +**Example 1:** + +**Input:** nums1 = [1,2,1,2], nums2 = [1,1,1,1] + +**Output:** 2 + +**Explanation:** We remove two occurences of 1 from nums1 and nums2. After the removals, the arrays become equal to nums1 = [2,2] and nums2 = [1,1]. Therefore, s = {1,2}. + +It can be shown that 2 is the maximum possible size of the set s after the removals. + +**Example 2:** + +**Input:** nums1 = [1,2,3,4,5,6], nums2 = [2,3,2,3,2,3] + +**Output:** 5 + +**Explanation:** We remove 2, 3, and 6 from nums1, as well as 2 and two occurrences of 3 from nums2. After the removals, the arrays become equal to nums1 = [1,4,5] and nums2 = [2,3,2]. Therefore, s = {1,2,3,4,5}. + +It can be shown that 5 is the maximum possible size of the set s after the removals. + +**Example 3:** + +**Input:** nums1 = [1,1,2,2,3,3], nums2 = [4,4,5,5,6,6] + +**Output:** 6 + +**Explanation:** We remove 1, 2, and 3 from nums1, as well as 4, 5, and 6 from nums2. After the removals, the arrays become equal to nums1 = [1,2,3] and nums2 = [4,5,6]. Therefore, s = {1,2,3,4,5,6}. + +It can be shown that 6 is the maximum possible size of the set s after the removals. + +**Constraints:** + +* `n == nums1.length == nums2.length` +* 1 <= n <= 2 * 104 +* `n` is even. +* 1 <= nums1[i], nums2[i] <= 109 + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + fun maximumSetSize(nums1: IntArray, nums2: IntArray): Int { + val uniq1 = HashSet() + val uniq2 = HashSet() + for (i in nums1.indices) { + uniq1.add(nums1[i]) + uniq2.add(nums2[i]) + } + var common = 0 + if (uniq1.size <= uniq2.size) { + for (u in uniq1) { + if (uniq2.contains(u)) { + common++ + } + } + } else { + for (u in uniq2) { + if (uniq1.contains(u)) { + common++ + } + } + } + val half = nums1.size / 2 + val from1 = min(uniq1.size - common, half) + val from2 = min(uniq2.size - common, half) + val takeFromCommon1 = half - from1 + val takeFromCommon2 = half - from2 + return from1 + from2 + min(takeFromCommon1 + takeFromCommon2, common) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3003_maximize_the_number_of_partitions_after_operations/readme.md b/src/main/kotlin/g3001_3100/s3003_maximize_the_number_of_partitions_after_operations/readme.md new file mode 100644 index 00000000..07d462af --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3003_maximize_the_number_of_partitions_after_operations/readme.md @@ -0,0 +1,161 @@ +[![](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) + +## 3003\. Maximize the Number of Partitions After Operations + +Hard + +You are given a **0-indexed** string `s` and an integer `k`. + +You are to perform the following partitioning operations until `s` is **empty**: + +* Choose the **longest** **prefix** of `s` containing at most `k` **distinct** characters. +* **Delete** the prefix from `s` and increase the number of partitions by one. The remaining characters (if any) in `s` maintain their initial order. + +**Before** the operations, you are allowed to change **at most** **one** index in `s` to another lowercase English letter. + +Return _an integer denoting the **maximum** number of resulting partitions after the operations by optimally choosing at most one index to change._ + +**Example 1:** + +**Input:** s = "accca", k = 2 + +**Output:** 3 + +**Explanation:** In this example, to maximize the number of resulting partitions, s[2] can be changed to 'b'. s becomes "acbca". The operations can now be performed as follows until s becomes empty: +- Choose the longest prefix containing at most 2 distinct characters, "acbca". +- Delete the prefix, and s becomes "bca". The number of partitions is now 1. +- Choose the longest prefix containing at most 2 distinct characters, "bca". +- Delete the prefix, and s becomes "a". The number of partitions is now 2. +- Choose the longest prefix containing at most 2 distinct characters, "a". +- Delete the prefix, and s becomes empty. The number of partitions is now 3. + +Hence, the answer is 3. It can be shown that it is not possible to obtain more than 3 partitions. + +**Example 2:** + +**Input:** s = "aabaab", k = 3 + +**Output:** 1 + +**Explanation:** In this example, to maximize the number of resulting partitions we can leave s as it is. The operations can now be performed as follows until s becomes empty: +- Choose the longest prefix containing at most 3 distinct characters, "aabaab". +- Delete the prefix, and s becomes empty. The number of partitions becomes 1. + +Hence, the answer is 1. It can be shown that it is not possible to obtain more than 1 partition. + +**Example 3:** + +**Input:** s = "xxyz", k = 1 + +**Output:** 4 + +**Explanation:** In this example, to maximize the number of resulting partitions, s[1] can be changed to 'a'. s becomes "xayz". The operations can now be performed as follows until s becomes empty: +- Choose the longest prefix containing at most 1 distinct character, "xayz". +- Delete the prefix, and s becomes "ayz". The number of partitions is now 1. +- Choose the longest prefix containing at most 1 distinct character, "ayz". +- Delete the prefix, and s becomes "yz". The number of partitions is now 2. +- Choose the longest prefix containing at most 1 distinct character, "yz". +- Delete the prefix, and s becomes "z". The number of partitions is now 3. +- Choose the longest prefix containing at most 1 distinct character, "z". +- Delete the prefix, and s becomes empty. The number of partitions is now 4. + +Hence, the answer is 4. It can be shown that it is not possible to obtain more than 4 partitions. + +**Constraints:** + +* 1 <= s.length <= 104 +* `s` consists only of lowercase English letters. +* `1 <= k <= 26` + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun maxPartitionsAfterOperations(s: String, k: Int): Int { + if (k == ALPHABET_SIZE) { + return 1 + } + val n = s.length + val ansr = IntArray(n) + val usedr = IntArray(n) + var used = 0 + var cntUsed = 0 + var ans = 1 + for (i in n - 1 downTo 0) { + val ch = s[i].code - 'a'.code + if ((used and (1 shl ch)) == 0) { + if (cntUsed == k) { + cntUsed = 0 + used = 0 + ans++ + } + used = used or (1 shl ch) + cntUsed++ + } + ansr[i] = ans + usedr[i] = used + } + var ansl = 0 + ans = ansr[0] + var l = 0 + while (l < n) { + used = 0 + cntUsed = 0 + var usedBeforeLast = 0 + var usedTwiceBeforeLast = 0 + var last = -1 + var r = l + while (r < n) { + val ch = s[r].code - 'a'.code + if ((used and (1 shl ch)) == 0) { + if (cntUsed == k) { + break + } + usedBeforeLast = used + last = r + used = used or (1 shl ch) + cntUsed++ + } else if (cntUsed < k) { + usedTwiceBeforeLast = usedTwiceBeforeLast or (1 shl ch) + } + r++ + } + if (cntUsed == k) { + if (last - l > Integer.bitCount(usedBeforeLast)) { + ans = max(ans, (ansl + 1 + ansr[last])) + } + if (last + 1 < r) { + if (last + 2 >= n) { + ans = max(ans, (ansl + 1 + 1)) + } else { + if (Integer.bitCount(usedr[last + 2]) == k) { + val canUse = ((1 shl ALPHABET_SIZE) - 1) and used.inv() and usedr[last + 2].inv() + ans = if (canUse > 0) { + max(ans, (ansl + 1 + 1 + ansr[last + 2])) + } else { + max(ans, (ansl + 1 + ansr[last + 2])) + } + val l1 = s[last + 1].code - 'a'.code + if ((usedTwiceBeforeLast and (1 shl l1)) == 0) { + ans = max(ans, (ansl + 1 + ansr[last + 1])) + } + } else { + ans = max(ans, (ansl + 1 + ansr[last + 2])) + } + } + } + } + l = r + ansl++ + } + return ans + } + + companion object { + private const val ALPHABET_SIZE = 'z'.code - 'a'.code + 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3005_count_elements_with_maximum_frequency/readme.md b/src/main/kotlin/g3001_3100/s3005_count_elements_with_maximum_frequency/readme.md new file mode 100644 index 00000000..fb19cd08 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3005_count_elements_with_maximum_frequency/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) + +## 3005\. Count Elements With Maximum Frequency + +Easy + +You are given an array `nums` consisting of **positive** integers. + +Return _the **total frequencies** of elements in_ `nums` _such that those elements all have the **maximum** frequency_. + +The **frequency** of an element is the number of occurrences of that element in the array. + +**Example 1:** + +**Input:** nums = [1,2,2,3,1,4] + +**Output:** 4 + +**Explanation:** The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array. So the number of elements in the array with maximum frequency is 4. + +**Example 2:** + +**Input:** nums = [1,2,3,4,5] + +**Output:** 5 + +**Explanation:** All elements of the array have a frequency of 1 which is the maximum. So the number of elements in the array with maximum frequency is 5. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `1 <= nums[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun maxFrequencyElements(nums: IntArray): Int { + if (nums.size == 1) { + return 1 + } + val list: MutableList = ArrayList() + var co = 0 + var prev = 0 + for (num in nums) { + if (list.contains(num)) { + continue + } + list.add(num) + if (list.size == nums.size) { + break + } + var c = 0 + for (i in nums) { + if (num == i) { + c++ + } + } + if (c > 1) { + if (c > prev) { + co = c + prev = c + } else if (c == prev) { + co += c + } + } + } + if (co == 0) { + return nums.size + } + return co + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3006_find_beautiful_indices_in_the_given_array_i/readme.md b/src/main/kotlin/g3001_3100/s3006_find_beautiful_indices_in_the_given_array_i/readme.md new file mode 100644 index 00000000..b192dcfc --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3006_find_beautiful_indices_in_the_given_array_i/readme.md @@ -0,0 +1,153 @@ +[![](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) + +## 3006\. Find Beautiful Indices in the Given Array I + +Medium + +You are given a **0-indexed** string `s`, a string `a`, a string `b`, and an integer `k`. + +An index `i` is **beautiful** if: + +* `0 <= i <= s.length - a.length` +* `s[i..(i + a.length - 1)] == a` +* There exists an index `j` such that: + * `0 <= j <= s.length - b.length` + * `s[j..(j + b.length - 1)] == b` + * `|j - i| <= k` + +Return _the array that contains beautiful indices in **sorted order from smallest to largest**_. + +**Example 1:** + +**Input:** s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15 + +**Output:** [16,33] + +**Explanation:** There are 2 beautiful indices: [16,33]. +- The index 16 is beautiful as s[16..17] == "my" and there exists an index 4 with s[4..11] == "squirrel" and \|16 - 4\| <= 15. +- The index 33 is beautiful as s[33..34] == "my" and there exists an index 18 with s[18..25] == "squirrel" and \|33 - 18\| <= 15. Thus we return [16,33] as the result. + +**Example 2:** + +**Input:** s = "abcd", a = "a", b = "a", k = 4 + +**Output:** [0] + +**Explanation:** There is 1 beautiful index: [0]. +- The index 0 is beautiful as s[0..0] == "a" and there exists an index 0 with s[0..0] == "a" and \|0 - 0\| <= 4. Thus we return [0] as the result. + +**Constraints:** + +* 1 <= k <= s.length <= 105 +* `1 <= a.length, b.length <= 10` +* `s`, `a`, and `b` contain only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun beautifulIndices(s: String, a: String, b: String, q: Int): List { + val sc = s.toCharArray() + val ac = a.toCharArray() + val bc = b.toCharArray() + val lpsa = getLps(ac) + val lpsb = getLps(bc) + val comp = IntArray(sc.size) + val st = IntArray(sc.size) + var si = 0 + var k: Int + var mo = -bc.size + 1 + if (bc[0] == sc[0]) { + comp[0] = 1 + if (bc.size == 1) { + st[si++] = mo + } + } + for (i in 1 until comp.size) { + mo++ + if (sc[i] == bc[0]) { + comp[i] = 1 + } + k = comp[i - 1] + if (k == bc.size) { + k = lpsb[k - 1] + } + while (k > 0) { + if (bc[k] == sc[i]) { + comp[i] = k + 1 + break + } + k = lpsb[k - 1] + } + if (comp[i] == bc.size) { + st[si++] = mo + } + } + var sia = 0 + mo = -ac.size + 1 + val ret: MutableList = ArrayList() + if (si == 0) { + return ret + } + if (sc[0] == ac[0]) { + comp[0] = 1 + if (ac.size == 1 && st[0] <= q) { + ret.add(0) + } + } else { + comp[0] = 0 + } + for (i in 1 until comp.size) { + mo++ + if (sc[i] == ac[0]) { + comp[i] = 1 + } else { + comp[i] = 0 + } + k = comp[i - 1] + if (k == ac.size) { + k = lpsa[k - 1] + } + while (k > 0) { + if (ac[k] == sc[i]) { + comp[i] = k + 1 + break + } + k = lpsa[k - 1] + } + if (comp[i] == ac.size) { + while (sia < si && st[sia] + q < mo) { + sia++ + } + if (sia == si) { + break + } + if (mo >= st[sia] - q && mo <= st[sia] + q) { + ret.add(mo) + } + } + } + return ret + } + + private fun getLps(xc: CharArray): IntArray { + val r = IntArray(xc.size) + var k: Int + for (i in 1 until xc.size) { + if (xc[i] == xc[0]) { + r[i] = 1 + } + k = r[i - 1] + while (k > 0) { + if (xc[k] == xc[i]) { + r[i] = k + 1 + break + } + k = r[k - 1] + } + } + return r + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3007_maximum_number_that_sum_of_the_prices_is_less_than_or_equal_to_k/readme.md b/src/main/kotlin/g3001_3100/s3007_maximum_number_that_sum_of_the_prices_is_less_than_or_equal_to_k/readme.md new file mode 100644 index 00000000..1f5dbc15 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3007_maximum_number_that_sum_of_the_prices_is_less_than_or_equal_to_k/readme.md @@ -0,0 +1,83 @@ +[![](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) + +## 3007\. Maximum Number That Sum of the Prices Is Less Than or Equal to K + +Medium + +You are given an integer `k` and an integer `x`. + +Consider `s` is the **1-indexed** binary representation of an integer `num`. The **price** of a number `num` is the number of `i`'s such that `i % x == 0` and `s[i]` is a **set bit**. + +Return _the **greatest** integer_ `num` _such that the sum of **prices** of all numbers from_ `1` _to_ `num` _is less than or equal to_ `k`_._ + +**Note**: + +* In the binary representation of a number **set bit** is a bit of value `1`. +* The binary representation of a number will be indexed from right to left. For example, if `s == 11100`, `s[4] == 1` and `s[2] == 0`. + +**Example 1:** + +**Input:** k = 9, x = 1 + +**Output:** 6 + +**Explanation:** The numbers 1, 2, 3, 4, 5, and 6 can be written in binary representation as "1", "10", "11", "100", "101", and "110" respectively. Since x is equal to 1, the price of each number is the number of its set bits. + +The number of set bits in these numbers is 9. So the sum of the prices of the first 6 numbers is 9. So the answer is 6. + +**Example 2:** + +**Input:** k = 7, x = 2 + +**Output:** 9 + +**Explanation:** Since x is equal to 2, we should just check eventh bits. + +The second bit of binary representation of numbers 2 and 3 is a set bit. + +So the sum of their prices is 2. + +The second bit of binary representation of numbers 6 and 7 is a set bit. + +So the sum of their prices is 2. + +The fourth bit of binary representation of numbers 8 and 9 is a set bit but their second bit is not. So the sum of their prices is 2. + +Numbers 1, 4, and 5 don't have set bits in their eventh bits in their binary representation. So the sum of their prices is 0. + +The second and the fourth bit of the binary representation of the number 10 are a set bit. So its price is 2. + +The sum of the prices of the first 9 numbers is 6. + +Because the sum of the prices of the first 10 numbers is 8, the answer is 9. + +**Constraints:** + +* 1 <= k <= 1015 +* `1 <= x <= 8` + +## Solution + +```kotlin +class Solution { + private fun count(k: Long, bit: Int, x: Int): Long { + if (k < bit) { + return 0 + } + var n: Long = 1 + var bits = bit.toLong() + var p: Long = 1 + while (2 * bits + (if (p % x == 0L) n else 0) <= k) { + bits = 2 * bits + (if (p % x == 0L) n else 0) + n *= 2 + ++p + } + return n + count(k - bits, bit + (if (p % x == 0L) 1 else 0), x) + } + + fun findMaximumNumber(k: Long, x: Int): Long { + return count(k, 0, x) - 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3008_find_beautiful_indices_in_the_given_array_ii/readme.md b/src/main/kotlin/g3001_3100/s3008_find_beautiful_indices_in_the_given_array_ii/readme.md new file mode 100644 index 00000000..99de64fd --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3008_find_beautiful_indices_in_the_given_array_ii/readme.md @@ -0,0 +1,129 @@ +[![](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) + +## 3008\. Find Beautiful Indices in the Given Array II + +Hard + +You are given a **0-indexed** string `s`, a string `a`, a string `b`, and an integer `k`. + +An index `i` is **beautiful** if: + +* `0 <= i <= s.length - a.length` +* `s[i..(i + a.length - 1)] == a` +* There exists an index `j` such that: + * `0 <= j <= s.length - b.length` + * `s[j..(j + b.length - 1)] == b` + * `|j - i| <= k` + +Return _the array that contains beautiful indices in **sorted order from smallest to largest**_. + +**Example 1:** + +**Input:** s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15 + +**Output:** [16,33] + +**Explanation:** There are 2 beautiful indices: [16,33]. +- The index 16 is beautiful as s[16..17] == "my" and there exists an index 4 with s[4..11] == "squirrel" and \|16 - 4\| <= 15. +- The index 33 is beautiful as s[33..34] == "my" and there exists an index 18 with s[18..25] == "squirrel" and \|33 - 18\| <= 15. Thus we return [16,33] as the result. + +**Example 2:** + +**Input:** s = "abcd", a = "a", b = "a", k = 4 + +**Output:** [0] + +**Explanation:** There is 1 beautiful index: [0]. +- The index 0 is beautiful as s[0..0] == "a" and there exists an index 0 with s[0..0] == "a" and \|0 - 0\| <= 4. Thus we return [0] as the result. + +**Constraints:** + +* 1 <= k <= s.length <= 5 * 105 +* 1 <= a.length, b.length <= 5 * 105 +* `s`, `a`, and `b` contain only lowercase English letters. + +## Solution + +```kotlin +import java.util.ArrayDeque +import java.util.Deque +import kotlin.math.abs + +class Solution { + fun beautifulIndices(s: String, a: String, b: String, k: Int): List { + val lpsA = getLps(a) + val lpsB = getLps(b) + val ans: MutableList = ArrayList() + val matchesA: Deque = ArrayDeque() + val n = s.length + val aLen = a.length + val bLen = b.length + var i = 0 + var j = 0 + while (i < n) { + if (s[i] == a[j]) { + i++ + j++ + } else { + if (j == 0) { + i++ + } else { + j = lpsA[j - 1] + } + } + if (j == aLen) { + val aStart = i - aLen + matchesA.offer(aStart) + j = lpsA[aLen - 1] + } + } + j = 0 + i = j + while (i < n && matchesA.isNotEmpty()) { + if (s[i] == b[j]) { + i++ + j++ + } else { + if (j == 0) { + i++ + } else { + j = lpsB[j - 1] + } + } + if (j == bLen) { + val bStart = i - bLen + j = lpsB[bLen - 1] + + while (matchesA.isNotEmpty() && bStart - matchesA.peek() > k) { + matchesA.poll() + } + while (matchesA.isNotEmpty() && abs((matchesA.peek() - bStart).toDouble()) <= k) { + ans.add(matchesA.poll()) + } + } + } + return ans + } + + private fun getLps(s: String): IntArray { + val n = s.length + val lps = IntArray(n) + var i = 1 + var prevLps = 0 + while (i < n) { + if (s[i] == s[prevLps]) { + prevLps++ + lps[i++] = prevLps + } else { + if (prevLps == 0) { + lps[i++] = 0 + } else { + prevLps = lps[prevLps - 1] + } + } + } + return lps + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3010_divide_an_array_into_subarrays_with_minimum_cost_i/readme.md b/src/main/kotlin/g3001_3100/s3010_divide_an_array_into_subarrays_with_minimum_cost_i/readme.md new file mode 100644 index 00000000..bff5cea3 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3010_divide_an_array_into_subarrays_with_minimum_cost_i/readme.md @@ -0,0 +1,70 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 3010\. Divide an Array Into Subarrays With Minimum Cost I + +Easy + +You are given an array of integers `nums` of length `n`. + +The **cost** of an array is the value of its **first** element. For example, the cost of `[1,2,3]` is `1` while the cost of `[3,4,1]` is `3`. + +You need to divide `nums` into `3` **disjoint contiguous** subarrays. + +Return _the **minimum** possible **sum** of the cost of these subarrays_. + +**Example 1:** + +**Input:** nums = [1,2,3,12] + +**Output:** 6 + +**Explanation:** The best possible way to form 3 subarrays is: [1], [2], and [3,12] at a total cost of 1 + 2 + 3 = 6. The other possible ways to form 3 subarrays are: +- \[1], [2,3], and [12] at a total cost of 1 + 2 + 12 = 15. +- \[1,2], [3], and [12] at a total cost of 1 + 3 + 12 = 16. + +**Example 2:** + +**Input:** nums = [5,4,3] + +**Output:** 12 + +**Explanation:** The best possible way to form 3 subarrays is: [5], [4], and [3] at a total cost of 5 + 4 + 3 = 12. + +It can be shown that 12 is the minimum cost achievable. + +**Example 3:** + +**Input:** nums = [10,3,1,1] + +**Output:** 12 + +**Explanation:** The best possible way to form 3 subarrays is: [10,3], [1], and [1] at a total cost of 10 + 1 + 1 = 12. + +It can be shown that 12 is the minimum cost achievable. + +**Constraints:** + +* `3 <= n <= 50` +* `1 <= nums[i] <= 50` + +## Solution + +```kotlin +class Solution { + fun minimumCost(nums: IntArray): Int { + val first = nums[0] + var min = 51 + var secMin = 52 + for (i in 1 until nums.size) { + if (nums[i] < min) { + secMin = min + min = nums[i] + } else if (nums[i] < secMin) { + secMin = nums[i] + } + } + return first + min + secMin + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3011_find_if_array_can_be_sorted/readme.md b/src/main/kotlin/g3001_3100/s3011_find_if_array_can_be_sorted/readme.md new file mode 100644 index 00000000..5b41ff5f --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3011_find_if_array_can_be_sorted/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) + +## 3011\. Find if Array Can Be Sorted + +Medium + +You are given a **0-indexed** array of **positive** integers `nums`. + +In one **operation**, you can swap any two **adjacent** elements if they have the **same** number of set bits. You are allowed to do this operation **any** number of times (**including zero**). + +Return `true` _if you can sort the array, else return_ `false`. + +**Example 1:** + +**Input:** nums = [8,4,2,30,15] + +**Output:** true + +**Explanation:** Let's look at the binary representation of every element. The numbers 2, 4, and 8 have one set bit each with binary representation "10", "100", and "1000" respectively. The numbers 15 and 30 have four set bits each with binary representation "1111" and "11110". We can sort the array using 4 operations: +- Swap nums[0] with nums[1]. This operation is valid because 8 and 4 have one set bit each. The array becomes [4,8,2,30,15]. +- Swap nums[1] with nums[2]. This operation is valid because 8 and 2 have one set bit each. The array becomes [4,2,8,30,15]. +- Swap nums[0] with nums[1]. This operation is valid because 4 and 2 have one set bit each. The array becomes [2,4,8,30,15]. +- Swap nums[3] with nums[4]. This operation is valid because 30 and 15 have four set bits each. The array becomes [2,4,8,15,30]. + +The array has become sorted, hence we return true. Note that there may be other sequences of operations which also sort the array. + +**Example 2:** + +**Input:** nums = [1,2,3,4,5] + +**Output:** true + +**Explanation:** The array is already sorted, hence we return true. + +**Example 3:** + +**Input:** nums = [3,16,8,4,2] + +**Output:** false + +**Explanation:** It can be shown that it is not possible to sort the input array using any number of operations. + +**Constraints:** + +* `1 <= nums.length <= 100` +* 1 <= nums[i] <= 28 + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun canSortArray(nums: IntArray): Boolean { + var lastGroupMax = Int.MIN_VALUE + var max = nums[0] + var lastBit = Integer.bitCount(nums[0]) + for (i in 1 until nums.size) { + val bit = Integer.bitCount(nums[i]) + if (bit == lastBit) { + max = max(max, nums[i]) + } else { + lastGroupMax = max + max = nums[i] + lastBit = bit + } + if (nums[i] < lastGroupMax) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3012_minimize_length_of_array_using_operations/readme.md b/src/main/kotlin/g3001_3100/s3012_minimize_length_of_array_using_operations/readme.md new file mode 100644 index 00000000..45acd003 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3012_minimize_length_of_array_using_operations/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) + +## 3012\. Minimize Length of Array Using Operations + +Medium + +You are given a **0-indexed** integer array `nums` containing **positive** integers. + +Your task is to **minimize** the length of `nums` by performing the following operations **any** number of times (including zero): + +* Select **two** **distinct** indices `i` and `j` from `nums`, such that `nums[i] > 0` and `nums[j] > 0`. +* Insert the result of `nums[i] % nums[j]` at the end of `nums`. +* Delete the elements at indices `i` and `j` from `nums`. + +Return _an integer denoting the **minimum** **length** of_ `nums` _after performing the operation any number of times._ + +**Example 1:** + +**Input:** nums = [1,4,3,1] + +**Output:** 1 + +**Explanation:** One way to minimize the length of the array is as follows: + +Operation 1: Select indices 2 and 1, insert nums[2] % nums[1] at the end and it becomes [1,4,3,1,3], then delete elements at indices 2 and 1. nums becomes [1,1,3]. + +Operation 2: Select indices 1 and 2, insert nums[1] % nums[2] at the end and it becomes [1,1,3,1], then delete elements at indices 1 and 2. nums becomes [1,1]. + +Operation 3: Select indices 1 and 0, insert nums[1] % nums[0] at the end and it becomes [1,1,0], then delete elements at indices 1 and 0. nums becomes [0]. + +The length of nums cannot be reduced further. Hence, the answer is 1. It can be shown that 1 is the minimum achievable length. + +**Example 2:** + +**Input:** nums = [5,5,5,10,5] + +**Output:** 2 + +**Explanation:** One way to minimize the length of the array is as follows: + +Operation 1: Select indices 0 and 3, insert nums[0] % nums[3] at the end and it becomes [5,5,5,10,5,5], then delete elements at indices 0 and 3. nums becomes [5,5,5,5]. + +Operation 2: Select indices 2 and 3, insert nums[2] % nums[3] at the end and it becomes [5,5,5,5,0], then delete elements at indices 2 and 3. nums becomes [5,5,0]. + +Operation 3: Select indices 0 and 1, insert nums[0] % nums[1] at the end and it becomes [5,5,0,0], then delete elements at indices 0 and 1. nums becomes [0,0]. + +The length of nums cannot be reduced further. Hence, the answer is 2. It can be shown that 2 is the minimum achievable length. + +**Example 3:** + +**Input:** nums = [2,3,4] + +**Output:** 1 + +**Explanation:** One way to minimize the length of the array is as follows: + +Operation 1: Select indices 1 and 2, insert nums[1] % nums[2] at the end and it becomes [2,3,4,3], then delete elements at indices 1 and 2. nums becomes [2,3]. + +Operation 2: Select indices 1 and 0, insert nums[1] % nums[0] at the end and it becomes [2,3,1], then delete elements at indices 1 and 0. nums becomes [1]. The length of nums cannot be reduced further. Hence, the answer is 1. It can be shown that 1 is the minimum achievable length. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun minimumArrayLength(nums: IntArray): Int { + var min = nums[0] + var max = nums[0] + for (i in nums) { + if (i < min) { + min = i + } + if (i > max) { + max = i + } + } + val n = nums.size + if (n == 1) { + return 1 + } + if (max % min != 0) { + return 1 + } + var count = 0 + for (i in nums) { + if (i % min != 0 && i % min < min) { + return 1 + } + if (i == min) { + count++ + } + } + return (count + 1) / 2 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3013_divide_an_array_into_subarrays_with_minimum_cost_ii/readme.md b/src/main/kotlin/g3001_3100/s3013_divide_an_array_into_subarrays_with_minimum_cost_ii/readme.md new file mode 100644 index 00000000..b7616e6d --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3013_divide_an_array_into_subarrays_with_minimum_cost_ii/readme.md @@ -0,0 +1,124 @@ +[![](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) + +## 3013\. Divide an Array Into Subarrays With Minimum Cost II + +Hard + +You are given a **0-indexed** array of integers `nums` of length `n`, and two **positive** integers `k` and `dist`. + +The **cost** of an array is the value of its **first** element. For example, the cost of `[1,2,3]` is `1` while the cost of `[3,4,1]` is `3`. + +You need to divide `nums` into `k` **disjoint contiguous** subarrays, such that the difference between the starting index of the **second** subarray and the starting index of the `kth` subarray should be **less than or equal to** `dist`. In other words, if you divide `nums` into the subarrays nums[0..(i1 - 1)], nums[i1..(i2 - 1)], ..., nums[ik-1..(n - 1)], then ik-1 - i1 <= dist. + +Return _the **minimum** possible sum of the cost of these_ _subarrays_. + +**Example 1:** + +**Input:** nums = [1,3,2,6,4,2], k = 3, dist = 3 + +**Output:** 5 + +**Explanation:** The best possible way to divide nums into 3 subarrays is: [1,3], [2,6,4], and [2]. This choice is valid because ik-1 - i1 is 5 - 2 = 3 which is equal to dist. + +The total cost is nums[0] + nums[2] + nums[5] which is 1 + 2 + 2 = 5. + +It can be shown that there is no possible way to divide nums into 3 subarrays at a cost lower than 5. + +**Example 2:** + +**Input:** nums = [10,1,2,2,2,1], k = 4, dist = 3 + +**Output:** 15 + +**Explanation:** The best possible way to divide nums into 4 subarrays is: [10], [1], [2], and [2,2,1]. This choice is valid because ik-1 - i1 is 3 - 1 = 2 which is less than dist. + +The total cost is nums[0] + nums[1] + nums[2] + nums[3] which is 10 + 1 + 2 + 2 = 15. + +The division [10], [1], [2,2,2], and [1] is not valid, because the difference between ik-1 and i1 is 5 - 1 = 4, which is greater than dist. + +It can be shown that there is no possible way to divide nums into 4 subarrays at a cost lower than 15. + +**Example 3:** + +**Input:** nums = [10,8,18,9], k = 3, dist = 1 + +**Output:** 36 + +**Explanation:** The best possible way to divide nums into 4 subarrays is: [10], [8], and [18,9]. This choice is valid because ik-1 - i1 is 2 - 1 = 1 which is equal to dist. + +The total cost is nums[0] + nums[1] + nums[2] which is 10 + 8 + 18 = 36. + +The division [10], [8,18], and [9] is not valid, because the difference between ik-1 and i1 is 3 - 1 = 2, which is greater than dist. + +It can be shown that there is no possible way to divide nums into 3 subarrays at a cost lower than 36. + +**Constraints:** + +* 3 <= n <= 105 +* 1 <= nums[i] <= 109 +* `3 <= k <= n` +* `k - 2 <= dist <= n - 2` + +## Solution + +```kotlin +import java.util.TreeSet +import kotlin.math.min + +@Suppress("NAME_SHADOWING") +class Solution { + fun minimumCost(nums: IntArray, k: Int, dist: Int): Long { + var k = k + val comparator = + Comparator { i: Int?, j: Int? -> + if (nums[i!!] == nums[j!!] + ) Integer.compare(i, j) + else nums[i].compareTo(nums[j]) + } + val used = TreeSet(comparator) + val unused = TreeSet(comparator) + k-- + var sum: Long = 0 + val n = nums.size.toLong() + var answer = Long.MAX_VALUE + for (currentWindow in 1..min((dist.toLong() + 1), (n - 1)).toInt()) { + sum += nums[currentWindow].toLong() + used.add(currentWindow) + } + while (used.size > k) { + val largeValueIndex = used.pollLast() + sum -= nums[largeValueIndex!!].toLong() + unused.add(largeValueIndex) + } + answer = min(sum, answer) + var currentWindow = dist + 2 + var prevWindow = 1 + while (currentWindow < n + ) { + unused.add(currentWindow) + if (used.contains(prevWindow)) { + sum -= nums[prevWindow].toLong() + used.remove(prevWindow) + val smallValueIndex = unused.pollFirst() + sum += nums[smallValueIndex!!].toLong() + used.add(smallValueIndex) + } else { + unused.remove(prevWindow) + if (nums[used.last()!!] > nums[unused.first()!!]) { + val largeValueIndex = used.pollLast() + sum -= nums[largeValueIndex!!].toLong() + unused.add(largeValueIndex) + val smallValueIndex = unused.pollFirst() + sum += nums[smallValueIndex!!].toLong() + used.add(smallValueIndex) + } + } + answer = min(answer, sum) + currentWindow++ + prevWindow++ + } + return nums[0] + answer + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3014_minimum_number_of_pushes_to_type_word_i/readme.md b/src/main/kotlin/g3001_3100/s3014_minimum_number_of_pushes_to_type_word_i/readme.md new file mode 100644 index 00000000..0c380981 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3014_minimum_number_of_pushes_to_type_word_i/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) + +## 3014\. Minimum Number of Pushes to Type Word I + +Easy + +You are given a string `word` containing **distinct** lowercase English letters. + +Telephone keypads have keys mapped with **distinct** collections of lowercase English letters, which can be used to form words by pushing them. For example, the key `2` is mapped with `["a","b","c"]`, we need to push the key one time to type `"a"`, two times to type `"b"`, and three times to type `"c"` _._ + +It is allowed to remap the keys numbered `2` to `9` to **distinct** collections of letters. The keys can be remapped to **any** amount of letters, but each letter **must** be mapped to **exactly** one key. You need to find the **minimum** number of times the keys will be pushed to type the string `word`. + +Return _the **minimum** number of pushes needed to type_ `word` _after remapping the keys_. + +An example mapping of letters to keys on a telephone keypad is given below. Note that `1`, `*`, `#`, and `0` do **not** map to any letters. + +![](https://assets.leetcode.com/uploads/2023/12/26/keypaddesc.png) + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/12/26/keypadv1e1.png) + +**Input:** word = "abcde" + +**Output:** 5 + +**Explanation:** The remapped keypad given in the image provides the minimum cost. + +"a" -> one push on key 2 + +"b" -> one push on key 3 + +"c" -> one push on key 4 + +"d" -> one push on key 5 + +"e" -> one push on key 6 + +Total cost is 1 + 1 + 1 + 1 + 1 = 5. + +It can be shown that no other mapping can provide a lower cost. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/12/26/keypadv1e2.png) + +**Input:** word = "xycdefghij" + +**Output:** 12 + +**Explanation:** The remapped keypad given in the image provides the minimum cost. + +"x" -> one push on key 2 + +"y" -> two pushes on key 2 + +"c" -> one push on key 3 + +"d" -> two pushes on key 3 + +"e" -> one push on key 4 + +"f" -> one push on key 5 + +"g" -> one push on key 6 + +"h" -> one push on key 7 + +"i" -> one push on key 8 + +"j" -> one push on key 9 + +Total cost is 1 + 2 + 1 + 2 + 1 + 1 + 1 + 1 + 1 + 1 = 12. + +It can be shown that no other mapping can provide a lower cost. + +**Constraints:** + +* `1 <= word.length <= 26` +* `word` consists of lowercase English letters. +* All letters in `word` are distinct. + +## Solution + +```kotlin +class Solution { + fun minimumPushes(word: String): Int { + return if (word.length <= 8) { + word.length + } else { + var iteration = 1 + var len = word.length + var count = 0 + while (len > 0) { + if (len >= 8) { + count += 8 * iteration + len -= 8 + } else { + count += len * iteration + len = 0 + } + iteration++ + } + count + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3015_count_the_number_of_houses_at_a_certain_distance_i/readme.md b/src/main/kotlin/g3001_3100/s3015_count_the_number_of_houses_at_a_certain_distance_i/readme.md new file mode 100644 index 00000000..f30096fa --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3015_count_the_number_of_houses_at_a_certain_distance_i/readme.md @@ -0,0 +1,107 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 3015\. Count the Number of Houses at a Certain Distance I + +Medium + +You are given three **positive** integers `n`, `x`, and `y`. + +In a city, there exist houses numbered `1` to `n` connected by `n` streets. There is a street connecting the house numbered `i` with the house numbered `i + 1` for all `1 <= i <= n - 1` . An additional street connects the house numbered `x` with the house numbered `y`. + +For each `k`, such that `1 <= k <= n`, you need to find the number of **pairs of houses** (house1, house2) such that the **minimum** number of streets that need to be traveled to reach house2 from house1 is `k`. + +Return _a **1-indexed** array_ `result` _of length_ `n` _where_ `result[k]` _represents the **total** number of pairs of houses such that the **minimum** streets required to reach one house from the other is_ `k`. + +**Note** that `x` and `y` can be **equal**. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/12/20/example2.png) + +**Input:** n = 3, x = 1, y = 3 + +**Output:** [6,0,0] + +**Explanation:** Let's look at each pair of houses: +- For the pair (1, 2), we can go from house 1 to house 2 directly. +- For the pair (2, 1), we can go from house 2 to house 1 directly. +- For the pair (1, 3), we can go from house 1 to house 3 directly. +- For the pair (3, 1), we can go from house 3 to house 1 directly. +- For the pair (2, 3), we can go from house 2 to house 3 directly. +- For the pair (3, 2), we can go from house 3 to house 2 directly. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/12/20/example3.png) + +**Input:** n = 5, x = 2, y = 4 + +**Output:** [10,8,2,0,0] + +**Explanation:** For each distance k the pairs are: +- For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3), (4, 5), and (5, 4). +- For k == 2, the pairs are (1, 3), (3, 1), (1, 4), (4, 1), (2, 5), (5, 2), (3, 5), and (5, 3). +- For k == 3, the pairs are (1, 5), and (5, 1). +- For k == 4 and k == 5, there are no pairs. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2023/12/20/example5.png) + +**Input:** n = 4, x = 1, y = 1 + +**Output:** [6,4,2,0] + +**Explanation:** For each distance k the pairs are: +- For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), and (4, 3). +- For k == 2, the pairs are (1, 3), (3, 1), (2, 4), and (4, 2). +- For k == 3, the pairs are (1, 4), and (4, 1). +- For k == 4, there are no pairs. + +**Constraints:** + +* `2 <= n <= 100` +* `1 <= x, y <= n` + +## Solution + +```kotlin +import kotlin.math.abs + +@Suppress("NAME_SHADOWING") +class Solution { + fun countOfPairs(n: Int, x: Int, y: Int): IntArray { + var x = x + var y = y + val answer = IntArray(n) + var distance = n - 1 + var k = distance - 1 + while (distance > 0) { + answer[k] = (n - distance) * 2 + distance-- + k-- + } + if (x > y) { + val tmp = x + x = y + y = tmp + } + val skip = y - x + if (skip < 2) { + return answer + } + for (i in 1 until n) { + for (j in i + 1..n) { + val oldDistance = j - i + val newDistance = (abs((x - i)) + abs((y - j)) + 1) + if (newDistance < oldDistance) { + answer[oldDistance - 1] -= 2 + answer[newDistance - 1] += 2 + } + } + } + return answer + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3016_minimum_number_of_pushes_to_type_word_ii/readme.md b/src/main/kotlin/g3001_3100/s3016_minimum_number_of_pushes_to_type_word_ii/readme.md new file mode 100644 index 00000000..b5372e73 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3016_minimum_number_of_pushes_to_type_word_ii/readme.md @@ -0,0 +1,130 @@ +[![](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) + +## 3016\. Minimum Number of Pushes to Type Word II + +Medium + +You are given a string `word` containing lowercase English letters. + +Telephone keypads have keys mapped with **distinct** collections of lowercase English letters, which can be used to form words by pushing them. For example, the key `2` is mapped with `["a","b","c"]`, we need to push the key one time to type `"a"`, two times to type `"b"`, and three times to type `"c"` _._ + +It is allowed to remap the keys numbered `2` to `9` to **distinct** collections of letters. The keys can be remapped to **any** amount of letters, but each letter **must** be mapped to **exactly** one key. You need to find the **minimum** number of times the keys will be pushed to type the string `word`. + +Return _the **minimum** number of pushes needed to type_ `word` _after remapping the keys_. + +An example mapping of letters to keys on a telephone keypad is given below. Note that `1`, `*`, `#`, and `0` do **not** map to any letters. + +![](https://assets.leetcode.com/uploads/2023/12/26/keypaddesc.png) + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/12/26/keypadv1e1.png) + +**Input:** word = "abcde" + +**Output:** 5 + +**Explanation:** The remapped keypad given in the image provides the minimum cost. + +"a" -> one push on key 2 + +"b" -> one push on key 3 + +"c" -> one push on key 4 + +"d" -> one push on key 5 + +"e" -> one push on key 6 + +Total cost is 1 + 1 + 1 + 1 + 1 = 5. + +It can be shown that no other mapping can provide a lower cost. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/12/26/keypadv2e2.png) + +**Input:** word = "xyzxyzxyzxyz" + +**Output:** 12 + +**Explanation:** The remapped keypad given in the image provides the minimum cost. + +"x" -> one push on key 2 + +"y" -> one push on key 3 + +"z" -> one push on key 4 Total cost is 1 * 4 + 1 * 4 + 1 * 4 = 12 + +It can be shown that no other mapping can provide a lower cost. + +Note that the key 9 is not mapped to any letter: it is not necessary to map letters to every key, but to map all the letters. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2023/12/27/keypadv2.png) + +**Input:** word = "aabbccddeeffgghhiiiiii" + +**Output:** 24 + +**Explanation:** The remapped keypad given in the image provides the minimum cost. + +"a" -> one push on key 2 + +"b" -> one push on key 3 + +"c" -> one push on key 4 + +"d" -> one push on key 5 + +"e" -> one push on key 6 + +"f" -> one push on key 7 + +"g" -> one push on key 8 + +"h" -> two pushes on key 9 + +"i" -> one push on key 9 + +Total cost is 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 2 * 2 + 6 * 1 = 24. + +It can be shown that no other mapping can provide a lower cost. + +**Constraints:** + +* 1 <= word.length <= 105 +* `word` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun minimumPushes(word: String): Int { + val count = IntArray(26) + val l = word.length + for (i in 0 until l) { + ++count[word[i].code - 'a'.code] + } + var j = 8 + var result = 0 + while (true) { + var mi = 0 + for (i in 0..25) { + if (count[mi] < count[i]) { + mi = i + } + } + if (count[mi] == 0) { + break + } + result += (j / 8) * count[mi] + count[mi] = 0 + ++j + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3017_count_the_number_of_houses_at_a_certain_distance_ii/readme.md b/src/main/kotlin/g3001_3100/s3017_count_the_number_of_houses_at_a_certain_distance_ii/readme.md new file mode 100644 index 00000000..a37c7548 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3017_count_the_number_of_houses_at_a_certain_distance_ii/readme.md @@ -0,0 +1,135 @@ +[![](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) + +## 3017\. Count the Number of Houses at a Certain Distance II + +Hard + +You are given three **positive** integers `n`, `x`, and `y`. + +In a city, there exist houses numbered `1` to `n` connected by `n` streets. There is a street connecting the house numbered `i` with the house numbered `i + 1` for all `1 <= i <= n - 1` . An additional street connects the house numbered `x` with the house numbered `y`. + +For each `k`, such that `1 <= k <= n`, you need to find the number of **pairs of houses** (house1, house2) such that the **minimum** number of streets that need to be traveled to reach house2 from house1 is `k`. + +Return _a **1-indexed** array_ `result` _of length_ `n` _where_ `result[k]` _represents the **total** number of pairs of houses such that the **minimum** streets required to reach one house from the other is_ `k`. + +**Note** that `x` and `y` can be **equal**. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/12/20/example2.png) + +**Input:** n = 3, x = 1, y = 3 + +**Output:** [6,0,0] + +**Explanation:** Let's look at each pair of houses: +- For the pair (1, 2), we can go from house 1 to house 2 directly. +- For the pair (2, 1), we can go from house 2 to house 1 directly. +- For the pair (1, 3), we can go from house 1 to house 3 directly. +- For the pair (3, 1), we can go from house 3 to house 1 directly. +- For the pair (2, 3), we can go from house 2 to house 3 directly. +- For the pair (3, 2), we can go from house 3 to house 2 directly. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/12/20/example3.png) + +**Input:** n = 5, x = 2, y = 4 + +**Output:** [10,8,2,0,0] + +**Explanation:** For each distance k the pairs are: +- For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3), (4, 5), and (5, 4). +- For k == 2, the pairs are (1, 3), (3, 1), (1, 4), (4, 1), (2, 5), (5, 2), (3, 5), and (5, 3). +- For k == 3, the pairs are (1, 5), and (5, 1). +- For k == 4 and k == 5, there are no pairs. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2023/12/20/example5.png) + +**Input:** n = 4, x = 1, y = 1 + +**Output:** [6,4,2,0] + +**Explanation:** For each distance k the pairs are: +- For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), and (4, 3). +- For k == 2, the pairs are (1, 3), (3, 1), (2, 4), and (4, 2). +- For k == 3, the pairs are (1, 4), and (4, 1). +- For k == 4, there are no pairs. + +**Constraints:** + +* 2 <= n <= 105 +* `1 <= x, y <= n` + +## Solution + +```kotlin +import kotlin.math.max +import kotlin.math.min + +class Solution { + fun countOfPairs(n: Int, x: Int, y: Int): LongArray { + val result = LongArray(n) + val leftCount = (min(x, y) - 1) + val rightCount = (n - max(x, y)) + val circleCount = n - leftCount - rightCount + circleInternal(circleCount, result) + lineToCircle(leftCount, circleCount, result) + lineToCircle(rightCount, circleCount, result) + lineToLine(leftCount, rightCount, if (x == y) 1 else 2, result) + lineInternal(leftCount, result) + lineInternal(rightCount, result) + return result + } + + private fun lineToCircle(lineCount: Int, circleCount: Int, curRes: LongArray) { + val circleLen = circleCount / 2 + 1 + var curModifier = 0 + for (i in 1 until circleLen + lineCount) { + if (i <= min(lineCount, circleLen)) { + curModifier += 4 + } else if (i > max(lineCount, circleLen)) { + curModifier -= 4 + } + curRes[i - 1] += curModifier.toLong() + if (i <= lineCount) { + curRes[i - 1] = curRes[i - 1] - 2 + } + if (i >= circleLen && circleCount % 2 == 0) { + curRes[i - 1] = curRes[i - 1] - 2 + } + } + } + + private fun lineToLine(lineCount1: Int, lineCount2: Int, initialDis: Int, curRes: LongArray) { + var curModifier = 0 + for (i in 1 until lineCount1 + lineCount2) { + if (i <= min(lineCount1, lineCount2)) { + curModifier += 2 + } else if (i > max(lineCount1, lineCount2)) { + curModifier -= 2 + } + curRes[i - 1 + initialDis] += curModifier.toLong() + } + } + + private fun lineInternal(lineCount: Int, curRes: LongArray) { + for (i in 1 until lineCount) { + curRes[i - 1] += (lineCount - i) * 2L + } + } + + private fun circleInternal(circleCount: Int, curRes: LongArray) { + for (i in 0 until circleCount / 2) { + if (circleCount % 2 == 0 && i + 1 == circleCount / 2) { + curRes[i] += circleCount.toLong() + } else { + curRes[i] += circleCount * 2L + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3019_number_of_changing_keys/readme.md b/src/main/kotlin/g3001_3100/s3019_number_of_changing_keys/readme.md new file mode 100644 index 00000000..a6eab4e2 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3019_number_of_changing_keys/readme.md @@ -0,0 +1,64 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 3019\. Number of Changing Keys + +Easy + +You are given a **0-indexed** string `s` typed by a user. Changing a key is defined as using a key different from the last used key. For example, `s = "ab"` has a change of a key while `s = "bBBb"` does not have any. + +Return _the number of times the user had to change the key._ + +**Note:** Modifiers like `shift` or `caps lock` won't be counted in changing the key that is if a user typed the letter `'a'` and then the letter `'A'` then it will not be considered as a changing of key. + +**Example 1:** + +**Input:** s = "aAbBcC" + +**Output:** 2 + +**Explanation:** + +From s[0] = 'a' to s[1] = 'A', there is no change of key as caps lock or shift is not counted. + +From s[1] = 'A' to s[2] = 'b', there is a change of key. + +From s[2] = 'b' to s[3] = 'B', there is no change of key as caps lock or shift is not counted. + +From s[3] = 'B' to s[4] = 'c', there is a change of key. + +From s[4] = 'c' to s[5] = 'C', there is no change of key as caps lock or shift is not counted. + +**Example 2:** + +**Input:** s = "AaAaAaaA" + +**Output:** 0 + +**Explanation:** There is no change of key since only the letters 'a' and 'A' are pressed which does not require change of key. + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` consists of only upper case and lower case English letters. + +## Solution + +```kotlin +import java.util.Locale + +@Suppress("NAME_SHADOWING") +class Solution { + fun countKeyChanges(s: String): Int { + var s = s + s = s.lowercase(Locale.getDefault()) + var count = 0 + for (i in 0 until s.length - 1) { + if (s[i] != s[i + 1]) { + count++ + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3020_find_the_maximum_number_of_elements_in_subset/readme.md b/src/main/kotlin/g3001_3100/s3020_find_the_maximum_number_of_elements_in_subset/readme.md new file mode 100644 index 00000000..741d2c56 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3020_find_the_maximum_number_of_elements_in_subset/readme.md @@ -0,0 +1,83 @@ +[![](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) + +## 3020\. Find the Maximum Number of Elements in Subset + +Medium + +You are given an array of **positive** integers `nums`. + +You need to select a subset of `nums` which satisfies the following condition: + +* You can place the selected elements in a **0-indexed** array such that it follows the pattern: [x, x2, x4, ..., xk/2, xk, xk/2, ..., x4, x2, x] (**Note** that `k` can be be any **non-negative** power of `2`). For example, `[2, 4, 16, 4, 2]` and `[3, 9, 3]` follow the pattern while `[2, 4, 8, 4, 2]` does not. + +Return _the **maximum** number of elements in a subset that satisfies these conditions._ + +**Example 1:** + +**Input:** nums = [5,4,1,2,2] + +**Output:** 3 + +**Explanation:** We can select the subset {4,2,2}, which can be placed in the array as [2,4,2] which follows the pattern and 22 == 4. Hence the answer is 3. + +**Example 2:** + +**Input:** nums = [1,3,2,4] + +**Output:** 1 + +**Explanation:** We can select the subset {1}, which can be placed in the array as [1] which follows the pattern. Hence the answer is 1. Note that we could have also selected the subsets {2}, {3}, or {4}, there may be multiple subsets which provide the same answer. + +**Constraints:** + +* 2 <= nums.length <= 105 +* 1 <= nums[i] <= 109 + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun maximumLength(nums: IntArray): Int { + return withHashMap(nums) + } + + private fun withHashMap(nums: IntArray): Int { + val map: MutableMap = HashMap() + for (i in nums) { + map[i] = map.getOrDefault(i, 0) + 1 + } + var ans = 0 + if (map.containsKey(1)) { + ans = if (map[1]!! % 2 == 0) { + map[1]!! - 1 + } else { + map[1]!! + } + } + for (key in map.keys) { + if (key == 1) { + continue + } + val len = findSeries(map, key) + ans = max(ans, len) + } + return ans + } + + private fun findSeries(map: Map, key: Int): Int { + val sqr = key * key + return if (map.containsKey(sqr)) { + if (map[key]!! >= 2) { + 2 + findSeries(map, sqr) + } else { + 1 + } + } else { + 1 + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3021_alice_and_bob_playing_flower_game/readme.md b/src/main/kotlin/g3001_3100/s3021_alice_and_bob_playing_flower_game/readme.md new file mode 100644 index 00000000..ff783749 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3021_alice_and_bob_playing_flower_game/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) + +## 3021\. Alice and Bob Playing Flower Game + +Medium + +Alice and Bob are playing a turn-based game on a circular field surrounded by flowers. The circle represents the field, and there are `x` flowers in the clockwise direction between Alice and Bob, and `y` flowers in the anti-clockwise direction between them. + +The game proceeds as follows: + +1. Alice takes the first turn. +2. In each turn, a player must choose either the clockwise or anti-clockwise direction and pick one flower from that side. +3. At the end of the turn, if there are no flowers left at all, the **current** player captures their opponent and wins the game. + +Given two integers, `n` and `m`, the task is to compute the number of possible pairs `(x, y)` that satisfy the conditions: + +* Alice must win the game according to the described rules. +* The number of flowers `x` in the clockwise direction must be in the range `[1,n]`. +* The number of flowers `y` in the anti-clockwise direction must be in the range `[1,m]`. + +Return _the number of possible pairs_ `(x, y)` _that satisfy the conditions mentioned in the statement_. + +**Example 1:** + +**Input:** n = 3, m = 2 + +**Output:** 3 + +**Explanation:** The following pairs satisfy conditions described in the statement: (1,2), (3,2), (2,1). + +**Example 2:** + +**Input:** n = 1, m = 1 + +**Output:** 0 + +**Explanation:** No pairs satisfy the conditions described in the statement. + +**Constraints:** + +* 1 <= n, m <= 105 + +## Solution + +```kotlin +class Solution { + fun flowerGame(n: Int, m: Int): Long { + val nEven = n.toLong() / 2 + val nOdd = n - nEven + val mEven = m.toLong() / 2 + val mOdd = m - mEven + return nEven * mOdd + nOdd * mEven + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3022_minimize_or_of_remaining_elements_using_operations/readme.md b/src/main/kotlin/g3001_3100/s3022_minimize_or_of_remaining_elements_using_operations/readme.md new file mode 100644 index 00000000..a79c2815 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3022_minimize_or_of_remaining_elements_using_operations/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) + +## 3022\. Minimize OR of Remaining Elements Using Operations + +Hard + +You are given a **0-indexed** integer array `nums` and an integer `k`. + +In one operation, you can pick any index `i` of `nums` such that `0 <= i < nums.length - 1` and replace `nums[i]` and `nums[i + 1]` with a single occurrence of `nums[i] & nums[i + 1]`, where `&` represents the bitwise `AND` operator. + +Return _the **minimum** possible value of the bitwise_ `OR` _of the remaining elements of_ `nums` _after applying **at most**_ `k` _operations_. + +**Example 1:** + +**Input:** nums = [3,5,3,2,7], k = 2 + +**Output:** 3 + +**Explanation:** Let's do the following operations: +1. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [1,3,2,7]. +2. Replace nums[2] and nums[3] with (nums[2] & nums[3]) so that nums becomes equal to [1,3,2]. + +The bitwise-or of the final array is 3. + +It can be shown that 3 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations. + +**Example 2:** + +**Input:** nums = [7,3,15,14,2,8], k = 4 + +**Output:** 2 + +**Explanation:** Let's do the following operations: +1. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [3,15,14,2,8]. +2. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [3,14,2,8]. +3. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [2,2,8]. +4. Replace nums[1] and nums[2] with (nums[1] & nums[2]) so that nums becomes equal to [2,0]. + +The bitwise-or of the final array is 2. + +It can be shown that 2 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations. + +**Example 3:** + +**Input:** nums = [10,7,10,3,9,14,9,4], k = 1 + +**Output:** 15 + +**Explanation:** Without applying any operations, the bitwise-or of nums is 15. It can be shown that 15 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 0 <= nums[i] < 230 +* `0 <= k < nums.length` + +## Solution + +```kotlin +class Solution { + fun minOrAfterOperations(nums: IntArray, k: Int): Int { + var ans = 0 + var mask = 0 + for (j in 30 downTo 0) { + mask = mask or (1 shl j) + var consecutiveAnd = mask + var mergeCount = 0 + for (i in nums) { + consecutiveAnd = consecutiveAnd and i + if ((consecutiveAnd or ans) != ans) { + mergeCount++ + } else { + consecutiveAnd = mask + } + } + if (mergeCount > k) { + ans = ans or (1 shl j) + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3024_type_of_triangle/readme.md b/src/main/kotlin/g3001_3100/s3024_type_of_triangle/readme.md new file mode 100644 index 00000000..1821e51c --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3024_type_of_triangle/readme.md @@ -0,0 +1,64 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 3024\. Type of Triangle + +Easy + +You are given a **0-indexed** integer array `nums` of size `3` which can form the sides of a triangle. + +* A triangle is called **equilateral** if it has all sides of equal length. +* A triangle is called **isosceles** if it has exactly two sides of equal length. +* A triangle is called **scalene** if all its sides are of different lengths. + +Return _a string representing_ _the type of triangle that can be formed_ _or_ `"none"` _if it **cannot** form a triangle._ + +**Example 1:** + +**Input:** nums = [3,3,3] + +**Output:** "equilateral" + +**Explanation:** Since all the sides are of equal length, therefore, it will form an equilateral triangle. + +**Example 2:** + +**Input:** nums = [3,4,5] + +**Output:** "scalene" + +**Explanation:** + +nums[0] + nums[1] = 3 + 4 = 7, which is greater than nums[2] = 5. + +nums[0] + nums[2] = 3 + 5 = 8, which is greater than nums[1] = 4. + +nums[1] + nums[2] = 4 + 5 = 9, which is greater than nums[0] = 3. + +Since the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle. + +As all the sides are of different lengths, it will form a scalene triangle. + +**Constraints:** + +* `nums.length == 3` +* `1 <= nums[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun triangleType(nums: IntArray): String { + if (nums[0] + nums[1] > nums[2] && nums[1] + nums[2] > nums[0] && nums[2] + nums[0] > nums[1]) { + return if (nums[0] == nums[1] && nums[1] == nums[2]) { + "equilateral" + } else if (nums[0] == nums[1] || nums[0] == nums[2] || nums[2] == nums[1]) { + "isosceles" + } else { + "scalene" + } + } + return "none" + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3025_find_the_number_of_ways_to_place_people_i/readme.md b/src/main/kotlin/g3001_3100/s3025_find_the_number_of_ways_to_place_people_i/readme.md new file mode 100644 index 00000000..840300af --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3025_find_the_number_of_ways_to_place_people_i/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) + +## 3025\. Find the Number of Ways to Place People I + +Medium + +You are given a 2D array `points` of size `n x 2` representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]. + +We define the **right** direction as positive x-axis (**increasing x-coordinate**) and the **left** direction as negative x-axis (**decreasing x-coordinate**). Similarly, we define the **up** direction as positive y-axis (**increasing y-coordinate**) and the **down** direction as negative y-axis (**decreasing y-coordinate**) + +You have to place `n` people, including Alice and Bob, at these points such that there is **exactly one** person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice's position as the **upper left corner** and Bob's position as the **lower right corner** of the fence (**Note** that the fence **might not** enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either **inside** the fence or **on** the fence, Alice will be sad. + +Return _the number of **pairs of points** where you can place Alice and Bob, such that Alice **does not** become sad on building the fence_. + +**Note** that Alice can only build a fence with Alice's position as the upper left corner, and Bob's position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners `(1, 1)`, `(1, 3)`, `(3, 1)`, and `(3, 3)`, because: + +* With Alice at `(3, 3)` and Bob at `(1, 1)`, Alice's position is not the upper left corner and Bob's position is not the lower right corner of the fence. +* With Alice at `(1, 3)` and Bob at `(1, 1)`, Bob's position is not the lower right corner of the fence. + +![](https://assets.leetcode.com/uploads/2024/01/04/example0alicebob-1.png) + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2024/01/04/example1alicebob.png) + +**Input:** points = \[\[1,1],[2,2],[3,3]] + +**Output:** 0 + +**Explanation:** There is no way to place Alice and Bob such that Alice can build a fence with Alice's position as the upper left corner and Bob's position as the lower right corner. Hence we return 0. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2024/02/04/example2alicebob.png) + +**Input:** points = \[\[6,2],[4,4],[2,6]] + +**Output:** 2 + +**Explanation:** There are two ways to place Alice and Bob such that Alice will not be sad: + +- Place Alice at (4, 4) and Bob at (6, 2). + +- Place Alice at (2, 6) and Bob at (4, 4). + +You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2024/02/04/example4alicebob.png) + +**Input:** points = \[\[3,1],[1,3],[1,1]] + +**Output:** 2 + +**Explanation:** There are two ways to place Alice and Bob such that Alice will not be sad: + +- Place Alice at (1, 1) and Bob at (3, 1). + +- Place Alice at (1, 3) and Bob at (1, 1). + +You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence. + +Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid. + +**Constraints:** + +* `2 <= n <= 50` +* `points[i].length == 2` +* `0 <= points[i][0], points[i][1] <= 50` +* All `points[i]` are distinct. + +## Solution + +```kotlin +class Solution { + fun numberOfPairs(points: Array): Int { + points.sortWith { a: IntArray, b: IntArray -> if (a[0] == b[0]) b[1] - a[1] else a[0] - b[0] } + var cnt = 0 + for (i in points.indices) { + var bot = Int.MIN_VALUE + var top = points[i][1] + for (j in i + 1 until points.size) { + val y1 = points[j][1] + if (y1 <= top && y1 > bot) { + cnt++ + bot = y1 + if (y1 == top) { + top-- + } + } + } + } + return cnt + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3026_maximum_good_subarray_sum/readme.md b/src/main/kotlin/g3001_3100/s3026_maximum_good_subarray_sum/readme.md new file mode 100644 index 00000000..175a923a --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3026_maximum_good_subarray_sum/readme.md @@ -0,0 +1,89 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 3026\. Maximum Good Subarray Sum + +Medium + +You are given an array `nums` of length `n` and a **positive** integer `k`. + +A subarray of `nums` is called **good** if the **absolute difference** between its first and last element is **exactly** `k`, in other words, the subarray `nums[i..j]` is good if `|nums[i] - nums[j]| == k`. + +Return _the **maximum** sum of a **good** subarray of_ `nums`. _If there are no good subarrays__, return_ `0`. + +**Example 1:** + +**Input:** nums = [1,2,3,4,5,6], k = 1 + +**Output:** 11 + +**Explanation:** The absolute difference between the first and last element must be 1 for a good subarray. All the good subarrays are: [1,2], [2,3], [3,4], [4,5], and [5,6]. The maximum subarray sum is 11 for the subarray [5,6]. + +**Example 2:** + +**Input:** nums = [-1,3,2,4,5], k = 3 + +**Output:** 11 + +**Explanation:** The absolute difference between the first and last element must be 3 for a good subarray. All the good subarrays are: [-1,3,2], and [2,4,5]. The maximum subarray sum is 11 for the subarray [2,4,5]. + +**Example 3:** + +**Input:** nums = [-1,-2,-3,-4], k = 2 + +**Output:** -6 + +**Explanation:** The absolute difference between the first and last element must be 2 for a good subarray. All the good subarrays are: [-1,-2,-3], and [-2,-3,-4]. The maximum subarray sum is -6 for the subarray [-1,-2,-3]. + +**Constraints:** + +* 2 <= nums.length <= 105 +* -109 <= nums[i] <= 109 +* 1 <= k <= 109 + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun maximumSubarraySum(input: IntArray, targetDifference: Int): Long { + val valueToMinPrefixSum: MutableMap = HashMap() + var prefixSum: Long = 0 + var maxSubarraySum = Long.MIN_VALUE + for (value in input) { + if (valueToMinPrefixSum.containsKey(value + targetDifference)) { + maxSubarraySum = max( + maxSubarraySum, + ( + prefixSum + + value - + valueToMinPrefixSum[value + targetDifference]!! + ) + ) + } + if (valueToMinPrefixSum.containsKey(value - targetDifference)) { + maxSubarraySum = max( + maxSubarraySum, + ( + prefixSum + + value - + valueToMinPrefixSum[value - targetDifference]!! + ) + ) + } + if (!valueToMinPrefixSum.containsKey(value) || + valueToMinPrefixSum[value]!! > prefixSum + ) { + valueToMinPrefixSum[value] = prefixSum + } + prefixSum += value.toLong() + } + return if (maxSubarraySum != Long.MIN_VALUE) maxSubarraySum else NO_GOOD_SUBARRAYS.toLong() + } + + companion object { + private const val NO_GOOD_SUBARRAYS = 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3027_find_the_number_of_ways_to_place_people_ii/readme.md b/src/main/kotlin/g3001_3100/s3027_find_the_number_of_ways_to_place_people_ii/readme.md new file mode 100644 index 00000000..e813c9be --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3027_find_the_number_of_ways_to_place_people_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) + +## 3027\. Find the Number of Ways to Place People II + +Hard + +You are given a 2D array `points` of size `n x 2` representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]. + +We define the **right** direction as positive x-axis (**increasing x-coordinate**) and the **left** direction as negative x-axis (**decreasing x-coordinate**). Similarly, we define the **up** direction as positive y-axis (**increasing y-coordinate**) and the **down** direction as negative y-axis (**decreasing y-coordinate**) + +You have to place `n` people, including Alice and Bob, at these points such that there is **exactly one** person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice's position as the **upper left corner** and Bob's position as the **lower right corner** of the fence (**Note** that the fence **might not** enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either **inside** the fence or **on** the fence, Alice will be sad. + +Return _the number of **pairs of points** where you can place Alice and Bob, such that Alice **does not** become sad on building the fence_. + +**Note** that Alice can only build a fence with Alice's position as the upper left corner, and Bob's position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners `(1, 1)`, `(1, 3)`, `(3, 1)`, and `(3, 3)`, because: + +* With Alice at `(3, 3)` and Bob at `(1, 1)`, Alice's position is not the upper left corner and Bob's position is not the lower right corner of the fence. +* With Alice at `(1, 3)` and Bob at `(1, 1)`, Bob's position is not the lower right corner of the fence. + +![](https://assets.leetcode.com/uploads/2024/01/04/example0alicebob-1.png) + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2024/01/04/example1alicebob.png) + +**Input:** points = \[\[1,1],[2,2],[3,3]] + +**Output:** 0 + +**Explanation:** There is no way to place Alice and Bob such that Alice can build a fence with Alice's position as the upper left corner and Bob's position as the lower right corner. Hence we return 0. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2024/02/04/example2alicebob.png) + +**Input:** points = \[\[6,2],[4,4],[2,6]] + +**Output:** 2 + +**Explanation:** There are two ways to place Alice and Bob such that Alice will not be sad: +- Place Alice at (4, 4) and Bob at (6, 2). +- Place Alice at (2, 6) and Bob at (4, 4). You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2024/02/04/example4alicebob.png) + +**Input:** points = \[\[3,1],[1,3],[1,1]] + +**Output:** 2 + +**Explanation:** There are two ways to place Alice and Bob such that Alice will not be sad: +- Place Alice at (1, 1) and Bob at (3, 1). +- Place Alice at (1, 3) and Bob at (1, 1). + +You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence. + +Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid. + +**Constraints:** + +* `2 <= n <= 1000` +* `points[i].length == 2` +* -109 <= points[i][0], points[i][1] <= 109 +* All `points[i]` are distinct. + +## Solution + +```kotlin +class Solution { + private fun customCompare(p1: IntArray, p2: IntArray): Int { + if (p1[0] != p2[0]) { + return Integer.signum(p1[0] - p2[0]) + } + return Integer.signum(p2[1] - p1[1]) + } + + fun numberOfPairs(points: Array): Int { + points.sortWith { p1: IntArray, p2: IntArray -> this.customCompare(p1, p2) } + var count = 0 + for (i in points.indices) { + var m = Int.MIN_VALUE + for (j in i + 1 until points.size) { + if ((points[i][1] >= points[j][1]) && (points[j][1] > m)) { + m = points[j][1] + count++ + } + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3028_ant_on_the_boundary/readme.md b/src/main/kotlin/g3001_3100/s3028_ant_on_the_boundary/readme.md new file mode 100644 index 00000000..7e22c49b --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3028_ant_on_the_boundary/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) + +## 3028\. Ant on the Boundary + +Easy + +An ant is on a boundary. It sometimes goes **left** and sometimes **right**. + +You are given an array of **non-zero** integers `nums`. The ant starts reading `nums` from the first element of it to its end. At each step, it moves according to the value of the current element: + +* If `nums[i] < 0`, it moves **left** by `-nums[i]` units. +* If `nums[i] > 0`, it moves **right** by `nums[i]` units. + +Return _the number of times the ant **returns** to the boundary._ + +**Notes:** + +* There is an infinite space on both sides of the boundary. +* We check whether the ant is on the boundary only after it has moved `|nums[i]|` units. In other words, if the ant crosses the boundary during its movement, it does not count. + +**Example 1:** + +**Input:** nums = [2,3,-5] + +**Output:** 1 + +**Explanation:** After the first step, the ant is 2 steps to the right of the boundary. + +After the second step, the ant is 5 steps to the right of the boundary. + +After the third step, the ant is on the boundary. So the answer is 1. + +**Example 2:** + +**Input:** nums = [3,2,-3,-4] + +**Output:** 0 + +**Explanation:** After the first step, the ant is 3 steps to the right of the boundary. + +After the second step, the ant is 5 steps to the right of the boundary. + +After the third step, the ant is 2 steps to the right of the boundary. + +After the fourth step, the ant is 2 steps to the left of the boundary. + +The ant never returned to the boundary, so the answer is 0. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `-10 <= nums[i] <= 10` +* `nums[i] != 0` + +## Solution + +```kotlin +class Solution { + fun returnToBoundaryCount(nums: IntArray): Int { + var diff: Long = 0 + var res = 0 + for (n in nums) { + diff += n.toLong() + // since n is non-zero, so prev diff is not zero, + // when current diff is zero. + if (diff == 0L) res++ + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3029_minimum_time_to_revert_word_to_initial_state_i/readme.md b/src/main/kotlin/g3001_3100/s3029_minimum_time_to_revert_word_to_initial_state_i/readme.md new file mode 100644 index 00000000..142529a9 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3029_minimum_time_to_revert_word_to_initial_state_i/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) + +## 3029\. Minimum Time to Revert Word to Initial State I + +Medium + +You are given a **0-indexed** string `word` and an integer `k`. + +At every second, you must perform the following operations: + +* Remove the first `k` characters of `word`. +* Add any `k` characters to the end of `word`. + +**Note** that you do not necessarily need to add the same characters that you removed. However, you must perform **both** operations at every second. + +Return _the **minimum** time greater than zero required for_ `word` _to revert to its **initial** state_. + +**Example 1:** + +**Input:** word = "abacaba", k = 3 + +**Output:** 2 + +**Explanation:** At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac". At the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state. It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state. + +**Example 2:** + +**Input:** word = "abacaba", k = 4 + +**Output:** 1 + +**Explanation:** At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state. It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state. + +**Example 3:** + +**Input:** word = "abcbabcd", k = 2 + +**Output:** 4 + +**Explanation:** At every second, we will remove the first 2 characters of word, and add the same characters to the end of word. After 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state. It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state. + +**Constraints:** + +* `1 <= word.length <= 50` +* `1 <= k <= word.length` +* `word` consists only of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun minimumTimeToInitialState(word: String, k: Int): Int { + val n = word.length + var i = k + while (i < n) { + if (word.substring(i, n) == word.substring(0, n - i)) { + return i / k + } + i += k + } + return (n + k - 1) / k + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3030_find_the_grid_of_region_average/readme.md b/src/main/kotlin/g3001_3100/s3030_find_the_grid_of_region_average/readme.md new file mode 100644 index 00000000..314b8f99 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3030_find_the_grid_of_region_average/readme.md @@ -0,0 +1,116 @@ +[![](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) + +## 3030\. Find the Grid of Region Average + +Medium + +You are given a **0-indexed** `m x n` grid `image` which represents a grayscale image, where `image[i][j]` represents a pixel with intensity in the range`[0..255]`. You are also given a **non-negative** integer `threshold`. + +Two pixels `image[a][b]` and `image[c][d]` are said to be **adjacent** if `|a - c| + |b - d| == 1`. + +A **region** is a `3 x 3` subgrid where the **absolute difference** in intensity between any two **adjacent** pixels is **less than or equal to** `threshold`. + +All pixels in a **region** belong to that region, note that a pixel **can** belong to **multiple** regions. + +You need to calculate a **0-indexed** `m x n` grid `result`, where `result[i][j]` is the **average** intensity of the region to which `image[i][j]` belongs, **rounded down** to the nearest integer. If `image[i][j]` belongs to multiple regions, `result[i][j]` is the **average** of the **rounded down average** intensities of these regions, **rounded down** to the nearest integer. If `image[i][j]` does **not** belong to any region, `result[i][j]` is **equal to** `image[i][j]`. + +Return _the grid_ `result`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/12/21/example0corrected.png) + +**Input:** image = \[\[5,6,7,10],[8,9,10,10],[11,12,13,10]], threshold = 3 + +**Output:** [[9,9,9,9],[9,9,9,9],[9,9,9,9]] + +**Explanation:** There exist two regions in the image, which are shown as the shaded areas in the picture. The average intensity of the first region is 9, while the average intensity of the second region is 9.67 which is rounded down to 9. The average intensity of both of the regions is (9 + 9) / 2 = 9. As all the pixels belong to either region 1, region 2, or both of them, the intensity of every pixel in the result is 9. Please note that the rounded-down values are used when calculating the average of multiple regions, hence the calculation is done using 9 as the average intensity of region 2, not 9.67. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/12/21/example1corrected.png) + +**Input:** image = \[\[10,20,30],[15,25,35],[20,30,40],[25,35,45]], threshold = 12 + +**Output:** [[25,25,25],[27,27,27],[27,27,27],[30,30,30]] + +**Explanation:** There exist two regions in the image, which are shown as the shaded areas in the picture. The average intensity of the first region is 25, while the average intensity of the second region is 30. The average intensity of both of the regions is (25 + 30) / 2 = 27.5 which is rounded down to 27. All the pixels in row 0 of the image belong to region 1, hence all the pixels in row 0 in the result are 25. Similarly, all the pixels in row 3 in the result are 30. The pixels in rows 1 and 2 of the image belong to region 1 and region 2, hence their assigned value is 27 in the result. + +**Example 3:** + +**Input:** image = \[\[5,6,7],[8,9,10],[11,12,13]], threshold = 1 + +**Output:** [[5,6,7],[8,9,10],[11,12,13]] + +**Explanation:** There does not exist any region in image, hence result[i][j] == image[i][j] for all the pixels. + +**Constraints:** + +* `3 <= n, m <= 500` +* `0 <= image[i][j] <= 255` +* `0 <= threshold <= 255` + +## Solution + +```kotlin +import kotlin.math.abs + +class Solution { + fun resultGrid(image: Array, threshold: Int): Array { + val n = image.size + val m = image[0].size + val intensity = Array(n) { IntArray(m) } + val count = Array(n) { IntArray(m) } + for (i in 1 until n - 1) { + for (j in 1 until m - 1) { + var regionPossible = true + var regionSum = 0 + val r0c0 = image[i - 1][j - 1] + val r0c1 = image[i - 1][j] + val r0c2 = image[i - 1][j + 1] + val r1c0 = image[i][j - 1] + val r1c1 = image[i][j] + val r1c2 = image[i][j + 1] + val r2c0 = image[i + 1][j - 1] + val r2c1 = image[i + 1][j] + val r2c2 = image[i + 1][j + 1] + regionSum += (r0c0 + r0c1 + r0c2 + r1c0 + r1c1 + r1c2 + r2c0 + r2c1 + r2c2) + if (abs((r0c0 - r0c1)) > threshold || abs((r0c0 - r1c0)) > threshold || abs( + (r0c1 - r0c0) + ) > threshold || abs((r0c1 - r1c1)) > threshold || abs((r0c1 - r0c2)) > threshold || abs( + (r0c2 - r0c1) + ) > threshold || abs((r0c2 - r1c2)) > threshold || abs((r1c0 - r1c1)) > threshold || abs( + (r1c2 - r1c1) + ) > threshold || abs((r2c0 - r2c1)) > threshold || abs((r2c0 - r1c0)) > threshold || abs( + (r2c1 - r2c0) + ) > threshold || abs((r2c1 - r1c1)) > threshold || abs((r2c1 - r2c2)) > threshold || abs( + (r2c2 - r2c1) + ) > threshold || abs((r2c2 - r1c2)) > threshold + ) { + regionPossible = false + } + if (regionPossible) { + regionSum /= 9 + for (k in -1..1) { + for (l in -1..1) { + intensity[i + k][j + l] += regionSum + count[i + k][j + l]++ + } + } + } + } + } + for (i in 0 until n) { + for (j in 0 until m) { + if (count[i][j] == 0) { + intensity[i][j] = image[i][j] + } else { + intensity[i][j] = intensity[i][j] / count[i][j] + } + } + } + return intensity + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3031_minimum_time_to_revert_word_to_initial_state_ii/readme.md b/src/main/kotlin/g3001_3100/s3031_minimum_time_to_revert_word_to_initial_state_ii/readme.md new file mode 100644 index 00000000..73cfb8e8 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3031_minimum_time_to_revert_word_to_initial_state_ii/readme.md @@ -0,0 +1,86 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 3031\. Minimum Time to Revert Word to Initial State II + +Hard + +You are given a **0-indexed** string `word` and an integer `k`. + +At every second, you must perform the following operations: + +* Remove the first `k` characters of `word`. +* Add any `k` characters to the end of `word`. + +**Note** that you do not necessarily need to add the same characters that you removed. However, you must perform **both** operations at every second. + +Return _the **minimum** time greater than zero required for_ `word` _to revert to its **initial** state_. + +**Example 1:** + +**Input:** word = "abacaba", k = 3 + +**Output:** 2 + +**Explanation:** At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac". At the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state. + +It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state. + +**Example 2:** + +**Input:** word = "abacaba", k = 4 + +**Output:** 1 + +**Explanation:** At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state. + +It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state. + +**Example 3:** + +**Input:** word = "abcbabcd", k = 2 + +**Output:** 4 + +**Explanation:** At every second, we will remove the first 2 characters of word, and add the same characters to the end of word. After 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state. + +It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state. + +**Constraints:** + +* 1 <= word.length <= 106 +* `1 <= k <= word.length` +* `word` consists only of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun minimumTimeToInitialState(word: String, k: Int): Int { + val c = word.toCharArray() + val lps = IntArray(c.size) + var q: Int + for (i in 1 until lps.size) { + if (c[i] == c[0]) { + lps[i] = 1 + } + q = lps[i - 1] + while (q > 0) { + if (c[q] == c[i]) { + lps[i] = q + 1 + break + } + q = lps[q - 1] + } + } + q = lps[lps.size - 1] + while (q > 0) { + if ((c.size - q) % k == 0) { + return (c.size - q) / k + } + q = lps[q - 1] + } + return (c.size + k - 1) / k + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3033_modify_the_matrix/readme.md b/src/main/kotlin/g3001_3100/s3033_modify_the_matrix/readme.md new file mode 100644 index 00000000..92f08223 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3033_modify_the_matrix/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) + +## 3033\. Modify the Matrix + +Easy + +Given a **0-indexed** `m x n` integer matrix `matrix`, create a new **0-indexed** matrix called `answer`. Make `answer` equal to `matrix`, then replace each element with the value `-1` with the **maximum** element in its respective column. + +Return _the matrix_ `answer`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/12/24/matrix1.png) + +**Input:** matrix = \[\[1,2,-1],[4,-1,6],[7,8,9]] + +**Output:** [[1,2,9],[4,8,6],[7,8,9]] + +**Explanation:** The diagram above shows the elements that are changed (in blue). +- We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8. +- We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/12/24/matrix2.png) + +**Input:** matrix = \[\[3,-1],[5,2]] + +**Output:** [[3,2],[5,2]] + +**Explanation:** The diagram above shows the elements that are changed (in blue). + +**Constraints:** + +* `m == matrix.length` +* `n == matrix[i].length` +* `2 <= m, n <= 50` +* `-1 <= matrix[i][j] <= 100` +* The input is generated such that each column contains at least one non-negative integer. + +## Solution + +```kotlin +class Solution { + fun modifiedMatrix(matrix: Array): Array { + for (i in matrix.indices) { + for (j in matrix[0].indices) { + if (matrix[i][j] == -1) { + var y = 0 + for (ints in matrix) { + if (ints[j] > y) { + y = ints[j] + } + } + matrix[i][j] = y + } + } + } + return matrix + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3034_number_of_subarrays_that_match_a_pattern_i/readme.md b/src/main/kotlin/g3001_3100/s3034_number_of_subarrays_that_match_a_pattern_i/readme.md new file mode 100644 index 00000000..2e9241e2 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3034_number_of_subarrays_that_match_a_pattern_i/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) + +## 3034\. Number of Subarrays That Match a Pattern I + +Medium + +You are given a **0-indexed** integer array `nums` of size `n`, and a **0-indexed** integer array `pattern` of size `m` consisting of integers `-1`, `0`, and `1`. + +A subarray `nums[i..j]` of size `m + 1` is said to match the `pattern` if the following conditions hold for each element `pattern[k]`: + +* `nums[i + k + 1] > nums[i + k]` if `pattern[k] == 1`. +* `nums[i + k + 1] == nums[i + k]` if `pattern[k] == 0`. +* `nums[i + k + 1] < nums[i + k]` if `pattern[k] == -1`. + +Return _the **count** of subarrays in_ `nums` _that match the_ `pattern`. + +**Example 1:** + +**Input:** nums = [1,2,3,4,5,6], pattern = [1,1] + +**Output:** 4 + +**Explanation:** The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern. + +Hence, there are 4 subarrays in nums that match the pattern. + +**Example 2:** + +**Input:** nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1] + +**Output:** 2 + +**Explanation:** Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern. + +Hence, there are 2 subarrays in nums that match the pattern. + +**Constraints:** + +* `2 <= n == nums.length <= 100` +* 1 <= nums[i] <= 109 +* `1 <= m == pattern.length < n` +* `-1 <= pattern[i] <= 1` + +## Solution + +```kotlin +class Solution { + fun countMatchingSubarrays(nums: IntArray, pattern: IntArray): Int { + val n = nums.size + val m = pattern.size + var count = 0 + for (i in 0..n - m - 1) { + var k = 0 + while (k < m) { + if (nums[i + k + 1] > nums[i + k] && pattern[k] == 1) { + k++ + } else if (nums[i + k + 1] == nums[i + k] && pattern[k] == 0) { + k++ + } else if (nums[i + k + 1] < nums[i + k] && pattern[k] == -1) { + k++ + } else { + break + } + } + if (k == m) { + count++ + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3035_maximum_palindromes_after_operations/readme.md b/src/main/kotlin/g3001_3100/s3035_maximum_palindromes_after_operations/readme.md new file mode 100644 index 00000000..cd438636 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3035_maximum_palindromes_after_operations/readme.md @@ -0,0 +1,107 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 3035\. Maximum Palindromes After Operations + +Medium + +You are given a **0-indexed** string array `words` having length `n` and containing **0-indexed** strings. + +You are allowed to perform the following operation **any** number of times (**including** **zero**): + +* Choose integers `i`, `j`, `x`, and `y` such that `0 <= i, j < n`, `0 <= x < words[i].length`, `0 <= y < words[j].length`, and **swap** the characters `words[i][x]` and `words[j][y]`. + +Return _an integer denoting the **maximum** number of palindromes_ `words` _can contain, after performing some operations._ + +**Note:** `i` and `j` may be equal during an operation. + +**Example 1:** + +**Input:** words = ["abbb","ba","aa"] + +**Output:** 3 + +**Explanation:** In this example, one way to get the maximum number of palindromes is: + +Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes ["bbbb","aa","aa"]. + +All strings in words are now palindromes. Hence, the maximum number of palindromes achievable is 3. + +**Example 2:** + +**Input:** words = ["abc","ab"] + +**Output:** 2 + +**Explanation:** In this example, one way to get the maximum number of palindromes is: + +Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes ["aac","bb"]. + +Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes ["aca","bb"]. + +Both strings are now palindromes. Hence, the maximum number of palindromes achievable is 2. + +**Example 3:** + +**Input:** words = ["cd","ef","a"] + +**Output:** 1 + +**Explanation:** In this example, there is no need to perform any operation. There is one palindrome in words "a". It can be shown that it is not possible to get more than one palindrome after any number of operations. Hence, the answer is 1. + +**Constraints:** + +* `1 <= words.length <= 1000` +* `1 <= words[i].length <= 100` +* `words[i]` consists only of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun maxPalindromesAfterOperations(words: Array): Int { + val ar = IntArray(26) + val dp = IntArray(101) + var s = 0 + var p = 0 + var ans = 0 + for (str in words) { + for (c in str.toCharArray()) { + ar[c.code - 'a'.code]++ + } + dp[str.length]++ + } + for (j in ar) { + s += j % 2 + p += (j / 2) + } + for (i in 1 until dp.size) { + if (dp[i] > 0) { + if (i % 2 == 0) { + while (dp[i] > 0 && p > 0) { + p -= i / 2 + if (p >= 0) { + ans++ + } + dp[i]-- + } + } else { + while (dp[i] > 0 && (i == 1 || p > 0)) { + if (s == 0) { + s += 2 + p-- + } + s-- + p -= (i - 1) / 2 + if (p >= 0) { + ans++ + } + dp[i]-- + } + } + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3036_number_of_subarrays_that_match_a_pattern_ii/readme.md b/src/main/kotlin/g3001_3100/s3036_number_of_subarrays_that_match_a_pattern_ii/readme.md new file mode 100644 index 00000000..989072fd --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3036_number_of_subarrays_that_match_a_pattern_ii/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) + +## 3036\. Number of Subarrays That Match a Pattern II + +Hard + +You are given a **0-indexed** integer array `nums` of size `n`, and a **0-indexed** integer array `pattern` of size `m` consisting of integers `-1`, `0`, and `1`. + +A subarray `nums[i..j]` of size `m + 1` is said to match the `pattern` if the following conditions hold for each element `pattern[k]`: + +* `nums[i + k + 1] > nums[i + k]` if `pattern[k] == 1`. +* `nums[i + k + 1] == nums[i + k]` if `pattern[k] == 0`. +* `nums[i + k + 1] < nums[i + k]` if `pattern[k] == -1`. + +Return _the **count** of subarrays in_ `nums` _that match the_ `pattern`. + +**Example 1:** + +**Input:** nums = [1,2,3,4,5,6], pattern = [1,1] + +**Output:** 4 + +**Explanation:** The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern. Hence, there are 4 subarrays in nums that match the pattern. + +**Example 2:** + +**Input:** nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1] + +**Output:** 2 + +**Explanation:** Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern. Hence, there are 2 subarrays in nums that match the pattern. + +**Constraints:** + +* 2 <= n == nums.length <= 106 +* 1 <= nums[i] <= 109 +* `1 <= m == pattern.length < n` +* `-1 <= pattern[i] <= 1` + +## Solution + +```kotlin +class Solution { + fun countMatchingSubarrays(nums: IntArray, pattern: IntArray): Int { + val n = nums.size + val m = pattern.size + val arr = IntArray(n - 1) + for (i in 0 until n - 1) { + if (nums[i + 1] > nums[i]) { + arr[i] = 1 + } else if (nums[i + 1] < nums[i]) { + arr[i] = -1 + } + } + var hash = 0 + var pHash = 0 + var base = 1 + for (i in 0 until m) { + hash = hash * 3 + arr[i] + 1 + pHash = pHash * 3 + pattern[i] + 1 + base *= 3 + } + var count = 0 + for (i in 0..n - 1 - m) { + if (hash == pHash) { + count++ + } + + if (i < n - 1 - m) { + hash = hash * 3 - base * (arr[i] + 1) + arr[i + m] + 1 + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3038_maximum_number_of_operations_with_the_same_score_i/readme.md b/src/main/kotlin/g3001_3100/s3038_maximum_number_of_operations_with_the_same_score_i/readme.md new file mode 100644 index 00000000..c031c06a --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3038_maximum_number_of_operations_with_the_same_score_i/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) + +## 3038\. Maximum Number of Operations With the Same Score I + +Easy + +Given an array of integers called `nums`, you can perform the following operation while `nums` contains **at least** `2` elements: + +* Choose the first two elements of `nums` and delete them. + +The **score** of the operation is the sum of the deleted elements. + +Your task is to find the **maximum** number of operations that can be performed, such that **all operations have the same score**. + +Return _the **maximum** number of operations possible that satisfy the condition mentioned above_. + +**Example 1:** + +**Input:** nums = [3,2,1,4,5] + +**Output:** 2 + +**Explanation:** We perform the following operations: +- Delete the first two elements, with score 3 + 2 = 5, nums = [1,4,5]. +- Delete the first two elements, with score 1 + 4 = 5, nums = [5]. + +We are unable to perform any more operations as nums contain only 1 element. + +**Example 2:** + +**Input:** nums = [3,2,6,1,4] + +**Output:** 1 + +**Explanation:** We perform the following operations: +- Delete the first two elements, with score 3 + 2 = 5, nums = [6,1,4]. + +We are unable to perform any more operations as the score of the next operation isn't the same as the previous one. + +**Constraints:** + +* `2 <= nums.length <= 100` +* `1 <= nums[i] <= 1000` + +## Solution + +```kotlin +class Solution { + fun maxOperations(nums: IntArray): Int { + var c = 1 + var i = 2 + val s = nums[0] + nums[1] + val l = nums.size - (if (nums.size % 2 == 0) 0 else 1) + while (i < l) { + if (nums[i] + nums[i + 1] == s) { + c++ + } else { + break + } + i += 2 + } + return c + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3039_apply_operations_to_make_string_empty/readme.md b/src/main/kotlin/g3001_3100/s3039_apply_operations_to_make_string_empty/readme.md new file mode 100644 index 00000000..8bb4befc --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3039_apply_operations_to_make_string_empty/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 3039\. Apply Operations to Make String Empty + +Medium + +You are given a string `s`. + +Consider performing the following operation until `s` becomes **empty**: + +* For **every** alphabet character from `'a'` to `'z'`, remove the **first** occurrence of that character in `s` (if it exists). + +For example, let initially `s = "aabcbbca"`. We do the following operations: + +* Remove the underlined characters s = "**a**a**bc**bbca". The resulting string is `s = "abbca"`. +* Remove the underlined characters s = "**ab**b**c**a". The resulting string is `s = "ba"`. +* Remove the underlined characters s = "**ba**". The resulting string is `s = ""`. + +Return _the value of the string_ `s` _right **before** applying the **last** operation_. In the example above, answer is `"ba"`. + +**Example 1:** + +**Input:** s = "aabcbbca" + +**Output:** "ba" + +**Explanation:** Explained in the statement. + +**Example 2:** + +**Input:** s = "abcd" + +**Output:** "abcd" + +**Explanation:** We do the following operation: +- Remove the underlined characters s = "**abcd**". The resulting string is s = "". + +The string just before the last operation is "abcd". + +**Constraints:** + +* 1 <= s.length <= 5 * 105 +* `s` consists only of lowercase English letters. + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun lastNonEmptyString(s: String): String { + val freq = IntArray(26) + val ar = s.toCharArray() + val n = ar.size + var max = 1 + val sb = StringBuilder() + for (c in ar) { + freq[c.code - 'a'.code]++ + max = max(freq[c.code - 'a'.code].toDouble(), max.toDouble()).toInt() + } + for (i in n - 1 downTo 0) { + if (freq[ar[i].code - 'a'.code] == max) { + sb.append(ar[i]) + freq[ar[i].code - 'a'.code] = 0 + } + } + return sb.reverse().toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3040_maximum_number_of_operations_with_the_same_score_ii/readme.md b/src/main/kotlin/g3001_3100/s3040_maximum_number_of_operations_with_the_same_score_ii/readme.md new file mode 100644 index 00000000..fe079335 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3040_maximum_number_of_operations_with_the_same_score_ii/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) + +## 3040\. Maximum Number of Operations With the Same Score II + +Medium + +Given an array of integers called `nums`, you can perform **any** of the following operation while `nums` contains **at least** `2` elements: + +* Choose the first two elements of `nums` and delete them. +* Choose the last two elements of `nums` and delete them. +* Choose the first and the last elements of `nums` and delete them. + +The **score** of the operation is the sum of the deleted elements. + +Your task is to find the **maximum** number of operations that can be performed, such that **all operations have the same score**. + +Return _the **maximum** number of operations possible that satisfy the condition mentioned above_. + +**Example 1:** + +**Input:** nums = [3,2,1,2,3,4] + +**Output:** 3 + +**Explanation:** We perform the following operations: +- Delete the first two elements, with score 3 + 2 = 5, nums = [1,2,3,4]. +- Delete the first and the last elements, with score 1 + 4 = 5, nums = [2,3]. +- Delete the first and the last elements, with score 2 + 3 = 5, nums = []. + +We are unable to perform any more operations as nums is empty. + +**Example 2:** + +**Input:** nums = [3,2,6,1,4] + +**Output:** 2 + +**Explanation:** We perform the following operations: +- Delete the first two elements, with score 3 + 2 = 5, nums = [6,1,4]. +- Delete the last two elements, with score 1 + 4 = 5, nums = [6]. + +It can be proven that we can perform at most 2 operations. + +**Constraints:** + +* `2 <= nums.length <= 2000` +* `1 <= nums[i] <= 1000` + +## Solution + +```kotlin +import java.util.Objects +import kotlin.math.max + +class Solution { + private lateinit var nums: IntArray + + private var maxOps = 1 + + private val dp: MutableMap = HashMap() + + private class Pos(var start: Int, var end: Int, var sum: Int) { + override fun equals(other: Any?): Boolean { + if (other == null) { + return false + } + if (other !is Pos) { + return false + } + return start == other.start && end == other.end && sum == other.sum + } + + override fun hashCode(): Int { + return Objects.hash(start, end, sum) + } + } + + fun maxOperations(nums: IntArray): Int { + this.nums = nums + val length = nums.size + + maxOperations(2, length - 1, nums[0] + nums[1], 1) + maxOperations(0, length - 3, nums[length - 2] + nums[length - 1], 1) + maxOperations(1, length - 2, nums[0] + nums[length - 1], 1) + + return maxOps + } + + private fun maxOperations(start: Int, end: Int, sum: Int, nOps: Int) { + if (start >= end) { + return + } + + if ((((end - start) / 2) + nOps) < maxOps) { + return + } + + val pos = Pos(start, end, sum) + val posNops = dp[pos] + if (posNops != null && posNops >= nOps) { + return + } + dp[pos] = nOps + if (nums[start] + nums[start + 1] == sum) { + maxOps = max(maxOps, (nOps + 1)) + maxOperations(start + 2, end, sum, nOps + 1) + } + if (nums[end - 1] + nums[end] == sum) { + maxOps = max(maxOps, (nOps + 1)) + maxOperations(start, end - 2, sum, nOps + 1) + } + if (nums[start] + nums[end] == sum) { + maxOps = max(maxOps, (nOps + 1)) + maxOperations(start + 1, end - 1, sum, nOps + 1) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3041_maximize_consecutive_elements_in_an_array_after_modification/readme.md b/src/main/kotlin/g3001_3100/s3041_maximize_consecutive_elements_in_an_array_after_modification/readme.md new file mode 100644 index 00000000..4b2d9918 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3041_maximize_consecutive_elements_in_an_array_after_modification/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) + +## 3041\. Maximize Consecutive Elements in an Array After Modification + +Hard + +You are given a **0-indexed** array `nums` consisting of **positive** integers. + +Initially, you can increase the value of **any** element in the array by **at most** `1`. + +After that, you need to select **one or more** elements from the final array such that those elements are **consecutive** when sorted in increasing order. For example, the elements `[3, 4, 5]` are consecutive while `[3, 4, 6]` and `[1, 1, 2, 3]` are not. + +Return _the **maximum** number of elements that you can select_. + +**Example 1:** + +**Input:** nums = [2,1,5,1,1] + +**Output:** 3 + +**Explanation:** We can increase the elements at indices 0 and 3. The resulting array is nums = [3,1,5,2,1]. + +We select the elements [**3**,**1**,5,**2**,1] and we sort them to obtain [1,2,3], which are consecutive. + +It can be shown that we cannot select more than 3 consecutive elements. + +**Example 2:** + +**Input:** nums = [1,4,7,10] + +**Output:** 1 + +**Explanation:** The maximum consecutive elements that we can select is 1. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 106 + +## Solution + +```kotlin +import kotlin.math.max +import kotlin.math.min + +class Solution { + fun maxSelectedElements(nums: IntArray): Int { + var max = 0 + var min = Int.MAX_VALUE + for (x in nums) { + max = max(x, max) + min = min(x, min) + } + val count = IntArray(max + 1) + for (x in nums) { + ++count[x] + } + val dp = IntArray(max + 2) + var ans = 0 + for (x in min..max) { + if (count[x] == 0) { + continue + } + val c = count[x] + if (c == 1) { + dp[x + 1] = dp[x] + 1 + dp[x] = dp[x - 1] + 1 + } else { + dp[x] = dp[x - 1] + 1 + dp[x + 1] = dp[x] + 1 + } + ans = max(ans, dp[x]) + ans = max(ans, dp[x + 1]) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3042_count_prefix_and_suffix_pairs_i/readme.md b/src/main/kotlin/g3001_3100/s3042_count_prefix_and_suffix_pairs_i/readme.md new file mode 100644 index 00000000..62466151 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3042_count_prefix_and_suffix_pairs_i/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) + +## 3042\. Count Prefix and Suffix Pairs I + +Easy + +You are given a **0-indexed** string array `words`. + +Let's define a **boolean** function `isPrefixAndSuffix` that takes two strings, `str1` and `str2`: + +* `isPrefixAndSuffix(str1, str2)` returns `true` if `str1` is **both** a prefix and a suffix of `str2`, and `false` otherwise. + +For example, `isPrefixAndSuffix("aba", "ababa")` is `true` because `"aba"` is a prefix of `"ababa"` and also a suffix, but `isPrefixAndSuffix("abc", "abcd")` is `false`. + +Return _an integer denoting the **number** of index pairs_ `(i, j)` _such that_ `i < j`_, and_ `isPrefixAndSuffix(words[i], words[j])` _is_ `true`_._ + +**Example 1:** + +**Input:** words = ["a","aba","ababa","aa"] + +**Output:** 4 + +**Explanation:** In this example, the counted index pairs are: + +i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true. + +i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true. + +i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true. + +i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true. + +Therefore, the answer is 4. + +**Example 2:** + +**Input:** words = ["pa","papa","ma","mama"] + +**Output:** 2 + +**Explanation:** In this example, the counted index pairs are: + +i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true. + +i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true. + +Therefore, the answer is 2. + +**Example 3:** + +**Input:** words = ["abab","ab"] + +**Output:** 0 + +**Explanation:** In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false. + +Therefore, the answer is 0. + +**Constraints:** + +* `1 <= words.length <= 50` +* `1 <= words[i].length <= 10` +* `words[i]` consists only of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun countPrefixSuffixPairs(words: Array): Int { + var count = 0 + for (i in words.indices) { + for (j in i + 1 until words.size) { + if (isPrefixAndSuffix(words[i], words[j])) { + count++ + } + } + } + return count + } + + private fun isPrefixAndSuffix(str1: String, str2: String): Boolean { + val m = str1.length + val n = str2.length + if (m > n) { + return false + } + for (i in 0 until m) { + if (str1[i] != str2[i]) { + return false + } + } + for (i in 0 until m) { + if (str1[i] != str2[n - m + i]) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3043_find_the_length_of_the_longest_common_prefix/readme.md b/src/main/kotlin/g3001_3100/s3043_find_the_length_of_the_longest_common_prefix/readme.md new file mode 100644 index 00000000..72da1c35 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3043_find_the_length_of_the_longest_common_prefix/readme.md @@ -0,0 +1,107 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 3043\. Find the Length of the Longest Common Prefix + +Medium + +You are given two arrays with **positive** integers `arr1` and `arr2`. + +A **prefix** of a positive integer is an integer formed by one or more of its digits, starting from its **leftmost** digit. For example, `123` is a prefix of the integer `12345`, while `234` is **not**. + +A **common prefix** of two integers `a` and `b` is an integer `c`, such that `c` is a prefix of both `a` and `b`. For example, `5655359` and `56554` have a common prefix `565` while `1223` and `43456` **do not** have a common prefix. + +You need to find the length of the **longest common prefix** between all pairs of integers `(x, y)` such that `x` belongs to `arr1` and `y` belongs to `arr2`. + +Return _the length of the **longest** common prefix among all pairs_. _If no common prefix exists among them_, _return_ `0`. + +**Example 1:** + +**Input:** arr1 = [1,10,100], arr2 = [1000] + +**Output:** 3 + +**Explanation:** There are 3 pairs (arr1[i], arr2[j]): + +- The longest common prefix of (1, 1000) is 1. + +- The longest common prefix of (10, 1000) is 10. + +- The longest common prefix of (100, 1000) is 100. + +The longest common prefix is 100 with a length of 3. + +**Example 2:** + +**Input:** arr1 = [1,2,3], arr2 = [4,4,4] + +**Output:** 0 + +**Explanation:** There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0. + +Note that common prefixes between elements of the same array do not count. + +**Constraints:** + +* 1 <= arr1.length, arr2.length <= 5 * 104 +* 1 <= arr1[i], arr2[i] <= 108 + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun longestCommonPrefix(arr1: IntArray, arr2: IntArray): Int { + val trie = Trie() + for (num in arr2) { + trie.addWord(num.toString()) + } + var longest = 0 + var `val`: String + for (num in arr1) { + `val` = num.toString() + if (`val`.length > longest) { + longest = max(longest, trie.findLongestPrefix(`val`)) + } + } + return longest + } + + private class Trie { + var root: TrieNode = TrieNode() + + fun addWord(word: String) { + var first: TrieNode? = root + var codePoint: Int + for (i in 0 until word.length) { + codePoint = word[i].code - '0'.code + if (first!!.nodes[codePoint] == null) { + first.nodes[codePoint] = TrieNode() + } + first = first.nodes[codePoint] + } + } + + fun findLongestPrefix(word: String): Int { + var first: TrieNode? = root + var i = 0 + var codePoint: Int + while (i < word.length) { + codePoint = word[i].code - '0'.code + if (first!!.nodes[codePoint] == null) { + return i + } + first = first.nodes[codePoint] + i++ + } + return i + } + } + + private class TrieNode { + var nodes: Array = + arrayOfNulls(10) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3044_most_frequent_prime/readme.md b/src/main/kotlin/g3001_3100/s3044_most_frequent_prime/readme.md new file mode 100644 index 00000000..bff886b8 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3044_most_frequent_prime/readme.md @@ -0,0 +1,167 @@ +[![](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) + +## 3044\. Most Frequent Prime + +Medium + +You are given a `m x n` **0-indexed** 2D matrix `mat`. From every cell, you can create numbers in the following way: + +* There could be at most `8` paths from the cells namely: east, south-east, south, south-west, west, north-west, north, and north-east. +* Select a path from them and append digits in this path to the number being formed by traveling in this direction. +* Note that numbers are generated at every step, for example, if the digits along the path are `1, 9, 1`, then there will be three numbers generated along the way: `1, 19, 191`. + +Return _the most frequent prime number **greater** than_ `10` _out of all the numbers created by traversing the matrix or_ `-1` _if no such prime number exists. If there are multiple prime numbers with the highest frequency, then return the **largest** among them._ + +**Note:** It is invalid to change the direction during the move. + +**Example 1:** + + **![](https://assets.leetcode.com/uploads/2024/02/15/south)** + + **Input:** mat = \[\[1,1],[9,9],[1,1]] + +**Output:** 19 + +**Explanation:** + +From cell (0,0) there are 3 possible directions and the numbers greater than 10 which can be created in those directions are: + +East: [11], South-East: [19], South: [19,191]. + +Numbers greater than 10 created from the cell (0,1) in all possible directions are: [19,191,19,11]. + +Numbers greater than 10 created from the cell (1,0) in all possible directions are: [99,91,91,91,91]. + +Numbers greater than 10 created from the cell (1,1) in all possible directions are: [91,91,99,91,91]. + +Numbers greater than 10 created from the cell (2,0) in all possible directions are: [11,19,191,19]. + +Numbers greater than 10 created from the cell (2,1) in all possible directions are: [11,19,19,191]. + +The most frequent prime number among all the created numbers is 19. + +**Example 2:** + +**Input:** mat = \[\[7]] + +**Output:** -1 + +**Explanation:** The only number which can be formed is 7. It is a prime number however it is not greater than 10, so return -1. + +**Example 3:** + +**Input:** mat = \[\[9,7,8],[4,6,5],[2,8,6]] + +**Output:** 97 + +**Explanation:** + +Numbers greater than 10 created from the cell (0,0) in all possible directions are: [97,978,96,966,94,942]. + +Numbers greater than 10 created from the cell (0,1) in all possible directions are: [78,75,76,768,74,79]. + +Numbers greater than 10 created from the cell (0,2) in all possible directions are: [85,856,86,862,87,879]. + +Numbers greater than 10 created from the cell (1,0) in all possible directions are: [46,465,48,42,49,47]. + +Numbers greater than 10 created from the cell (1,1) in all possible directions are: [65,66,68,62,64,69,67,68]. + +Numbers greater than 10 created from the cell (1,2) in all possible directions are: [56,58,56,564,57,58]. + +Numbers greater than 10 created from the cell (2,0) in all possible directions are: [28,286,24,249,26,268]. + +Numbers greater than 10 created from the cell (2,1) in all possible directions are: [86,82,84,86,867,85]. + +Numbers greater than 10 created from the cell (2,2) in all possible directions are: [68,682,66,669,65,658]. + +The most frequent prime number among all the created numbers is 97. + +**Constraints:** + +* `m == mat.length` +* `n == mat[i].length` +* `1 <= m, n <= 6` +* `1 <= mat[i][j] <= 9` + +## Solution + +```kotlin +import kotlin.math.max +import kotlin.math.sqrt + +@Suppress("NAME_SHADOWING") +class Solution { + private var max = 0 + private var freqNum = -1 + + fun mostFrequentPrime(mat: Array): Int { + val nexts = + arrayOf( + intArrayOf(1, 1), + intArrayOf(-1, -1), + intArrayOf(1, -1), + intArrayOf(-1, 1), + intArrayOf(0, 1), + intArrayOf(0, -1), + intArrayOf(1, 0), + intArrayOf(-1, 0) + ) + val m = mat.size + val n = mat[0].size + val primeFreq: MutableMap = HashMap() + for (i in 0 until m) { + for (j in 0 until n) { + for (next in nexts) { + getPrime(i, j, mat, 0, next, primeFreq) + } + } + } + return freqNum + } + + private fun getPrime( + i: Int, + j: Int, + mat: Array, + num: Int, + next: IntArray, + primeFreq: MutableMap + ) { + var num = num + val m = mat.size + val n = mat[0].size + if (i < 0 || j < 0 || i == m || j == n) { + return + } + num = num * 10 + mat[i][j] + if (num > 10 && isPrime(num)) { + val count = primeFreq.getOrDefault(num, 0) + 1 + if ((count == max && freqNum < num) || count > max) { + freqNum = num + } + max = max(max, count) + primeFreq[num] = count + } + getPrime(i + next[0], j + next[1], mat, num, next, primeFreq) + } + + private fun isPrime(num: Int): Boolean { + if (num == 2) { + return true + } + if (num == 1 || (num and 1) == 0) { + return false + } + val n = sqrt(num.toDouble()).toInt() + var i = 3 + while (i <= n) { + if ((num % i) == 0) { + return false + } + i += 2 + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3045_count_prefix_and_suffix_pairs_ii/readme.md b/src/main/kotlin/g3001_3100/s3045_count_prefix_and_suffix_pairs_ii/readme.md new file mode 100644 index 00000000..852aaa78 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3045_count_prefix_and_suffix_pairs_ii/readme.md @@ -0,0 +1,93 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 3045\. Count Prefix and Suffix Pairs II + +Hard + +You are given a **0-indexed** string array `words`. + +Let's define a **boolean** function `isPrefixAndSuffix` that takes two strings, `str1` and `str2`: + +* `isPrefixAndSuffix(str1, str2)` returns `true` if `str1` is **both** a prefix and a suffix of `str2`, and `false` otherwise. + +For example, `isPrefixAndSuffix("aba", "ababa")` is `true` because `"aba"` is a prefix of `"ababa"` and also a suffix, but `isPrefixAndSuffix("abc", "abcd")` is `false`. + +Return _an integer denoting the **number** of index pairs_ `(i_,_ j)` _such that_ `i < j`_, and_ `isPrefixAndSuffix(words[i], words[j])` _is_ `true`_._ + +**Example 1:** + +**Input:** words = ["a","aba","ababa","aa"] + +**Output:** 4 + +**Explanation:** In this example, the counted index pairs are: + +i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true. + +i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true. + +i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true. + +i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true. + +Therefore, the answer is 4. + +**Example 2:** + +**Input:** words = ["pa","papa","ma","mama"] + +**Output:** 2 + +**Explanation:** In this example, the counted index pairs are: + +i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true. + +i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true. + +Therefore, the answer is 2. + +**Example 3:** + +**Input:** words = ["abab","ab"] + +**Output:** 0 + +**Explanation:** In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false. + +Therefore, the answer is 0. + +**Constraints:** + +* 1 <= words.length <= 105 +* 1 <= words[i].length <= 105 +* `words[i]` consists only of lowercase English letters. +* The sum of the lengths of all `words[i]` does not exceed 5 * 105. + +## Solution + +```kotlin +class Solution { + fun countPrefixSuffixPairs(words: Array): Long { + var ans: Long = 0 + val visited = BooleanArray(words.size) + for (i in words.indices) { + val p = words[i] + if (!visited[i]) { + var found = 1 + for (j in i + 1 until words.size) { + val s = words[j] + if (s.length >= p.length && s.startsWith(p) && s.endsWith(p)) { + ans += found.toLong() + } + if (p == s) { + found++ + visited[j] = true + } + } + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3046_split_the_array/readme.md b/src/main/kotlin/g3001_3100/s3046_split_the_array/readme.md new file mode 100644 index 00000000..3a904b6f --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3046_split_the_array/readme.md @@ -0,0 +1,53 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 3046\. Split the Array + +Easy + +You are given an integer array `nums` of **even** length. You have to split the array into two parts `nums1` and `nums2` such that: + +* `nums1.length == nums2.length == nums.length / 2`. +* `nums1` should contain **distinct** elements. +* `nums2` should also contain **distinct** elements. + +Return `true` _if it is possible to split the array, and_ `false` _otherwise__._ + +**Example 1:** + +**Input:** nums = [1,1,2,2,3,4] + +**Output:** true + +**Explanation:** One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4]. + +**Example 2:** + +**Input:** nums = [1,1,1,1] + +**Output:** false + +**Explanation:** The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `nums.length % 2 == 0` +* `1 <= nums[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun isPossibleToSplit(nums: IntArray): Boolean { + val a = IntArray(101) + for (n in nums) { + a[n]++ + if (a[n] > 2) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3047_find_the_largest_area_of_square_inside_two_rectangles/readme.md b/src/main/kotlin/g3001_3100/s3047_find_the_largest_area_of_square_inside_two_rectangles/readme.md new file mode 100644 index 00000000..a924949d --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3047_find_the_largest_area_of_square_inside_two_rectangles/readme.md @@ -0,0 +1,91 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 3047\. Find the Largest Area of Square Inside Two Rectangles + +Medium + +There exist `n` rectangles in a 2D plane. You are given two **0-indexed** 2D integer arrays `bottomLeft` and `topRight`, both of size `n x 2`, where `bottomLeft[i]` and `topRight[i]` represent the **bottom-left** and **top-right** coordinates of the ith rectangle respectively. + +You can select a region formed from the **intersection** of two of the given rectangles. You need to find the **largest** area of a **square** that can fit **inside** this region if you select the region optimally. + +Return _the **largest** possible area of a square, or_ `0` _if there **do not** exist any intersecting regions between the rectangles_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2024/01/05/example12.png) + +**Input:** bottomLeft = \[\[1,1],[2,2],[3,1]], topRight = \[\[3,3],[4,4],[6,6]] + +**Output:** 1 + +**Explanation:** A square with side length 1 can fit inside either the intersecting region of rectangle 0 and rectangle 1, or the intersecting region of rectangle 1 and rectangle 2. Hence the largest area is side \* side which is 1 \* 1 == 1. + +It can be shown that a square with a greater side length can not fit inside any intersecting region. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2024/01/04/rectanglesexample2.png) + +**Input:** bottomLeft = \[\[1,1],[2,2],[1,2]], topRight = \[\[3,3],[4,4],[3,4]] + +**Output:** 1 + +**Explanation:** A square with side length 1 can fit inside either the intersecting region of rectangle 0 and rectangle 1, the intersecting region of rectangle 1 and rectangle 2, or the intersection region of all 3 rectangles. Hence the largest area is side \* side which is 1 \* 1 == 1. + +It can be shown that a square with a greater side length can not fit inside any intersecting region. Note that the region can be formed by the intersection of more than 2 rectangles. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2024/01/04/rectanglesexample3.png) + +**Input:** bottomLeft = \[\[1,1],[3,3],[3,1]], topRight = \[\[2,2],[4,4],[4,2]] + +**Output:** 0 + +**Explanation:** No pair of rectangles intersect, hence, we return 0. + +**Constraints:** + +* `n == bottomLeft.length == topRight.length` +* 2 <= n <= 103 +* `bottomLeft[i].length == topRight[i].length == 2` +* 1 <= bottomLeft[i][0], bottomLeft[i][1] <= 107 +* 1 <= topRight[i][0], topRight[i][1] <= 107 +* `bottomLeft[i][0] < topRight[i][0]` +* `bottomLeft[i][1] < topRight[i][1]` + +## Solution + +```kotlin +import kotlin.math.max +import kotlin.math.min +import kotlin.math.pow + +class Solution { + fun largestSquareArea(bottomLeft: Array, topRight: Array): Long { + val n = bottomLeft.size + var maxArea: Long = 0 + for (i in 0 until n) { + val ax = bottomLeft[i][0] + val ay = bottomLeft[i][1] + val bx = topRight[i][0] + val by = topRight[i][1] + for (j in i + 1 until n) { + val cx = bottomLeft[j][0] + val cy = bottomLeft[j][1] + val dx = topRight[j][0] + val dy = topRight[j][1] + val x1 = max(ax, cx) + val y1 = max(ay, cy) + val x2 = min(bx, dx) + val y2 = min(by, dy) + val minSide = min((x2 - x1), (y2 - y1)) + val area = max(minSide.toDouble(), 0.0).pow(2.0).toLong() + maxArea = max(maxArea, area) + } + } + return maxArea + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3048_earliest_second_to_mark_indices_i/readme.md b/src/main/kotlin/g3001_3100/s3048_earliest_second_to_mark_indices_i/readme.md new file mode 100644 index 00000000..1e6371f9 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3048_earliest_second_to_mark_indices_i/readme.md @@ -0,0 +1,140 @@ +[![](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) + +## 3048\. Earliest Second to Mark Indices I + +Medium + +You are given two **1-indexed** integer arrays, `nums` and, `changeIndices`, having lengths `n` and `m`, respectively. + +Initially, all indices in `nums` are unmarked. Your task is to mark **all** indices in `nums`. + +In each second, `s`, in order from `1` to `m` (**inclusive**), you can perform **one** of the following operations: + +* Choose an index `i` in the range `[1, n]` and **decrement** `nums[i]` by `1`. +* If `nums[changeIndices[s]]` is **equal** to `0`, **mark** the index `changeIndices[s]`. +* Do nothing. + +Return _an integer denoting the **earliest second** in the range_ `[1, m]` _when **all** indices in_ `nums` _can be marked by choosing operations optimally, or_ `-1` _if it is impossible._ + +**Example 1:** + +**Input:** nums = [2,2,0], changeIndices = [2,2,2,2,3,2,2,1] + +**Output:** 8 + +**Explanation:** In this example, we have 8 seconds. The following operations can be performed to mark all indices: + +Second 1: Choose index 1 and decrement nums[1] by one. nums becomes [1,2,0]. + +Second 2: Choose index 1 and decrement nums[1] by one. nums becomes [0,2,0]. + +Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [0,1,0]. + +Second 4: Choose index 2 and decrement nums[2] by one. nums becomes [0,0,0]. + +Second 5: Mark the index changeIndices[5], which is marking index 3, since nums[3] is equal to 0. + +Second 6: Mark the index changeIndices[6], which is marking index 2, since nums[2] is equal to 0. + +Second 7: Do nothing. + +Second 8: Mark the index changeIndices[8], which is marking index 1, since nums[1] is equal to 0. + +Now all indices have been marked. + +It can be shown that it is not possible to mark all indices earlier than the 8th second. + +Hence, the answer is 8. + +**Example 2:** + +**Input:** nums = [1,3], changeIndices = [1,1,1,2,1,1,1] + +**Output:** 6 + +**Explanation:** In this example, we have 7 seconds. The following operations can be performed to mark all indices: + +Second 1: Choose index 2 and decrement nums[2] by one. nums becomes [1,2]. + +Second 2: Choose index 2 and decrement nums[2] by one. nums becomes [1,1]. + +Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [1,0]. + +Second 4: Mark the index changeIndices[4], which is marking index 2, since nums[2] is equal to 0. + +Second 5: Choose index 1 and decrement nums[1] by one. nums becomes [0,0]. + +Second 6: Mark the index changeIndices[6], which is marking index 1, since nums[1] is equal to 0. + +Now all indices have been marked. + +It can be shown that it is not possible to mark all indices earlier than the 6th second. + +Hence, the answer is 6. + +**Example 3:** + +**Input:** nums = [0,1], changeIndices = [2,2,2] + +**Output:** -1 + +**Explanation:** In this example, it is impossible to mark all indices because index 1 isn't in changeIndices. Hence, the answer is -1. + +**Constraints:** + +* `1 <= n == nums.length <= 2000` +* 0 <= nums[i] <= 109 +* `1 <= m == changeIndices.length <= 2000` +* `1 <= changeIndices[i] <= n` + +## Solution + +```kotlin +class Solution { + fun earliestSecondToMarkIndices(nums: IntArray, changeIndices: IntArray): Int { + val n = nums.size + if (nums.isEmpty() || changeIndices.isEmpty()) { + return 0 + } + val last = IntArray(n) + last.fill(-1) + for (i in changeIndices.indices) { + changeIndices[i] -= 1 + } + var low = 0 + var high = changeIndices.size - 1 + while (low < high) { + val mid = low + (high - low) / 2 + if (isPossible(mid, nums, changeIndices, last)) { + high = mid + } else { + low = mid + 1 + } + } + return if (isPossible(low, nums, changeIndices, last)) low + 1 else -1 + } + + private fun isPossible(s: Int, nums: IntArray, changeIndices: IntArray, last: IntArray): Boolean { + val n = nums.size + last.fill(-1) + for (i in 0..s) { + last[changeIndices[i]] = i + } + var marked = 0 + var operations = 0 + for (i in 0..s) { + if (i == last[changeIndices[i]]) { + if (nums[changeIndices[i]] > operations) { + return false + } + operations -= nums[changeIndices[i]] + marked++ + } else { + operations++ + } + } + return marked == n + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g3001_3100/s3049_earliest_second_to_mark_indices_ii/readme.md b/src/main/kotlin/g3001_3100/s3049_earliest_second_to_mark_indices_ii/readme.md new file mode 100644 index 00000000..378637f2 --- /dev/null +++ b/src/main/kotlin/g3001_3100/s3049_earliest_second_to_mark_indices_ii/readme.md @@ -0,0 +1,157 @@ +[![](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) + +## 3049\. Earliest Second to Mark Indices II + +Hard + +You are given two **1-indexed** integer arrays, `nums` and, `changeIndices`, having lengths `n` and `m`, respectively. + +Initially, all indices in `nums` are unmarked. Your task is to mark **all** indices in `nums`. + +In each second, `s`, in order from `1` to `m` (**inclusive**), you can perform **one** of the following operations: + +* Choose an index `i` in the range `[1, n]` and **decrement** `nums[i]` by `1`. +* Set `nums[changeIndices[s]]` to any **non-negative** value. +* Choose an index `i` in the range `[1, n]`, where `nums[i]` is **equal** to `0`, and **mark** index `i`. +* Do nothing. + +Return _an integer denoting the **earliest second** in the range_ `[1, m]` _when **all** indices in_ `nums` _can be marked by choosing operations optimally, or_ `-1` _if it is impossible._ + +**Example 1:** + +**Input:** nums = [3,2,3], changeIndices = [1,3,2,2,2,2,3] + +**Output:** 6 + +**Explanation:** In this example, we have 7 seconds. The following operations can be performed to mark all indices: + +Second 1: Set nums[changeIndices[1]] to 0. nums becomes [0,2,3]. + +Second 2: Set nums[changeIndices[2]] to 0. nums becomes [0,2,0]. + +Second 3: Set nums[changeIndices[3]] to 0. nums becomes [0,0,0]. + +Second 4: Mark index 1, since nums[1] is equal to 0. + +Second 5: Mark index 2, since nums[2] is equal to 0. + +Second 6: Mark index 3, since nums[3] is equal to 0. + +Now all indices have been marked. + +It can be shown that it is not possible to mark all indices earlier than the 6th second. + +Hence, the answer is 6. + +**Example 2:** + +**Input:** nums = [0,0,1,2], changeIndices = [1,2,1,2,1,2,1,2] + +**Output:** 7 + +**Explanation:** In this example, we have 8 seconds. The following operations can be performed to mark all indices: + +Second 1: Mark index 1, since nums[1] is equal to 0. + +Second 2: Mark index 2, since nums[2] is equal to 0. + +Second 3: Decrement index 4 by one. nums becomes [0,0,1,1]. + +Second 4: Decrement index 4 by one. nums becomes [0,0,1,0]. + +Second 5: Decrement index 3 by one. nums becomes [0,0,0,0]. + +Second 6: Mark index 3, since nums[3] is equal to 0. + +Second 7: Mark index 4, since nums[4] is equal to 0. + +Now all indices have been marked. + +It can be shown that it is not possible to mark all indices earlier than the 7th second. + +Hence, the answer is 7. + +**Example 3:** + +**Input:** nums = [1,2,3], changeIndices = [1,2,3] + +**Output:** -1 + +**Explanation:** In this example, it can be shown that it is impossible to mark all indices, as we don't have enough seconds. Hence, the answer is -1. + +**Constraints:** + +* `1 <= n == nums.length <= 5000` +* 0 <= nums[i] <= 109 +* `1 <= m == changeIndices.length <= 5000` +* `1 <= changeIndices[i] <= n` + +## Solution + +```kotlin +import java.util.PriorityQueue +import java.util.Queue +import kotlin.math.min + +class Solution { + private lateinit var nums: IntArray + private lateinit var changeIndices: IntArray + private lateinit var first: BooleanArray + private var sum: Long = 0 + + fun earliestSecondToMarkIndices(nums: IntArray, changeIndices: IntArray): Int { + val m = changeIndices.size + val n = nums.size + if (m < n) { + return -1 + } + this.nums = nums + this.changeIndices = changeIndices + val set: MutableSet = HashSet() + first = BooleanArray(m) + for (i in 0 until m) { + if (nums[changeIndices[i] - 1] > 1 && set.add(changeIndices[i])) { + first[i] = true + } + } + for (num in nums) { + sum += num.toLong() + } + sum += n.toLong() + var l = n + var r = (min(sum.toInt(), m)) + 1 + while (l < r) { + val mid = (l + r) / 2 + if (check(mid)) { + r = mid + } else { + l = mid + 1 + } + } + return if (l > min(sum.toInt(), m)) -1 else l + } + + private fun check(idx: Int): Boolean { + val pq: Queue = PriorityQueue() + var need = sum + var count = 0 + var i = idx - 1 + while (i >= 0 && need > idx) { + if (!first[i]) { + count++ + i-- + continue + } + pq.add(nums[changeIndices[i] - 1]) + need -= (nums[changeIndices[i] - 1] - 1).toLong() + if (pq.size > count) { + need += (pq.poll() - 1).toLong() + count++ + } + i-- + } + return need <= idx + } +} +``` \ No newline at end of file