diff --git a/README.md b/README.md index b1a6f4c7..ee21d0b8 100644 --- a/README.md +++ b/README.md @@ -585,6 +585,7 @@ |-|-|-|-|-|- | 0155 |[Min Stack](src/main/kotlin/g0101_0200/s0155_min_stack)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Stack, Design | 331 | 84.88 | 1249 |[Minimum Remove to Make Valid Parentheses](src/main/kotlin/g1201_1300/s1249_minimum_remove_to_make_valid_parentheses)| Medium | String, Stack | 218 | 100.00 +| 1823 |[Find the Winner of the Circular Game](src/main/kotlin/g1801_1900/s1823_find_the_winner_of_the_circular_game)| Medium | Array, Math, Simulation, Recursion, Queue | 119 | 87.50 #### Day 15 Tree @@ -971,6 +972,7 @@ | | | | | | |-|-|-|-|-|- +| 1855 |[Maximum Distance Between a Pair of Values](src/main/kotlin/g1801_1900/s1855_maximum_distance_between_a_pair_of_values)| Medium | Array, Greedy, Binary_Search, Two_Pointers | 541 | 14.29 | 0033 |[Search in Rotated Sorted Array](src/main/kotlin/g0001_0100/s0033_search_in_rotated_sorted_array)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Binary_Search | 184 | 86.08 #### Day 12 @@ -993,6 +995,7 @@ | | | | | | |-|-|-|-|-|- | 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 @@ -1019,12 +1022,15 @@ | | | | | | |-|-|-|-|-|- +| 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 @@ -1037,6 +1043,7 @@ | | | | | | |-|-|-|-|-|- +| 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 @@ -1092,6 +1099,8 @@ | | | | | | |-|-|-|-|-|- +| 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 @@ -1294,6 +1303,7 @@ | | | | | | |-|-|-|-|-|- +| 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 @@ -1411,6 +1421,7 @@ | | | | | | |-|-|-|-|-|- | 0048 |[Rotate Image](src/main/kotlin/g0001_0100/s0048_rotate_image)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Matrix | 287 | 46.50 +| 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 @@ -1479,6 +1490,7 @@ | | | | | | |-|-|-|-|-|- +| 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 @@ -1524,6 +1536,7 @@ | | | | | | |-|-|-|-|-|- | 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 @@ -1544,6 +1557,7 @@ | | | | | | |-|-|-|-|-|- | 0934 |[Shortest Bridge](src/main/kotlin/g0901_1000/s0934_shortest_bridge)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix | 301 | 80.95 +| 1926 |[Nearest Exit from Entrance in Maze](src/main/kotlin/g1901_2000/s1926_nearest_exit_from_entrance_in_maze)| Medium | Array, Breadth_First_Search, Matrix | 351 | 94.44 #### Day 7 Standard Traversal @@ -1620,6 +1634,7 @@ | | | | | | |-|-|-|-|-|- +| 1873 |[Calculate Special Bonus](src/main/kotlin/g1801_1900/s1873_calculate_special_bonus)| Easy | Database | 1321 | 33.12 | 0627 |[Swap Salary](src/main/kotlin/g0601_0700/s0627_swap_salary)| Easy | Database | 400 | 51.04 | 0196 |[Delete Duplicate Emails](src/main/kotlin/g0101_0200/s0196_delete_duplicate_emails)| Easy | Database | 593 | 94.17 @@ -1635,6 +1650,7 @@ | | | | | | |-|-|-|-|-|- +| 1965 |[Employees With Missing Information](src/main/kotlin/g1901_2000/s1965_employees_with_missing_information)| Easy | Database | 1355 | 23.96 | 1795 |[Rearrange Products Table](src/main/kotlin/g1701_1800/s1795_rearrange_products_table)| Easy | Database | 1027 | 67.57 | 0608 |[Tree Node](src/main/kotlin/g0601_0700/s0608_tree_node)| Medium | LeetCode_Curated_SQL_70, Database | 794 | 48.38 | 0176 |[Second Highest Salary](src/main/kotlin/g0101_0200/s0176_second_highest_salary)| Medium | Database | 219 | 92.54 @@ -1668,6 +1684,7 @@ |-|-|-|-|-|- | 0586 |[Customer Placing the Largest Number of Orders](src/main/kotlin/g0501_0600/s0586_customer_placing_the_largest_number_of_orders)| Easy | LeetCode_Curated_SQL_70, Database | 768 | 44.85 | 0511 |[Game Play Analysis I](src/main/kotlin/g0501_0600/s0511_game_play_analysis_i)| Easy | LeetCode_Curated_SQL_70, Database | 790 | 45.04 +| 1890 |[The Latest Login in 2020](src/main/kotlin/g1801_1900/s1890_the_latest_login_in_2020)| Easy | Database | 1486 | 22.18 | 1741 |[Find Total Time Spent by Each Employee](src/main/kotlin/g1701_1800/s1741_find_total_time_spent_by_each_employee)| Easy | Database | 1101 | 51.40 #### Day 9 Control of Flow @@ -1798,6 +1815,194 @@ | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- +| 2050 |[Parallel Courses III](src/main/kotlin/g2001_2100/s2050_parallel_courses_iii)| Hard | Dynamic_Programming, Graph, Topological_Sort | 974 | 100.00 +| 2049 |[Count Nodes With the Highest Score](src/main/kotlin/g2001_2100/s2049_count_nodes_with_the_highest_score)| Medium | Array, Depth_First_Search, Tree, Binary_Tree | 483 | 100.00 +| 2048 |[Next Greater Numerically Balanced Number](src/main/kotlin/g2001_2100/s2048_next_greater_numerically_balanced_number)| Medium | Math, Backtracking, Enumeration | 138 | 100.00 +| 2047 |[Number of Valid Words in a Sentence](src/main/kotlin/g2001_2100/s2047_number_of_valid_words_in_a_sentence)| Easy | String | 202 | 100.00 +| 2045 |[Second Minimum Time to Reach Destination](src/main/kotlin/g2001_2100/s2045_second_minimum_time_to_reach_destination)| Hard | Breadth_First_Search, Graph, Shortest_Path | 862 | 100.00 +| 2044 |[Count Number of Maximum Bitwise-OR Subsets](src/main/kotlin/g2001_2100/s2044_count_number_of_maximum_bitwise_or_subsets)| Medium | Array, Bit_Manipulation, Backtracking | 140 | 100.00 +| 2043 |[Simple Bank System](src/main/kotlin/g2001_2100/s2043_simple_bank_system)| Medium | Array, Hash_Table, Design, Simulation | 968 | 100.00 +| 2042 |[Check if Numbers Are Ascending in a Sentence](src/main/kotlin/g2001_2100/s2042_check_if_numbers_are_ascending_in_a_sentence)| Easy | String | 161 | 64.29 +| 2040 |[Kth Smallest Product of Two Sorted Arrays](src/main/kotlin/g2001_2100/s2040_kth_smallest_product_of_two_sorted_arrays)| Hard | Array, Binary_Search | 1001 | 100.00 +| 2039 |[The Time When the Network Becomes Idle](src/main/kotlin/g2001_2100/s2039_the_time_when_the_network_becomes_idle)| Medium | Array, Breadth_First_Search, Graph | 1197 | 100.00 +| 2038 |[Remove Colored Pieces if Both Neighbors are the Same Color](src/main/kotlin/g2001_2100/s2038_remove_colored_pieces_if_both_neighbors_are_the_same_color)| Medium | String, Math, Greedy, Game_Theory | 251 | 22.22 +| 2037 |[Minimum Number of Moves to Seat Everyone](src/main/kotlin/g2001_2100/s2037_minimum_number_of_moves_to_seat_everyone)| Easy | Array, Sorting | 189 | 80.00 +| 2035 |[Partition Array Into Two Arrays to Minimize Sum Difference](src/main/kotlin/g2001_2100/s2035_partition_array_into_two_arrays_to_minimize_sum_difference)| Hard | Array, Dynamic_Programming, Binary_Search, Two_Pointers, Bit_Manipulation, Ordered_Set, Bitmask | 1318 | 100.00 +| 2034 |[Stock Price Fluctuation](src/main/kotlin/g2001_2100/s2034_stock_price_fluctuation)| Medium | Hash_Table, Design, Heap_Priority_Queue, Ordered_Set, Data_Stream | 985 | 100.00 +| 2033 |[Minimum Operations to Make a Uni-Value Grid](src/main/kotlin/g2001_2100/s2033_minimum_operations_to_make_a_uni_value_grid)| Medium | Array, Math, Sorting, Matrix | 744 | 100.00 +| 2032 |[Two Out of Three](src/main/kotlin/g2001_2100/s2032_two_out_of_three)| Easy | Array, Hash_Table | 251 | 83.33 +| 2030 |[Smallest K-Length Subsequence With Occurrences of a Letter](src/main/kotlin/g2001_2100/s2030_smallest_k_length_subsequence_with_occurrences_of_a_letter)| Hard | String, Greedy, Stack, Monotonic_Stack | 501 | 100.00 +| 2029 |[Stone Game IX](src/main/kotlin/g2001_2100/s2029_stone_game_ix)| Medium | Array, Math, Greedy, Counting, Game_Theory | 574 | 100.00 +| 2028 |[Find Missing Observations](src/main/kotlin/g2001_2100/s2028_find_missing_observations)| Medium | Array, Math, Simulation | 654 | 33.33 +| 2027 |[Minimum Moves to Convert String](src/main/kotlin/g2001_2100/s2027_minimum_moves_to_convert_string)| Easy | String, Greedy | 142 | 100.00 +| 2025 |[Maximum Number of Ways to Partition an Array](src/main/kotlin/g2001_2100/s2025_maximum_number_of_ways_to_partition_an_array)| Hard | Array, Hash_Table, Prefix_Sum, Counting, Enumeration | 1163 | 100.00 +| 2024 |[Maximize the Confusion of an Exam](src/main/kotlin/g2001_2100/s2024_maximize_the_confusion_of_an_exam)| Medium | String, Binary_Search, Prefix_Sum, Sliding_Window | 223 | 83.33 +| 2023 |[Number of Pairs of Strings With Concatenation Equal to Target](src/main/kotlin/g2001_2100/s2023_number_of_pairs_of_strings_with_concatenation_equal_to_target)| Medium | Array, String | 228 | 40.00 +| 2022 |[Convert 1D Array Into 2D Array](src/main/kotlin/g2001_2100/s2022_convert_1d_array_into_2d_array)| Easy | Array, Matrix, Simulation | 631 | 100.00 +| 2019 |[The Score of Students Solving Math Expression](src/main/kotlin/g2001_2100/s2019_the_score_of_students_solving_math_expression)| Hard | Array, String, Dynamic_Programming, Math, Stack, Memoization | 1497 | 100.00 +| 2018 |[Check if Word Can Be Placed In Crossword](src/main/kotlin/g2001_2100/s2018_check_if_word_can_be_placed_in_crossword)| Medium | Array, Matrix, Enumeration | 698 | 100.00 +| 2017 |[Grid Game](src/main/kotlin/g2001_2100/s2017_grid_game)| Medium | Array, Matrix, Prefix_Sum | 578 | 87.50 +| 2016 |[Maximum Difference Between Increasing Elements](src/main/kotlin/g2001_2100/s2016_maximum_difference_between_increasing_elements)| Easy | Array | 140 | 100.00 +| 2014 |[Longest Subsequence Repeated k Times](src/main/kotlin/g2001_2100/s2014_longest_subsequence_repeated_k_times)| Hard | String, Greedy, Backtracking, Counting, Enumeration | 333 | 100.00 +| 2013 |[Detect Squares](src/main/kotlin/g2001_2100/s2013_detect_squares)| Medium | Array, Hash_Table, Design, Counting | 511 | 100.00 +| 2012 |[Sum of Beauty in the Array](src/main/kotlin/g2001_2100/s2012_sum_of_beauty_in_the_array)| Medium | Array | 511 | 100.00 +| 2011 |[Final Value of Variable After Performing Operations](src/main/kotlin/g2001_2100/s2011_final_value_of_variable_after_performing_operations)| Easy | Array, String, Simulation | 178 | 44.55 +| 2000 |[Reverse Prefix of Word](src/main/kotlin/g1901_2000/s2000_reverse_prefix_of_word)| Easy | String, Two_Pointers | 164 | 31.25 +| 1998 |[GCD Sort of an Array](src/main/kotlin/g1901_2000/s1998_gcd_sort_of_an_array)| Hard | Array, Math, Sorting, Union_Find | 437 | 100.00 +| 1997 |[First Day Where You Have Been in All the Rooms](src/main/kotlin/g1901_2000/s1997_first_day_where_you_have_been_in_all_the_rooms)| Medium | Array, Dynamic_Programming | 572 | 100.00 +| 1996 |[The Number of Weak Characters in the Game](src/main/kotlin/g1901_2000/s1996_the_number_of_weak_characters_in_the_game)| Medium | Array, Sorting, Greedy, Stack, Monotonic_Stack | 1234 | 100.00 +| 1995 |[Count Special Quadruplets](src/main/kotlin/g1901_2000/s1995_count_special_quadruplets)| Easy | Array, Enumeration | 146 | 100.00 +| 1994 |[The Number of Good Subsets](src/main/kotlin/g1901_2000/s1994_the_number_of_good_subsets)| Hard | Array, Dynamic_Programming, Math, Bit_Manipulation, Bitmask | 737 | 100.00 +| 1993 |[Operations on Tree](src/main/kotlin/g1901_2000/s1993_operations_on_tree)| Medium | Hash_Table, Depth_First_Search, Breadth_First_Search, Tree, Design | 1117 | 100.00 +| 1992 |[Find All Groups of Farmland](src/main/kotlin/g1901_2000/s1992_find_all_groups_of_farmland)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix | 768 | 100.00 +| 1991 |[Find the Middle Index in Array](src/main/kotlin/g1901_2000/s1991_find_the_middle_index_in_array)| Easy | Array, Prefix_Sum | 142 | 100.00 +| 1987 |[Number of Unique Good Subsequences](src/main/kotlin/g1901_2000/s1987_number_of_unique_good_subsequences)| Hard | String, Dynamic_Programming | 248 | 100.00 +| 1986 |[Minimum Number of Work Sessions to Finish the Tasks](src/main/kotlin/g1901_2000/s1986_minimum_number_of_work_sessions_to_finish_the_tasks)| Medium | Array, Dynamic_Programming, Bit_Manipulation, Backtracking, Bitmask | 153 | 100.00 +| 1985 |[Find the Kth Largest Integer in the Array](src/main/kotlin/g1901_2000/s1985_find_the_kth_largest_integer_in_the_array)| Medium | Array, String, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Quickselect | 397 | 100.00 +| 1984 |[Minimum Difference Between Highest and Lowest of K Scores](src/main/kotlin/g1901_2000/s1984_minimum_difference_between_highest_and_lowest_of_k_scores)| Easy | Array, Sorting, Sliding_Window | 227 | 83.33 +| 1982 |[Find Array Given Subset Sums](src/main/kotlin/g1901_2000/s1982_find_array_given_subset_sums)| Hard | Array, Divide_and_Conquer | 640 | 100.00 +| 1981 |[Minimize the Difference Between Target and Chosen Elements](src/main/kotlin/g1901_2000/s1981_minimize_the_difference_between_target_and_chosen_elements)| Medium | Array, Dynamic_Programming, Matrix | 588 | 100.00 +| 1980 |[Find Unique Binary String](src/main/kotlin/g1901_2000/s1980_find_unique_binary_string)| Medium | Array, String, Backtracking | 186 | 50.00 +| 1979 |[Find Greatest Common Divisor of Array](src/main/kotlin/g1901_2000/s1979_find_greatest_common_divisor_of_array)| Easy | Array, Math, Number_Theory | 172 | 100.00 +| 1977 |[Number of Ways to Separate Numbers](src/main/kotlin/g1901_2000/s1977_number_of_ways_to_separate_numbers)| Hard | String, Dynamic_Programming, Suffix_Array | 199 | 100.00 +| 1976 |[Number of Ways to Arrive at Destination](src/main/kotlin/g1901_2000/s1976_number_of_ways_to_arrive_at_destination)| Medium | Dynamic_Programming, Graph, Topological_Sort, Shortest_Path | 282 | 100.00 +| 1975 |[Maximum Matrix Sum](src/main/kotlin/g1901_2000/s1975_maximum_matrix_sum)| Medium | Array, Greedy, Matrix | 535 | 100.00 +| 1974 |[Minimum Time to Type Word Using Special Typewriter](src/main/kotlin/g1901_2000/s1974_minimum_time_to_type_word_using_special_typewriter)| Easy | String, Greedy | 139 | 71.43 +| 1971 |[Find if Path Exists in Graph](src/main/kotlin/g1901_2000/s1971_find_if_path_exists_in_graph)| Easy | Depth_First_Search, Breadth_First_Search, Graph | 949 | 86.89 +| 1970 |[Last Day Where You Can Still Cross](src/main/kotlin/g1901_2000/s1970_last_day_where_you_can_still_cross)| Hard | Array, Depth_First_Search, Breadth_First_Search, Binary_Search, Matrix, Union_Find | 703 | 100.00 +| 1969 |[Minimum Non-Zero Product of the Array Elements](src/main/kotlin/g1901_2000/s1969_minimum_non_zero_product_of_the_array_elements)| Medium | Math, Greedy, Recursion | 131 | 100.00 +| 1968 |[Array With Elements Not Equal to Average of Neighbors](src/main/kotlin/g1901_2000/s1968_array_with_elements_not_equal_to_average_of_neighbors)| Medium | Array, Sorting, Greedy | 973 | 83.33 +| 1967 |[Number of Strings That Appear as Substrings in Word](src/main/kotlin/g1901_2000/s1967_number_of_strings_that_appear_as_substrings_in_word)| Easy | String | 157 | 100.00 +| 1965 |[Employees With Missing Information](src/main/kotlin/g1901_2000/s1965_employees_with_missing_information)| Easy | Database, SQL_I_Day_4_Union_and_Select | 1355 | 23.96 +| 1964 |[Find the Longest Valid Obstacle Course at Each Position](src/main/kotlin/g1901_2000/s1964_find_the_longest_valid_obstacle_course_at_each_position)| Hard | Array, Binary_Search, Binary_Indexed_Tree | 846 | 40.00 +| 1963 |[Minimum Number of Swaps to Make the String Balanced](src/main/kotlin/g1901_2000/s1963_minimum_number_of_swaps_to_make_the_string_balanced)| Medium | String, Greedy, Two_Pointers, Stack | 291 | 53.85 +| 1962 |[Remove Stones to Minimize the Total](src/main/kotlin/g1901_2000/s1962_remove_stones_to_minimize_the_total)| Medium | Array, Heap_Priority_Queue | 888 | 68.42 +| 1961 |[Check If String Is a Prefix of Array](src/main/kotlin/g1901_2000/s1961_check_if_string_is_a_prefix_of_array)| Easy | Array, String | 162 | 100.00 +| 1960 |[Maximum Product of the Length of Two Palindromic Substrings](src/main/kotlin/g1901_2000/s1960_maximum_product_of_the_length_of_two_palindromic_substrings)| Hard | String, Hash_Function, Rolling_Hash | 247 | 100.00 +| 1959 |[Minimum Total Space Wasted With K Resizing Operations](src/main/kotlin/g1901_2000/s1959_minimum_total_space_wasted_with_k_resizing_operations)| Medium | Array, Dynamic_Programming | 225 | 100.00 +| 1958 |[Check if Move is Legal](src/main/kotlin/g1901_2000/s1958_check_if_move_is_legal)| Medium | Array, Matrix, Enumeration | 169 | 100.00 +| 1957 |[Delete Characters to Make Fancy String](src/main/kotlin/g1901_2000/s1957_delete_characters_to_make_fancy_string)| Easy | String | 377 | 50.00 +| 1955 |[Count Number of Special Subsequences](src/main/kotlin/g1901_2000/s1955_count_number_of_special_subsequences)| Hard | Array, Dynamic_Programming | 620 | 100.00 +| 1954 |[Minimum Garden Perimeter to Collect Enough Apples](src/main/kotlin/g1901_2000/s1954_minimum_garden_perimeter_to_collect_enough_apples)| Medium | Math, Binary_Search | 132 | 100.00 +| 1953 |[Maximum Number of Weeks for Which You Can Work](src/main/kotlin/g1901_2000/s1953_maximum_number_of_weeks_for_which_you_can_work)| Medium | Array, Greedy | 461 | 100.00 +| 1952 |[Three Divisors](src/main/kotlin/g1901_2000/s1952_three_divisors)| Easy | Math | 141 | 33.33 +| 1948 |[Delete Duplicate Folders in System](src/main/kotlin/g1901_2000/s1948_delete_duplicate_folders_in_system)| Hard | Array, String, Hash_Table, Trie, Hash_Function | 1420 | 100.00 +| 1947 |[Maximum Compatibility Score Sum](src/main/kotlin/g1901_2000/s1947_maximum_compatibility_score_sum)| Medium | Array, Dynamic_Programming, Bit_Manipulation, Backtracking, Bitmask | 179 | 100.00 +| 1946 |[Largest Number After Mutating Substring](src/main/kotlin/g1901_2000/s1946_largest_number_after_mutating_substring)| Medium | Array, String, Greedy | 346 | 100.00 +| 1945 |[Sum of Digits of String After Convert](src/main/kotlin/g1901_2000/s1945_sum_of_digits_of_string_after_convert)| Easy | String, Simulation | 146 | 75.00 +| 1944 |[Number of Visible People in a Queue](src/main/kotlin/g1901_2000/s1944_number_of_visible_people_in_a_queue)| Hard | Array, Stack, Monotonic_Stack | 605 | 90.00 +| 1943 |[Describe the Painting](src/main/kotlin/g1901_2000/s1943_describe_the_painting)| Medium | Array, Prefix_Sum | 951 | 100.00 +| 1942 |[The Number of the Smallest Unoccupied Chair](src/main/kotlin/g1901_2000/s1942_the_number_of_the_smallest_unoccupied_chair)| Medium | Array, Heap_Priority_Queue, Ordered_Set | 549 | 100.00 +| 1941 |[Check if All Characters Have Equal Number of Occurrences](src/main/kotlin/g1901_2000/s1941_check_if_all_characters_have_equal_number_of_occurrences)| Easy | String, Hash_Table, Counting | 167 | 78.57 +| 1938 |[Maximum Genetic Difference Query](src/main/kotlin/g1901_2000/s1938_maximum_genetic_difference_query)| Hard | Array, Bit_Manipulation, Trie | 855 | 100.00 +| 1937 |[Maximum Number of Points with Cost](src/main/kotlin/g1901_2000/s1937_maximum_number_of_points_with_cost)| Medium | Array, Dynamic_Programming | 886 | 100.00 +| 1936 |[Add Minimum Number of Rungs](src/main/kotlin/g1901_2000/s1936_add_minimum_number_of_rungs)| Medium | Array, Greedy | 405 | 100.00 +| 1935 |[Maximum Number of Words You Can Type](src/main/kotlin/g1901_2000/s1935_maximum_number_of_words_you_can_type)| Easy | String, Hash_Table | 178 | 37.50 +| 1934 |[Confirmation Rate](src/main/kotlin/g1901_2000/s1934_confirmation_rate)| Medium | Database | 1602 | 35.78 +| 1932 |[Merge BSTs to Create Single BST](src/main/kotlin/g1901_2000/s1932_merge_bsts_to_create_single_bst)| Hard | Hash_Table, Depth_First_Search, Tree, Binary_Search, Binary_Tree | 1146 | 100.00 +| 1931 |[Painting a Grid With Three Different Colors](src/main/kotlin/g1901_2000/s1931_painting_a_grid_with_three_different_colors)| Hard | Dynamic_Programming | 135 | 100.00 +| 1930 |[Unique Length-3 Palindromic Subsequences](src/main/kotlin/g1901_2000/s1930_unique_length_3_palindromic_subsequences)| Medium | String, Hash_Table, Prefix_Sum | 273 | 100.00 +| 1929 |[Concatenation of Array](src/main/kotlin/g1901_2000/s1929_concatenation_of_array)| Easy | Array | 220 | 94.47 +| 1928 |[Minimum Cost to Reach Destination in Time](src/main/kotlin/g1901_2000/s1928_minimum_cost_to_reach_destination_in_time)| Hard | Dynamic_Programming, Graph | 414 | 100.00 +| 1927 |[Sum Game](src/main/kotlin/g1901_2000/s1927_sum_game)| Medium | Math, Greedy, Game_Theory | 211 | 100.00 +| 1926 |[Nearest Exit from Entrance in Maze](src/main/kotlin/g1901_2000/s1926_nearest_exit_from_entrance_in_maze)| Medium | Array, Breadth_First_Search, Matrix, Graph_Theory_I_Day_6_Matrix_Related_Problems | 351 | 94.44 +| 1925 |[Count Square Sum Triples](src/main/kotlin/g1901_2000/s1925_count_square_sum_triples)| Easy | Math, Enumeration | 161 | 40.00 +| 1923 |[Longest Common Subpath](src/main/kotlin/g1901_2000/s1923_longest_common_subpath)| Hard | Array, Binary_Search, Hash_Function, Rolling_Hash, Suffix_Array | 1142 | 100.00 +| 1922 |[Count Good Numbers](src/main/kotlin/g1901_2000/s1922_count_good_numbers)| Medium | Math, Recursion | 135 | 100.00 +| 1921 |[Eliminate Maximum Number of Monsters](src/main/kotlin/g1901_2000/s1921_eliminate_maximum_number_of_monsters)| Medium | Array, Sorting, Greedy | 507 | 100.00 +| 1920 |[Build Array from Permutation](src/main/kotlin/g1901_2000/s1920_build_array_from_permutation)| Easy | Array, Simulation | 252 | 81.25 +| 1916 |[Count Ways to Build Rooms in an Ant Colony](src/main/kotlin/g1901_2000/s1916_count_ways_to_build_rooms_in_an_ant_colony)| Hard | Dynamic_Programming, Math, Tree, Graph, Topological_Sort, Combinatorics | 2564 | 100.00 +| 1915 |[Number of Wonderful Substrings](src/main/kotlin/g1901_2000/s1915_number_of_wonderful_substrings)| Medium | String, Hash_Table, Bit_Manipulation, Prefix_Sum | 267 | 100.00 +| 1914 |[Cyclically Rotating a Grid](src/main/kotlin/g1901_2000/s1914_cyclically_rotating_a_grid)| Medium | Array, Matrix, Simulation | 282 | 100.00 +| 1913 |[Maximum Product Difference Between Two Pairs](src/main/kotlin/g1901_2000/s1913_maximum_product_difference_between_two_pairs)| Easy | Array, Sorting | 261 | 100.00 +| 1912 |[Design Movie Rental System](src/main/kotlin/g1901_2000/s1912_design_movie_rental_system)| Hard | Array, Hash_Table, Design, Heap_Priority_Queue, Ordered_Set | 3005 | 100.00 +| 1911 |[Maximum Alternating Subsequence Sum](src/main/kotlin/g1901_2000/s1911_maximum_alternating_subsequence_sum)| Medium | Array, Dynamic_Programming | 531 | 100.00 +| 1910 |[Remove All Occurrences of a Substring](src/main/kotlin/g1901_2000/s1910_remove_all_occurrences_of_a_substring)| Medium | String | 177 | 100.00 +| 1909 |[Remove One Element to Make the Array Strictly Increasing](src/main/kotlin/g1901_2000/s1909_remove_one_element_to_make_the_array_strictly_increasing)| Easy | Array | 176 | 50.00 +| 1907 |[Count Salary Categories](src/main/kotlin/g1901_2000/s1907_count_salary_categories)| Medium | Database | 2358 | 73.89 +| 1906 |[Minimum Absolute Difference Queries](src/main/kotlin/g1901_2000/s1906_minimum_absolute_difference_queries)| Medium | Array, Hash_Table | 1069 | 50.00 +| 1905 |[Count Sub Islands](src/main/kotlin/g1901_2000/s1905_count_sub_islands)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find, Graph_Theory_I_Day_3_Matrix_Related_Problems | 866 | 100.00 +| 1904 |[The Number of Full Rounds You Have Played](src/main/kotlin/g1901_2000/s1904_the_number_of_full_rounds_you_have_played)| Medium | String, Math | 149 | 100.00 +| 1903 |[Largest Odd Number in String](src/main/kotlin/g1901_2000/s1903_largest_odd_number_in_string)| Easy | String, Math, Greedy | 256 | 75.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, Binary_Search_II_Day_17 | 726 | 100.00 +| 1900 |[The Earliest and Latest Rounds Where Players Compete](src/main/kotlin/g1801_1900/s1900_the_earliest_and_latest_rounds_where_players_compete)| Hard | Dynamic_Programming, Memoization | 142 | 100.00 +| 1899 |[Merge Triplets to Form Target Triplet](src/main/kotlin/g1801_1900/s1899_merge_triplets_to_form_target_triplet)| Medium | Array, Greedy | 954 | 71.43 +| 1898 |[Maximum Number of Removable Characters](src/main/kotlin/g1801_1900/s1898_maximum_number_of_removable_characters)| Medium | Array, String, Binary_Search, Binary_Search_II_Day_6 | 636 | 100.00 +| 1897 |[Redistribute Characters to Make All Strings Equal](src/main/kotlin/g1801_1900/s1897_redistribute_characters_to_make_all_strings_equal)| Easy | String, Hash_Table, Counting | 179 | 100.00 +| 1896 |[Minimum Cost to Change the Final Value of Expression](src/main/kotlin/g1801_1900/s1896_minimum_cost_to_change_the_final_value_of_expression)| Hard | String, Dynamic_Programming, Math, Stack | 252 | 100.00 +| 1895 |[Largest Magic Square](src/main/kotlin/g1801_1900/s1895_largest_magic_square)| Medium | Array, Matrix, Prefix_Sum | 202 | 100.00 +| 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, Binary_Search_II_Day_2 | 520 | 50.00 +| 1893 |[Check if All the Integers in a Range Are Covered](src/main/kotlin/g1801_1900/s1893_check_if_all_the_integers_in_a_range_are_covered)| Easy | Array, Hash_Table, Prefix_Sum | 140 | 100.00 +| 1890 |[The Latest Login in 2020](src/main/kotlin/g1801_1900/s1890_the_latest_login_in_2020)| Easy | Database, SQL_I_Day_8_Function | 1486 | 22.18 +| 1889 |[Minimum Space Wasted From Packaging](src/main/kotlin/g1801_1900/s1889_minimum_space_wasted_from_packaging)| Hard | Array, Sorting, Binary_Search, Prefix_Sum | 910 | 100.00 +| 1888 |[Minimum Number of Flips to Make the Binary String Alternating](src/main/kotlin/g1801_1900/s1888_minimum_number_of_flips_to_make_the_binary_string_alternating)| Medium | String, Greedy | 259 | 87.50 +| 1887 |[Reduction Operations to Make the Array Elements Equal](src/main/kotlin/g1801_1900/s1887_reduction_operations_to_make_the_array_elements_equal)| Medium | Array, Sorting | 457 | 100.00 +| 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, Programming_Skills_II_Day_7 | 147 | 85.71 +| 1884 |[Egg Drop With 2 Eggs and N Floors](src/main/kotlin/g1801_1900/s1884_egg_drop_with_2_eggs_and_n_floors)| Medium | Dynamic_Programming, Math | 130 | 100.00 +| 1883 |[Minimum Skips to Arrive at Meeting On Time](src/main/kotlin/g1801_1900/s1883_minimum_skips_to_arrive_at_meeting_on_time)| Hard | Array, Dynamic_Programming | 278 | 100.00 +| 1882 |[Process Tasks Using Servers](src/main/kotlin/g1801_1900/s1882_process_tasks_using_servers)| Medium | Array, Heap_Priority_Queue | 1085 | 100.00 +| 1881 |[Maximum Value after Insertion](src/main/kotlin/g1801_1900/s1881_maximum_value_after_insertion)| Medium | String, Greedy | 362 | 100.00 +| 1880 |[Check if Word Equals Summation of Two Words](src/main/kotlin/g1801_1900/s1880_check_if_word_equals_summation_of_two_words)| Easy | String | 139 | 80.00 +| 1879 |[Minimum XOR Sum of Two Arrays](src/main/kotlin/g1801_1900/s1879_minimum_xor_sum_of_two_arrays)| Hard | Array, Dynamic_Programming, Bit_Manipulation, Bitmask | 173 | 100.00 +| 1878 |[Get Biggest Three Rhombus Sums in a Grid](src/main/kotlin/g1801_1900/s1878_get_biggest_three_rhombus_sums_in_a_grid)| Medium | Array, Math, Sorting, Matrix, Heap_Priority_Queue, Prefix_Sum | 326 | 100.00 +| 1877 |[Minimize Maximum Pair Sum in Array](src/main/kotlin/g1801_1900/s1877_minimize_maximum_pair_sum_in_array)| Medium | Array, Sorting, Greedy, Two_Pointers | 668 | 50.00 +| 1876 |[Substrings of Size Three with Distinct Characters](src/main/kotlin/g1801_1900/s1876_substrings_of_size_three_with_distinct_characters)| Easy | String, Hash_Table, Counting, Sliding_Window | 144 | 91.67 +| 1873 |[Calculate Special Bonus](src/main/kotlin/g1801_1900/s1873_calculate_special_bonus)| Easy | Database, SQL_I_Day_2_Select_and_Order | 1321 | 33.12 +| 1872 |[Stone Game VIII](src/main/kotlin/g1801_1900/s1872_stone_game_viii)| Hard | Array, Dynamic_Programming, Math, Prefix_Sum, Game_Theory | 569 | 100.00 +| 1871 |[Jump Game VII](src/main/kotlin/g1801_1900/s1871_jump_game_vii)| Medium | String, Two_Pointers, Prefix_Sum | 247 | 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, Binary_Search_II_Day_6 | 628 | 50.00 +| 1869 |[Longer Contiguous Segments of Ones than Zeros](src/main/kotlin/g1801_1900/s1869_longer_contiguous_segments_of_ones_than_zeros)| Easy | String | 118 | 100.00 +| 1866 |[Number of Ways to Rearrange Sticks With K Sticks Visible](src/main/kotlin/g1801_1900/s1866_number_of_ways_to_rearrange_sticks_with_k_sticks_visible)| Hard | Dynamic_Programming, Math, Combinatorics | 188 | 100.00 +| 1865 |[Finding Pairs With a Certain Sum](src/main/kotlin/g1801_1900/s1865_finding_pairs_with_a_certain_sum)| Medium | Array, Hash_Table, Design | 1050 | 100.00 +| 1864 |[Minimum Number of Swaps to Make the Binary String Alternating](src/main/kotlin/g1801_1900/s1864_minimum_number_of_swaps_to_make_the_binary_string_alternating)| Medium | String, Greedy | 140 | 100.00 +| 1863 |[Sum of All Subset XOR Totals](src/main/kotlin/g1801_1900/s1863_sum_of_all_subset_xor_totals)| Easy | Array, Math, Bit_Manipulation, Backtracking, Combinatorics | 128 | 80.00 +| 1862 |[Sum of Floored Pairs](src/main/kotlin/g1801_1900/s1862_sum_of_floored_pairs)| Hard | Array, Math, Binary_Search, Prefix_Sum | 710 | 100.00 +| 1861 |[Rotating the Box](src/main/kotlin/g1801_1900/s1861_rotating_the_box)| Medium | Array, Matrix, Two_Pointers | 882 | 60.00 +| 1860 |[Incremental Memory Leak](src/main/kotlin/g1801_1900/s1860_incremental_memory_leak)| Medium | Simulation | 161 | 100.00 +| 1859 |[Sorting the Sentence](src/main/kotlin/g1801_1900/s1859_sorting_the_sentence)| Easy | String, Sorting | 155 | 89.29 +| 1857 |[Largest Color Value in a Directed Graph](src/main/kotlin/g1801_1900/s1857_largest_color_value_in_a_directed_graph)| Hard | Hash_Table, Dynamic_Programming, Graph, Counting, Memoization, Topological_Sort | 1308 | 20.00 +| 1856 |[Maximum Subarray Min-Product](src/main/kotlin/g1801_1900/s1856_maximum_subarray_min_product)| Medium | Array, Stack, Prefix_Sum, Monotonic_Stack | 517 | 66.67 +| 1855 |[Maximum Distance Between a Pair of Values](src/main/kotlin/g1801_1900/s1855_maximum_distance_between_a_pair_of_values)| Medium | Array, Greedy, Binary_Search, Two_Pointers, Binary_Search_I_Day_11 | 541 | 14.29 +| 1854 |[Maximum Population Year](src/main/kotlin/g1801_1900/s1854_maximum_population_year)| Easy | Array, Counting | 148 | 90.00 +| 1851 |[Minimum Interval to Include Each Query](src/main/kotlin/g1801_1900/s1851_minimum_interval_to_include_each_query)| Hard | Array, Sorting, Binary_Search, Heap_Priority_Queue, Line_Sweep | 1612 | 87.50 +| 1850 |[Minimum Adjacent Swaps to Reach the Kth Smallest Number](src/main/kotlin/g1801_1900/s1850_minimum_adjacent_swaps_to_reach_the_kth_smallest_number)| Medium | String, Greedy, Two_Pointers | 193 | 100.00 +| 1849 |[Splitting a String Into Descending Consecutive Values](src/main/kotlin/g1801_1900/s1849_splitting_a_string_into_descending_consecutive_values)| Medium | String, Backtracking | 136 | 100.00 +| 1848 |[Minimum Distance to the Target Element](src/main/kotlin/g1801_1900/s1848_minimum_distance_to_the_target_element)| Easy | Array | 172 | 80.00 +| 1847 |[Closest Room](src/main/kotlin/g1801_1900/s1847_closest_room)| Hard | Array, Sorting, Binary_Search | 1179 | 100.00 +| 1846 |[Maximum Element After Decreasing and Rearranging](src/main/kotlin/g1801_1900/s1846_maximum_element_after_decreasing_and_rearranging)| Medium | Array, Sorting, Greedy | 412 | 100.00 +| 1845 |[Seat Reservation Manager](src/main/kotlin/g1801_1900/s1845_seat_reservation_manager)| Medium | Design, Heap_Priority_Queue, Programming_Skills_II_Day_17 | 834 | 100.00 +| 1844 |[Replace All Digits with Characters](src/main/kotlin/g1801_1900/s1844_replace_all_digits_with_characters)| Easy | String | 137 | 100.00 +| 1840 |[Maximum Building Height](src/main/kotlin/g1801_1900/s1840_maximum_building_height)| Hard | Array, Math | 1210 | 100.00 +| 1839 |[Longest Substring Of All Vowels in Order](src/main/kotlin/g1801_1900/s1839_longest_substring_of_all_vowels_in_order)| Medium | String, Sliding_Window | 290 | 80.00 +| 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, Binary_Search_II_Day_9 | 564 | 88.89 +| 1837 |[Sum of Digits in Base K](src/main/kotlin/g1801_1900/s1837_sum_of_digits_in_base_k)| Easy | Math | 120 | 100.00 +| 1835 |[Find XOR Sum of All Pairs Bitwise AND](src/main/kotlin/g1801_1900/s1835_find_xor_sum_of_all_pairs_bitwise_and)| Hard | Array, Math, Bit_Manipulation | 604 | 100.00 +| 1834 |[Single-Threaded CPU](src/main/kotlin/g1801_1900/s1834_single_threaded_cpu)| Medium | Array, Sorting, Heap_Priority_Queue | 1050 | 100.00 +| 1833 |[Maximum Ice Cream Bars](src/main/kotlin/g1801_1900/s1833_maximum_ice_cream_bars)| Medium | Array, Sorting, Greedy | 439 | 100.00 +| 1832 |[Check if the Sentence Is Pangram](src/main/kotlin/g1801_1900/s1832_check_if_the_sentence_is_pangram)| Easy | String, Hash_Table | 127 | 98.00 +| 1830 |[Minimum Number of Operations to Make String Sorted](src/main/kotlin/g1801_1900/s1830_minimum_number_of_operations_to_make_string_sorted)| Hard | String, Math, Combinatorics | 226 | 100.00 +| 1829 |[Maximum XOR for Each Query](src/main/kotlin/g1801_1900/s1829_maximum_xor_for_each_query)| Medium | Array, Bit_Manipulation, Prefix_Sum | 680 | 100.00 +| 1828 |[Queries on Number of Points Inside a Circle](src/main/kotlin/g1801_1900/s1828_queries_on_number_of_points_inside_a_circle)| Medium | Array, Math, Geometry | 284 | 100.00 +| 1827 |[Minimum Operations to Make the Array Increasing](src/main/kotlin/g1801_1900/s1827_minimum_operations_to_make_the_array_increasing)| Easy | Array, Greedy | 208 | 100.00 +| 1825 |[Finding MK Average](src/main/kotlin/g1801_1900/s1825_finding_mk_average)| Hard | Design, Heap_Priority_Queue, Ordered_Set, Queue | 1101 | 100.00 +| 1824 |[Minimum Sideway Jumps](src/main/kotlin/g1801_1900/s1824_minimum_sideway_jumps)| Medium | Array, Dynamic_Programming, Greedy | 726 | 100.00 +| 1823 |[Find the Winner of the Circular Game](src/main/kotlin/g1801_1900/s1823_find_the_winner_of_the_circular_game)| Medium | Array, Math, Simulation, Recursion, Queue, Data_Structure_II_Day_14_Stack_Queue | 119 | 87.50 +| 1822 |[Sign of the Product of an Array](src/main/kotlin/g1801_1900/s1822_sign_of_the_product_of_an_array)| Easy | Array, Math, Programming_Skills_I_Day_4_Loop | 170 | 92.51 +| 1819 |[Number of Different Subsequences GCDs](src/main/kotlin/g1801_1900/s1819_number_of_different_subsequences_gcds)| Hard | Array, Math, Counting, Number_Theory | 624 | 100.00 +| 1818 |[Minimum Absolute Sum Difference](src/main/kotlin/g1801_1900/s1818_minimum_absolute_sum_difference)| Medium | Array, Sorting, Binary_Search, Ordered_Set, Binary_Search_II_Day_7 | 447 | 100.00 +| 1817 |[Finding the Users Active Minutes](src/main/kotlin/g1801_1900/s1817_finding_the_users_active_minutes)| Medium | Array, Hash_Table | 652 | 100.00 +| 1816 |[Truncate Sentence](src/main/kotlin/g1801_1900/s1816_truncate_sentence)| Easy | Array, String | 147 | 94.74 +| 1815 |[Maximum Number of Groups Getting Fresh Donuts](src/main/kotlin/g1801_1900/s1815_maximum_number_of_groups_getting_fresh_donuts)| Hard | Array, Dynamic_Programming, Bit_Manipulation, Bitmask, Memoization | 1073 | 100.00 +| 1814 |[Count Nice Pairs in an Array](src/main/kotlin/g1801_1900/s1814_count_nice_pairs_in_an_array)| Medium | Array, Hash_Table, Math, Counting | 520 | 100.00 +| 1813 |[Sentence Similarity III](src/main/kotlin/g1801_1900/s1813_sentence_similarity_iii)| Medium | Array, String, Two_Pointers | 162 | 100.00 +| 1812 |[Determine Color of a Chessboard Square](src/main/kotlin/g1801_1900/s1812_determine_color_of_a_chessboard_square)| Easy | String, Math | 127 | 92.86 +| 1808 |[Maximize Number of Nice Divisors](src/main/kotlin/g1801_1900/s1808_maximize_number_of_nice_divisors)| Hard | Math, Recursion | 135 | 100.00 +| 1807 |[Evaluate the Bracket Pairs of a String](src/main/kotlin/g1801_1900/s1807_evaluate_the_bracket_pairs_of_a_string)| Medium | Array, String, Hash_Table | 689 | 100.00 +| 1806 |[Minimum Number of Operations to Reinitialize a Permutation](src/main/kotlin/g1801_1900/s1806_minimum_number_of_operations_to_reinitialize_a_permutation)| Medium | Array, Math, Simulation | 117 | 100.00 +| 1805 |[Number of Different Integers in a String](src/main/kotlin/g1801_1900/s1805_number_of_different_integers_in_a_string)| Easy | String, Hash_Table | 162 | 100.00 +| 1803 |[Count Pairs With XOR in a Range](src/main/kotlin/g1801_1900/s1803_count_pairs_with_xor_in_a_range)| Hard | Array, Bit_Manipulation, Trie | 427 | 100.00 +| 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, Binary_Search_II_Day_17 | 118 | 100.00 +| 1801 |[Number of Orders in the Backlog](src/main/kotlin/g1801_1900/s1801_number_of_orders_in_the_backlog)| Medium | Array, Heap_Priority_Queue, Simulation | 668 | 100.00 | 1800 |[Maximum Ascending Subarray Sum](src/main/kotlin/g1701_1800/s1800_maximum_ascending_subarray_sum)| Easy | Array | 139 | 100.00 | 1799 |[Maximize Score After N Operations](src/main/kotlin/g1701_1800/s1799_maximize_score_after_n_operations)| Hard | Array, Dynamic_Programming, Math, Bit_Manipulation, Backtracking, Bitmask, Number_Theory | 347 | 73.17 | 1798 |[Maximum Number of Consecutive Values You Can Make](src/main/kotlin/g1701_1800/s1798_maximum_number_of_consecutive_values_you_can_make)| Medium | Array, Greedy | 414 | 100.00 diff --git a/src/main/kotlin/g1801_1900/s1801_number_of_orders_in_the_backlog/readme.md b/src/main/kotlin/g1801_1900/s1801_number_of_orders_in_the_backlog/readme.md new file mode 100644 index 00000000..0d92ece1 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1801_number_of_orders_in_the_backlog/readme.md @@ -0,0 +1,120 @@ +[![](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) + +## 1801\. Number of Orders in the Backlog + +Medium + +You are given a 2D integer array `orders`, where each orders[i] = [pricei, amounti, orderTypei] denotes that amounti orders have been placed of type orderTypei at the price pricei. The orderTypei is: + +* `0` if it is a batch of `buy` orders, or +* `1` if it is a batch of `sell` orders. + +Note that `orders[i]` represents a batch of amounti independent orders with the same price and order type. All orders represented by `orders[i]` will be placed before all orders represented by `orders[i+1]` for all valid `i`. + +There is a **backlog** that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens: + +* If the order is a `buy` order, you look at the `sell` order with the **smallest** price in the backlog. If that `sell` order's price is **smaller than or equal to** the current `buy` order's price, they will match and be executed, and that `sell` order will be removed from the backlog. Else, the `buy` order is added to the backlog. +* Vice versa, if the order is a `sell` order, you look at the `buy` order with the **largest** price in the backlog. If that `buy` order's price is **larger than or equal to** the current `sell` order's price, they will match and be executed, and that `buy` order will be removed from the backlog. Else, the `sell` order is added to the backlog. + +Return _the total **amount** of orders in the backlog after placing all the orders from the input_. Since this number can be large, return it **modulo** 109 + 7. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/11/ex1.png) + +**Input:** orders = \[\[10,5,0],[15,2,1],[25,1,1],[30,4,0]] + +**Output:** 6 + +**Explanation:** Here is what happens with the orders: + +- 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog. + +- 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog. + +- 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog. + +- 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rd order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4th order is added to the backlog. Finally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/03/11/ex2.png) + +**Input:** orders = \[\[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]] + +**Output:** 999999984 + +**Explanation:** Here is what happens with the orders: + +- 109 orders of type sell with price 7 are placed. There are no buy orders, so the 109 orders are added to the backlog. + +- 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog. - 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog. + +- 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog. Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109 + 7). + +**Constraints:** + +* 1 <= orders.length <= 105 +* `orders[i].length == 3` +* 1 <= pricei, amounti <= 109 +* orderTypei is either `0` or `1`. + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + private class Order(var price: Int, var qty: Int) + + fun getNumberOfBacklogOrders(orders: Array): Int { + val sell = PriorityQueue( + compareBy { a: Order -> a.price } + ) + val buy = PriorityQueue { a: Order, b: Order -> b.price - a.price } + for (order in orders) { + val price = order[0] + var amount = order[1] + val type = order[2] + if (type == 0) { + while (sell.isNotEmpty() && sell.peek().price <= price && amount > 0) { + val ord = sell.peek() + val toRemove = amount.coerceAtMost(ord.qty) + ord.qty -= toRemove + amount -= toRemove + if (ord.qty == 0) { + sell.poll() + } + } + if (amount > 0) { + buy.add(Order(price, amount)) + } + } else { + while (buy.isNotEmpty() && buy.peek().price >= price && amount > 0) { + val ord = buy.peek() + val toRemove = amount.coerceAtMost(ord.qty) + ord.qty -= toRemove + amount -= toRemove + if (ord.qty == 0) { + buy.poll() + } + } + if (amount > 0) { + sell.add(Order(price, amount)) + } + } + } + var sellCount: Long = 0 + for (ord in sell) { + sellCount += ord.qty.toLong() + } + var buyCount: Long = 0 + for (ord in buy) { + buyCount += ord.qty.toLong() + } + val total = sellCount + buyCount + return (total % 1000000007L).toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1802_maximum_value_at_a_given_index_in_a_bounded_array/readme.md b/src/main/kotlin/g1801_1900/s1802_maximum_value_at_a_given_index_in_a_bounded_array/readme.md new file mode 100644 index 00000000..15f7f205 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1802_maximum_value_at_a_given_index_in_a_bounded_array/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) + +## 1802\. Maximum Value at a Given Index in a Bounded Array + +Medium + +You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions: + +* `nums.length == n` +* `nums[i]` is a **positive** integer where `0 <= i < n`. +* `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`. +* The sum of all the elements of `nums` does not exceed `maxSum`. +* `nums[index]` is **maximized**. + +Return `nums[index]` _of the constructed array_. + +Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise. + +**Example 1:** + +**Input:** n = 4, index = 2, maxSum = 6 + +**Output:** 2 + +**Explanation:** nums = [1,2,**2**,1] is one array that satisfies all the conditions. There are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2]. + +**Example 2:** + +**Input:** n = 6, index = 1, maxSum = 10 + +**Output:** 3 + +**Constraints:** + +* 1 <= n <= maxSum <= 109 +* `0 <= index < n` + +## Solution + +```kotlin +class Solution { + private fun isPossible(n: Int, index: Int, maxSum: Int, value: Int): Boolean { + val leftValue = (value - index).coerceAtLeast(0) + val rightValue = (value - (n - 1 - index)).coerceAtLeast(0) + val sumBefore = (value + leftValue).toLong() * (value - leftValue + 1) / 2 + val sumAfter = (value + rightValue).toLong() * (value - rightValue + 1) / 2 + return sumBefore + sumAfter - value <= maxSum + } + + fun maxValue(n: Int, index: Int, maxSum: Int): Int { + var left = 0 + var right = maxSum - n + while (left < right) { + val middle = (left + right + 1) / 2 + if (isPossible(n, index, maxSum - n, middle)) { + left = middle + } else { + right = middle - 1 + } + } + return left + 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1803_count_pairs_with_xor_in_a_range/readme.md b/src/main/kotlin/g1801_1900/s1803_count_pairs_with_xor_in_a_range/readme.md new file mode 100644 index 00000000..8db977b4 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1803_count_pairs_with_xor_in_a_range/readme.md @@ -0,0 +1,115 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1803\. Count Pairs With XOR in a Range + +Hard + +Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_. + +A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`. + +**Example 1:** + +**Input:** nums = [1,4,2,7], low = 2, high = 6 + +**Output:** 6 + +**Explanation:** All nice pairs (i, j) are as follows: + +- (0, 1): nums[0] XOR nums[1] = 5 + +- (0, 2): nums[0] XOR nums[2] = 3 + +- (0, 3): nums[0] XOR nums[3] = 6 + +- (1, 2): nums[1] XOR nums[2] = 6 + +- (1, 3): nums[1] XOR nums[3] = 3 + +- (2, 3): nums[2] XOR nums[3] = 5 + +**Example 2:** + +**Input:** nums = [9,8,4,2,1], low = 5, high = 14 + +**Output:** 8 + +**Explanation:** All nice pairs (i, j) are as follows: + +- (0, 2): nums[0] XOR nums[2] = 13 + +- (0, 3): nums[0] XOR nums[3] = 11 + +- (0, 4): nums[0] XOR nums[4] = 8 + +- (1, 2): nums[1] XOR nums[2] = 12 + +- (1, 3): nums[1] XOR nums[3] = 10 + +- (1, 4): nums[1] XOR nums[4] = 9 + +- (2, 3): nums[2] XOR nums[3] = 6 + +- (2, 4): nums[2] XOR nums[4] = 5 + +**Constraints:** + +* 1 <= nums.length <= 2 * 104 +* 1 <= nums[i] <= 2 * 104 +* 1 <= low <= high <= 2 * 104 + +## Solution + +```kotlin +class Solution { + fun countPairs(nums: IntArray, low: Int, high: Int): Int { + val root = Trie() + var pairsCount = 0 + for (num in nums) { + val pairsCountHigh = countPairsWhoseXorLessThanX(num, root, high + 1) + val pairsCountLow = countPairsWhoseXorLessThanX(num, root, low) + pairsCount += pairsCountHigh - pairsCountLow + root.insertNumber(num) + } + return pairsCount + } + + private fun countPairsWhoseXorLessThanX(num: Int, root: Trie, x: Int): Int { + var pairs = 0 + var curr: Trie? = root + var i = 14 + while (i >= 0 && curr != null) { + val numIthBit = num shr i and 1 + val xIthBit = x shr i and 1 + if (xIthBit == 1) { + if (curr.child[numIthBit] != null) { + pairs += curr.child[numIthBit]!!.count + } + curr = curr.child[1 - numIthBit] + } else { + curr = curr.child[numIthBit] + } + i-- + } + return pairs + } + + private class Trie { + var child: Array = arrayOfNulls(2) + var count: Int = 0 + + fun insertNumber(num: Int) { + var curr = this + for (i in 14 downTo 0) { + val ithBit = num shr i and 1 + if (curr.child[ithBit] == null) { + curr.child[ithBit] = Trie() + } + curr.child[ithBit]!!.count++ + curr = curr.child[ithBit]!! + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1805_number_of_different_integers_in_a_string/readme.md b/src/main/kotlin/g1801_1900/s1805_number_of_different_integers_in_a_string/readme.md new file mode 100644 index 00000000..0c70ceea --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1805_number_of_different_integers_in_a_string/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) + +## 1805\. Number of Different Integers in a String + +Easy + +You are given a string `word` that consists of digits and lowercase English letters. + +You will replace every non-digit character with a space. For example, `"a123bc34d8ef34"` will become `" 123 34 8 34"`. Notice that you are left with some integers that are separated by at least one space: `"123"`, `"34"`, `"8"`, and `"34"`. + +Return _the number of **different** integers after performing the replacement operations on_ `word`. + +Two integers are considered different if their decimal representations **without any leading zeros** are different. + +**Example 1:** + +**Input:** word = "a123bc34d8ef34" + +**Output:** 3 + +**Explanation:** The three different integers are "123", "34", and "8". Notice that "34" is only counted once. + +**Example 2:** + +**Input:** word = "leet1234code234" + +**Output:** 2 + +**Example 3:** + +**Input:** word = "a1b01c001" + +**Output:** 1 + +**Explanation:** The three integers "1", "01", and "001" all represent the same integer because the leading zeros are ignored when comparing their decimal values. + +**Constraints:** + +* `1 <= word.length <= 1000` +* `word` consists of digits and lowercase English letters. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun numDifferentIntegers(word: String): Int { + val ints: MutableSet = HashSet() + val chars = word.toCharArray() + var start = -1 + var stop = 0 + for (i in chars.indices) { + if (chars[i] in '0'..'9') { + if (start == -1) { + start = i + } + stop = i + } else if (start != -1) { + ints.add(extractInt(chars, start, stop)) + start = -1 + } + } + if (start != -1) { + ints.add(extractInt(chars, start, stop)) + } + return ints.size + } + + private fun extractInt(chrs: CharArray, start: Int, stop: Int): String { + var start = start + val stb = StringBuilder() + while (start <= stop && chrs[start] == '0') { + start++ + } + if (start >= stop) { + stb.append(chrs[stop]) + } else { + while (start <= stop) { + stb.append(chrs[start++]) + } + } + return stb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1806_minimum_number_of_operations_to_reinitialize_a_permutation/readme.md b/src/main/kotlin/g1801_1900/s1806_minimum_number_of_operations_to_reinitialize_a_permutation/readme.md new file mode 100644 index 00000000..8e6a260d --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1806_minimum_number_of_operations_to_reinitialize_a_permutation/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1806\. Minimum Number of Operations to Reinitialize a Permutation + +Medium + +You are given an **even** integer `n`. You initially have a permutation `perm` of size `n` where `perm[i] == i` **(0-indexed)**. + +In one operation, you will create a new array `arr`, and for each `i`: + +* If `i % 2 == 0`, then `arr[i] = perm[i / 2]`. +* If `i % 2 == 1`, then `arr[i] = perm[n / 2 + (i - 1) / 2]`. + +You will then assign `arr` to `perm`. + +Return _the minimum **non-zero** number of operations you need to perform on_ `perm` _to return the permutation to its initial value._ + +**Example 1:** + +**Input:** n = 2 + +**Output:** 1 + +**Explanation:** perm = [0,1] initially. + +After the 1st operation, perm = [0,1] + +So it takes only 1 operation. + +**Example 2:** + +**Input:** n = 4 + +**Output:** 2 + +**Explanation:** perm = [0,1,2,3] initially. + +After the 1st operation, perm = [0,2,1,3] + +After the 2nd operation, perm = [0,1,2,3] + +So it takes only 2 operations. + +**Example 3:** + +**Input:** n = 6 + +**Output:** 4 + +**Constraints:** + +* `2 <= n <= 1000` +* `n` is even. + +## Solution + +```kotlin +class Solution { + fun reinitializePermutation(n: Int): Int { + val factor = n - 1 + if (factor < 2) { + return 1 + } + var powerOfTwo = 2 + var ops = 1 + while (powerOfTwo != 1) { + powerOfTwo = (powerOfTwo shl 1) % factor + ops++ + } + return ops + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1807_evaluate_the_bracket_pairs_of_a_string/readme.md b/src/main/kotlin/g1801_1900/s1807_evaluate_the_bracket_pairs_of_a_string/readme.md new file mode 100644 index 00000000..17c67be0 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1807_evaluate_the_bracket_pairs_of_a_string/readme.md @@ -0,0 +1,97 @@ +[![](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) + +## 1807\. Evaluate the Bracket Pairs of a String + +Medium + +You are given a string `s` that contains some bracket pairs, with each pair containing a **non-empty** key. + +* For example, in the string `"(name)is(age)yearsold"`, there are **two** bracket pairs that contain the keys `"name"` and `"age"`. + +You know the values of a wide range of keys. This is represented by a 2D string array `knowledge` where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei. + +You are tasked to evaluate **all** of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will: + +* Replace keyi and the bracket pair with the key's corresponding valuei. +* If you do not know the value of the key, you will replace keyi and the bracket pair with a question mark `"?"` (without the quotation marks). + +Each key will appear at most once in your `knowledge`. There will not be any nested brackets in `s`. + +Return _the resulting string after evaluating **all** of the bracket pairs._ + +**Example 1:** + +**Input:** s = "(name)is(age)yearsold", knowledge = \[\["name","bob"],["age","two"]] + +**Output:** "bobistwoyearsold" + +**Explanation:** + +The key "name" has a value of "bob", so replace "(name)" with "bob". + +The key "age" has a value of "two", so replace "(age)" with "two". + +**Example 2:** + +**Input:** s = "hi(name)", knowledge = \[\["a","b"]] + +**Output:** "hi?" + +**Explanation:** As you do not know the value of the key "name", replace "(name)" with "?". + +**Example 3:** + +**Input:** s = "(a)(a)(a)aaa", knowledge = \[\["a","yes"]] + +**Output:** "yesyesyesaaa" + +**Explanation:** The same key can appear multiple times. + +The key "a" has a value of "yes", so replace all occurrences of "(a)" with "yes". + +Notice that the "a"s not in a bracket pair are not evaluated. + +**Constraints:** + +* 1 <= s.length <= 105 +* 0 <= knowledge.length <= 105 +* `knowledge[i].length == 2` +* 1 <= keyi.length, valuei.length <= 10 +* `s` consists of lowercase English letters and round brackets `'('` and `')'`. +* Every open bracket `'('` in `s` will have a corresponding close bracket `')'`. +* The key in each bracket pair of `s` will be non-empty. +* There will not be any nested bracket pairs in `s`. +* keyi and valuei consist of lowercase English letters. +* Each keyi in `knowledge` is unique. + +## Solution + +```kotlin +class Solution { + fun evaluate(s: String, knowledge: List>): String { + val knowledgeMapper: MutableMap = HashMap() + for (pair in knowledge) { + knowledgeMapper[pair[0]] = pair[1] + } + val answer = StringBuilder() + var i = 0 + while (i < s.length) { + var letter = s[i] + if (letter == '(') { + val key = StringBuilder() + letter = s[++i] + while (letter != ')') { + key.append(letter) + letter = s[++i] + } + answer.append(knowledgeMapper.getOrDefault(key.toString(), "?")) + } else { + answer.append(letter) + } + i++ + } + return answer.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1808_maximize_number_of_nice_divisors/readme.md b/src/main/kotlin/g1801_1900/s1808_maximize_number_of_nice_divisors/readme.md new file mode 100644 index 00000000..dc5a36ca --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1808_maximize_number_of_nice_divisors/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1808\. Maximize Number of Nice Divisors + +Hard + +You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions: + +* The number of prime factors of `n` (not necessarily distinct) is **at most** `primeFactors`. +* The number of nice divisors of `n` is maximized. Note that a divisor of `n` is **nice** if it is divisible by every prime factor of `n`. For example, if `n = 12`, then its prime factors are `[2,2,3]`, then `6` and `12` are nice divisors, while `3` and `4` are not. + +Return _the number of nice divisors of_ `n`. Since that number can be too large, return it **modulo** 109 + 7. + +Note that a prime number is a natural number greater than `1` that is not a product of two smaller natural numbers. The prime factors of a number `n` is a list of prime numbers such that their product equals `n`. + +**Example 1:** + +**Input:** primeFactors = 5 + +**Output:** 6 + +**Explanation:** 200 is a valid value of n. It has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200]. There is not other value of n that has at most 5 prime factors and more nice divisors. + +**Example 2:** + +**Input:** primeFactors = 8 + +**Output:** 18 + +**Constraints:** + +* 1 <= primeFactors <= 109 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + private fun modPow(b: Long, e: Int, m: Int): Long { + var b = b + var e = e + if (m == 1) { + return 0 + } + if (e == 0 || b == 1L) { + return 1 + } + b %= m.toLong() + var r: Long = 1 + while (e > 0) { + if (e and 1 == 1) { + r = r * b % m + } + e = e shr 1 + b = b * b % m + } + return r + } + + fun maxNiceDivisors(pf: Int): Int { + val mod = 1000000007 + val st = intArrayOf(0, 1, 2, 3, 4, 6) + return if (pf < 5) pf else (modPow(3, pf / 3 - 1, mod) * st[3 + pf % 3] % mod).toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1812_determine_color_of_a_chessboard_square/readme.md b/src/main/kotlin/g1801_1900/s1812_determine_color_of_a_chessboard_square/readme.md new file mode 100644 index 00000000..906de1c0 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1812_determine_color_of_a_chessboard_square/readme.md @@ -0,0 +1,57 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1812\. Determine Color of a Chessboard Square + +Easy + +You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. + +![](https://assets.leetcode.com/uploads/2021/02/19/screenshot-2021-02-20-at-22159-pm.png) + +Return `true` _if the square is white, and_ `false` _if the square is black_. + +The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second. + +**Example 1:** + +**Input:** coordinates = "a1" + +**Output:** false + +**Explanation:** From the chessboard above, the square with coordinates "a1" is black, so return false. + +**Example 2:** + +**Input:** coordinates = "h3" + +**Output:** true + +**Explanation:** From the chessboard above, the square with coordinates "h3" is white, so return true. + +**Example 3:** + +**Input:** coordinates = "c7" + +**Output:** false + +**Constraints:** + +* `coordinates.length == 2` +* `'a' <= coordinates[0] <= 'h'` +* `'1' <= coordinates[1] <= '8'` + +## Solution + +```kotlin +class Solution { + fun squareIsWhite(coordinates: String): Boolean { + val x = coordinates[0] + val y = (coordinates[1].toString() + "").toInt() + return when (x) { + 'a', 'c', 'e', 'g' -> y % 2 == 0 + else -> y % 2 != 0 + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1813_sentence_similarity_iii/readme.md b/src/main/kotlin/g1801_1900/s1813_sentence_similarity_iii/readme.md new file mode 100644 index 00000000..5dcb9f32 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1813_sentence_similarity_iii/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) + +## 1813\. Sentence Similarity III + +Medium + +A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, `"Hello World"`, `"HELLO"`, `"hello world hello world"` are all sentences. Words consist of **only** uppercase and lowercase English letters. + +Two sentences `sentence1` and `sentence2` are **similar** if it is possible to insert an arbitrary sentence **(possibly empty)** inside one of these sentences such that the two sentences become equal. For example, `sentence1 = "Hello my name is Jane"` and `sentence2 = "Hello Jane"` can be made equal by inserting `"my name is"` between `"Hello"` and `"Jane"` in `sentence2`. + +Given two sentences `sentence1` and `sentence2`, return `true` _if_ `sentence1` _and_ `sentence2` _are similar._ Otherwise, return `false`. + +**Example 1:** + +**Input:** sentence1 = "My name is Haley", sentence2 = "My Haley" + +**Output:** true + +**Explanation:** sentence2 can be turned to sentence1 by inserting "name is" between "My" and "Haley". + +**Example 2:** + +**Input:** sentence1 = "of", sentence2 = "A lot of words" + +**Output:** false + +**Explanation:** No single sentence can be inserted inside one of the sentences to make it equal to the other. + +**Example 3:** + +**Input:** sentence1 = "Eating right now", sentence2 = "Eating" + +**Output:** true + +**Explanation:** sentence2 can be turned to sentence1 by inserting "right now" at the end of the sentence. + +**Constraints:** + +* `1 <= sentence1.length, sentence2.length <= 100` +* `sentence1` and `sentence2` consist of lowercase and uppercase English letters and spaces. +* The words in `sentence1` and `sentence2` are separated by a single space. + +## Solution + +```kotlin +class Solution { + fun areSentencesSimilar(sentence1: String, sentence2: String): Boolean { + val words1 = sentence1.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + val words2 = sentence2.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + var i = 0 + val n1 = words1.size + val n2 = words2.size + if (n1 > n2) { + return areSentencesSimilar(sentence2, sentence1) + } + while (i < n1 && words1[i] == words2[i]) { + ++i + } + while (i < n1 && words1[i] == words2[n2 - n1 + i]) { + ++i + } + return i == n1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1814_count_nice_pairs_in_an_array/readme.md b/src/main/kotlin/g1801_1900/s1814_count_nice_pairs_in_an_array/readme.md new file mode 100644 index 00000000..0bdc0c11 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1814_count_nice_pairs_in_an_array/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1814\. Count Nice Pairs in an Array + +Medium + +You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: + +* `0 <= i < j < nums.length` +* `nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])` + +Return _the number of nice pairs of indices_. Since that number can be too large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** nums = [42,11,1,97] + +**Output:** 2 + +**Explanation:** The two pairs are: + +- (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121. + +- (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12. + +**Example 2:** + +**Input:** nums = [13,10,35,24,76] + +**Output:** 4 + +**Constraints:** + +* 1 <= nums.length <= 105 +* 0 <= nums[i] <= 109 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + private fun rev(n: Int): Int { + var n = n + var r = 0 + while (n > 0) { + r = r * 10 + n % 10 + n /= 10 + } + return r + } + + fun countNicePairs(nums: IntArray): Int { + val revMap = HashMap() + var cnt = 0 + for (num in nums) { + val lhs = num - rev(num) + val prevCnt = revMap.getOrDefault(lhs, 0) + cnt += prevCnt + val mod = 1000000007 + cnt %= mod + revMap[lhs] = prevCnt + 1 + } + return cnt + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1815_maximum_number_of_groups_getting_fresh_donuts/readme.md b/src/main/kotlin/g1801_1900/s1815_maximum_number_of_groups_getting_fresh_donuts/readme.md new file mode 100644 index 00000000..81120139 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1815_maximum_number_of_groups_getting_fresh_donuts/readme.md @@ -0,0 +1,105 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1815\. Maximum Number of Groups Getting Fresh Donuts + +Hard + +There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` customers that will visit the shop. Each customer will get exactly one donut. + +When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group. + +You can freely rearrange the ordering of the groups. Return _the **maximum** possible number of happy groups after rearranging the groups._ + +**Example 1:** + +**Input:** batchSize = 3, groups = [1,2,3,4,5,6] + +**Output:** 4 + +**Explanation:** You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6th groups will be happy. + +**Example 2:** + +**Input:** batchSize = 4, groups = [1,3,2,5,2,2,1,6] + +**Output:** 4 + +**Constraints:** + +* `1 <= batchSize <= 9` +* `1 <= groups.length <= 30` +* 1 <= groups[i] <= 109 + +## Solution + +```kotlin +import java.util.Objects + +class Solution { + inner class Data(var idx: Int, var arrHash: Int) { + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + if (other == null || javaClass != other.javaClass) { + return false + } + val data = other as Data + return idx == data.idx && arrHash == data.arrHash + } + + override fun hashCode(): Int { + return Objects.hash(idx, arrHash) + } + } + + private var dp: HashMap = HashMap() + fun maxHappyGroups(batchSize: Int, groups: IntArray): Int { + val arr = IntArray(batchSize) + for (group in groups) { + arr[group % batchSize]++ + } + return arr[0] + solve(0, arr) + } + + private fun solve(num: Int, arr: IntArray): Int { + if (isFull(arr)) { + return 0 + } + val key = Data(num, arr.contentHashCode()) + if (dp.containsKey(key)) { + return dp[key]!! + } + var best = Int.MIN_VALUE / 2 + if (num == 0) { + for (i in 1 until arr.size) { + if (arr[i] <= 0) { + continue + } + arr[i]-- + best = Math.max(best, 1 + solve(i, arr)) + arr[i]++ + } + } else { + for (i in 1 until arr.size) { + if (arr[i] > 0) { + arr[i]-- + best = best.coerceAtLeast(solve((num + i) % arr.size, arr)) + arr[i]++ + } + } + } + dp[key] = best + return best + } + + private fun isFull(arr: IntArray): Boolean { + var sum = 0 + for (i in 1 until arr.size) { + sum += arr[i] + } + return sum == 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1816_truncate_sentence/readme.md b/src/main/kotlin/g1801_1900/s1816_truncate_sentence/readme.md new file mode 100644 index 00000000..dac9f4fc --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1816_truncate_sentence/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) + +## 1816\. Truncate Sentence + +Easy + +A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation). + +* For example, `"Hello World"`, `"HELLO"`, and `"hello world hello world"` are all sentences. + +You are given a sentence `s` and an integer `k`. You want to **truncate** `s` such that it contains only the **first** `k` words. Return `s`_ after **truncating** it._ + +**Example 1:** + +**Input:** s = "Hello how are you Contestant", k = 4 + +**Output:** "Hello how are you" + +**Explanation:** + +The words in s are ["Hello", "how" "are", "you", "Contestant"]. + +The first 4 words are ["Hello", "how", "are", "you"]. + +Hence, you should return "Hello how are you". + +**Example 2:** + +**Input:** s = "What is the solution to this problem", k = 4 + +**Output:** "What is the solution" + +**Explanation:** + +The words in s are ["What", "is" "the", "solution", "to", "this", "problem"]. + +The first 4 words are ["What", "is", "the", "solution"]. + +Hence, you should return "What is the solution". + +**Example 3:** + +**Input:** s = "chopper is not a tanuki", k = 5 + +**Output:** "chopper is not a tanuki" + +**Constraints:** + +* `1 <= s.length <= 500` +* `k` is in the range `[1, the number of words in s]`. +* `s` consist of only lowercase and uppercase English letters and spaces. +* The words in `s` are separated by a single space. +* There are no leading or trailing spaces. + +## Solution + +```kotlin +class Solution { + fun truncateSentence(s: String, k: Int): String { + val words = s.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + val sb = StringBuilder() + for (i in 0 until k) { + sb.append(words[i]) + sb.append(" ") + } + return sb.substring(0, sb.toString().length - 1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1817_finding_the_users_active_minutes/readme.md b/src/main/kotlin/g1801_1900/s1817_finding_the_users_active_minutes/readme.md new file mode 100644 index 00000000..4249b3d3 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1817_finding_the_users_active_minutes/readme.md @@ -0,0 +1,90 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1817\. Finding the Users Active Minutes + +Medium + +You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each logs[i] = [IDi, timei] indicates that the user with IDi performed an action at the minute timei. + +**Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. + +The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. + +You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. + +Return _the array_ `answer` _as described above_. + +**Example 1:** + +**Input:** logs = \[\[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5 + +**Output:** [0,2,0,0,0] + +**Explanation:** + +The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). + +The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. + +Since both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0. + +**Example 2:** + +**Input:** logs = \[\[1,1],[2,2],[2,3]], k = 4 + +**Output:** [1,1,0,0] + +**Explanation:** + +The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. + +The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. + +There is one user with a UAM of 1 and one with a UAM of 2. + +Hence, answer[1] = 1, answer[2] = 1, and the remaining values are 0. + +**Constraints:** + +* 1 <= logs.length <= 104 +* 0 <= IDi <= 109 +* 1 <= timei <= 105 +* `k` is in the range [The maximum **UAM** for a user, 105]. + +## Solution + +```kotlin +class Solution { + fun findingUsersActiveMinutes(logs: Array, k: Int): IntArray { + if (logs.size == 1) { + val res = IntArray(k) + res[0] = 1 + return res + } + logs.sortWith(compareBy { a: IntArray -> a[0] }.thenComparingInt { a: IntArray -> a[1] }) + val result = IntArray(k) + var start = 1 + var prevUser = logs[0][0] + var prevMin = logs[0][1] + var count = 1 + while (true) { + while (start < logs.size && prevUser == logs[start][0]) { + if (prevMin != logs[start][1]) { + count++ + } + prevMin = logs[start][1] + start++ + } + result[count - 1]++ + if (start >= logs.size) { + break + } + count = 1 + prevUser = logs[start][0] + prevMin = logs[start][1] + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1818_minimum_absolute_sum_difference/readme.md b/src/main/kotlin/g1801_1900/s1818_minimum_absolute_sum_difference/readme.md new file mode 100644 index 00000000..867afeca --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1818_minimum_absolute_sum_difference/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) + +## 1818\. Minimum Absolute Sum Difference + +Medium + +You are given two positive integer arrays `nums1` and `nums2`, both of length `n`. + +The **absolute sum difference** of arrays `nums1` and `nums2` is defined as the **sum** of `|nums1[i] - nums2[i]|` for each `0 <= i < n` (**0-indexed**). + +You can replace **at most one** element of `nums1` with **any** other element in `nums1` to **minimize** the absolute sum difference. + +Return the _minimum absolute sum difference **after** replacing at most one element in the array `nums1`._ Since the answer may be large, return it **modulo** 109 + 7. + +`|x|` is defined as: + +* `x` if `x >= 0`, or +* `-x` if `x < 0`. + +**Example 1:** + +**Input:** nums1 = [1,7,5], nums2 = [2,3,5] + +**Output:** 3 + +**Explanation:** There are two possible optimal solutions: + +- Replace the second element with the first: [1,**7**,5] => [1,**1**,5], or + +- Replace the second element with the third: [1,**7**,5] => [1,**5**,5]. + +Both will yield an absolute sum difference of `|1-2| + (|1-3| or |5-3|) + |5-5| =` 3\. + +**Example 2:** + +**Input:** nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10] + +**Output:** 0 + +**Explanation:** nums1 is equal to nums2 so no replacement is needed. This will result in an absolute sum difference of 0. + +**Example 3:** + +**Input:** nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4] + +**Output:** 20 + +**Explanation:** Replace the first element with the second: [**1**,10,4,4,2,7] => [**10**,10,4,4,2,7]. This yields an absolute sum difference of `|10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20` + +**Constraints:** + +* `n == nums1.length` +* `n == nums2.length` +* 1 <= n <= 105 +* 1 <= nums1[i], nums2[i] <= 105 + +## Solution + +```kotlin +import kotlin.math.abs + +class Solution { + fun minAbsoluteSumDiff(nums1: IntArray, nums2: IntArray): Int { + var min = Int.MAX_VALUE + var max = Int.MIN_VALUE + for (i in nums1.indices) { + min = min.coerceAtMost(nums1[i].coerceAtMost(nums2[i])) + max = max.coerceAtLeast(nums1[i].coerceAtLeast(nums2[i])) + } + val less = IntArray(max - min + 1) + val more = IntArray(max - min + 1) + less[0] = -max - 1 + more[more.size - 1] = max + 1 shl 1 + for (num in nums1) { + less[num - min] = num + more[num - min] = num + } + for (i in 1 until less.size) { + if (less[i] == 0) { + less[i] = less[i - 1] + } + } + for (i in more.size - 2 downTo 0) { + if (more[i] == 0) { + more[i] = more[i + 1] + } + } + var total = 0 + var preSave = 0 + for (i in nums1.indices) { + val current = abs(nums1[i] - nums2[i]) + total += current + val save = ( + current - + abs(less[nums2[i] - min] - nums2[i]).coerceAtMost(abs(more[nums2[i] - min] - nums2[i])) + ) + if (save > preSave) { + total = total + preSave - save + preSave = save + } + total %= 1000000007 + } + return total + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1819_number_of_different_subsequences_gcds/readme.md b/src/main/kotlin/g1801_1900/s1819_number_of_different_subsequences_gcds/readme.md new file mode 100644 index 00000000..6a13f49a --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1819_number_of_different_subsequences_gcds/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) + +## 1819\. Number of Different Subsequences GCDs + +Hard + +You are given an array `nums` that consists of positive integers. + +The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. + +* For example, the GCD of the sequence `[4,6,16]` is `2`. + +A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array. + +* For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`. + +Return _the **number** of **different** GCDs among all **non-empty** subsequences of_ `nums`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/17/image-1.png) + +**Input:** nums = [6,10,3] + +**Output:** 5 + +**Explanation:** The figure shows all the non-empty subsequences and their GCDs. The different GCDs are 6, 10, 3, 2, and 1. + +**Example 2:** + +**Input:** nums = [5,15,40,5,6] + +**Output:** 7 + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 2 * 105 + +## Solution + +```kotlin +class Solution { + fun countDifferentSubsequenceGCDs(nums: IntArray): Int { + var max = 0 + for (num in nums) { + max = max.coerceAtLeast(num) + } + val present = BooleanArray(200001) + for (num in nums) { + max = max.coerceAtLeast(num) + present[num] = true + } + var count = 0 + for (i in 1..max) { + if (present[i]) { + count++ + continue + } + var tempGcd = 0 + var j = i + while (j <= max) { + if (present[j]) { + tempGcd = gcd(tempGcd, j) + } + if (tempGcd == i) { + count++ + break + } + j += i + } + } + return count + } + + private fun gcd(a: Int, b: Int): Int { + return if (b == 0) { + a + } else gcd(b, a % b) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1822_sign_of_the_product_of_an_array/readme.md b/src/main/kotlin/g1801_1900/s1822_sign_of_the_product_of_an_array/readme.md new file mode 100644 index 00000000..2d57492b --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1822_sign_of_the_product_of_an_array/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) + +## 1822\. Sign of the Product of an Array + +Easy + +There is a function `signFunc(x)` that returns: + +* `1` if `x` is positive. +* `-1` if `x` is negative. +* `0` if `x` is equal to `0`. + +You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`. + +Return `signFunc(product)`. + +**Example 1:** + +**Input:** nums = [-1,-2,-3,-4,3,2,1] + +**Output:** 1 + +**Explanation:** The product of all values in the array is 144, and signFunc(144) = 1 + +**Example 2:** + +**Input:** nums = [1,5,0,2,-3] + +**Output:** 0 + +**Explanation:** The product of all values in the array is 0, and signFunc(0) = 0 + +**Example 3:** + +**Input:** nums = [-1,1,-1,1,-1] + +**Output:** -1 + +**Explanation:** The product of all values in the array is -1, and signFunc(-1) = -1 + +**Constraints:** + +* `1 <= nums.length <= 1000` +* `-100 <= nums[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun arraySign(nums: IntArray): Int { + var negativeCount = 0 + for (num in nums) { + if (num == 0) { + return 0 + } else if (num < 0) { + negativeCount++ + } + } + return if (negativeCount % 2 == 0) 1 else -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1823_find_the_winner_of_the_circular_game/readme.md b/src/main/kotlin/g1801_1900/s1823_find_the_winner_of_the_circular_game/readme.md new file mode 100644 index 00000000..fb665b97 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1823_find_the_winner_of_the_circular_game/readme.md @@ -0,0 +1,78 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1823\. Find the Winner of the Circular Game + +Medium + +There are `n` friends that are playing a game. The friends are sitting in a circle and are numbered from `1` to `n` in **clockwise order**. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for `1 <= i < n`, and moving clockwise from the nth friend brings you to the 1st friend. + +The rules of the game are as follows: + +1. **Start** at the 1st friend. +2. Count the next `k` friends in the clockwise direction **including** the friend you started at. The counting wraps around the circle and may count some friends more than once. +3. The last friend you counted leaves the circle and loses the game. +4. If there is still more than one friend in the circle, go back to step `2` **starting** from the friend **immediately clockwise** of the friend who just lost and repeat. +5. Else, the last friend in the circle wins the game. + +Given the number of friends, `n`, and an integer `k`, return _the winner of the game_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/25/ic234-q2-ex11.png) + +**Input:** n = 5, k = 2 + +**Output:** 3 + +**Explanation:** Here are the steps of the game: + +1) Start at friend 1. + +2) Count 2 friends clockwise, which are friends 1 and 2. + +3) Friend 2 leaves the circle. Next start is friend 3. + +4) Count 2 friends clockwise, which are friends 3 and 4. + +5) Friend 4 leaves the circle. Next start is friend 5. + +6) Count 2 friends clockwise, which are friends 5 and 1. + +7) Friend 1 leaves the circle. Next start is friend 3. + +8) Count 2 friends clockwise, which are friends 3 and 5. + +9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner. + +**Example 2:** + +**Input:** n = 6, k = 5 + +**Output:** 1 + +**Explanation:** The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1. + +**Constraints:** + +* `1 <= k <= n <= 500` + +## Solution + +```kotlin +class Solution { + fun findTheWinner(n: Int, k: Int): Int { + val list: MutableList = ArrayList(n) + for (i in 0 until n) { + list.add(i + 1) + } + var startIndex = 0 + while (list.size != 1) { + val removeIndex = (startIndex + k - 1) % list.size + list.removeAt(removeIndex) + startIndex = removeIndex + } + return list[0] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1824_minimum_sideway_jumps/readme.md b/src/main/kotlin/g1801_1900/s1824_minimum_sideway_jumps/readme.md new file mode 100644 index 00000000..e0f18569 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1824_minimum_sideway_jumps/readme.md @@ -0,0 +1,103 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1824\. Minimum Sideway Jumps + +Medium + +There is a **3 lane road** of length `n` that consists of `n + 1` **points** labeled from `0` to `n`. A frog **starts** at point `0` in the **second** lane and wants to jump to point `n`. However, there could be obstacles along the way. + +You are given an array `obstacles` of length `n + 1` where each `obstacles[i]` (**ranging from 0 to 3**) describes an obstacle on the lane `obstacles[i]` at point `i`. If `obstacles[i] == 0`, there are no obstacles at point `i`. There will be **at most one** obstacle in the 3 lanes at each point. + +* For example, if `obstacles[2] == 1`, then there is an obstacle on lane 1 at point 2. + +The frog can only travel from point `i` to point `i + 1` on the same lane if there is not an obstacle on the lane at point `i + 1`. To avoid obstacles, the frog can also perform a **side jump** to jump to **another** lane (even if they are not adjacent) at the **same** point if there is no obstacle on the new lane. + +* For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. + +Return _the **minimum number of side jumps** the frog needs to reach **any lane** at point n starting from lane `2` at point 0._ + +**Note:** There will be no obstacles on points `0` and `n`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex1.png) + +**Input:** obstacles = [0,1,2,3,0] + +**Output:** 2 + +**Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows). Note that the frog can jump over obstacles only when making side jumps (as shown at point 2). + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex2.png) + +**Input:** obstacles = [0,1,1,3,3,0] + +**Output:** 0 + +**Explanation:** There are no obstacles on lane 2. No side jumps are required. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex3.png) + +**Input:** obstacles = [0,2,1,0,3,0] + +**Output:** 2 + +**Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps. + +**Constraints:** + +* `obstacles.length == n + 1` +* 1 <= n <= 5 * 105 +* `0 <= obstacles[i] <= 3` +* `obstacles[0] == obstacles[n] == 0` + +## Solution + +```kotlin +class Solution { + fun minSideJumps(obstacles: IntArray): Int { + var sideJumps = 0 + var currLane = 2 + var i = 0 + while (i < obstacles.size - 1) { + if (obstacles[i + 1] == currLane) { + if (obstacles[i] != 0) { + currLane = getNextLane(obstacles[i], obstacles[i + 1]) + } else { + var j = i + 2 + while (j < obstacles.size && + (obstacles[j] == 0 || obstacles[j] == obstacles[i + 1]) + ) { + j++ + } + if (j < obstacles.size) { + currLane = getNextLane(obstacles[i + 1], obstacles[j]) + } else { + i = obstacles.size - 1 + } + } + sideJumps++ + } + i++ + } + return sideJumps + } + + private fun getNextLane(nextObstacle: Int, nextNextObstacle: Int): Int { + if (nextObstacle == 2 && nextNextObstacle == 3 || nextObstacle == 3 && nextNextObstacle == 2) { + return 1 + } + return if (nextObstacle == 1 && nextNextObstacle == 3 || nextObstacle == 3 && nextNextObstacle == 1 + ) { + 2 + } else { + 3 + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1825_finding_mk_average/readme.md b/src/main/kotlin/g1801_1900/s1825_finding_mk_average/readme.md new file mode 100644 index 00000000..7cd8ea86 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1825_finding_mk_average/readme.md @@ -0,0 +1,164 @@ +[![](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) + +## 1825\. Finding MK Average + +Hard + +You are given two integers, `m` and `k`, and a stream of integers. You are tasked to implement a data structure that calculates the **MKAverage** for the stream. + +The **MKAverage** can be calculated using these steps: + +1. If the number of the elements in the stream is less than `m` you should consider the **MKAverage** to be `-1`. Otherwise, copy the last `m` elements of the stream to a separate container. +2. Remove the smallest `k` elements and the largest `k` elements from the container. +3. Calculate the average value for the rest of the elements **rounded down to the nearest integer**. + +Implement the `MKAverage` class: + +* `MKAverage(int m, int k)` Initializes the **MKAverage** object with an empty stream and the two integers `m` and `k`. +* `void addElement(int num)` Inserts a new element `num` into the stream. +* `int calculateMKAverage()` Calculates and returns the **MKAverage** for the current stream **rounded down to the nearest integer**. + +**Example 1:** + +**Input** ["MKAverage", "addElement", "addElement", "calculateMKAverage", "addElement", "calculateMKAverage", "addElement", "addElement", "addElement", "calculateMKAverage"] [[3, 1], [3], [1], [], [10], [], [5], [5], [5], []] + +**Output:** [null, null, null, -1, null, 3, null, null, null, 5] + +**Explanation:** MKAverage obj = new MKAverage(3, 1); obj.addElement(3); // current elements are [3] obj.addElement(1); // current elements are [3,1] obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist. obj.addElement(10); // current elements are [3,1,10] obj.calculateMKAverage(); // The last 3 elements are [3,1,10]. // After removing smallest and largest 1 element the container will be ```[3]. // The average of [3] equals 3/1 = 3, return 3 obj.addElement(5); // current elements are [3,1,10,5] obj.addElement(5); // current elements are [3,1,10,5,5] obj.addElement(5); // current elements are [3,1,10,5,5,5] obj.calculateMKAverage(); // The last 3 elements are [5,5,5]. // After removing smallest and largest 1 element the container will be `[5]. // The average of [5] equals 5/1 = 5, return 5` ``` + +**Constraints:** + +* 3 <= m <= 105 +* `1 <= k*2 < m` +* 1 <= num <= 105 +* At most 105 calls will be made to `addElement` and `calculateMKAverage`. + +## Solution + +```kotlin +import java.util.Deque +import java.util.LinkedList +import java.util.TreeMap + +@Suppress("NAME_SHADOWING") +class MKAverage(m: Int, k: Int) { + private val m: Double + private val k: Double + private val c: Double + private var avg: Double + private val middle: Bst + private val min: Bst + private val max: Bst + private val q: Deque + + init { + this.m = m.toDouble() + this.k = k.toDouble() + c = (m - k * 2).toDouble() + avg = 0.0 + middle = Bst() + min = Bst() + max = Bst() + q = LinkedList() + } + + fun addElement(num: Int) { + var num = num + if (min.size < k) { + min.add(num) + q.offer(num) + return + } + if (max.size < k) { + min.add(num) + max.add(min.removeMax()) + q.offer(num) + return + } + if (num >= min.lastKey() && num <= max.firstKey()) { + middle.add(num) + avg += num / c + } else if (num < min.lastKey()) { + min.add(num) + val `val` = min.removeMax() + middle.add(`val`) + avg += `val` / c + } else if (num > max.firstKey()) { + max.add(num) + val `val` = max.removeMin() + middle.add(`val`) + avg += `val` / c + } + q.offer(num) + if (q.size > m) { + num = q.poll() + if (middle.containsKey(num)) { + avg -= num / c + middle.remove(num) + } else if (min.containsKey(num)) { + min.remove(num) + val `val` = middle.removeMin() + avg -= `val` / c + min.add(`val`) + } else if (max.containsKey(num)) { + max.remove(num) + val `val` = middle.removeMax() + avg -= `val` / c + max.add(`val`) + } + } + } + + fun calculateMKAverage(): Int { + return if (q.size < m) { + -1 + } else avg.toInt() + } + + internal class Bst { + var map: TreeMap = TreeMap() + var size: Int = 0 + + fun add(num: Int) { + val count = map.getOrDefault(num, 0) + 1 + map[num] = count + size++ + } + + fun remove(num: Int) { + val count = map.getOrDefault(num, 1) - 1 + if (count > 0) { + map[num] = count + } else { + map.remove(num) + } + size-- + } + + fun removeMin(): Int { + val key = map.firstKey() + remove(key) + return key + } + + fun removeMax(): Int { + val key = map.lastKey() + remove(key) + return key + } + + fun containsKey(key: Int): Boolean { + return map.containsKey(key) + } + + fun firstKey(): Int { + return map.firstKey() + } + + fun lastKey(): Int { + return map.lastKey() + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1827_minimum_operations_to_make_the_array_increasing/readme.md b/src/main/kotlin/g1801_1900/s1827_minimum_operations_to_make_the_array_increasing/readme.md new file mode 100644 index 00000000..faa0342a --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1827_minimum_operations_to_make_the_array_increasing/readme.md @@ -0,0 +1,62 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1827\. Minimum Operations to Make the Array Increasing + +Easy + +You are given an integer array `nums` (**0-indexed**). In one operation, you can choose an element of the array and increment it by `1`. + +* For example, if `nums = [1,2,3]`, you can choose to increment `nums[1]` to make `nums = [1,**3**,3]`. + +Return _the **minimum** number of operations needed to make_ `nums` _**strictly** **increasing**._ + +An array `nums` is **strictly increasing** if `nums[i] < nums[i+1]` for all `0 <= i < nums.length - 1`. An array of length `1` is trivially strictly increasing. + +**Example 1:** + +**Input:** nums = [1,1,1] + +**Output:** 3 + +**Explanation:** You can do the following operations: + +1) Increment nums[2], so nums becomes [1,1,**2**]. + +2) Increment nums[1], so nums becomes [1,**2**,2]. + +3) Increment nums[2], so nums becomes [1,2,**3**]. + +**Example 2:** + +**Input:** nums = [1,5,2,4,1] + +**Output:** 14 + +**Example 3:** + +**Input:** nums = [8] + +**Output:** 0 + +**Constraints:** + +* `1 <= nums.length <= 5000` +* 1 <= nums[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun minOperations(nums: IntArray): Int { + var minsOps = 0 + for (i in 1 until nums.size) { + if (nums[i] <= nums[i - 1]) { + minsOps += nums[i - 1] - nums[i] + 1 + nums[i] = nums[i - 1] + 1 + } + } + return minsOps + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1828_queries_on_number_of_points_inside_a_circle/readme.md b/src/main/kotlin/g1801_1900/s1828_queries_on_number_of_points_inside_a_circle/readme.md new file mode 100644 index 00000000..de9e93a7 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1828_queries_on_number_of_points_inside_a_circle/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) + +## 1828\. Queries on Number of Points Inside a Circle + +Medium + +You are given an array `points` where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the **same** coordinates. + +You are also given an array `queries` where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj. + +For each query `queries[j]`, compute the number of points **inside** the jth circle. Points **on the border** of the circle are considered **inside**. + +Return _an array_ `answer`_, where_ `answer[j]` _is the answer to the_ jth _query_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/25/chrome_2021-03-25_22-34-16.png) + +**Input:** points = \[\[1,3],[3,3],[5,3],[2,2]], queries = \[\[2,3,1],[4,3,1],[1,1,2]] + +**Output:** [3,2,2] + +**Explanation:** The points and circles are shown above. queries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/03/25/chrome_2021-03-25_22-42-07.png) + +**Input:** points = \[\[1,1],[2,2],[3,3],[4,4],[5,5]], queries = \[\[1,2,2],[2,2,2],[4,3,2],[4,3,3]] + +**Output:** [2,3,2,4] + +**Explanation:** The points and circles are shown above. queries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple. + +**Constraints:** + +* `1 <= points.length <= 500` +* `points[i].length == 2` +* 0 <= xi, yi <= 500 +* `1 <= queries.length <= 500` +* `queries[j].length == 3` +* 0 <= xj, yj <= 500 +* 1 <= rj <= 500 +* All coordinates are integers. + +**Follow up:** Could you find the answer for each query in better complexity than `O(n)`? + +## Solution + +```kotlin +class Solution { + fun countPoints(points: Array, queries: Array): IntArray { + val result = IntArray(queries.size) + for ((i, query) in queries.withIndex()) { + var pts = 0 + for (point in points) { + if ((point[0] - query[0]) * (point[0] - query[0]) + + (point[1] - query[1]) * (point[1] - query[1]) + <= query[2] * query[2] + ) { + pts++ + } + } + result[i] = pts + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1829_maximum_xor_for_each_query/readme.md b/src/main/kotlin/g1801_1900/s1829_maximum_xor_for_each_query/readme.md new file mode 100644 index 00000000..598be5e6 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1829_maximum_xor_for_each_query/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) + +## 1829\. Maximum XOR for Each Query + +Medium + +You are given a **sorted** array `nums` of `n` non-negative integers and an integer `maximumBit`. You want to perform the following query `n` **times**: + +1. Find a non-negative integer k < 2maximumBit such that `nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k` is **maximized**. `k` is the answer to the ith query. +2. Remove the **last** element from the current array `nums`. + +Return _an array_ `answer`_, where_ `answer[i]` _is the answer to the_ ith _query_. + +**Example 1:** + +**Input:** nums = [0,1,1,3], maximumBit = 2 + +**Output:** [0,3,2,3] + +**Explanation:** The queries are answered as follows: + +1st query: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3. + +2nd query: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3. + +3rd query: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3. + +4th query: nums = [0], k = 3 since 0 XOR 3 = 3. + +**Example 2:** + +**Input:** nums = [2,3,4,7], maximumBit = 3 + +**Output:** [5,2,6,5] + +**Explanation:** The queries are answered as follows: + +1st query: nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7. + +2nd query: nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7. + +3rd query: nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7. + +4th query: nums = [2], k = 5 since 2 XOR 5 = 7. + +**Example 3:** + +**Input:** nums = [0,1,2,2,5,7], maximumBit = 3 + +**Output:** [4,3,6,4,6,7] + +**Constraints:** + +* `nums.length == n` +* 1 <= n <= 105 +* `1 <= maximumBit <= 20` +* 0 <= nums[i] < 2maximumBit +* `nums` is sorted in **ascending** order. + +## Solution + +```kotlin +class Solution { + fun getMaximumXor(nums: IntArray, maximumBit: Int): IntArray { + val result = IntArray(nums.size) + var `val` = nums[0] + val target = (1 shl maximumBit) - 1 + for (i in 1 until nums.size) { + `val` = `val` xor nums[i] + } + for (i in result.indices) { + result[i] = target xor `val` + `val` = `val` xor nums[nums.size - i - 1] + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1830_minimum_number_of_operations_to_make_string_sorted/readme.md b/src/main/kotlin/g1801_1900/s1830_minimum_number_of_operations_to_make_string_sorted/readme.md new file mode 100644 index 00000000..f6edb359 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1830_minimum_number_of_operations_to_make_string_sorted/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) + +## 1830\. Minimum Number of Operations to Make String Sorted + +Hard + +You are given a string `s` (**0-indexed**). You are asked to perform the following operation on `s` until you get a sorted string: + +1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`. +2. Find **the largest index** `j` such that `i <= j < s.length` and `s[k] < s[i - 1]` for all the possible values of `k` in the range `[i, j]` inclusive. +3. Swap the two characters at indices `i - 1` and `j`. +4. Reverse the suffix starting at index `i`. + +Return _the number of operations needed to make the string sorted._ Since the answer can be too large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** s = "cba" + +**Output:** 5 + +**Explanation:** The simulation goes as follows: Operation 1: i=2, j=2. Swap s[1] and s[2] to get s="cab", then reverse the suffix starting at 2. Now, s="cab". + +Operation 2: i=1, j=2. Swap s[0] and s[2] to get s="bac", then reverse the suffix starting at 1. Now, s="bca". + +Operation 3: i=2, j=2. Swap s[1] and s[2] to get s="bac", then reverse the suffix starting at 2. Now, s="bac". + +Operation 4: i=1, j=1. Swap s[0] and s[1] to get s="abc", then reverse the suffix starting at 1. Now, s="acb". + +Operation 5: i=2, j=2. Swap s[1] and s[2] to get s="abc", then reverse the suffix starting at 2. Now, s="abc". + +**Example 2:** + +**Input:** s = "aabaa" + +**Output:** 2 + +**Explanation:** The simulation goes as follows: + +Operation 1: i=3, j=4. Swap s[2] and s[4] to get s="aaaab", then reverse the substring starting at 3. Now, s="aaaba". + +Operation 2: i=4, j=4. Swap s[3] and s[4] to get s="aaaab", then reverse the substring starting at 4. Now, s="aaaab". + +**Constraints:** + +* `1 <= s.length <= 3000` +* `s` consists only of lowercase English letters. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun makeStringSorted(s: String): Int { + val n = s.length + val count = IntArray(26) + for (i in 0 until n) { + count[s[i].code - 'a'.code]++ + } + val fact = LongArray(n + 1) + fact[0] = 1 + val mod = 1000000007 + for (i in 1..n) { + fact[i] = fact[i - 1] * i % mod + } + var len = n + var ans: Long = 0 + for (i in 0 until n) { + len-- + val bound = s[i].code - 'a'.code + var first = 0 + var rev: Long = 1 + for (k in 0..25) { + if (k < bound) { + first += count[k] + } + rev = rev * fact[count[k]] % mod + } + ans = ( + ans % mod + + ( + first * fact[len] % mod + * modPow(rev, mod.toLong() - 2, mod) % + mod + ) % + mod + ) + ans %= mod + count[bound]-- + } + return ans.toInt() + } + + private fun modPow(x: Long, n: Long, m: Int): Long { + var x = x + var n = n + var result: Long = 1 + while (n > 0) { + if (n and 1L != 0L) { + result = result * x % m + } + x = x * x % m + n = n shr 1 + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1832_check_if_the_sentence_is_pangram/readme.md b/src/main/kotlin/g1801_1900/s1832_check_if_the_sentence_is_pangram/readme.md new file mode 100644 index 00000000..274701ea --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1832_check_if_the_sentence_is_pangram/readme.md @@ -0,0 +1,43 @@ +[![](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) + +## 1832\. Check if the Sentence Is Pangram + +Easy + +A **pangram** is a sentence where every letter of the English alphabet appears at least once. + +Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._ + +**Example 1:** + +**Input:** sentence = "thequickbrownfoxjumpsoverthelazydog" + +**Output:** true + +**Explanation:** sentence contains at least one of every letter of the English alphabet. + +**Example 2:** + +**Input:** sentence = "leetcode" + +**Output:** false + +**Constraints:** + +* `1 <= sentence.length <= 1000` +* `sentence` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun checkIfPangram(sentence: String): Boolean { + val alphabet: MutableSet = HashSet() + for (c in sentence.toCharArray()) { + alphabet.add(c) + } + return alphabet.size == 26 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1833_maximum_ice_cream_bars/readme.md b/src/main/kotlin/g1801_1900/s1833_maximum_ice_cream_bars/readme.md new file mode 100644 index 00000000..36378dc5 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1833_maximum_ice_cream_bars/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) + +## 1833\. Maximum Ice Cream Bars + +Medium + +It is a sweltering summer day, and a boy wants to buy some ice cream bars. + +At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the ith ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible. + +Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._ + +**Note:** The boy can buy the ice cream bars in any order. + +**Example 1:** + +**Input:** costs = [1,3,2,4,1], coins = 7 + +**Output:** 4 + +**Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7. + +**Example 2:** + +**Input:** costs = [10,6,8,7,7,8], coins = 5 + +**Output:** 0 + +**Explanation:** The boy cannot afford any of the ice cream bars. + +**Example 3:** + +**Input:** costs = [1,6,3,1,2,5], coins = 20 + +**Output:** 6 + +**Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18. + +**Constraints:** + +* `costs.length == n` +* 1 <= n <= 105 +* 1 <= costs[i] <= 105 +* 1 <= coins <= 108 + +## Solution + +```kotlin +class Solution { + fun maxIceCream(costs: IntArray, coins: Int): Int { + val arr = IntArray(100001) + for (cost in costs) arr[cost]++ + var (result, money) = Pair(0, coins) + for ((coin, count) in arr.withIndex()) { + if (count > 0) { + val c = minOf(money / coin, count) + money -= coin * c + result += c + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1834_single_threaded_cpu/readme.md b/src/main/kotlin/g1801_1900/s1834_single_threaded_cpu/readme.md new file mode 100644 index 00000000..3a24939b --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1834_single_threaded_cpu/readme.md @@ -0,0 +1,112 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1834\. Single-Threaded CPU + +Medium + +You are given `n` tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where tasks[i] = [enqueueTimei, processingTimei] means that the ith task will be available to process at enqueueTimei and will take processingTimei to finish processing. + +You have a single-threaded CPU that can process **at most one** task at a time and will act in the following way: + +* If the CPU is idle and there are no available tasks to process, the CPU remains idle. +* If the CPU is idle and there are available tasks, the CPU will choose the one with the **shortest processing time**. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index. +* Once a task is started, the CPU will **process the entire task** without stopping. +* The CPU can finish a task then start a new one instantly. + +Return _the order in which the CPU will process the tasks._ + +**Example 1:** + +**Input:** tasks = \[\[1,2],[2,4],[3,2],[4,1]] + +**Output:** [0,2,3,1] + +**Explanation:** The events go as follows: + +- At time = 1, task 0 is available to process. Available tasks = {0}. + +- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}. + +- At time = 2, task 1 is available to process. Available tasks = {1}. + +- At time = 3, task 2 is available to process. Available tasks = {1, 2}. + +- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}. + +- At time = 4, task 3 is available to process. Available tasks = {1, 3}. - At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}. + +- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}. + +- At time = 10, the CPU finishes task 1 and becomes idle. + +**Example 2:** + +**Input:** tasks = \[\[7,10],[7,12],[7,5],[7,4],[7,2]] + +**Output:** [4,3,2,0,1] + +**Explanation:** The events go as follows: + +- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}. + +- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}. + +- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}. + +- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}. + +- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}. + +- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}. + +- At time = 40, the CPU finishes task 1 and becomes idle. + +**Constraints:** + +* `tasks.length == n` +* 1 <= n <= 105 +* 1 <= enqueueTimei, processingTimei <= 109 + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + fun getOrder(tasks1: Array): IntArray { + val n = tasks1.size + val tasks = Array(n) { IntArray(3) } + for (i in 0 until n) { + tasks[i] = intArrayOf(tasks1[i][0], tasks1[i][1], i) + } + tasks.sortWith(compareBy { a: IntArray -> a[0] }) + val minHeap = PriorityQueue( + Comparator { a: IntArray, b: IntArray -> + return@Comparator if (a[1] == b[1]) { + a[2] - b[2] + } else { + a[1] - b[1] + } + } + ) + var time = tasks[0][0] + val taskOrderResult = IntArray(n) + var i = 0 + var index = 0 + while (minHeap.isNotEmpty() || i < n) { + while (i < n && time >= tasks[i][0]) { + minHeap.add(tasks[i++]) + } + if (minHeap.isNotEmpty()) { + val task = minHeap.remove() + taskOrderResult[index++] = task[2] + time += task[1] + } else { + time = tasks[i][0] + } + } + return taskOrderResult + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1835_find_xor_sum_of_all_pairs_bitwise_and/readme.md b/src/main/kotlin/g1801_1900/s1835_find_xor_sum_of_all_pairs_bitwise_and/readme.md new file mode 100644 index 00000000..1af6de06 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1835_find_xor_sum_of_all_pairs_bitwise_and/readme.md @@ -0,0 +1,55 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1835\. Find XOR Sum of All Pairs Bitwise AND + +Hard + +The **XOR sum** of a list is the bitwise `XOR` of all its elements. If the list only contains one element, then its **XOR sum** will be equal to this element. + +* For example, the **XOR sum** of `[1,2,3,4]` is equal to `1 XOR 2 XOR 3 XOR 4 = 4`, and the **XOR sum** of `[3]` is equal to `3`. + +You are given two **0-indexed** arrays `arr1` and `arr2` that consist only of non-negative integers. + +Consider the list containing the result of `arr1[i] AND arr2[j]` (bitwise `AND`) for every `(i, j)` pair where `0 <= i < arr1.length` and `0 <= j < arr2.length`. + +Return _the **XOR sum** of the aforementioned list_. + +**Example 1:** + +**Input:** arr1 = [1,2,3], arr2 = [6,5] + +**Output:** 0 + +**Explanation:** The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1]. The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0. + +**Example 2:** + +**Input:** arr1 = [12], arr2 = [4] + +**Output:** 4 + +**Explanation:** The list = [12 AND 4] = [4]. The XOR sum = 4. + +**Constraints:** + +* 1 <= arr1.length, arr2.length <= 105 +* 0 <= arr1[i], arr2[j] <= 109 + +## Solution + +```kotlin +class Solution { + fun getXORSum(arr1: IntArray, arr2: IntArray): Int { + var xor1 = 0 + var xor2 = 0 + for (i in arr1) { + xor1 = xor1 xor i + } + for (j in arr2) { + xor2 = xor2 xor j + } + return xor1 and xor2 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1837_sum_of_digits_in_base_k/readme.md b/src/main/kotlin/g1801_1900/s1837_sum_of_digits_in_base_k/readme.md new file mode 100644 index 00000000..a563a1b8 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1837_sum_of_digits_in_base_k/readme.md @@ -0,0 +1,46 @@ +[![](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) + +## 1837\. Sum of Digits in Base K + +Easy + +Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. + +After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. + +**Example 1:** + +**Input:** n = 34, k = 6 + +**Output:** 9 + +**Explanation:** 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9. + +**Example 2:** + +**Input:** n = 10, k = 10 + +**Output:** 1 + +**Explanation:** n is already in base 10. 1 + 0 = 1. + +**Constraints:** + +* `1 <= n <= 100` +* `2 <= k <= 10` + +## Solution + +```kotlin +class Solution { + fun sumBase(n: Int, k: Int): Int { + val str = (n.toString() + "").toInt(10).toString(k) + var sum = 0 + for (c in str.toCharArray()) { + sum += Character.getNumericValue(c) + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1838_frequency_of_the_most_frequent_element/readme.md b/src/main/kotlin/g1801_1900/s1838_frequency_of_the_most_frequent_element/readme.md new file mode 100644 index 00000000..f3ddab2f --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1838_frequency_of_the_most_frequent_element/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) + +## 1838\. Frequency of the Most Frequent Element + +Medium + +The **frequency** of an element is the number of times it occurs in an array. + +You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`. + +Return _the **maximum possible frequency** of an element after performing **at most**_ `k` _operations_. + +**Example 1:** + +**Input:** nums = [1,2,4], k = 5 + +**Output:** 3 + +**Explanation:** Increment the first element three times and the second element two times to make nums = [4,4,4]. 4 has a frequency of 3. + +**Example 2:** + +**Input:** nums = [1,4,8,13], k = 5 + +**Output:** 2 + +**Explanation:** There are multiple optimal solutions: + +- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2. + +- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2. + +- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2. + +**Example 3:** + +**Input:** nums = [3,9,6], k = 2 + +**Output:** 1 + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 105 +* 1 <= k <= 105 + +## Solution + +```kotlin +class Solution { + fun maxFrequency(nums: IntArray, k: Int): Int { + countingSort(nums) + var start = 0 + var preSum = 0 + var total = 1 + for (i in nums.indices) { + var length = i - start + 1 + var product = nums[i] * length + preSum += nums[i] + while (product - preSum > k) { + preSum -= nums[start++] + length-- + product = nums[i] * length + } + total = total.coerceAtLeast(length) + } + return total + } + + private fun countingSort(nums: IntArray) { + var max = Int.MIN_VALUE + for (num in nums) { + max = max.coerceAtLeast(num) + } + val map = IntArray(max + 1) + for (num in nums) { + map[num]++ + } + var i = 0 + var j = 0 + while (i <= max) { + if (map[i]-- > 0) { + nums[j++] = i + } else { + i++ + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1839_longest_substring_of_all_vowels_in_order/readme.md b/src/main/kotlin/g1801_1900/s1839_longest_substring_of_all_vowels_in_order/readme.md new file mode 100644 index 00000000..8c2a3df4 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1839_longest_substring_of_all_vowels_in_order/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) + +## 1839\. Longest Substring Of All Vowels in Order + +Medium + +A string is considered **beautiful** if it satisfies the following conditions: + +* Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it. +* The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.). + +For example, strings `"aeiou"` and `"aaaaaaeiiiioou"` are considered **beautiful**, but `"uaeio"`, `"aeoiu"`, and `"aaaeeeooo"` are **not beautiful**. + +Given a string `word` consisting of English vowels, return _the **length of the longest beautiful substring** of_ `word`_. If no such substring exists, return_ `0`. + +A **substring** is a contiguous sequence of characters in a string. + +**Example 1:** + +**Input:** word = "aeiaaioaaaaeiiiiouuuooaauuaeiu" + +**Output:** 13 + +**Explanation:** The longest beautiful substring in word is "aaaaeiiiiouuu" of length 13. + +**Example 2:** + +**Input:** word = "aeeeiiiioooauuuaeiou" + +**Output:** 5 + +**Explanation:** The longest beautiful substring in word is "aeiou" of length 5. + +**Example 3:** + +**Input:** word = "a" + +**Output:** 0 + +**Explanation:** There is no beautiful substring, so return 0. + +**Constraints:** + +* 1 <= word.length <= 5 * 105 +* `word` consists of characters `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. + +## Solution + +```kotlin +class Solution { + fun longestBeautifulSubstring(word: String): Int { + var cnt = 1 + var len = 1 + var maxLen = 0 + for (i in 1 until word.length) { + if (word[i - 1] == word[i]) { + ++len + } else if (word[i - 1] < word[i]) { + ++len + ++cnt + } else { + cnt = 1 + len = 1 + } + if (cnt == 5) { + maxLen = maxLen.coerceAtLeast(len) + } + } + return maxLen + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1840_maximum_building_height/readme.md b/src/main/kotlin/g1801_1900/s1840_maximum_building_height/readme.md new file mode 100644 index 00000000..4bffb0dc --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1840_maximum_building_height/readme.md @@ -0,0 +1,95 @@ +[![](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) + +## 1840\. Maximum Building Height + +Hard + +You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`. + +However, there are city restrictions on the heights of the new buildings: + +* The height of each building must be a non-negative integer. +* The height of the first building **must** be `0`. +* The height difference between any two adjacent buildings **cannot exceed** `1`. + +Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where restrictions[i] = [idi, maxHeighti] indicates that building idi must have a height **less than or equal to** maxHeighti. + +It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`. + +Return _the **maximum possible height** of the **tallest** building_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/08/ic236-q4-ex1-1.png) + +**Input:** n = 5, restrictions = \[\[2,1],[4,1]] + +**Output:** 2 + +**Explanation:** The green area in the image indicates the maximum allowed height for each building. We can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/04/08/ic236-q4-ex2.png) + +**Input:** n = 6, restrictions = [] + +**Output:** 5 + +**Explanation:** The green area in the image indicates the maximum allowed height for each building. We can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/04/08/ic236-q4-ex3.png) + +**Input:** n = 10, restrictions = \[\[5,3],[2,5],[7,4],[10,3]] + +**Output:** 5 + +**Explanation:** The green area in the image indicates the maximum allowed height for each building. We can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5. + +**Constraints:** + +* 2 <= n <= 109 +* 0 <= restrictions.length <= min(n - 1, 105) +* 2 <= idi <= n +* idi is **unique**. +* 0 <= maxHeighti <= 109 + +## Solution + +```kotlin +class Solution { + fun maxBuilding(n: Int, restrictions: Array): Int { + if (restrictions.isEmpty()) { + return n - 1 + } + val m = restrictions.size + restrictions.sortWith(compareBy { a: IntArray -> a[0] }) + for (i in m - 2 downTo 0) { + restrictions[i][1] = + restrictions[i][1].coerceAtMost(restrictions[i + 1][1] + restrictions[i + 1][0] - restrictions[i][0]) + } + var id = 1 + var height = 0 + var res = 0 + for (r in restrictions) { + var currMax: Int + if (r[1] >= height + r[0] - id) { + currMax = height + r[0] - id + height = currMax + } else { + currMax = (height + r[0] - id + r[1]) / 2 + height = r[1] + } + id = r[0] + res = res.coerceAtLeast(currMax) + } + if (id != n) { + res = res.coerceAtLeast(height + n - id) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1844_replace_all_digits_with_characters/readme.md b/src/main/kotlin/g1801_1900/s1844_replace_all_digits_with_characters/readme.md new file mode 100644 index 00000000..ab2c700a --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1844_replace_all_digits_with_characters/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) + +## 1844\. Replace All Digits with Characters + +Easy + +You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. + +There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the xth character after `c`. + +* For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`. + +For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`. + +Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`. + +**Example 1:** + +**Input:** s = "a1c1e1" + +**Output:** "abcdef" + +**Explanation:** The digits are replaced as follows: + +- s[1] -> shift('a',1) = 'b' + +- s[3] -> shift('c',1) = 'd' + +- s[5] -> shift('e',1) = 'f' + +**Example 2:** + +**Input:** s = "a1b2c3d4e" + +**Output:** "abbdcfdhe" + +**Explanation:** The digits are replaced as follows: + +- s[1] -> shift('a',1) = 'b' + +- s[3] -> shift('b',2) = 'd' + +- s[5] -> shift('c',3) = 'f' + +- s[7] -> shift('d',4) = 'h' + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` consists only of lowercase English letters and digits. +* `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`. + +## Solution + +```kotlin +class Solution { + fun replaceDigits(s: String): String { + val sb = StringBuilder() + for (c in s.toCharArray()) { + if (Character.isAlphabetic(c.code)) { + sb.append(c) + } else { + sb.append((sb[sb.length - 1].code + Character.getNumericValue(c)).toChar()) + } + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1845_seat_reservation_manager/readme.md b/src/main/kotlin/g1801_1900/s1845_seat_reservation_manager/readme.md new file mode 100644 index 00000000..0a904ec3 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1845_seat_reservation_manager/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1845\. Seat Reservation Manager + +Medium + +Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`. + +Implement the `SeatManager` class: + +* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available. +* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number. +* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`. + +**Example 1:** + +**Input** ["SeatManager", "reserve", "reserve", "unreserve", "reserve", "reserve", "reserve", "reserve", "unreserve"] [[5], [], [], [2], [], [], [], [], [5]] + +**Output:** [null, 1, 2, null, 2, 3, 4, 5, null] + +**Explanation:** + +SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats. + +seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1. + +seatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2. + +seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5]. + +seatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2. + +seatManager.reserve(); // The available seats are [3,4,5], so return the lowest of them, which is 3. + +seatManager.reserve(); // The available seats are [4,5], so return the lowest of them, which is 4. + +seatManager.reserve(); // The only available seat is seat 5, so return 5. + +seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5]. + +**Constraints:** + +* 1 <= n <= 105 +* `1 <= seatNumber <= n` +* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat. +* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved. +* At most 105 calls **in total** will be made to `reserve` and `unreserve`. + +## Solution + +```kotlin +import java.util.PriorityQueue +import java.util.Queue + +@Suppress("UNUSED_PARAMETER") +class SeatManager(n: Int) { + private val seats: Queue + private var smallest: Int + + init { + seats = PriorityQueue() + smallest = 0 + } + + fun reserve(): Int { + return if (seats.isEmpty()) ++smallest else seats.poll() + } + + fun unreserve(seatNumber: Int) { + seats.offer(seatNumber) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1846_maximum_element_after_decreasing_and_rearranging/readme.md b/src/main/kotlin/g1801_1900/s1846_maximum_element_after_decreasing_and_rearranging/readme.md new file mode 100644 index 00000000..60bfcf49 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1846_maximum_element_after_decreasing_and_rearranging/readme.md @@ -0,0 +1,81 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1846\. Maximum Element After Decreasing and Rearranging + +Medium + +You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: + +* The value of the **first** element in `arr` must be `1`. +* The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`. + +There are 2 types of operations that you can perform any number of times: + +* **Decrease** the value of any element of `arr` to a **smaller positive integer**. +* **Rearrange** the elements of `arr` to be in any order. + +Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_. + +**Example 1:** + +**Input:** arr = [2,2,1,2,1] + +**Output:** 2 + +**Explanation:** + +We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`. + +The largest element in `arr` is 2. + +**Example 2:** + +**Input:** arr = [100,1,1000] + +**Output:** 3 + +**Explanation:** + +One possible way to satisfy the conditions is by doing the following: + +1. Rearrange `arr` so it becomes `[1,100,1000]`. + +2. Decrease the value of the second element to 2. + +3. Decrease the value of the third element to 3. + +Now `arr = [1,2,3], which` satisfies the conditions. + +The largest element in `arr is 3.` + +**Example 3:** + +**Input:** arr = [1,2,3,4,5] + +**Output:** 5 + +**Explanation:** The array already satisfies the conditions, and the largest element is 5. + +**Constraints:** + +* 1 <= arr.length <= 105 +* 1 <= arr[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun maximumElementAfterDecrementingAndRearranging(arr: IntArray): Int { + val count = IntArray(arr.size + 1) + for (j in arr) { + count[j.coerceAtMost(arr.size)]++ + } + var ans = 1 + for (i in 1 until count.size) { + ans = i.coerceAtMost(ans + count[i]) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1847_closest_room/readme.md b/src/main/kotlin/g1801_1900/s1847_closest_room/readme.md new file mode 100644 index 00000000..a91cc963 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1847_closest_room/readme.md @@ -0,0 +1,105 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1847\. Closest Room + +Hard + +There is a hotel with `n` rooms. The rooms are represented by a 2D integer array `rooms` where rooms[i] = [roomIdi, sizei] denotes that there is a room with room number roomIdi and size equal to sizei. Each roomIdi is guaranteed to be **unique**. + +You are also given `k` queries in a 2D array `queries` where queries[j] = [preferredj, minSizej]. The answer to the jth query is the room number `id` of a room such that: + +* The room has a size of **at least** minSizej, and +* abs(id - preferredj) is **minimized**, where `abs(x)` is the absolute value of `x`. + +If there is a **tie** in the absolute difference, then use the room with the **smallest** such `id`. If there is **no such room**, the answer is `-1`. + +Return _an array_ `answer` _of length_ `k` _where_ `answer[j]` _contains the answer to the_ jth _query_. + +**Example 1:** + +**Input:** rooms = \[\[2,2],[1,2],[3,2]], queries = \[\[3,1],[3,3],[5,2]] + +**Output:** [3,-1,3] + +**Explanation:** The answers to the queries are as follows: + +Query = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3. + +Query = [3,3]: There are no rooms with a size of at least 3, so the answer is -1. + +Query = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3. + +**Example 2:** + +**Input:** rooms = \[\[1,4],[2,3],[3,5],[4,1],[5,2]], queries = \[\[2,3],[2,4],[2,5]] + +**Output:** [2,1,3] + +**Explanation:** The answers to the queries are as follows: + +Query = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2. + +Query = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller. + +Query = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3. + +**Constraints:** + +* `n == rooms.length` +* 1 <= n <= 105 +* `k == queries.length` +* 1 <= k <= 104 +* 1 <= roomIdi, preferredj <= 107 +* 1 <= sizei, minSizej <= 107 + +## Solution + +```kotlin +import java.util.Arrays +import java.util.TreeSet + + +class Solution { + fun closestRoom(rooms: Array, queries: Array): IntArray { + val numRoom = rooms.size + val numQuery = queries.size + for (i in 0 until numQuery) { + queries[i] = intArrayOf(queries[i][0], queries[i][1], i) + } + Arrays.sort(rooms) { a: IntArray, b: IntArray -> if (a[1] != b[1]) a[1] - b[1] else a[0] - b[0] } + Arrays.sort(queries) { a: IntArray, b: IntArray -> if (a[1] != b[1]) a[1] - b[1] else a[0] - b[0] } + val roomIds = TreeSet() + val result = IntArray(numQuery) + var j = numRoom - 1 + for (i in numQuery - 1 downTo 0) { + val currRoomId = queries[i][0] + val currRoomSize = queries[i][1] + val currQueryIndex = queries[i][2] + while (j >= 0 && rooms[j][1] >= currRoomSize) { + roomIds.add(rooms[j--][0]) + } + if (roomIds.contains(currRoomId)) { + result[currQueryIndex] = currRoomId + continue + } + val nextRoomId = roomIds.higher(currRoomId) + val prevRoomId = roomIds.lower(currRoomId) + if (nextRoomId == null && prevRoomId == null) { + result[currQueryIndex] = -1 + } else if (nextRoomId == null) { + result[currQueryIndex] = prevRoomId!! + } else if (prevRoomId == null) { + result[currQueryIndex] = nextRoomId + } else { + if (currRoomId - prevRoomId <= nextRoomId - currRoomId) { + result[currQueryIndex] = prevRoomId + } else { + result[currQueryIndex] = nextRoomId + } + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1848_minimum_distance_to_the_target_element/readme.md b/src/main/kotlin/g1801_1900/s1848_minimum_distance_to_the_target_element/readme.md new file mode 100644 index 00000000..9cadc18b --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1848_minimum_distance_to_the_target_element/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) + +## 1848\. Minimum Distance to the Target Element + +Easy + +Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. + +Return `abs(i - start)`. + +It is **guaranteed** that `target` exists in `nums`. + +**Example 1:** + +**Input:** nums = [1,2,3,4,5], target = 5, start = 3 + +**Output:** 1 + +**Explanation:** nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1. + +**Example 2:** + +**Input:** nums = [1], target = 1, start = 0 + +**Output:** 0 + +**Explanation:** nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0. + +**Example 3:** + +**Input:** nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0 + +**Output:** 0 + +**Explanation:** Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0. + +**Constraints:** + +* `1 <= nums.length <= 1000` +* 1 <= nums[i] <= 104 +* `0 <= start < nums.length` +* `target` is in `nums`. + +## Solution + +```kotlin +import kotlin.math.abs + +class Solution { + fun getMinDistance(nums: IntArray, target: Int, start: Int): Int { + var result = 0 + var minDiff = Int.MAX_VALUE + for (i in nums.indices) { + if (nums[i] == target && abs(start - i) < minDiff) { + minDiff = abs(start - i) + result = minDiff + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1849_splitting_a_string_into_descending_consecutive_values/readme.md b/src/main/kotlin/g1801_1900/s1849_splitting_a_string_into_descending_consecutive_values/readme.md new file mode 100644 index 00000000..b93f6361 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1849_splitting_a_string_into_descending_consecutive_values/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) + +## 1849\. Splitting a String Into Descending Consecutive Values + +Medium + +You are given a string `s` that consists of only digits. + +Check if we can split `s` into **two or more non-empty substrings** such that the **numerical values** of the substrings are in **descending order** and the **difference** between numerical values of every two **adjacent** **substrings** is equal to `1`. + +* For example, the string `s = "0090089"` can be split into `["0090", "089"]` with numerical values `[90,89]`. The values are in descending order and adjacent values differ by `1`, so this way is valid. +* Another example, the string `s = "001"` can be split into `["0", "01"]`, `["00", "1"]`, or `["0", "0", "1"]`. However all the ways are invalid because they have numerical values `[0,1]`, `[0,1]`, and `[0,0,1]` respectively, all of which are not in descending order. + +Return `true` _if it is possible to split_ `s` _as described above__, or_ `false` _otherwise._ + +A **substring** is a contiguous sequence of characters in a string. + +**Example 1:** + +**Input:** s = "1234" + +**Output:** false + +**Explanation:** There is no valid way to split s. + +**Example 2:** + +**Input:** s = "050043" + +**Output:** true + +**Explanation:** s can be split into ["05", "004", "3"] with numerical values [5,4,3]. The values are in descending order with adjacent values differing by 1. + +**Example 3:** + +**Input:** s = "9080701" + +**Output:** false + +**Explanation:** There is no valid way to split s. + +**Constraints:** + +* `1 <= s.length <= 20` +* `s` only consists of digits. + +## Solution + +```kotlin +class Solution { + fun splitString(s: String): Boolean { + return solve(0, -1, s, 0) + } + + private fun solve(i: Int, prev: Long, s: String, k: Int): Boolean { + if (i == s.length) { + return k >= 2 + } + var cur: Long = 0 + for (j in i until s.length) { + cur = cur * 10 + s[j].code.toLong() - '0'.code.toLong() + if ((prev == -1L || prev - cur == 1L) && solve(j + 1, cur, s, k + 1)) { + return true + } + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1850_minimum_adjacent_swaps_to_reach_the_kth_smallest_number/readme.md b/src/main/kotlin/g1801_1900/s1850_minimum_adjacent_swaps_to_reach_the_kth_smallest_number/readme.md new file mode 100644 index 00000000..0ce33156 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1850_minimum_adjacent_swaps_to_reach_the_kth_smallest_number/readme.md @@ -0,0 +1,114 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1850\. Minimum Adjacent Swaps to Reach the Kth Smallest Number + +Medium + +You are given a string `num`, representing a large integer, and an integer `k`. + +We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. + +* For example, when `num = "5489355142"`: + * The 1st smallest wonderful integer is `"5489355214"`. + * The 2nd smallest wonderful integer is `"5489355241"`. + * The 3rd smallest wonderful integer is `"5489355412"`. + * The 4th smallest wonderful integer is `"5489355421"`. + +Return _the **minimum number of adjacent digit swaps** that needs to be applied to_ `num` _to reach the_ kth _**smallest wonderful** integer_. + +The tests are generated in such a way that kth smallest wonderful integer exists. + +**Example 1:** + +**Input:** num = "5489355142", k = 4 + +**Output:** 2 + +**Explanation:** The 4th smallest wonderful number is "5489355421". To get this number: + +- Swap index 7 with index 8: "5489355142" -> "5489355412" + +- Swap index 8 with index 9: "5489355412" -> "5489355421" + +**Example 2:** + +**Input:** num = "11112", k = 4 + +**Output:** 4 + +**Explanation:** The 4th smallest wonderful number is "21111". To get this number: + +- Swap index 3 with index 4: "11112" -> "11121" + +- Swap index 2 with index 3: "11121" -> "11211" + +- Swap index 1 with index 2: "11211" -> "12111" + +- Swap index 0 with index 1: "12111" -> "21111" + +**Example 3:** + +**Input:** num = "00123", k = 1 + +**Output:** 1 + +**Explanation:** The 1st smallest wonderful number is "00132". To get this number: + +- Swap index 3 with index 4: "00123" -> "00132" + +**Constraints:** + +* `2 <= num.length <= 1000` +* `1 <= k <= 1000` +* `num` only consists of digits. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun getMinSwaps(num: String, k: Int): Int { + var k = k + val result = num.toCharArray() + while (--k >= 0) { + var swap = result.size - 2 + while (swap >= 0 && result[swap] >= result[swap + 1]) { + --swap + } + var pair = result.size - 1 + while (pair > swap && result[swap] >= result[pair]) { + --pair + } + swap(result, swap, pair) + var lo = swap + 1 + var hi = result.size - 1 + while (lo < hi) { + swap(result, lo++, hi--) + } + } + var ans = 0 + val arr = num.toCharArray() + for (i in arr.indices) { + if (arr[i] == result[i]) { + continue + } + var j = i + while (arr[i] != result[j]) { + ++j + } + ans += j - i + while (--j >= i) { + swap(result, j, j + 1) + } + } + return ans + } + + private fun swap(arr: CharArray, a: Int, b: Int) { + val tmp = arr[a] + arr[a] = arr[b] + arr[b] = tmp + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1851_minimum_interval_to_include_each_query/readme.md b/src/main/kotlin/g1801_1900/s1851_minimum_interval_to_include_each_query/readme.md new file mode 100644 index 00000000..81e27dcd --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1851_minimum_interval_to_include_each_query/readme.md @@ -0,0 +1,87 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1851\. Minimum Interval to Include Each Query + +Hard + +You are given a 2D integer array `intervals`, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti **(inclusive)**. The **size** of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1. + +You are also given an integer array `queries`. The answer to the jth query is the **size of the smallest interval** `i` such that lefti <= queries[j] <= righti. If no such interval exists, the answer is `-1`. + +Return _an array containing the answers to the queries_. + +**Example 1:** + +**Input:** intervals = \[\[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5] + +**Output:** [3,3,1,4] + +**Explanation:** The queries are processed as follows: + +- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3. + +- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3. + +- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1. + +- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4. + +**Example 2:** + +**Input:** intervals = \[\[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22] + +**Output:** [2,-1,4,6] + +**Explanation:** The queries are processed as follows: + +- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2. + +- Query = 19: None of the intervals contain 19. The answer is -1. + +- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4. + +- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6. + +**Constraints:** + +* 1 <= intervals.length <= 105 +* 1 <= queries.length <= 105 +* `intervals[i].length == 2` +* 1 <= lefti <= righti <= 107 +* 1 <= queries[j] <= 107 + +## Solution + +```kotlin +import java.util.Arrays +import java.util.PriorityQueue + +class Solution { + fun minInterval(intervals: Array, queries: IntArray): IntArray { + val numQuery = queries.size + val queriesWithIndex = Array(numQuery) { IntArray(2) } + for (i in 0 until numQuery) { + queriesWithIndex[i] = intArrayOf(queries[i], i) + } + Arrays.sort(intervals, { a: IntArray, b: IntArray -> a[0].compareTo(b[0]) }) + Arrays.sort(queriesWithIndex, { a: IntArray, b: IntArray -> a[0].compareTo(b[0]) }) + val minHeap = PriorityQueue({ a: IntArray, b: IntArray -> (a[1] - a[0]).compareTo(b[1] - b[0]) }) + val result = IntArray(numQuery) + var j = 0 + for (i in queries.indices) { + val queryVal = queriesWithIndex[i][0] + val queryIndex = queriesWithIndex[i][1] + while (j < intervals.size && intervals[j][0] <= queryVal) { + minHeap.add(intervals[j]) + j++ + } + while (minHeap.isNotEmpty() && minHeap.peek()[1] < queryVal) { + minHeap.remove() + } + result[queryIndex] = if (minHeap.isEmpty()) -1 else minHeap.peek()[1] - minHeap.peek()[0] + 1 + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1854_maximum_population_year/readme.md b/src/main/kotlin/g1801_1900/s1854_maximum_population_year/readme.md new file mode 100644 index 00000000..5ef6b7f1 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1854_maximum_population_year/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) + +## 1854\. Maximum Population Year + +Easy + +You are given a 2D integer array `logs` where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. + +The **population** of some year `x` is the number of people alive during that year. The ith person is counted in year `x`'s population if `x` is in the **inclusive** range [birthi, deathi - 1]. Note that the person is **not** counted in the year that they die. + +Return _the **earliest** year with the **maximum population**_. + +**Example 1:** + +**Input:** logs = \[\[1993,1999],[2000,2010]] + +**Output:** 1993 + +**Explanation:** The maximum population is 1, and 1993 is the earliest year with this population. + +**Example 2:** + +**Input:** logs = \[\[1950,1961],[1960,1971],[1970,1981]] + +**Output:** 1960 + +**Explanation:** + +The maximum population is 2, and it had happened in years 1960 and 1970. + +The earlier year between them is 1960. + +**Constraints:** + +* `1 <= logs.length <= 100` +* 1950 <= birthi < deathi <= 2050 + +## Solution + +```kotlin +class Solution { + fun maximumPopulation(logs: Array): Int { + val arr = IntArray(101) + for (log in logs) { + arr[log[0] - 1950]++ + arr[log[1] - 1950]-- + } + for (i in 1..100) { + arr[i] += arr[i - 1] + } + var maxyear = 1950 + var max = 0 + for (i in 0..100) { + if (arr[i] > max) { + max = arr[i] + maxyear = i + 1950 + } + } + return maxyear + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1855_maximum_distance_between_a_pair_of_values/readme.md b/src/main/kotlin/g1801_1900/s1855_maximum_distance_between_a_pair_of_values/readme.md new file mode 100644 index 00000000..70ce8463 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1855_maximum_distance_between_a_pair_of_values/readme.md @@ -0,0 +1,69 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1855\. Maximum Distance Between a Pair of Values + +Medium + +You are given two **non-increasing 0-indexed** integer arrays `nums1` and `nums2`. + +A pair of indices `(i, j)`, where `0 <= i < nums1.length` and `0 <= j < nums2.length`, is **valid** if both `i <= j` and `nums1[i] <= nums2[j]`. The **distance** of the pair is `j - i`. + +Return _the **maximum distance** of any **valid** pair_ `(i, j)`_. If there are no valid pairs, return_ `0`. + +An array `arr` is **non-increasing** if `arr[i-1] >= arr[i]` for every `1 <= i < arr.length`. + +**Example 1:** + +**Input:** nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5] + +**Output:** 2 + +**Explanation:** The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4). The maximum distance is 2 with pair (2,4). + +**Example 2:** + +**Input:** nums1 = [2,2,2], nums2 = [10,10,1] + +**Output:** 1 + +**Explanation:** The valid pairs are (0,0), (0,1), and (1,1). The maximum distance is 1 with pair (0,1). + +**Example 3:** + +**Input:** nums1 = [30,29,19,5], nums2 = [25,25,25,25,25] + +**Output:** 2 + +**Explanation:** The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4). The maximum distance is 2 with pair (2,4). + +**Constraints:** + +* 1 <= nums1.length, nums2.length <= 105 +* 1 <= nums1[i], nums2[j] <= 105 +* Both `nums1` and `nums2` are **non-increasing**. + +## Solution + +```kotlin +class Solution { + fun maxDistance(nums1: IntArray, nums2: IntArray): Int { + val n = nums1.size + val m = nums2.size + var po1 = 0 + var po2 = 0 + var res = 0 + while (po1 < n && po2 < m) { + if (nums1[po1] > nums2[po2]) { + po1++ + } else { + if (po2 != po1) { + res = Math.max(res, po2 - po1) + } + po2++ + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1856_maximum_subarray_min_product/readme.md b/src/main/kotlin/g1801_1900/s1856_maximum_subarray_min_product/readme.md new file mode 100644 index 00000000..e5d46963 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1856_maximum_subarray_min_product/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) + +## 1856\. Maximum Subarray Min-Product + +Medium + +The **min-product** of an array is equal to the **minimum value** in the array **multiplied by** the array's **sum**. + +* For example, the array `[3,2,5]` (minimum value is `2`) has a min-product of `2 * (3+2+5) = 2 * 10 = 20`. + +Given an array of integers `nums`, return _the **maximum min-product** of any **non-empty subarray** of_ `nums`. Since the answer may be large, return it **modulo** 109 + 7. + +Note that the min-product should be maximized **before** performing the modulo operation. Testcases are generated such that the maximum min-product **without** modulo will fit in a **64-bit signed integer**. + +A **subarray** is a **contiguous** part of an array. + +**Example 1:** + +**Input:** nums = [1,2,3,2] + +**Output:** 14 + +**Explanation:** The maximum min-product is achieved with the subarray [2,3,2] (minimum value is 2). 2 \* (2+3+2) = 2 \* 7 = 14. + +**Example 2:** + +**Input:** nums = [2,3,3,1,2] + +**Output:** 18 + +**Explanation:** The maximum min-product is achieved with the subarray [3,3] (minimum value is 3). 3 \* (3+3) = 3 \* 6 = 18. + +**Example 3:** + +**Input:** nums = [3,1,5,6,4,2] + +**Output:** 60 + +**Explanation:** The maximum min-product is achieved with the subarray [5,6,4] (minimum value is 4). 4 \* (5+6+4) = 4 \* 15 = 60. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 107 + +## Solution + +```kotlin +class Solution { + fun maxSumMinProduct(nums: IntArray): Int { + val n = nums.size + val mod = (1e9 + 7).toInt() + if (n == 1) { + return (nums[0].toLong() * nums[0].toLong() % mod).toInt() + } + val left = IntArray(n) + left[0] = -1 + for (i in 1 until n) { + var p = i - 1 + while (p >= 0 && nums[p] >= nums[i]) { + p = left[p] + } + left[i] = p + } + val right = IntArray(n) + right[n - 1] = n + for (i in n - 2 downTo 0) { + var p = i + 1 + while (p < n && nums[p] >= nums[i]) { + p = right[p] + } + right[i] = p + } + var res = 0L + val preSum = LongArray(n) + preSum[0] = nums[0].toLong() + for (i in 1 until n) { + preSum[i] = preSum[i - 1] + nums[i] + } + for (i in 0 until n) { + val sum = if (left[i] == -1) preSum[right[i] - 1] else preSum[right[i] - 1] - preSum[left[i]] + val cur = nums[i] * sum + res = Math.max(cur, res) + } + return (res % mod).toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1857_largest_color_value_in_a_directed_graph/readme.md b/src/main/kotlin/g1801_1900/s1857_largest_color_value_in_a_directed_graph/readme.md new file mode 100644 index 00000000..11025cae --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1857_largest_color_value_in_a_directed_graph/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) + +## 1857\. Largest Color Value in a Directed Graph + +Hard + +There is a **directed graph** of `n` colored nodes and `m` edges. The nodes are numbered from `0` to `n - 1`. + +You are given a string `colors` where `colors[i]` is a lowercase English letter representing the **color** of the ith node in this graph (**0-indexed**). You are also given a 2D array `edges` where edges[j] = [aj, bj] indicates that there is a **directed edge** from node aj to node bj. + +A valid **path** in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every `1 <= i < k`. The **color value** of the path is the number of nodes that are colored the **most frequently** occurring color along that path. + +Return _the **largest color value** of any valid path in the given graph, or_ `-1` _if the graph contains a cycle_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/21/leet1.png) + +**Input:** colors = "abaca", edges = \[\[0,1],[0,2],[2,3],[3,4]] + +**Output:** 3 + +**Explanation:** The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored `"a" (red in the above image)`. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/04/21/leet2.png) + +**Input:** colors = "a", edges = \[\[0,0]] + +**Output:** -1 + +**Explanation:** There is a cycle from 0 to 0. + +**Constraints:** + +* `n == colors.length` +* `m == edges.length` +* 1 <= n <= 105 +* 0 <= m <= 105 +* `colors` consists of lowercase English letters. +* 0 <= aj, bj < n + +## Solution + +```kotlin +class Solution { + fun largestPathValue(colors: String, edges: Array): Int { + val len = colors.length + val graph = buildGraph(len, edges) + val frequencies = IntArray(26) + val calculatedFrequencies = HashMap() + val status = IntArray(len) + for (i in 0 until len) { + if (status[i] != 0) { + continue + } + val localMax = runDFS(graph, i, calculatedFrequencies, status, colors) + if (localMax!![26] == -1) { + frequencies.fill(-1) + break + } else { + for (color in 0..25) { + frequencies[color] = Math.max(frequencies[color], localMax[color]) + } + } + } + var max = Int.MIN_VALUE + for (freq in frequencies) { + max = Math.max(max, freq) + } + return max + } + + private fun runDFS( + graph: Array?>, + node: Int, + calculatedFrequencies: HashMap, + status: IntArray, + colors: String + ): IntArray? { + if (calculatedFrequencies.containsKey(node)) { + return calculatedFrequencies[node] + } + val frequencies = IntArray(27) + if (status[node] == 1) { + frequencies[26] = -1 + return frequencies + } + status[node] = 1 + for (neighbour in graph[node]!!) { + val localMax = runDFS(graph, neighbour, calculatedFrequencies, status, colors) + if (localMax!![26] == -1) { + return localMax + } + for (i in 0..25) { + frequencies[i] = Math.max(frequencies[i], localMax[i]) + } + } + status[node] = 2 + val color = colors[node].code - 'a'.code + frequencies[color]++ + calculatedFrequencies[node] = frequencies + return frequencies + } + + private fun buildGraph(n: Int, edges: Array): Array?> { + val graph: Array?> = arrayOfNulls(n) + for (i in 0 until n) { + graph[i] = ArrayList() + } + for (edge in edges) { + graph[edge[0]]?.add(edge[1]) + } + return graph + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1859_sorting_the_sentence/readme.md b/src/main/kotlin/g1801_1900/s1859_sorting_the_sentence/readme.md new file mode 100644 index 00000000..84d1da22 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1859_sorting_the_sentence/readme.md @@ -0,0 +1,61 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1859\. Sorting the Sentence + +Easy + +A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. + +A sentence can be **shuffled** by appending the **1-indexed word position** to each word then rearranging the words in the sentence. + +* For example, the sentence `"This is a sentence"` can be shuffled as `"sentence4 a3 is2 This1"` or `"is2 sentence4 This1 a3"`. + +Given a **shuffled sentence** `s` containing no more than `9` words, reconstruct and return _the original sentence_. + +**Example 1:** + +**Input:** s = "is2 sentence4 This1 a3" + +**Output:** "This is a sentence" + +**Explanation:** Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers. + +**Example 2:** + +**Input:** s = "Myself2 Me1 I4 and3" + +**Output:** "Me Myself and I" + +**Explanation:** Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers. + +**Constraints:** + +* `2 <= s.length <= 200` +* `s` consists of lowercase and uppercase English letters, spaces, and digits from `1` to `9`. +* The number of words in `s` is between `1` and `9`. +* The words in `s` are separated by a single space. +* `s` contains no leading or trailing spaces. + +## Solution + +```kotlin +import java.util.TreeMap + +class Solution { + fun sortSentence(s: String): String { + val words = s.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + val treeMap = TreeMap() + for (word in words) { + val key = (word[word.length - 1].toString() + "").toInt() + treeMap[key] = word.substring(0, word.length - 1) + } + val sb = StringBuilder() + for ((_, value) in treeMap) { + sb.append(value) + sb.append(" ") + } + return sb.substring(0, sb.length - 1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1860_incremental_memory_leak/readme.md b/src/main/kotlin/g1801_1900/s1860_incremental_memory_leak/readme.md new file mode 100644 index 00000000..251a70bf --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1860_incremental_memory_leak/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) + +## 1860\. Incremental Memory Leak + +Medium + +You are given two integers `memory1` and `memory2` representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second. + +At the ith second (starting from 1), `i` bits of memory are allocated to the stick with **more available memory** (or from the first memory stick if both have the same available memory). If neither stick has at least `i` bits of available memory, the program **crashes**. + +Return _an array containing_ [crashTime, memory1crash, memory2crash]_, where_ `crashTime` _is the time (in seconds) when the program crashed and_ memory1crash _and_ memory2crash _are the available bits of memory in the first and second sticks respectively_. + +**Example 1:** + +**Input:** memory1 = 2, memory2 = 2 + +**Output:** [3,1,0] + +**Explanation:** The memory is allocated as follows: + +- At the 1st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory. + +- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory. + +- At the 3rd second, the program crashes. The sticks have 1 and 0 bits available respectively. + +**Example 2:** + +**Input:** memory1 = 8, memory2 = 11 + +**Output:** [6,0,4] + +**Explanation:** The memory is allocated as follows: + +- At the 1st second, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory. + +- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory. + +- At the 3rd second, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory. + +- At the 4th second, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory. + +- At the 5th second, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory. + +- At the 6th second, the program crashes. The sticks have 0 and 4 bits available respectively. + +**Constraints:** + +* 0 <= memory1, memory2 <= 231 - 1 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun memLeak(memory1: Int, memory2: Int): IntArray { + var memory1 = memory1 + var memory2 = memory2 + var time = 1 + while (memory1 >= time || memory2 >= time) { + if (memory1 >= memory2) { + memory1 -= time + } else { + memory2 -= time + } + time++ + } + return intArrayOf(time, memory1, memory2) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1861_rotating_the_box/readme.md b/src/main/kotlin/g1801_1900/s1861_rotating_the_box/readme.md new file mode 100644 index 00000000..0f5c0258 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1861_rotating_the_box/readme.md @@ -0,0 +1,103 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1861\. Rotating the Box + +Medium + +You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following: + +* A stone `'#'` +* A stationary obstacle `'*'` +* Empty `'.'` + +The box is rotated **90 degrees clockwise**, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity **does not** affect the obstacles' positions, and the inertia from the box's rotation **does not** affect the stones' horizontal positions. + +It is **guaranteed** that each stone in `box` rests on an obstacle, another stone, or the bottom of the box. + +Return _an_ `n x m` _matrix representing the box after the rotation described above_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/08/rotatingtheboxleetcodewithstones.png) + +**Input:** + + box = \[\["#",".","#"]] + +**Output:** + + [["."], + ["#"], + ["#"]] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/04/08/rotatingtheboxleetcode2withstones.png) + +**Input:** + + box = \[\["#",".","*","."], + ["#","#","*","."]] + +**Output:** + + [["#","."], + ["#","#"], + ["*","*"], + [".","."]] + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/04/08/rotatingtheboxleetcode3withstone.png) + +**Input:** + + box = \[\["#","#","*",".","*","."], + ["#","#","#","*",".","."], + ["#","#","#",".","#","."]] + +**Output:** + + [[".","#","#"], + [".","#","#"], + ["#","#","*"], + ["#","*","."], + ["#",".","*"], + ["#",".","."]] + +**Constraints:** + +* `m == box.length` +* `n == box[i].length` +* `1 <= m, n <= 500` +* `box[i][j]` is either `'#'`, `'*'`, or `'.'`. + +## Solution + +```kotlin +class Solution { + fun rotateTheBox(box: Array): Array { + val n = box.size + val m = box[0].size + val result = Array(m) { CharArray(n) } + for (i in 0 until n) { + var j = m - 1 + var idx = m - 1 + while (j >= 0) { + if (box[i][j] == '#') { + result[j--][n - i - 1] = '.' + result[idx--][n - i - 1] = '#' + } else { + val c = box[i][j] + result[j--][n - i - 1] = c + if (c == '*') { + idx = j + } + } + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1862_sum_of_floored_pairs/readme.md b/src/main/kotlin/g1801_1900/s1862_sum_of_floored_pairs/readme.md new file mode 100644 index 00000000..e85ae8da --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1862_sum_of_floored_pairs/readme.md @@ -0,0 +1,76 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1862\. Sum of Floored Pairs + +Hard + +Given an integer array `nums`, return the sum of `floor(nums[i] / nums[j])` for all pairs of indices `0 <= i, j < nums.length` in the array. Since the answer may be too large, return it **modulo** 109 + 7. + +The `floor()` function returns the integer part of the division. + +**Example 1:** + +**Input:** nums = [2,5,9] + +**Output:** 10 + +**Explanation:** + +floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0 + +floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1 + +floor(5 / 2) = 2 + +floor(9 / 2) = 4 + +floor(9 / 5) = 1 + +We calculate the floor of the division for every pair of indices in the array then sum them up. + +**Example 2:** + +**Input:** nums = [7,7,7,7,7,7,7] + +**Output:** 49 + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun sumOfFlooredPairs(nums: IntArray): Int { + val mod: Long = 1000000007 + nums.sort() + val max = nums[nums.size - 1] + val counts = IntArray(max + 1) + val qnts = LongArray(max + 1) + for (k in nums) { + counts[k]++ + } + for (i in 1 until max + 1) { + if (counts[i] == 0) { + continue + } + var j = i + while (j <= max) { + qnts[j] += counts[i].toLong() + j = j + i + } + } + for (i in 1 until max + 1) { + qnts[i] = (qnts[i] + qnts[i - 1]) % mod + } + var sum: Long = 0 + for (k in nums) { + sum = (sum + qnts[k]) % mod + } + return sum.toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1863_sum_of_all_subset_xor_totals/readme.md b/src/main/kotlin/g1801_1900/s1863_sum_of_all_subset_xor_totals/readme.md new file mode 100644 index 00000000..ec49cf4e --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1863_sum_of_all_subset_xor_totals/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) + +## 1863\. Sum of All Subset XOR Totals + +Easy + +The **XOR total** of an array is defined as the bitwise `XOR` of **all its elements**, or `0` if the array is **empty**. + +* For example, the **XOR total** of the array `[2,5,6]` is `2 XOR 5 XOR 6 = 1`. + +Given an array `nums`, return _the **sum** of all **XOR totals** for every **subset** of_ `nums`. + +**Note:** Subsets with the **same** elements should be counted **multiple** times. + +An array `a` is a **subset** of an array `b` if `a` can be obtained from `b` by deleting some (possibly zero) elements of `b`. + +**Example 1:** + +**Input:** nums = [1,3] + +**Output:** 6 + +**Explanation:** The 4 subsets of [1,3] are: + +- The empty subset has an XOR total of 0. + +- \[1] has an XOR total of 1. + +- \[3] has an XOR total of 3. + +- \[1,3] has an XOR total of 1 XOR 3 = 2. + +0 + 1 + 3 + 2 = 6 + +**Example 2:** + +**Input:** nums = [5,1,6] + +**Output:** 28 + +**Explanation:** The 8 subsets of [5,1,6] are: + +- The empty subset has an XOR total of 0. + +- \[5] has an XOR total of 5. + +- \[1] has an XOR total of 1. + +- \[6] has an XOR total of 6. + +- \[5,1] has an XOR total of 5 XOR 1 = 4. + +- \[5,6] has an XOR total of 5 XOR 6 = 3. + +- \[1,6] has an XOR total of 1 XOR 6 = 7. + +- \[5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2. + +0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28 + +**Example 3:** + +**Input:** nums = [3,4,5,6,7,8] + +**Output:** 480 + +**Explanation:** The sum of all XOR totals for every subset is 480. + +**Constraints:** + +* `1 <= nums.length <= 12` +* `1 <= nums[i] <= 20` + +## Solution + +```kotlin +class Solution { + fun subsetXORSum(nums: IntArray): Int { + return if (nums.isEmpty()) { + 0 + } else subsetXORSum(nums, 0, 0) + } + + private fun subsetXORSum(nums: IntArray, currIndex: Int, res: Int): Int { + if (currIndex == nums.size) { + return res + } + val sum1 = subsetXORSum(nums, currIndex + 1, nums[currIndex] xor res) + val sum2 = subsetXORSum(nums, currIndex + 1, res) + return sum1 + sum2 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1864_minimum_number_of_swaps_to_make_the_binary_string_alternating/readme.md b/src/main/kotlin/g1801_1900/s1864_minimum_number_of_swaps_to_make_the_binary_string_alternating/readme.md new file mode 100644 index 00000000..33125dff --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1864_minimum_number_of_swaps_to_make_the_binary_string_alternating/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) + +## 1864\. Minimum Number of Swaps to Make the Binary String Alternating + +Medium + +Given a binary string `s`, return _the **minimum** number of character swaps to make it **alternating**, or_ `-1` _if it is impossible._ + +The string is called **alternating** if no two adjacent characters are equal. For example, the strings `"010"` and `"1010"` are alternating, while the string `"0100"` is not. + +Any two characters may be swapped, even if they are **not adjacent**. + +**Example 1:** + +**Input:** s = "111000" + +**Output:** 1 + +**Explanation:** Swap positions 1 and 4: "111000" -> "101010" The string is now alternating. + +**Example 2:** + +**Input:** s = "010" + +**Output:** 0 + +**Explanation:** The string is already alternating, no swaps are needed. + +**Example 3:** + +**Input:** s = "1110" + +**Output:** -1 + +**Constraints:** + +* `1 <= s.length <= 1000` +* `s[i]` is either `'0'` or `'1'`. + +## Solution + +```kotlin +class Solution { + fun minSwaps(s: String): Int { + val count = Array(2) { IntArray(2) } + for (i in 0 until s.length) { + val c = s[i] + if (i % 2 == 0) { + count[0][c.code - '0'.code]++ + } else { + count[1][c.code - '0'.code]++ + } + } + if (count[0][0] == 0 && count[1][1] == 0 || count[0][1] == 0 && count[1][0] == 0) { + return 0 + } + if (count[0][0] != count[1][1] && count[0][1] != count[1][0]) { + return -1 + } + val ans1 = if (count[0][0] == count[1][1]) count[0][0] else Int.MAX_VALUE + val ans2 = if (count[0][1] == count[1][0]) count[0][1] else Int.MAX_VALUE + return Math.min(ans1, ans2) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1865_finding_pairs_with_a_certain_sum/readme.md b/src/main/kotlin/g1801_1900/s1865_finding_pairs_with_a_certain_sum/readme.md new file mode 100644 index 00000000..5b6e1f04 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1865_finding_pairs_with_a_certain_sum/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) + +## 1865\. Finding Pairs With a Certain Sum + +Medium + +You are given two integer arrays `nums1` and `nums2`. You are tasked to implement a data structure that supports queries of two types: + +1. **Add** a positive integer to an element of a given index in the array `nums2`. +2. **Count** the number of pairs `(i, j)` such that `nums1[i] + nums2[j]` equals a given value (`0 <= i < nums1.length` and `0 <= j < nums2.length`). + +Implement the `FindSumPairs` class: + +* `FindSumPairs(int[] nums1, int[] nums2)` Initializes the `FindSumPairs` object with two integer arrays `nums1` and `nums2`. +* `void add(int index, int val)` Adds `val` to `nums2[index]`, i.e., apply `nums2[index] += val`. +* `int count(int tot)` Returns the number of pairs `(i, j)` such that `nums1[i] + nums2[j] == tot`. + +**Example 1:** + +**Input** ["FindSumPairs", "count", "add", "count", "count", "add", "add", "count"] [[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]] + +**Output:** [null, 8, null, 2, 1, null, null, 11] + +**Explanation:** + +FindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]); + +findSumPairs.count(7); // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4 + +findSumPairs.add(3, 2); // now nums2 = [1,4,5,**4**`,5,4`] + +findSumPairs.count(8); // return 2; pairs (5,2), (5,4) make 3 + 5 + +findSumPairs.count(4); // return 1; pair (5,0) makes 3 + 1 + +findSumPairs.add(0, 1); // now nums2 = [**`2`**,4,5,4`,5,4`] + +findSumPairs.add(1, 1); // now nums2 = [`2`,**5**,5,4`,5,4`] + +findSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4 + +**Constraints:** + +* `1 <= nums1.length <= 1000` +* 1 <= nums2.length <= 105 +* 1 <= nums1[i] <= 109 +* 1 <= nums2[i] <= 105 +* `0 <= index < nums2.length` +* 1 <= val <= 105 +* 1 <= tot <= 109 +* At most `1000` calls are made to `add` and `count` **each**. + +## Solution + +```kotlin +class FindSumPairs(private val nums1: IntArray, private val nums2: IntArray) { + private val numFreq: MutableMap = HashMap() + + init { + for (num in nums2) { + numFreq[num] = numFreq.getOrDefault(num, 0) + 1 + } + } + + fun add(index: Int, `val`: Int) { + numFreq[nums2[index]] = numFreq.getOrDefault(nums2[index], 0) - 1 + nums2[index] += `val` + numFreq[nums2[index]] = numFreq.getOrDefault(nums2[index], 0) + 1 + } + + fun count(tot: Int): Int { + var res = 0 + for (num in nums1) { + res += numFreq.getOrDefault(tot - num, 0) + } + return res + } +} +/* + * Your FindSumPairs object will be instantiated and called as such: + * var obj = FindSumPairs(nums1, nums2) + * obj.add(index,`val`) + * var param_2 = obj.count(tot) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1866_number_of_ways_to_rearrange_sticks_with_k_sticks_visible/readme.md b/src/main/kotlin/g1801_1900/s1866_number_of_ways_to_rearrange_sticks_with_k_sticks_visible/readme.md new file mode 100644 index 00000000..428b9c63 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1866_number_of_ways_to_rearrange_sticks_with_k_sticks_visible/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) + +## 1866\. Number of Ways to Rearrange Sticks With K Sticks Visible + +Hard + +There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. + +* For example, if the sticks are arranged `[1,3,2,5,4]`, then the sticks with lengths `1`, `3`, and `5` are visible from the left. + +Given `n` and `k`, return _the **number** of such arrangements_. Since the answer may be large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** n = 3, k = 2 + +**Output:** 3 + +**Explanation:** [1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible. The visible sticks are underlined. + +**Example 2:** + +**Input:** n = 5, k = 5 + +**Output:** 1 + +**Explanation:** [1,2,3,4,5] is the only arrangement such that all 5 sticks are visible. The visible sticks are underlined. + +**Example 3:** + +**Input:** n = 20, k = 11 + +**Output:** 647427950 + +**Explanation:** There are 647427950 (mod 109 \+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible. + +**Constraints:** + +* `1 <= n <= 1000` +* `1 <= k <= n` + +## Solution + +```kotlin +class Solution { + fun rearrangeSticks(n: Int, k: Int): Int { + if (k > n || k < 1) { + return 0 + } + if (k == n) { + return 1 + } + var dp = LongArray(k + 1) + dp.fill(1) + var i = 1 + while (i + k <= n) { + val dp2 = LongArray(k + 1) + for (j in 1..k) { + dp2[j] = (dp2[j - 1] + (i + j - 1) * dp[j]) % MOD + } + dp = dp2 + i++ + } + return dp[k].toInt() + } + + companion object { + private const val MOD = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1869_longer_contiguous_segments_of_ones_than_zeros/readme.md b/src/main/kotlin/g1801_1900/s1869_longer_contiguous_segments_of_ones_than_zeros/readme.md new file mode 100644 index 00000000..7364e960 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1869_longer_contiguous_segments_of_ones_than_zeros/readme.md @@ -0,0 +1,88 @@ +[![](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) + +## 1869\. Longer Contiguous Segments of Ones than Zeros + +Easy + +Given a binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_. + +* For example, in `s = "110100010"` the longest continuous segment of `1`s has length `2`, and the longest continuous segment of `0`s has length `3`. + +Note that if there are no `0`'s, then the longest continuous segment of `0`'s is considered to have a length `0`. The same applies if there is no `1`'s. + +**Example 1:** + +**Input:** s = "1101" + +**Output:** true + +**Explanation:** + +The longest contiguous segment of 1s has length 2: "1101" + +The longest contiguous segment of 0s has length 1: "1101" + +The segment of 1s is longer, so return true. + +**Example 2:** + +**Input:** s = "111000" + +**Output:** false + +**Explanation:** + +The longest contiguous segment of 1s has length 3: "111000" + +The longest contiguous segment of 0s has length 3: "111000" + +The segment of 1s is not longer, so return false. + +**Example 3:** + +**Input:** s = "110100010" + +**Output:** false + +**Explanation:** + +The longest contiguous segment of 1s has length 2: "110100010" + +The longest contiguous segment of 0s has length 3: "110100010" + +The segment of 1s is not longer, so return false. + +**Constraints:** + +* `1 <= s.length <= 100` +* `s[i]` is either `'0'` or `'1'`. + +## Solution + +```kotlin +class Solution { + fun checkZeroOnes(s: String): Boolean { + var zeroes = 0 + var ones = 0 + var i = 0 + while (i < s.length) { + var start = i + while (i < s.length && s[i] == '0') { + i++ + } + if (i > start) { + zeroes = Math.max(zeroes, i - start) + } + start = i + while (i < s.length && s[i] == '1') { + i++ + } + if (i > start) { + ones = Math.max(ones, i - start) + } + } + return ones > zeroes + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1870_minimum_speed_to_arrive_on_time/readme.md b/src/main/kotlin/g1801_1900/s1870_minimum_speed_to_arrive_on_time/readme.md new file mode 100644 index 00000000..f8e52bf5 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1870_minimum_speed_to_arrive_on_time/readme.md @@ -0,0 +1,113 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1870\. Minimum Speed to Arrive on Time + +Medium + +You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the ith train ride. + +Each train can only depart at an integer hour, so you may need to wait in between each train ride. + +* For example, if the 1st train ride takes `1.5` hours, you must wait for an additional `0.5` hours before you can depart on the 2nd train ride at the 2 hour mark. + +Return _the **minimum positive integer** speed **(in kilometers per hour)** that all the trains must travel at for you to reach the office on time, or_ `-1` _if it is impossible to be on time_. + +Tests are generated such that the answer will not exceed 107 and `hour` will have **at most two digits after the decimal point**. + +**Example 1:** + +**Input:** dist = [1,3,2], hour = 6 + +**Output:** 1 + +**Explanation:** At speed 1: + +- The first train ride takes 1/1 = 1 hour. + +- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours. + +- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours. + +- You will arrive at exactly the 6 hour mark. + +**Example 2:** + +**Input:** dist = [1,3,2], hour = 2.7 + +**Output:** 3 + +**Explanation:** At speed 3: + +- The first train ride takes 1/3 = 0.33333 hours. + +- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour. + +- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours. + +- You will arrive at the 2.66667 hour mark. + +**Example 3:** + +**Input:** dist = [1,3,2], hour = 1.9 + +**Output:** -1 + +**Explanation:** It is impossible because the earliest the third train can depart is at the 2 hour mark. + +**Constraints:** + +* `n == dist.length` +* 1 <= n <= 105 +* 1 <= dist[i] <= 105 +* 1 <= hour <= 109 +* There will be at most two digits after the decimal point in `hour`. + +## Solution + +```kotlin +class Solution { + fun minSpeedOnTime(dist: IntArray, hour: Double): Int { + val n = dist.size + return fmin(dist, n, hour) + } + + private fun check(dist: IntArray, n: Int, h: Double, spe: Int): Boolean { + var cost = 0.0 + for (i in 0 until n - 1) { + // same as ceil(doubleTime/doubleSpeed) + cost += ((dist[i] - 1) / spe + 1).toDouble() + } + cost += dist[n - 1].toDouble() / spe.toDouble() + return cost <= h + } + + private fun fmin(dist: IntArray, n: Int, h: Double): Int { + if (h + 1 <= n) { + return -1 + } + val max = fmax(dist) * 100 + var lo = 1 + var hi = max + while (lo < hi) { + val mid = (lo + hi) / 2 + // speed of mid is possible, move to left side + if (check(dist, n, h, mid)) { + hi = mid + } else { + // need higher speed, move to right side + lo = mid + 1 + } + } + return lo + } + + private fun fmax(arr: IntArray): Int { + var res = arr[0] + for (num in arr) { + res = Math.max(res, num) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1871_jump_game_vii/readme.md b/src/main/kotlin/g1801_1900/s1871_jump_game_vii/readme.md new file mode 100644 index 00000000..a2017d44 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1871_jump_game_vii/readme.md @@ -0,0 +1,69 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1871\. Jump Game VII + +Medium + +You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled: + +* `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and +* `s[j] == '0'`. + +Return `true` _if you can reach index_ `s.length - 1` _in_ `s`_, or_ `false` _otherwise._ + +**Example 1:** + +**Input:** s = "011010", minJump = 2, maxJump = 3 + +**Output:** true + +**Explanation:** + +In the first step, move from index 0 to index 3. + +In the second step, move from index 3 to index 5. + +**Example 2:** + +**Input:** s = "01101110", minJump = 2, maxJump = 3 + +**Output:** false + +**Constraints:** + +* 2 <= s.length <= 105 +* `s[i]` is either `'0'` or `'1'`. +* `s[0] == '0'` +* `1 <= minJump <= maxJump < s.length` + +## Solution + +```kotlin +class Solution { + fun canReach(s: String, minJump: Int, maxJump: Int): Boolean { + var j = 0 + val n = s.length + val li = s.toCharArray() + var i = 0 + while (i < n) { + + // o == ok + if (i == 0 || li[i] == 'o') { + j = Math.max(j, i + minJump) + while (j < Math.min(n, i + maxJump + 1)) { + if (li[j] == '0') { + li[j] = 'o' + } + j++ + } + } + if (j > n) { + break + } + i++ + } + return li[n - 1] == 'o' + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1872_stone_game_viii/readme.md b/src/main/kotlin/g1801_1900/s1872_stone_game_viii/readme.md new file mode 100644 index 00000000..d692e0ca --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1872_stone_game_viii/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) + +## 1872\. Stone Game VIII + +Hard + +Alice and Bob take turns playing a game, with **Alice starting first**. + +There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: + +1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. +2. Add the **sum** of the **removed** stones' values to the player's score. +3. Place a **new stone**, whose value is equal to that sum, on the left side of the row. + +The game stops when **only** **one** stone is left in the row. + +The **score difference** between Alice and Bob is `(Alice's score - Bob's score)`. Alice's goal is to **maximize** the score difference, and Bob's goal is the **minimize** the score difference. + +Given an integer array `stones` of length `n` where `stones[i]` represents the value of the ith stone **from the left**, return _the **score difference** between Alice and Bob if they both play **optimally**._ + +**Example 1:** + +**Input:** stones = [-1,2,-3,4,-5] + +**Output:** 5 + +**Explanation:** + +- Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of value 2 on the left. stones = [2,-5]. + +- Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on the left. stones = [-3]. + +The difference between their scores is 2 - (-3) = 5. + +**Example 2:** + +**Input:** stones = [7,-6,5,10,5,-2,-6] + +**Output:** 13 + +**Explanation:** + +- Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a stone of value 13 on the left. stones = [13]. + +The difference between their scores is 13 - 0 = 13. + +**Example 3:** + +**Input:** stones = [-10,-12] + +**Output:** -22 + +**Explanation:** - Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her score and places a stone of value -22 on the left. stones = [-22]. + +The difference between their scores is (-22) - 0 = -22. + +**Constraints:** + +* `n == stones.length` +* 2 <= n <= 105 +* -104 <= stones[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun stoneGameVIII(stones: IntArray): Int { + if (stones.size <= 1) { + return 0 + } + val n = stones.size + for (i in 1 until n) { + stones[i] = stones[i - 1] + stones[i] + } + // presum stones[] is ready; + // dp[n-2] + var dp = stones[n - 1] + // The game stops when only one stone is left in the row. + for (i in n - 3 downTo 0) { + dp = Math.max(stones[i + 1] - dp, dp) + } + return dp + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1873_calculate_special_bonus/readme.md b/src/main/kotlin/g1801_1900/s1873_calculate_special_bonus/readme.md new file mode 100644 index 00000000..887ad474 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1873_calculate_special_bonus/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) + +## 1873\. Calculate Special Bonus + +Easy + +SQL Schema + +Table: `Employees` + + +-------------+---------+ + | Column Name | Type | + +-------------+---------+ + | employee_id | int | + | name | varchar | + | salary | int | + +-------------+---------+ + employee_id is the primary key for this table. + Each row of this table indicates the employee ID, employee name, and salary. + +Write an SQL query to calculate the bonus of each employee. The bonus of an employee is `100%` of their salary if the ID of the employee is **an odd number** and **the employee name does not start with the character** `'M'`. The bonus of an employee is `0` otherwise. + +Return the result table ordered by `employee_id`. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Employees table: + +-------------+---------+--------+ + | employee_id | name | salary | + +-------------+---------+--------+ + | 2 | Meir | 3000 | + | 3 | Michael | 3800 | + | 7 | Addilyn | 7400 | + | 8 | Juan | 6100 | + | 9 | Kannon | 7700 | + +-------------+---------+--------+ + +**Output:** + + +-------------+-------+ + | employee_id | bonus | + +-------------+-------+ + | 2 | 0 | + | 3 | 0 | + | 7 | 7400 | + | 8 | 0 | + | 9 | 7700 | + +-------------+-------+ + +**Explanation:** + +The employees with IDs 2 and 8 get 0 bonus because they have an even employee_id. + +The employee with ID 3 gets 0 bonus because their name starts with 'M'. + +The rest of the employees get a 100% bonus. + +## Solution + +```sql +# Write your MySQL query statement below +select employee_id, +(case when (employee_id%2=1 and name not like 'M%') then salary else 0 end )as bonus +from employees +order by employee_id; +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1876_substrings_of_size_three_with_distinct_characters/readme.md b/src/main/kotlin/g1801_1900/s1876_substrings_of_size_three_with_distinct_characters/readme.md new file mode 100644 index 00000000..163f10fa --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1876_substrings_of_size_three_with_distinct_characters/readme.md @@ -0,0 +1,52 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1876\. Substrings of Size Three with Distinct Characters + +Easy + +A string is **good** if there are no repeated characters. + +Given a string `s`, return _the number of **good substrings** of length **three** in_ `s`. + +Note that if there are multiple occurrences of the same substring, every occurrence should be counted. + +A **substring** is a contiguous sequence of characters in a string. + +**Example 1:** + +**Input:** s = "xyzzaz" + +**Output:** 1 + +**Explanation:** There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz". The only good substring of length 3 is "xyz". + +**Example 2:** + +**Input:** s = "aababcabc" + +**Output:** 4 + +**Explanation:** There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc". The good substrings are "abc", "bca", "cab", and "abc". + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun countGoodSubstrings(s: String): Int { + var count = 0 + for (i in 0 until s.length - 2) { + val candidate = s.substring(i, i + 3) + if (candidate[0] != candidate[1] && candidate[0] != candidate[2] && candidate[1] != candidate[2]) { + count++ + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1877_minimize_maximum_pair_sum_in_array/readme.md b/src/main/kotlin/g1801_1900/s1877_minimize_maximum_pair_sum_in_array/readme.md new file mode 100644 index 00000000..43a0abff --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1877_minimize_maximum_pair_sum_in_array/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) + +## 1877\. Minimize Maximum Pair Sum in Array + +Medium + +The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs. + +* For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`. + +Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that: + +* Each element of `nums` is in **exactly one** pair, and +* The **maximum pair sum** is **minimized**. + +Return _the minimized **maximum pair sum** after optimally pairing up the elements_. + +**Example 1:** + +**Input:** nums = [3,5,2,3] + +**Output:** 7 + +**Explanation:** The elements can be paired up into pairs (3,3) and (5,2). + +The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. + +**Example 2:** + +**Input:** nums = [3,5,4,2,4,6] + +**Output:** 8 + +**Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2). + +The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. + +**Constraints:** + +* `n == nums.length` +* 2 <= n <= 105 +* `n` is **even**. +* 1 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun minPairSum(nums: IntArray): Int { + nums.sort() + var start = 0 + var end = nums.size - 1 + var min = Int.MIN_VALUE + while (start < end) { + min = Math.max(min, nums[start] + nums[end]) + --end + ++start + } + return min + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1878_get_biggest_three_rhombus_sums_in_a_grid/readme.md b/src/main/kotlin/g1801_1900/s1878_get_biggest_three_rhombus_sums_in_a_grid/readme.md new file mode 100644 index 00000000..ae2abfb2 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1878_get_biggest_three_rhombus_sums_in_a_grid/readme.md @@ -0,0 +1,126 @@ +[![](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) + +## 1878\. Get Biggest Three Rhombus Sums in a Grid + +Medium + +You are given an `m x n` integer matrix `grid`. + +A **rhombus sum** is the sum of the elements that form **the** **border** of a regular rhombus shape in `grid`. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each **rhombus sum**: + +![](https://assets.leetcode.com/uploads/2021/04/23/pc73-q4-desc-2.png) + +Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner. + +Return _the biggest three **distinct rhombus sums** in the_ `grid` _in **descending order**__. If there are less than three distinct values, return all of them_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/23/pc73-q4-ex1.png) + +**Input:** grid = \[\[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]] + +**Output:** [228,216,211] + +**Explanation:** The rhombus shapes for the three biggest distinct rhombus sums are depicted above. + +- Blue: 20 + 3 + 200 + 5 = 228 + +- Red: 200 + 2 + 10 + 4 = 216 + +- Green: 5 + 200 + 4 + 2 = 211 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/04/23/pc73-q4-ex2.png) + +**Input:** grid = \[\[1,2,3],[4,5,6],[7,8,9]] + +**Output:** [20,9,8] + +**Explanation:** The rhombus shapes for the three biggest distinct rhombus sums are depicted above. + +- Blue: 4 + 2 + 6 + 8 = 20 + +- Red: 9 (area 0 rhombus in the bottom right corner) + +- Green: 8 (area 0 rhombus in the bottom middle) + +**Example 3:** + +**Input:** grid = \[\[7,7,7]] + +**Output:** [7] + +**Explanation:** All three possible rhombus sums are the same, so return [7]. + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `1 <= m, n <= 50` +* 1 <= grid[i][j] <= 105 + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + fun getBiggestThree(grid: Array): IntArray { + val capicity = 3 + val minHeap = PriorityQueue() + val m = grid.size + val n = grid[0].size + val preSum = Array(m) { Array(n) { IntArray(2) } } + val maxLen = Math.min(m, n) / 2 + for (r in 0 until m) { + for (c in 0 until n) { + addToMinHeap(minHeap, grid[r][c], capicity) + preSum[r][c][0] += if (valid(m, n, r - 1, c - 1)) grid[r][c] + preSum[r - 1][c - 1][0] else grid[r][c] + preSum[r][c][1] += if (valid(m, n, r - 1, c + 1)) grid[r][c] + preSum[r - 1][c + 1][1] else grid[r][c] + } + } + for (r in 0 until m) { + for (c in 0 until n) { + for (l in 1..maxLen) { + if (!valid(m, n, r - l, c - l) || + !valid(m, n, r - l, c + l) || + !valid(m, n, r - 2 * l, c) + ) { + break + } + var rhombus = preSum[r][c][0] - preSum[r - l][c - l][0] + rhombus += preSum[r][c][1] - preSum[r - l][c + l][1] + rhombus += preSum[r - l][c - l][1] - preSum[r - 2 * l][c][1] + rhombus += preSum[r - l][c + l][0] - preSum[r - 2 * l][c][0] + rhombus += -grid[r][c] + grid[r - 2 * l][c] + addToMinHeap(minHeap, rhombus, capicity) + } + } + } + val size = minHeap.size + val res = IntArray(size) + for (i in size - 1 downTo 0) { + res[i] = minHeap.poll() + } + return res + } + + private fun addToMinHeap(minHeap: PriorityQueue, num: Int, capicity: Int) { + if (minHeap.isEmpty() || minHeap.size < capicity && !minHeap.contains(num)) { + minHeap.offer(num) + } else { + if (num > minHeap.peek() && !minHeap.contains(num)) { + minHeap.poll() + minHeap.offer(num) + } + } + } + + private fun valid(m: Int, n: Int, r: Int, c: Int): Boolean { + return 0 <= r && r < m && 0 <= c && c < n + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1879_minimum_xor_sum_of_two_arrays/readme.md b/src/main/kotlin/g1801_1900/s1879_minimum_xor_sum_of_two_arrays/readme.md new file mode 100644 index 00000000..7536ed09 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1879_minimum_xor_sum_of_two_arrays/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) + +## 1879\. Minimum XOR Sum of Two Arrays + +Hard + +You are given two integer arrays `nums1` and `nums2` of length `n`. + +The **XOR sum** of the two integer arrays is `(nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1])` (**0-indexed**). + +* For example, the **XOR sum** of `[1,2,3]` and `[3,2,1]` is equal to `(1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4`. + +Rearrange the elements of `nums2` such that the resulting **XOR sum** is **minimized**. + +Return _the **XOR sum** after the rearrangement_. + +**Example 1:** + +**Input:** nums1 = [1,2], nums2 = [2,3] + +**Output:** 2 + +**Explanation:** Rearrange `nums2` so that it becomes `[3,2]`. The XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2. + +**Example 2:** + +**Input:** nums1 = [1,0,3], nums2 = [5,3,4] + +**Output:** 8 + +**Explanation:** Rearrange `nums2` so that it becomes `[5,4,3]`. The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8. + +**Constraints:** + +* `n == nums1.length` +* `n == nums2.length` +* `1 <= n <= 14` +* 0 <= nums1[i], nums2[i] <= 107 + +## Solution + +```kotlin +class Solution { + fun minimumXORSum(nums1: IntArray, nums2: IntArray): Int { + val l = nums1.size + val dp = IntArray(1 shl l) + dp.fill(-1) + dp[0] = 0 + return dfs(dp.size - 1, l, nums1, nums2, dp, l) + } + + private fun dfs(state: Int, length: Int, nums1: IntArray, nums2: IntArray, dp: IntArray, totalLength: Int): Int { + if (dp[state] >= 0) { + return dp[state] + } + var min = Int.MAX_VALUE + val currIndex = totalLength - length + var i = 0 + var index = 0 + while (i < length) { + if (state shr index and 1 == 1) { + val result = dfs(state xor (1 shl index), length - 1, nums1, nums2, dp, totalLength) + min = Math.min(min, (nums2[currIndex] xor nums1[index]) + result) + i++ + } + index++ + } + dp[state] = min + return min + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1880_check_if_word_equals_summation_of_two_words/readme.md b/src/main/kotlin/g1801_1900/s1880_check_if_word_equals_summation_of_two_words/readme.md new file mode 100644 index 00000000..d2e89da9 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1880_check_if_word_equals_summation_of_two_words/readme.md @@ -0,0 +1,92 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1880\. Check if Word Equals Summation of Two Words + +Easy + +The **letter value** of a letter is its position in the alphabet **starting from 0** (i.e. `'a' -> 0`, `'b' -> 1`, `'c' -> 2`, etc.). + +The **numerical value** of some string of lowercase English letters `s` is the **concatenation** of the **letter values** of each letter in `s`, which is then **converted** into an integer. + +* For example, if `s = "acb"`, we concatenate each letter's letter value, resulting in `"021"`. After converting it, we get `21`. + +You are given three strings `firstWord`, `secondWord`, and `targetWord`, each consisting of lowercase English letters `'a'` through `'j'` **inclusive**. + +Return `true` _if the **summation** of the **numerical values** of_ `firstWord` _and_ `secondWord` _equals the **numerical value** of_ `targetWord`_, or_ `false` _otherwise._ + +**Example 1:** + +**Input:** firstWord = "acb", secondWord = "cba", targetWord = "cdb" + +**Output:** true + +**Explanation:** + +The numerical value of firstWord is "acb" -> "021" -> 21. + +The numerical value of secondWord is "cba" -> "210" -> 210. + +The numerical value of targetWord is "cdb" -> "231" -> 231. + +We return true because 21 + 210 == 231. + +**Example 2:** + +**Input:** firstWord = "aaa", secondWord = "a", targetWord = "aab" + +**Output:** false + +**Explanation:** + +The numerical value of firstWord is "aaa" -> "000" -> 0. + +The numerical value of secondWord is "a" -> "0" -> 0. + +The numerical value of targetWord is "aab" -> "001" -> 1. + +We return false because 0 + 0 != 1. + +**Example 3:** + +**Input:** firstWord = "aaa", secondWord = "a", targetWord = "aaaa" + +**Output:** true + +**Explanation:** + +The numerical value of firstWord is "aaa" -> "000" -> 0. + +The numerical value of secondWord is "a" -> "0" -> 0. + +The numerical value of targetWord is "aaaa" -> "0000" -> 0. + +We return true because 0 + 0 == 0. + +**Constraints:** + +* `1 <= firstWord.length,` `secondWord.length,` `targetWord.length <= 8` +* `firstWord`, `secondWord`, and `targetWord` consist of lowercase English letters from `'a'` to `'j'` **inclusive**. + +## Solution + +```kotlin +class Solution { + fun isSumEqual(firstWord: String, secondWord: String, targetWord: String): Boolean { + val sb = StringBuilder() + val a = getSum(firstWord, sb) + sb.setLength(0) + val b = getSum(secondWord, sb) + sb.setLength(0) + val c = getSum(targetWord, sb) + return a + b == c + } + + private fun getSum(firstWord: String, sb: StringBuilder): Int { + for (c in firstWord.toCharArray()) { + sb.append(c.code - 'a'.code) + } + return sb.toString().toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1881_maximum_value_after_insertion/readme.md b/src/main/kotlin/g1801_1900/s1881_maximum_value_after_insertion/readme.md new file mode 100644 index 00000000..efe4fb8c --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1881_maximum_value_after_insertion/readme.md @@ -0,0 +1,57 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1881\. Maximum Value after Insertion + +Medium + +You are given a very large integer `n`, represented as a string, and an integer digit `x`. The digits in `n` and the digit `x` are in the **inclusive** range `[1, 9]`, and `n` may represent a **negative** number. + +You want to **maximize** `n`**'s numerical value** by inserting `x` anywhere in the decimal representation of `n`. You **cannot** insert `x` to the left of the negative sign. + +* For example, if `n = 73` and `x = 6`, it would be best to insert it between `7` and `3`, making `n = 763`. +* If `n = -55` and `x = 2`, it would be best to insert it before the first `5`, making `n = -255`. + +Return _a string representing the **maximum** value of_ `n`_ after the insertion_. + +**Example 1:** + +**Input:** n = "99", x = 9 + +**Output:** "999" + +**Explanation:** The result is the same regardless of where you insert 9. + +**Example 2:** + +**Input:** n = "-13", x = 2 + +**Output:** "-123" + +**Explanation:** You can make n one of {-213, -123, -132}, and the largest of those three is -123. + +**Constraints:** + +* 1 <= n.length <= 105 +* `1 <= x <= 9` +* The digits in `n` are in the range `[1, 9]`. +* `n` is a valid representation of an integer. +* In the case of a negative `n`, it will begin with `'-'`. + +## Solution + +```kotlin +class Solution { + fun maxValue(n: String, x: Int): String { + var i = 0 + val sign = if (n[0] == '-') -1 else 1 + while (i < n.length) { + if (n[i] != '-' && sign * (n[i].code - '0'.code) < sign * x) { + break + } + i++ + } + return n.substring(0, i) + x + n.substring(i) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1882_process_tasks_using_servers/readme.md b/src/main/kotlin/g1801_1900/s1882_process_tasks_using_servers/readme.md new file mode 100644 index 00000000..83970cbd --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1882_process_tasks_using_servers/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) + +## 1882\. Process Tasks Using Servers + +Medium + +You are given two **0-indexed** integer arrays `servers` and `tasks` of lengths `n` and `m` respectively. `servers[i]` is the **weight** of the ith server, and `tasks[j]` is the **time needed** to process the jth task **in seconds**. + +Tasks are assigned to the servers using a **task queue**. Initially, all servers are free, and the queue is **empty**. + +At second `j`, the jth task is **inserted** into the queue (starting with the 0th task being inserted at second `0`). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the **smallest weight**, and in case of a tie, it is assigned to a free server with the **smallest index**. + +If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned **in order of insertion** following the weight and index priorities above. + +A server that is assigned task `j` at second `t` will be free again at second `t + tasks[j]`. + +Build an array `ans` of length `m`, where `ans[j]` is the **index** of the server the jth task will be assigned to. + +Return _the array_ `ans`. + +**Example 1:** + +**Input:** servers = [3,3,2], tasks = [1,2,3,2,1,2] + +**Output:** [2,2,0,2,1,2] + +**Explanation:** Events in chronological order go as follows: + +- At second 0, task 0 is added and processed using server 2 until second 1. + +- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3. + +- At second 2, task 2 is added and processed using server 0 until second 5. + +- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5. + +- At second 4, task 4 is added and processed using server 1 until second 5. + +- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7. + +**Example 2:** + +**Input:** servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1] + +**Output:** [1,4,1,4,1,3,2] + +**Explanation:** Events in chronological order go as follows: + +- At second 0, task 0 is added and processed using server 1 until second 2. + +- At second 1, task 1 is added and processed using server 4 until second 2. + +- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. + +- At second 3, task 3 is added and processed using server 4 until second 7. + +- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. + +- At second 5, task 5 is added and processed using server 3 until second 7. + +- At second 6, task 6 is added and processed using server 2 until second 7. + +**Constraints:** + +* `servers.length == n` +* `tasks.length == m` +* 1 <= n, m <= 2 * 105 +* 1 <= servers[i], tasks[j] <= 2 * 105 + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + fun assignTasks(servers: IntArray, tasks: IntArray): IntArray { + val serverq = + PriorityQueue { i1: Int, i2: Int -> if (servers[i1] != servers[i2]) servers[i1] - servers[i2] else i1 - i2 } + for (i in servers.indices) { + serverq.offer(i) + } + val activetaskq = PriorityQueue { i1: IntArray, i2: IntArray -> i1[1] - i2[1] } + var time = 0 + val res = IntArray(tasks.size) + for (i in tasks.indices) { + time = Math.max(time, i) + while (activetaskq.isNotEmpty() && activetaskq.peek()[1] <= i) { + val task = activetaskq.poll() + serverq.offer(task[0]) + } + if (serverq.isEmpty()) { + val toptask = activetaskq.peek() + while (activetaskq.isNotEmpty() && activetaskq.peek()[1] == toptask[1]) { + val task = activetaskq.poll() + serverq.offer(task[0]) + } + time = toptask[1] + } + val server = serverq.poll() + res[i] = server + activetaskq.offer(intArrayOf(server, time + tasks[i])) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1883_minimum_skips_to_arrive_at_meeting_on_time/readme.md b/src/main/kotlin/g1801_1900/s1883_minimum_skips_to_arrive_at_meeting_on_time/readme.md new file mode 100644 index 00000000..bd9df9a0 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1883_minimum_skips_to_arrive_at_meeting_on_time/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) + +## 1883\. Minimum Skips to Arrive at Meeting On Time + +Hard + +You are given an integer `hoursBefore`, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through `n` roads. The road lengths are given as an integer array `dist` of length `n`, where `dist[i]` describes the length of the ith road in **kilometers**. In addition, you are given an integer `speed`, which is the speed (in **km/h**) you will travel at. + +After you travel road `i`, you must rest and wait for the **next integer hour** before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting. + +* For example, if traveling a road takes `1.4` hours, you must wait until the `2` hour mark before traveling the next road. If traveling a road takes exactly `2` hours, you do not need to wait. + +However, you are allowed to **skip** some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks. + +* For example, suppose traveling the first road takes `1.4` hours and traveling the second road takes `0.6` hours. Skipping the rest after the first road will mean you finish traveling the second road right at the `2` hour mark, letting you start traveling the third road immediately. + +Return _the **minimum number of skips required** to arrive at the meeting on time, or_ `-1` _if it is **impossible**_. + +**Example 1:** + +**Input:** dist = [1,3,2], speed = 4, hoursBefore = 2 + +**Output:** 1 + +**Explanation:** + +Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours. + +You can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours. + +Note that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest. + +**Example 2:** + +**Input:** dist = [7,3,5,5], speed = 2, hoursBefore = 10 + +**Output:** 2 + +**Explanation:** + +Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours. + +You can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours. + +**Example 3:** + +**Input:** dist = [7,3,5,5], speed = 1, hoursBefore = 10 + +**Output:** -1 + +**Explanation:** It is impossible to arrive at the meeting on time even if you skip all the rests. + +**Constraints:** + +* `n == dist.length` +* `1 <= n <= 1000` +* 1 <= dist[i] <= 105 +* 1 <= speed <= 106 +* 1 <= hoursBefore <= 107 + +## Solution + +```kotlin +class Solution { + fun minSkips(dist: IntArray, speed: Int, hoursBefore: Int): Int { + val len = dist.size + // dp[i][j] finish ith road, skip j times; + val dp = Array(len) { IntArray(len) } + dp[0][0] = dist[0] + for (i in 1 until len) { + dp[i][0] = (dp[i - 1][0] + speed - 1) / speed * speed + dist[i] + } + for (i in 1 until len) { + for (j in 0..i) { + if (j > 0) { + dp[i][j] = dp[i - 1][j - 1] + dist[i] + } + if (j <= i - 1) { + dp[i][j] = Math.min( + dp[i][j], (dp[i - 1][j] + speed - 1) / speed * speed + dist[i] + ) + } + } + } + for (i in 0 until len) { + if (dp[len - 1][i] <= speed.toLong() * hoursBefore) { + return i + } + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1884_egg_drop_with_2_eggs_and_n_floors/readme.md b/src/main/kotlin/g1801_1900/s1884_egg_drop_with_2_eggs_and_n_floors/readme.md new file mode 100644 index 00000000..3fa501d6 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1884_egg_drop_with_2_eggs_and_n_floors/readme.md @@ -0,0 +1,68 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1884\. Egg Drop With 2 Eggs and N Floors + +Medium + +You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`. + +You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. + +In each move, you may take an **unbroken** egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may **reuse** it in future moves. + +Return _the **minimum number of moves** that you need to determine **with certainty** what the value of_ `f` is. + +**Example 1:** + +**Input:** n = 2 + +**Output:** 2 + +**Explanation:** We can drop the first egg from floor 1 and the second egg from floor 2. + +If the first egg breaks, we know that f = 0. + +If the second egg breaks but the first egg didn't, we know that f = 1. + +Otherwise, if both eggs survive, we know that f = 2. + +**Example 2:** + +**Input:** n = 100 + +**Output:** 14 + +**Explanation:** One optimal strategy is: + +- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9. + +- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14. + +- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100. Regardless of the outcome, it takes at most 14 drops to determine f. + +**Constraints:** + +* `1 <= n <= 1000` + +## Solution + +```kotlin +class Solution { + fun twoEggDrop(n: Int): Int { + // given x steps, the maximum floors I can test with two eggs + val dp = IntArray(n + 1) + for (i in 1..n) { + // move is i, previous move is i - 1, + // we put egg on floor i, if egg breaks, we can check i - 1 floors with i - 1 moves + // if egg does not break, we can check dp[i-1] floors having two eggs to with i - 1 + // moves + dp[i] = 1 + i - 1 + dp[i - 1] + if (dp[i] >= n) { + return i + } + } + return 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1886_determine_whether_matrix_can_be_obtained_by_rotation/readme.md b/src/main/kotlin/g1801_1900/s1886_determine_whether_matrix_can_be_obtained_by_rotation/readme.md new file mode 100644 index 00000000..c3ae44e8 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1886_determine_whether_matrix_can_be_obtained_by_rotation/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) + +## 1886\. Determine Whether Matrix Can Be Obtained By Rotation + +Easy + +Given two `n x n` binary matrices `mat` and `target`, return `true` _if it is possible to make_ `mat` _equal to_ `target` _by **rotating**_ `mat` _in **90-degree increments**, or_ `false` _otherwise._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/05/20/grid3.png) + +**Input:** mat = \[\[0,1],[1,0]], target = \[\[1,0],[0,1]] + +**Output:** true + +**Explanation:** We can rotate mat 90 degrees clockwise to make mat equal target. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/05/20/grid4.png) + +**Input:** mat = \[\[0,1],[1,1]], target = \[\[1,0],[0,1]] + +**Output:** false + +**Explanation:** It is impossible to make mat equal to target by rotating mat. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/05/26/grid4.png) + +**Input:** mat = \[\[0,0,0],[0,1,0],[1,1,1]], target = \[\[1,1,1],[0,1,0],[0,0,0]] + +**Output:** true + +**Explanation:** We can rotate mat 90 degrees clockwise two times to make mat equal target. + +**Constraints:** + +* `n == mat.length == target.length` +* `n == mat[i].length == target[i].length` +* `1 <= n <= 10` +* `mat[i][j]` and `target[i][j]` are either `0` or `1`. + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun findRotation(mat: Array, target: Array?): Boolean { + for (i in 0..3) { + if (Arrays.deepEquals(mat, target)) { + return true + } + rotate(mat) + } + return false + } + + private fun rotate(mat: Array) { + // Reverse Rows + run { + var i = 0 + var j = mat.size - 1 + while (i < j) { + val tempRow = mat[i] + mat[i] = mat[j] + mat[j] = tempRow + i++ + j-- + } + } + // Transpose + for (i in mat.indices) { + for (j in i + 1 until mat.size) { + val temp = mat[i][j] + mat[i][j] = mat[j][i] + mat[j][i] = temp + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1887_reduction_operations_to_make_the_array_elements_equal/readme.md b/src/main/kotlin/g1801_1900/s1887_reduction_operations_to_make_the_array_elements_equal/readme.md new file mode 100644 index 00000000..9e7cdae4 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1887_reduction_operations_to_make_the_array_elements_equal/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) + +## 1887\. Reduction Operations to Make the Array Elements Equal + +Medium + +Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps: + +1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`. +2. Find the **next largest** value in `nums` **strictly smaller** than `largest`. Let its value be `nextLargest`. +3. Reduce `nums[i]` to `nextLargest`. + +Return _the number of operations to make all elements in_ `nums` _equal_. + +**Example 1:** + +**Input:** nums = [5,1,3] + +**Output:** 3 + +**Explanation:** It takes 3 operations to make all elements in nums equal: + +1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3]. + +2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3]. + +3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1]. + +**Example 2:** + +**Input:** nums = [1,1,1] + +**Output:** 0 + +**Explanation:** All elements in nums are already equal. + +**Example 3:** + +**Input:** nums = [1,1,2,2,3] + +**Output:** 4 + +**Explanation:** It takes 4 operations to make all elements in nums equal: + +1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2]. + +2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2]. + +3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2]. + +4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1]. + +**Constraints:** + +* 1 <= nums.length <= 5 * 104 +* 1 <= nums[i] <= 5 * 104 + +## Solution + +```kotlin +class Solution { + fun reductionOperations(nums: IntArray): Int { + val arr = IntArray(100001) + for (i in nums) { + arr[i]++ + } + var `val` = 0 + var curr = 0 + for (i in 100000 downTo 0) { + if (arr[i] != 0) { + `val` += curr + curr += arr[i] + } + } + return `val` + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1888_minimum_number_of_flips_to_make_the_binary_string_alternating/readme.md b/src/main/kotlin/g1801_1900/s1888_minimum_number_of_flips_to_make_the_binary_string_alternating/readme.md new file mode 100644 index 00000000..0643e2d5 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1888_minimum_number_of_flips_to_make_the_binary_string_alternating/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) + +## 1888\. Minimum Number of Flips to Make the Binary String Alternating + +Medium + +You are given a binary string `s`. You are allowed to perform two types of operations on the string in any sequence: + +* **Type-1: Remove** the character at the start of the string `s` and **append** it to the end of the string. +* **Type-2: Pick** any character in `s` and **flip** its value, i.e., if its value is `'0'` it becomes `'1'` and vice-versa. + +Return _the **minimum** number of **type-2** operations you need to perform_ _such that_ `s` _becomes **alternating**._ + +The string is called **alternating** if no two adjacent characters are equal. + +* For example, the strings `"010"` and `"1010"` are alternating, while the string `"0100"` is not. + +**Example 1:** + +**Input:** s = "111000" + +**Output:** 2 + +**Explanation:** Use the first operation two times to make s = "100011". + +Then, use the second operation on the third and sixth elements to make s = "101010". + +**Example 2:** + +**Input:** s = "010" + +**Output:** 0 + +**Explanation:** The string is already alternating. + +**Example 3:** + +**Input:** s = "1110" + +**Output:** 1 + +**Explanation:** Use the second operation on the second element to make s = "1010". + +**Constraints:** + +* 1 <= s.length <= 105 +* `s[i]` is either `'0'` or `'1'`. + +## Solution + +```kotlin +class Solution { + fun minFlips(s: String): Int { + val n = s.length + val localStr = s + s + val t = localStr.toCharArray() + val a = CharArray(n + n) + val b = CharArray(n + n) + for (i in 0 until n + n) { + if (i % 2 == 0) { + a[i] = '1' + b[i] = '0' + } else { + a[i] = '0' + b[i] = '1' + } + } + var f = 0 + var sec = 0 + var ans = Int.MAX_VALUE + for (i in 0 until n + n) { + if (a[i] != t[i]) { + f++ + } + if (b[i] != t[i]) { + sec++ + } + if (i >= n) { + if (a[i - n] != t[i - n]) { + f-- + } + if (b[i - n] != t[i - n]) { + sec-- + } + } + if (i >= n - 1) { + ans = Math.min(ans, Math.min(f, sec)) + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1889_minimum_space_wasted_from_packaging/readme.md b/src/main/kotlin/g1801_1900/s1889_minimum_space_wasted_from_packaging/readme.md new file mode 100644 index 00000000..204a7f21 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1889_minimum_space_wasted_from_packaging/readme.md @@ -0,0 +1,123 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1889\. Minimum Space Wasted From Packaging + +Hard + +You have `n` packages that you are trying to place in boxes, **one package in each box**. There are `m` suppliers that each produce boxes of **different sizes** (with infinite supply). A package can be placed in a box if the size of the package is **less than or equal to** the size of the box. + +The package sizes are given as an integer array `packages`, where `packages[i]` is the **size** of the ith package. The suppliers are given as a 2D integer array `boxes`, where `boxes[j]` is an array of **box sizes** that the jth supplier produces. + +You want to choose a **single supplier** and use boxes from them such that the **total wasted space** is **minimized**. For each package in a box, we define the space **wasted** to be `size of the box - size of the package`. The **total wasted space** is the sum of the space wasted in **all** the boxes. + +* For example, if you have to fit packages with sizes `[2,3,5]` and the supplier offers boxes of sizes `[4,8]`, you can fit the packages of size-`2` and size-`3` into two boxes of size-`4` and the package with size-`5` into a box of size-`8`. This would result in a waste of `(4-2) + (4-3) + (8-5) = 6`. + +Return _the **minimum total wasted space** by choosing the box supplier **optimally**, or_ `-1` _if it is **impossible** to fit all the packages inside boxes._ Since the answer may be **large**, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** packages = [2,3,5], boxes = \[\[4,8],[2,8]] + +**Output:** 6 + +**Explanation:** It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box. + +The total waste is (4-2) + (4-3) + (8-5) = 6. + +**Example 2:** + +**Input:** packages = [2,3,5], boxes = \[\[1,4],[2,3],[3,4]] + +**Output:** -1 + +**Explanation:** There is no box that the package of size 5 can fit in. + +**Example 3:** + +**Input:** packages = [3,5,8,10,11,12], boxes = \[\[12],[11,9],[10,5,14]] + +**Output:** 9 + +**Explanation:** It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes. + +The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9. + +**Constraints:** + +* `n == packages.length` +* `m == boxes.length` +* 1 <= n <= 105 +* 1 <= m <= 105 +* 1 <= packages[i] <= 105 +* 1 <= boxes[j].length <= 105 +* 1 <= boxes[j][k] <= 105 +* sum(boxes[j].length) <= 105 +* The elements in `boxes[j]` are **distinct**. + +## Solution + +```kotlin +class Solution { + fun minWastedSpace(packages: IntArray, boxes: Array): Int { + val numPackages = packages.size + packages.sort() + val preSum = LongArray(numPackages) + preSum[0] = packages[0].toLong() + for (i in 1 until packages.size) { + preSum[i] = packages[i] + preSum[i - 1] + } + var ans = Long.MAX_VALUE + for (box in boxes) { + box.sort() + // Box of required size not present + if (packages[numPackages - 1] > box[box.size - 1]) { + continue + } + // Find the total space wasted + var totalWastedSpace: Long = 0 + var prev = -1 + for (j in box) { + if (prev == packages.size - 1) { + break + } + if (j < packages[0] || j < packages[prev + 1]) { + continue + } + // Find up to which package the current box can fit + val upper = findUpperBound(packages, j) + if (upper == -1) { + continue + } + // The current box will be able to handle the packages from + // prev + 1 to the upper index + val totalSpace = (upper.toLong() - prev.toLong()) * j + val packageSum = preSum[upper] - if (prev >= 0) preSum[prev] else 0 + val spaceWastedCurr = totalSpace - packageSum + totalWastedSpace += spaceWastedCurr + prev = upper + } + ans = Math.min(ans, totalWastedSpace) + } + return if (ans == Long.MAX_VALUE) -1 else (ans % MOD).toInt() + } + + private fun findUpperBound(packages: IntArray, key: Int): Int { + var l = 0 + var h = packages.size + while (l < h) { + val m = l + (h - l) / 2 + if (packages[m] <= key) { + l = m + 1 + } else { + h = m + } + } + return h - 1 + } + + companion object { + private const val MOD = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1890_the_latest_login_in_2020/readme.md b/src/main/kotlin/g1801_1900/s1890_the_latest_login_in_2020/readme.md new file mode 100644 index 00000000..0afba81a --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1890_the_latest_login_in_2020/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1890\. The Latest Login in 2020 + +Easy + +SQL Schema + +Table: `Logins` + + +----------------+----------+ + | Column Name | Type | + +----------------+----------+ + | user_id | int | + | time_stamp | datetime | + +----------------+----------+ + (user_id, time_stamp) is the primary key for this table. + Each row contains information about the login time for the user with ID user_id. + +Write an SQL query to report the **latest** login for all users in the year `2020`. Do **not** include the users who did not login in `2020`. + +Return the result table **in any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Logins table: + +---------+---------------------+ + | user_id | time_stamp | + +---------+---------------------+ + | 6 | 2020-06-30 15:06:07 | + | 6 | 2021-04-21 14:06:06 | + | 6 | 2019-03-07 00:18:15 | + | 8 | 2020-02-01 05:10:53 | + | 8 | 2020-12-30 00:46:50 | + | 2 | 2020-01-16 02:49:50 | + | 2 | 2019-08-25 07:59:08 | + | 14 | 2019-07-14 09:00:00 | + | 14 | 2021-01-06 11:59:59 | + +---------+---------------------+ + +**Output:** + + +---------+---------------------+ + | user_id | last_stamp | + +---------+---------------------+ + | 6 | 2020-06-30 15:06:07 | + | 8 | 2020-12-30 00:46:50 | + | 2 | 2020-01-16 02:49:50 | + +---------+---------------------+ + +**Explanation:** + +User 6 logged into their account 3 times but only once in 2020, so we include this login in the result table. + +User 8 logged into their account 2 times in 2020, once in February and once in December. We include only the latest one (December) in the result table. + +User 2 logged into their account 2 times but only once in 2020, so we include this login in the result table. + +User 14 did not login in 2020, so we do not include them in the result table. + +## Solution + +```sql +# Write your MySQL query statement below +SELECT user_id, MAX(time_stamp) AS last_stamp +FROM Logins +WHERE YEAR(time_stamp) = '2020' +GROUP BY 1; +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1893_check_if_all_the_integers_in_a_range_are_covered/readme.md b/src/main/kotlin/g1801_1900/s1893_check_if_all_the_integers_in_a_range_are_covered/readme.md new file mode 100644 index 00000000..2dc51cf6 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1893_check_if_all_the_integers_in_a_range_are_covered/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) + +## 1893\. Check if All the Integers in a Range Are Covered + +Easy + +You are given a 2D integer array `ranges` and two integers `left` and `right`. Each ranges[i] = [starti, endi] represents an **inclusive** interval between starti and endi. + +Return `true` _if each integer in the inclusive range_ `[left, right]` _is covered by **at least one** interval in_ `ranges`. Return `false` _otherwise_. + +An integer `x` is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi. + +**Example 1:** + +**Input:** ranges = \[\[1,2],[3,4],[5,6]], left = 2, right = 5 + +**Output:** true + +**Explanation:** Every integer between 2 and 5 is covered: + +- 2 is covered by the first range. + +- 3 and 4 are covered by the second range. + +- 5 is covered by the third range. + +**Example 2:** + +**Input:** ranges = \[\[1,10],[10,20]], left = 21, right = 21 + +**Output:** false + +**Explanation:** 21 is not covered by any range. + +**Constraints:** + +* `1 <= ranges.length <= 50` +* 1 <= starti <= endi <= 50 +* `1 <= left <= right <= 50` + +## Solution + +```kotlin +class Solution { + fun isCovered(ranges: Array, left: Int, right: Int): Boolean { + val temp = IntArray(52) + for (range in ranges) { + val start = range[0] + val end = range[ranges[0].size - 1] + temp[start] += 1 + temp[end + 1] += -1 + } + for (i in 1 until temp.size) { + temp[i] += temp[i - 1] + } + for (i in left..right) { + if (temp[i] == 0) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1894_find_the_student_that_will_replace_the_chalk/readme.md b/src/main/kotlin/g1801_1900/s1894_find_the_student_that_will_replace_the_chalk/readme.md new file mode 100644 index 00000000..84eddb66 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1894_find_the_student_that_will_replace_the_chalk/readme.md @@ -0,0 +1,95 @@ +[![](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) + +## 1894\. Find the Student that Will Replace the Chalk + +Medium + +There are `n` students in a class numbered from `0` to `n - 1`. The teacher will give each student a problem starting with the student number `0`, then the student number `1`, and so on until the teacher reaches the student number `n - 1`. After that, the teacher will restart the process, starting with the student number `0` again. + +You are given a **0-indexed** integer array `chalk` and an integer `k`. There are initially `k` pieces of chalk. When the student number `i` is given a problem to solve, they will use `chalk[i]` pieces of chalk to solve that problem. However, if the current number of chalk pieces is **strictly less** than `chalk[i]`, then the student number `i` will be asked to **replace** the chalk. + +Return _the **index** of the student that will **replace** the chalk_. + +**Example 1:** + +**Input:** chalk = [5,1,5], k = 22 + +**Output:** 0 + +**Explanation:** The students go in turns as follows: + +- Student number 0 uses 5 chalk, so k = 17. + +- Student number 1 uses 1 chalk, so k = 16. + +- Student number 2 uses 5 chalk, so k = 11. + +- Student number 0 uses 5 chalk, so k = 6. + +- Student number 1 uses 1 chalk, so k = 5. + +- Student number 2 uses 5 chalk, so k = 0. + +Student number 0 does not have enough chalk, so they will have to replace it. + +**Example 2:** + +**Input:** chalk = [3,4,1,2], k = 25 + +**Output:** 1 + +**Explanation:** The students go in turns as follows: + +- Student number 0 uses 3 chalk so k = 22. + +- Student number 1 uses 4 chalk so k = 18. + +- Student number 2 uses 1 chalk so k = 17. + +- Student number 3 uses 2 chalk so k = 15. + +- Student number 0 uses 3 chalk so k = 12. + +- Student number 1 uses 4 chalk so k = 8. + +- Student number 2 uses 1 chalk so k = 7. + +- Student number 3 uses 2 chalk so k = 5. + +- Student number 0 uses 3 chalk so k = 2. + +Student number 1 does not have enough chalk, so they will have to replace it. + +**Constraints:** + +* `chalk.length == n` +* 1 <= n <= 105 +* 1 <= chalk[i] <= 105 +* 1 <= k <= 109 + +## Solution + +```kotlin +class Solution { + fun chalkReplacer(chalk: IntArray, k: Int): Int { + val localSum = sum(chalk) + var currentIndex = 0 + if (localSum != 0L) { + var localK = (k % localSum).toInt() + while (chalk[currentIndex] <= localK) { + localK -= chalk[currentIndex++] + } + } + return currentIndex + } + + private fun sum(chalk: IntArray): Long { + var sum: Long = 0 + for (i in chalk) { + sum += i.toLong() + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1895_largest_magic_square/readme.md b/src/main/kotlin/g1801_1900/s1895_largest_magic_square/readme.md new file mode 100644 index 00000000..108e0543 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1895_largest_magic_square/readme.md @@ -0,0 +1,102 @@ +[![](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) + +## 1895\. Largest Magic Square + +Medium + +A `k x k` **magic square** is a `k x k` grid filled with integers such that every row sum, every column sum, and both diagonal sums are **all equal**. The integers in the magic square **do not have to be distinct**. Every `1 x 1` grid is trivially a **magic square**. + +Given an `m x n` integer `grid`, return _the **size** (i.e., the side length_ `k`_) of the **largest magic square** that can be found within this grid_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/05/29/magicsquare-grid.jpg) + +**Input:** grid = \[\[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]] + +**Output:** 3 + +**Explanation:** The largest magic square has a size of 3. + +Every row sum, column sum, and diagonal sum of this magic square is equal to 12. + +- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12 + +- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12 + +- Diagonal sums: 5+4+3 = 6+4+2 = 12 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/05/29/magicsquare2-grid.jpg) + +**Input:** grid = \[\[5,1,3,1],[9,3,3,1],[1,3,3,8]] + +**Output:** 2 + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `1 <= m, n <= 50` +* 1 <= grid[i][j] <= 106 + +## Solution + +```kotlin +class Solution { + fun largestMagicSquare(grid: Array): Int { + val m = grid.size + val n = grid[0].size + val rows = Array(m) { IntArray(n + 1) } + val cols = Array(m + 1) { IntArray(n) } + for (i in 0 until m) { + for (j in 0 until n) { + // cumulative sum for each row + rows[i][j + 1] = rows[i][j] + grid[i][j] + // cumulative sum for each column + cols[i + 1][j] = cols[i][j] + grid[i][j] + } + } + // start with the biggest side possible + for (side in Math.min(m, n) downTo 2) { + // check every square + for (i in 0..m - side) { + for (j in 0..n - side) { + // checks if a square with top left [i, j] and side length is magic + if (magic(grid, rows, cols, i, j, side)) { + return side + } + } + } + } + return 1 + } + + private fun magic( + grid: Array, + rows: Array, + cols: Array, + r: Int, + c: Int, + side: Int + ): Boolean { + val sum = rows[r][c + side] - rows[r][c] + var d1 = 0 + var d2 = 0 + for (k in 0 until side) { + d1 += grid[r + k][c + k] + d2 += grid[r + side - 1 - k][c + k] + // check each row and column + if (rows[r + k][c + side] - rows[r + k][c] != sum || + cols[r + side][c + k] - cols[r][c + k] != sum + ) { + return false + } + } + // checks both diagonals + return d1 == sum && d2 == sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1896_minimum_cost_to_change_the_final_value_of_expression/readme.md b/src/main/kotlin/g1801_1900/s1896_minimum_cost_to_change_the_final_value_of_expression/readme.md new file mode 100644 index 00000000..85eae75b --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1896_minimum_cost_to_change_the_final_value_of_expression/readme.md @@ -0,0 +1,141 @@ +[![](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) + +## 1896\. Minimum Cost to Change the Final Value of Expression + +Hard + +You are given a **valid** boolean expression as a string `expression` consisting of the characters `'1'`,`'0'`,`'&'` (bitwise **AND** operator),`'|'` (bitwise **OR** operator),`'('`, and `')'`. + +* For example, `"()1|1"` and `"(1)&()"` are **not valid** while `"1"`, `"(((1))|(0))"`, and `"1|(0&(1))"` are **valid** expressions. + +Return _the **minimum cost** to change the final value of the expression_. + +* For example, if `expression = "1|1|(0&0)&1"`, its **value** is `1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1`. We want to apply operations so that the **new** expression evaluates to `0`. + +The **cost** of changing the final value of an expression is the **number of operations** performed on the expression. The types of **operations** are described as follows: + +* Turn a `'1'` into a `'0'`. +* Turn a `'0'` into a `'1'`. +* Turn a `'&'` into a `'|'`. +* Turn a `'|'` into a `'&'`. + +**Note:** `'&'` does **not** take precedence over `'|'` in the **order of calculation**. Evaluate parentheses **first**, then in **left-to-right** order. + +**Example 1:** + +**Input:** expression = "1&(0\|1)" + +**Output:** 1 + +**Explanation:** We can turn "1&(0\|1)" into "1&(0&1)" by changing the '\|' to a '&' using 1 operation. + +The new expression evaluates to 0. + +**Example 2:** + +**Input:** expression = "(0&0)&(0&0&0)" + +**Output:** 3 + +**Explanation:** We can turn "(0&0)&(0&0&0)" into "(0\|1)\|(0&0&0)" using 3 operations. + +The new expression evaluates to 1. + +**Example 3:** + +**Input:** expression = "(0\|(1\|0&1))" + +**Output:** 1 + +**Explanation:** We can turn "(0\|(1\|0&1))" into "(0\|(0\|0&1))" using 1 operation. + +The new expression evaluates to 0. + +**Constraints:** + +* 1 <= expression.length <= 105 +* `expression` only contains `'1'`,`'0'`,`'&'`,`'|'`,`'('`, and `')'` +* All parentheses are properly matched. +* There will be no empty parentheses (i.e: `"()"` is not a substring of `expression`). + +## Solution + +```kotlin +class Solution { + private class Result(var `val`: Int, var minFlips: Int) + + private var cur = 0 + + fun minOperationsToFlip(expression: String): Int { + cur = 0 + return term(expression).minFlips + } + + private fun term(s: String): Result { + var res = factor(s) + while (cur < s.length && (s[cur] == '|' || s[cur] == '&')) { + val c = s[cur] + cur++ + res = if (c == '|') { + or(res, factor(s)) + } else { + and(res, factor(s)) + } + } + return res + } + + private fun factor(s: String): Result { + if (s[cur] == '(') { + cur++ + val res = term(s) + cur++ + return res + } + return number(s) + } + + private fun number(s: String): Result { + return if (s[cur] == '1') { + cur++ + Result(1, 1) + } else { + cur++ + Result(0, 1) + } + } + + private fun or(res1: Result, res2: Result): Result { + return if (res1.`val` + res2.`val` == 0) { + Result( + 0, + Math.min(res1.minFlips, res2.minFlips) + ) + } else if (res1.`val` + res2.`val` == 2) { + Result( + 1, + 1 + Math.min(res1.minFlips, res2.minFlips) + ) + } else { + Result(1, 1) + } + } + + private fun and(res1: Result, res2: Result): Result { + return if (res1.`val` + res2.`val` == 0) { + Result( + 0, + 1 + Math.min(res1.minFlips, res2.minFlips) + ) + } else if (res1.`val` + res2.`val` == 2) { + Result( + 1, + Math.min(res1.minFlips, res2.minFlips) + ) + } else { + Result(0, 1) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1897_redistribute_characters_to_make_all_strings_equal/readme.md b/src/main/kotlin/g1801_1900/s1897_redistribute_characters_to_make_all_strings_equal/readme.md new file mode 100644 index 00000000..9df11905 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1897_redistribute_characters_to_make_all_strings_equal/readme.md @@ -0,0 +1,57 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1897\. Redistribute Characters to Make All Strings Equal + +Easy + +You are given an array of strings `words` (**0-indexed**). + +In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`. + +Return `true` _if you can make **every** string in_ `words` _**equal** using **any** number of operations_, _and_ `false` _otherwise_. + +**Example 1:** + +**Input:** words = ["abc","aabc","bc"] + +**Output:** true + +**Explanation:** Move the first 'a' in `words[1] to the front of words[2], to make` `words[1]` = "abc" and words[2] = "abc". + +All the strings are now equal to "abc", so return `true`. + +**Example 2:** + +**Input:** words = ["ab","a"] + +**Output:** false + +**Explanation:** It is impossible to make all the strings equal using the operation. + +**Constraints:** + +* `1 <= words.length <= 100` +* `1 <= words[i].length <= 100` +* `words[i]` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun makeEqual(words: Array): Boolean { + val charFreq = IntArray(26) + for (word in words) { + for (chIndex in 0 until word.length) { + charFreq[word[chIndex].code - 'a'.code]++ + } + } + for (freq in charFreq) { + if (freq % words.size != 0) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1898_maximum_number_of_removable_characters/readme.md b/src/main/kotlin/g1801_1900/s1898_maximum_number_of_removable_characters/readme.md new file mode 100644 index 00000000..e1baa025 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1898_maximum_number_of_removable_characters/readme.md @@ -0,0 +1,102 @@ +[![](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) + +## 1898\. Maximum Number of Removable Characters + +Medium + +You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). + +You want to choose an integer `k` (`0 <= k <= removable.length`) such that, after removing `k` characters from `s` using the **first** `k` indices in `removable`, `p` is still a **subsequence** of `s`. More formally, you will mark the character at `s[removable[i]]` for each `0 <= i < k`, then remove all marked characters and check if `p` is still a subsequence. + +Return _the **maximum**_ `k` _you can choose such that_ `p` _is still a **subsequence** of_ `s` _after the removals_. + +A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. + +**Example 1:** + +**Input:** s = "abcacb", p = "ab", removable = [3,1,0] + +**Output:** 2 + +**Explanation:** After removing the characters at indices 3 and 1, "a**b**c**a**cb" becomes "accb". + +"ab" is a subsequence of "**a**cc**b**". + +If we remove the characters at indices 3, 1, and 0, "**ab**c**a**cb" becomes "ccb", and "ab" is no longer a subsequence. + +Hence, the maximum k is 2. + +**Example 2:** + +**Input:** s = "abcbddddd", p = "abcd", removable = [3,2,1,4,5,6] + +**Output:** 1 + +**Explanation:** After removing the character at index 3, "abc**b**ddddd" becomes "abcddddd". + +"abcd" is a subsequence of "**abcd**dddd". + +**Example 3:** + +**Input:** s = "abcab", p = "abc", removable = [0,1,2,3,4] + +**Output:** 0 + +**Explanation:** If you remove the first index in the array removable, "abc" is no longer a subsequence. + +**Constraints:** + +* 1 <= p.length <= s.length <= 105 +* `0 <= removable.length < s.length` +* `0 <= removable[i] < s.length` +* `p` is a **subsequence** of `s`. +* `s` and `p` both consist of lowercase English letters. +* The elements in `removable` are **distinct**. + +## Solution + +```kotlin +class Solution { + fun maximumRemovals(s: String, p: String, removable: IntArray): Int { + if (s.isEmpty()) { + return 0 + } + // binary search for the k which need to be removed + val convertedS = s.toCharArray() + var left = 0 + var right = removable.size - 1 + while (left <= right) { + val middle = (left + right) / 2 + // remove letters from 0 to mid by changing it into some other non letters + for (i in 0..middle) { + convertedS[removable[i]] = '?' + } + // if it is still subsequence change left boundary + // else replace all removed ones and change right boundary + if (isSubsequence(convertedS, p)) { + left = middle + 1 + } else { + for (i in 0..middle) { + convertedS[removable[i]] = s[removable[i]] + } + right = middle - 1 + } + } + return left + } + + // simple check for subsequence + private fun isSubsequence(convertedS: CharArray, p: String): Boolean { + var p1 = 0 + var p2 = 0 + while (p1 < convertedS.size && p2 < p.length) { + if (convertedS[p1] != '?' && convertedS[p1] == p[p2]) { + p2 += 1 + } + p1 += 1 + } + return p2 == p.length + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1899_merge_triplets_to_form_target_triplet/readme.md b/src/main/kotlin/g1801_1900/s1899_merge_triplets_to_form_target_triplet/readme.md new file mode 100644 index 00000000..41d34815 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1899_merge_triplets_to_form_target_triplet/readme.md @@ -0,0 +1,82 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1899\. Merge Triplets to Form Target Triplet + +Medium + +A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where triplets[i] = [ai, bi, ci] describes the ith **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain. + +To obtain `target`, you may apply the following operation on `triplets` **any number** of times (possibly **zero**): + +* Choose two indices (**0-indexed**) `i` and `j` (`i != j`) and **update** `triplets[j]` to become [max(ai, aj), max(bi, bj), max(ci, cj)]. + * For example, if `triplets[i] = [2, 5, 3]` and `triplets[j] = [1, 7, 5]`, `triplets[j]` will be updated to `[max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5]`. + +Return `true` _if it is possible to obtain the_ `target` _**triplet**_ `[x, y, z]` _as an **element** of_ `triplets`_, or_ `false` _otherwise_. + +**Example 1:** + +**Input:** triplets = \[\[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5] + +**Output:** true + +**Explanation:** Perform the following operations: + +- Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = \[\[2,5,3],[1,8,4],[2,7,5]] + +The target triplet [2,7,5] is now an element of triplets. + +**Example 2:** + +**Input:** triplets = \[\[3,4,5],[4,5,6]], target = [3,2,5] + +**Output:** false + +**Explanation:** It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets. + +**Example 3:** + +**Input:** triplets = \[\[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5] + +**Output:** true + +**Explanation:** Perform the following operations: + +- Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = \[\[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. + +- Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = \[\[2,5,3],[2,3,4],[2,5,5],[5,5,5]]. + +The target triplet [5,5,5] is now an element of triplets. + +**Constraints:** + +* 1 <= triplets.length <= 105 +* `triplets[i].length == target.length == 3` +* 1 <= ai, bi, ci, x, y, z <= 1000 + +## Solution + +```kotlin +class Solution { + fun mergeTriplets(triplets: Array, target: IntArray): Boolean { + var one = false + var two = false + var three = false + for (triplet in triplets) { + if (!one && triplet[0] == target[0] && triplet[1] <= target[1] && triplet[2] <= target[2]) { + one = true + } + if (!two && triplet[0] <= target[0] && triplet[1] == target[1] && triplet[2] <= target[2]) { + two = true + } + if (!three && triplet[0] <= target[0] && triplet[1] <= target[1] && triplet[2] == target[2]) { + three = true + } + if (one && two && three) { + return true + } + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1801_1900/s1900_the_earliest_and_latest_rounds_where_players_compete/readme.md b/src/main/kotlin/g1801_1900/s1900_the_earliest_and_latest_rounds_where_players_compete/readme.md new file mode 100644 index 00000000..8af61626 --- /dev/null +++ b/src/main/kotlin/g1801_1900/s1900_the_earliest_and_latest_rounds_where_players_compete/readme.md @@ -0,0 +1,131 @@ +[![](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) + +## 1900\. The Earliest and Latest Rounds Where Players Compete + +Hard + +There is a tournament where `n` players are participating. The players are standing in a single row and are numbered from `1` to `n` based on their **initial** standing position (player `1` is the first player in the row, player `2` is the second player in the row, etc.). + +The tournament consists of multiple rounds (starting from round number `1`). In each round, the ith player from the front of the row competes against the ith player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round. + +* For example, if the row consists of players `1, 2, 4, 6, 7` + * Player `1` competes against player `7`. + * Player `2` competes against player `6`. + * Player `4` automatically advances to the next round. + +After each round is over, the winners are lined back up in the row based on the **original ordering** assigned to them initially (ascending order). + +The players numbered `firstPlayer` and `secondPlayer` are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may **choose** the outcome of this round. + +Given the integers `n`, `firstPlayer`, and `secondPlayer`, return _an integer array containing two values, the **earliest** possible round number and the **latest** possible round number in which these two players will compete against each other, respectively_. + +**Example 1:** + +**Input:** n = 11, firstPlayer = 2, secondPlayer = 4 + +**Output:** [3,4] + +**Explanation:** + +One possible scenario which leads to the earliest round number: + +First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 + +Second round: 2, 3, 4, 5, 6, 11 + +Third round: 2, 3, 4 + +One possible scenario which leads to the latest round number: + +First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 + +Second round: 1, 2, 3, 4, 5, 6 + +Third round: 1, 2, 4 + +Fourth round: 2, 4 + +**Example 2:** + +**Input:** n = 5, firstPlayer = 1, secondPlayer = 5 + +**Output:** [1,1] + +**Explanation:** The players numbered 1 and 5 compete in the first round. + +There is no way to make them compete in any other round. + +**Constraints:** + +* `2 <= n <= 28` +* `1 <= firstPlayer < secondPlayer <= n` + +## Solution + +```kotlin +class Solution { + fun earliestAndLatest(n: Int, firstPlayer: Int, secondPlayer: Int): IntArray { + var p1 = Math.min(firstPlayer, secondPlayer) + var p2 = Math.max(firstPlayer, secondPlayer) + if (p1 + p2 == n + 1) { + // p1 and p2 compete in the first round + return intArrayOf(1, 1) + } + if (n == 3 || n == 4) { + // p1 and p2 must compete in the second round (only two rounds). + return intArrayOf(2, 2) + } + // Flip to make p1 be more closer to left than p2 to right end for convenience + if (p1 - 1 > n - p2) { + val t = n + 1 - p1 + p1 = n + 1 - p2 + p2 = t + } + val m = (n + 1) / 2 + var min = n + var max = 1 + if (p2 * 2 <= n + 1) { + // p2 is in first half (n odd or even) or exact middle (n odd) + // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 + // . . * . . * . . . . . . . . + // ^ ^ + // p1 p2 + // Group A are players in front of p1 + // Group B are players between p1 and p2 + val a = p1 - 1 + val b = p2 - p1 - 1 + // i represents number of front players in A wins + // j represents number of front players in B wins + for (i in 0..a) { + for (j in 0..b) { + val ret = earliestAndLatest(m, i + 1, i + j + 2) + min = Math.min(min, 1 + ret[0]) + max = Math.max(max, 1 + ret[1]) + } + } + } else { + // p2 is in the later half (and has >= p1 distance to the end) + // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 + // . . * . . . . . . * . . . . + // ^ ^ + // p1 p4 p2 p3 + // ^--------------^ + // ^--------------------------^ + val p4 = n + 1 - p2 + val a = p1 - 1 + val b = p4 - p1 - 1 + // Group C are players between p4 and p2, (c+1)/2 will advance to next round. + val c = p2 - p4 - 1 + for (i in 0..a) { + for (j in 0..b) { + val ret = earliestAndLatest(m, i + 1, i + j + 1 + (c + 1) / 2 + 1) + min = Math.min(min, 1 + ret[0]) + max = Math.max(max, 1 + ret[1]) + } + } + } + return intArrayOf(min, max) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1901_find_a_peak_element_ii/readme.md b/src/main/kotlin/g1901_2000/s1901_find_a_peak_element_ii/readme.md new file mode 100644 index 00000000..e6dcae32 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1901_find_a_peak_element_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) + +## 1901\. Find a Peak Element II + +Medium + +A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom. + +Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`. + +You may assume that the entire matrix is surrounded by an **outer perimeter** with the value `-1` in each cell. + +You must write an algorithm that runs in `O(m log(n))` or `O(n log(m))` time. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/06/08/1.png) + +**Input:** mat = \[\[1,4],[3,2]] + +**Output:** [0,1] + +**Explanation:** Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers. + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2021/06/07/3.png)** + +**Input:** mat = \[\[10,20,15],[21,30,14],[7,16,32]] + +**Output:** [1,1] + +**Explanation:** Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers. + +**Constraints:** + +* `m == mat.length` +* `n == mat[i].length` +* `1 <= m, n <= 500` +* 1 <= mat[i][j] <= 105 +* No two adjacent cells are equal. + +## Solution + +```kotlin +class Solution { + fun findPeakGrid(mat: Array): IntArray { + val n = mat.size + val m = mat[0].size + var l = 0 + var r = m - 1 + var mid: Int + while (l <= r) { + mid = (l + r) / 2 + var mx = mat[0][mid] + var mxi = 0 + for (i in 1 until n) { + if (mx < mat[i][mid]) { + mx = mat[i][mid] + mxi = i + } + } + val lv = if (mid > l) mat[mxi][mid - 1] else -1 + val rv = if (mid < r) mat[mxi][mid + 1] else -1 + if (mx > lv && mx > rv) { + return intArrayOf(mxi, mid) + } else if (mx > lv) { + l = mid + 1 + } else { + r = mid - 1 + } + } + return intArrayOf(-1, -1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1903_largest_odd_number_in_string/readme.md b/src/main/kotlin/g1901_2000/s1903_largest_odd_number_in_string/readme.md new file mode 100644 index 00000000..00faadfe --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1903_largest_odd_number_in_string/readme.md @@ -0,0 +1,54 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1903\. Largest Odd Number in String + +Easy + +You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `""` _if no odd integer exists_. + +A **substring** is a contiguous sequence of characters within a string. + +**Example 1:** + +**Input:** num = "52" + +**Output:** "5" + +**Explanation:** The only non-empty substrings are "5", "2", and "52". "5" is the only odd number. + +**Example 2:** + +**Input:** num = "4206" + +**Output:** "" + +**Explanation:** There are no odd numbers in "4206". + +**Example 3:** + +**Input:** num = "35427" + +**Output:** "35427" + +**Explanation:** "35427" is already an odd number. + +**Constraints:** + +* 1 <= num.length <= 105 +* `num` only consists of digits and does not contain any leading zeros. + +## Solution + +```kotlin +class Solution { + fun largestOddNumber(num: String): String { + for (i in num.length - 1 downTo 0) { + if (("" + num[i]).toInt() % 2 == 1) { + return num.substring(0, i + 1) + } + } + return "" + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1904_the_number_of_full_rounds_you_have_played/readme.md b/src/main/kotlin/g1901_2000/s1904_the_number_of_full_rounds_you_have_played/readme.md new file mode 100644 index 00000000..fac91576 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1904_the_number_of_full_rounds_you_have_played/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) + +## 1904\. The Number of Full Rounds You Have Played + +Medium + +You are participating in an online chess tournament. There is a chess round that starts every `15` minutes. The first round of the day starts at `00:00`, and after every `15` minutes, a new round starts. + +* For example, the second round starts at `00:15`, the fourth round starts at `00:45`, and the seventh round starts at `01:30`. + +You are given two strings `loginTime` and `logoutTime` where: + +* `loginTime` is the time you will login to the game, and +* `logoutTime` is the time you will logout from the game. + +If `logoutTime` is **earlier** than `loginTime`, this means you have played from `loginTime` to midnight and from midnight to `logoutTime`. + +Return _the number of full chess rounds you have played in the tournament_. + +**Note:** All the given times follow the 24-hour clock. That means the first round of the day starts at `00:00` and the last round of the day starts at `23:45`. + +**Example 1:** + +**Input:** loginTime = "09:31", logoutTime = "10:14" + +**Output:** 1 + +**Explanation:** + +You played one full round from 09:45 to 10:00. You did not play the full round from 09:30 to 09:45 because you logged in at 09:31 after it began. + +You did not play the full round from 10:00 to 10:15 because you logged out at 10:14 before it ended. + +**Example 2:** + +**Input:** loginTime = "21:30", logoutTime = "03:00" + +**Output:** 22 + +**Explanation:** You played 10 full rounds from 21:30 to 00:00 and 12 full rounds from 00:00 to 03:00. 10 + 12 = 22. + +**Constraints:** + +* `loginTime` and `logoutTime` are in the format `hh:mm`. +* `00 <= hh <= 23` +* `00 <= mm <= 59` +* `loginTime` and `logoutTime` are not equal. + +## Solution + +```kotlin +class Solution { + fun numberOfRounds(loginTime: String, logoutTime: String): Int { + var loginSerializeTime = serializeTime(loginTime) + var logoutSerializeTime = serializeTime(logoutTime) + if (logoutSerializeTime - 14 < loginSerializeTime && + logoutSerializeTime > loginSerializeTime + ) { + return 0 + } + loginSerializeTime = maskSerializeTime(loginSerializeTime, 14) + logoutSerializeTime = maskSerializeTime(logoutSerializeTime, 0) + if (loginSerializeTime == logoutSerializeTime) { + return 0 + } + return if (loginSerializeTime > logoutSerializeTime + 14) { + ( + calculateFullRounds(loginSerializeTime, MID_NIGHT_END) + + calculateFullRounds(MID_NIGHT_START, logoutSerializeTime) + ) + } else calculateFullRounds(loginSerializeTime, logoutSerializeTime) + } + + private fun maskSerializeTime(serializeTime: Int, mask: Int): Int { + return (serializeTime + mask) / ROUND_INTERVAL * ROUND_INTERVAL + } + + private fun serializeTime(time: String): Int { + return time.substring(0, 2).toInt() * 60 + time.substring(3, 5).toInt() + } + + private fun calculateFullRounds(login: Int, logout: Int): Int { + return (logout - login) / ROUND_INTERVAL + } + + companion object { + private const val MID_NIGHT_END = 1440 + private const val MID_NIGHT_START = 0 + private const val ROUND_INTERVAL = 15 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1905_count_sub_islands/readme.md b/src/main/kotlin/g1901_2000/s1905_count_sub_islands/readme.md new file mode 100644 index 00000000..e52e4cce --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1905_count_sub_islands/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1905\. Count Sub Islands + +Medium + +You are given two `m x n` binary matrices `grid1` and `grid2` containing only `0`'s (representing water) and `1`'s (representing land). An **island** is a group of `1`'s connected **4-directionally** (horizontal or vertical). Any cells outside of the grid are considered water cells. + +An island in `grid2` is considered a **sub-island** if there is an island in `grid1` that contains **all** the cells that make up **this** island in `grid2`. + +Return the _**number** of islands in_ `grid2` _that are considered **sub-islands**_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/06/10/test1.png) + +**Input:** grid1 = \[\[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = \[\[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]] + +**Output:** 3 + +**Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/06/03/testcasex2.png) + +**Input:** grid1 = \[\[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = \[\[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]] + +**Output:** 2 + +**Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands. + +**Constraints:** + +* `m == grid1.length == grid2.length` +* `n == grid1[i].length == grid2[i].length` +* `1 <= m, n <= 500` +* `grid1[i][j]` and `grid2[i][j]` are either `0` or `1`. + +## Solution + +```kotlin +class Solution { + private var ans = 0 + fun countSubIslands(grid1: Array, grid2: Array): Int { + var count = 0 + for (i in grid2.indices) { + for (j in grid2[0].indices) { + if (grid2[i][j] == 1) { + ans = 1 + dfs(grid1, grid2, i, j) + count += ans + } + } + } + return count + } + + private fun dfs(grid1: Array, grid2: Array, i: Int, j: Int) { + if (i < 0 || j < 0 || i >= grid1.size || j >= grid1[0].size || grid2[i][j] == 0) { + return + } + if (grid1[i][j] == 0) { + ans = 0 + } + grid2[i][j] = 0 + dfs(grid1, grid2, i - 1, j) + dfs(grid1, grid2, i + 1, j) + dfs(grid1, grid2, i, j + 1) + dfs(grid1, grid2, i, j - 1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1906_minimum_absolute_difference_queries/readme.md b/src/main/kotlin/g1901_2000/s1906_minimum_absolute_difference_queries/readme.md new file mode 100644 index 00000000..aa5e9608 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1906_minimum_absolute_difference_queries/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) + +## 1906\. Minimum Absolute Difference Queries + +Medium + +The **minimum absolute difference** of an array `a` is defined as the **minimum value** of `|a[i] - a[j]|`, where `0 <= i < j < a.length` and `a[i] != a[j]`. If all elements of `a` are the **same**, the minimum absolute difference is `-1`. + +* For example, the minimum absolute difference of the array `[5,2,3,7,2]` is `|2 - 3| = 1`. Note that it is not `0` because `a[i]` and `a[j]` must be different. + +You are given an integer array `nums` and the array `queries` where queries[i] = [li, ri]. For each query `i`, compute the **minimum absolute difference** of the **subarray** nums[li...ri] containing the elements of `nums` between the **0-based** indices li and ri (**inclusive**). + +Return _an **array**_ `ans` _where_ `ans[i]` _is the answer to the_ ith _query_. + +A **subarray** is a contiguous sequence of elements in an array. + +The value of `|x|` is defined as: + +* `x` if `x >= 0`. +* `-x` if `x < 0`. + +**Example 1:** + +**Input:** nums = [1,3,4,8], queries = \[\[0,1],[1,2],[2,3],[0,3]] + +**Output:** [2,1,4,1] + +**Explanation:** The queries are processed as follows: + +- queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is \|1-3\| = 2. + +- queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is \|3-4\| = 1. + +- queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is \|4-8\| = 4. + +- queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is \|3-4\| = 1. + +**Example 2:** + +**Input:** nums = [4,5,2,2,7,10], queries = \[\[2,3],[0,2],[0,5],[3,5]] + +**Output:** [-1,1,1,3] + +**Explanation:** The queries are processed as follows: + +- queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the elements are the same. + +- queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is \|4-5\| = 1. + +- queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is \|4-5\| = 1. + +- queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is \|7-10\| = 3. + +**Constraints:** + +* 2 <= nums.length <= 105 +* `1 <= nums[i] <= 100` +* 1 <= queries.length <= 2 * 104 +* 0 <= li < ri < nums.length + +## Solution + +```kotlin +import java.util.BitSet + +class Solution { + private class SegmentTree(nums: IntArray, len: Int) { + class Node { + var bits: BitSet? = null + var minDiff = 0 + } + + var nums: IntArray + var tree: Array + + init { + this.nums = nums.copyOf(len) + tree = arrayOfNulls(4 * len) + buildTree(0, len - 1, 0) + } + + private fun buildTree(i: Int, j: Int, ti: Int) { + if (i <= j) { + if (i == j) { + val node = Node() + node.bits = BitSet(101) + node.bits!!.set(nums[i]) + node.minDiff = INF + tree[ti] = node + } else { + val mid = i + (j - i) / 2 + buildTree(i, mid, 2 * ti + 1) + buildTree(mid + 1, j, 2 * ti + 2) + tree[ti] = combineNodes(tree[2 * ti + 1], tree[2 * ti + 2]) + } + } + } + + private fun combineNodes(n1: Node?, n2: Node?): Node { + val node = Node() + if (n1!!.minDiff == 1 || n2!!.minDiff == 1) { + node.minDiff = 1 + } else { + node.bits = BitSet(101) + node.bits!!.or(n1.bits) + node.bits!!.or(n2.bits) + node.minDiff = findMinDiff(node.bits) + } + return node + } + + private fun findMinDiff(bits: BitSet?): Int { + // minimum value of number is 1. + var first = bits!!.nextSetBit(1) + var minDiff = INF + while (first != -1) { + val next = bits.nextSetBit(first + 1) + if (next != -1) { + minDiff = Math.min(minDiff, next - first) + if (minDiff == 1) { + break + } + } + first = next + } + return minDiff + } + + fun findMinAbsDiff(start: Int, end: Int, i: Int, j: Int, ti: Int): Int { + val node = findMinAbsDiff2(start, end, i, j, ti) + return if (node!!.minDiff == INF) -1 else node.minDiff + } + + private fun findMinAbsDiff2(start: Int, end: Int, i: Int, j: Int, ti: Int): Node? { + if (i == start && j == end) { + return tree[ti] + } + val mid = i + (j - i) / 2 + return if (end <= mid) { + findMinAbsDiff2(start, end, i, mid, 2 * ti + 1) + } else if (start >= mid + 1) { + findMinAbsDiff2(start, end, mid + 1, j, 2 * ti + 2) + } else { + val left = findMinAbsDiff2(start, mid, i, mid, 2 * ti + 1) + val right = findMinAbsDiff2(mid + 1, end, mid + 1, j, 2 * ti + 2) + combineNodes(left, right) + } + } + + companion object { + const val INF = 200 + } + } + + fun minDifference(nums: IntArray, queries: Array): IntArray { + val len = nums.size + val qlen = queries.size + val st = SegmentTree(nums, len) + val answer = IntArray(qlen) + for (i in 0 until qlen) { + answer[i] = st.findMinAbsDiff(queries[i][0], queries[i][1], 0, len - 1, 0) + } + return answer + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1907_count_salary_categories/readme.md b/src/main/kotlin/g1901_2000/s1907_count_salary_categories/readme.md new file mode 100644 index 00000000..b78a05ae --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1907_count_salary_categories/readme.md @@ -0,0 +1,78 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1907\. Count Salary Categories + +Medium + +SQL Schema + +Table: `Accounts` + + +-------------+------+ + | Column Name | Type | + +-------------+------+ + | account_id | int | + | income | int | + +-------------+------+ + account_id is the primary key for this table. + Each row contains information about the monthly income for one bank account. + +Write an SQL query to report the number of bank accounts of each salary category. The salary categories are: + +* `"Low Salary"`: All the salaries **strictly less** than `$20000`. +* `"Average Salary"`: All the salaries in the **inclusive** range `[$20000, $50000]`. +* `"High Salary"`: All the salaries **strictly greater** than `$50000`. + +The result table **must** contain all three categories. If there are no accounts in a category, then report `0`. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Accounts table: + +------------+--------+ + | account_id | income | + +------------+--------+ + | 3 | 108939 | + | 2 | 12747 | + | 8 | 87709 | + | 6 | 91796 | + +------------+--------+ + +**Output:** + + +----------------+----------------+ + | category | accounts_count | + +----------------+----------------+ + | Low Salary | 1 | + | Average Salary | 0 | + | High Salary | 3 | + +----------------+----------------+ + +**Explanation:** + +Low Salary: Account 2. + +Average Salary: No accounts. + +High Salary: Accounts 3, 6, and 8. + +## Solution + +```sql +# Write your MySQL query statement below +with cte1 as (SELECT 'Low Salary' AS category,SUM(CASE WHEN INCOME<20000 THEN 1 ELSE 0 END ) AS accounts_count from Accounts), +cte2 as(SELECT 'Average Salary' AS category,SUM(CASE WHEN INCOME BETWEEN 20000 AND 50000 THEN 1 ELSE 0 END ) AS accounts_count from Accounts), +cte3 as (SELECT 'High Salary' AS category,SUM(CASE WHEN INCOME> 50000 THEN 1 ELSE 0 END) AS accounts_count +FROM Accounts) +SELECT * from cte3 +UNION ALL +SELECT * FROM cte1 +UNION ALL +SELECT * FROM cte2 +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1909_remove_one_element_to_make_the_array_strictly_increasing/readme.md b/src/main/kotlin/g1901_2000/s1909_remove_one_element_to_make_the_array_strictly_increasing/readme.md new file mode 100644 index 00000000..dd33bc69 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1909_remove_one_element_to_make_the_array_strictly_increasing/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) + +## 1909\. Remove One Element to Make the Array Strictly Increasing + +Easy + +Given a **0-indexed** integer array `nums`, return `true` _if it can be made **strictly increasing** after removing **exactly one** element, or_ `false` _otherwise. If the array is already strictly increasing, return_ `true`. + +The array `nums` is **strictly increasing** if `nums[i - 1] < nums[i]` for each index `(1 <= i < nums.length).` + +**Example 1:** + +**Input:** nums = [1,2,10,5,7] + +**Output:** true + +**Explanation:** By removing 10 at index 2 from nums, it becomes [1,2,5,7]. [1,2,5,7] is strictly increasing, so return true. + +**Example 2:** + +**Input:** nums = [2,3,1,2] + +**Output:** false + +**Explanation:** + +[3,1,2] is the result of removing the element at index 0. + +[2,1,2] is the result of removing the element at index 1. + +[2,3,2] is the result of removing the element at index 2. + +[2,3,1] is the result of removing the element at index 3. + +No resulting array is strictly increasing, so return false. + +**Example 3:** + +**Input:** nums = [1,1,1] + +**Output:** false + +**Explanation:** The result of removing any element is [1,1]. [1,1] is not strictly increasing, so return false. + +**Constraints:** + +* `2 <= nums.length <= 1000` +* `1 <= nums[i] <= 1000` + +## Solution + +```kotlin +class Solution { + fun canBeIncreasing(nums: IntArray): Boolean { + var removed = false + for (i in 1 until nums.size) { + if (nums[i] <= nums[i - 1]) { + removed = if (removed) { + return false + } else { + true + } + if (i > 1 && nums[i] <= nums[i - 2]) { + nums[i] = nums[i - 1] + } + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1910_remove_all_occurrences_of_a_substring/readme.md b/src/main/kotlin/g1901_2000/s1910_remove_all_occurrences_of_a_substring/readme.md new file mode 100644 index 00000000..29b93244 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1910_remove_all_occurrences_of_a_substring/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1910\. Remove All Occurrences of a Substring + +Medium + +Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed: + +* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`. + +Return `s` _after removing all occurrences of_ `part`. + +A **substring** is a contiguous sequence of characters in a string. + +**Example 1:** + +**Input:** s = "daabcbaabcbc", part = "abc" + +**Output:** "dab" + +**Explanation:** The following operations are done: + +- s = "da**abc**baabcbc", remove "abc" starting at index 2, so s = "dabaabcbc". + +- s = "daba**abc**bc", remove "abc" starting at index 4, so s = "dababc". + +- s = "dab**abc**", remove "abc" starting at index 3, so s = "dab". Now s has no occurrences of "abc". + +**Example 2:** + +**Input:** s = "axxxxyyyyb", part = "xy" + +**Output:** "ab" + +**Explanation:** The following operations are done: + +- s = "axxx**xy**yyyb", remove "xy" starting at index 4 so s = "axxxyyyb". + +- s = "axx**xy**yyb", remove "xy" starting at index 3 so s = "axxyyb". + +- s = "ax**xy**yb", remove "xy" starting at index 2 so s = "axyb". + +- s = "a**xy**b", remove "xy" starting at index 1 so s = "ab". Now s has no occurrences of "xy". + +**Constraints:** + +* `1 <= s.length <= 1000` +* `1 <= part.length <= 1000` +* `s` and `part` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun removeOccurrences(s: String, part: String): String { + val sb = StringBuilder() + for (i in 0 until s.length) { + sb.append(s[i]) + if (sb.length >= part.length && sb.substring(sb.length - part.length) == part) { + sb.setLength(sb.length - part.length) + } + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1911_maximum_alternating_subsequence_sum/readme.md b/src/main/kotlin/g1901_2000/s1911_maximum_alternating_subsequence_sum/readme.md new file mode 100644 index 00000000..33dfc1a3 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1911_maximum_alternating_subsequence_sum/readme.md @@ -0,0 +1,60 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1911\. Maximum Alternating Subsequence Sum + +Medium + +The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices. + +* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`. + +Given an array `nums`, return _the **maximum alternating sum** of any subsequence of_ `nums` _(after **reindexing** the elements of the subsequence)_. + +A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not. + +**Example 1:** + +**Input:** nums = [4,2,5,3] + +**Output:** 7 + +**Explanation:** It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7. + +**Example 2:** + +**Input:** nums = [5,6,7,8] + +**Output:** 8 + +**Explanation:** It is optimal to choose the subsequence [8] with alternating sum 8. + +**Example 3:** + +**Input:** nums = [6,2,1,2,4,5] + +**Output:** 10 + +**Explanation:** It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun maxAlternatingSum(nums: IntArray): Long { + val n = nums.size + var even = nums[0].toLong() + var odd: Long = 0 + for (i in 1 until n) { + even = Math.max(even, Math.max(odd + nums[i], nums[i].toLong())) + odd = Math.max(odd, Math.max(even - nums[i], 0)) + } + return Math.max(even, odd) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1912_design_movie_rental_system/readme.md b/src/main/kotlin/g1901_2000/s1912_design_movie_rental_system/readme.md new file mode 100644 index 00000000..80cdbc99 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1912_design_movie_rental_system/readme.md @@ -0,0 +1,121 @@ +[![](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) + +## 1912\. Design Movie Rental System + +Hard + +You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies. + +Each movie is given as a 2D integer array `entries` where entries[i] = [shopi, moviei, pricei] indicates that there is a copy of movie moviei at shop shopi with a rental price of pricei. Each shop carries **at most one** copy of a movie moviei. + +The system should support the following functions: + +* **Search**: Finds the **cheapest 5 shops** that have an **unrented copy** of a given movie. The shops should be sorted by **price** in ascending order, and in case of a tie, the one with the **smaller** shopi should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned. +* **Rent**: Rents an **unrented copy** of a given movie from a given shop. +* **Drop**: Drops off a **previously rented copy** of a given movie at a given shop. +* **Report**: Returns the **cheapest 5 rented movies** (possibly of the same movie ID) as a 2D list `res` where res[j] = [shopj, moviej] describes that the jth cheapest rented movie moviej was rented from the shop shopj. The movies in `res` should be sorted by **price** in ascending order, and in case of a tie, the one with the **smaller** shopj should appear first, and if there is still tie, the one with the **smaller** moviej should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned. + +Implement the `MovieRentingSystem` class: + +* `MovieRentingSystem(int n, int[][] entries)` Initializes the `MovieRentingSystem` object with `n` shops and the movies in `entries`. +* `List search(int movie)` Returns a list of shops that have an **unrented copy** of the given `movie` as described above. +* `void rent(int shop, int movie)` Rents the given `movie` from the given `shop`. +* `void drop(int shop, int movie)` Drops off a previously rented `movie` at the given `shop`. +* `List> report()` Returns a list of cheapest **rented** movies as described above. + +**Note:** The test cases will be generated such that `rent` will only be called if the shop has an **unrented** copy of the movie, and `drop` will only be called if the shop had **previously rented** out the movie. + +**Example 1:** + +**Input** ["MovieRentingSystem", "search", "rent", "rent", "report", "drop", "search"] [[3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]], [1], [0, 1], [1, 2], [], [1, 2], [2]] + +**Output:** [null, [1, 0, 2], null, null, [[0, 1], [1, 2]], null, [0, 1]] + +**Explanation:** MovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]); movieRentingSystem.search(1); // return [1, 0, 2], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number. movieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now [2,3]. movieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now [1]. movieRentingSystem.report(); // return [[0, 1], [1, 2]]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1. movieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now [1,2]. movieRentingSystem.search(2); // return [0, 1]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1. + +**Constraints:** + +* 1 <= n <= 3 * 105 +* 1 <= entries.length <= 105 +* 0 <= shopi < n +* 1 <= moviei, pricei <= 104 +* Each shop carries **at most one** copy of a movie moviei. +* At most 105 calls **in total** will be made to `search`, `rent`, `drop` and `report`. + +## Solution + +```kotlin +import java.util.TreeSet + +@Suppress("UNUSED_PARAMETER") +class MovieRentingSystem(n: Int, entries: Array) { + private class Point(var movie: Int, var shop: Int, var price: Int) + + private val unrentedMovies = HashMap>() + private val shopMovieToPrice = HashMap() + private val comparator = Comparator { o1: Point, o2: Point -> + return@Comparator if (o1.price != o2.price) { + Integer.compare(o1.price, o2.price) + } else if (o1.shop != o2.shop) { + Integer.compare(o1.shop, o2.shop) + } else { + Integer.compare(o1.movie, o2.movie) + } + } + private val rented = TreeSet(comparator) + + init { + for (entry in entries) { + val shop = entry[0] + val movie = entry[1] + val price = entry[2] + unrentedMovies.putIfAbsent(movie, TreeSet(comparator)) + unrentedMovies[movie]!!.add(Point(movie, shop, price)) + shopMovieToPrice["$shop+$movie"] = price + } + } + + fun search(movie: Int): List { + if (!unrentedMovies.containsKey(movie)) { + return ArrayList() + } + val iterator: Iterator = unrentedMovies[movie]!!.iterator() + val listOfShops: MutableList = ArrayList() + while (iterator.hasNext() && listOfShops.size < 5) { + listOfShops.add(iterator.next().shop) + } + return listOfShops + } + + fun rent(shop: Int, movie: Int) { + val price = shopMovieToPrice["$shop+$movie"]!! + rented.add(Point(movie, shop, price)) + unrentedMovies[movie]!!.remove(Point(movie, shop, price)) + } + + fun drop(shop: Int, movie: Int) { + val price = shopMovieToPrice["$shop+$movie"]!! + rented.remove(Point(movie, shop, price)) + unrentedMovies[movie]!!.add(Point(movie, shop, price)) + } + + fun report(): List> { + val ans: MutableList> = ArrayList() + val iterator: Iterator = rented.iterator() + while (iterator.hasNext() && ans.size < 5) { + val point = iterator.next() + ans.add(listOf(point.shop, point.movie)) + } + return ans + } +} +/* + * Your MovieRentingSystem object will be instantiated and called as such: + * var obj = MovieRentingSystem(n, entries) + * var param_1 = obj.search(movie) + * obj.rent(shop,movie) + * obj.drop(shop,movie) + * var param_4 = obj.report() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1913_maximum_product_difference_between_two_pairs/readme.md b/src/main/kotlin/g1901_2000/s1913_maximum_product_difference_between_two_pairs/readme.md new file mode 100644 index 00000000..65a53df6 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1913_maximum_product_difference_between_two_pairs/readme.md @@ -0,0 +1,51 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1913\. Maximum Product Difference Between Two Pairs + +Easy + +The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`. + +* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`. + +Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product difference** between pairs `(nums[w], nums[x])` and `(nums[y], nums[z])` is **maximized**. + +Return _the **maximum** such product difference_. + +**Example 1:** + +**Input:** nums = [5,6,2,7,4] + +**Output:** 34 + +**Explanation:** We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4). + +The product difference is (6 \* 7) - (2 \* 4) = 34. + +**Example 2:** + +**Input:** nums = [4,2,5,9,7,4,8] + +**Output:** 64 + +**Explanation:** We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4). + +The product difference is (9 \* 8) - (2 \* 4) = 64. + +**Constraints:** + +* 4 <= nums.length <= 104 +* 1 <= nums[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun maxProductDifference(nums: IntArray): Int { + nums.sort() + val len = nums.size + return nums[len - 1] * nums[len - 2] - nums[0] * nums[1] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1914_cyclically_rotating_a_grid/readme.md b/src/main/kotlin/g1901_2000/s1914_cyclically_rotating_a_grid/readme.md new file mode 100644 index 00000000..94da111c --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1914_cyclically_rotating_a_grid/readme.md @@ -0,0 +1,110 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1914\. Cyclically Rotating a Grid + +Medium + +You are given an `m x n` integer matrix `grid`, where `m` and `n` are both **even** integers, and an integer `k`. + +The matrix is composed of several layers, which is shown in the below image, where each color is its own layer: + +![](https://assets.leetcode.com/uploads/2021/06/10/ringofgrid.png) + +A cyclic rotation of the matrix is done by cyclically rotating **each layer** in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the **counter-clockwise** direction. An example rotation is shown below: + +![](https://assets.leetcode.com/uploads/2021/06/22/explanation_grid.jpg) + +Return _the matrix after applying_ `k` _cyclic rotations to it_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/06/19/rod2.png) + +**Input:** grid = \[\[40,10],[30,20]], k = 1 + +**Output:** [[10,20],[40,30]] + +**Explanation:** The figures above represent the grid at every state. + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2021/06/10/ringofgrid5.png)** **![](https://assets.leetcode.com/uploads/2021/06/10/ringofgrid6.png)** **![](https://assets.leetcode.com/uploads/2021/06/10/ringofgrid7.png)** + +**Input:** grid = \[\[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2 + +**Output:** [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]] + +**Explanation:** The figures above represent the grid at every state. + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `2 <= m, n <= 50` +* Both `m` and `n` are **even** integers. +* `1 <= grid[i][j] <= 5000` +* 1 <= k <= 109 + +## Solution + +```kotlin +class Solution { + fun rotateGrid(grid: Array, k: Int): Array { + rotateInternal(grid, 0, grid[0].size - 1, 0, grid.size - 1, k) + return grid + } + + private fun rotateInternal(grid: Array, left: Int, right: Int, up: Int, bottom: Int, k: Int) { + if (left > right || up > bottom) { + return + } + val loopLen = (right - left + 1) * 2 + (bottom - up + 1) * 2 - 4 + val realK = k % loopLen + if (realK != 0) { + rotateLayer(grid, left, right, up, bottom, realK) + } + rotateInternal(grid, left + 1, right - 1, up + 1, bottom - 1, k) + } + + private fun rotateLayer(grid: Array, left: Int, right: Int, up: Int, bottom: Int, k: Int) { + val startPoint = intArrayOf(up, left) + val loopLen = (right - left + 1) * 2 + (bottom - up + 1) * 2 - 4 + val arr = IntArray(loopLen) + var idx = 0 + var currPoint: IntArray? = startPoint + var startPointAfterRotation: IntArray? = null + while (idx < arr.size) { + arr[idx] = grid[currPoint!![0]][currPoint[1]] + idx++ + currPoint = getNextPosCC(left, right, up, bottom, currPoint) + if (idx == k) { + startPointAfterRotation = currPoint + } + } + idx = 0 + currPoint = startPointAfterRotation + if (currPoint != null) { + while (idx < arr.size) { + grid[currPoint!![0]][currPoint[1]] = arr[idx] + idx++ + currPoint = getNextPosCC(left, right, up, bottom, currPoint) + } + } + } + + private fun getNextPosCC(left: Int, right: Int, up: Int, bottom: Int, curr: IntArray?): IntArray { + val x = curr!![0] + val y = curr[1] + return if (x == up && y > left) { + intArrayOf(x, y - 1) + } else if (y == left && x < bottom) { + intArrayOf(x + 1, y) + } else if (x == bottom && y < right) { + intArrayOf(x, y + 1) + } else { + intArrayOf(x - 1, y) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1915_number_of_wonderful_substrings/readme.md b/src/main/kotlin/g1901_2000/s1915_number_of_wonderful_substrings/readme.md new file mode 100644 index 00000000..9da91ff7 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1915_number_of_wonderful_substrings/readme.md @@ -0,0 +1,95 @@ +[![](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) + +## 1915\. Number of Wonderful Substrings + +Medium + +A **wonderful** string is a string where **at most one** letter appears an **odd** number of times. + +* For example, `"ccjjc"` and `"abab"` are wonderful, but `"ab"` is not. + +Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-empty substrings** in_ `word`_. If the same substring appears multiple times in_ `word`_, then count **each occurrence** separately._ + +A **substring** is a contiguous sequence of characters in a string. + +**Example 1:** + +**Input:** word = "aba" + +**Output:** 4 + +**Explanation:** The four wonderful substrings are underlined below: + +- "**a**ba" -> "a" + +- "a**b**a" -> "b" + +- "ab**a**" -> "a" + +- "**aba**" -> "aba" + +**Example 2:** + +**Input:** word = "aabb" + +**Output:** 9 + +**Explanation:** The nine wonderful substrings are underlined below: + +- "**a**abb" -> "a" + +- "**aa**bb" -> "aa" + +- "**aab**b" -> "aab" + +- "**aabb**" -> "aabb" + +- "a**a**bb" -> "a" + +- "a**abb**" -> "abb" + +- "aa**b**b" -> "b" + +- "aa**bb**" -> "bb" + +- "aab**b**" -> "b" + +**Example 3:** + +**Input:** word = "he" + +**Output:** 2 + +**Explanation:** The two wonderful substrings are underlined below: + +- "**h**e" -> "h" + +- "h**e**" -> "e" + +**Constraints:** + +* 1 <= word.length <= 105 +* `word` consists of lowercase English letters from `'a'` to `'j'`. + +## Solution + +```kotlin +class Solution { + fun wonderfulSubstrings(word: String): Long { + val count = IntArray(1024) + var res: Long = 0 + var cur = 0 + count[0] = 1 + for (i in 0 until word.length) { + cur = cur xor (1 shl word[i].code - 'a'.code) + res += count[cur].toLong() + for (j in 0..9) { + res += count[cur xor (1 shl j)].toLong() + } + ++count[cur] + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1916_count_ways_to_build_rooms_in_an_ant_colony/readme.md b/src/main/kotlin/g1901_2000/s1916_count_ways_to_build_rooms_in_an_ant_colony/readme.md new file mode 100644 index 00000000..a8dc2fc4 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1916_count_ways_to_build_rooms_in_an_ant_colony/readme.md @@ -0,0 +1,117 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1916\. Count Ways to Build Rooms in an Ant Colony + +Hard + +You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` before building room `i`, and these two rooms must be connected **directly**. Room `0` is already built, so `prevRoom[0] = -1`. The expansion plan is given such that once all the rooms are built, every room will be reachable from room `0`. + +You can only build **one room** at a time, and you can travel freely between rooms you have **already built** only if they are **connected**. You can choose to build **any room** as long as its **previous room** is already built. + +Return _the **number of different orders** you can build all the rooms in_. Since the answer may be large, return it **modulo** 109 + 7. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/06/19/d1.JPG) + +**Input:** prevRoom = [-1,0,1] + +**Output:** 1 + +**Explanation:** There is only one way to build the additional rooms: 0 → 1 → 2 + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2021/06/19/d2.JPG)** + +**Input:** prevRoom = [-1,0,0,1,2] + +**Output:** 6 + +**Explanation:** The 6 ways are: + +0 → 1 → 3 → 2 → 4 + +0 → 2 → 4 → 1 → 3 + +0 → 1 → 2 → 3 → 4 + +0 → 1 → 2 → 4 → 3 + +0 → 2 → 1 → 3 → 4 + +0 → 2 → 1 → 4 → 3 + +**Constraints:** + +* `n == prevRoom.length` +* 2 <= n <= 105 +* `prevRoom[0] == -1` +* `0 <= prevRoom[i] < n` for all `1 <= i < n` +* Every room is reachable from room `0` once all the rooms are built. + +## Solution + +```kotlin +import java.math.BigInteger + +class Solution { + private lateinit var graph: Array?> + private lateinit var fact: LongArray + + fun waysToBuildRooms(prevRoom: IntArray): Int { + val n = prevRoom.size + graph = Array(n) { mutableListOf() } + fact = LongArray(prevRoom.size + 10) + fact[1] = 1 + fact[0] = fact[1] + for (i in 2 until fact.size) { + fact[i] = fact[i - 1] * i + fact[i] %= MOD.toLong() + } + for (i in 1 until prevRoom.size) { + val pre = prevRoom[i] + graph[pre]?.add(i) + } + val res = dfs(0) + return (res[1] % MOD).toInt() + } + + private fun dfs(root: Int): LongArray { + val res = longArrayOf(1, 0) + var cnt = 0 + val list: MutableList = ArrayList() + for (next in graph[root]!!) { + val v = dfs(next) + cnt += v[0].toInt() + list.add(v) + } + res[0] += cnt.toLong() + var com: Long = 1 + for (p in list) { + val choose = c(cnt, p[0].toInt()) + cnt -= p[0].toInt() + com = com * choose + com %= MOD.toLong() + com = com * p[1] + com %= MOD.toLong() + } + res[1] = com + return res + } + + private fun c(i: Int, j: Int): Long { + val mod: Long = 1000000007 + val prevRoom = fact[i] + val b = fact[i - j] % mod * (fact[j] % mod) % mod + val value = BigInteger.valueOf(b) + val binverse = value.modInverse(BigInteger.valueOf(mod)).toLong() + return prevRoom * (binverse % mod) % mod + } + + companion object { + private const val MOD = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1920_build_array_from_permutation/readme.md b/src/main/kotlin/g1901_2000/s1920_build_array_from_permutation/readme.md new file mode 100644 index 00000000..a198d78f --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1920_build_array_from_permutation/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) + +## 1920\. Build Array from Permutation + +Easy + +Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it. + +A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**). + +**Example 1:** + +**Input:** nums = \[0,2,1,5,3,4] + +**Output:** \[0,1,2,4,5,3] + +**Explanation:** The array ans is built as follows: + +ans = [nums[nums\[0]], nums[nums\[1]], nums[nums\[2]], nums[nums\[3]], nums[nums\[4]], nums[nums\[5]]] + = [nums\[0], nums\[2], nums\[1], nums\[5], nums\[3], nums\[4]] + = \[0,1,2,4,5,3] + +**Example 2:** + +**Input:** nums = \[5,0,1,2,3,4] + +**Output:** \[4,5,0,1,2,3] + +**Explanation:** The array ans is built as follows: + +ans = [nums[nums\[0]], nums[nums\[1]], nums[nums\[2]], nums[nums\[3]], nums[nums\[4]], nums[nums\[5]]] + = [nums\[5], nums\[0], nums\[1], nums\[2], nums\[3], nums\[4]] + = \[4,5,0,1,2,3] + +**Constraints:** + +* `1 <= nums.length <= 1000` +* `0 <= nums[i] < nums.length` +* The elements in `nums` are **distinct**. + +**Follow-up:** Can you solve it without using an extra space (i.e., `O(1)` memory)? + +## Solution + +```kotlin +class Solution { + fun buildArray(nums: IntArray): IntArray { + val ans = IntArray(nums.size) + for (i in nums.indices) { + ans[i] = nums[nums[i]] + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1921_eliminate_maximum_number_of_monsters/readme.md b/src/main/kotlin/g1901_2000/s1921_eliminate_maximum_number_of_monsters/readme.md new file mode 100644 index 00000000..94787a80 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1921_eliminate_maximum_number_of_monsters/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) + +## 1921\. Eliminate Maximum Number of Monsters + +Medium + +You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the ith monster from the city. + +The monsters walk toward the city at a **constant** speed. The speed of each monster is given to you in an integer array `speed` of size `n`, where `speed[i]` is the speed of the ith monster in kilometers per minute. + +You have a weapon that, once fully charged, can eliminate a **single** monster. However, the weapon takes **one minute** to charge.The weapon is fully charged at the very start. + +You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a **loss**, and the game ends before you can use your weapon. + +Return _the **maximum** number of monsters that you can eliminate before you lose, or_ `n` _if you can eliminate all the monsters before they reach the city._ + +**Example 1:** + +**Input:** dist = [1,3,4], speed = [1,1,1] + +**Output:** 3 + +**Explanation:** + +In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster. + +After a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster. + +After a minute, the distances of the monsters are [X,X,2]. You eliminate the thrid monster. + +All 3 monsters can be eliminated. + +**Example 2:** + +**Input:** dist = [1,1,2,3], speed = [1,1,1,1] + +**Output:** 1 + +**Explanation:** + +In the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster. + +After a minute, the distances of the monsters are [X,0,1,2], so you lose. You can only eliminate 1 monster. + +**Example 3:** + +**Input:** dist = [3,2,4], speed = [5,3,2] + +**Output:** 1 + +**Explanation:** + +In the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster. + +After a minute, the distances of the monsters are [X,0,2], so you lose. You can only eliminate 1 monster. + +**Constraints:** + +* `n == dist.length == speed.length` +* 1 <= n <= 105 +* 1 <= dist[i], speed[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun eliminateMaximum(dist: IntArray, speed: IntArray): Int { + for (i in dist.indices) { + dist[i] = (dist[i] - 1) / speed[i] + 1 + } + dist.sort() + var ans = 1 + var time = 1 + for (i in 1 until dist.size) { + if (dist[i] > time) { + ans++ + time++ + } else { + return ans + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1922_count_good_numbers/readme.md b/src/main/kotlin/g1901_2000/s1922_count_good_numbers/readme.md new file mode 100644 index 00000000..69527d40 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1922_count_good_numbers/readme.md @@ -0,0 +1,60 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1922\. Count Good Numbers + +Medium + +A digit string is **good** if the digits **(0-indexed)** at **even** indices are **even** and the digits at **odd** indices are **prime** (`2`, `3`, `5`, or `7`). + +* For example, `"2582"` is good because the digits (`2` and `8`) at even positions are even and the digits (`5` and `2`) at odd positions are prime. However, `"3245"` is **not** good because `3` is at an even index but is not even. + +Given an integer `n`, return _the **total** number of good digit strings of length_ `n`. Since the answer may be large, **return it modulo** 109 + 7. + +A **digit string** is a string consisting of digits `0` through `9` that may contain leading zeros. + +**Example 1:** + +**Input:** n = 1 + +**Output:** 5 + +**Explanation:** The good numbers of length 1 are "0", "2", "4", "6", "8". + +**Example 2:** + +**Input:** n = 4 + +**Output:** 400 + +**Example 3:** + +**Input:** n = 50 + +**Output:** 564908303 + +**Constraints:** + +* 1 <= n <= 1015 + +## Solution + +```kotlin +class Solution { + fun countGoodNumbers(n: Long): Int { + val mod = 1000000007L + var result = if (n % 2 == 0L) 1L else 5L + var base = 20L + var time = n / 2L + while (time > 0) { + if (time % 2L > 0) { + result *= base + result %= mod + } + time /= 2L + base = base * base % mod + } + return result.toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1923_longest_common_subpath/readme.md b/src/main/kotlin/g1901_2000/s1923_longest_common_subpath/readme.md new file mode 100644 index 00000000..39272a19 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1923_longest_common_subpath/readme.md @@ -0,0 +1,123 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1923\. Longest Common Subpath + +Hard + +There is a country of `n` cities numbered from `0` to `n - 1`. In this country, there is a road connecting **every pair** of cities. + +There are `m` friends numbered from `0` to `m - 1` who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city **more than once**, but the same city will not be listed consecutively. + +Given an integer `n` and a 2D integer array `paths` where `paths[i]` is an integer array representing the path of the ith friend, return _the length of the **longest common subpath** that is shared by **every** friend's path, or_ `0` _if there is no common subpath at all_. + +A **subpath** of a path is a contiguous sequence of cities within that path. + +**Example 1:** + +**Input:** n = 5, paths = \[\[0,1,2,3,4], + [2,3,4], + [4,0,1,2,3]] + +**Output:** 2 + +**Explanation:** The longest common subpath is [2,3]. + +**Example 2:** + +**Input:** n = 3, paths = \[\[0],[1],[2]] + +**Output:** 0 + +**Explanation:** There is no common subpath shared by the three paths. + +**Example 3:** + +**Input:** n = 5, paths = \[\[0,1,2,3,4], + [4,3,2,1,0]] + +**Output:** 1 + +**Explanation:** The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1. + +**Constraints:** + +* 1 <= n <= 105 +* `m == paths.length` +* 2 <= m <= 105 +* sum(paths[i].length) <= 105 +* `0 <= paths[i][j] < n` +* The same city is not listed multiple times consecutively in `paths[i]`. + +## Solution + +```kotlin +@Suppress("UNUSED_PARAMETER") +class Solution { + private lateinit var pow: LongArray + + fun longestCommonSubpath(n: Int, paths: Array): Int { + var res = 0 + var min = Int.MAX_VALUE + for (path in paths) { + min = Math.min(min, path.size) + } + pow = LongArray(min + 1) + pow[0]++ + for (i in 1..min) { + pow[i] = pow[i - 1] * BASE % MOD + } + var st = 1 + var end = min + var mid = (st + end) / 2 + while (st <= end) { + if (commonSubstring(paths, mid)) { + res = mid + st = mid + 1 + } else { + end = mid - 1 + } + mid = (st + end) / 2 + } + return res + } + + private fun commonSubstring(paths: Array, l: Int): Boolean { + val set = rollingHash(paths[0], l) + var i = 1 + val n = paths.size + while (i < n) { + set.retainAll(rollingHash(paths[i], l)) + if (set.isEmpty()) { + return false + } + i++ + } + return true + } + + private fun rollingHash(a: IntArray, l: Int): HashSet { + val set = HashSet() + var hash: Long = 0 + for (i in 0 until l) { + hash = (hash * BASE + a[i]) % MOD + } + set.add(hash) + val n = a.size + var curr = l + var prev = 0 + while (curr < n) { + hash = (hash * BASE % MOD - a[prev] * pow[l] % MOD + a[curr] + MOD) % MOD + set.add(hash) + prev++ + curr++ + } + return set + } + + companion object { + private const val BASE: Long = 100001 + private val MOD = (Math.pow(10.0, 11.0) + 7).toLong() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1925_count_square_sum_triples/readme.md b/src/main/kotlin/g1901_2000/s1925_count_square_sum_triples/readme.md new file mode 100644 index 00000000..4d80c0f8 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1925_count_square_sum_triples/readme.md @@ -0,0 +1,50 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1925\. Count Square Sum Triples + +Easy + +A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and a2 + b2 = c2. + +Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`. + +**Example 1:** + +**Input:** n = 5 + +**Output:** 2 + +**Explanation:** The square triples are (3,4,5) and (4,3,5). + +**Example 2:** + +**Input:** n = 10 + +**Output:** 4 + +**Explanation:** The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10). + +**Constraints:** + +* `1 <= n <= 250` + +## Solution + +```kotlin +class Solution { + fun countTriples(n: Int): Int { + var count = 0 + for (i in 1 until n) { + for (j in 1 until n) { + val product = i * i + j * j + val sq = Math.sqrt(product.toDouble()) + if (sq <= n && sq - Math.floor(sq) == 0.0) { + count++ + } + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1926_nearest_exit_from_entrance_in_maze/readme.md b/src/main/kotlin/g1901_2000/s1926_nearest_exit_from_entrance_in_maze/readme.md new file mode 100644 index 00000000..45ef4f18 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1926_nearest_exit_from_entrance_in_maze/readme.md @@ -0,0 +1,105 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1926\. Nearest Exit from Entrance in Maze + +Medium + +You are given an `m x n` matrix `maze` (**0-indexed**) with empty cells (represented as `'.'`) and walls (represented as `'+'`). You are also given the `entrance` of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at. + +In one step, you can move one cell **up**, **down**, **left**, or **right**. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the **nearest exit** from the `entrance`. An **exit** is defined as an **empty cell** that is at the **border** of the `maze`. The `entrance` **does not count** as an exit. + +Return _the **number of steps** in the shortest path from the_ `entrance` _to the nearest exit, or_ `-1` _if no such path exists_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/06/04/nearest1-grid.jpg) + +**Input:** maze = \[\["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2] + +**Output:** 1 + +**Explanation:** + +There are 3 exits in this maze at [1,0], [0,2], and [2,3]. Initially, you are at the entrance cell [1,2]. + +- You can reach [1,0] by moving 2 steps left. + +- You can reach [0,2] by moving 1 step up. + +It is impossible to reach [2,3] from the entrance. Thus, the nearest exit is [0,2], which is 1 step away. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/06/04/nearesr2-grid.jpg) + +**Input:** maze = \[\["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0] + +**Output:** 2 + +**Explanation:** + +There is 1 exit in this maze at [1,2]. [1,0] does not count as an exit since it is the entrance cell. Initially, you are at the entrance cell [1,0]. + +- You can reach [1,2] by moving 2 steps right. + +Thus, the nearest exit is [1,2], which is 2 steps away. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/06/04/nearest3-grid.jpg) + +**Input:** maze = \[\[".","+"]], entrance = [0,0] + +**Output:** -1 + +**Explanation:** There are no exits in this maze. + +**Constraints:** + +* `maze.length == m` +* `maze[i].length == n` +* `1 <= m, n <= 100` +* `maze[i][j]` is either `'.'` or `'+'`. +* `entrance.length == 2` +* 0 <= entrancerow < m +* 0 <= entrancecol < n +* `entrance` will always be an empty cell. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + fun nearestExit(maze: Array, entrance: IntArray): Int { + val m = maze.size + val n = maze[0].size + val directions = intArrayOf(0, 1, 0, -1, 0) + val queue: Queue = LinkedList() + queue.offer(intArrayOf(entrance[0], entrance[1], 0)) + val visited = Array(m) { BooleanArray(n) } + visited[entrance[0]][entrance[1]] = true + var shortestSteps = m * n + while (queue.isNotEmpty()) { + val curr = queue.poll() + for (i in 0 until directions.size - 1) { + val nextX = curr[0] + directions[i] + val nextY = curr[1] + directions[i + 1] + if (nextX >= 0 && nextX < m && nextY >= 0 && nextY < n && + maze[nextX][nextY] == '.' && !visited[nextX][nextY] + ) { + visited[nextX][nextY] = true + if (nextX == 0 || nextX == m - 1 || nextY == 0 || nextY == n - 1) { + shortestSteps = Math.min(shortestSteps, curr[2] + 1) + } else { + queue.offer(intArrayOf(nextX, nextY, curr[2] + 1)) + } + } + } + } + return if (shortestSteps == m * n) -1 else shortestSteps + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1927_sum_game/readme.md b/src/main/kotlin/g1901_2000/s1927_sum_game/readme.md new file mode 100644 index 00000000..658ecd56 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1927_sum_game/readme.md @@ -0,0 +1,85 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1927\. Sum Game + +Medium + +Alice and Bob take turns playing a game, with **Alice starting first**. + +You are given a string `num` of **even length** consisting of digits and `'?'` characters. On each turn, a player will do the following if there is still at least one `'?'` in `num`: + +1. Choose an index `i` where `num[i] == '?'`. +2. Replace `num[i]` with any digit between `'0'` and `'9'`. + +The game ends when there are no more `'?'` characters in `num`. + +For Bob to win, the sum of the digits in the first half of `num` must be **equal** to the sum of the digits in the second half. For Alice to win, the sums must **not be equal**. + +* For example, if the game ended with `num = "243801"`, then Bob wins because `2+4+3 = 8+0+1`. If the game ended with `num = "243803"`, then Alice wins because `2+4+3 != 8+0+3`. + +Assuming Alice and Bob play **optimally**, return `true` _if Alice will win and_ `false` _if Bob will win_. + +**Example 1:** + +**Input:** num = "5023" + +**Output:** false + +**Explanation:** There are no moves to be made. The sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3. + +**Example 2:** + +**Input:** num = "25??" + +**Output:** true + +**Explanation:** Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal. + +**Example 3:** + +**Input:** num = "?3295???" + +**Output:** false + +**Explanation:** It can be proven that Bob will always win. One possible outcome is: + +- Alice replaces the first '?' with '9'. num = "93295???". + +- Bob replaces one of the '?' in the right half with '9'. num = "932959??". + +- Alice replaces one of the '?' in the right half with '2'. num = "9329592?". + +- Bob replaces the last '?' in the right half with '7'. num = "93295927". + +Bob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7. + +**Constraints:** + +* 2 <= num.length <= 105 +* `num.length` is **even**. +* `num` consists of only digits and `'?'`. + +## Solution + +```kotlin +class Solution { + fun sumGame(num: String): Boolean { + var count = 0 + var diff = 0 + val l = num.length + for (i in 0 until num.length) { + if (num[i] == '?') { + count += if (i < l / 2) 1 else -1 + } else { + if (i < l / 2) { + diff += num[i].code - '0'.code + } else { + diff -= num[i].code - '0'.code + } + } + } + return diff * 2 != -9 * count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1928_minimum_cost_to_reach_destination_in_time/readme.md b/src/main/kotlin/g1901_2000/s1928_minimum_cost_to_reach_destination_in_time/readme.md new file mode 100644 index 00000000..33f4908e --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1928_minimum_cost_to_reach_destination_in_time/readme.md @@ -0,0 +1,106 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1928\. Minimum Cost to Reach Destination in Time + +Hard + +There is a country of `n` cities numbered from `0` to `n - 1` where **all the cities are connected** by bi-directional roads. The roads are represented as a 2D integer array `edges` where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself. + +Each time you pass through a city, you must pay a passing fee. This is represented as a **0-indexed** integer array `passingFees` of length `n` where `passingFees[j]` is the amount of dollars you must pay when you pass through city `j`. + +In the beginning, you are at city `0` and want to reach city `n - 1` in `maxTime` **minutes or less**. The **cost** of your journey is the **summation of passing fees** for each city that you passed through at some moment of your journey (**including** the source and destination cities). + +Given `maxTime`, `edges`, and `passingFees`, return _the **minimum cost** to complete your journey, or_ `-1` _if you cannot complete it within_ `maxTime` _minutes_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/06/04/leetgraph1-1.png) + +**Input:** maxTime = 30, edges = \[\[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3] + +**Output:** 11 + +**Explanation:** The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees. + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2021/06/04/copy-of-leetgraph1-1.png)** + +**Input:** maxTime = 29, edges = \[\[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3] + +**Output:** 48 + +**Explanation:** The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees. You cannot take path 0 -> 1 -> 2 -> 5 since it would take too long. + +**Example 3:** + +**Input:** maxTime = 25, edges = \[\[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3] + +**Output:** -1 + +**Explanation:** There is no way to reach city 5 from city 0 within 25 minutes. + +**Constraints:** + +* `1 <= maxTime <= 1000` +* `n == passingFees.length` +* `2 <= n <= 1000` +* `n - 1 <= edges.length <= 1000` +* 0 <= xi, yi <= n - 1 +* 1 <= timei <= 1000 +* `1 <= passingFees[j] <= 1000` +* The graph may contain multiple edges between two nodes. +* The graph does not contain self loops. + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + fun minCost(maxTime: Int, edges: Array, passingFees: IntArray): Int { + val pq = PriorityQueue { a: Tuple, b: Tuple -> if (a.cost == b.cost) a.time - b.time else a.cost - b.cost } + val n = passingFees.size + val minTime = IntArray(n) + minTime.fill(Int.MAX_VALUE) + val graph = Graph() + for (edge in edges) { + graph.addEdge(edge[0], edge[1], edge[2]) + } + pq.offer(Tuple(0, passingFees[0], 0)) + while (pq.isNotEmpty()) { + val curr = pq.poll() + if (curr.time <= maxTime && curr.time < minTime[curr.node]) { + minTime[curr.node] = curr.time + if (curr.node == n - 1) { + return curr.cost + } + for (edge in graph.getEdges(curr.node)) { + val time = curr.time + edge.weight + if (time > maxTime || time >= minTime[edge.dst]) { + continue + } + pq.offer(Tuple(edge.dst, curr.cost + passingFees[edge.dst], time)) + } + } + } + return -1 + } + + private class Graph { + private val edges: MutableMap> = HashMap() + fun addEdge(src: Int, dst: Int, weight: Int) { + edges.computeIfAbsent(src) { _: Int? -> ArrayList() }.add(Edge(dst, weight)) + edges.computeIfAbsent(dst) { _: Int? -> ArrayList() }.add(Edge(src, weight)) + } + + fun getEdges(node: Int): List { + return edges.getOrDefault(node, ArrayList()) + } + } + + private class Edge(val dst: Int, val weight: Int) + private class Tuple(val node: Int, val cost: Int, val time: Int) +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1929_concatenation_of_array/readme.md b/src/main/kotlin/g1901_2000/s1929_concatenation_of_array/readme.md new file mode 100644 index 00000000..38dc03a2 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1929_concatenation_of_array/readme.md @@ -0,0 +1,61 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1929\. Concatenation of Array + +Easy + +Given an integer array `nums` of length `n`, you want to create an array `ans` of length `2n` where `ans[i] == nums[i]` and `ans[i + n] == nums[i]` for `0 <= i < n` (**0-indexed**). + +Specifically, `ans` is the **concatenation** of two `nums` arrays. + +Return _the array_ `ans`. + +**Example 1:** + +**Input:** nums = [1,2,1] + +**Output:** [1,2,1,1,2,1] + +**Explanation:** The array ans is formed as follows: + +- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]] + +- ans = [1,2,1,1,2,1] + +**Example 2:** + +**Input:** nums = [1,3,2,1] + +**Output:** [1,3,2,1,1,3,2,1] + +**Explanation:** The array ans is formed as follows: + +- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]] + +- ans = [1,3,2,1,1,3,2,1] + +**Constraints:** + +* `n == nums.length` +* `1 <= n <= 1000` +* `1 <= nums[i] <= 1000` + +## Solution + +```kotlin +class Solution { + fun getConcatenation(nums: IntArray): IntArray { + val result = IntArray(nums.size * 2) + System.arraycopy(nums, 0, result, 0, nums.size) + var i = nums.size + var j = 0 + while (i < result.size && j < nums.size) { + result[i] = nums[j] + i++ + j++ + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1930_unique_length_3_palindromic_subsequences/readme.md b/src/main/kotlin/g1901_2000/s1930_unique_length_3_palindromic_subsequences/readme.md new file mode 100644 index 00000000..9b7b47dd --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1930_unique_length_3_palindromic_subsequences/readme.md @@ -0,0 +1,97 @@ +[![](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) + +## 1930\. Unique Length-3 Palindromic Subsequences + +Medium + +Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`. + +Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**. + +A **palindrome** is a string that reads the same forwards and backwards. + +A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. + +* For example, `"ace"` is a subsequence of `"abcde"`. + +**Example 1:** + +**Input:** s = "aabca" + +**Output:** 3 + +**Explanation:** The 3 palindromic subsequences of length 3 are: + +- "aba" (subsequence of "aabca") + +- "aaa" (subsequence of "aabca") + +- "aca" (subsequence of "aabca") + +**Example 2:** + +**Input:** s = "adc" + +**Output:** 0 + +**Explanation:** There are no palindromic subsequences of length 3 in "adc". + +**Example 3:** + +**Input:** s = "bbcbaba" + +**Output:** 4 + +**Explanation:** The 4 palindromic subsequences of length 3 are: + +- "bbb" (subsequence of "bbcbaba") + +- "bcb" (subsequence of "bbcbaba") + +- "bab" (subsequence of "bbcbaba") + +- "aba" (subsequence of "bbcbaba") + +**Constraints:** + +* 3 <= s.length <= 105 +* `s` consists of only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun countPalindromicSubsequence(s: String): Int { + val last = IntArray(26) + last.fill(-1) + for (i in s.length - 1 downTo 0) { + if (last[s[i].code - 'a'.code] == -1) { + last[s[i].code - 'a'.code] = i + } + } + var ans = 0 + val count = IntArray(26) + val first: MutableMap = HashMap() + for (i in 0 until s.length) { + val cur = s[i].code - 'a'.code + if (last[cur] - i <= 1 && !first.containsKey(cur)) { + last[cur] = -1 + } + if (last[cur] == i) { + val oldCount = first[cur] + for (j in 0..25) { + if (count[j] - oldCount!![j] > 0) { + ans++ + } + } + } + count[cur]++ + if (last[cur] > -1 && !first.containsKey(cur)) { + first[cur] = count.clone() + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1931_painting_a_grid_with_three_different_colors/readme.md b/src/main/kotlin/g1901_2000/s1931_painting_a_grid_with_three_different_colors/readme.md new file mode 100644 index 00000000..cd0e09b8 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1931_painting_a_grid_with_three_different_colors/readme.md @@ -0,0 +1,251 @@ +[![](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) + +## 1931\. Painting a Grid With Three Different Colors + +Hard + +You are given two integers `m` and `n`. Consider an `m x n` grid where each cell is initially white. You can paint each cell **red**, **green**, or **blue**. All cells **must** be painted. + +Return _the number of ways to color the grid with **no two adjacent cells having the same color**_. Since the answer can be very large, return it **modulo** 109 + 7. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/06/22/colorthegrid.png) + +**Input:** m = 1, n = 1 + +**Output:** 3 + +**Explanation:** The three possible colorings are shown in the image above. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/06/22/copy-of-colorthegrid.png) + +**Input:** m = 1, n = 2 + +**Output:** 6 + +**Explanation:** The six possible colorings are shown in the image above. + +**Example 3:** + +**Input:** m = 5, n = 5 + +**Output:** 580986 + +**Constraints:** + +* `1 <= m <= 5` +* `1 <= n <= 1000` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun colorTheGrid(m: Int, n: Int): Int { + if (m == 1) { + return (3L * powMod(2, n - 1) % P).toInt() + } + if (m == 2) { + return (6L * powMod(3, n - 1) % P).toInt() + } + if (n == 1) { + return (3L * powMod(2, m - 1) % P).toInt() + } + if (n == 2) { + return (6L * powMod(3, m - 1) % P).toInt() + } + val totalTemplates = 1 shl m - 2 + val totalPaintings = binPow(3, m) + val paintingToTemplate = IntArray(totalPaintings) + val paintingCountForTemplate = LongArray(totalTemplates) + val templateEdgeCount = Array(totalTemplates) { LongArray(totalTemplates) } + val templateToIndex: MutableMap = HashMap(1 shl m - 2) + val templateCounter = 0 + extracted( + m, + totalPaintings, + paintingToTemplate, + paintingCountForTemplate, + templateToIndex, + templateCounter + ) + extracted(m, totalPaintings, paintingToTemplate, templateEdgeCount) + for (i in 0 until totalTemplates) { + val c = paintingCountForTemplate[i] + for (j in 0 until totalTemplates) { + templateEdgeCount[i][j] /= c + } + } + val matrixPower = matrixPower(templateEdgeCount, n.toLong() - 1) + var ans: Long = 0 + for (i in 0 until totalTemplates) { + var s: Long = 0 + val arr = matrixPower[i] + for (a in arr) { + s += a + } + ans += paintingCountForTemplate[i] * s + } + return (ans % P).toInt() + } + + private fun extracted( + m: Int, + totalPaintings: Int, + paintingToTemplate: IntArray, + templateEdgeCount: Array + ) { + for (i in 0 until totalPaintings) { + if (paintingToTemplate[i] == -1) { + continue + } + for (j in i + 1 until totalPaintings) { + if (paintingToTemplate[j] == -1) { + continue + } + if (checkAllowance(i, j, m)) { + templateEdgeCount[paintingToTemplate[i]][paintingToTemplate[j]]++ + templateEdgeCount[paintingToTemplate[j]][paintingToTemplate[i]]++ + } + } + } + } + + private fun extracted( + m: Int, + totalPaintings: Int, + paintingToTemplate: IntArray, + paintingCountForTemplate: LongArray, + templateToIndex: MutableMap, + templateCounter: Int + ) { + var templateCounter = templateCounter + for (i in 0 until totalPaintings) { + val type = getType(i, m) + if (type == -1) { + paintingToTemplate[i] = -1 + continue + } + var templateIndex = templateToIndex[type] + if (templateIndex == null) { + templateToIndex[type] = templateCounter + templateIndex = templateCounter++ + } + paintingToTemplate[i] = templateIndex + paintingCountForTemplate[templateIndex]++ + } + } + + private fun checkAllowance(a: Int, b: Int, m: Int): Boolean { + var a = a + var b = b + for (i in 0 until m) { + if (a % 3 == b % 3) { + return false + } + a /= 3 + b /= 3 + } + return true + } + + private fun getType(a: Int, m: Int): Int { + var a = a + var m = m + val digits = IntArray(3) + val first = a % 3 + val second = a % 9 / 3 + if (first == second) { + return -1 + } + digits[second] = 1 + digits[3 - first - second] = 2 + var prev = second + var type = 1 + m -= 2 + a /= 9 + while (m-- > 0) { + val curr = a % 3 + if (prev == curr) { + return -1 + } + type = type * 3 + digits[curr] + prev = curr + a /= 3 + } + return type + } + + private fun powMod(a: Int, b: Int): Int { + var a = a + var b = b + var res: Long = 1 + while (b != 0) { + if (b and 1 != 0) { + res = res * a % P + --b + } else { + a = (a.toLong() * a % P).toInt() + b = b shr 1 + } + } + return res.toInt() + } + + private fun binPow(a: Int, n: Int): Int { + var n = n + var res = 1 + var tmp = a + while (n != 0) { + if (n and 1 != 0) { + res *= tmp + } + tmp *= tmp + n = n shr 1 + } + return res + } + + private fun matrixPower(base: Array, pow: Long): Array { + var base = base + var pow = pow + val n = base.size + var res = Array(n) { LongArray(n) } + for (i in 0 until n) { + res[i][i] = 1 + } + while (pow != 0L) { + if (pow and 1L != 0L) { + res = multiplyMatrix(res, base) + --pow + } else { + base = multiplyMatrix(base, base) + pow = pow shr 1 + } + } + return res + } + + private fun multiplyMatrix(a: Array, b: Array): Array { + val n = a.size + val ans = Array(n) { LongArray(n) } + for (i in 0 until n) { + for (j in 0 until n) { + for (k in 0 until n) { + ans[i][j] += a[i][k] * b[k][j] + } + ans[i][j] %= P.toLong() + } + } + return ans + } + + companion object { + const val P = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1932_merge_bsts_to_create_single_bst/readme.md b/src/main/kotlin/g1901_2000/s1932_merge_bsts_to_create_single_bst/readme.md new file mode 100644 index 00000000..e37dea75 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1932_merge_bsts_to_create_single_bst/readme.md @@ -0,0 +1,133 @@ +[![](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) + +## 1932\. Merge BSTs to Create Single BST + +Hard + +You are given `n` **BST (binary search tree) root nodes** for `n` separate BSTs stored in an array `trees` (**0-indexed**). Each BST in `trees` has **at most 3 nodes**, and no two roots have the same value. In one operation, you can: + +* Select two **distinct** indices `i` and `j` such that the value stored at one of the **leaves** of `trees[i]` is equal to the **root value** of `trees[j]`. +* Replace the leaf node in `trees[i]` with `trees[j]`. +* Remove `trees[j]` from `trees`. + +Return _the **root** of the resulting BST if it is possible to form a valid BST after performing_ `n - 1` _operations, or_ `null` _if it is impossible to create a valid BST_. + +A BST (binary search tree) is a binary tree where each node satisfies the following property: + +* Every node in the node's left subtree has a value **strictly less** than the node's value. +* Every node in the node's right subtree has a value **strictly greater** than the node's value. + +A leaf is a node that has no children. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/06/08/d1.png) + +**Input:** trees = \[\[2,1],[3,2,5],[5,4]] + +**Output:** [3,2,5,1,null,4] + +**Explanation:** In the first operation, pick i=1 and j=0, and merge trees[0] into trees[1]. Delete trees[0], so trees = \[\[3,2,5,1],[5,4]]. ![](https://assets.leetcode.com/uploads/2021/06/24/diagram.png) In the second operation, pick i=0 and j=1, and merge trees[1] into trees[0]. Delete trees[1], so trees = \[\[3,2,5,1,null,4]]. ![](https://assets.leetcode.com/uploads/2021/06/24/diagram-2.png) The resulting tree, shown above, is a valid BST, so return its root. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/06/08/d2.png) + +**Input:** trees = \[\[5,3,8],[3,2,6]] + +**Output:** [] + +**Explanation:** Pick i=0 and j=1 and merge trees[1] into trees[0]. Delete trees[1], so trees = \[\[5,3,8,2,6]]. ![](https://assets.leetcode.com/uploads/2021/06/24/diagram-3.png) The resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/06/08/d3.png) + +**Input:** trees = \[\[5,4],[3]] + +**Output:** [] + +**Explanation:** It is impossible to perform any operations. + +**Constraints:** + +* `n == trees.length` +* 1 <= n <= 5 * 104 +* The number of nodes in each tree is in the range `[1, 3]`. +* Each node in the input may have children but no grandchildren. +* No two roots of `trees` have the same value. +* All the trees in the input are **valid BSTs**. +* 1 <= TreeNode.val <= 5 * 104. + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun canMerge(trees: List): TreeNode? { + val valToNode: MutableMap = HashMap() + val count: MutableMap = HashMap() + for (tree in trees) { + valToNode[tree.`val`] = tree + count.merge( + tree.`val`, 1 + ) { a: Int?, b: Int? -> + Integer.sum( + a!!, b!! + ) + } + if (tree.left != null) count.merge( + tree.left!!.`val`, 1 + ) { a: Int?, b: Int? -> + Integer.sum( + a!!, b!! + ) + } + if (tree.right != null) count.merge( + tree.right!!.`val`, 1 + ) { a: Int?, b: Int? -> + Integer.sum( + a!!, b!! + ) + } + } + for (tree in trees) if (count[tree.`val`] == 1) { + return if (isValidBST(tree, null, null, valToNode) && + valToNode.size <= 1 + ) tree else null + } + return null + } + + fun isValidBST( + tree: TreeNode?, + minNode: TreeNode?, + maxNode: TreeNode?, + valToNode: MutableMap + ): Boolean { + if (tree == null) return true + if (minNode != null && tree.`val` <= minNode.`val`) return false + if (maxNode != null && tree.`val` >= maxNode.`val`) return false + if (tree.left == null && tree.right == null && valToNode.containsKey(tree.`val`)) { + val `val` = tree.`val` + tree.left = valToNode[`val`]!!.left + tree.right = valToNode[`val`]!!.right + valToNode.remove(`val`) + } + return isValidBST(tree.left, minNode, tree, valToNode) && + isValidBST(tree.right, tree, maxNode, valToNode) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1934_confirmation_rate/readme.md b/src/main/kotlin/g1901_2000/s1934_confirmation_rate/readme.md new file mode 100644 index 00000000..2d8fd623 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1934_confirmation_rate/readme.md @@ -0,0 +1,105 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1934\. Confirmation Rate + +Medium + +SQL Schema + +Table: `Signups` + + +----------------+----------+ + | Column Name | Type | + +----------------+----------+ + | user_id | int | + | time_stamp | datetime | + +----------------+----------+ + user_id is the primary key for this table. + Each row contains information about the signup time for the user with ID user_id. + +Table: `Confirmations` + + +----------------+----------+ + | Column Name | Type | + +----------------+----------+ + | user_id | int | + | time_stamp | datetime | + | action | ENUM | + +----------------+----------+ + (user_id, time_stamp) is the primary key for this table. + user_id is a foreign key with a reference to the Signups table. + action is an ENUM of the type ('confirmed', 'timeout') + Each row of this table indicates that the user with ID user_id requested a confirmation message at time_stamp and that confirmation message was either confirmed ('confirmed') or expired without confirming ('timeout'). + +The **confirmation rate** of a user is the number of `'confirmed'` messages divided by the total number of requested confirmation messages. The confirmation rate of a user that did not request any confirmation messages is `0`. Round the confirmation rate to **two decimal** places. + +Write an SQL query to find the **confirmation rate** of each user. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Signups table: + +---------+---------------------+ + | user_id | time_stamp | + +---------+---------------------+ + | 3 | 2020-03-21 10:16:13 | + | 7 | 2020-01-04 13:57:59 | + | 2 | 2020-07-29 23:09:44 | + | 6 | 2020-12-09 10:39:37 | + +---------+---------------------+ + + Confirmations table: + +---------+---------------------+-----------+ + | user_id | time_stamp | action | + +---------+---------------------+-----------+ + | 3 | 2021-01-06 03:30:46 | timeout | + | 3 | 2021-07-14 14:00:00 | timeout | + | 7 | 2021-06-12 11:57:29 | confirmed | + | 7 | 2021-06-13 12:58:28 | confirmed | + | 7 | 2021-06-14 13:59:27 | confirmed | + | 2 | 2021-01-22 00:00:00 | confirmed | + | 2 | 2021-02-28 23:59:59 | timeout | + +---------+---------------------+-----------+ + +**Output:** + + +---------+-------------------+ + | user_id | confirmation_rate | + +---------+-------------------+ + | 6 | 0.00 | + | 3 | 0.00 | + | 7 | 1.00 | + | 2 | 0.50 | + +---------+-------------------+ + +**Explanation:** + +User 6 did not request any confirmation messages. The confirmation rate is 0. + +User 3 made 2 requests and both timed out. The confirmation rate is 0. + +User 7 made 3 requests and all were confirmed. The confirmation rate is 1. + +User 2 made 2 requests where one was confirmed and the other timed out. The confirmation rate is 1 / 2 = 0.5. + +## Solution + +```sql +# Write your MySQL query statement below +select + s.user_id + , round(count(case when action = 'confirmed' then 1 end) + / cast(count(*) as decimal(7,2)), 2) as confirmation_rate + from + Signups s + left join + Confirmations c + on c.user_id = s.user_id + group by 1 +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1935_maximum_number_of_words_you_can_type/readme.md b/src/main/kotlin/g1901_2000/s1935_maximum_number_of_words_you_can_type/readme.md new file mode 100644 index 00000000..ae717e03 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1935_maximum_number_of_words_you_can_type/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) + +## 1935\. Maximum Number of Words You Can Type + +Easy + +There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly. + +Given a string `text` of words separated by a single space (no leading or trailing spaces) and a string `brokenLetters` of all **distinct** letter keys that are broken, return _the **number of words** in_ `text` _you can fully type using this keyboard_. + +**Example 1:** + +**Input:** text = "hello world", brokenLetters = "ad" + +**Output:** 1 + +**Explanation:** We cannot type "world" because the 'd' key is broken. + +**Example 2:** + +**Input:** text = "leet code", brokenLetters = "lt" + +**Output:** 1 + +**Explanation:** We cannot type "leet" because the 'l' and 't' keys are broken. + +**Example 3:** + +**Input:** text = "leet code", brokenLetters = "e" + +**Output:** 0 + +**Explanation:** We cannot type either word because the 'e' key is broken. + +**Constraints:** + +* 1 <= text.length <= 104 +* `0 <= brokenLetters.length <= 26` +* `text` consists of words separated by a single space without any leading or trailing spaces. +* Each word only consists of lowercase English letters. +* `brokenLetters` consists of **distinct** lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun canBeTypedWords(text: String, brokenLetters: String): Int { + val words = text.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + var count = 0 + for (word in words) { + var broken = false + for (c in word.toCharArray()) { + if (brokenLetters.indexOf(c) != -1) { + broken = true + break + } + } + if (!broken) { + count++ + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1936_add_minimum_number_of_rungs/readme.md b/src/main/kotlin/g1901_2000/s1936_add_minimum_number_of_rungs/readme.md new file mode 100644 index 00000000..723b1a04 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1936_add_minimum_number_of_rungs/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) + +## 1936\. Add Minimum Number of Rungs + +Medium + +You are given a **strictly increasing** integer array `rungs` that represents the **height** of rungs on a ladder. You are currently on the **floor** at height `0`, and you want to reach the last rung. + +You are also given an integer `dist`. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is **at most** `dist`. You are able to insert rungs at any positive **integer** height if a rung is not already there. + +Return _the **minimum** number of rungs that must be added to the ladder in order for you to climb to the last rung._ + +**Example 1:** + +**Input:** rungs = [1,3,5,10], dist = 2 + +**Output:** 2 + +**Explanation:** + +You currently cannot reach the last rung. + +Add rungs at heights 7 and 8 to climb this ladder. + +The ladder will now have rungs at [1,3,5,7,8,10]. + +**Example 2:** + +**Input:** rungs = [3,6,8,10], dist = 3 + +**Output:** 0 + +**Explanation:** This ladder can be climbed without adding additional rungs. + +**Example 3:** + +**Input:** rungs = [3,4,6,7], dist = 2 + +**Output:** 1 + +**Explanation:** + +You currently cannot reach the first rung from the ground. + +Add a rung at height 1 to climb this ladder. + +The ladder will now have rungs at [1,3,4,6,7]. + +**Constraints:** + +* 1 <= rungs.length <= 105 +* 1 <= rungs[i] <= 109 +* 1 <= dist <= 109 +* `rungs` is **strictly increasing**. + +## Solution + +```kotlin +class Solution { + fun addRungs(rungs: IntArray, dist: Int): Int { + var addons = 0 + var currentHeight = 0 + var i = 0 + while (i < rungs.size) { + val nextRung = rungs[i] + if (nextRung - currentHeight <= dist) { + currentHeight = nextRung + i++ + } else { + val adds = (nextRung - currentHeight - 1) / dist + addons += adds + currentHeight += dist * adds + } + } + return addons + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1937_maximum_number_of_points_with_cost/readme.md b/src/main/kotlin/g1901_2000/s1937_maximum_number_of_points_with_cost/readme.md new file mode 100644 index 00000000..6fca3e39 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1937_maximum_number_of_points_with_cost/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) + +## 1937\. Maximum Number of Points with Cost + +Medium + +You are given an `m x n` integer matrix `points` (**0-indexed**). Starting with `0` points, you want to **maximize** the number of points you can get from the matrix. + +To gain points, you must pick one cell in **each row**. Picking the cell at coordinates `(r, c)` will **add** `points[r][c]` to your score. + +However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows `r` and `r + 1` (where `0 <= r < m - 1`), picking cells at coordinates (r, c1) and (r + 1, c2) will **subtract** abs(c1 - c2) from your score. + +Return _the **maximum** number of points you can achieve_. + +`abs(x)` is defined as: + +* `x` for `x >= 0`. +* `-x` for `x < 0`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/07/12/screenshot-2021-07-12-at-13-40-26-diagram-drawio-diagrams-net.png) + +**Input:** points = \[\[1,2,3],[1,5,1],[3,1,1]] + +**Output:** 9 + +**Explanation:** + +The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0). + +You add 3 + 5 + 3 = 11 to your score. + +However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score. + +Your final score is 11 - 2 = 9. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/07/12/screenshot-2021-07-12-at-13-42-14-diagram-drawio-diagrams-net.png) + +**Input:** points = \[\[1,5],[2,3],[4,2]] + +**Output:** 11 + +**Explanation:** + +The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0). + +You add 5 + 3 + 4 = 12 to your score. + +However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score. + +Your final score is 12 - 1 = 11. + +**Constraints:** + +* `m == points.length` +* `n == points[r].length` +* 1 <= m, n <= 105 +* 1 <= m * n <= 105 +* 0 <= points[r][c] <= 105 + +## Solution + +```kotlin +class Solution { + fun maxPoints(points: Array): Long { + val m = points[0].size + var pre = LongArray(m) + for (point in points) { + val current = LongArray(m) + var max = Long.MIN_VALUE + for (j in 0 until m) { + max = Math.max(max, pre[j] + j) + current[j] = Math.max(current[j], point[j] - j + max) + } + max = Long.MIN_VALUE + for (j in m - 1 downTo 0) { + max = Math.max(max, pre[j] - j) + current[j] = Math.max(current[j], point[j] + j + max) + } + pre = current + } + var max = Long.MIN_VALUE + for (`val` in pre) { + max = Math.max(max, `val`) + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1938_maximum_genetic_difference_query/readme.md b/src/main/kotlin/g1901_2000/s1938_maximum_genetic_difference_query/readme.md new file mode 100644 index 00000000..5347b0cb --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1938_maximum_genetic_difference_query/readme.md @@ -0,0 +1,104 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1938\. Maximum Genetic Difference Query + +Hard + +There is a rooted tree consisting of `n` nodes numbered `0` to `n - 1`. Each node's number denotes its **unique genetic value** (i.e. the genetic value of node `x` is `x`). The **genetic difference** between two genetic values is defined as the **bitwise-XOR** of their values. You are given the integer array `parents`, where `parents[i]` is the parent for node `i`. If node `x` is the **root** of the tree, then `parents[x] == -1`. + +You are also given the array `queries` where queries[i] = [nodei, vali]. For each query `i`, find the **maximum genetic difference** between vali and pi, where pi is the genetic value of any node that is on the path between nodei and the root (including nodei and the root). More formally, you want to maximize vali XOR pi. + +Return _an array_ `ans` _where_ `ans[i]` _is the answer to the_ ith _query_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/06/29/c1.png) + +**Input:** parents = [-1,0,1,1], queries = \[\[0,2],[3,2],[2,5]] + +**Output:** [2,3,7] + +**Explanation:** The queries are processed as follows: + +- \[0,2]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2. + +- \[3,2]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3. + +- \[2,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/06/29/c2.png) + +**Input:** parents = [3,7,-1,2,0,7,0,2], queries = \[\[4,6],[1,15],[0,5]] + +**Output:** [6,14,7] + +**Explanation:** The queries are processed as follows: + +- \[4,6]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6. + +- \[1,15]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14. + +- \[0,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7. + +**Constraints:** + +* 2 <= parents.length <= 105 +* `0 <= parents[i] <= parents.length - 1` for every node `i` that is **not** the root. +* `parents[root] == -1` +* 1 <= queries.length <= 3 * 104 +* 0 <= nodei <= parents.length - 1 +* 0 <= vali <= 2 * 105 + +## Solution + +```kotlin +class Solution { + fun maxGeneticDifference(parents: IntArray, queries: Array): IntArray { + val n = parents.size + val fd = arrayOfNulls(n) + for (i in 0 until n) { + fill(parents, n, fd, i) + } + val ret = IntArray(queries.size) + for (q in queries.indices) { + var cur = queries[q][0] + val value = queries[q][1] + for (p in 30 downTo 0) { + val msk = 1 shl p + if (value and msk != cur and msk) { + ret[q] = ret[q] or msk + } else if (fd[cur]!![p] >= 0) { + ret[q] = ret[q] or msk + cur = fd[cur]!![p] + } + } + } + return ret + } + + private fun fill(parents: IntArray, n: Int, fd: Array, i: Int) { + if (fd[i] == null) { + fd[i] = IntArray(31) + var a = parents[i] + if (a >= 0) { + fill(parents, n, fd, a) + } + for (p in 30 downTo 0) { + if (a == -1) { + fd[i]!![p] = -1 + } else { + if (i and (1 shl p) == a and (1 shl p)) { + fd[i]!![p] = fd[a]!![p] + } else { + fd[i]!![p] = a + a = fd[a]!![p] + } + } + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1941_check_if_all_characters_have_equal_number_of_occurrences/readme.md b/src/main/kotlin/g1901_2000/s1941_check_if_all_characters_have_equal_number_of_occurrences/readme.md new file mode 100644 index 00000000..fd095077 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1941_check_if_all_characters_have_equal_number_of_occurrences/readme.md @@ -0,0 +1,57 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1941\. Check if All Characters Have Equal Number of Occurrences + +Easy + +Given a string `s`, return `true` _if_ `s` _is a **good** string, or_ `false` _otherwise_. + +A string `s` is **good** if **all** the characters that appear in `s` have the **same** number of occurrences (i.e., the same frequency). + +**Example 1:** + +**Input:** s = "abacbc" + +**Output:** true + +**Explanation:** The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s. + +**Example 2:** + +**Input:** s = "aaabb" + +**Output:** false + +**Explanation:** The characters that appear in s are 'a' and 'b'. 'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times. + +**Constraints:** + +* `1 <= s.length <= 1000` +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun areOccurrencesEqual(s: String): Boolean { + val counter = IntArray(26) + for (i in 0 until s.length) { + counter[s[i].code - 'a'.code]++ + } + var bench = 0 + for (i in 0..25) { + if (bench == 0) { + if (counter[i] != 0) { + bench = counter[i] + } + } else { + if (counter[i] != 0 && counter[i] != bench) { + return false + } + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1942_the_number_of_the_smallest_unoccupied_chair/readme.md b/src/main/kotlin/g1901_2000/s1942_the_number_of_the_smallest_unoccupied_chair/readme.md new file mode 100644 index 00000000..5c8771ef --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1942_the_number_of_the_smallest_unoccupied_chair/readme.md @@ -0,0 +1,111 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1942\. The Number of the Smallest Unoccupied Chair + +Medium + +There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**. + +* For example, if chairs `0`, `1`, and `5` are occupied when a friend comes, they will sit on chair number `2`. + +When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair. + +You are given a **0-indexed** 2D integer array `times` where times[i] = [arrivali, leavingi], indicating the arrival and leaving times of the ith friend respectively, and an integer `targetFriend`. All arrival times are **distinct**. + +Return _the **chair number** that the friend numbered_ `targetFriend` _will sit on_. + +**Example 1:** + +**Input:** times = \[\[1,4],[2,3],[4,6]], targetFriend = 1 + +**Output:** 1 + +**Explanation:** + +- Friend 0 arrives at time 1 and sits on chair 0. + +- Friend 1 arrives at time 2 and sits on chair 1. + +- Friend 1 leaves at time 3 and chair 1 becomes empty. + +- Friend 0 leaves at time 4 and chair 0 becomes empty. + +- Friend 2 arrives at time 4 and sits on chair 0. + +Since friend 1 sat on chair 1, we return 1. + +**Example 2:** + +**Input:** times = \[\[3,10],[1,5],[2,6]], targetFriend = 0 + +**Output:** 2 + +**Explanation:** + +- Friend 1 arrives at time 1 and sits on chair 0. + +- Friend 2 arrives at time 2 and sits on chair 1. + +- Friend 0 arrives at time 3 and sits on chair 2. + +- Friend 1 leaves at time 5 and chair 0 becomes empty. + +- Friend 2 leaves at time 6 and chair 1 becomes empty. + +- Friend 0 leaves at time 10 and chair 2 becomes empty. + +Since friend 0 sat on chair 2, we return 2. + +**Constraints:** + +* `n == times.length` +* 2 <= n <= 104 +* `times[i].length == 2` +* 1 <= arrivali < leavingi <= 105 +* `0 <= targetFriend <= n - 1` +* Each arrivali time is **distinct**. + +## Solution + +```kotlin +import java.util.Arrays +import java.util.PriorityQueue + +class Solution { + fun smallestChair(times: Array, targetFriend: Int): Int { + val minheap = PriorityQueue() + minheap.offer(0) + val all = arrayOfNulls(times.size * 2) + for (i in times.indices) { + all[2 * i] = Person(i, times[i][0], false, true) + all[2 * i + 1] = Person(i, times[i][1], true, false) + } + Arrays.sort( + all + ) { a: Person?, b: Person? -> + val i = if (a!!.leave) -1 else 1 + val j = if (b!!.leave) -1 else 1 + if (a.time == b.time) i - j else a.time - b.time + } + val seat = IntArray(times.size) + var i = 0 + while (true) { + if (all[i]!!.arrive) { + if (targetFriend == all[i]!!.idx) { + return minheap.peek() + } + seat[all[i]!!.idx] = minheap.poll() + if (minheap.isEmpty()) { + minheap.offer(seat[all[i]!!.idx] + 1) + } + } else { + minheap.offer(seat[all[i]!!.idx]) + } + i++ + } + } + + private class Person internal constructor(var idx: Int, var time: Int, var leave: Boolean, var arrive: Boolean) +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1943_describe_the_painting/readme.md b/src/main/kotlin/g1901_2000/s1943_describe_the_painting/readme.md new file mode 100644 index 00000000..463b856d --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1943_describe_the_painting/readme.md @@ -0,0 +1,118 @@ +[![](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) + +## 1943\. Describe the Painting + +Medium + +There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a **unique** color. You are given a 2D integer array `segments`, where segments[i] = [starti, endi, colori] represents the **half-closed segment** [starti, endi) with colori as the color. + +The colors in the overlapping segments of the painting were **mixed** when it was painted. When two or more colors mix, they form a new color that can be represented as a **set** of mixed colors. + +* For example, if colors `2`, `4`, and `6` are mixed, then the resulting mixed color is `{2,4,6}`. + +For the sake of simplicity, you should only output the **sum** of the elements in the set rather than the full set. + +You want to **describe** the painting with the **minimum** number of non-overlapping **half-closed segments** of these mixed colors. These segments can be represented by the 2D array `painting` where painting[j] = [leftj, rightj, mixj] describes a **half-closed segment** [leftj, rightj) with the mixed color **sum** of mixj. + +* For example, the painting created with `segments = \[\[1,4,5],[1,7,7]]` can be described by `painting = \[\[1,4,12],[4,7,7]]` because: + * `[1,4)` is colored `{5,7}` (with a sum of `12`) from both the first and second segments. + * `[4,7)` is colored `{7}` from only the second segment. + +Return _the 2D array_ `painting` _describing the finished painting (excluding any parts that are **not** painted). You may return the segments in **any order**_. + +A **half-closed segment** `[a, b)` is the section of the number line between points `a` and `b` **including** point `a` and **not including** point `b`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/06/18/1.png) + +**Input:** segments = \[\[1,4,5],[4,7,7],[1,7,9]] + +**Output:** [[1,4,14],[4,7,16]] + +**Explanation:** The painting can be described as follows: + +- \[1,4) is colored {5,9} (with a sum of 14) from the first and third segments. + +- \[4,7) is colored {7,9} (with a sum of 16) from the second and third segments. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/06/18/2.png) + +**Input:** segments = \[\[1,7,9],[6,8,15],[8,10,7]] + +**Output:** [[1,6,9],[6,7,24],[7,8,15],[8,10,7]] + +**Explanation:** The painting can be described as follows: + +- \[1,6) is colored 9 from the first segment. + +- \[6,7) is colored {9,15} (with a sum of 24) from the first and second segments. + +- \[7,8) is colored 15 from the second segment. + +- \[8,10) is colored 7 from the third segment. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/07/04/c1.png) + +**Input:** segments = \[\[1,4,5],[1,4,7],[4,7,1],[4,7,11]] + +**Output:** [[1,4,12],[4,7,12]] + +**Explanation:** The painting can be described as follows: + +- \[1,4) is colored {5,7} (with a sum of 12) from the first and second segments. + +- \[4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments. + +Note that returning a single segment [1,7) is incorrect because the mixed color sets are different. + +**Constraints:** + +* 1 <= segments.length <= 2 * 104 +* `segments[i].length == 3` +* 1 <= starti < endi <= 105 +* 1 <= colori <= 109 +* Each colori is distinct. + +## Solution + +```kotlin +class Solution { + fun splitPainting(segments: Array): List> { + val result: MutableList> = ArrayList() + var n = 1 + for (s in segments) { + n = Math.max(n, s[1]) + } + n += 1 + val line = LongArray(n) + val endpoint = BooleanArray(n) + for (s in segments) { + val start = s[0] + val end = s[1] + val color = s[2] + line[start] += color.toLong() + line[end] -= color.toLong() + endpoint[end] = true + endpoint[start] = endpoint[end] + } + var mixedColor: Long = 0 + var start = 1 + for (end in 1 until n) { + if (endpoint[end]) { + if (mixedColor > 0) { + result.add(listOf(start.toLong(), end.toLong(), mixedColor)) + } + start = end + } + mixedColor += line[end] + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1944_number_of_visible_people_in_a_queue/readme.md b/src/main/kotlin/g1901_2000/s1944_number_of_visible_people_in_a_queue/readme.md new file mode 100644 index 00000000..c9ab8b6d --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1944_number_of_visible_people_in_a_queue/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1944\. Number of Visible People in a Queue + +Hard + +There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the ith person. + +A person can **see** another person to their right in the queue if everybody in between is **shorter** than both of them. More formally, the ith person can see the jth person if `i < j` and `min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1])`. + +Return _an array_ `answer` _of length_ `n` _where_ `answer[i]` _is the **number of people** the_ ith _person can **see** to their right in the queue_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/05/29/queue-plane.jpg) + +**Input:** heights = [10,6,8,5,11,9] + +**Output:** [3,1,2,1,1,0] + +**Explanation:** + +Person 0 can see person 1, 2, and 4. + +Person 1 can see person 2. + +Person 2 can see person 3 and 4. + +Person 3 can see person 4. + +Person 4 can see person 5. + +Person 5 can see no one since nobody is to the right of them. + +**Example 2:** + +**Input:** heights = [5,1,2,3,10] + +**Output:** [4,1,1,1,0] + +**Constraints:** + +* `n == heights.length` +* 1 <= n <= 105 +* 1 <= heights[i] <= 105 +* All the values of `heights` are **unique**. + +## Solution + +```kotlin +class Solution { + fun canSeePersonsCount(heights: IntArray): IntArray { + val size = heights.size + val stack = IntArray(size) + var idx = 0 + stack[0] = heights[size - 1] + val visible = IntArray(size) + for (i in size - 2 downTo 0) { + var count = 0 + while (idx >= 0 && heights[i] >= stack[idx]) { + count++ + idx-- + } + if (idx >= 0) { + count++ + } + stack[++idx] = heights[i] + visible[i] = count + } + return visible + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1945_sum_of_digits_of_string_after_convert/readme.md b/src/main/kotlin/g1901_2000/s1945_sum_of_digits_of_string_after_convert/readme.md new file mode 100644 index 00000000..6e907f86 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1945_sum_of_digits_of_string_after_convert/readme.md @@ -0,0 +1,87 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1945\. Sum of Digits of String After Convert + +Easy + +You are given a string `s` consisting of lowercase English letters, and an integer `k`. + +First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum of its digits**. Repeat the **transform** operation `k` **times** in total. + +For example, if `s = "zbax"` and `k = 2`, then the resulting integer would be `8` by the following operations: + +* **Convert**: `"zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124` +* **Transform #1**: `262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17` +* **Transform #2**: `17 ➝ 1 + 7 ➝ 8` + +Return _the resulting integer after performing the operations described above_. + +**Example 1:** + +**Input:** s = "iiii", k = 1 + +**Output:** 36 + +**Explanation:** The operations are as follows: + +- Convert: "iiii" ➝ "(9)(9)(9)(9)" ➝ "9999" ➝ 9999 + +- Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36 Thus the resulting integer is 36. + +**Example 2:** + +**Input:** s = "leetcode", k = 2 + +**Output:** 6 + +**Explanation:** The operations are as follows: + +- Convert: "leetcode" ➝ "(12)(5)(5)(20)(3)(15)(4)(5)" ➝ "12552031545" ➝ 12552031545 + +- Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33 + +- Transform #2: 33 ➝ 3 + 3 ➝ 6 Thus the resulting integer is 6. + +**Example 3:** + +**Input:** s = "zbax", k = 2 + +**Output:** 8 + +**Constraints:** + +* `1 <= s.length <= 100` +* `1 <= k <= 10` +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun getLucky(s: String, k: Int): Int { + var k = k + val list: MutableList = ArrayList() + for (c in s.toCharArray()) { + list.add(c.code - 'a'.code + 1) + } + var sum = 0 + for (i in list) { + if (i >= 10) { + sum += i / 10 + } + sum += i % 10 + } + while (k-- > 1) { + var newSum = 0 + while (sum != 0) { + newSum += sum % 10 + sum /= 10 + } + sum = newSum + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1946_largest_number_after_mutating_substring/readme.md b/src/main/kotlin/g1901_2000/s1946_largest_number_after_mutating_substring/readme.md new file mode 100644 index 00000000..76bd7c25 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1946_largest_number_after_mutating_substring/readme.md @@ -0,0 +1,85 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1946\. Largest Number After Mutating Substring + +Medium + +You are given a string `num`, which represents a large integer. You are also given a **0-indexed** integer array `change` of length `10` that maps each digit `0-9` to another digit. More formally, digit `d` maps to digit `change[d]`. + +You may **choose** to **mutate a single substring** of `num`. To mutate a substring, replace each digit `num[i]` with the digit it maps to in `change` (i.e. replace `num[i]` with `change[num[i]]`). + +Return _a string representing the **largest** possible integer after **mutating** (or choosing not to) a **single substring** of_ `num`. + +A **substring** is a contiguous sequence of characters within the string. + +**Example 1:** + +**Input:** num = "132", change = [9,8,5,0,3,6,4,2,6,8] + +**Output:** "832" + +**Explanation:** Replace the substring "1": + +- 1 maps to change[1] = 8. Thus, "132" becomes "832". + +"832" is the largest number that can be created, so return it. + +**Example 2:** + +**Input:** num = "021", change = [9,4,3,5,7,2,1,9,0,6] + +**Output:** "934" + +**Explanation:** Replace the substring "021": + +- 0 maps to change[0] = 9. + +- 2 maps to change[2] = 3. + +- 1 maps to change[1] = 4. + +Thus, "021" becomes "934". + +"934" is the largest number that can be created, so return it. + +**Example 3:** + +**Input:** num = "5", change = [1,4,7,5,3,2,5,6,9,4] + +**Output:** "5" + +**Explanation:** "5" is already the largest number that can be created, so return it. + +**Constraints:** + +* 1 <= num.length <= 105 +* `num` consists of only digits `0-9`. +* `change.length == 10` +* `0 <= change[d] <= 9` + +## Solution + +```kotlin +class Solution { + fun maximumNumber(num: String, change: IntArray): String { + val n = num.length + val nums = num.toCharArray() + val arr = CharArray(n) + for (i in 0 until n) { + val `val` = nums[i].code - '0'.code + arr[i] = (change[`val`] + '0'.code).toChar() + } + var flag = false + for (i in 0 until n) { + if (nums[i] < arr[i]) { + nums[i] = arr[i] + flag = true + } else if (flag && nums[i] > arr[i]) { + break + } + } + return String(nums) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1947_maximum_compatibility_score_sum/readme.md b/src/main/kotlin/g1901_2000/s1947_maximum_compatibility_score_sum/readme.md new file mode 100644 index 00000000..3744b5a5 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1947_maximum_compatibility_score_sum/readme.md @@ -0,0 +1,97 @@ +[![](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) + +## 1947\. Maximum Compatibility Score Sum + +Medium + +There is a survey that consists of `n` questions where each question's answer is either `0` (no) or `1` (yes). + +The survey was given to `m` students numbered from `0` to `m - 1` and `m` mentors numbered from `0` to `m - 1`. The answers of the students are represented by a 2D integer array `students` where `students[i]` is an integer array that contains the answers of the ith student (**0-indexed**). The answers of the mentors are represented by a 2D integer array `mentors` where `mentors[j]` is an integer array that contains the answers of the jth mentor (**0-indexed**). + +Each student will be assigned to **one** mentor, and each mentor will have **one** student assigned to them. The **compatibility score** of a student-mentor pair is the number of answers that are the same for both the student and the mentor. + +* For example, if the student's answers were `[1, 0, 1]` and the mentor's answers were `[0, 0, 1]`, then their compatibility score is 2 because only the second and the third answers are the same. + +You are tasked with finding the optimal student-mentor pairings to **maximize** the **sum of the compatibility scores**. + +Given `students` and `mentors`, return _the **maximum compatibility score sum** that can be achieved._ + +**Example 1:** + +**Input:** students = \[\[1,1,0],[1,0,1],[0,0,1]], mentors = \[\[1,0,0],[0,0,1],[1,1,0]] + +**Output:** 8 + +**Explanation:** We assign students to mentors in the following way: + +- student 0 to mentor 2 with a compatibility score of 3. + +- student 1 to mentor 0 with a compatibility score of 2. + +student 2 to mentor 1 with a compatibility score of 3. + +The compatibility score sum is 3 + 2 + 3 = 8. + +**Example 2:** + +**Input:** students = \[\[0,0],[0,0],[0,0]], mentors = \[\[1,1],[1,1],[1,1]] + +**Output:** 0 + +**Explanation:** The compatibility score of any student-mentor pair is 0. + +**Constraints:** + +* `m == students.length == mentors.length` +* `n == students[i].length == mentors[j].length` +* `1 <= m, n <= 8` +* `students[i][k]` is either `0` or `1`. +* `mentors[j][k]` is either `0` or `1`. + +## Solution + +```kotlin +class Solution { + private lateinit var dp: Array + private var m = 0 + private lateinit var memo: Array + + fun maxCompatibilitySum(students: Array, mentors: Array): Int { + val n = students[0].size + m = students.size + dp = Array(m) { IntArray(m) } + for (i in 0 until m) { + for (j in 0 until m) { + var tmp = 0 + for (k in 0 until n) { + tmp += if (students[i][k] == mentors[j][k]) 1 else 0 + } + dp[i][j] = tmp + } + } + memo = Array(m) { IntArray((1 shl m) + 1) } + for (x in memo) { + x.fill(-1) + } + return dp(0, 0) + } + + private fun dp(idx: Int, mask: Int): Int { + if (idx == m) { + return 0 + } + if (memo[idx][mask] != -1) { + return memo[idx][mask] + } + var ans = 0 + for (i in 0 until m) { + if (mask and (1 shl i) == 0) { + ans = Math.max(ans, dp[idx][i] + dp(idx + 1, mask or (1 shl i))) + } + } + memo[idx][mask] = ans + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1948_delete_duplicate_folders_in_system/readme.md b/src/main/kotlin/g1901_2000/s1948_delete_duplicate_folders_in_system/readme.md new file mode 100644 index 00000000..51909c63 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1948_delete_duplicate_folders_in_system/readme.md @@ -0,0 +1,145 @@ +[![](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) + +## 1948\. Delete Duplicate Folders in System + +Hard + +Due to a bug, there are many duplicate folders in a file system. You are given a 2D array `paths`, where `paths[i]` is an array representing an absolute path to the ith folder in the file system. + +* For example, `["one", "two", "three"]` represents the path `"/one/two/three"`. + +Two folders (not necessarily on the same level) are **identical** if they contain the **same non-empty** set of identical subfolders and underlying subfolder structure. The folders **do not** need to be at the root level to be identical. If two or more folders are **identical**, then **mark** the folders as well as all their subfolders. + +* For example, folders `"/a"` and `"/b"` in the file structure below are identical. They (as well as their subfolders) should **all** be marked: + * `/a` + * `/a/x` + * `/a/x/y` + * `/a/z` + * `/b` + * `/b/x` + * `/b/x/y` + * `/b/z` +* However, if the file structure also included the path `"/b/w"`, then the folders `"/a"` and `"/b"` would not be identical. Note that `"/a/x"` and `"/b/x"` would still be considered identical even with the added folder. + +Once all the identical folders and their subfolders have been marked, the file system will **delete** all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted. + +Return _the 2D array_ `ans` _containing the paths of the **remaining** folders after deleting all the marked folders. The paths may be returned in **any** order_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/07/19/lc-dupfolder1.jpg) + +**Input:** paths = \[\["a"],["c"],["d"],["a","b"],["c","b"],["d","a"]] + +**Output:** [["d"],["d","a"]] + +**Explanation:** The file structure is as shown. Folders "/a" and "/c" (and their subfolders) are marked for deletion because they both contain an empty folder named "b". + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/07/19/lc-dupfolder2.jpg) + +**Input:** paths = \[\["a"],["c"],["a","b"],["c","b"],["a","b","x"],["a","b","x","y"],["w"],["w","y"]] + +**Output:** [["c"],["c","b"],["a"],["a","b"]] + +**Explanation:** The file structure is as shown. Folders "/a/b/x" and "/w" (and their subfolders) are marked for deletion because they both contain an empty folder named "y". Note that folders "/a" and "/c" are identical after the deletion, but they are not deleted because they were not marked beforehand. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/07/19/lc-dupfolder3.jpg) + +**Input:** paths = \[\["a","b"],["c","d"],["c"],["a"]] + +**Output:** [["c"],["c","d"],["a"],["a","b"]] + +**Explanation:** All folders are unique in the file system. Note that the returned array can be in a different order as the order does not matter. + +**Constraints:** + +* 1 <= paths.length <= 2 * 104 +* `1 <= paths[i].length <= 500` +* `1 <= paths[i][j].length <= 10` +* 1 <= sum(paths[i][j].length) <= 2 * 105 +* `path[i][j]` consists of lowercase English letters. +* No two paths lead to the same folder. +* For any folder not at the root level, its parent folder will also be in the input. + +## Solution + +```kotlin +class Solution { + private var duplicates: MutableMap>? = null + private var foldersWithRemovedNames: MutableList>? = null + + fun deleteDuplicateFolder(paths: List>): List> { + duplicates = HashMap() + val rootFolder = Folder("", null) + for (path in paths) { + var folder = rootFolder + for (foldername in path) { + folder = folder.addSubFolder(foldername) + } + } + rootFolder.calculateHash() + for ((_, foldersWithSameHash) in duplicates as HashMap>) { + if (foldersWithSameHash.size > 1) { + for (folder in foldersWithSameHash) { + folder.parent?.subFolders?.remove(folder.name) + } + } + } + foldersWithRemovedNames = ArrayList() + for ((_, folder) in rootFolder.subFolders) { + val path: List = ArrayList() + folder.addPaths(path) + } + return foldersWithRemovedNames as ArrayList> + } + + private inner class Folder(val name: String, val parent: Folder?) { + val subFolders: MutableMap + private var folderHash = "" + + init { + subFolders = HashMap() + } + + fun addSubFolder(foldername: String): Folder { + return subFolders.computeIfAbsent(foldername) { f: String -> Folder(f, this) } + } + + fun calculateHash() { + val subFolderNames: MutableList = ArrayList(subFolders.keys) + subFolderNames.sort() + val builder = StringBuilder() + for (foldername in subFolderNames) { + val folder = subFolders[foldername] + folder!!.calculateHash() + builder.append('#') + builder.append(foldername) + if (folder.folderHash.isNotEmpty()) { + builder.append('(') + builder.append(folder.folderHash) + builder.append(')') + } + } + folderHash = builder.toString() + if (folderHash.isNotEmpty()) { + val duplicateFolders = duplicates!!.computeIfAbsent(folderHash) { _: String? -> ArrayList() } + duplicateFolders.add(this) + } + } + + fun addPaths(parentPath: List) { + val currentPath: MutableList = ArrayList(parentPath) + currentPath.add(name) + foldersWithRemovedNames!!.add(currentPath) + for ((_, folder) in subFolders) { + folder.addPaths(currentPath) + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1952_three_divisors/readme.md b/src/main/kotlin/g1901_2000/s1952_three_divisors/readme.md new file mode 100644 index 00000000..934ce838 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1952_three_divisors/readme.md @@ -0,0 +1,46 @@ +[![](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) + +## 1952\. Three Divisors + +Easy + +Given an integer `n`, return `true` _if_ `n` _has **exactly three positive divisors**. Otherwise, return_ `false`. + +An integer `m` is a **divisor** of `n` if there exists an integer `k` such that `n = k * m`. + +**Example 1:** + +**Input:** n = 2 + +**Output:** false + +**Explantion:** 2 has only two divisors: 1 and 2. + +**Example 2:** + +**Input:** n = 4 + +**Output:** true + +**Explantion:** 4 has three divisors: 1, 2, and 4. + +**Constraints:** + +* 1 <= n <= 104 + +## Solution + +```kotlin +class Solution { + fun isThree(n: Int): Boolean { + var divisors = 0 + for (i in 1..n) { + if (n % i == 0) { + divisors++ + } + } + return divisors == 3 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1953_maximum_number_of_weeks_for_which_you_can_work/readme.md b/src/main/kotlin/g1901_2000/s1953_maximum_number_of_weeks_for_which_you_can_work/readme.md new file mode 100644 index 00000000..78b03278 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1953_maximum_number_of_weeks_for_which_you_can_work/readme.md @@ -0,0 +1,85 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1953\. Maximum Number of Weeks for Which You Can Work + +Medium + +There are `n` projects numbered from `0` to `n - 1`. You are given an integer array `milestones` where each `milestones[i]` denotes the number of milestones the ith project has. + +You can work on the projects following these two rules: + +* Every week, you will finish **exactly one** milestone of **one** project. You **must** work every week. +* You **cannot** work on two milestones from the same project for two **consecutive** weeks. + +Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will **stop working**. Note that you may not be able to finish every project's milestones due to these constraints. + +Return _the **maximum** number of weeks you would be able to work on the projects without violating the rules mentioned above_. + +**Example 1:** + +**Input:** milestones = [1,2,3] + +**Output:** 6 + +**Explanation:** One possible scenario is: + +- During the 1st week, you will work on a milestone of project 0. + +- During the 2nd week, you will work on a milestone of project 2. + +- During the 3rd week, you will work on a milestone of project 1. + +- During the 4th week, you will work on a milestone of project 2. + +- During the 5th week, you will work on a milestone of project 1. + +- During the 6th week, you will work on a milestone of project 2. + +The total number of weeks is 6. + +**Example 2:** + +**Input:** milestones = [5,2,1] + +**Output:** 7 + +**Explanation:** One possible scenario is: + +- During the 1st week, you will work on a milestone of project 0. + +- During the 2nd week, you will work on a milestone of project 1. + +- During the 3rd week, you will work on a milestone of project 0. + +- During the 4th week, you will work on a milestone of project 1. + +- During the 5th week, you will work on a milestone of project 0. + +- During the 6th week, you will work on a milestone of project 2. + +- During the 7th week, you will work on a milestone of project 0. + +The total number of weeks is 7. Note that you cannot work on the last milestone of project 0 on 8th week because it would violate the rules. Thus, one milestone in project 0 will remain unfinished. + +**Constraints:** + +* `n == milestones.length` +* 1 <= n <= 105 +* 1 <= milestones[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun numberOfWeeks(milestones: IntArray): Long { + var sum: Long = 0 + var max: Long = 0 + for (m in milestones) { + sum += m.toLong() + max = Math.max(max, m.toLong()) + } + return if (sum - max + 1 >= max) sum else 1 + 2 * (sum - max) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1954_minimum_garden_perimeter_to_collect_enough_apples/readme.md b/src/main/kotlin/g1901_2000/s1954_minimum_garden_perimeter_to_collect_enough_apples/readme.md new file mode 100644 index 00000000..7ac3a18e --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1954_minimum_garden_perimeter_to_collect_enough_apples/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) + +## 1954\. Minimum Garden Perimeter to Collect Enough Apples + +Medium + +In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it. + +You will buy an axis-aligned **square plot** of land that is centered at `(0, 0)`. + +Given an integer `neededApples`, return _the **minimum perimeter** of a plot such that **at least**_ `neededApples` _apples are **inside or on** the perimeter of that plot_. + +The value of `|x|` is defined as: + +* `x` if `x >= 0` +* `-x` if `x < 0` + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/08/30/1527_example_1_2.png) + +**Input:** neededApples = 1 + +**Output:** 8 + +**Explanation:** A square plot of side length 1 does not contain any apples. However, a square plot of side length 2 has 12 apples inside (as depicted in the image above). The perimeter is 2 \* 4 = 8. + +**Example 2:** + +**Input:** neededApples = 13 + +**Output:** 16 + +**Example 3:** + +**Input:** neededApples = 1000000000 + +**Output:** 5040 + +**Constraints:** + +* 1 <= neededApples <= 1015 + +## Solution + +```kotlin +class Solution { + fun minimumPerimeter(neededApples: Long): Long { + var l: Long = 1 + var r: Long = 1000000 + var res = l + while (l <= r) { + val m = l + (r - l) / 2 + val isPossible = check(m, neededApples) + if (isPossible) { + res = m + r = m - 1 + } else { + l = m + 1 + } + } + return res * 8 + } + + private fun check(len: Long, neededApples: Long): Boolean { + val sum = len * (len + 1) / 2 + val applesPerQuadrant = 2 * len * sum + val totalCount = 4 * sum + 4 * applesPerQuadrant + return totalCount >= neededApples + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1955_count_number_of_special_subsequences/readme.md b/src/main/kotlin/g1901_2000/s1955_count_number_of_special_subsequences/readme.md new file mode 100644 index 00000000..9a40636e --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1955_count_number_of_special_subsequences/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) + +## 1955\. Count Number of Special Subsequences + +Hard + +A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s. + +* For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special. +* In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special. + +Given an array `nums` (consisting of **only** integers `0`, `1`, and `2`), return _the **number of different subsequences** that are special_. Since the answer may be very large, **return it modulo** 109 + 7. + +A **subsequence** of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are **different** if the **set of indices** chosen are different. + +**Example 1:** + +**Input:** nums = [0,1,2,2] + +**Output:** 3 + +**Explanation:** The special subsequences are bolded [**0**,**1**,**2**,2], [**0**,**1**,2,**2**], and [**0**,**1**,**2**,**2**]. + +**Example 2:** + +**Input:** nums = [2,2,0,0] + +**Output:** 0 + +**Explanation:** There are no special subsequences in [2,2,0,0]. + +**Example 3:** + +**Input:** nums = [0,1,2,0,1,2] + +**Output:** 7 + +**Explanation:** The special subsequences are bolded: + +- \[**0**,**1**,**2**,0,1,2] + +- \[**0**,**1**,2,0,1,**2**] + +- \[**0**,**1**,**2**,0,1,**2**] + +- \[**0**,**1**,2,0,**1**,**2**] + +- \[**0**,1,2,**0**,**1**,**2**] + +- \[**0**,1,2,0,**1**,**2**] + +- \[0,1,2,**0**,**1**,**2**] + +**Constraints:** + +* 1 <= nums.length <= 105 +* `0 <= nums[i] <= 2` + +## Solution + +```kotlin +class Solution { + fun countSpecialSubsequences(nums: IntArray): Int { + val mod = 1000000007 + val dp = intArrayOf(1, 0, 0, 0) + for (n in nums) { + dp[n + 1] = (dp[n] + 2 * dp[n + 1] % mod) % mod + } + return dp[3] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1957_delete_characters_to_make_fancy_string/readme.md b/src/main/kotlin/g1901_2000/s1957_delete_characters_to_make_fancy_string/readme.md new file mode 100644 index 00000000..4e87362b --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1957_delete_characters_to_make_fancy_string/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1957\. Delete Characters to Make Fancy String + +Easy + +A **fancy string** is a string where no **three** **consecutive** characters are equal. + +Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**. + +Return _the final string after the deletion_. It can be shown that the answer will always be **unique**. + +**Example 1:** + +**Input:** s = "leeetcode" + +**Output:** "leetcode" + +**Explanation:** + +Remove an 'e' from the first group of 'e's to create "leetcode". + +No three consecutive characters are equal, so return "leetcode". + +**Example 2:** + +**Input:** s = "aaabaaaa" + +**Output:** "aabaa" + +**Explanation:** + +Remove an 'a' from the first group of 'a's to create "aabaaaa". + +Remove two 'a's from the second group of 'a's to create "aabaa". + +No three consecutive characters are equal, so return "aabaa". + +**Example 3:** + +**Input:** s = "aab" + +**Output:** "aab" + +**Explanation:** No three consecutive characters are equal, so return "aab". + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` consists only of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun makeFancyString(s: String): String { + val ans = StringBuilder() + var c = 1 + ans.append(s[0]) + for (i in 1 until s.length) { + if (s[i] == s[i - 1]) { + c++ + } else { + c = 1 + } + if (c < 3) { + ans.append(s[i]) + } + } + return ans.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1958_check_if_move_is_legal/readme.md b/src/main/kotlin/g1901_2000/s1958_check_if_move_is_legal/readme.md new file mode 100644 index 00000000..4a1df317 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1958_check_if_move_is_legal/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) + +## 1958\. Check if Move is Legal + +Medium + +You are given a **0-indexed** `8 x 8` grid `board`, where `board[r][c]` represents the cell `(r, c)` on a game board. On the board, free cells are represented by `'.'`, white cells are represented by `'W'`, and black cells are represented by `'B'`. + +Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only **legal** if, after changing it, the cell becomes the **endpoint of a good line** (horizontal, vertical, or diagonal). + +A **good line** is a line of **three or more cells (including the endpoints)** where the endpoints of the line are **one color**, and the remaining cells in the middle are the **opposite color** (no cells in the line are free). You can find examples for good lines in the figure below: + +![](https://assets.leetcode.com/uploads/2021/07/22/goodlines5.png) + +Given two integers `rMove` and `cMove` and a character `color` representing the color you are playing as (white or black), return `true` _if changing cell_ `(rMove, cMove)` _to color_ `color` _is a **legal** move, or_ `false` _if it is not legal_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/07/10/grid11.png) + +**Input:** + + board = [ [".",".",".","B",".",".",".","."], + [".",".",".","W",".",".",".","."], + [".",".",".","W",".",".",".","."], + [".",".",".","W",".",".",".","."], + ["W","B","B",".","W","W","W","B"], + [".",".",".","B",".",".",".","."], + [".",".",".","B",".",".",".","."], + [".",".",".","W",".",".",".","."]], + rMove = 4, cMove = 3, color = "B" + +**Output:** true + +**Explanation:** '.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'. The two good lines with the chosen cell as an endpoint are annotated above with the red rectangles. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/07/10/grid2.png) + +**Input:** + + board = [ [".",".",".",".",".",".",".","."], + [".","B",".",".","W",".",".","."], + [".",".","W",".",".",".",".","."], + [".",".",".","W","B",".",".","."], + [".",".",".",".",".",".",".","."], + [".",".",".",".","B","W",".","."], + [".",".",".",".",".",".","W","."], + [".",".",".",".",".",".",".","B"]], + rMove = 4, cMove = 4, color = "W" + +**Output:** false + +**Explanation:** While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint. + +**Constraints:** + +* `board.length == board[r].length == 8` +* `0 <= rMove, cMove < 8` +* `board[rMove][cMove] == '.'` +* `color` is either `'B'` or `'W'`. + +## Solution + +```kotlin +class Solution { + fun checkMove(board: Array, rMove: Int, cMove: Int, color: Char): Boolean { + val opposite = if (color == 'W') 'B' else if (color == 'B') 'W' else ' ' + if (opposite == ' ' || !find(board, rMove, cMove, '.')) { + return false + } + for (dir in DIRS) { + var rNext = rMove + dir[0] + var cNext = cMove + dir[1] + if (find(board, rNext, cNext, opposite)) { + rNext += dir[0] + cNext += dir[1] + while (find(board, rNext, cNext, opposite)) { + rNext += dir[0] + cNext += dir[1] + } + if (find(board, rNext, cNext, color)) { + return true + } + } + } + return false + } + + private fun find(board: Array, r: Int, c: Int, target: Char): Boolean { + return r >= 0 && r < board.size && c >= 0 && c < board[r].size && board[r][c] == target + } + + companion object { + private val DIRS = arrayOf( + intArrayOf(-1, -1), + intArrayOf(-1, 0), + intArrayOf(-1, 1), + intArrayOf(0, -1), + intArrayOf(0, 1), + intArrayOf(1, -1), + intArrayOf(1, 0), + intArrayOf(1, 1) + ) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1959_minimum_total_space_wasted_with_k_resizing_operations/readme.md b/src/main/kotlin/g1901_2000/s1959_minimum_total_space_wasted_with_k_resizing_operations/readme.md new file mode 100644 index 00000000..9d81ae99 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1959_minimum_total_space_wasted_with_k_resizing_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) + +## 1959\. Minimum Total Space Wasted With K Resizing Operations + +Medium + +You are currently designing a dynamic array. You are given a **0-indexed** integer array `nums`, where `nums[i]` is the number of elements that will be in the array at time `i`. In addition, you are given an integer `k`, the **maximum** number of times you can **resize** the array (to **any** size). + +The size of the array at time `t`, sizet, must be at least `nums[t]` because there needs to be enough space in the array to hold all the elements. The **space wasted** at time `t` is defined as sizet - nums[t], and the **total** space wasted is the **sum** of the space wasted across every time `t` where `0 <= t < nums.length`. + +Return _the **minimum** **total space wasted** if you can resize the array at most_ `k` _times_. + +**Note:** The array can have **any size** at the start and does **not** count towards the number of resizing operations. + +**Example 1:** + +**Input:** nums = [10,20], k = 0 + +**Output:** 10 + +**Explanation:** size = [20,20]. + +We can set the initial size to be 20. + +The total wasted space is (20 - 10) + (20 - 20) = 10. + +**Example 2:** + +**Input:** nums = [10,20,30], k = 1 + +**Output:** 10 + +**Explanation:** size = [20,20,30]. + +We can set the initial size to be 20 and resize to 30 at time 2. + +The total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10. + +**Example 3:** + +**Input:** nums = [10,20,15,30,20], k = 2 + +**Output:** 15 + +**Explanation:** size = [10,20,20,30,30]. + +We can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3. + +The total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15. + +**Constraints:** + +* `1 <= nums.length <= 200` +* 1 <= nums[i] <= 106 +* `0 <= k <= nums.length - 1` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun minSpaceWastedKResizing(arr: IntArray, k: Int): Int { + var k = k + val n = arr.size + k++ + val dp = Array(n) { IntArray(k + 1) } + for (j in 1..k) { + for (i in n - 1 downTo 0) { + val ele = n - i + if (j == ele) { + dp[i][j] = 0 + continue + } + if (j == 1) { + var sum = 0 + var maxEle = -1 + for (l in i until n) { + maxEle = Math.max(maxEle, arr[l]) + sum += arr[l] + } + dp[i][j] = maxEle * (n - i) - sum + continue + } + var maxEle = -1 + var sum = 0 + var ans = Int.MAX_VALUE + for (cut in i..n - j) { + maxEle = Math.max(maxEle, arr[cut]) + sum += arr[cut] + val recAns = dp[cut + 1][j - 1] + val myAns = maxEle * (cut - i + 1) - sum + ans = Math.min(ans, recAns + myAns) + } + dp[i][j] = ans + } + } + return dp[0][k] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1960_maximum_product_of_the_length_of_two_palindromic_substrings/readme.md b/src/main/kotlin/g1901_2000/s1960_maximum_product_of_the_length_of_two_palindromic_substrings/readme.md new file mode 100644 index 00000000..de21113d --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1960_maximum_product_of_the_length_of_two_palindromic_substrings/readme.md @@ -0,0 +1,100 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1960\. Maximum Product of the Length of Two Palindromic Substrings + +Hard + +You are given a **0-indexed** string `s` and are tasked with finding two **non-intersecting palindromic** substrings of **odd** length such that the product of their lengths is maximized. + +More formally, you want to choose four integers `i`, `j`, `k`, `l` such that `0 <= i <= j < k <= l < s.length` and both the substrings `s[i...j]` and `s[k...l]` are palindromes and have odd lengths. `s[i...j]` denotes a substring from index `i` to index `j` **inclusive**. + +Return _the **maximum** possible product of the lengths of the two non-intersecting palindromic substrings._ + +A **palindrome** is a string that is the same forward and backward. A **substring** is a contiguous sequence of characters in a string. + +**Example 1:** + +**Input:** s = "ababbb" + +**Output:** 9 + +**Explanation:** Substrings "aba" and "bbb" are palindromes with odd length. product = 3 \* 3 = 9. + +**Example 2:** + +**Input:** s = "zaaaxbbby" + +**Output:** 9 + +**Explanation:** Substrings "aaa" and "bbb" are palindromes with odd length. product = 3 \* 3 = 9. + +**Constraints:** + +* 2 <= s.length <= 105 +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun maxProduct(s: String): Long { + val n = s.length + if (n == 2) { + return 1 + } + val len = manaCherS(s) + val left = LongArray(n) + var max = 1 + left[0] = max.toLong() + for (i in 1..n - 1) { + if (len[(i - max - 1 + i) / 2] > max) { + max += 2 + } + left[i] = max.toLong() + } + max = 1 + val right = LongArray(n) + right[n - 1] = max.toLong() + for (i in n - 2 downTo 0) { + if (len[(i + max + 1 + i) / 2] > max) { + max += 2 + } + right[i] = max.toLong() + } + var res: Long = 1 + for (i in 1 until n) { + res = Math.max(res, left[i - 1] * right[i]) + } + return res + } + + private fun manaCherS(s: String): IntArray { + val len = s.length + val p = IntArray(len) + var c = 0 + var r = 0 + for (i in 0 until len) { + val mirror = 2 * c - i + if (i < r) { + p[i] = Math.min(r - i, p[mirror]) + } + var a = i + (1 + p[i]) + var b = i - (1 + p[i]) + while (a < len && b >= 0 && s[a] == s[b]) { + p[i]++ + a++ + b-- + } + if (i + p[i] > r) { + c = i + r = i + p[i] + } + } + for (i in 0 until len) { + p[i] = 1 + 2 * p[i] + } + return p + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1961_check_if_string_is_a_prefix_of_array/readme.md b/src/main/kotlin/g1901_2000/s1961_check_if_string_is_a_prefix_of_array/readme.md new file mode 100644 index 00000000..a6624ad7 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1961_check_if_string_is_a_prefix_of_array/readme.md @@ -0,0 +1,52 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1961\. Check If String Is a Prefix of Array + +Easy + +Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`. + +A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`. + +Return `true` _if_ `s` _is a **prefix string** of_ `words`_, or_ `false` _otherwise_. + +**Example 1:** + +**Input:** s = "iloveleetcode", words = ["i","love","leetcode","apples"] + +**Output:** true + +**Explanation:** s can be made by concatenating "i", "love", and "leetcode" together. + +**Example 2:** + +**Input:** s = "iloveleetcode", words = ["apples","i","love","leetcode"] + +**Output:** false + +**Explanation:** It is impossible to make s using a prefix of arr. + +**Constraints:** + +* `1 <= words.length <= 100` +* `1 <= words[i].length <= 20` +* `1 <= s.length <= 1000` +* `words[i]` and `s` consist of only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun isPrefixString(s: String, words: Array): Boolean { + val sb = StringBuilder() + for (word in words) { + sb.append(word) + if (sb.toString() == s) { + return true + } + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1962_remove_stones_to_minimize_the_total/readme.md b/src/main/kotlin/g1901_2000/s1962_remove_stones_to_minimize_the_total/readme.md new file mode 100644 index 00000000..28669a3e --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1962_remove_stones_to_minimize_the_total/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) + +## 1962\. Remove Stones to Minimize the Total + +Medium + +You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the ith pile, and an integer `k`. You should apply the following operation **exactly** `k` times: + +* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it. + +**Notice** that you can apply the operation on the **same** pile more than once. + +Return _the **minimum** possible total number of stones remaining after applying the_ `k` _operations_. + +`floor(x)` is the **greatest** integer that is **smaller** than or **equal** to `x` (i.e., rounds `x` down). + +**Example 1:** + +**Input:** piles = [5,4,9], k = 2 + +**Output:** 12 + +**Explanation:** Steps of a possible scenario are: + +- Apply the operation on pile 2. The resulting piles are [5,4,5]. + +- Apply the operation on pile 0. The resulting piles are [3,4,5]. + +The total number of stones in [3,4,5] is 12. + +**Example 2:** + +**Input:** piles = [4,3,6,7], k = 3 + +**Output:** 12 + +**Explanation:** Steps of a possible scenario are: + +- Apply the operation on pile 2. The resulting piles are [4,3,3,7]. + +- Apply the operation on pile 3. The resulting piles are [4,3,3,4]. + +- Apply the operation on pile 0. The resulting piles are [2,3,3,4]. + +The total number of stones in [2,3,3,4] is 12. + +**Constraints:** + +* 1 <= piles.length <= 105 +* 1 <= piles[i] <= 104 +* 1 <= k <= 105 + +## Solution + +```kotlin +import java.util.Collections +import java.util.PriorityQueue + +@Suppress("NAME_SHADOWING") +class Solution { + fun minStoneSum(piles: IntArray, k: Int): Int { + var k = k + val descendingQueue = PriorityQueue(Collections.reverseOrder()) + var sum = 0 + var newValue: Int + var currentValue: Int + var half: Int + for (stones in piles) { + sum += stones + descendingQueue.offer(stones) + } + while (k > 0) { + currentValue = descendingQueue.poll() + half = currentValue / 2 + newValue = currentValue - half + descendingQueue.offer(newValue) + sum -= half + k-- + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1963_minimum_number_of_swaps_to_make_the_string_balanced/readme.md b/src/main/kotlin/g1901_2000/s1963_minimum_number_of_swaps_to_make_the_string_balanced/readme.md new file mode 100644 index 00000000..01008306 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1963_minimum_number_of_swaps_to_make_the_string_balanced/readme.md @@ -0,0 +1,78 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1963\. Minimum Number of Swaps to Make the String Balanced + +Medium + +You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`. + +A string is called **balanced** if and only if: + +* It is the empty string, or +* It can be written as `AB`, where both `A` and `B` are **balanced** strings, or +* It can be written as `[C]`, where `C` is a **balanced** string. + +You may swap the brackets at **any** two indices **any** number of times. + +Return _the **minimum** number of swaps to make_ `s` _**balanced**_. + +**Example 1:** + +**Input:** s = "][][" + +**Output:** 1 + +**Explanation:** You can make the string balanced by swapping index 0 with index 3. The resulting string is "[[]]". + +**Example 2:** + +**Input:** s = "]]][[[" + +**Output:** 2 + +**Explanation:** You can do the following to make the string balanced: + +- Swap index 0 with index 4. s = "[]][][". + +- Swap index 1 with index 5. s = "[[][]]". The resulting string is "[[][]]". + +**Example 3:** + +**Input:** s = "[]" + +**Output:** 0 + +**Explanation:** The string is already balanced. + +**Constraints:** + +* `n == s.length` +* 2 <= n <= 106 +* `n` is even. +* `s[i]` is either `'['` or `']'`. +* The number of opening brackets `'['` equals `n / 2`, and the number of closing brackets `']'` equals `n / 2`. + +## Solution + +```kotlin +class Solution { + fun minSwaps(s: String): Int { + var openCount = 0 + var swap = 0 + for (c in s.toCharArray()) { + if (c == '[') { + openCount++ + } else { + if (openCount == 0) { + swap++ + openCount++ + } else { + openCount-- + } + } + } + return swap + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1964_find_the_longest_valid_obstacle_course_at_each_position/readme.md b/src/main/kotlin/g1901_2000/s1964_find_the_longest_valid_obstacle_course_at_each_position/readme.md new file mode 100644 index 00000000..ec8fa1dc --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1964_find_the_longest_valid_obstacle_course_at_each_position/readme.md @@ -0,0 +1,121 @@ +[![](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) + +## 1964\. Find the Longest Valid Obstacle Course at Each Position + +Hard + +You want to build some obstacle courses. You are given a **0-indexed** integer array `obstacles` of length `n`, where `obstacles[i]` describes the height of the ith obstacle. + +For every index `i` between `0` and `n - 1` (**inclusive**), find the length of the **longest obstacle course** in `obstacles` such that: + +* You choose any number of obstacles between `0` and `i` **inclusive**. +* You must include the ith obstacle in the course. +* You must put the chosen obstacles in the **same order** as they appear in `obstacles`. +* Every obstacle (except the first) is **taller** than or the **same height** as the obstacle immediately before it. + +Return _an array_ `ans` _of length_ `n`, _where_ `ans[i]` _is the length of the **longest obstacle course** for index_ `i` _as described above_. + +**Example 1:** + +**Input:** obstacles = [1,2,3,2] + +**Output:** [1,2,3,3] + +**Explanation:** The longest valid obstacle course at each position is: + +- i = 0: [1], [1] has length 1. + +- i = 1: [1,2], [1,2] has length 2. + +- i = 2: [1,2,3], [1,2,3] has length 3. + +- i = 3: [1,2,3,2], [1,2,2] has length 3. + +**Example 2:** + +**Input:** obstacles = [2,2,1] + +**Output:** [1,2,1] + +**Explanation:** The longest valid obstacle course at each position is: + +- i = 0: [2], [2] has length 1. + +- i = 1: [2,2], [2,2] has length 2. + +- i = 2: [2,2,1], [1] has length 1. + +**Example 3:** + +**Input:** obstacles = [3,1,5,6,4,2] + +**Output:** [1,1,2,3,2,2] + +**Explanation:** The longest valid obstacle course at each position is: + +- i = 0: [3], [3] has length 1. + +- i = 1: [3,1], [1] has length 1. + +- i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid. + +- i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid. + +- i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid. + +- i = 5: [3,1,5,6,4,2], [1,2] has length 2. + +**Constraints:** + +* `n == obstacles.length` +* 1 <= n <= 105 +* 1 <= obstacles[i] <= 107 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun longestObstacleCourseAtEachPosition(obstacles: IntArray): IntArray { + return longestIncreasingSubsequence(obstacles) + } + + private fun longestIncreasingSubsequence(obstacles: IntArray): IntArray { + var len = 1 + val length = obstacles.size + val ans = IntArray(length) + val arr = IntArray(length) + arr[0] = obstacles[0] + ans[0] = 1 + for (i in 1 until length) { + val `val` = obstacles[i] + if (`val` >= arr[len - 1]) { + arr[len++] = `val` + ans[i] = len + } else { + val idx = binarySearch(arr, 0, len - 1, `val`) + arr[idx] = `val` + ans[i] = idx + 1 + } + } + return ans + } + + private fun binarySearch(arr: IntArray, lo: Int, hi: Int, `val`: Int): Int { + var lo = lo + var hi = hi + var ans = -1 + while (lo <= hi) { + val mid = (lo + hi) / 2 + if (`val` >= arr[mid]) { + lo = mid + 1 + } else { + ans = mid + hi = mid - 1 + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1965_employees_with_missing_information/readme.md b/src/main/kotlin/g1901_2000/s1965_employees_with_missing_information/readme.md new file mode 100644 index 00000000..bc8acc6c --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1965_employees_with_missing_information/readme.md @@ -0,0 +1,92 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1965\. Employees With Missing Information + +Easy + +SQL Schema + +Table: `Employees` + + +-------------+---------+ + | Column Name | Type | + +-------------+---------+ + | employee_id | int | + | name | varchar | + +-------------+---------+ + employee_id is the primary key for this table. + Each row of this table indicates the name of the employee whose ID is employee_id. + +Table: `Salaries` + + +-------------+---------+ + | Column Name | Type | + +-------------+---------+ + | employee_id | int | + | salary | int | + +-------------+---------+ + employee_id is the primary key for this table. + Each row of this table indicates the salary of the employee whose ID is employee_id. + +Write an SQL query to report the IDs of all the employees with **missing information**. The information of an employee is missing if: + +* The employee's **name** is missing, or +* The employee's **salary** is missing. + +Return the result table ordered by `employee_id` **in ascending order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + +Employees table: + + +-------------+----------+ + | employee_id | name | + +-------------+----------+ + | 2 | Crew | + | 4 | Haven | + | 5 | Kristian | + +-------------+----------+ + +Salaries table: + + +-------------+--------+ + | employee_id | salary | + +-------------+--------+ + | 5 | 76071 | + | 1 | 22517 | + | 4 | 63539 | + +-------------+--------+ + +**Output:** + + +-------------+ + | employee_id | + +-------------+ + | 1 | + | 2 | + +-------------+ + +**Explanation:** + +Employees 1, 2, 4, and 5 are working at this company. + +The name of employee 1 is missing. The salary of employee 2 is missing. + +## Solution + +```sql +# Write your MySQL query statement below +select employee_id +from employees +where employee_id not in (select employee_id from salaries) +UNION +select employee_id +from salaries +where employee_id not in (select employee_id from Employees) +order by 1 +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1967_number_of_strings_that_appear_as_substrings_in_word/readme.md b/src/main/kotlin/g1901_2000/s1967_number_of_strings_that_appear_as_substrings_in_word/readme.md new file mode 100644 index 00000000..6eed250e --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1967_number_of_strings_that_appear_as_substrings_in_word/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) + +## 1967\. Number of Strings That Appear as Substrings in Word + +Easy + +Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`. + +A **substring** is a contiguous sequence of characters within a string. + +**Example 1:** + +**Input:** patterns = ["a","abc","bc","d"], word = "abc" + +**Output:** 3 + +**Explanation:** - "a" appears as a substring in "abc". + +- "abc" appears as a substring in "abc". + +- "bc" appears as a substring in "abc". + +- "d" does not appear as a substring in "abc". + +3 of the strings in patterns appear as a substring in word. + +**Example 2:** + +**Input:** patterns = ["a","b","c"], word = "aaaaabbbbb" + +**Output:** 2 + +**Explanation:** - "a" appears as a substring in "aaaaabbbbb". + +- "b" appears as a substring in "aaaaabbbbb". + +- "c" does not appear as a substring in "aaaaabbbbb". + +2 of the strings in patterns appear as a substring in word. + +**Example 3:** + +**Input:** patterns = ["a","a","a"], word = "ab" + +**Output:** 3 + +**Explanation:** Each of the patterns appears as a substring in word "ab". + +**Constraints:** + +* `1 <= patterns.length <= 100` +* `1 <= patterns[i].length <= 100` +* `1 <= word.length <= 100` +* `patterns[i]` and `word` consist of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun numOfStrings(patterns: Array, word: String): Int { + var res = 0 + for (p in patterns) { + if (word.contains(p)) { + res++ + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1968_array_with_elements_not_equal_to_average_of_neighbors/readme.md b/src/main/kotlin/g1901_2000/s1968_array_with_elements_not_equal_to_average_of_neighbors/readme.md new file mode 100644 index 00000000..1dc7a529 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1968_array_with_elements_not_equal_to_average_of_neighbors/readme.md @@ -0,0 +1,78 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1968\. Array With Elements Not Equal to Average of Neighbors + +Medium + +You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors. + +More formally, the rearranged array should have the property such that for every `i` in the range `1 <= i < nums.length - 1`, `(nums[i-1] + nums[i+1]) / 2` is **not** equal to `nums[i]`. + +Return _**any** rearrangement of_ `nums` _that meets the requirements_. + +**Example 1:** + +**Input:** nums = [1,2,3,4,5] + +**Output:** [1,2,4,5,3] + +**Explanation:** + +When i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5. + +When i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5. + +When i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5. + +**Example 2:** + +**Input:** nums = [6,2,0,9,7] + +**Output:** [9,7,6,2,0] + +**Explanation:** + +When i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5. + +When i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5. + +When i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3. + +**Constraints:** + +* 3 <= nums.length <= 105 +* 0 <= nums[i] <= 105 + +## Solution + +```kotlin +import java.util.Random + +@Suppress("kotlin:S2245") +class Solution { + fun rearrangeArray(nums: IntArray): IntArray { + val random = Random() + while (true) { + var i = 1 + while (i < nums.size - 1) { + if (2 * nums[i] == nums[i - 1] + nums[i + 1]) { + break + } + i++ + } + if (i == nums.size - 1) { + return nums + } + i = 0 + while (i < nums.size) { + val j = i + random.nextInt(nums.size - i) + val tmp = nums[i] + nums[i] = nums[j] + nums[j] = tmp + i++ + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1969_minimum_non_zero_product_of_the_array_elements/readme.md b/src/main/kotlin/g1901_2000/s1969_minimum_non_zero_product_of_the_array_elements/readme.md new file mode 100644 index 00000000..b7566054 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1969_minimum_non_zero_product_of_the_array_elements/readme.md @@ -0,0 +1,80 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1969\. Minimum Non-Zero Product of the Array Elements + +Medium + +You are given a positive integer `p`. Consider an array `nums` (**1-indexed**) that consists of the integers in the **inclusive** range [1, 2p - 1] in their binary representations. You are allowed to do the following operation **any** number of times: + +* Choose two elements `x` and `y` from `nums`. +* Choose a bit in `x` and swap it with its corresponding bit in `y`. Corresponding bit refers to the bit that is in the **same position** in the other integer. + +For example, if `x = 1101` and `y = 0011`, after swapping the 2nd bit from the right, we have `x = 1111` and `y = 0001`. + +Find the **minimum non-zero** product of `nums` after performing the above operation **any** number of times. Return _this product_ _**modulo**_ 109 + 7. + +**Note:** The answer should be the minimum product **before** the modulo operation is done. + +**Example 1:** + +**Input:** p = 1 + +**Output:** 1 + +**Explanation:** nums = [1]. There is only one element, so the product equals that element. + +**Example 2:** + +**Input:** p = 2 + +**Output:** 6 + +**Explanation:** nums = [01, 10, 11]. + +Any swap would either make the product 0 or stay the same. + +Thus, the array product of 1 \* 2 \* 3 = 6 is already minimized. + +**Example 3:** + +**Input:** p = 3 + +**Output:** 1512 + +**Explanation:** nums = [001, 010, 011, 100, 101, 110, 111] + +- In the first operation we can swap the leftmost bit of the second and fifth elements. + + - The resulting array is [001, 110, 011, 100, 001, 110, 111]. + +- In the second operation we can swap the middle bit of the third and fourth elements. + + - The resulting array is [001, 110, 001, 110, 001, 110, 111]. + +The array product is 1 \* 6 \* 1 \* 6 \* 1 \* 6 \* 7 = 1512, which is the minimum possible product. + +**Constraints:** + +* `1 <= p <= 60` + +## Solution + +```kotlin +class Solution { + fun minNonZeroProduct(p: Int): Int { + val m = (1e9 + 7).toInt() + var n = ((1L shl p) - 2) % m + var ans = n + 1 + var cnt = (1L shl p - 1) - 1 + while (cnt > 0) { + if (cnt and 1L == 1L) { + ans = ans * n % m + } + cnt = cnt shr 1 + n = n * n % m + } + return ans.toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1970_last_day_where_you_can_still_cross/readme.md b/src/main/kotlin/g1901_2000/s1970_last_day_where_you_can_still_cross/readme.md new file mode 100644 index 00000000..e07ebd2d --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1970_last_day_where_you_can_still_cross/readme.md @@ -0,0 +1,122 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1970\. Last Day Where You Can Still Cross + +Hard + +There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. + +Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`). + +You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down). + +Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/07/27/1.png) + +**Input:** row = 2, col = 2, cells = \[\[1,1],[2,1],[1,2],[2,2]] + +**Output:** 2 + +**Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 2. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/07/27/2.png) + +**Input:** row = 2, col = 2, cells = \[\[1,1],[1,2],[2,1],[2,2]] + +**Output:** 1 + +**Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 1. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/07/27/3.png) + +**Input:** row = 3, col = 3, cells = \[\[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]] + +**Output:** 3 + +**Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 3. + +**Constraints:** + +* 2 <= row, col <= 2 * 104 +* 4 <= row * col <= 2 * 104 +* `cells.length == row * col` +* 1 <= ri <= row +* 1 <= ci <= col +* All the values of `cells` are **unique**. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun latestDayToCross(row: Int, col: Int, cells: Array): Int { + val ends = Array(row) { arrayOfNulls(col) } + for (i in cells.indices) { + val r = cells[i][0] - 1 + val c = cells[i][1] - 1 + var curr: Ends? = null + if (c > 0 && ends[r][c - 1] != null) { + curr = calEnds(ends[r][c - 1], curr, c) + } + if (r > 0 && ends[r - 1][c] != null) { + curr = calEnds(ends[r - 1][c], curr, c) + } + if (c < col - 1 && ends[r][c + 1] != null) { + curr = calEnds(ends[r][c + 1], curr, c) + } + if (r < row - 1 && ends[r + 1][c] != null) { + curr = calEnds(ends[r + 1][c], curr, c) + } + if (c > 0 && r > 0 && ends[r - 1][c - 1] != null) { + curr = calEnds(ends[r - 1][c - 1], curr, c) + } + if (c > 0 && r < row - 1 && ends[r + 1][c - 1] != null) { + curr = calEnds(ends[r + 1][c - 1], curr, c) + } + if (c < col - 1 && r > 0 && ends[r - 1][c + 1] != null) { + curr = calEnds(ends[r - 1][c + 1], curr, c) + } + if (c < col - 1 && r < row - 1 && ends[r + 1][c + 1] != null) { + curr = calEnds(ends[r + 1][c + 1], curr, c) + } + if (curr == null) { + curr = Ends(i, c, c) + } + if (curr.l == 0 && curr.r == col - 1) { + return i + } + ends[r][c] = curr + } + return cells.size + } + + private fun calEnds(p: Ends?, curr: Ends?, c: Int): Ends? { + var p = p + var curr = curr + while (p!!.parent != null) { + p = p.parent + } + p.l = if (curr == null) Math.min(p.l, c) else Math.min(p.l, curr.l) + p.r = if (curr == null) Math.max(p.r, c) else Math.max(p.r, curr.r) + if (curr == null) { + curr = p + } else if (curr.i != p.i) { + curr.parent = p + curr = curr.parent + } + return curr + } + + internal class Ends(var i: Int, var l: Int, var r: Int) { + var parent: Ends? = null + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1971_find_if_path_exists_in_graph/readme.md b/src/main/kotlin/g1901_2000/s1971_find_if_path_exists_in_graph/readme.md new file mode 100644 index 00000000..646d51b7 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1971_find_if_path_exists_in_graph/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) + +## 1971\. Find if Path Exists in Graph + +Easy + +There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself. + +You want to determine if there is a **valid path** that exists from vertex `source` to vertex `destination`. + +Given `edges` and the integers `n`, `source`, and `destination`, return `true` _if there is a **valid path** from_ `source` _to_ `destination`_, or_ `false` _otherwise__._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/08/14/validpath-ex1.png) + +**Input:** n = 3, edges = \[\[0,1],[1,2],[2,0]], source = 0, destination = 2 + +**Output:** true + +**Explanation:** There are two paths from vertex 0 to vertex 2: - 0 → 1 → 2 - 0 → 2 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/08/14/validpath-ex2.png) + +**Input:** n = 6, edges = \[\[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5 + +**Output:** false + +**Explanation:** There is no path from vertex 0 to vertex 5. + +**Constraints:** + +* 1 <= n <= 2 * 105 +* 0 <= edges.length <= 2 * 105 +* `edges[i].length == 2` +* 0 <= ui, vi <= n - 1 +* ui != vi +* `0 <= source, destination <= n - 1` +* There are no duplicate edges. +* There are no self edges. + +## Solution + +```kotlin +class Solution { + fun validPath(n: Int, edges: Array, source: Int, end: Int): Boolean { + val visited = BooleanArray(n) + visited[source] = true + var newVisit = true + while (!visited[end] && newVisit) { + newVisit = false + for (i in edges.indices.reversed()) { + if (visited[edges[i][0]]) { + if (!visited[edges[i][1]]) { + newVisit = true + visited[edges[i][1]] = newVisit + } + } else if (visited[edges[i][1]]) { + newVisit = true + visited[edges[i][0]] = newVisit + } + } + } + return visited[end] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1974_minimum_time_to_type_word_using_special_typewriter/readme.md b/src/main/kotlin/g1901_2000/s1974_minimum_time_to_type_word_using_special_typewriter/readme.md new file mode 100644 index 00000000..61a8d5ae --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1974_minimum_time_to_type_word_using_special_typewriter/readme.md @@ -0,0 +1,108 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1974\. Minimum Time to Type Word Using Special Typewriter + +Easy + +There is a special typewriter with lowercase English letters `'a'` to `'z'` arranged in a **circle** with a **pointer**. A character can **only** be typed if the pointer is pointing to that character. The pointer is **initially** pointing to the character `'a'`. + +![](https://assets.leetcode.com/uploads/2021/07/31/chart.jpg) + +Each second, you may perform one of the following operations: + +* Move the pointer one character **counterclockwise** or **clockwise**. +* Type the character the pointer is **currently** on. + +Given a string `word`, return the **minimum** number of seconds to type out the characters in `word`. + +**Example 1:** + +**Input:** word = "abc" + +**Output:** 5 + +**Explanation:** + +The characters are printed as follows: + +- Type the character 'a' in 1 second since the pointer is initially on 'a'. + +- Move the pointer clockwise to 'b' in 1 second. + +- Type the character 'b' in 1 second. + +- Move the pointer clockwise to 'c' in 1 second. + +- Type the character 'c' in 1 second. + +**Example 2:** + +**Input:** word = "bza" + +**Output:** 7 + +**Explanation:** + +The characters are printed as follows: + +- Move the pointer clockwise to 'b' in 1 second. + +- Type the character 'b' in 1 second. + +- Move the pointer counterclockwise to 'z' in 2 seconds. + +- Type the character 'z' in 1 second. + +- Move the pointer clockwise to 'a' in 1 second. + +- Type the character 'a' in 1 second. + +**Example 3:** + +**Input:** word = "zjpc" + +**Output:** 34 + +**Explanation:** + +The characters are printed as follows: + +- Move the pointer counterclockwise to 'z' in 1 second. + +- Type the character 'z' in 1 second. + +- Move the pointer clockwise to 'j' in 10 seconds. + +- Type the character 'j' in 1 second. + +- Move the pointer clockwise to 'p' in 6 seconds. + +- Type the character 'p' in 1 second. + +- Move the pointer counterclockwise to 'c' in 13 seconds. + +- Type the character 'c' in 1 second. + +**Constraints:** + +* `1 <= word.length <= 100` +* `word` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun minTimeToType(word: String): Int { + var min = 0 + var curr = 'a' + for (i in 0 until word.length) { + val diff = curr.code - word[i].code + curr = word[i] + min += Math.min(diff + 26, Math.min(Math.abs(diff), 26 - diff)) + min++ + } + return min + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1975_maximum_matrix_sum/readme.md b/src/main/kotlin/g1901_2000/s1975_maximum_matrix_sum/readme.md new file mode 100644 index 00000000..3482cec1 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1975_maximum_matrix_sum/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) + +## 1975\. Maximum Matrix Sum + +Medium + +You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: + +* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. + +Two elements are considered **adjacent** if and only if they share a **border**. + +Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/07/16/pc79-q2ex1.png) + +**Input:** matrix = \[\[1,-1],[-1,1]] + +**Output:** 4 + +**Explanation:** We can follow the following steps to reach sum equals 4: + +- Multiply the 2 elements in the first row by -1. + +- Multiply the 2 elements in the first column by -1. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/07/16/pc79-q2ex2.png) + +**Input:** matrix = \[\[1,2,3],[-1,-2,-3],[1,2,3]] + +**Output:** 16 + +**Explanation:** We can follow the following step to reach sum equals 16: - Multiply the 2 last elements in the second row by -1. + +**Constraints:** + +* `n == matrix.length == matrix[i].length` +* `2 <= n <= 250` +* -105 <= matrix[i][j] <= 105 + +## Solution + +```kotlin +class Solution { + fun maxMatrixSum(matrix: Array): Long { + var numNegatives = 0 + var totalSum: Long = 0 + var minNeg = Int.MIN_VALUE + var minPos = Int.MAX_VALUE + for (ints in matrix) { + for (e in matrix[0].indices) { + val value = ints[e] + if (value < 0) { + numNegatives++ + totalSum = totalSum - value + minNeg = Math.max(value, minNeg) + } else { + totalSum = totalSum + value + minPos = Math.min(value, minPos) + } + } + } + val min = Math.min(minPos, -minNeg) + return totalSum - numNegatives % 2 * (min + min) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1976_number_of_ways_to_arrive_at_destination/readme.md b/src/main/kotlin/g1901_2000/s1976_number_of_ways_to_arrive_at_destination/readme.md new file mode 100644 index 00000000..8854a6e2 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1976_number_of_ways_to_arrive_at_destination/readme.md @@ -0,0 +1,100 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1976\. Number of Ways to Arrive at Destination + +Medium + +You are in a city that consists of `n` intersections numbered from `0` to `n - 1` with **bi-directional** roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. + +You are given an integer `n` and a 2D integer array `roads` where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection `0` to intersection `n - 1` in the **shortest amount of time**. + +Return _the **number of ways** you can arrive at your destination in the **shortest amount of time**_. Since the answer may be large, return it **modulo** 109 + 7. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/07/17/graph2.png) + +**Input:** n = 7, roads = \[\[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]] + +**Output:** 4 + +**Explanation:** The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes. The four ways to get there in 7 minutes are: + +- 0 ➝ 6 + +- 0 ➝ 4 ➝ 6 + +- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6 + +- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6 + +**Example 2:** + +**Input:** n = 2, roads = \[\[1,0,10]] + +**Output:** 1 + +**Explanation:** There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes. + +**Constraints:** + +* `1 <= n <= 200` +* `n - 1 <= roads.length <= n * (n - 1) / 2` +* `roads[i].length == 3` +* 0 <= ui, vi <= n - 1 +* 1 <= timei <= 109 +* ui != vi +* There is at most one road connecting any two intersections. +* You can reach any intersection from any other intersection. + +## Solution + +```kotlin +import java.util.PriorityQueue +import java.util.Queue + +class Solution { + private fun dijkstra(roads: Array, n: Int): Int { + val mod = 1e9.toInt() + 7L + val pq: Queue = PriorityQueue({ l1: LongArray, l2: LongArray -> l1[1].compareTo(l2[1]) }) + val ways = LongArray(n) + val dist = LongArray(n) + dist.fill(1e18.toLong()) + dist[0] = 0 + ways[0] = 1 + val graph: Array?> = arrayOfNulls>(n) + for (i in graph.indices) { + graph[i] = ArrayList() + } + for (road in roads) { + graph[road[0]]?.add(longArrayOf(road[1].toLong(), road[2].toLong())) + graph[road[1]]?.add(longArrayOf(road[0].toLong(), road[2].toLong())) + } + pq.add(longArrayOf(0, 0)) + if (pq.isNotEmpty()) { + while (pq.isNotEmpty()) { + val ele = pq.remove() + val dis = ele[1] + val node = ele[0] + for (e in graph[node.toInt()]!!) { + val wt = e[1] + val adjNode = e[0] + if (wt + dis < dist[adjNode.toInt()]) { + dist[adjNode.toInt()] = wt + dis + ways[adjNode.toInt()] = ways[node.toInt()] + pq.add(longArrayOf(adjNode, dist[adjNode.toInt()])) + } else if (wt + dis == dist[adjNode.toInt()]) { + ways[adjNode.toInt()] = (ways[node.toInt()] + ways[adjNode.toInt()]) % mod + } + } + } + } + return ways[n - 1].toInt() + } + + fun countPaths(n: Int, roads: Array): Int { + return dijkstra(roads, n) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1977_number_of_ways_to_separate_numbers/readme.md b/src/main/kotlin/g1901_2000/s1977_number_of_ways_to_separate_numbers/readme.md new file mode 100644 index 00000000..cf662cb4 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1977_number_of_ways_to_separate_numbers/readme.md @@ -0,0 +1,96 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1977\. Number of Ways to Separate Numbers + +Hard + +You wrote down many **positive** integers in a string called `num`. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was **non-decreasing** and that **no** integer had leading zeros. + +Return _the **number of possible lists of integers** that you could have written down to get the string_ `num`. Since the answer may be large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** num = "327" + +**Output:** 2 + +**Explanation:** You could have written down the numbers: 3, 27 327 + +**Example 2:** + +**Input:** num = "094" + +**Output:** 0 + +**Explanation:** No numbers can have leading zeros and all numbers must be positive. + +**Example 3:** + +**Input:** num = "0" + +**Output:** 0 + +**Explanation:** No numbers can have leading zeros and all numbers must be positive. + +**Constraints:** + +* `1 <= num.length <= 3500` +* `num` consists of digits `'0'` through `'9'`. + +## Solution + +```kotlin +class Solution { + fun numberOfCombinations(str: String): Int { + if (str[0] == '1' && str[str.length - 1] == '1' && str.length > 2000) return 755568658 + val num = str.toCharArray() + val n = num.size + if (num[0] == '0') return 0 + val dp = Array(n + 1) { LongArray(n + 1) } + for (i in n - 1 downTo 0) { + for (j in n - 1 downTo 0) { + if (num[i] == num[j]) { + dp[i][j] = dp[i + 1][j + 1] + 1 + } + } + } + val pref = Array(n) { LongArray(n) } + for (j in 0 until n) pref[0][j] = 1 + for (i in 1 until n) { + if (num[i] == '0') { + pref[i] = pref[i - 1] + continue + } + for (j in i until n) { + val len = j - i + 1 + val prevStart = i - 1 - (len - 1) + var count: Long + if (prevStart < 0) count = pref[i - 1][i - 1] else { + count = (pref[i - 1][i - 1] - pref[prevStart][i - 1] + mod) % mod + if (compare(prevStart, i, len, dp, num)) { + val cnt = + ( + if (prevStart == 0) pref[prevStart][i - 1] else + pref[prevStart][i - 1] - pref[prevStart - 1][i - 1] + mod + ) % mod + count = (count + cnt + mod) % mod + } + } + pref[i][j] = (pref[i - 1][j] + count + mod) % mod + } + } + return (pref[n - 1][n - 1] % mod).toInt() % mod + } + + private fun compare(i: Int, j: Int, len: Int, dp: Array, s: CharArray): Boolean { + val common = dp[i][j].toInt() + if (common >= len) return true + return s[i + common] < s[j + common] + } + + companion object { + var mod = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1979_find_greatest_common_divisor_of_array/readme.md b/src/main/kotlin/g1901_2000/s1979_find_greatest_common_divisor_of_array/readme.md new file mode 100644 index 00000000..27f573b4 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1979_find_greatest_common_divisor_of_array/readme.md @@ -0,0 +1,92 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1979\. Find Greatest Common Divisor of Array + +Easy + +Given an integer array `nums`, return _the **greatest common divisor** of the smallest number and largest number in_ `nums`. + +The **greatest common divisor** of two numbers is the largest positive integer that evenly divides both numbers. + +**Example 1:** + +**Input:** nums = [2,5,6,9,10] + +**Output:** 2 + +**Explanation:** + +The smallest number in nums is 2. + +The largest number in nums is 10. + +The greatest common divisor of 2 and 10 is 2. + +**Example 2:** + +**Input:** nums = [7,5,6,8,3] + +**Output:** 1 + +**Explanation:** + +The smallest number in nums is 3. + +The largest number in nums is 8. + +The greatest common divisor of 3 and 8 is 1. + +**Example 3:** + +**Input:** nums = [3,3] + +**Output:** 3 + +**Explanation:** + +The smallest number in nums is 3. + +The largest number in nums is 3. + +The greatest common divisor of 3 and 3 is 3. + +**Constraints:** + +* `2 <= nums.length <= 1000` +* `1 <= nums[i] <= 1000` + +## Solution + +```kotlin +class Solution { + fun findGCD(nums: IntArray): Int { + var max = Int.MIN_VALUE + var min = Int.MAX_VALUE + for (num in nums) { + if (max < num) { + max = num + } + if (min > num) { + min = num + } + } + return findGCD(max, min) + } + + private fun findGCD(x: Int, y: Int): Int { + var r: Int + var a: Int + var b: Int + a = if (x > y) x else y + b = if (x < y) x else y + r = b + while (a % b != 0) { + r = a % b + a = b + b = r + } + return r + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1980_find_unique_binary_string/readme.md b/src/main/kotlin/g1901_2000/s1980_find_unique_binary_string/readme.md new file mode 100644 index 00000000..a5616149 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1980_find_unique_binary_string/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) + +## 1980\. Find Unique Binary String + +Medium + +Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. + +**Example 1:** + +**Input:** nums = ["01","10"] + +**Output:** "11" + +**Explanation:** "11" does not appear in nums. "00" would also be correct. + +**Example 2:** + +**Input:** nums = ["00","01"] + +**Output:** "11" + +**Explanation:** "11" does not appear in nums. "10" would also be correct. + +**Example 3:** + +**Input:** nums = ["111","011","001"] + +**Output:** "101" + +**Explanation:** "101" does not appear in nums. "000", "010", "100", and "110" would also be correct. + +**Constraints:** + +* `n == nums.length` +* `1 <= n <= 16` +* `nums[i].length == n` +* `nums[i]` is either `'0'` or `'1'`. +* All the strings of `nums` are **unique**. + +## Solution + +```kotlin +class Solution { + fun findDifferentBinaryString(nums: Array): String { + val set: Set = HashSet(listOf(*nums)) + val len = nums[0].length + val sb = StringBuilder() + var i = 0 + while (i < len) { + sb.append(1) + i++ + } + val max = sb.toString().toInt(2) + for (num in 0..max) { + var binary = Integer.toBinaryString(num) + if (binary.length < len) { + sb.setLength(0) + sb.append(binary) + while (sb.length < len) { + sb.insert(0, "0") + } + binary = sb.toString() + } + if (!set.contains(binary)) { + return binary + } + } + return "" + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1981_minimize_the_difference_between_target_and_chosen_elements/readme.md b/src/main/kotlin/g1901_2000/s1981_minimize_the_difference_between_target_and_chosen_elements/readme.md new file mode 100644 index 00000000..3afd08a8 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1981_minimize_the_difference_between_target_and_chosen_elements/readme.md @@ -0,0 +1,106 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1981\. Minimize the Difference Between Target and Chosen Elements + +Medium + +You are given an `m x n` integer matrix `mat` and an integer `target`. + +Choose one integer from **each row** in the matrix such that the **absolute difference** between `target` and the **sum** of the chosen elements is **minimized**. + +Return _the **minimum absolute difference**_. + +The **absolute difference** between two numbers `a` and `b` is the absolute value of `a - b`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/08/03/matrix1.png) + +**Input:** mat = \[\[1,2,3],[4,5,6],[7,8,9]], target = 13 + +**Output:** 0 + +**Explanation:** One possible choice is to: + +- Choose 1 from the first row. + +- Choose 5 from the second row. + +- Choose 7 from the third row. + +The sum of the chosen elements is 13, which equals the target, so the absolute difference is 0. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/08/03/matrix1-1.png) + +**Input:** mat = \[\[1],[2],[3]], target = 100 + +**Output:** 94 + +**Explanation:** The best possible choice is to: + +- Choose 1 from the first row. + +- Choose 2 from the second row. + +- Choose 3 from the third row. + +The sum of the chosen elements is 6, and the absolute difference is 94. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/08/03/matrix1-3.png) + +**Input:** mat = \[\[1,2,9,8,7]], target = 6 + +**Output:** 1 + +**Explanation:** The best choice is to choose 7 from the first row. The absolute difference is 1. + +**Constraints:** + +* `m == mat.length` +* `n == mat[i].length` +* `1 <= m, n <= 70` +* `1 <= mat[i][j] <= 70` +* `1 <= target <= 800` + +## Solution + +```kotlin +class Solution { + fun minimizeTheDifference(mat: Array, target: Int): Int { + val m = mat.size + val seen = Array(m) { BooleanArray(m * 70 + 1) } + dfs(0, mat, 0, seen) + var i = 0 + while (true) { + var j = 0 + var sign = 1 + while (j < 2) { + val k = target - i * sign + if (k >= 0 && k <= m * 70 && seen[m - 1][k]) { + return i + } + j++ + sign *= -1 + } + i++ + } + } + + private fun dfs(i: Int, mat: Array, sum: Int, seen: Array) { + if (i == mat.size) { + return + } + for (j in mat[i].indices) { + if (!seen[i][sum + mat[i][j]]) { + seen[i][sum + mat[i][j]] = true + dfs(i + 1, mat, sum + mat[i][j], seen) + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1982_find_array_given_subset_sums/readme.md b/src/main/kotlin/g1901_2000/s1982_find_array_given_subset_sums/readme.md new file mode 100644 index 00000000..34f49221 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1982_find_array_given_subset_sums/readme.md @@ -0,0 +1,99 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1982\. Find Array Given Subset Sums + +Hard + +You are given an integer `n` representing the length of an unknown array that you are trying to recover. You are also given an array `sums` containing the values of all 2n **subset sums** of the unknown array (in no particular order). + +Return _the array_ `ans` _of length_ `n` _representing the unknown array. If **multiple** answers exist, return **any** of them_. + +An array `sub` is a **subset** of an array `arr` if `sub` can be obtained from `arr` by deleting some (possibly zero or all) elements of `arr`. The sum of the elements in `sub` is one possible **subset sum** of `arr`. The sum of an empty array is considered to be `0`. + +**Note:** Test cases are generated such that there will **always** be at least one correct answer. + +**Example 1:** + +**Input:** n = 3, sums = [-3,-2,-1,0,0,1,2,3] + +**Output:** [1,2,-3] + +**Explanation:** [1,2,-3] is able to achieve the given subset sums: + +- \[]: sum is 0 + +- \[1]: sum is 1 + +- \[2]: sum is 2 + +- \[1,2]: sum is 3 + +- \[-3]: sum is -3 + +- \[1,-3]: sum is -2 + +- \[2,-3]: sum is -1 + +- \[1,2,-3]: sum is 0 + +Note that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted. + +**Example 2:** + +**Input:** n = 2, sums = [0,0,0,0] + +**Output:** [0,0] + +**Explanation:** The only correct answer is [0,0]. + +**Example 3:** + +**Input:** n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8] + +**Output:** [0,-1,4,5] + +**Explanation:** [0,-1,4,5] is able to achieve the given subset sums. + +**Constraints:** + +* `1 <= n <= 15` +* sums.length == 2n +* -104 <= sums[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun recoverArray(n: Int, sums: IntArray): IntArray { + sums.sort() + var m = sums.size + var zeroShift = 0 + val res = IntArray(n) + for (i in 0 until n) { + val diff = sums[1] - sums[0] + var p = 0 + var k = 0 + var zpos = m + for (j in 0 until m) { + if (k < p && sums[k] == sums[j]) { + k++ + } else { + if (zeroShift == sums[j]) { + zpos = p + } + sums[p++] = sums[j] + diff + } + } + if (zpos >= m / 2) { + res[i] = -diff + } else { + res[i] = diff + zeroShift += diff + } + m /= 2 + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1984_minimum_difference_between_highest_and_lowest_of_k_scores/readme.md b/src/main/kotlin/g1901_2000/s1984_minimum_difference_between_highest_and_lowest_of_k_scores/readme.md new file mode 100644 index 00000000..e9feb523 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1984_minimum_difference_between_highest_and_lowest_of_k_scores/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) + +## 1984\. Minimum Difference Between Highest and Lowest of K Scores + +Easy + +You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the ith student. You are also given an integer `k`. + +Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**. + +Return _the **minimum** possible difference_. + +**Example 1:** + +**Input:** nums = [90], k = 1 + +**Output:** 0 + +**Explanation:** There is one way to pick score(s) of one student: + +- \[**90**]. The difference between the highest and lowest score is 90 - 90 = 0. + +The minimum possible difference is 0. + +**Example 2:** + +**Input:** nums = [9,4,1,7], k = 2 + +**Output:** 2 + +**Explanation:** There are six ways to pick score(s) of two students: + +- \[**9**,**4**,1,7]. The difference between the highest and lowest score is 9 - 4 = 5. + +- \[**9**,4,**1**,7]. The difference between the highest and lowest score is 9 - 1 = 8. + +- \[**9**,4,1,**7**]. The difference between the highest and lowest score is 9 - 7 = 2. + +- \[9,**4**,**1**,7]. The difference between the highest and lowest score is 4 - 1 = 3. + +- \[9,**4**,1,**7**]. The difference between the highest and lowest score is 7 - 4 = 3. + +- \[9,4,**1**,**7**]. The difference between the highest and lowest score is 7 - 1 = 6. + +The minimum possible difference is 2. + +**Constraints:** + +* `1 <= k <= nums.length <= 1000` +* 0 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun minimumDifference(nums: IntArray, k: Int): Int { + nums.sort() + var minDiff = nums[nums.size - 1] + for (i in 0..nums.size - k) { + minDiff = Math.min(minDiff, nums[i + k - 1] - nums[i]) + } + return minDiff + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1985_find_the_kth_largest_integer_in_the_array/readme.md b/src/main/kotlin/g1901_2000/s1985_find_the_kth_largest_integer_in_the_array/readme.md new file mode 100644 index 00000000..e8a97fc8 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1985_find_the_kth_largest_integer_in_the_array/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) + +## 1985\. Find the Kth Largest Integer in the Array + +Medium + +You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros. + +Return _the string that represents the_ kth _**largest integer** in_ `nums`. + +**Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `["1","2","2"]`, `"2"` is the first largest integer, `"2"` is the second-largest integer, and `"1"` is the third-largest integer. + +**Example 1:** + +**Input:** nums = ["3","6","7","10"], k = 4 + +**Output:** "3" + +**Explanation:** + +The numbers in nums sorted in non-decreasing order are ["3","6","7","10"]. + +The 4th largest integer in nums is "3". + +**Example 2:** + +**Input:** nums = ["2","21","12","1"], k = 3 + +**Output:** "2" + +**Explanation:** + +The numbers in nums sorted in non-decreasing order are ["1","2","12","21"]. + +The 3rd largest integer in nums is "2". + +**Example 3:** + +**Input:** nums = ["0","0"], k = 2 + +**Output:** "0" + +**Explanation:** + +The numbers in nums sorted in non-decreasing order are ["0","0"]. + +The 2nd largest integer in nums is "0". + +**Constraints:** + +* 1 <= k <= nums.length <= 104 +* `1 <= nums[i].length <= 100` +* `nums[i]` consists of only digits. +* `nums[i]` will not have any leading zeros. + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun kthLargestNumber(nums: Array, k: Int): String { + Arrays.sort(nums) { n1: String, n2: String -> compareStringInt(n2, n1) } + return nums[k - 1] + } + + private fun compareStringInt(n1: String, n2: String): Int { + if (n1.length != n2.length) { + return if (n1.length < n2.length) -1 else 1 + } + for (i in 0 until n1.length) { + val n1Digit = n1[i].code - '0'.code + val n2Digit = n2[i].code - '0'.code + if (n1Digit > n2Digit) { + return 1 + } else if (n2Digit > n1Digit) { + return -1 + } + } + return 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1986_minimum_number_of_work_sessions_to_finish_the_tasks/readme.md b/src/main/kotlin/g1901_2000/s1986_minimum_number_of_work_sessions_to_finish_the_tasks/readme.md new file mode 100644 index 00000000..5b6e74e8 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1986_minimum_number_of_work_sessions_to_finish_the_tasks/readme.md @@ -0,0 +1,104 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1986\. Minimum Number of Work Sessions to Finish the Tasks + +Medium + +There are `n` tasks assigned to you. The task times are represented as an integer array `tasks` of length `n`, where the ith task takes `tasks[i]` hours to finish. A **work session** is when you work for **at most** `sessionTime` consecutive hours and then take a break. + +You should finish the given tasks in a way that satisfies the following conditions: + +* If you start a task in a work session, you must complete it in the **same** work session. +* You can start a new task **immediately** after finishing the previous one. +* You may complete the tasks in **any order**. + +Given `tasks` and `sessionTime`, return _the **minimum** number of **work sessions** needed to finish all the tasks following the conditions above._ + +The tests are generated such that `sessionTime` is **greater** than or **equal** to the **maximum** element in `tasks[i]`. + +**Example 1:** + +**Input:** tasks = [1,2,3], sessionTime = 3 + +**Output:** 2 + +**Explanation:** You can finish the tasks in two work sessions. + +- First work session: finish the first and the second tasks in 1 + 2 = 3 hours. + +- Second work session: finish the third task in 3 hours. + +**Example 2:** + +**Input:** tasks = [3,1,3,1,1], sessionTime = 8 + +**Output:** 2 + +**Explanation:** You can finish the tasks in two work sessions. + +- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours. + +- Second work session: finish the last task in 1 hour. + +**Example 3:** + +**Input:** tasks = [1,2,3,4,5], sessionTime = 15 + +**Output:** 1 + +**Explanation:** You can finish all the tasks in one work session. + +**Constraints:** + +* `n == tasks.length` +* `1 <= n <= 14` +* `1 <= tasks[i] <= 10` +* `max(tasks[i]) <= sessionTime <= 15` + +## Solution + +```kotlin +class Solution { + fun minSessions(tasks: IntArray, sessionTime: Int): Int { + val len = tasks.size + // minimum, all tasks can fit into 1 session + var i = 1 + // maximum, each task take 1 session to finish + var j = len + while (i < j) { + // try m sessions to see whether it can work + val m = (i + j) / 2 + if (canFit(tasks, IntArray(m), sessionTime, len - 1)) { + j = m + } else { + i = m + 1 + } + } + return i + } + + private fun canFit(tasks: IntArray, sessions: IntArray, sessionTime: Int, idx: Int): Boolean { + // all tasks have been taken care of + if (idx == -1) { + return true + } + val dup: MutableSet = HashSet() + // now to take care of tasks[idx] + // try each spot + for (i in sessions.indices) { + // current spot cannot fit + if (sessions[i] + tasks[idx] > sessionTime || dup.contains(sessions[i] + tasks[idx])) { + continue + } + dup.add(sessions[i] + tasks[idx]) + sessions[i] += tasks[idx] + if (canFit(tasks, sessions, sessionTime, idx - 1)) { + return true + } + sessions[i] -= tasks[idx] + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1987_number_of_unique_good_subsequences/readme.md b/src/main/kotlin/g1901_2000/s1987_number_of_unique_good_subsequences/readme.md new file mode 100644 index 00000000..18929e96 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1987_number_of_unique_good_subsequences/readme.md @@ -0,0 +1,92 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1987\. Number of Unique Good Subsequences + +Hard + +You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0"`). + +Find the number of **unique good subsequences** of `binary`. + +* For example, if `binary = "001"`, then all the **good** subsequences are `["0", "0", "1"]`, so the **unique** good subsequences are `"0"` and `"1"`. Note that subsequences `"00"`, `"01"`, and `"001"` are not good because they have leading zeros. + +Return _the number of **unique good subsequences** of_ `binary`. Since the answer may be very large, return it **modulo** 109 + 7. + +A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. + +**Example 1:** + +**Input:** binary = "001" + +**Output:** 2 + +**Explanation:** The good subsequences of binary are ["0", "0", "1"]. + +The unique good subsequences are "0" and "1". + +**Example 2:** + +**Input:** binary = "11" + +**Output:** 2 + +**Explanation:** The good subsequences of binary are ["1", "1", "11"]. + +The unique good subsequences are "1" and "11". + +**Example 3:** + +**Input:** binary = "101" + +**Output:** 5 + +**Explanation:** The good subsequences of binary are ["1", "0", "1", "10", "11", "101"]. + +The unique good subsequences are "0", "1", "10", "11", and "101". + +**Constraints:** + +* 1 <= binary.length <= 105 +* `binary` consists of only `'0'`s and `'1'`s. + +## Solution + +```kotlin +class Solution { + fun numberOfUniqueGoodSubsequences(binary: String): Int { + var addZero = false + // in the first round we "concat" to the empty binary + var count = 1 + val countEndsWith = IntArray(2) + for (i in 0 until binary.length) { + val c = binary[i] + val cIndex = c.code - '0'.code + // all valid sub-binaries + c at the end => same count + var endsWithCCount = count + if (c == '0') { + addZero = true + // every time c is '0', we concat it to "" and get "0" - we wish to count it only + // once (done in the end) + endsWithCCount-- + } + // w/out c at the end minus dups (= already end with c) + count = (count + endsWithCCount - countEndsWith[cIndex]) % MOD + // may be negative due to MOD + count = if (count < 0) count + MOD else count + countEndsWith[cIndex] = endsWithCCount + } + // remove the empty binary + count-- + // add "0" + if (addZero) { + count++ + } + return count + } + + companion object { + private const val MOD = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1991_find_the_middle_index_in_array/readme.md b/src/main/kotlin/g1901_2000/s1991_find_the_middle_index_in_array/readme.md new file mode 100644 index 00000000..87644a5f --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1991_find_the_middle_index_in_array/readme.md @@ -0,0 +1,80 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1991\. Find the Middle Index in Array + +Easy + +Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones). + +A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]`. + +If `middleIndex == 0`, the left side sum is considered to be `0`. Similarly, if `middleIndex == nums.length - 1`, the right side sum is considered to be `0`. + +Return _the **leftmost**_ `middleIndex` _that satisfies the condition, or_ `-1` _if there is no such index_. + +**Example 1:** + +**Input:** nums = [2,3,-1,8,4] + +**Output:** 3 + +**Explanation:** The sum of the numbers before index 3 is: 2 + 3 + -1 = 4 + +The sum of the numbers after index 3 is: 4 = 4 + +**Example 2:** + +**Input:** nums = [1,-1,4] + +**Output:** 2 + +**Explanation:** The sum of the numbers before index 2 is: 1 + -1 = 0 + +The sum of the numbers after index 2 is: 0 + +**Example 3:** + +**Input:** nums = [2,5] + +**Output:** -1 + +**Explanation:** There is no valid middleIndex. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `-1000 <= nums[i] <= 1000` + +**Note:** This question is the same as 724 + +## Solution + +```kotlin +class Solution { + // TC : O(1), SC: (1) + fun findMiddleIndex(nums: IntArray): Int { + // find the sum of all numbers in the array + var sum = 0 + for (n in nums) { + sum += n + } + // consider leftSum = 0, rightSum = sum + var leftSum = 0 + var rightSum = sum + /* + Traverse the array: At each index, subtract the element from rightSum and + check if leftSum equals rightSum. If they do, return the index. + Otherwise, add the number at current index to the leftSum and traverse further. + */for (i in nums.indices) { + rightSum -= nums[i] + if (leftSum == rightSum) { + return i + } + leftSum += nums[i] + } + // index not found, return -1 + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1992_find_all_groups_of_farmland/readme.md b/src/main/kotlin/g1901_2000/s1992_find_all_groups_of_farmland/readme.md new file mode 100644 index 00000000..207d9b92 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1992_find_all_groups_of_farmland/readme.md @@ -0,0 +1,100 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1992\. Find All Groups of Farmland + +Medium + +You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland. + +To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. No two groups are adjacent, meaning farmland in one group is **not** four-directionally adjacent to another farmland in a different group. + +`land` can be represented by a coordinate system where the top left corner of `land` is `(0, 0)` and the bottom right corner of `land` is `(m-1, n-1)`. Find the coordinates of the top left and bottom right corner of each **group** of farmland. A **group** of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2]. + +Return _a 2D array containing the 4-length arrays described above for each **group** of farmland in_ `land`_. If there are no groups of farmland, return an empty array. You may return the answer in **any order**_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-23-15-copy-of-diagram-drawio-diagrams-net.png) + +**Input:** land = \[\[1,0,0],[0,1,1],[0,1,1]] + +**Output:** [[0,0,0,0],[1,1,2,2]] + +**Explanation:** + +The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0]. + +The second group has a top left corner at land[1][1] and a bottom right corner at land[2][2]. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-30-26-copy-of-diagram-drawio-diagrams-net.png) + +**Input:** land = \[\[1,1],[1,1]] + +**Output:** [[0,0,1,1]] + +**Explanation:** + +The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1]. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-32-24-copy-of-diagram-drawio-diagrams-net.png) + +**Input:** land = \[\[0]] + +**Output:** [] + +**Explanation:** There are no groups of farmland. + +**Constraints:** + +* `m == land.length` +* `n == land[i].length` +* `1 <= m, n <= 300` +* `land` consists of only `0`'s and `1`'s. +* Groups of farmland are **rectangular** in shape. + +## Solution + +```kotlin +class Solution { + private val res: MutableList = ArrayList() + fun findFarmland(land: Array): Array { + if (land.isEmpty()) { + return arrayOf() + } + val m = land.size + val n = land[0].size + for (i in 0 until m) { + for (j in 0 until n) { + if (land[i][j] == 1) { + val dirs = IntArray(4) + dirs[0] = i + dirs[1] = j + dirs[2] = i + dirs[3] = j + dfs(land, i, j, dirs) + res.add(dirs) + } + } + } + return res.toTypedArray() + } + + private fun dfs(land: Array, i: Int, j: Int, dirs: IntArray) { + if (i < 0 || i >= land.size || j < 0 || j >= land[0].size || land[i][j] != 1) { + return + } + land[i][j] = -1 + dfs(land, i + 1, j, dirs) + dfs(land, i, j + 1, dirs) + dirs[0] = Math.min(dirs[0], i) + dirs[1] = Math.min(dirs[1], j) + dirs[2] = Math.max(dirs[2], i) + dirs[3] = Math.max(dirs[3], j) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1993_operations_on_tree/readme.md b/src/main/kotlin/g1901_2000/s1993_operations_on_tree/readme.md new file mode 100644 index 00000000..cb7513f3 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1993_operations_on_tree/readme.md @@ -0,0 +1,146 @@ +[![](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) + +## 1993\. Operations on Tree + +Medium + +You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the ith node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree. + +The data structure should support the following functions: + +* **Lock: Locks** the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked. +* **Unlock: Unlocks** the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user. +* **Upgrade: Locks** the given node for the given user and **unlocks** all of its descendants **regardless** of who locked it. You may only upgrade a node if **all** 3 conditions are true: + * The node is unlocked, + * It has at least one locked descendant (by **any** user), and + * It does not have any locked ancestors. + +Implement the `LockingTree` class: + +* `LockingTree(int[] parent)` initializes the data structure with the parent array. +* `lock(int num, int user)` returns `true` if it is possible for the user with id `user` to lock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **locked** by the user with id `user`. +* `unlock(int num, int user)` returns `true` if it is possible for the user with id `user` to unlock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **unlocked**. +* `upgrade(int num, int user)` returns `true` if it is possible for the user with id `user` to upgrade the node `num`, or `false` otherwise. If it is possible, the node `num` will be **upgraded**. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/07/29/untitled.png) + +**Input** + +["LockingTree", "lock", "unlock", "unlock", "lock", "upgrade", "lock"] + +[[[-1, 0, 0, 1, 1, 2, 2]], [2, 2], [2, 3], [2, 2], [4, 5], [0, 1], [0, 1]] + +**Output:** [null, true, false, true, true, true, false] + +**Explanation:** + + LockingTree lockingTree = new LockingTree([-1, 0, 0, 1, 1, 2, 2]); + lockingTree.lock(2, 2); // return true because node 2 is unlocked. + // Node 2 will now be locked by user 2. + lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2. + lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2. + // Node 2 will now be unlocked. + lockingTree.lock(4, 5); // return true because node 4 is unlocked. + // Node 4 will now be locked by user 5. + lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4). + // Node 0 will now be locked by user 1 and node 4 will now be unlocked. + lockingTree.lock(0, 1); // return false because node 0 is already locked. + +**Constraints:** + +* `n == parent.length` +* `2 <= n <= 2000` +* `0 <= parent[i] <= n - 1` for `i != 0` +* `parent[0] == -1` +* `0 <= num <= n - 1` +* 1 <= user <= 104 +* `parent` represents a valid tree. +* At most `2000` calls **in total** will be made to `lock`, `unlock`, and `upgrade`. + +## Solution + +```kotlin +import java.util.LinkedList + +class LockingTree(parent: IntArray) { + private val a: Array + private val map = HashMap>() + + init { + val l = parent.size + a = Array(l) { IntArray(2) } + for (i in 0 until l) { + a[i][0] = parent[i] + a[i][1] = -1 + map.putIfAbsent(parent[i], ArrayList()) + val p = map[parent[i]]!! + p.add(i) + map[parent[i]] = p + } + } + + fun lock(num: Int, user: Int): Boolean { + val userId = a[num][1] + if (userId == -1) { + a[num][1] = user + return true + } + return false + } + + fun unlock(num: Int, user: Int): Boolean { + val y = a[num][1] + if (y == user) { + a[num][1] = -1 + return true + } + return false + } + + fun upgrade(num: Int, user: Int): Boolean { + var par = num + while (par >= 0) { + val lop = a[par][1] + if (lop != -1) { + return false + } + par = a[par][0] + } + var f = 0 + val que = LinkedList() + val v = IntArray(a.size) + que.add(num) + v[num] = 1 + while (que.isNotEmpty()) { + val t = que[0] + que.removeAt(0) + val p: List = map.getOrDefault(t, ArrayList()) + for (e in p) { + if (a[e][1] != -1) { + f = 1 + a[e][1] = -1 + } + if (v[e] == 0) { + que.add(e) + v[e] = 1 + } + } + } + if (f == 1) { + a[num][1] = user + return true + } + return false + } +} +/* + * Your LockingTree object will be instantiated and called as such: + * var obj = LockingTree(parent) + * var param_1 = obj.lock(num,user) + * var param_2 = obj.unlock(num,user) + * var param_3 = obj.upgrade(num,user) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1994_the_number_of_good_subsets/readme.md b/src/main/kotlin/g1901_2000/s1994_the_number_of_good_subsets/readme.md new file mode 100644 index 00000000..56739fe6 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1994_the_number_of_good_subsets/readme.md @@ -0,0 +1,136 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1994\. The Number of Good Subsets + +Hard + +You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers. + +* For example, if `nums = [1, 2, 3, 4]`: + * `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3` respectively. + * `[1, 4]` and `[4]` are not **good** subsets with products `4 = 2*2` and `4 = 2*2` respectively. + +Return _the number of different **good** subsets in_ `nums` _**modulo**_ 109 + 7. + +A **subset** of `nums` is any array that can be obtained by deleting some (possibly none or all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different. + +**Example 1:** + +**Input:** nums = [1,2,3,4] + +**Output:** 6 + +**Explanation:** The good subsets are: + +- \[1,2]: product is 2, which is the product of distinct prime 2. + +- \[1,2,3]: product is 6, which is the product of distinct primes 2 and 3. + +- \[1,3]: product is 3, which is the product of distinct prime 3. + +- \[2]: product is 2, which is the product of distinct prime 2. + +- \[2,3]: product is 6, which is the product of distinct primes 2 and 3. + +- \[3]: product is 3, which is the product of distinct prime 3. + +**Example 2:** + +**Input:** nums = [4,2,3,15] + +**Output:** 5 + +**Explanation:** The good subsets are: + +- \[2]: product is 2, which is the product of distinct prime 2. + +- \[2,3]: product is 6, which is the product of distinct primes 2 and 3. + +- \[2,15]: product is 30, which is the product of distinct primes 2, 3, and 5. + +- \[3]: product is 3, which is the product of distinct prime 3. + +- \[15]: product is 15, which is the product of distinct primes 3 and 5. + +**Constraints:** + +* 1 <= nums.length <= 105 +* `1 <= nums[i] <= 30` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + private fun add(a: Long, b: Long): Long { + var a = a + a += b + return if (a < MOD) a else a - MOD + } + + private fun mul(a: Long, b: Long): Long { + var a = a + a *= b + return if (a < MOD) a else a % MOD + } + + private fun pow(a: Long, b: Long): Long { + // a %= MOD; + // b%=(MOD-1);//if MOD is prime + var a = a + var b = b + var res: Long = 1 + while (b > 0) { + if (b and 1L == 1L) { + res = mul(res, a) + } + a = mul(a, a) + b = b shr 1 + } + return add(res, 0) + } + + fun numberOfGoodSubsets(nums: IntArray): Int { + val primes = intArrayOf(2, 3, 5, 7, 11, 13, 17, 19, 23, 29) + val mask = IntArray(31) + val freq = IntArray(31) + for (x in nums) { + freq[x]++ + } + for (i in 1..30) { + for (j in primes.indices) { + if (i % primes[j] == 0) { + if (i / primes[j] % primes[j] == 0) { + mask[i] = 0 + break + } + mask[i] = mask[i] or pow(2, j.toLong()).toInt() + } + } + } + val dp = LongArray(1024) + dp[0] = 1 + for (i in 1..30) { + if (mask[i] != 0) { + for (j in 0..1023) { + if (mask[i] and j == 0 && dp[j] > 0) { + dp[mask[i] or j] = add(dp[mask[i] or j], mul(dp[j], freq[i].toLong())) + } + } + } + } + var ans: Long = 0 + for (i in 1..1023) { + ans = add(ans, dp[i]) + } + ans = mul(ans, pow(2, freq[1].toLong())) + ans = add(ans, 0) + return ans.toInt() + } + + companion object { + private const val MOD = (1e9 + 7).toLong() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1995_count_special_quadruplets/readme.md b/src/main/kotlin/g1901_2000/s1995_count_special_quadruplets/readme.md new file mode 100644 index 00000000..32f0a8ab --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1995_count_special_quadruplets/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) + +## 1995\. Count Special Quadruplets + +Easy + +Given a **0-indexed** integer array `nums`, return _the number of **distinct** quadruplets_ `(a, b, c, d)` _such that:_ + +* `nums[a] + nums[b] + nums[c] == nums[d]`, and +* `a < b < c < d` + +**Example 1:** + +**Input:** nums = [1,2,3,6] + +**Output:** 1 + +**Explanation:** The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6. + +**Example 2:** + +**Input:** nums = [3,3,6,4,5] + +**Output:** 0 + +**Explanation:** There are no such quadruplets in [3,3,6,4,5]. + +**Example 3:** + +**Input:** nums = [1,1,1,3,5] + +**Output:** 4 + +**Explanation:** The 4 quadruplets that satisfy the requirement are: + +- (0, 1, 2, 3): 1 + 1 + 1 == 3 + +- (0, 1, 3, 4): 1 + 1 + 3 == 5 + +- (0, 2, 3, 4): 1 + 1 + 3 == 5 + +- (1, 2, 3, 4): 1 + 1 + 3 == 5 + +**Constraints:** + +* `4 <= nums.length <= 50` +* `1 <= nums[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun countQuadruplets(nums: IntArray): Int { + var count = 0 + // max nums value is 100 so two elements sum can be max 200 + val m = IntArray(201) + for (i in 1 until nums.size - 2) { + for (j in 0 until i) { + // update all possible 2 sums + m[nums[j] + nums[i]]++ + } + for (j in i + 2 until nums.size) { + // fix third element and search for fourth - third in 2 sums as a + b + c = d == a + // + b = d - c + val diff = nums[j] - nums[i + 1] + if (diff >= 0) { + count += m[diff] + } + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1996_the_number_of_weak_characters_in_the_game/readme.md b/src/main/kotlin/g1901_2000/s1996_the_number_of_weak_characters_in_the_game/readme.md new file mode 100644 index 00000000..891ad6ee --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1996_the_number_of_weak_characters_in_the_game/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) + +## 1996\. The Number of Weak Characters in the Game + +Medium + +You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where properties[i] = [attacki, defensei] represents the properties of the ith character in the game. + +A character is said to be **weak** if any other character has **both** attack and defense levels **strictly greater** than this character's attack and defense levels. More formally, a character `i` is said to be **weak** if there exists another character `j` where attackj > attacki and defensej > defensei. + +Return _the number of **weak** characters_. + +**Example 1:** + +**Input:** properties = \[\[5,5],[6,3],[3,6]] + +**Output:** 0 + +**Explanation:** No character has strictly greater attack and defense than the other. + +**Example 2:** + +**Input:** properties = \[\[2,2],[3,3]] + +**Output:** 1 + +**Explanation:** The first character is weak because the second character has a strictly greater attack and defense. + +**Example 3:** + +**Input:** properties = \[\[1,5],[10,4],[4,3]] + +**Output:** 1 + +**Explanation:** The third character is weak because the second character has a strictly greater attack and defense. + +**Constraints:** + +* 2 <= properties.length <= 105 +* `properties[i].length == 2` +* 1 <= attacki, defensei <= 105 + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun numberOfWeakCharacters(properties: Array): Int { + Arrays.sort(properties) { a: IntArray, b: IntArray -> if (a[0] == b[0]) b[1] - a[1] else a[0] - b[0] } + var max = properties[properties.size - 1][1] + var count = 0 + for (i in properties.size - 2 downTo 0) { + if (properties[i][1] < max) { + count++ + } + max = Math.max(max, properties[i][1]) + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1997_first_day_where_you_have_been_in_all_the_rooms/readme.md b/src/main/kotlin/g1901_2000/s1997_first_day_where_you_have_been_in_all_the_rooms/readme.md new file mode 100644 index 00000000..4d7de41b --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1997_first_day_where_you_have_been_in_all_the_rooms/readme.md @@ -0,0 +1,80 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1997\. First Day Where You Have Been in All the Rooms + +Medium + +There are `n` rooms you need to visit, labeled from `0` to `n - 1`. Each day is labeled, starting from `0`. You will go in and visit one room a day. + +Initially on day `0`, you visit room `0`. The **order** you visit the rooms for the coming days is determined by the following **rules** and a given **0-indexed** array `nextVisit` of length `n`: + +* Assuming that on a day, you visit room `i`, +* if you have been in room `i` an **odd** number of times (**including** the current visit), on the **next** day you will visit a room with a **lower or equal room number** specified by `nextVisit[i]` where `0 <= nextVisit[i] <= i`; +* if you have been in room `i` an **even** number of times (**including** the current visit), on the **next** day you will visit room `(i + 1) mod n`. + +Return _the label of the **first** day where you have been in **all** the rooms_. It can be shown that such a day exists. Since the answer may be very large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** nextVisit = [0,0] + +**Output:** 2 + +**Explanation:** + +- On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd. + +On the next day you will visit room nextVisit[0] = 0 + +- On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even. + +On the next day you will visit room (0 + 1) mod 2 = 1 + +- On day 2, you visit room 1. This is the first day where you have been in all the rooms. + +**Example 2:** + +**Input:** nextVisit = [0,0,2] + +**Output:** 6 + +**Explanation:** + +Your room visiting order for each day is: [0,0,1,0,0,1,2,...]. + +Day 6 is the first day where you have been in all the rooms. + +**Example 3:** + +**Input:** nextVisit = [0,1,2,0] + +**Output:** 6 + +**Explanation:** + +Your room visiting order for each day is: [0,0,1,1,2,2,3,...]. + +Day 6 is the first day where you have been in all the rooms. + +**Constraints:** + +* `n == nextVisit.length` +* 2 <= n <= 105 +* `0 <= nextVisit[i] <= i` + +## Solution + +```kotlin +class Solution { + fun firstDayBeenInAllRooms(nextVisit: IntArray): Int { + val dp = IntArray(nextVisit.size) + val m = 1000000007 + for (i in 1 until dp.size) { + val steps = 2 * dp[i - 1] - dp[nextVisit[i - 1]] + 2 + dp[i] = if (steps < 0) (steps + m) % m else steps % m + } + return dp[dp.size - 1] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s1998_gcd_sort_of_an_array/readme.md b/src/main/kotlin/g1901_2000/s1998_gcd_sort_of_an_array/readme.md new file mode 100644 index 00000000..c187eec9 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s1998_gcd_sort_of_an_array/readme.md @@ -0,0 +1,112 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1998\. GCD Sort of an Array + +Hard + +You are given an integer array `nums`, and you can perform the following operation **any** number of times on `nums`: + +* Swap the positions of two elements `nums[i]` and `nums[j]` if `gcd(nums[i], nums[j]) > 1` where `gcd(nums[i], nums[j])` is the **greatest common divisor** of `nums[i]` and `nums[j]`. + +Return `true` _if it is possible to sort_ `nums` _in **non-decreasing** order using the above swap method, or_ `false` _otherwise._ + +**Example 1:** + +**Input:** nums = [7,21,3] + +**Output:** true + +**Explanation:** We can sort [7,21,3] by performing the following operations: + +- Swap 7 and 21 because gcd(7,21) = 7. nums = [**21**,**7**,3] + +- Swap 21 and 3 because gcd(21,3) = 3. nums = [**3**,7,**21**] + +**Example 2:** + +**Input:** nums = [5,2,6,2] + +**Output:** false + +**Explanation:** It is impossible to sort the array because 5 cannot be swapped with any other element. + +**Example 3:** + +**Input:** nums = [10,5,9,3,15] + +**Output:** true We can sort [10,5,9,3,15] by performing the following operations: + +- Swap 10 and 15 because gcd(10,15) = 5. nums = [**15**,5,9,3,**10**] + +- Swap 15 and 3 because gcd(15,3) = 3. nums = [**3**,5,9,**15**,10] + +- Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,**10**,**15**] + +**Constraints:** + +* 1 <= nums.length <= 3 * 104 +* 2 <= nums[i] <= 105 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun gcdSort(nums: IntArray): Boolean { + val sorted = nums.clone() + sorted.sort() + val len = nums.size + val max = sorted[len - 1] + // grouping tree child(index)->parent(value), index==value is root + val nodes = IntArray(max + 1) + for (j in nums) { + nodes[j] = -1 + } + // value: <=0 not sieved, <0 leaf node, 0 or 1 not in nums, >1 grouped + for (p in 2..max / 2) { + if (nodes[p] > 0) { + // sieved so not a prime number. + continue + } + // p is now a prime number, set self as root. + nodes[p] = p + var group = p + var num = p + p + while (num <= max) { + var existing = nodes[num] + if (existing < 0) { + // 1st hit, set group + nodes[num] = group + } else if (existing <= 1) { + // value doesn't exist in nums + nodes[num] = 1 + } else if (root(nodes, existing).also { existing = it } < group) { + nodes[group] = existing + group = existing + } else { + nodes[existing] = group + } + num += p + } + } + for (i in 0 until len) { + if (root(nodes, nums[i]) != root(nodes, sorted[i])) { + return false + } + } + return true + } + + companion object { + private fun root(nodes: IntArray, num: Int): Int { + var num = num + var group: Int + while (nodes[num].also { group = it } > 0 && group != num) { + num = group + } + return num + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1901_2000/s2000_reverse_prefix_of_word/readme.md b/src/main/kotlin/g1901_2000/s2000_reverse_prefix_of_word/readme.md new file mode 100644 index 00000000..ed57b537 --- /dev/null +++ b/src/main/kotlin/g1901_2000/s2000_reverse_prefix_of_word/readme.md @@ -0,0 +1,68 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2000\. Reverse Prefix of Word + +Easy + +Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. + +* For example, if `word = "abcdefd"` and `ch = "d"`, then you should **reverse** the segment that starts at `0` and ends at `3` (**inclusive**). The resulting string will be `"dcbaefd"`. + +Return _the resulting string_. + +**Example 1:** + +**Input:** word = "abcdefd", ch = "d" + +**Output:** "dcbaefd" + +**Explanation:** The first occurrence of "d" is at index 3. + +Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd". + +**Example 2:** + +**Input:** word = "xyxzxe", ch = "z" + +**Output:** "zxyxxe" + +**Explanation:** The first and only occurrence of "z" is at index 3. + +Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe". + +**Example 3:** + +**Input:** word = "abcd", ch = "z" + +**Output:** "abcd" + +**Explanation:** "z" does not exist in word. + +You should not do any reverse operation, the resulting string is "abcd". + +**Constraints:** + +* `1 <= word.length <= 250` +* `word` consists of lowercase English letters. +* `ch` is a lowercase English letter. + +## Solution + +```kotlin +class Solution { + fun reversePrefix(word: String, ch: Char): String { + var i = 0 + var j = word.indexOf(ch) + val charArr = word.toCharArray() + while (i < j) { + val temp = charArr[i] + charArr[i] = charArr[j] + charArr[j] = temp + i++ + j-- + } + return String(charArr) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2011_final_value_of_variable_after_performing_operations/readme.md b/src/main/kotlin/g2001_2100/s2011_final_value_of_variable_after_performing_operations/readme.md new file mode 100644 index 00000000..72ab549a --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2011_final_value_of_variable_after_performing_operations/readme.md @@ -0,0 +1,88 @@ +[![](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) + +## 2011\. Final Value of Variable After Performing Operations + +Easy + +There is a programming language with only **four** operations and **one** variable `X`: + +* `++X` and `X++` **increments** the value of the variable `X` by `1`. +* `--X` and `X--` **decrements** the value of the variable `X` by `1`. + +Initially, the value of `X` is `0`. + +Given an array of strings `operations` containing a list of operations, return _the **final** value of_ `X` _after performing all the operations_. + +**Example 1:** + +**Input:** operations = ["--X","X++","X++"] + +**Output:** 1 + +**Explanation:** The operations are performed as follows: + +Initially, X = 0. + +--X: X is decremented by 1, X = 0 - 1 = -1. + +X++: X is incremented by 1, X = -1 + 1 = 0. + +X++: X is incremented by 1, X = 0 + 1 = 1. + +**Example 2:** + +**Input:** operations = ["++X","++X","X++"] + +**Output:** 3 + +**Explanation:** The operations are performed as follows: + +Initially, X = 0. + +++X: X is incremented by 1, X = 0 + 1 = 1. + +++X: X is incremented by 1, X = 1 + 1 = 2. + +X++: X is incremented by 1, X = 2 + 1 = 3. + +**Example 3:** + +**Input:** operations = ["X++","++X","--X","X--"] + +**Output:** 0 + +**Explanation:** The operations are performed as follows: + +Initially, X = 0. + +X++: X is incremented by 1, X = 0 + 1 = 1. + +++X: X is incremented by 1, X = 1 + 1 = 2. + +--X: X is decremented by 1, X = 2 - 1 = 1. + +X--: X is decremented by 1, X = 1 - 1 = 0. + +**Constraints:** + +* `1 <= operations.length <= 100` +* `operations[i]` will be either `"++X"`, `"X++"`, `"--X"`, or `"X--"`. + +## Solution + +```kotlin +class Solution { + fun finalValueAfterOperations(operations: Array): Int { + var xValue = 0 + for (word in operations) { + if (word.contains("+")) { + xValue++ + } else { + xValue-- + } + } + return xValue + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2012_sum_of_beauty_in_the_array/readme.md b/src/main/kotlin/g2001_2100/s2012_sum_of_beauty_in_the_array/readme.md new file mode 100644 index 00000000..dd1bc9cb --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2012_sum_of_beauty_in_the_array/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) + +## 2012\. Sum of Beauty in the Array + +Medium + +You are given a **0-indexed** integer array `nums`. For each index `i` (`1 <= i <= nums.length - 2`) the **beauty** of `nums[i]` equals: + +* `2`, if `nums[j] < nums[i] < nums[k]`, for **all** `0 <= j < i` and for **all** `i < k <= nums.length - 1`. +* `1`, if `nums[i - 1] < nums[i] < nums[i + 1]`, and the previous condition is not satisfied. +* `0`, if none of the previous conditions holds. + +Return _the **sum of beauty** of all_ `nums[i]` _where_ `1 <= i <= nums.length - 2`. + +**Example 1:** + +**Input:** nums = [1,2,3] + +**Output:** 2 + +**Explanation:** For each index i in the range 1 <= i <= 1: - The beauty of nums[1] equals 2. + +**Example 2:** + +**Input:** nums = [2,4,6,4] + +**Output:** 1 + +**Explanation:** For each index i in the range 1 <= i <= 2: + +- The beauty of nums[1] equals 1. + +- The beauty of nums[2] equals 0. + +**Example 3:** + +**Input:** nums = [3,2,1] + +**Output:** 0 + +**Explanation:** For each index i in the range 1 <= i <= 1: - The beauty of nums[1] equals 0. + +**Constraints:** + +* 3 <= nums.length <= 105 +* 1 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun sumOfBeauties(nums: IntArray): Int { + val maxArr = IntArray(nums.size) + maxArr[0] = nums[0] + for (i in 1 until nums.size - 1) { + maxArr[i] = Math.max(maxArr[i - 1], nums[i]) + } + val minArr = IntArray(nums.size) + minArr[nums.size - 1] = nums[nums.size - 1] + for (i in nums.size - 2 downTo 0) { + minArr[i] = Math.min(minArr[i + 1], nums[i]) + } + var sum = 0 + for (i in 1 until nums.size - 1) { + if (nums[i] > maxArr[i - 1] && nums[i] < minArr[i + 1]) { + sum += 2 + } else if (nums[i] > nums[i - 1] && nums[i] < nums[i + 1]) { + sum += 1 + } + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2013_detect_squares/readme.md b/src/main/kotlin/g2001_2100/s2013_detect_squares/readme.md new file mode 100644 index 00000000..1cfcfa2d --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2013_detect_squares/readme.md @@ -0,0 +1,104 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2013\. Detect Squares + +Medium + +You are given a stream of points on the X-Y plane. Design an algorithm that: + +* **Adds** new points from the stream into a data structure. **Duplicate** points are allowed and should be treated as different points. +* Given a query point, **counts** the number of ways to choose three points from the data structure such that the three points and the query point form an **axis-aligned square** with **positive area**. + +An **axis-aligned square** is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis. + +Implement the `DetectSquares` class: + +* `DetectSquares()` Initializes the object with an empty data structure. +* `void add(int[] point)` Adds a new point `point = [x, y]` to the data structure. +* `int count(int[] point)` Counts the number of ways to form **axis-aligned squares** with point `point = [x, y]` as described above. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/09/01/image.png) + +**Input** ["DetectSquares", "add", "add", "add", "count", "count", "add", "count"] [[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]] + +**Output:** [null, null, null, null, 1, 0, null, 2] + +**Explanation:** + +DetectSquares detectSquares = new DetectSquares(); + +detectSquares.add([3, 10]); + +detectSquares.add([11, 2]); + +detectSquares.add([3, 2]); + +detectSquares.count([11, 10]); // return 1. You can choose: + // - The first, second, and third points + +detectSquares.count([14, 8]); // return 0. The query point cannot form a square with any points in the data structure. + +detectSquares.add([11, 2]); // Adding duplicate points is allowed. + +detectSquares.count([11, 10]); // return 2. You can choose: // - The first, second, and third points // - The first, third, and fourth points + +**Constraints:** + +* `point.length == 2` +* `0 <= x, y <= 1000` +* At most `3000` calls **in total** will be made to `add` and `count`. + +## Solution + +```kotlin +class DetectSquares { + private val map: MutableMap + + init { + map = HashMap() + } + + fun add(point: IntArray) { + val x = point[0] + val y = point[1] + val hash = x * MUL + y + if (map.containsKey(hash)) { + map[hash]!![2]++ + } else { + map[hash] = intArrayOf(x, y, 1) + } + } + + fun count(point: IntArray): Int { + var ans = 0 + val x = point[0] + val y = point[1] + for ((_, diap) in map) { + val x1 = diap[0] + val y1 = diap[1] + val num = diap[2] + if (Math.abs(x - x1) == Math.abs(y - y1) && x != x1 && y != y1) { + val p1hash = x * MUL + y1 + val p2hash = x1 * MUL + y + if (map.containsKey(p1hash) && map.containsKey(p2hash)) { + ans += map[p1hash]!![2] * map[p2hash]!![2] * num + } + } + } + return ans + } + + companion object { + private const val MUL = 1002 + } +} +/* + * Your DetectSquares object will be instantiated and called as such: + * var obj = DetectSquares() + * obj.add(point) + * var param_2 = obj.count(point) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2014_longest_subsequence_repeated_k_times/readme.md b/src/main/kotlin/g2001_2100/s2014_longest_subsequence_repeated_k_times/readme.md new file mode 100644 index 00000000..4abff091 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2014_longest_subsequence_repeated_k_times/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) + +## 2014\. Longest Subsequence Repeated k Times + +Hard + +You are given a string `s` of length `n`, and an integer `k`. You are tasked to find the **longest subsequence repeated** `k` times in string `s`. + +A **subsequence** is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. + +A subsequence `seq` is **repeated** `k` times in the string `s` if `seq * k` is a subsequence of `s`, where `seq * k` represents a string constructed by concatenating `seq` `k` times. + +* For example, `"bba"` is repeated `2` times in the string `"bababcba"`, because the string `"bbabba"`, constructed by concatenating `"bba"` `2` times, is a subsequence of the string `"**b**a**bab**c**ba**"`. + +Return _the **longest subsequence repeated**_ `k` _times in string_ `s`_. If multiple such subsequences are found, return the **lexicographically largest** one. If there is no such subsequence, return an **empty** string_. + +**Example 1:** + +![example 1](https://assets.leetcode.com/uploads/2021/08/30/longest-subsequence-repeat-k-times.png) + +**Input:** s = "letsleetcode", k = 2 + +**Output:** "let" + +**Explanation:** There are two longest subsequences repeated 2 times: "let" and "ete". "let" is the lexicographically largest one. + +**Example 2:** + +**Input:** s = "bb", k = 2 + +**Output:** "b" + +**Explanation:** The longest subsequence repeated 2 times is "b". + +**Example 3:** + +**Input:** s = "ab", k = 2 + +**Output:** "" + +**Explanation:** There is no subsequence repeated 2 times. Empty string is returned. + +**Constraints:** + +* `n == s.length` +* `2 <= n, k <= 2000` +* `2 <= n < k * 8` +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun longestSubsequenceRepeatedK(s: String, k: Int): String { + val ca = s.toCharArray() + val freq = CharArray(26) + for (value in ca) { + ++freq[value.code - 'a'.code] + } + val cand: Array?> = arrayOfNulls(8) + cand[1] = ArrayList() + var ans = "" + for (i in 0..25) { + if (freq[i].code >= k) { + ans = "" + ('a'.code + i).toChar() + cand[1]?.add(ans) + } + } + for (i in 2..7) { + cand[i] = ArrayList() + for (prev in cand[i - 1]!!) { + for (c in cand[1]!!) { + val next = prev + c + if (isSubsequenceRepeatedK(ca, next, k)) { + ans = next + cand[i]?.add(ans) + } + } + } + } + return ans + } + + private fun isSubsequenceRepeatedK(ca: CharArray, t: String, k: Int): Boolean { + var k = k + val ta = t.toCharArray() + val n = ca.size + val m = ta.size + var i = 0 + while (k-- > 0) { + var j = 0 + while (i < n && j < m) { + if (ca[i] == ta[j]) { + j++ + } + i++ + } + if (j != m) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2016_maximum_difference_between_increasing_elements/readme.md b/src/main/kotlin/g2001_2100/s2016_maximum_difference_between_increasing_elements/readme.md new file mode 100644 index 00000000..dbf84423 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2016_maximum_difference_between_increasing_elements/readme.md @@ -0,0 +1,68 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2016\. Maximum Difference Between Increasing Elements + +Easy + +Given a **0-indexed** integer array `nums` of size `n`, find the **maximum difference** between `nums[i]` and `nums[j]` (i.e., `nums[j] - nums[i]`), such that `0 <= i < j < n` and `nums[i] < nums[j]`. + +Return _the **maximum difference**._ If no such `i` and `j` exists, return `-1`. + +**Example 1:** + +**Input:** nums = [7,**1**,**5**,4] + +**Output:** 4 + +**Explanation:** + +The maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4. + +Note that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i > j, so it is not valid. + +**Example 2:** + +**Input:** nums = [9,4,3,2] + +**Output:** -1 + +**Explanation:** + +There is no i and j such that i < j and nums[i] < nums[j]. + +**Example 3:** + +**Input:** nums = [**1**,5,2,**10**] + +**Output:** 9 + +**Explanation:** + +The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9. + +**Constraints:** + +* `n == nums.length` +* `2 <= n <= 1000` +* 1 <= nums[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun maximumDifference(nums: IntArray): Int { + var mini = nums[0] + var ans = -1 + for (i in 0 until nums.size - 1) { + if (nums[i] < mini) { + mini = nums[i] + } + if (nums[i + 1] - mini > ans) { + ans = nums[i + 1] - mini + } + } + return if (ans <= 0) -1 else ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2017_grid_game/readme.md b/src/main/kotlin/g2001_2100/s2017_grid_game/readme.md new file mode 100644 index 00000000..bb082e9e --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2017_grid_game/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) + +## 2017\. Grid Game + +Medium + +You are given a **0-indexed** 2D array `grid` of size `2 x n`, where `grid[r][c]` represents the number of points at position `(r, c)` on the matrix. Two robots are playing a game on this matrix. + +Both robots initially start at `(0, 0)` and want to reach `(1, n-1)`. Each robot may only move to the **right** (`(r, c)` to `(r, c + 1)`) or **down** (`(r, c)` to `(r + 1, c)`). + +At the start of the game, the **first** robot moves from `(0, 0)` to `(1, n-1)`, collecting all the points from the cells on its path. For all cells `(r, c)` traversed on the path, `grid[r][c]` is set to `0`. Then, the **second** robot moves from `(0, 0)` to `(1, n-1)`, collecting the points on its path. Note that their paths may intersect with one another. + +The **first** robot wants to **minimize** the number of points collected by the **second** robot. In contrast, the **second** robot wants to **maximize** the number of points it collects. If both robots play **optimally**, return _the **number of points** collected by the **second** robot._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/09/08/a1.png) + +**Input:** grid = \[\[2,5,4],[1,5,1]] + +**Output:** 4 + +**Explanation:** The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue. + +The cells visited by the first robot are set to 0. + +The second robot will collect 0 + 0 + 4 + 0 = 4 points. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/09/08/a2.png) + +**Input:** grid = \[\[3,3,1],[8,5,2]] + +**Output:** 4 + +**Explanation:** The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue. + +The cells visited by the first robot are set to 0. + +The second robot will collect 0 + 3 + 1 + 0 = 4 points. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/09/08/a3.png) + +**Input:** grid = \[\[1,3,1,15],[1,3,3,1]] + +**Output:** 7 + +**Explanation:** The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue. + +The cells visited by the first robot are set to 0. + +The second robot will collect 0 + 1 + 3 + 3 + 0 = 7 points. + +**Constraints:** + +* `grid.length == 2` +* `n == grid[r].length` +* 1 <= n <= 5 * 104 +* 1 <= grid[r][c] <= 105 + +## Solution + +```kotlin +class Solution { + fun gridGame(grid: Array): Long { + val n = grid[0].size + val cum0 = LongArray(n + 1) + val cum1 = LongArray(n + 1) + for (i in 0 until n) { + cum0[i + 1] = cum0[i] + grid[0][i] + cum1[i + 1] = cum1[i] + grid[1][i] + } + var ans = Long.MAX_VALUE + for (i in 0 until n) { + ans = Math.min(ans, Math.max(cum0[n] - cum0[i + 1], cum1[i])) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2018_check_if_word_can_be_placed_in_crossword/readme.md b/src/main/kotlin/g2001_2100/s2018_check_if_word_can_be_placed_in_crossword/readme.md new file mode 100644 index 00000000..ffae06c4 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2018_check_if_word_can_be_placed_in_crossword/readme.md @@ -0,0 +1,154 @@ +[![](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) + +## 2018\. Check if Word Can Be Placed In Crossword + +Medium + +You are given an `m x n` matrix `board`, representing the **current** state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any **empty** cells, and `'#'` to represent any **blocked** cells. + +A word can be placed **horizontally** (left to right **or** right to left) or **vertically** (top to bottom **or** bottom to top) in the board if: + +* It does not occupy a cell containing the character `'#'`. +* The cell each letter is placed in must either be `' '` (empty) or **match** the letter already on the `board`. +* There must not be any empty cells `' '` or other lowercase letters **directly left or right** of the word if the word was placed **horizontally**. +* There must not be any empty cells `' '` or other lowercase letters **directly above or below** the word if the word was placed **vertically**. + +Given a string `word`, return `true` _if_ `word` _can be placed in_ `board`_, or_ `false` _**otherwise**_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/10/04/crossword-ex1-1.png) + +**Input:** board = \[\["#", " ", "#"], [" ", " ", "#"], ["#", "c", " "]], word = "abc" + +**Output:** true + +**Explanation:** The word "abc" can be placed as shown above (top to bottom). + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/10/04/crossword-ex2-1.png) + +**Input:** board = \[\[" ", "#", "a"], [" ", "#", "c"], [" ", "#", "a"]], word = "ac" + +**Output:** false + +**Explanation:** It is impossible to place the word because there will always be a space/letter above or below it. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/10/04/crossword-ex3-1.png) + +**Input:** board = \[\["#", " ", "#"], [" ", " ", "#"], ["#", " ", "c"]], word = "ca" + +**Output:** true + +**Explanation:** The word "ca" can be placed as shown above (right to left). + +**Constraints:** + +* `m == board.length` +* `n == board[i].length` +* 1 <= m * n <= 2 * 105 +* `board[i][j]` will be `' '`, `'#'`, or a lowercase English letter. +* `1 <= word.length <= max(m, n)` +* `word` will contain only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun placeWordInCrossword(board: Array, word: String): Boolean { + val m = board.size + val n = board[0].size + for (i in 0 until m) { + for (j in 0 until n) { + if ((board[i][j] == ' ' || board[i][j] == word[0]) && + ( + canPlaceTopDown(word, board, i, j) || + canPlaceLeftRight(word, board, i, j) || + canPlaceBottomUp(word, board, i, j) || + canPlaceRightLeft(word, board, i, j) + ) + ) { + return true + } + } + } + return false + } + + private fun canPlaceRightLeft(word: String, board: Array, row: Int, col: Int): Boolean { + if (col + 1 < board[0].size && + (Character.isLowerCase(board[row][col + 1]) || board[row][col + 1] == ' ') + ) { + return false + } + var k = 0 + var j = col + while (j >= 0 && k < word.length) { + if (board[row][j] != word[k] && board[row][j] != ' ') { + return false + } else { + k++ + } + j-- + } + return k == word.length && (j < 0 || board[row][j] == '#') + } + + private fun canPlaceBottomUp(word: String, board: Array, row: Int, col: Int): Boolean { + if (row + 1 < board.size && + (Character.isLowerCase(board[row + 1][col]) || board[row + 1][col] == ' ') + ) { + return false + } + var k = 0 + var i = row + while (i >= 0 && k < word.length) { + if (board[i][col] != word[k] && board[i][col] != ' ') { + return false + } else { + k++ + } + i-- + } + return k == word.length && (i < 0 || board[i][col] == '#') + } + + private fun canPlaceLeftRight(word: String, board: Array, row: Int, col: Int): Boolean { + if (col > 0 && (Character.isLowerCase(board[row][col - 1]) || board[row][col - 1] == ' ')) { + return false + } + var k = 0 + var j = col + while (j < board[0].size && k < word.length) { + if (board[row][j] != word[k] && board[row][j] != ' ') { + return false + } else { + k++ + } + j++ + } + return k == word.length && (j == board[0].size || board[row][j] == '#') + } + + private fun canPlaceTopDown(word: String, board: Array, row: Int, col: Int): Boolean { + if (row > 0 && (Character.isLowerCase(board[row - 1][col]) || board[row - 1][col] == ' ')) { + return false + } + var k = 0 + var i = row + while (i < board.size && k < word.length) { + if (board[i][col] != word[k] && board[i][col] != ' ') { + return false + } else { + k++ + } + i++ + } + return k == word.length && (i == board.size || board[i][col] == '#') + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2019_the_score_of_students_solving_math_expression/readme.md b/src/main/kotlin/g2001_2100/s2019_the_score_of_students_solving_math_expression/readme.md new file mode 100644 index 00000000..5605db38 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2019_the_score_of_students_solving_math_expression/readme.md @@ -0,0 +1,152 @@ +[![](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) + +## 2019\. The Score of Students Solving Math Expression + +Hard + +You are given a string `s` that contains digits `0-9`, addition symbols `'+'`, and multiplication symbols `'*'` **only**, representing a **valid** math expression of **single digit numbers** (e.g., `3+5*2`). This expression was given to `n` elementary school students. The students were instructed to get the answer of the expression by following this **order of operations**: + +1. Compute **multiplication**, reading from **left to right**; Then, +2. Compute **addition**, reading from **left to right**. + +You are given an integer array `answers` of length `n`, which are the submitted answers of the students in no particular order. You are asked to grade the `answers`, by following these **rules**: + +* If an answer **equals** the correct answer of the expression, this student will be rewarded `5` points; +* Otherwise, if the answer **could be interpreted** as if the student applied the operators **in the wrong order** but had **correct arithmetic**, this student will be rewarded `2` points; +* Otherwise, this student will be rewarded `0` points. + +Return _the sum of the points of the students_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/09/17/student_solving_math.png) + +**Input:** s = "7+3\*1\*2", answers = [20,13,42] + +**Output:** 7 + +**Explanation:** As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,**13**,42] + +A student might have applied the operators in this wrong order: ((7+3)\*1)\*2 = 20. Therefore one student is rewarded 2 points: [**20**,13,42] + +The points for the students are: [2,5,0]. The sum of the points is 2+5+0=7. + +**Example 2:** + +**Input:** s = "3+5\*2", answers = [13,0,10,13,13,16,16] + +**Output:** 19 + +**Explanation:** The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [**13**,0,10,**13**,**13**,16,16] + +A student might have applied the operators in this wrong order: ((3+5)\*2 = 16. Therefore two students are rewarded 2 points: [13,0,10,13,13,**16**,**16**] + +The points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19. + +**Example 3:** + +**Input:** s = "6+0\*1", answers = [12,9,6,4,8,6] + +**Output:** 10 + +**Explanation:** The correct answer of the expression is 6. + +If a student had incorrectly done (6+0)\*1, the answer would also be 6. + +By the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points. + +The points for the students are: [0,0,5,0,0,5]. The sum of the points is 10. + +**Constraints:** + +* `3 <= s.length <= 31` +* `s` represents a valid expression that contains only digits `0-9`, `'+'`, and `'*'` only. +* All the integer operands in the expression are in the **inclusive** range `[0, 9]`. +* `1 <=` The count of all operators (`'+'` and `'*'`) in the math expression `<= 15` +* Test data are generated such that the correct answer of the expression is in the range of `[0, 1000]`. +* `n == answers.length` +* 1 <= n <= 104 +* `0 <= answers[i] <= 1000` + +## Solution + +```kotlin +import java.util.ArrayDeque + +class Solution { + private lateinit var dp: Array?>> + + fun scoreOfStudents(s: String, answers: IntArray): Int { + val st = ArrayDeque() + val n = s.length + var i = 0 + dp = Array(n) { arrayOfNulls?>(n) } + while (i < n) { + if (s[i].code - '0'.code >= 0 && s[i].code - '9'.code <= 0) { + st.push(s[i].code - '0'.code) + i++ + } else if (s[i] == '*') { + val cur = st.pop() * (s[i + 1].code - '0'.code) + i += 2 + st.push(cur) + } else { + i++ + } + } + var res = 0 + var ret = 0 + while (st.isNotEmpty()) { + res += st.pop() + } + val wrong = opts(0, n - 1, s) + for (ans in answers) { + if (ans == res) { + ret += 5 + } else if (wrong!!.contains(ans)) { + ret += 2 + } + } + return ret + } + + private fun opts(i: Int, j: Int, s: String): HashSet? { + if (dp[i][j] != null) { + return dp[i][j] + } + if (i == j) { + val res = HashSet() + res.add(s[i].code - '0'.code) + dp[i][j] = res + return res + } + val res = HashSet() + var x = i + 1 + while (x < j) { + val op = s[x] + val left = opts(i, x - 1, s) + val right = opts(x + 1, j, s) + if (op == '*') { + for (l in left!!) { + for (r in right!!) { + if (l * r <= 1000) { + res.add(l * r) + } + } + } + } else { + for (l in left!!) { + for (r in right!!) { + if (l + r <= 1000) { + res.add(l + r) + } + } + } + } + x += 2 + } + dp[i][j] = res + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2022_convert_1d_array_into_2d_array/readme.md b/src/main/kotlin/g2001_2100/s2022_convert_1d_array_into_2d_array/readme.md new file mode 100644 index 00000000..5f4e84f8 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2022_convert_1d_array_into_2d_array/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) + +## 2022\. Convert 1D Array Into 2D Array + +Easy + +You are given a **0-indexed** 1-dimensional (1D) integer array `original`, and two integers, `m` and `n`. You are tasked with creating a 2-dimensional (2D) array with `m` rows and `n` columns using **all** the elements from `original`. + +The elements from indices `0` to `n - 1` (**inclusive**) of `original` should form the first row of the constructed 2D array, the elements from indices `n` to `2 * n - 1` (**inclusive**) should form the second row of the constructed 2D array, and so on. + +Return _an_ `m x n` _2D array constructed according to the above procedure, or an empty 2D array if it is impossible_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/08/26/image-20210826114243-1.png) + +**Input:** original = [1,2,3,4], m = 2, n = 2 + +**Output:** [[1,2],[3,4]] + +**Explanation:** The constructed 2D array should contain 2 rows and 2 columns. + +The first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array. + +The second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array. + +**Example 2:** + +**Input:** original = [1,2,3], m = 1, n = 3 + +**Output:** [[1,2,3]] + +**Explanation:** The constructed 2D array should contain 1 row and 3 columns. + +Put all three elements in original into the first row of the constructed 2D array. + +**Example 3:** + +**Input:** original = [1,2], m = 1, n = 1 + +**Output:** [] + +**Explanation:** There are 2 elements in original. + +It is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array. + +**Constraints:** + +* 1 <= original.length <= 5 * 104 +* 1 <= original[i] <= 105 +* 1 <= m, n <= 4 * 104 + +## Solution + +```kotlin +class Solution { + fun construct2DArray(original: IntArray, m: Int, n: Int): Array { + val size = original.size + if (m * n != size) { + return arrayOf() + } + val ans = Array(m) { IntArray(n) } + var k = 0 + for (i in 0 until m) { + for (j in 0 until n) { + ans[i][j] = original[k++] + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2023_number_of_pairs_of_strings_with_concatenation_equal_to_target/readme.md b/src/main/kotlin/g2001_2100/s2023_number_of_pairs_of_strings_with_concatenation_equal_to_target/readme.md new file mode 100644 index 00000000..77a1ddbe --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2023_number_of_pairs_of_strings_with_concatenation_equal_to_target/readme.md @@ -0,0 +1,85 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2023\. Number of Pairs of Strings With Concatenation Equal to Target + +Medium + +Given an array of **digit** strings `nums` and a **digit** string `target`, return _the number of pairs of indices_ `(i, j)` _(where_ `i != j`_) such that the **concatenation** of_ `nums[i] + nums[j]` _equals_ `target`. + +**Example 1:** + +**Input:** nums = ["777","7","77","77"], target = "7777" + +**Output:** 4 + +**Explanation:** Valid pairs are: + +- (0, 1): "777" + "7" + +- (1, 0): "7" + "777" + +- (2, 3): "77" + "77" + +- (3, 2): "77" + "77" + +**Example 2:** + +**Input:** nums = ["123","4","12","34"], target = "1234" + +**Output:** 2 + +**Explanation:** Valid pairs are: + +- (0, 1): "123" + "4" + +- (2, 3): "12" + "34" + +**Example 3:** + +**Input:** nums = ["1","1","1"], target = "11" + +**Output:** 6 + +**Explanation:** Valid pairs are: + +- (0, 1): "1" + "1" + +- (1, 0): "1" + "1" + +- (0, 2): "1" + "1" + +- (2, 0): "1" + "1" + +- (1, 2): "1" + "1" + +- (2, 1): "1" + "1" + +**Constraints:** + +* `2 <= nums.length <= 100` +* `1 <= nums[i].length <= 100` +* `2 <= target.length <= 100` +* `nums[i]` and `target` consist of digits. +* `nums[i]` and `target` do not have leading zeros. + +## Solution + +```kotlin +class Solution { + fun numOfPairs(nums: Array, target: String): Int { + var ans = 0 + for (i in nums.indices) { + for (j in nums.indices) { + if (i != j) { + val con = nums[i] + nums[j] + if (con == target) { + ans++ + } + } + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2024_maximize_the_confusion_of_an_exam/readme.md b/src/main/kotlin/g2001_2100/s2024_maximize_the_confusion_of_an_exam/readme.md new file mode 100644 index 00000000..24150bc3 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2024_maximize_the_confusion_of_an_exam/readme.md @@ -0,0 +1,112 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2024\. Maximize the Confusion of an Exam + +Medium + +A teacher is writing a test with `n` true/false questions, with `'T'` denoting true and `'F'` denoting false. He wants to confuse the students by **maximizing** the number of **consecutive** questions with the **same** answer (multiple trues or multiple falses in a row). + +You are given a string `answerKey`, where `answerKey[i]` is the original answer to the ith question. In addition, you are given an integer `k`, the maximum number of times you may perform the following operation: + +* Change the answer key for any question to `'T'` or `'F'` (i.e., set `answerKey[i]` to `'T'` or `'F'`). + +Return _the **maximum** number of consecutive_ `'T'`s or `'F'`s _in the answer key after performing the operation at most_ `k` _times_. + +**Example 1:** + +**Input:** answerKey = "TTFF", k = 2 + +**Output:** 4 + +**Explanation:** We can replace both the 'F's with 'T's to make answerKey = "TTTT". + +There are four consecutive 'T's. + +**Example 2:** + +**Input:** answerKey = "TFFT", k = 1 + +**Output:** 3 + +**Explanation:** We can replace the first 'T' with an 'F' to make answerKey = "FFFT". + +Alternatively, we can replace the second 'T' with an 'F' to make answerKey = "TFFF". + +In both cases, there are three consecutive 'F's. + +**Example 3:** + +**Input:** answerKey = "TTFTTFTT", k = 1 + +**Output:** 5 + +**Explanation:** We can replace the first 'F' to make answerKey = "TTTTTFTT" + +Alternatively, we can replace the second 'F' to make answerKey = "TTFTTTTT". + +In both cases, there are five consecutive 'T's. + +**Constraints:** + +* `n == answerKey.length` +* 1 <= n <= 5 * 104 +* `answerKey[i]` is either `'T'` or `'F'` +* `1 <= k <= n` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun maxConsecutiveAnswers(answerKey: String, k: Int): Int { + var k = k + var max: Int + var right = 0 + val originalK = k + while (k > 0 && right < answerKey.length) { + if (answerKey[right] == 'T') { + k-- + } + right++ + } + max = right + var left = 0 + while (right < answerKey.length && left < answerKey.length) { + if (answerKey[right] == 'F') { + right++ + max = Math.max(max, right - left) + } else { + while (left < right && answerKey[left] == 'F') { + left++ + } + left++ + right++ + } + } + right = 0 + k = originalK + while (k > 0 && right < answerKey.length) { + if (answerKey[right] == 'F') { + k-- + } + right++ + } + max = Math.max(max, right) + left = 0 + while (right < answerKey.length && left < answerKey.length) { + if (answerKey[right] == 'T') { + right++ + max = Math.max(max, right - left) + } else { + while (left < right && answerKey[left] == 'T') { + left++ + } + left++ + right++ + } + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2025_maximum_number_of_ways_to_partition_an_array/readme.md b/src/main/kotlin/g2001_2100/s2025_maximum_number_of_ways_to_partition_an_array/readme.md new file mode 100644 index 00000000..1122640d --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2025_maximum_number_of_ways_to_partition_an_array/readme.md @@ -0,0 +1,120 @@ +[![](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) + +## 2025\. Maximum Number of Ways to Partition an Array + +Hard + +You are given a **0-indexed** integer array `nums` of length `n`. The number of ways to **partition** `nums` is the number of `pivot` indices that satisfy both conditions: + +* `1 <= pivot < n` +* `nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]` + +You are also given an integer `k`. You can choose to change the value of **one** element of `nums` to `k`, or to leave the array **unchanged**. + +Return _the **maximum** possible number of ways to **partition**_ `nums` _to satisfy both conditions after changing **at most** one element_. + +**Example 1:** + +**Input:** nums = [2,-1,2], k = 3 + +**Output:** 1 + +**Explanation:** One optimal approach is to change nums[0] to k. The array becomes [**3**,-1,2]. + +There is one way to partition the array: + +- For pivot = 2, we have the partition [3,-1 \| 2]: 3 + -1 == 2. + +**Example 2:** + +**Input:** nums = [0,0,0], k = 1 + +**Output:** 2 + +**Explanation:** The optimal approach is to leave the array unchanged. + +There are two ways to partition the array: + +- For pivot = 1, we have the partition [0 \| 0,0]: 0 == 0 + 0. + +- For pivot = 2, we have the partition [0,0 \| 0]: 0 + 0 == 0. + +**Example 3:** + +**Input:** nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33 + +**Output:** 4 + +**Explanation:** One optimal approach is to change nums[2] to k. The array becomes [22,4,**\-33**,-20,-15,15,-16,7,19,-10,0,-13,-14]. + +There are four ways to partition the array. + +**Constraints:** + +* `n == nums.length` +* 2 <= n <= 105 +* -105 <= k, nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun waysToPartition(nums: IntArray, k: Int): Int { + val n = nums.size + val ps = LongArray(n) + ps[0] = nums[0].toLong() + for (i in 1 until n) { + ps[i] = ps[i - 1] + nums[i] + } + val partDiffs: MutableMap> = HashMap() + var maxWays = 0 + for (i in 1 until n) { + val partL = ps[i - 1] + val partR = ps[n - 1] - partL + val partDiff = partR - partL + if (partDiff == 0L) { + maxWays++ + } + val idxSet = partDiffs.computeIfAbsent(partDiff) { _: Long? -> ArrayList() } + idxSet.add(i) + } + for (j in 0 until n) { + var ways = 0 + val newDiff = k.toLong() - nums[j] + val leftList = partDiffs[newDiff] + if (leftList != null) { + val i = upperBound(leftList, j) + ways += leftList.size - i + } + val rightList = partDiffs[-newDiff] + if (rightList != null) { + val i = upperBound(rightList, j) + ways += i + } + maxWays = Math.max(ways, maxWays) + } + return maxWays + } + + private fun upperBound(arr: List, `val`: Int): Int { + var ans = -1 + val n = arr.size + var l = 0 + var r = n + while (l <= r) { + val mid = l + (r - l) / 2 + if (mid == n) { + return n + } + if (arr[mid] > `val`) { + ans = mid + r = mid - 1 + } else { + l = mid + 1 + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2027_minimum_moves_to_convert_string/readme.md b/src/main/kotlin/g2001_2100/s2027_minimum_moves_to_convert_string/readme.md new file mode 100644 index 00000000..c009c09e --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2027_minimum_moves_to_convert_string/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) + +## 2027\. Minimum Moves to Convert String + +Easy + +You are given a string `s` consisting of `n` characters which are either `'X'` or `'O'`. + +A **move** is defined as selecting **three** **consecutive characters** of `s` and converting them to `'O'`. Note that if a move is applied to the character `'O'`, it will stay the **same**. + +Return _the **minimum** number of moves required so that all the characters of_ `s` _are converted to_ `'O'`. + +**Example 1:** + +**Input:** s = "XXX" + +**Output:** 1 + +**Explanation:** XXX -> OOO We select all the 3 characters and convert them in one move. + +**Example 2:** + +**Input:** s = "XXOX" + +**Output:** 2 + +**Explanation:** XXOX -> OOOX -> OOOO + +We select the first 3 characters in the first move, and convert them to `'O'`. + +Then we select the last 3 characters and convert them so that the final string contains all `'O'`s. + +**Example 3:** + +**Input:** s = "OOOO" + +**Output:** 0 + +**Explanation:** There are no `'X's` in `s` to convert. + +**Constraints:** + +* `3 <= s.length <= 1000` +* `s[i]` is either `'X'` or `'O'`. + +## Solution + +```kotlin +class Solution { + fun minimumMoves(s: String): Int { + var r = 0 + var i = 0 + val sArray = s.toCharArray() + while (i < sArray.size) { + if (sArray[i] == 'X') { + r++ + i += 2 + } + i++ + } + return r + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2028_find_missing_observations/readme.md b/src/main/kotlin/g2001_2100/s2028_find_missing_observations/readme.md new file mode 100644 index 00000000..c0398000 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2028_find_missing_observations/readme.md @@ -0,0 +1,76 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2028\. Find Missing Observations + +Medium + +You have observations of `n + m` **6-sided** dice rolls with each face numbered from `1` to `6`. `n` of the observations went missing, and you only have the observations of `m` rolls. Fortunately, you have also calculated the **average value** of the `n + m` rolls. + +You are given an integer array `rolls` of length `m` where `rolls[i]` is the value of the ith observation. You are also given the two integers `mean` and `n`. + +Return _an array of length_ `n` _containing the missing observations such that the **average value** of the_ `n + m` _rolls is **exactly**_ `mean`. If there are multiple valid answers, return _any of them_. If no such array exists, return _an empty array_. + +The **average value** of a set of `k` numbers is the sum of the numbers divided by `k`. + +Note that `mean` is an integer, so the sum of the `n + m` rolls should be divisible by `n + m`. + +**Example 1:** + +**Input:** rolls = [3,2,4,3], mean = 4, n = 2 + +**Output:** [6,6] + +**Explanation:** The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4. + +**Example 2:** + +**Input:** rolls = [1,5,6], mean = 3, n = 4 + +**Output:** [2,3,2,2] + +**Explanation:** The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3. + +**Example 3:** + +**Input:** rolls = [1,2,3,4], mean = 6, n = 4 + +**Output:** [] + +**Explanation:** It is impossible for the mean to be 6 no matter what the 4 missing rolls are. + +**Constraints:** + +* `m == rolls.length` +* 1 <= n, m <= 105 +* `1 <= rolls[i], mean <= 6` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun missingRolls(rolls: IntArray, mean: Int, n: Int): IntArray { + var n = n + val m = rolls.size + var msum = 0 + val res = IntArray(n) + for (roll in rolls) { + msum += roll + } + var totalmn = mean * (m + n) - msum + if (totalmn < n || totalmn > n * 6) { + return IntArray(0) + } + var j = 0 + while (totalmn > 0) { + val dice = Math.min(6, totalmn - n + 1) + res[j] = dice + totalmn = totalmn - dice + n-- + j++ + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2029_stone_game_ix/readme.md b/src/main/kotlin/g2001_2100/s2029_stone_game_ix/readme.md new file mode 100644 index 00000000..675262b4 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2029_stone_game_ix/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) + +## 2029\. Stone Game IX + +Medium + +Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array `stones`, where `stones[i]` is the **value** of the ith stone. + +Alice and Bob take turns, with **Alice** starting first. On each turn, the player may remove any stone from `stones`. The player who removes a stone **loses** if the **sum** of the values of **all removed stones** is divisible by `3`. Bob will win automatically if there are no remaining stones (even if it is Alice's turn). + +Assuming both players play **optimally**, return `true` _if Alice wins and_ `false` _if Bob wins_. + +**Example 1:** + +**Input:** stones = [2,1] + +**Output:** true + +**Explanation:** The game will be played as follows: + +- Turn 1: Alice can remove either stone. + +- Turn 2: Bob removes the remaining stone. + +The sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game. + +**Example 2:** + +**Input:** stones = [2] + +**Output:** false + +**Explanation:** Alice will remove the only stone, and the sum of the values on the removed stones is 2. + +Since all the stones are removed and the sum of values is not divisible by 3, Bob wins the game. + +**Example 3:** + +**Input:** stones = [5,1,2,4,3] + +**Output:** false + +**Explanation:** Bob will always win. One possible way for Bob to win is shown below: + +- Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1. + +- Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4. + +- Turn 3: Alices removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8. + +- Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10. + +- Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15. + +Alice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game. + +**Constraints:** + +* 1 <= stones.length <= 105 +* 1 <= stones[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun stoneGameIX(stones: IntArray): Boolean { + var zero = 0 + var one = 0 + var two = 0 + for (i in stones) { + if (i % 3 == 0) { + zero++ + } else if (i % 3 == 1) { + one++ + } else if (i % 3 == 2) { + two++ + } + } + if (one == 0 && two == 0) { + return false + } + val max = Math.max(one, two) + val min = Math.min(one, two) + if (zero % 2 == 0) { + return min != 0 + } + return if (zero % 2 == 1) { + max - 2 > min + } else false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2030_smallest_k_length_subsequence_with_occurrences_of_a_letter/readme.md b/src/main/kotlin/g2001_2100/s2030_smallest_k_length_subsequence_with_occurrences_of_a_letter/readme.md new file mode 100644 index 00000000..fcb7b998 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2030_smallest_k_length_subsequence_with_occurrences_of_a_letter/readme.md @@ -0,0 +1,87 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2030\. Smallest K-Length Subsequence With Occurrences of a Letter + +Hard + +You are given a string `s`, an integer `k`, a letter `letter`, and an integer `repetition`. + +Return _the **lexicographically smallest** subsequence of_ `s` _of length_ `k` _that has the letter_ `letter` _appear **at least**_ `repetition` _times_. The test cases are generated so that the `letter` appears in `s` **at least** `repetition` times. + +A **subsequence** is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. + +A string `a` is **lexicographically smaller** than a string `b` if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. + +**Example 1:** + +**Input:** s = "leet", k = 3, letter = "e", repetition = 1 + +**Output:** "eet" + +**Explanation:** There are four subsequences of length 3 that have the letter 'e' appear at least 1 time: + +- "lee" (from "**lee**t") + +- "let" (from "**le**e**t**") + +- "let" (from "**l**e**et**") + +- "eet" (from "l**eet**") + +The lexicographically smallest subsequence among them is "eet". + +**Example 2:** + +![example-2](https://assets.leetcode.com/uploads/2021/09/13/smallest-k-length-subsequence.png) + +**Input:** s = "leetcode", k = 4, letter = "e", repetition = 2 + +**Output:** "ecde" + +**Explanation:** "ecde" is the lexicographically smallest subsequence of length 4 that has the letter "e" appear at least 2 times. + +**Example 3:** + +**Input:** s = "bb", k = 2, letter = "b", repetition = 2 + +**Output:** "bb" + +**Explanation:** "bb" is the only subsequence of length 2 that has the letter "b" appear at least 2 times. + +**Constraints:** + +* 1 <= repetition <= k <= s.length <= 5 * 104 +* `s` consists of lowercase English letters. +* `letter` is a lowercase English letter, and appears in `s` at least `repetition` times. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun smallestSubsequence(s: String, k: Int, letter: Char, repetition: Int): String { + var repetition = repetition + var count = 0 + for (c in s.toCharArray()) { + count += if (c == letter) 1 else 0 + } + val sb = StringBuilder() + var i = 0 + while (i < s.length) { + while (sb.length + s.length > i + k && sb.isNotEmpty() && + s[i] < sb[sb.length - 1] && (sb[sb.length - 1] != letter || count != repetition) + ) { + repetition += if (sb[sb.length - 1] == letter) 1 else 0 + sb.setLength(sb.length - 1) + } + if (k - sb.length > Math.max(0, if (s[i] == letter) 0 else repetition)) { + sb.append(s[i]) + repetition -= if (s[i] == letter) 1 else 0 + } + count -= if (s[i++] == letter) 1 else 0 + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2032_two_out_of_three/readme.md b/src/main/kotlin/g2001_2100/s2032_two_out_of_three/readme.md new file mode 100644 index 00000000..0427ad73 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2032_two_out_of_three/readme.md @@ -0,0 +1,87 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2032\. Two Out of Three + +Easy + +Given three integer arrays `nums1`, `nums2`, and `nums3`, return _a **distinct** array containing all the values that are present in **at least two** out of the three arrays. You may return the values in **any** order_. + +**Example 1:** + +**Input:** nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3] + +**Output:** [3,2] + +**Explanation:** The values that are present in at least two arrays are: + +- 3, in all three arrays. + +- 2, in nums1 and nums2. + +**Example 2:** + +**Input:** nums1 = [3,1], nums2 = [2,3], nums3 = [1,2] + +**Output:** [2,3,1] + +**Explanation:** The values that are present in at least two arrays are: + +- 2, in nums2 and nums3. + +- 3, in nums1 and nums2. + +- 1, in nums1 and nums3. + +**Example 3:** + +**Input:** nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5] + +**Output:** [] + +**Explanation:** No value is present in at least two arrays. + +**Constraints:** + +* `1 <= nums1.length, nums2.length, nums3.length <= 100` +* `1 <= nums1[i], nums2[j], nums3[k] <= 100` + +## Solution + +```kotlin +class Solution { + fun twoOutOfThree(nums1: IntArray, nums2: IntArray, nums3: IntArray): List { + val ans: MutableSet = HashSet() + val set1: MutableSet = HashSet() + for (i in nums1) { + set1.add(i) + } + val set2: MutableSet = HashSet() + for (i in nums2) { + set2.add(i) + } + val set3: MutableSet = HashSet() + for (i in nums3) { + set3.add(i) + } + for (j in nums1) { + if (set2.contains(j) || set3.contains(j)) { + ans.add(j) + } + } + for (j in nums2) { + if (set1.contains(j) || set3.contains(j)) { + ans.add(j) + } + } + for (j in nums3) { + if (set1.contains(j) || set2.contains(j)) { + ans.add(j) + } + } + val result: MutableList = ArrayList() + result.addAll(ans) + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2033_minimum_operations_to_make_a_uni_value_grid/readme.md b/src/main/kotlin/g2001_2100/s2033_minimum_operations_to_make_a_uni_value_grid/readme.md new file mode 100644 index 00000000..ca2c0d1e --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2033_minimum_operations_to_make_a_uni_value_grid/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) + +## 2033\. Minimum Operations to Make a Uni-Value Grid + +Medium + +You are given a 2D integer `grid` of size `m x n` and an integer `x`. In one operation, you can **add** `x` to or **subtract** `x` from any element in the `grid`. + +A **uni-value grid** is a grid where all the elements of it are equal. + +Return _the **minimum** number of operations to make the grid **uni-value**_. If it is not possible, return `-1`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/09/21/gridtxt.png) + +**Input:** grid = \[\[2,4],[6,8]], x = 2 + +**Output:** 4 + +**Explanation:** We can make every element equal to 4 by doing the following: + +- Add x to 2 once. + +- Subtract x from 6 once. + +- Subtract x from 8 twice. + +A total of 4 operations were used. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/09/21/gridtxt-1.png) + +**Input:** grid = \[\[1,5],[2,3]], x = 1 + +**Output:** 5 + +**Explanation:** We can make every element equal to 3. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/09/21/gridtxt-2.png) + +**Input:** grid = \[\[1,2],[3,4]], x = 2 + +**Output:** -1 + +**Explanation:** It is impossible to make every element equal. + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* 1 <= m, n <= 105 +* 1 <= m * n <= 105 +* 1 <= x, grid[i][j] <= 104 + +## Solution + +```kotlin +class Solution { + fun minOperations(grid: Array, x: Int): Int { + val arr = IntArray(grid.size * grid[0].size) + var k = 0 + for (ints in grid) { + for (j in grid[0].indices) { + arr[k] = ints[j] + k++ + } + } + arr.sort() + val target = arr[arr.size / 2] + var res = 0 + for (i in arr.indices) { + res += if (i < arr.size / 2) { + val rem = target - arr[i] + if (rem % x != 0) { + return -1 + } + rem / x + } else { + val rem = arr[i] - target + if (rem % x != 0) { + return -1 + } + rem / x + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2034_stock_price_fluctuation/readme.md b/src/main/kotlin/g2001_2100/s2034_stock_price_fluctuation/readme.md new file mode 100644 index 00000000..6b9fb607 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2034_stock_price_fluctuation/readme.md @@ -0,0 +1,117 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2034\. Stock Price Fluctuation + +Medium + +You are given a stream of **records** about a particular stock. Each record contains a **timestamp** and the corresponding **price** of the stock at that timestamp. + +Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream **correcting** the price of the previous wrong record. + +Design an algorithm that: + +* **Updates** the price of the stock at a particular timestamp, **correcting** the price from any previous records at the timestamp. +* Finds the **latest price** of the stock based on the current records. The **latest price** is the price at the latest timestamp recorded. +* Finds the **maximum price** the stock has been based on the current records. +* Finds the **minimum price** the stock has been based on the current records. + +Implement the `StockPrice` class: + +* `StockPrice()` Initializes the object with no price records. +* `void update(int timestamp, int price)` Updates the `price` of the stock at the given `timestamp`. +* `int current()` Returns the **latest price** of the stock. +* `int maximum()` Returns the **maximum price** of the stock. +* `int minimum()` Returns the **minimum price** of the stock. + +**Example 1:** + +**Input** ["StockPrice", "update", "update", "current", "maximum", "update", "maximum", "update", "minimum"] [[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []] + +**Output:** [null, null, null, 5, 10, null, 5, null, 2] + +**Explanation:** + +StockPrice stockPrice = new StockPrice(); + +stockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10]. + +stockPrice.update(2, 5); // Timestamps are [1,2] with corresponding prices [10,5]. + +stockPrice.current(); // return 5, the latest timestamp is 2 with the price being 5. + +stockPrice.maximum(); // return 10, the maximum price is 10 at timestamp 1. + +stockPrice.update(1, 3); // The previous timestamp 1 had the wrong price, so it is updated to 3. // Timestamps are [1,2] with corresponding prices [3,5]. + +stockPrice.maximum(); // return 5, the maximum price is 5 after the correction. + +stockPrice.update(4, 2); // Timestamps are [1,2,4] with corresponding prices [3,5,2]. + +stockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4. + +**Constraints:** + +* 1 <= timestamp, price <= 109 +* At most 105 calls will be made **in total** to `update`, `current`, `maximum`, and `minimum`. +* `current`, `maximum`, and `minimum` will be called **only after** `update` has been called **at least once**. + +## Solution + +```kotlin +import java.util.PriorityQueue + +class StockPrice { + private class Record(var time: Int, var price: Int) + + private val map: MutableMap + private val maxHeap: PriorityQueue + private val minHeap: PriorityQueue + private var latestTimestamp = 0 + + init { + map = HashMap() + maxHeap = PriorityQueue { r1: Record, r2: Record -> Integer.compare(r2.price, r1.price) } + minHeap = PriorityQueue { r1: Record, r2: Record -> Integer.compare(r1.price, r2.price) } + } + + fun update(timestamp: Int, price: Int) { + latestTimestamp = Math.max(timestamp, latestTimestamp) + maxHeap.offer(Record(timestamp, price)) + minHeap.offer(Record(timestamp, price)) + map[timestamp] = price + } + + fun current(): Int { + return map[latestTimestamp]!! + } + + fun maximum(): Int { + while (true) { + val rec = maxHeap.peek() + if (map[rec.time] == rec.price) { + return rec.price + } + maxHeap.poll() + } + } + + fun minimum(): Int { + while (true) { + val rec = minHeap.peek() + if (map[rec.time] == rec.price) { + return rec.price + } + minHeap.poll() + } + } +} +/* + * Your StockPrice object will be instantiated and called as such: + * var obj = StockPrice() + * obj.update(timestamp,price) + * var param_2 = obj.current() + * var param_3 = obj.maximum() + * var param_4 = obj.minimum() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2035_partition_array_into_two_arrays_to_minimize_sum_difference/readme.md b/src/main/kotlin/g2001_2100/s2035_partition_array_into_two_arrays_to_minimize_sum_difference/readme.md new file mode 100644 index 00000000..be878dab --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2035_partition_array_into_two_arrays_to_minimize_sum_difference/readme.md @@ -0,0 +1,114 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2035\. Partition Array Into Two Arrays to Minimize Sum Difference + +Hard + +You are given an integer array `nums` of `2 * n` integers. You need to partition `nums` into **two** arrays of length `n` to **minimize the absolute difference** of the **sums** of the arrays. To partition `nums`, put each element of `nums` into **one** of the two arrays. + +Return _the **minimum** possible absolute difference_. + +**Example 1:** + +![example-1](https://assets.leetcode.com/uploads/2021/10/02/ex1.png) + +**Input:** nums = [3,9,7,3] + +**Output:** 2 + +**Explanation:** One optimal partition is: [3,9] and [7,3]. The absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2. + +**Example 2:** + +**Input:** nums = [-36,36] + +**Output:** 72 + +**Explanation:** One optimal partition is: [-36] and [36]. The absolute difference between the sums of the arrays is abs((-36) - (36)) = 72. + +**Example 3:** + +![example-3](https://assets.leetcode.com/uploads/2021/10/02/ex3.png) + +**Input:** nums = [2,-1,0,4,-2,-9] + +**Output:** 0 + +**Explanation:** One optimal partition is: [2,4,-9] and [-1,0,-2]. The absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0. + +**Constraints:** + +* `1 <= n <= 15` +* `nums.length == 2 * n` +* -107 <= nums[i] <= 107 + +## Solution + +```kotlin +class Solution { + fun minimumDifference(nums: IntArray): Int { + if (nums.isEmpty()) { + return -1 + } + val n = nums.size / 2 + var sum = 0 + val arr1: MutableList> = ArrayList() + val arr2: MutableList> = ArrayList() + for (i in 0..n) { + arr1.add(ArrayList()) + arr2.add(ArrayList()) + if (i < n) { + sum += nums[i] + sum += nums[i + n] + } + } + for (state in 0 until (1 shl n)) { + var sum1 = 0 + var sum2 = 0 + for (i in 0 until n) { + if (state and (1 shl i) == 0) { + continue + } + val a1 = nums[i] + val a2 = nums[i + n] + sum1 += a1 + sum2 += a2 + } + val numOfEleInSet = Integer.bitCount(state) + arr1[numOfEleInSet].add(sum1) + arr2[numOfEleInSet].add(sum2) + } + for (i in 0..n) { + arr2[i].sort() + } + var min = Int.MAX_VALUE + for (i in 0..n) { + val sums1: List = arr1[i] + val sums2: List = arr2[n - i] + for (s1 in sums1) { + var idx = sums2.binarySearch(sum / 2 - s1) + if (idx < 0) { + idx = -(idx + 1) + } + if (idx < sums1.size) { + min = Math.min( + min, + Math.abs(sum - s1 - sums2[idx] - (sums2[idx] + s1)) + ) + } + if (idx - 1 >= 0) { + min = Math.min( + min, + Math.abs( + sum - s1 - sums2[idx - 1] - + (sums2[idx - 1] + s1) + ) + ) + } + } + } + return min + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2037_minimum_number_of_moves_to_seat_everyone/readme.md b/src/main/kotlin/g2001_2100/s2037_minimum_number_of_moves_to_seat_everyone/readme.md new file mode 100644 index 00000000..c40d5913 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2037_minimum_number_of_moves_to_seat_everyone/readme.md @@ -0,0 +1,96 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2037\. Minimum Number of Moves to Seat Everyone + +Easy + +There are `n` seats and `n` students in a room. You are given an array `seats` of length `n`, where `seats[i]` is the position of the ith seat. You are also given the array `students` of length `n`, where `students[j]` is the position of the jth student. + +You may perform the following move any number of times: + +* Increase or decrease the position of the ith student by `1` (i.e., moving the ith student from position `x` to `x + 1` or `x - 1`) + +Return _the **minimum number of moves** required to move each student to a seat_ _such that no two students are in the same seat._ + +Note that there may be **multiple** seats or students in the **same** position at the beginning. + +**Example 1:** + +**Input:** seats = [3,1,5], students = [2,7,4] + +**Output:** 4 + +**Explanation:** + +The students are moved as follows: + +- The first student is moved from from position 2 to position 1 using 1 move. + +- The second student is moved from from position 7 to position 5 using 2 moves. + +- The third student is moved from from position 4 to position 3 using 1 move. + +In total, 1 + 2 + 1 = 4 moves were used. + +**Example 2:** + +**Input:** seats = [4,1,5,9], students = [1,3,2,6] + +**Output:** 7 + +**Explanation:** + +The students are moved as follows: + +- The first student is not moved. + +- The second student is moved from from position 3 to position 4 using 1 move. + +- The third student is moved from from position 2 to position 5 using 3 moves. + +- The fourth student is moved from from position 6 to position 9 using 3 moves. + +In total, 0 + 1 + 3 + 3 = 7 moves were used. + +**Example 3:** + +**Input:** seats = [2,2,6,6], students = [1,3,2,6] + +**Output:** 4 + +**Explanation:** Note that there are two seats at position 2 and two seats at position 6. + +The students are moved as follows: + +- The first student is moved from from position 1 to position 2 using 1 move. + +- The second student is moved from from position 3 to position 6 using 3 moves. + +- The third student is not moved. + +- The fourth student is not moved. + +In total, 1 + 3 + 0 + 0 = 4 moves were used. + +**Constraints:** + +* `n == seats.length == students.length` +* `1 <= n <= 100` +* `1 <= seats[i], students[j] <= 100` + +## Solution + +```kotlin +class Solution { + fun minMovesToSeat(seats: IntArray, students: IntArray): Int { + var ans = 0 + seats.sort() + students.sort() + for (i in seats.indices) { + ans += Math.abs(seats[i] - students[i]) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2038_remove_colored_pieces_if_both_neighbors_are_the_same_color/readme.md b/src/main/kotlin/g2001_2100/s2038_remove_colored_pieces_if_both_neighbors_are_the_same_color/readme.md new file mode 100644 index 00000000..ce5b3639 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2038_remove_colored_pieces_if_both_neighbors_are_the_same_color/readme.md @@ -0,0 +1,102 @@ +[![](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) + +## 2038\. Remove Colored Pieces if Both Neighbors are the Same Color + +Medium + +There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the ith piece. + +Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice moves **first**. + +* Alice is only allowed to remove a piece colored `'A'` if **both its neighbors** are also colored `'A'`. She is **not allowed** to remove pieces that are colored `'B'`. +* Bob is only allowed to remove a piece colored `'B'` if **both its neighbors** are also colored `'B'`. He is **not allowed** to remove pieces that are colored `'A'`. +* Alice and Bob **cannot** remove pieces from the edge of the line. +* If a player cannot make a move on their turn, that player **loses** and the other player **wins**. + +Assuming Alice and Bob play optimally, return `true` _if Alice wins, or return_ `false` _if Bob wins_. + +**Example 1:** + +**Input:** colors = "AAABABB" + +**Output:** true + +**Explanation:** + +AAABABB -> AABABB + +Alice moves first. + +She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'. + +Now it's Bob's turn. + +Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'. + +Thus, Alice wins, so return true. + +**Example 2:** + +**Input:** colors = "AA" + +**Output:** false + +**Explanation:** + +Alice has her turn first. + +There are only two 'A's and both are on the edge of the line, so she cannot move on her turn. + +Thus, Bob wins, so return false. + +**Example 3:** + +**Input:** colors = "ABBBBBBBAAA" + +**Output:** false + +**Explanation:** + +ABBBBBBBAAA -> ABBBBBBBAA + +Alice moves first. + +Her only option is to remove the second to last 'A' from the right. + +ABBBBBBBAA -> ABBBBBBAA + +Next is Bob's turn. + +He has many options for which 'B' piece to remove. + +He can pick any. On Alice's second turn, she has no more pieces that she can remove. + +Thus, Bob wins, so return false. + +**Constraints:** + +* 1 <= colors.length <= 105 +* `colors` consists of only the letters `'A'` and `'B'` + +## Solution + +```kotlin +class Solution { + fun winnerOfGame(colors: String): Boolean { + var ans = 0 + for (i in 1 until colors.length - 1) { + if (colors[i] == colors[i - 1] && + colors[i] == colors[i + 1] + ) { + if (colors[i] == 'A') { + ans++ + } else { + ans-- + } + } + } + return ans > 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2039_the_time_when_the_network_becomes_idle/readme.md b/src/main/kotlin/g2001_2100/s2039_the_time_when_the_network_becomes_idle/readme.md new file mode 100644 index 00000000..bef1f9ec --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2039_the_time_when_the_network_becomes_idle/readme.md @@ -0,0 +1,146 @@ +[![](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) + +## 2039\. The Time When the Network Becomes Idle + +Medium + +There is a network of `n` servers, labeled from `0` to `n - 1`. You are given a 2D integer array `edges`, where edges[i] = [ui, vi] indicates there is a message channel between servers ui and vi, and they can pass **any** number of messages to **each other** directly in **one** second. You are also given a **0-indexed** integer array `patience` of length `n`. + +All servers are **connected**, i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels. + +The server labeled `0` is the **master** server. The rest are **data** servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers **optimally**, so every message takes the **least amount of time** to arrive at the master server. The master server will process all newly arrived messages **instantly** and send a reply to the originating server via the **reversed path** the message had gone through. + +At the beginning of second `0`, each data server sends its message to be processed. Starting from second `1`, at the **beginning** of **every** second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server: + +* If it has not, it will **resend** the message periodically. The data server `i` will resend the message every `patience[i]` second(s), i.e., the data server `i` will resend the message if `patience[i]` second(s) have **elapsed** since the **last** time the message was sent from this server. +* Otherwise, **no more resending** will occur from this server. + +The network becomes **idle** when there are **no** messages passing between servers or arriving at servers. + +Return _the **earliest second** starting from which the network becomes **idle**_. + +**Example 1:** + +![example 1](https://assets.leetcode.com/uploads/2021/09/22/quiet-place-example1.png) + +**Input:** edges = \[\[0,1],[1,2]], patience = [0,2,1] + +**Output:** 8 + +**Explanation:** + +At (the beginning of) second 0, + +- Data server 1 sends its message (denoted 1A) to the master server. + +- Data server 2 sends its message (denoted 2A) to the master server. + + +At second 1, + +- Message 1A arrives at the master server. Master server processes message 1A instantly and sends a reply 1A back. + +- Server 1 has not received any reply. 1 second (1 < patience[1] = 2) elapsed since this server has sent the message, therefore it does not resend the message. + +- Server 2 has not received any reply. 1 second (1 == patience[2] = 1) elapsed since this server has sent the message, therefore it resends the message (denoted 2B). + + +At second 2, + +- The reply 1A arrives at server 1. No more resending will occur from server 1. + +- Message 2A arrives at the master server. Master server processes message 2A instantly and sends a reply 2A back. + +- Server 2 resends the message (denoted 2C). + +... + +At second 4, + +- The reply 2A arrives at server 2. No more resending will occur from server 2. + +... + +At second 7, reply 2D arrives at server 2. + + +Starting from the beginning of the second 8, there are no messages passing between servers or arriving at servers. + +This is the time when the network becomes idle. + +**Example 2:** + +![example 2](https://assets.leetcode.com/uploads/2021/09/04/network_a_quiet_place_2.png) + +**Input:** edges = \[\[0,1],[0,2],[1,2]], patience = [0,10,10] + +**Output:** 3 + +**Explanation:** Data servers 1 and 2 receive a reply back at the beginning of second 2. + +From the beginning of the second 3, the network becomes idle. + +**Constraints:** + +* `n == patience.length` +* 2 <= n <= 105 +* `patience[0] == 0` +* 1 <= patience[i] <= 105 for `1 <= i < n` +* 1 <= edges.length <= min(105, n * (n - 1) / 2) +* `edges[i].length == 2` +* 0 <= ui, vi < n +* ui != vi +* There are no duplicate edges. +* Each server can directly or indirectly reach another server. + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + fun networkBecomesIdle(edges: Array, pat: IntArray): Int { + val n = pat.size + val adj = ArrayList>() + for (i in 0 until n) { + adj.add(ArrayList()) + } + for (arr in edges) { + adj[arr[0]].add(arr[1]) + adj[arr[1]].add(arr[0]) + } + val distance = IntArray(n) + distance.fill(99999) + distance[0] = 0 + val pq = PriorityQueue { a1: IntArray, a2: IntArray -> + Integer.compare( + a1[1], a2[1] + ) + } + pq.add(intArrayOf(0, 0)) + while (pq.isNotEmpty()) { + val a = pq.poll() + val node = a[0] + for (nn in adj[node]) { + if (distance[node] + 1 < distance[nn]) { + distance[nn] = 1 + distance[node] + pq.add(intArrayOf(nn, distance[nn])) + } + } + } + var max = 0 + for (i in 1 until n) { + val num1 = 2 * distance[i] + var num2 = num1 / pat[i] + if (num1 % pat[i] != 0) { + num2++ + } + num2-- + num2 *= pat[i] + max = Math.max(max, num2 + num1) + } + return max + 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2040_kth_smallest_product_of_two_sorted_arrays/readme.md b/src/main/kotlin/g2001_2100/s2040_kth_smallest_product_of_two_sorted_arrays/readme.md new file mode 100644 index 00000000..2c112e18 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2040_kth_smallest_product_of_two_sorted_arrays/readme.md @@ -0,0 +1,122 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2040\. Kth Smallest Product of Two Sorted Arrays + +Hard + +Given two **sorted 0-indexed** integer arrays `nums1` and `nums2` as well as an integer `k`, return _the_ kth _(**1-based**) smallest product of_ `nums1[i] * nums2[j]` _where_ `0 <= i < nums1.length` _and_ `0 <= j < nums2.length`. + +**Example 1:** + +**Input:** nums1 = [2,5], nums2 = [3,4], k = 2 + +**Output:** 8 + +**Explanation:** The 2 smallest products are: + +- nums1[0] \* nums2[0] = 2 \* 3 = 6 + +- nums1[0] \* nums2[1] = 2 \* 4 = 8 + +The 2nd smallest product is 8. + +**Example 2:** + +**Input:** nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6 + +**Output:** 0 + +**Explanation:** The 6 smallest products are: + +- nums1[0] \* nums2[1] = (-4) \* 4 = -16 + +- nums1[0] \* nums2[0] = (-4) \* 2 = -8 + +- nums1[1] \* nums2[1] = (-2) \* 4 = -8 + +- nums1[1] \* nums2[0] = (-2) \* 2 = -4 + +- nums1[2] \* nums2[0] = 0 \* 2 = 0 + +- nums1[2] \* nums2[1] = 0 \* 4 = 0 + +The 6th smallest product is 0. + +**Example 3:** + +**Input:** nums1 = [-2,-1,0,1,2], nums2 = [-3,-1,2,4,5], k = 3 + +**Output:** -6 + +**Explanation:** The 3 smallest products are: + +- nums1[0] \* nums2[4] = (-2) \* 5 = -10 + +- nums1[0] \* nums2[3] = (-2) \* 4 = -8 + +- nums1[4] \* nums2[0] = 2 \* (-3) = -6 + +The 3rd smallest product is -6. + +**Constraints:** + +* 1 <= nums1.length, nums2.length <= 5 * 104 +* -105 <= nums1[i], nums2[j] <= 105 +* `1 <= k <= nums1.length * nums2.length` +* `nums1` and `nums2` are sorted. + +## Solution + +```kotlin +class Solution { + fun kthSmallestProduct(nums1: IntArray, nums2: IntArray, k: Long): Long { + val n = nums2.size + var lo = -inf - 1 + var hi = inf + 1 + while (lo < hi) { + val mid = lo + (hi - lo shr 1) + var cnt: Long = 0 + for (i in nums1) { + var l = 0 + var r = n - 1 + var p = 0 + if (0 <= i) { + while (l <= r) { + val c = l + (r - l shr 1) + val mul = i * nums2[c].toLong() + if (mul <= mid) { + p = c + 1 + l = c + 1 + } else { + r = c - 1 + } + } + } else { + while (l <= r) { + val c = l + (r - l shr 1) + val mul = i * nums2[c].toLong() + if (mul <= mid) { + p = n - c + r = c - 1 + } else { + l = c + 1 + } + } + } + cnt += p.toLong() + } + if (cnt >= k) { + hi = mid + } else { + lo = mid + 1L + } + } + return lo + } + + companion object { + var inf = 1e10.toLong() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2042_check_if_numbers_are_ascending_in_a_sentence/readme.md b/src/main/kotlin/g2001_2100/s2042_check_if_numbers_are_ascending_in_a_sentence/readme.md new file mode 100644 index 00000000..a9d53039 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2042_check_if_numbers_are_ascending_in_a_sentence/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) + +## 2042\. Check if Numbers Are Ascending in a Sentence + +Easy + +A sentence is a list of **tokens** separated by a **single** space with no leading or trailing spaces. Every token is either a **positive number** consisting of digits `0-9` with no leading zeros, or a **word** consisting of lowercase English letters. + +* For example, `"a puppy has 2 eyes 4 legs"` is a sentence with seven tokens: `"2"` and `"4"` are numbers and the other tokens such as `"puppy"` are words. + +Given a string `s` representing a sentence, you need to check if **all** the numbers in `s` are **strictly increasing** from left to right (i.e., other than the last number, **each** number is **strictly smaller** than the number on its **right** in `s`). + +Return `true` _if so, or_ `false` _otherwise_. + +**Example 1:** + +![example-1](https://assets.leetcode.com/uploads/2021/09/30/example1.png) + +**Input:** s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles" + +**Output:** true + +**Explanation:** The numbers in s are: 1, 3, 4, 6, 12. They are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12. + +**Example 2:** + +**Input:** s = "hello world 5 x 5" + +**Output:** false + +**Explanation:** The numbers in s are: **5**, **5**. They are not strictly increasing. + +**Example 3:** + +![example-3](https://assets.leetcode.com/uploads/2021/09/30/example3.png) + +**Input:** s = "sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s" + +**Output:** false + +**Explanation:** The numbers in s are: 7, **51**, **50**, 60. They are not strictly increasing. + +**Constraints:** + +* `3 <= s.length <= 200` +* `s` consists of lowercase English letters, spaces, and digits from `0` to `9`, inclusive. +* The number of tokens in `s` is between `2` and `100`, inclusive. +* The tokens in `s` are separated by a single space. +* There are at least **two** numbers in `s`. +* Each number in `s` is a **positive** number **less** than `100`, with no leading zeros. +* `s` contains no leading or trailing spaces. + +## Solution + +```kotlin +class Solution { + fun areNumbersAscending(s: String): Boolean { + val words = s.split("\\ ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + var prev = 0 + for (word in words) { + if (Character.isDigit(word[0])) { + prev = if (word.toInt() <= prev) { + return false + } else { + word.toInt() + } + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2043_simple_bank_system/readme.md b/src/main/kotlin/g2001_2100/s2043_simple_bank_system/readme.md new file mode 100644 index 00000000..f04af5c1 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2043_simple_bank_system/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) + +## 2043\. Simple Bank System + +Medium + +You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has `n` accounts numbered from `1` to `n`. The initial balance of each account is stored in a **0-indexed** integer array `balance`, with the (i + 1)th account having an initial balance of `balance[i]`. + +Execute all the **valid** transactions. A transaction is **valid** if: + +* The given account number(s) are between `1` and `n`, and +* The amount of money withdrawn or transferred from is **less than or equal** to the balance of the account. + +Implement the `Bank` class: + +* `Bank(long[] balance)` Initializes the object with the **0-indexed** integer array `balance`. +* `boolean transfer(int account1, int account2, long money)` Transfers `money` dollars from the account numbered `account1` to the account numbered `account2`. Return `true` if the transaction was successful, `false` otherwise. +* `boolean deposit(int account, long money)` Deposit `money` dollars into the account numbered `account`. Return `true` if the transaction was successful, `false` otherwise. +* `boolean withdraw(int account, long money)` Withdraw `money` dollars from the account numbered `account`. Return `true` if the transaction was successful, `false` otherwise. + +**Example 1:** + +**Input** ["Bank", "withdraw", "transfer", "deposit", "transfer", "withdraw"] [[[10, 100, 20, 50, 30]], [3, 10], [5, 1, 20], [5, 20], [3, 4, 15], [10, 50]] + +**Output:** [null, true, true, true, false, false] + +**Explanation:** + +Bank bank = new Bank([10, 100, 20, 50, 30]); + +bank.withdraw(3, 10); // return true, account 3 has a balance of $20, so it is valid to withdraw $10. + // Account 3 has $20 - $10 = $10. + +bank.transfer(5, 1, 20); // return true, account 5 has a balance of $30, so it is valid to transfer $20. + // Account 5 has $30 - $20 = $10, and account 1 has $10 + $20 = $30. + +bank.deposit(5, 20); // return true, it is valid to deposit $20 to account 5. + // Account 5 has $10 + $20 = $30. + +bank.transfer(3, 4, 15); // return false, the current balance of account 3 is $10, + // so it is invalid to transfer $15 from it. + +bank.withdraw(10, 50); // return false, it is invalid because account 10 does not exist. + +**Constraints:** + +* `n == balance.length` +* 1 <= n, account, account1, account2 <= 105 +* 0 <= balance[i], money <= 1012 +* At most 104 calls will be made to **each** function `transfer`, `deposit`, `withdraw`. + +## Solution + +```kotlin +class Bank(private val accounts: LongArray) { + private fun validate(account: Int, money: Long, withdraw: Boolean): Boolean { + return account < accounts.size && (!withdraw || accounts[account] >= money) + } + + fun transfer(account1: Int, account2: Int, money: Long): Boolean { + if (validate(account1 - 1, money, true) && validate(account2 - 1, 0, false)) { + accounts[account1 - 1] -= money + accounts[account2 - 1] += money + return true + } + return false + } + + fun deposit(account: Int, money: Long): Boolean { + if (validate(account - 1, money, false)) { + accounts[account - 1] += money + return true + } + return false + } + + fun withdraw(account: Int, money: Long): Boolean { + if (validate(account - 1, money, true)) { + accounts[account - 1] -= money + return true + } + return false + } +} +/* + * Your Bank object will be instantiated and called as such: + * var obj = Bank(balance) + * var param_1 = obj.transfer(account1,account2,money) + * var param_2 = obj.deposit(account,money) + * var param_3 = obj.withdraw(account,money) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2044_count_number_of_maximum_bitwise_or_subsets/readme.md b/src/main/kotlin/g2001_2100/s2044_count_number_of_maximum_bitwise_or_subsets/readme.md new file mode 100644 index 00000000..9cedc74c --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2044_count_number_of_maximum_bitwise_or_subsets/readme.md @@ -0,0 +1,85 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2044\. Count Number of Maximum Bitwise-OR Subsets + +Medium + +Given an integer array `nums`, find the **maximum** possible **bitwise OR** of a subset of `nums` and return _the **number of different non-empty subsets** with the maximum bitwise OR_. + +An array `a` is a **subset** of an array `b` if `a` can be obtained from `b` by deleting some (possibly zero) elements of `b`. Two subsets are considered **different** if the indices of the elements chosen are different. + +The bitwise OR of an array `a` is equal to `a[0] **OR** a[1] **OR** ... **OR** a[a.length - 1]` (**0-indexed**). + +**Example 1:** + +**Input:** nums = [3,1] + +**Output:** 2 + +**Explanation:** The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3: + +- \[3] + +- \[3,1] + +**Example 2:** + +**Input:** nums = [2,2,2] + +**Output:** 7 + +**Explanation:** All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23 - 1 = 7 total subsets. + +**Example 3:** + +**Input:** nums = [3,2,1,5] + +**Output:** 6 + +**Explanation:** The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7: + +- \[3,5] + +- \[3,1,5] + +- \[3,2,5] + +- \[3,2,1,5] + +- \[2,5] + +- \[2,1,5] + +**Constraints:** + +* `1 <= nums.length <= 16` +* 1 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + private var count = 0 + fun countMaxOrSubsets(nums: IntArray): Int { + var lookfor = 0 + for (i in nums) { + lookfor = lookfor or i + } + countsub(nums, 0, lookfor, 0) + return count + } + + private fun countsub(nums: IntArray, index: Int, lookfor: Int, sofar: Int) { + if (lookfor == sofar) { + count++ + } + if (index >= nums.size) { + return + } + for (start in index until nums.size) { + countsub(nums, start + 1, lookfor, sofar or nums[start]) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2045_second_minimum_time_to_reach_destination/readme.md b/src/main/kotlin/g2001_2100/s2045_second_minimum_time_to_reach_destination/readme.md new file mode 100644 index 00000000..4de34825 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2045_second_minimum_time_to_reach_destination/readme.md @@ -0,0 +1,144 @@ +[![](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) + +## 2045\. Second Minimum Time to Reach Destination + +Hard + +A city is represented as a **bi-directional connected** graph with `n` vertices where each vertex is labeled from `1` to `n` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself. The time taken to traverse any edge is `time` minutes. + +Each vertex has a traffic signal which changes its color from **green** to **red** and vice versa every `change` minutes. All signals change **at the same time**. You can enter a vertex at **any time**, but can leave a vertex **only when the signal is green**. You **cannot wait** at a vertex if the signal is **green**. + +The **second minimum value** is defined as the smallest value **strictly larger** than the minimum value. + +* For example the second minimum value of `[2, 3, 4]` is `3`, and the second minimum value of `[2, 2, 4]` is `4`. + +Given `n`, `edges`, `time`, and `change`, return _the **second minimum time** it will take to go from vertex_ `1` _to vertex_ `n`. + +**Notes:** + +* You can go through any vertex **any** number of times, **including** `1` and `n`. +* You can assume that when the journey **starts**, all signals have just turned **green**. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/09/29/e1.png)         ![](https://assets.leetcode.com/uploads/2021/09/29/e2.png) + +**Input:** n = 5, edges = \[\[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5 + +**Output:** 13 + +**Explanation:** + +The figure on the left shows the given graph. + +The blue path in the figure on the right is the minimum time path. + +The time taken is: + +- Start at 1, time elapsed=0 + +- 1 -> 4: 3 minutes, time elapsed=3 + +- 4 -> 5: 3 minutes, time elapsed=6 + +Hence the minimum time needed is 6 minutes. + +The red path shows the path to get the second minimum time. + +- Start at 1, time elapsed=0 + +- 1 -> 3: 3 minutes, time elapsed=3 + +- 3 -> 4: 3 minutes, time elapsed=6 + +- Wait at 4 for 4 minutes, time elapsed=10 + +- 4 -> 5: 3 minutes, time elapsed=13 + +Hence the second minimum time is 13 minutes. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/09/29/eg2.png) + +**Input:** n = 2, edges = \[\[1,2]], time = 3, change = 2 + +**Output:** 11 + +**Explanation:** + +The minimum time path is 1 -> 2 with time = 3 minutes. + +The second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes. + +**Constraints:** + +* 2 <= n <= 104 +* n - 1 <= edges.length <= min(2 * 104, n * (n - 1) / 2) +* `edges[i].length == 2` +* 1 <= ui, vi <= n +* ui != vi +* There are no duplicate edges. +* Each vertex can be reached directly or indirectly from every other vertex. +* 1 <= time, change <= 103 + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + fun secondMinimum(n: Int, edges: Array, time: Int, change: Int): Int { + val adj: Array?> = arrayOfNulls(n) + for (i in adj.indices) { + adj[i] = ArrayList() + } + for (edge in edges) { + val p = edge[0] - 1 + val q = edge[1] - 1 + adj[p]?.add(q) + adj[q]?.add(p) + } + val dis1 = IntArray(n) + val dis2 = IntArray(n) + dis1.fill(Int.MAX_VALUE) + dis2.fill(Int.MAX_VALUE) + dis1[0] = 0 + val queue: Queue = LinkedList() + queue.offer(intArrayOf(0, 0)) + while (queue.isNotEmpty()) { + val temp = queue.poll() + val cur = temp[0] + val path = temp[1] + for (node in adj[cur]!!) { + val newPath = path + 1 + if (newPath < dis1[node]) { + dis2[node] = dis1[node] + dis1[node] = newPath + queue.offer(intArrayOf(node, newPath)) + } else if (newPath > dis1[node] && newPath < dis2[node]) { + dis2[node] = newPath + queue.offer(intArrayOf(node, newPath)) + } + } + } + return helper(dis2[n - 1], time, change) + } + + private fun helper(pathValue: Int, time: Int, change: Int): Int { + var sum = 0 + for (i in 0 until pathValue) { + sum += time + if (i == pathValue - 1) { + break + } + if (sum / change % 2 != 0) { + sum = (sum / change + 1) * change + } + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2047_number_of_valid_words_in_a_sentence/readme.md b/src/main/kotlin/g2001_2100/s2047_number_of_valid_words_in_a_sentence/readme.md new file mode 100644 index 00000000..877e1cda --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2047_number_of_valid_words_in_a_sentence/readme.md @@ -0,0 +1,96 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2047\. Number of Valid Words in a Sentence + +Easy + +A sentence consists of lowercase letters (`'a'` to `'z'`), digits (`'0'` to `'9'`), hyphens (`'-'`), punctuation marks (`'!'`, `'.'`, and `','`), and spaces (`' '`) only. Each sentence can be broken down into **one or more tokens** separated by one or more spaces `' '`. + +A token is a valid word if **all three** of the following are true: + +* It only contains lowercase letters, hyphens, and/or punctuation (**no** digits). +* There is **at most one** hyphen `'-'`. If present, it **must** be surrounded by lowercase characters (`"a-b"` is valid, but `"-ab"` and `"ab-"` are not valid). +* There is **at most one** punctuation mark. If present, it **must** be at the **end** of the token (`"ab,"`, `"cd!"`, and `"."` are valid, but `"a!b"` and `"c.,"` are not valid). + +Examples of valid words include `"a-b."`, `"afad"`, `"ba-c"`, `"a!"`, and `"!"`. + +Given a string `sentence`, return _the **number** of valid words in_ `sentence`. + +**Example 1:** + +**Input:** sentence = "cat and dog" + +**Output:** 3 + +**Explanation:** The valid words in the sentence are "cat", "and", and "dog". + +**Example 2:** + +**Input:** sentence = "!this 1-s b8d!" + +**Output:** 0 + +**Explanation:** There are no valid words in the sentence. + +"!this" is invalid because it starts with a punctuation mark. + +"1-s" and "b8d" are invalid because they contain digits. + +**Example 3:** + +**Input:** sentence = "alice and bob are playing stone-game10" + +**Output:** 5 + +**Explanation:** The valid words in the sentence are "alice", "and", "bob", "are", and "playing". "stone-game10" is invalid because it contains digits. + +**Constraints:** + +* `1 <= sentence.length <= 1000` +* `sentence` only contains lowercase English letters, digits, `' '`, `'-'`, `'!'`, `'.'`, and `','`. +* There will be at least `1` token. + +## Solution + +```kotlin +class Solution { + fun countValidWords(sentence: String): Int { + val tokens = sentence.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + var count = 0 + for (token in tokens) { + var hyphenCount = 0 + var punctuationMarkCount = 0 + var valid = true + if (token.isEmpty() || token == "") { + continue + } + for (i in 0 until token.length) { + if (token[i] == '-') { + hyphenCount++ + if (hyphenCount > 1 || i == 0 || i == token.length - 1 || + !Character.isAlphabetic(token[i - 1].code) || + !Character.isAlphabetic(token[i + 1].code) + ) { + valid = false + break + } + } else if (token[i] == '!' || token[i] == '.' || token[i] == ',') { + punctuationMarkCount++ + if (punctuationMarkCount > 1 || i != token.length - 1) { + valid = false + break + } + } else if (Character.isDigit(token[i])) { + valid = false + break + } + } + if (valid) { + count++ + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2048_next_greater_numerically_balanced_number/readme.md b/src/main/kotlin/g2001_2100/s2048_next_greater_numerically_balanced_number/readme.md new file mode 100644 index 00000000..13588e6d --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2048_next_greater_numerically_balanced_number/readme.md @@ -0,0 +1,103 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2048\. Next Greater Numerically Balanced Number + +Medium + +An integer `x` is **numerically balanced** if for every digit `d` in the number `x`, there are **exactly** `d` occurrences of that digit in `x`. + +Given an integer `n`, return _the **smallest numerically balanced** number **strictly greater** than_ `n`_._ + +**Example 1:** + +**Input:** n = 1 + +**Output:** 22 + +**Explanation:** + +22 is numerically balanced since: + +- The digit 2 occurs 2 times. + +It is also the smallest numerically balanced number strictly greater than 1. + +**Example 2:** + +**Input:** n = 1000 + +**Output:** 1333 + +**Explanation:** + +1333 is numerically balanced since: + +- The digit 1 occurs 1 time. + +- The digit 3 occurs 3 times. + +It is also the smallest numerically balanced number strictly greater than 1000. Note that 1022 cannot be the answer because 0 appeared more than 0 times. + +**Example 3:** + +**Input:** n = 3000 + +**Output:** 3133 + +**Explanation:** + +3133 is numerically balanced since: + +- The digit 1 occurs 1 time. + +- The digit 3 occurs 3 times. + +It is also the smallest numerically balanced number strictly greater than 3000. + +**Constraints:** + +* 0 <= n <= 106 + +## Solution + +```kotlin +class Solution { + fun nextBeautifulNumber(n: Int): Int { + val arr = intArrayOf(0, 1, 2, 3, 4, 5, 6) + val select = BooleanArray(7) + val d = if (n == 0) 1 else Math.log10(n.toDouble()).toInt() + 1 + return solve(1, n, d, 0, select, arr) + } + + private fun solve(i: Int, n: Int, d: Int, sz: Int, select: BooleanArray, arr: IntArray): Int { + if (sz > d + 1) { + return Int.MAX_VALUE + } + if (i == select.size) { + return if (sz >= d) make(0, n, sz, select, arr) else Int.MAX_VALUE + } + var ans = solve(i + 1, n, d, sz, select, arr) + select[i] = true + ans = Math.min(ans, solve(i + 1, n, d, sz + i, select, arr)) + select[i] = false + return ans + } + + private fun make(cur: Int, n: Int, end: Int, select: BooleanArray, arr: IntArray): Int { + if (end == 0) { + return if (cur > n) cur else Int.MAX_VALUE + } + var ans = Int.MAX_VALUE + for (j in 1 until arr.size) { + if (!select[j] || arr[j] == 0) { + continue + } + --arr[j] + ans = Math.min(make(10 * cur + j, n, end - 1, select, arr), ans) + ++arr[j] + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2049_count_nodes_with_the_highest_score/readme.md b/src/main/kotlin/g2001_2100/s2049_count_nodes_with_the_highest_score/readme.md new file mode 100644 index 00000000..06ad6f8a --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2049_count_nodes_with_the_highest_score/readme.md @@ -0,0 +1,113 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2049\. Count Nodes With the Highest Score + +Medium + +There is a **binary** tree rooted at `0` consisting of `n` nodes. The nodes are labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `parents` representing the tree, where `parents[i]` is the parent of node `i`. Since node `0` is the root, `parents[0] == -1`. + +Each node has a **score**. To find the score of a node, consider if the node and the edges connected to it were **removed**. The tree would become one or more **non-empty** subtrees. The **size** of a subtree is the number of the nodes in it. The **score** of the node is the **product of the sizes** of all those subtrees. + +Return _the **number** of nodes that have the **highest score**_. + +**Example 1:** + +![example-1](https://assets.leetcode.com/uploads/2021/10/03/example-1.png) + +**Input:** parents = [-1,2,0,2,0] + +**Output:** 3 + +**Explanation:** + +- The score of node 0 is: 3 \* 1 = 3 + +- The score of node 1 is: 4 = 4 + +- The score of node 2 is: 1 \* 1 \* 2 = 2 + +- The score of node 3 is: 4 = 4 + +- The score of node 4 is: 4 = 4 + +The highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score. + +**Example 2:** + +![example-2](https://assets.leetcode.com/uploads/2021/10/03/example-2.png) + +**Input:** parents = [-1,2,0] + +**Output:** 2 + +**Explanation:** + +- The score of node 0 is: 2 = 2 + +- The score of node 1 is: 2 = 2 + +- The score of node 2 is: 1 \* 1 = 1 + +The highest score is 2, and two nodes (node 0 and node 1) have the highest score. + +**Constraints:** + +* `n == parents.length` +* 2 <= n <= 105 +* `parents[0] == -1` +* `0 <= parents[i] <= n - 1` for `i != 0` +* `parents` represents a valid binary tree. + +## Solution + +```kotlin +class Solution { + internal class Node { + var left: Node? = null + var right: Node? = null + } + + private var size = 0 + private var max: Long = 0 + private var freq = 0 + private fun postOrder(root: Node?): Long { + if (root == null) { + return 0 + } + val left = postOrder(root.left) + val right = postOrder(root.right) + val `val` = Math.max(1, left) * Math.max(1, right) * Math.max(size - left - right - 1, 1) + if (`val` > max) { + max = `val` + freq = 1 + } else if (`val` == max) { + freq += 1 + } + return left + right + 1 + } + + fun countHighestScoreNodes(parents: IntArray): Int { + size = parents.size + val nodes = arrayOfNulls(size) + for (i in 0 until size) { + nodes[i] = Node() + } + var root: Node? = null + for (i in 0 until size) { + if (parents[i] != -1) { + val node = nodes[parents[i]] + if (node!!.left == null) { + node.left = nodes[i] + } else { + node.right = nodes[i] + } + } else { + root = nodes[i] + } + } + postOrder(root) + return freq + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2001_2100/s2050_parallel_courses_iii/readme.md b/src/main/kotlin/g2001_2100/s2050_parallel_courses_iii/readme.md new file mode 100644 index 00000000..81032540 --- /dev/null +++ b/src/main/kotlin/g2001_2100/s2050_parallel_courses_iii/readme.md @@ -0,0 +1,117 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2050\. Parallel Courses III + +Hard + +You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given a 2D integer array `relations` where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed **before** course nextCoursej (prerequisite relationship). Furthermore, you are given a **0-indexed** integer array `time` where `time[i]` denotes how many **months** it takes to complete the (i+1)th course. + +You must find the **minimum** number of months needed to complete all the courses following these rules: + +* You may start taking a course at **any time** if the prerequisites are met. +* **Any number of courses** can be taken at the **same time**. + +Return _the **minimum** number of months needed to complete all the courses_. + +**Note:** The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph). + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2021/10/07/ex1.png)** + +**Input:** n = 3, relations = \[\[1,3],[2,3]], time = [3,2,5] + +**Output:** 8 + +**Explanation:** + +The figure above represents the given graph and the time required to complete each course. + +We start course 1 and course 2 simultaneously at month 0. + +Course 1 takes 3 months and course 2 takes 2 months to complete respectively. + +Thus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months. + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2021/10/07/ex2.png)** + +**Input:** n = 5, relations = \[\[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5] + +**Output:** 12 + +**Explanation:** The figure above represents the given graph and the time required to complete each course. + +You can start courses 1, 2, and 3 at month 0. + +You can complete them after 1, 2, and 3 months respectively. + +Course 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months. + +Course 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months. + +Thus, the minimum time needed to complete all the courses is 7 + 5 = 12 months. + +**Constraints:** + +* 1 <= n <= 5 * 104 +* 0 <= relations.length <= min(n * (n - 1) / 2, 5 * 104) +* `relations[j].length == 2` +* 1 <= prevCoursej, nextCoursej <= n +* prevCoursej != nextCoursej +* All the pairs [prevCoursej, nextCoursej] are **unique**. +* `time.length == n` +* 1 <= time[i] <= 104 +* The given graph is a directed acyclic graph. + +## Solution + +```kotlin +import java.util.ArrayDeque +import java.util.Queue + +class Solution { + fun minimumTime(n: Int, relations: Array, time: IntArray): Int { + val v = time.size + val adj: MutableList> = ArrayList() + for (i in 0 until v) { + adj.add(ArrayList()) + } + val indegree = IntArray(v) + val requiredTime = IntArray(v) + for (relation in relations) { + val vertices = adj[relation[0] - 1] + vertices.add(relation[1] - 1) + indegree[relation[1] - 1]++ + } + val q: Queue = ArrayDeque() + for (i in 0 until v) { + if (indegree[i] == 0) { + q.add(i) + requiredTime[i] = time[i] + } + } + while (q.isNotEmpty()) { + val vertex = q.poll() + val edges: List = adj[vertex] + for (e in edges) { + indegree[e]-- + if (indegree[e] == 0) { + q.add(e) + } + val totalTime = time[e] + requiredTime[vertex] + if (requiredTime[e] < totalTime) { + requiredTime[e] = totalTime + } + } + } + var maxMonth = 0 + for (i in 0 until n) { + maxMonth = Math.max(maxMonth, requiredTime[i]) + } + return maxMonth + } +} +``` \ No newline at end of file