From a9f79696238894b3bdcb68b888282d45a751ac3e Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Sun, 18 Jun 2023 19:51:13 +0300 Subject: [PATCH] Added tasks 1608-1800 --- README.md | 180 +++++++++++++++++- .../s0093_restore_ip_addresses/readme.md | 2 +- .../s0638_shopping_offers/readme.md | 2 +- .../readme.md | 2 +- .../readme.md | 92 +++++++++ .../readme.md | 76 ++++++++ .../readme.md | 72 +++++++ .../g1601_1700/s1609_even_odd_tree/readme.md | 118 ++++++++++++ .../readme.md | 119 ++++++++++++ .../readme.md | 90 +++++++++ .../readme.md | 66 +++++++ .../s1615_maximal_network_rank/readme.md | 78 ++++++++ .../readme.md | 81 ++++++++ .../readme.md | 118 ++++++++++++ .../readme.md | 56 ++++++ .../readme.md | 100 ++++++++++ .../readme.md | 66 +++++++ .../g1601_1700/s1622_fancy_sequence/readme.md | 119 ++++++++++++ .../readme.md | 61 ++++++ .../readme.md | 137 +++++++++++++ .../readme.md | 89 +++++++++ .../readme.md | 148 ++++++++++++++ .../g1601_1700/s1629_slowest_key/readme.md | 103 ++++++++++ .../s1630_arithmetic_subarrays/readme.md | 96 ++++++++++ .../s1631_path_with_minimum_effort/readme.md | 106 +++++++++++ .../readme.md | 145 ++++++++++++++ .../readme.md | 102 ++++++++++ .../readme.md | 76 ++++++++ .../readme.md | 56 ++++++ .../readme.md | 83 ++++++++ .../readme.md | 125 ++++++++++++ .../readme.md | 81 ++++++++ .../readme.md | 70 +++++++ .../readme.md | 95 +++++++++ .../s1643_kth_smallest_instructions/readme.md | 99 ++++++++++ .../readme.md | 86 +++++++++ .../readme.md | 64 +++++++ .../readme.md | 72 +++++++ .../readme.md | 134 +++++++++++++ .../s1652_defuse_the_bomb/readme.md | 89 +++++++++ .../readme.md | 56 ++++++ .../readme.md | 101 ++++++++++ .../readme.md | 88 +++++++++ .../s1656_design_an_ordered_stream/readme.md | 75 ++++++++ .../readme.md | 87 +++++++++ .../readme.md | 75 ++++++++ .../s1659_maximize_grid_happiness/readme.md | 148 ++++++++++++++ .../readme.md | 88 +++++++++ .../readme.md | 61 ++++++ .../readme.md | 54 ++++++ .../s1664_ways_to_make_a_fair_array/readme.md | 93 +++++++++ .../readme.md | 99 ++++++++++ .../s1667_fix_names_in_a_table/readme.md | 53 ++++++ .../readme.md | 56 ++++++ .../readme.md | 80 ++++++++ .../readme.md | 130 +++++++++++++ .../readme.md | 82 ++++++++ .../s1672_richest_customer_wealth/readme.md | 71 +++++++ .../readme.md | 61 ++++++ .../readme.md | 80 ++++++++ .../readme.md | 77 ++++++++ .../readme.md | 66 +++++++ .../s1679_max_number_of_k_sum_pairs/readme.md | 70 +++++++ .../readme.md | 69 +++++++ .../s1681_minimum_incompatibility/readme.md | 121 ++++++++++++ .../g1601_1700/s1683_invalid_tweets/readme.md | 60 ++++++ .../readme.md | 66 +++++++ .../readme.md | 60 ++++++ .../g1601_1700/s1686_stone_game_vi/readme.md | 99 ++++++++++ .../readme.md | 101 ++++++++++ .../readme.md | 73 +++++++ .../readme.md | 51 +++++ .../g1601_1700/s1690_stone_game_vii/readme.md | 67 +++++++ .../readme.md | 100 ++++++++++ .../s1693_daily_leads_and_partners/readme.md | 72 +++++++ .../s1694_reformat_phone_number/readme.md | 105 ++++++++++ .../s1695_maximum_erasure_value/readme.md | 56 ++++++ .../g1601_1700/s1696_jump_game_vi/readme.md | 69 +++++++ .../readme.md | 101 ++++++++++ .../readme.md | 88 +++++++++ .../s1701_average_waiting_time/readme.md | 72 +++++++ .../readme.md | 69 +++++++ .../readme.md | 83 ++++++++ .../readme.md | 59 ++++++ .../readme.md | 77 ++++++++ .../s1706_where_will_the_ball_fall/readme.md | 97 ++++++++++ .../readme.md | 126 ++++++++++++ .../s1710_maximum_units_on_a_truck/readme.md | 68 +++++++ .../s1711_count_good_meals/readme.md | 70 +++++++ .../readme.md | 87 +++++++++ .../readme.md | 73 +++++++ .../readme.md | 65 +++++++ .../readme.md | 84 ++++++++ .../readme.md | 80 ++++++++ .../readme.md | 168 ++++++++++++++++ .../s1720_decode_xored_array/readme.md | 50 +++++ .../readme.md | 71 +++++++ .../readme.md | 117 ++++++++++++ .../readme.md | 79 ++++++++ .../readme.md | 58 ++++++ .../s1726_tuple_with_same_product/readme.md | 63 ++++++ .../readme.md | 71 +++++++ .../s1728_cat_and_mouse_ii/readme.md | 162 ++++++++++++++++ .../s1729_find_followers_count/readme.md | 67 +++++++ .../readme.md | 74 +++++++ .../s1732_find_the_highest_altitude/readme.md | 48 +++++ .../readme.md | 113 +++++++++++ .../s1734_decode_xored_permutation/readme.md | 56 ++++++ .../readme.md | 104 ++++++++++ .../readme.md | 91 +++++++++ .../readme.md | 74 +++++++ .../readme.md | 104 ++++++++++ .../g1701_1800/s1739_building_boxes/readme.md | 105 ++++++++++ .../readme.md | 71 +++++++ .../readme.md | 95 +++++++++ .../readme.md | 82 ++++++++ .../readme.md | 73 +++++++ .../readme.md | 56 ++++++ .../s1748_sum_of_unique_elements/readme.md | 59 ++++++ .../readme.md | 54 ++++++ .../readme.md | 82 ++++++++ .../readme.md | 105 ++++++++++ .../readme.md | 61 ++++++ .../readme.md | 84 ++++++++ .../readme.md | 105 ++++++++++ .../s1755_closest_subsequence_sum/readme.md | 89 +++++++++ .../readme.md | 61 ++++++ .../readme.md | 64 +++++++ .../readme.md | 75 ++++++++ .../readme.md | 84 ++++++++ .../readme.md | 82 ++++++++ .../s1763_longest_nice_substring/readme.md | 71 +++++++ .../readme.md | 92 +++++++++ .../s1765_map_of_highest_peak/readme.md | 91 +++++++++ .../s1766_tree_of_coprimes/readme.md | 113 +++++++++++ .../s1768_merge_strings_alternately/readme.md | 81 ++++++++ .../readme.md | 70 +++++++ .../readme.md | 84 ++++++++ .../readme.md | 78 ++++++++ .../readme.md | 61 ++++++ .../s1774_closest_dessert_cost/readme.md | 93 +++++++++ .../readme.md | 120 ++++++++++++ .../g1701_1800/s1776_car_fleet_ii/readme.md | 77 ++++++++ .../readme.md | 64 +++++++ .../readme.md | 55 ++++++ .../readme.md | 67 +++++++ .../s1782_count_pairs_of_nodes/readme.md | 96 ++++++++++ .../readme.md | 52 +++++ .../readme.md | 48 +++++ .../readme.md | 130 +++++++++++++ .../readme.md | 73 +++++++ .../readme.md | 79 ++++++++ .../readme.md | 78 ++++++++ .../s1791_find_center_of_star_graph/readme.md | 47 +++++ .../readme.md | 72 +++++++ .../readme.md | 71 +++++++ .../s1795_rearrange_products_table/readme.md | 74 +++++++ .../readme.md | 54 ++++++ .../readme.md | 108 +++++++++++ .../readme.md | 84 ++++++++ .../readme.md | 96 ++++++++++ .../readme.md | 64 +++++++ 162 files changed, 13369 insertions(+), 4 deletions(-) create mode 100644 src/main/kotlin/g1301_1400/s1378_replace_employee_id_with_the_unique_identifier/readme.md create mode 100644 src/main/kotlin/g1501_1600/s1517_find_users_with_valid_e_mails/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1608_special_array_with_x_elements_greater_than_or_equal_x/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1609_even_odd_tree/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1610_maximum_number_of_visible_points/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1611_minimum_one_bit_operations_to_make_integers_zero/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1614_maximum_nesting_depth_of_the_parentheses/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1615_maximal_network_rank/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1616_split_two_strings_to_make_palindrome/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1617_count_subtrees_with_max_distance_between_cities/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1619_mean_of_array_after_removing_some_elements/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1620_coordinate_with_maximum_network_quality/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1621_number_of_sets_of_k_non_overlapping_line_segments/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1622_fancy_sequence/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1624_largest_substring_between_two_equal_characters/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1625_lexicographically_smallest_string_after_applying_operations/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1626_best_team_with_no_conflicts/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1627_graph_connectivity_with_threshold/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1629_slowest_key/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1630_arithmetic_subarrays/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1631_path_with_minimum_effort/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1632_rank_transform_of_a_matrix/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1633_percentage_of_users_attended_a_contest/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1636_sort_array_by_increasing_frequency/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1637_widest_vertical_area_between_two_points_containing_no_points/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1638_count_substrings_that_differ_by_one_character/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1639_number_of_ways_to_form_a_target_string_given_a_dictionary/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1640_check_array_formation_through_concatenation/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1641_count_sorted_vowel_strings/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1642_furthest_building_you_can_reach/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1643_kth_smallest_instructions/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1646_get_maximum_in_generated_array/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1647_minimum_deletions_to_make_character_frequencies_unique/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1648_sell_diminishing_valued_colored_balls/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1649_create_sorted_array_through_instructions/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1652_defuse_the_bomb/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1653_minimum_deletions_to_make_string_balanced/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1654_minimum_jumps_to_reach_home/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1655_distribute_repeating_integers/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1656_design_an_ordered_stream/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1657_determine_if_two_strings_are_close/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1658_minimum_operations_to_reduce_x_to_zero/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1659_maximize_grid_happiness/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1661_average_time_of_process_per_machine/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1662_check_if_two_string_arrays_are_equivalent/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1663_smallest_string_with_a_given_numeric_value/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1664_ways_to_make_a_fair_array/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1665_minimum_initial_energy_to_finish_tasks/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1667_fix_names_in_a_table/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1668_maximum_repeating_substring/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1669_merge_in_between_linked_lists/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1670_design_front_middle_back_queue/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1671_minimum_number_of_removals_to_make_mountain_array/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1672_richest_customer_wealth/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1673_find_the_most_competitive_subsequence/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1674_minimum_moves_to_make_array_complementary/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1675_minimize_deviation_in_array/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1678_goal_parser_interpretation/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1679_max_number_of_k_sum_pairs/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1680_concatenation_of_consecutive_binary_numbers/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1681_minimum_incompatibility/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1683_invalid_tweets/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1684_count_the_number_of_consistent_strings/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1685_sum_of_absolute_differences_in_a_sorted_array/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1686_stone_game_vi/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1687_delivering_boxes_from_storage_to_ports/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1688_count_of_matches_in_tournament/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1689_partitioning_into_minimum_number_of_deci_binary_numbers/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1690_stone_game_vii/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1691_maximum_height_by_stacking_cuboids/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1693_daily_leads_and_partners/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1694_reformat_phone_number/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1695_maximum_erasure_value/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1696_jump_game_vi/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1697_checking_existence_of_edge_length_limited_paths/readme.md create mode 100644 src/main/kotlin/g1601_1700/s1700_number_of_students_unable_to_eat_lunch/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1701_average_waiting_time/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1702_maximum_binary_string_after_change/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1703_minimum_adjacent_swaps_for_k_consecutive_ones/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1704_determine_if_string_halves_are_alike/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1705_maximum_number_of_eaten_apples/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1706_where_will_the_ball_fall/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1707_maximum_xor_with_an_element_from_array/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1710_maximum_units_on_a_truck/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1711_count_good_meals/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1712_ways_to_split_array_into_three_subarrays/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1713_minimum_operations_to_make_a_subsequence/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1716_calculate_money_in_leetcode_bank/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1717_maximum_score_from_removing_substrings/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1718_construct_the_lexicographically_largest_valid_sequence/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1719_number_of_ways_to_reconstruct_a_tree/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1720_decode_xored_array/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1721_swapping_nodes_in_a_linked_list/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1722_minimize_hamming_distance_after_swap_operations/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1723_find_minimum_time_to_finish_all_jobs/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1725_number_of_rectangles_that_can_form_the_largest_square/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1726_tuple_with_same_product/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1727_largest_submatrix_with_rearrangements/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1728_cat_and_mouse_ii/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1729_find_followers_count/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1731_the_number_of_employees_which_report_to_each_employee/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1732_find_the_highest_altitude/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1733_minimum_number_of_people_to_teach/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1734_decode_xored_permutation/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1735_count_ways_to_make_array_with_product/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1736_latest_time_by_replacing_hidden_digits/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1737_change_minimum_characters_to_satisfy_one_of_three_conditions/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1738_find_kth_largest_xor_coordinate_value/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1739_building_boxes/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1741_find_total_time_spent_by_each_employee/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1742_maximum_number_of_balls_in_a_box/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1743_restore_the_array_from_adjacent_pairs/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1744_can_you_eat_your_favorite_candy_on_your_favorite_day/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1745_palindrome_partitioning_iv/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1748_sum_of_unique_elements/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1749_maximum_absolute_sum_of_any_subarray/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1750_minimum_length_of_string_after_deleting_similar_ends/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1751_maximum_number_of_events_that_can_be_attended_ii/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1752_check_if_array_is_sorted_and_rotated/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1753_maximum_score_from_removing_stones/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1754_largest_merge_of_two_strings/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1755_closest_subsequence_sum/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1757_recyclable_and_low_fat_products/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1758_minimum_changes_to_make_alternating_binary_string/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1759_count_number_of_homogenous_substrings/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1760_minimum_limit_of_balls_in_a_bag/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1761_minimum_degree_of_a_connected_trio_in_a_graph/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1763_longest_nice_substring/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1764_form_array_by_concatenating_subarrays_of_another_array/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1765_map_of_highest_peak/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1766_tree_of_coprimes/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1768_merge_strings_alternately/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1769_minimum_number_of_operations_to_move_all_balls_to_each_box/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1770_maximum_score_from_performing_multiplication_operations/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1771_maximize_palindrome_length_from_subsequences/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1773_count_items_matching_a_rule/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1774_closest_dessert_cost/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1775_equal_sum_arrays_with_minimum_number_of_operations/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1776_car_fleet_ii/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1779_find_nearest_point_that_has_the_same_x_or_y_coordinate/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1780_check_if_number_is_a_sum_of_powers_of_three/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1781_sum_of_beauty_of_all_substrings/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1782_count_pairs_of_nodes/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1784_check_if_binary_string_has_at_most_one_segment_of_ones/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1785_minimum_elements_to_add_to_form_a_given_sum/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1786_number_of_restricted_paths_from_first_to_last_node/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1787_make_the_xor_of_all_segments_equal_to_zero/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1789_primary_department_for_each_employee/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1790_check_if_one_string_swap_can_make_strings_equal/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1791_find_center_of_star_graph/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1792_maximum_average_pass_ratio/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1793_maximum_score_of_a_good_subarray/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1795_rearrange_products_table/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1796_second_largest_digit_in_a_string/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1797_design_authentication_manager/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1798_maximum_number_of_consecutive_values_you_can_make/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1799_maximize_score_after_n_operations/readme.md create mode 100644 src/main/kotlin/g1701_1800/s1800_maximum_ascending_subarray_sum/readme.md diff --git a/README.md b/README.md index b0855b9e..b1a6f4c7 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ |-|-|-|-|-|- | 0202 |[Happy Number](src/main/kotlin/g0201_0300/s0202_happy_number)| Easy | Top_Interview_Questions, Hash_Table, Math, Two_Pointers | 261 | 45.08 | 0054 |[Spiral Matrix](src/main/kotlin/g0001_0100/s0054_spiral_matrix)| Medium | Top_Interview_Questions, Array, Matrix, Simulation | 224 | 62.50 +| 1706 |[Where Will the Ball Fall](src/main/kotlin/g1701_1800/s1706_where_will_the_ball_fall)| Medium | Array, Dynamic_Programming, Depth_First_Search, Matrix, Simulation | 270 | 67.86 #### Day 2 String @@ -943,6 +944,7 @@ | | | | | | |-|-|-|-|-|- | 0167 |[Two Sum II - Input Array Is Sorted](src/main/kotlin/g0101_0200/s0167_two_sum_ii_input_array_is_sorted)| Medium | Array, Binary_Search, Two_Pointers | 403 | 68.74 +| 1608 |[Special Array With X Elements Greater Than or Equal X](src/main/kotlin/g1601_1700/s1608_special_array_with_x_elements_greater_than_or_equal_x)| Easy | Array, Sorting, Binary_Search | 147 | 81.82 #### Day 8 @@ -997,6 +999,7 @@ | | | | | | |-|-|-|-|-|- | 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search | 318 | 82.28 +| 1760 |[Minimum Limit of Balls in a Bag](src/main/kotlin/g1701_1800/s1760_minimum_limit_of_balls_in_a_bag)| Medium | Array, Binary_Search | 460 | 100.00 #### Day 4 @@ -1041,6 +1044,7 @@ | | | | | | |-|-|-|-|-|- | 0222 |[Count Complete Tree Nodes](src/main/kotlin/g0201_0300/s0222_count_complete_tree_nodes)| ||| +| 1712 |[Ways to Split Array Into Three Subarrays](src/main/kotlin/g1701_1800/s1712_ways_to_split_array_into_three_subarrays)| Medium | Array, Binary_Search, Two_Pointers, Prefix_Sum | 486 | 100.00 #### Day 11 @@ -1101,6 +1105,7 @@ | | | | | | |-|-|-|-|-|- | 1562 |[Find Latest Group of Size M](src/main/kotlin/g1501_1600/s1562_find_latest_group_of_size_m)| Medium | Array, Binary_Search, Simulation | 534 | 100.00 +| 1648 |[Sell Diminishing-Valued Colored Balls](src/main/kotlin/g1601_1700/s1648_sell_diminishing_valued_colored_balls)| Medium | Array, Math, Sorting, Greedy, Binary_Search, Heap_Priority_Queue | 509 | 100.00 #### Day 20 @@ -1283,6 +1288,7 @@ | | | | | | |-|-|-|-|-|- | 0976 |[Largest Perimeter Triangle](src/main/kotlin/g0901_1000/s0976_largest_perimeter_triangle)| Easy | Array, Math, Sorting, Greedy | 304 | 33.33 +| 1779 |[Find Nearest Point That Has the Same X or Y Coordinate](src/main/kotlin/g1701_1800/s1779_find_nearest_point_that_has_the_same_x_or_y_coordinate)| Easy | Array | 364 | 100.00 #### Day 4 Loop @@ -1290,6 +1296,7 @@ |-|-|-|-|-|- | 1502 |[Can Make Arithmetic Progression From Sequence](src/main/kotlin/g1501_1600/s1502_can_make_arithmetic_progression_from_sequence)| Easy | Array, Sorting | 156 | 94.82 | 0202 |[Happy Number](src/main/kotlin/g0201_0300/s0202_happy_number)| Easy | Top_Interview_Questions, Hash_Table, Math, Two_Pointers | 261 | 45.08 +| 1790 |[Check if One String Swap Can Make Strings Equal](src/main/kotlin/g1701_1800/s1790_check_if_one_string_swap_can_make_strings_equal)| Easy | String, Hash_Table, Counting | 138 | 100.00 #### Day 5 Function @@ -1305,6 +1312,7 @@ |-|-|-|-|-|- | 1588 |[Sum of All Odd Length Subarrays](src/main/kotlin/g1501_1600/s1588_sum_of_all_odd_length_subarrays)| Easy | Array, Math, Prefix_Sum | 157 | 64.00 | 0283 |[Move Zeroes](src/main/kotlin/g0201_0300/s0283_move_zeroes)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Two_Pointers | 516 | 79.07 +| 1672 |[Richest Customer Wealth](src/main/kotlin/g1601_1700/s1672_richest_customer_wealth)| Easy | Array, Matrix | 155 | 94.54 #### Day 7 Array @@ -1317,6 +1325,8 @@ | | | | | | |-|-|-|-|-|- +| 1768 |[Merge Strings Alternately](src/main/kotlin/g1701_1800/s1768_merge_strings_alternately)| Easy | String, Two_Pointers | 138 | 93.81 +| 1678 |[Goal Parser Interpretation](src/main/kotlin/g1601_1700/s1678_goal_parser_interpretation)| Easy | String | 136 | 88.24 | 0389 |[Find the Difference](src/main/kotlin/g0301_0400/s0389_find_the_difference)| Easy | String, Hash_Table, Sorting, Bit_Manipulation | 256 | 64.81 #### Day 9 String @@ -1413,6 +1423,7 @@ | | | | | | |-|-|-|-|-|- +| 1630 |[Arithmetic Subarrays](src/main/kotlin/g1601_1700/s1630_arithmetic_subarrays)| Medium | Array, Sorting | 264 | 100.00 | 0429 |[N-ary Tree Level Order Traversal](src/main/kotlin/g0401_0500/s0429_n_ary_tree_level_order_traversal)| Medium | Breadth_First_Search, Tree | 248 | 75.86 #### Day 10 @@ -1481,6 +1492,7 @@ | | | | | | |-|-|-|-|-|- +| 1797 |[Design Authentication Manager](src/main/kotlin/g1701_1800/s1797_design_authentication_manager)| Medium | Hash_Table, Design | 334 | 100.00 | 0707 |[Design Linked List](src/main/kotlin/g0701_0800/s0707_design_linked_list)| Medium | Design, Linked_List | 243 | 100.00 #### Day 20 @@ -1567,6 +1579,7 @@ | | | | | | |-|-|-|-|-|- | 1306 |[Jump Game III](src/main/kotlin/g1301_1400/s1306_jump_game_iii)| Medium | Array, Depth_First_Search, Breadth_First_Search | 291 | 100.00 +| 1654 |[Minimum Jumps to Reach Home](src/main/kotlin/g1601_1700/s1654_minimum_jumps_to_reach_home)| Medium | Array, Dynamic_Programming, Breadth_First_Search | 192 | 100.00 | 0365 |[Water and Jug Problem](src/main/kotlin/g0301_0400/s0365_water_and_jug_problem)| Medium | Math, Depth_First_Search, Breadth_First_Search | 130 | 100.00 #### Day 12 Breadth First Search @@ -1588,6 +1601,7 @@ | | | | | | |-|-|-|-|-|- +| 1615 |[Maximal Network Rank](src/main/kotlin/g1601_1700/s1615_maximal_network_rank)| Medium | Graph | 282 | 100.00 | 0886 |[Possible Bipartition](src/main/kotlin/g0801_0900/s0886_possible_bipartition)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 397 | 100.00 | 0785 |[Is Graph Bipartite?](src/main/kotlin/g0701_0800/s0785_is_graph_bipartite)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 215 | 82.35 @@ -1598,6 +1612,7 @@ | | | | | | |-|-|-|-|-|- | 0595 |[Big Countries](src/main/kotlin/g0501_0600/s0595_big_countries)| Easy | Database | 417 | 56.09 +| 1757 |[Recyclable and Low Fat Products](src/main/kotlin/g1701_1800/s1757_recyclable_and_low_fat_products)| Easy | Database | 1237 | 34.20 | 0584 |[Find Customer Referee](src/main/kotlin/g0501_0600/s0584_find_customer_referee)| Easy | Database | 779 | 43.48 | 0183 |[Customers Who Never Order](src/main/kotlin/g0101_0200/s0183_customers_who_never_order)| Easy | Database | 712 | 33.67 @@ -1612,6 +1627,7 @@ | | | | | | |-|-|-|-|-|- +| 1667 |[Fix Names in a Table](src/main/kotlin/g1601_1700/s1667_fix_names_in_a_table)| Easy | Database | 1196 | 61.40 | 1484 |[Group Sold Products By The Date](src/main/kotlin/g1401_1500/s1484_group_sold_products_by_the_date)| Easy | LeetCode_Curated_SQL_70, Database | 899 | 40.76 | 1527 |[Patients With a Condition](src/main/kotlin/g1501_1600/s1527_patients_with_a_condition)| Easy | Database | 708 | 48.23 @@ -1619,6 +1635,7 @@ | | | | | | |-|-|-|-|-|- +| 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 @@ -1642,6 +1659,8 @@ | | | | | | |-|-|-|-|-|- | 1141 |[User Activity for the Past 30 Days I](src/main/kotlin/g1101_1200/s1141_user_activity_for_the_past_30_days_i)| Easy | LeetCode_Curated_SQL_70, Database | 790 | 87.11 +| 1693 |[Daily Leads and Partners](src/main/kotlin/g1601_1700/s1693_daily_leads_and_partners)| Easy | Database | 1115 | 52.84 +| 1729 |[Find Followers Count](src/main/kotlin/g1701_1800/s1729_find_followers_count)| Easy | Database | 1228 | 38.04 #### Day 8 Function @@ -1649,6 +1668,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 +| 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 @@ -1778,6 +1798,162 @@ | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- +| 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 +| 1797 |[Design Authentication Manager](src/main/kotlin/g1701_1800/s1797_design_authentication_manager)| Medium | Hash_Table, Design, Programming_Skills_II_Day_19 | 334 | 100.00 +| 1796 |[Second Largest Digit in a String](src/main/kotlin/g1701_1800/s1796_second_largest_digit_in_a_string)| Easy | String, Hash_Table | 148 | 100.00 +| 1795 |[Rearrange Products Table](src/main/kotlin/g1701_1800/s1795_rearrange_products_table)| Easy | Database, SQL_I_Day_4_Union_and_Select | 1027 | 67.57 +| 1793 |[Maximum Score of a Good Subarray](src/main/kotlin/g1701_1800/s1793_maximum_score_of_a_good_subarray)| Hard | Array, Binary_Search, Two_Pointers, Stack, Monotonic_Stack | 568 | 100.00 +| 1792 |[Maximum Average Pass Ratio](src/main/kotlin/g1701_1800/s1792_maximum_average_pass_ratio)| Medium | Array, Greedy, Heap_Priority_Queue | 1111 | 75.00 +| 1791 |[Find Center of Star Graph](src/main/kotlin/g1701_1800/s1791_find_center_of_star_graph)| Easy | Graph | 476 | 91.67 +| 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, Programming_Skills_I_Day_4_Loop | 138 | 100.00 +| 1789 |[Primary Department for Each Employee](src/main/kotlin/g1701_1800/s1789_primary_department_for_each_employee)| Easy | Database | 1033 | 77.87 +| 1787 |[Make the XOR of All Segments Equal to Zero](src/main/kotlin/g1701_1800/s1787_make_the_xor_of_all_segments_equal_to_zero)| Hard | Array, Dynamic_Programming, Bit_Manipulation | 374 | 100.00 +| 1786 |[Number of Restricted Paths From First to Last Node](src/main/kotlin/g1701_1800/s1786_number_of_restricted_paths_from_first_to_last_node)| Medium | Dynamic_Programming, Heap_Priority_Queue, Graph, Topological_Sort, Shortest_Path | 977 | 100.00 +| 1785 |[Minimum Elements to Add to Form a Given Sum](src/main/kotlin/g1701_1800/s1785_minimum_elements_to_add_to_form_a_given_sum)| Medium | Array, Greedy | 595 | 100.00 +| 1784 |[Check if Binary String Has at Most One Segment of Ones](src/main/kotlin/g1701_1800/s1784_check_if_binary_string_has_at_most_one_segment_of_ones)| Easy | String | 135 | 85.71 +| 1782 |[Count Pairs Of Nodes](src/main/kotlin/g1701_1800/s1782_count_pairs_of_nodes)| Hard | Binary_Search, Two_Pointers, Graph | 1441 | 100.00 +| 1781 |[Sum of Beauty of All Substrings](src/main/kotlin/g1701_1800/s1781_sum_of_beauty_of_all_substrings)| Medium | String, Hash_Table, Counting | 172 | 100.00 +| 1780 |[Check if Number is a Sum of Powers of Three](src/main/kotlin/g1701_1800/s1780_check_if_number_is_a_sum_of_powers_of_three)| Medium | Math | 133 | 66.67 +| 1779 |[Find Nearest Point That Has the Same X or Y Coordinate](src/main/kotlin/g1701_1800/s1779_find_nearest_point_that_has_the_same_x_or_y_coordinate)| Easy | Array, Programming_Skills_I_Day_3_Conditional_Statements | 364 | 100.00 +| 1776 |[Car Fleet II](src/main/kotlin/g1701_1800/s1776_car_fleet_ii)| Hard | Array, Math, Stack, Heap_Priority_Queue, Monotonic_Stack | 2049 | 100.00 +| 1775 |[Equal Sum Arrays With Minimum Number of Operations](src/main/kotlin/g1701_1800/s1775_equal_sum_arrays_with_minimum_number_of_operations)| Medium | Array, Hash_Table, Greedy, Counting | 529 | 100.00 +| 1774 |[Closest Dessert Cost](src/main/kotlin/g1701_1800/s1774_closest_dessert_cost)| Medium | Array, Dynamic_Programming, Backtracking | 147 | 100.00 +| 1773 |[Count Items Matching a Rule](src/main/kotlin/g1701_1800/s1773_count_items_matching_a_rule)| Easy | Array, String | 227 | 97.50 +| 1771 |[Maximize Palindrome Length From Subsequences](src/main/kotlin/g1701_1800/s1771_maximize_palindrome_length_from_subsequences)| Hard | String, Dynamic_Programming | 248 | 100.00 +| 1770 |[Maximum Score from Performing Multiplication Operations](src/main/kotlin/g1701_1800/s1770_maximum_score_from_performing_multiplication_operations)| Medium | Array, Dynamic_Programming | 436 | 91.67 +| 1769 |[Minimum Number of Operations to Move All Balls to Each Box](src/main/kotlin/g1701_1800/s1769_minimum_number_of_operations_to_move_all_balls_to_each_box)| Medium | Array, String | 217 | 75.00 +| 1768 |[Merge Strings Alternately](src/main/kotlin/g1701_1800/s1768_merge_strings_alternately)| Easy | String, Two_Pointers, Programming_Skills_I_Day_8_String | 138 | 93.81 +| 1766 |[Tree of Coprimes](src/main/kotlin/g1701_1800/s1766_tree_of_coprimes)| Hard | Math, Depth_First_Search, Breadth_First_Search, Tree | 991 | 100.00 +| 1765 |[Map of Highest Peak](src/main/kotlin/g1701_1800/s1765_map_of_highest_peak)| Medium | Array, Breadth_First_Search, Matrix | 1087 | 100.00 +| 1764 |[Form Array by Concatenating Subarrays of Another Array](src/main/kotlin/g1701_1800/s1764_form_array_by_concatenating_subarrays_of_another_array)| Medium | Array, Greedy, String_Matching | 206 | 100.00 +| 1763 |[Longest Nice Substring](src/main/kotlin/g1701_1800/s1763_longest_nice_substring)| Easy | String, Hash_Table, Bit_Manipulation, Sliding_Window | 158 | 91.67 +| 1761 |[Minimum Degree of a Connected Trio in a Graph](src/main/kotlin/g1701_1800/s1761_minimum_degree_of_a_connected_trio_in_a_graph)| Hard | Graph | 590 | 50.00 +| 1760 |[Minimum Limit of Balls in a Bag](src/main/kotlin/g1701_1800/s1760_minimum_limit_of_balls_in_a_bag)| Medium | Array, Binary_Search, Binary_Search_II_Day_3 | 460 | 100.00 +| 1759 |[Count Number of Homogenous Substrings](src/main/kotlin/g1701_1800/s1759_count_number_of_homogenous_substrings)| Medium | String, Math | 230 | 100.00 +| 1758 |[Minimum Changes To Make Alternating Binary String](src/main/kotlin/g1701_1800/s1758_minimum_changes_to_make_alternating_binary_string)| Easy | String | 153 | 100.00 +| 1757 |[Recyclable and Low Fat Products](src/main/kotlin/g1701_1800/s1757_recyclable_and_low_fat_products)| Easy | Database, SQL_I_Day_1_Select | 1237 | 34.20 +| 1755 |[Closest Subsequence Sum](src/main/kotlin/g1701_1800/s1755_closest_subsequence_sum)| Hard | Array, Dynamic_Programming, Two_Pointers, Bit_Manipulation, Bitmask | 620 | 100.00 +| 1754 |[Largest Merge Of Two Strings](src/main/kotlin/g1701_1800/s1754_largest_merge_of_two_strings)| Medium | String, Greedy, Two_Pointers | 217 | 100.00 +| 1753 |[Maximum Score From Removing Stones](src/main/kotlin/g1701_1800/s1753_maximum_score_from_removing_stones)| Medium | Math, Greedy, Heap_Priority_Queue | 141 | 100.00 +| 1752 |[Check if Array Is Sorted and Rotated](src/main/kotlin/g1701_1800/s1752_check_if_array_is_sorted_and_rotated)| Easy | Array | 133 | 85.71 +| 1751 |[Maximum Number of Events That Can Be Attended II](src/main/kotlin/g1701_1800/s1751_maximum_number_of_events_that_can_be_attended_ii)| Hard | Array, Dynamic_Programming, Binary_Search | 608 | 100.00 +| 1750 |[Minimum Length of String After Deleting Similar Ends](src/main/kotlin/g1701_1800/s1750_minimum_length_of_string_after_deleting_similar_ends)| Medium | String, Two_Pointers | 215 | 100.00 +| 1749 |[Maximum Absolute Sum of Any Subarray](src/main/kotlin/g1701_1800/s1749_maximum_absolute_sum_of_any_subarray)| Medium | Array, Dynamic_Programming | 367 | 100.00 +| 1748 |[Sum of Unique Elements](src/main/kotlin/g1701_1800/s1748_sum_of_unique_elements)| Easy | Array, Hash_Table, Counting | 143 | 82.35 +| 1745 |[Palindrome Partitioning IV](src/main/kotlin/g1701_1800/s1745_palindrome_partitioning_iv)| Hard | String, Dynamic_Programming | 179 | 100.00 +| 1744 |[Can You Eat Your Favorite Candy on Your Favorite Day?](src/main/kotlin/g1701_1800/s1744_can_you_eat_your_favorite_candy_on_your_favorite_day)| Medium | Array, Prefix_Sum | 809 | 100.00 +| 1743 |[Restore the Array From Adjacent Pairs](src/main/kotlin/g1701_1800/s1743_restore_the_array_from_adjacent_pairs)| Medium | Array, Hash_Table | 1018 | 100.00 +| 1742 |[Maximum Number of Balls in a Box](src/main/kotlin/g1701_1800/s1742_maximum_number_of_balls_in_a_box)| Easy | Hash_Table, Math, Counting | 125 | 100.00 +| 1741 |[Find Total Time Spent by Each Employee](src/main/kotlin/g1701_1800/s1741_find_total_time_spent_by_each_employee)| Easy | Database, SQL_I_Day_8_Function | 1101 | 51.40 +| 1739 |[Building Boxes](src/main/kotlin/g1701_1800/s1739_building_boxes)| Hard | Math, Greedy, Binary_Search | 133 | 100.00 +| 1738 |[Find Kth Largest XOR Coordinate Value](src/main/kotlin/g1701_1800/s1738_find_kth_largest_xor_coordinate_value)| Medium | Array, Matrix, Bit_Manipulation, Heap_Priority_Queue, Prefix_Sum, Divide_and_Conquer, Quickselect | 936 | 100.00 +| 1737 |[Change Minimum Characters to Satisfy One of Three Conditions](src/main/kotlin/g1701_1800/s1737_change_minimum_characters_to_satisfy_one_of_three_conditions)| Medium | String, Hash_Table, Prefix_Sum, Counting | 240 | 100.00 +| 1736 |[Latest Time by Replacing Hidden Digits](src/main/kotlin/g1701_1800/s1736_latest_time_by_replacing_hidden_digits)| Easy | String, Greedy | 161 | 100.00 +| 1735 |[Count Ways to Make Array With Product](src/main/kotlin/g1701_1800/s1735_count_ways_to_make_array_with_product)| Hard | Array, Dynamic_Programming, Math | 394 | 100.00 +| 1734 |[Decode XORed Permutation](src/main/kotlin/g1701_1800/s1734_decode_xored_permutation)| Medium | Array, Bit_Manipulation | 684 | 100.00 +| 1733 |[Minimum Number of People to Teach](src/main/kotlin/g1701_1800/s1733_minimum_number_of_people_to_teach)| Medium | Array, Greedy | 580 | 100.00 +| 1732 |[Find the Highest Altitude](src/main/kotlin/g1701_1800/s1732_find_the_highest_altitude)| Easy | Array, Prefix_Sum | 139 | 90.70 +| 1731 |[The Number of Employees Which Report to Each Employee](src/main/kotlin/g1701_1800/s1731_the_number_of_employees_which_report_to_each_employee)| Easy | Database | 1385 | 39.02 +| 1729 |[Find Followers Count](src/main/kotlin/g1701_1800/s1729_find_followers_count)| Easy | Database, SQL_I_Day_7_Function | 1228 | 38.04 +| 1728 |[Cat and Mouse II](src/main/kotlin/g1701_1800/s1728_cat_and_mouse_ii)| Hard | Array, Dynamic_Programming, Math, Matrix, Graph, Memoization, Topological_Sort, Game_Theory | 193 | 100.00 +| 1727 |[Largest Submatrix With Rearrangements](src/main/kotlin/g1701_1800/s1727_largest_submatrix_with_rearrangements)| Medium | Array, Sorting, Greedy, Matrix | 650 | 100.00 +| 1726 |[Tuple with Same Product](src/main/kotlin/g1701_1800/s1726_tuple_with_same_product)| Medium | Array, Hash_Table | 762 | 100.00 +| 1725 |[Number Of Rectangles That Can Form The Largest Square](src/main/kotlin/g1701_1800/s1725_number_of_rectangles_that_can_form_the_largest_square)| Easy | Array | 244 | 100.00 +| 1723 |[Find Minimum Time to Finish All Jobs](src/main/kotlin/g1701_1800/s1723_find_minimum_time_to_finish_all_jobs)| Hard | Array, Dynamic_Programming, Bit_Manipulation, Backtracking, Bitmask | 167 | 100.00 +| 1722 |[Minimize Hamming Distance After Swap Operations](src/main/kotlin/g1701_1800/s1722_minimize_hamming_distance_after_swap_operations)| Medium | Array, Depth_First_Search, Union_Find | 843 | 100.00 +| 1721 |[Swapping Nodes in a Linked List](src/main/kotlin/g1701_1800/s1721_swapping_nodes_in_a_linked_list)| Medium | Two_Pointers, Linked_List | 879 | 13.84 +| 1720 |[Decode XORed Array](src/main/kotlin/g1701_1800/s1720_decode_xored_array)| Easy | Array, Bit_Manipulation | 304 | 95.00 +| 1719 |[Number Of Ways To Reconstruct A Tree](src/main/kotlin/g1701_1800/s1719_number_of_ways_to_reconstruct_a_tree)| Hard | Tree, Graph, Topological_Sort | 1015 | 100.00 +| 1718 |[Construct the Lexicographically Largest Valid Sequence](src/main/kotlin/g1701_1800/s1718_construct_the_lexicographically_largest_valid_sequence)| Medium | Array, Backtracking | 140 | 100.00 +| 1717 |[Maximum Score From Removing Substrings](src/main/kotlin/g1701_1800/s1717_maximum_score_from_removing_substrings)| Medium | String, Greedy, Stack | 265 | 100.00 +| 1716 |[Calculate Money in Leetcode Bank](src/main/kotlin/g1701_1800/s1716_calculate_money_in_leetcode_bank)| Easy | Math | 119 | 66.67 +| 1713 |[Minimum Operations to Make a Subsequence](src/main/kotlin/g1701_1800/s1713_minimum_operations_to_make_a_subsequence)| Hard | Array, Hash_Table, Greedy, Binary_Search | 862 | 100.00 +| 1712 |[Ways to Split Array Into Three Subarrays](src/main/kotlin/g1701_1800/s1712_ways_to_split_array_into_three_subarrays)| Medium | Array, Binary_Search, Two_Pointers, Prefix_Sum, Binary_Search_II_Day_10 | 486 | 100.00 +| 1711 |[Count Good Meals](src/main/kotlin/g1701_1800/s1711_count_good_meals)| Medium | Array, Hash_Table | 549 | 100.00 +| 1710 |[Maximum Units on a Truck](src/main/kotlin/g1701_1800/s1710_maximum_units_on_a_truck)| Easy | Array, Sorting, Greedy | 228 | 100.00 +| 1707 |[Maximum XOR With an Element From Array](src/main/kotlin/g1701_1800/s1707_maximum_xor_with_an_element_from_array)| Hard | Array, Bit_Manipulation, Trie | 1295 | 100.00 +| 1706 |[Where Will the Ball Fall](src/main/kotlin/g1701_1800/s1706_where_will_the_ball_fall)| Medium | Array, Dynamic_Programming, Depth_First_Search, Matrix, Simulation, Level_2_Day_1_Implementation/Simulation | 270 | 67.86 +| 1705 |[Maximum Number of Eaten Apples](src/main/kotlin/g1701_1800/s1705_maximum_number_of_eaten_apples)| Medium | Array, Greedy, Heap_Priority_Queue | 428 | 100.00 +| 1704 |[Determine if String Halves Are Alike](src/main/kotlin/g1701_1800/s1704_determine_if_string_halves_are_alike)| Easy | String, Counting | 162 | 83.33 +| 1703 |[Minimum Adjacent Swaps for K Consecutive Ones](src/main/kotlin/g1701_1800/s1703_minimum_adjacent_swaps_for_k_consecutive_ones)| Hard | Array, Greedy, Prefix_Sum, Sliding_Window | 518 | 100.00 +| 1702 |[Maximum Binary String After Change](src/main/kotlin/g1701_1800/s1702_maximum_binary_string_after_change)| Medium | String, Greedy | 343 | 100.00 +| 1701 |[Average Waiting Time](src/main/kotlin/g1701_1800/s1701_average_waiting_time)| Medium | Array, Simulation | 654 | 100.00 +| 1700 |[Number of Students Unable to Eat Lunch](src/main/kotlin/g1601_1700/s1700_number_of_students_unable_to_eat_lunch)| Easy | Array, Stack, Simulation, Queue | 143 | 100.00 +| 1697 |[Checking Existence of Edge Length Limited Paths](src/main/kotlin/g1601_1700/s1697_checking_existence_of_edge_length_limited_paths)| Hard | Array, Sorting, Graph, Union_Find | 1411 | 72.90 +| 1696 |[Jump Game VI](src/main/kotlin/g1601_1700/s1696_jump_game_vi)| Medium | Array, Dynamic_Programming, Heap_Priority_Queue, Sliding_Window, Queue, Monotonic_Queue | 497 | 100.00 +| 1695 |[Maximum Erasure Value](src/main/kotlin/g1601_1700/s1695_maximum_erasure_value)| Medium | Array, Hash_Table, Sliding_Window | 478 | 100.00 +| 1694 |[Reformat Phone Number](src/main/kotlin/g1601_1700/s1694_reformat_phone_number)| Easy | String | 142 | 100.00 +| 1693 |[Daily Leads and Partners](src/main/kotlin/g1601_1700/s1693_daily_leads_and_partners)| Easy | Database, SQL_I_Day_7_Function | 1115 | 52.84 +| 1691 |[Maximum Height by Stacking Cuboids](src/main/kotlin/g1601_1700/s1691_maximum_height_by_stacking_cuboids)| Hard | Array, Dynamic_Programming, Sorting | 187 | 100.00 +| 1690 |[Stone Game VII](src/main/kotlin/g1601_1700/s1690_stone_game_vii)| Medium | Array, Dynamic_Programming, Math, Game_Theory | 196 | 100.00 +| 1689 |[Partitioning Into Minimum Number Of Deci-Binary Numbers](src/main/kotlin/g1601_1700/s1689_partitioning_into_minimum_number_of_deci_binary_numbers)| Medium | String, Greedy | 226 | 84.44 +| 1688 |[Count of Matches in Tournament](src/main/kotlin/g1601_1700/s1688_count_of_matches_in_tournament)| Easy | Math, Simulation | 124 | 83.33 +| 1687 |[Delivering Boxes from Storage to Ports](src/main/kotlin/g1601_1700/s1687_delivering_boxes_from_storage_to_ports)| Hard | Array, Dynamic_Programming, Heap_Priority_Queue, Queue, Segment_Tree, Monotonic_Queue | 778 | 100.00 +| 1686 |[Stone Game VI](src/main/kotlin/g1601_1700/s1686_stone_game_vi)| Medium | Array, Math, Sorting, Greedy, Heap_Priority_Queue, Game_Theory | 702 | 100.00 +| 1685 |[Sum of Absolute Differences in a Sorted Array](src/main/kotlin/g1601_1700/s1685_sum_of_absolute_differences_in_a_sorted_array)| Medium | Array, Math, Prefix_Sum | 612 | 100.00 +| 1684 |[Count the Number of Consistent Strings](src/main/kotlin/g1601_1700/s1684_count_the_number_of_consistent_strings)| Easy | Array, String, Hash_Table, Bit_Manipulation | 234 | 100.00 +| 1683 |[Invalid Tweets](src/main/kotlin/g1601_1700/s1683_invalid_tweets)| Easy | Database | 1263 | 53.93 +| 1681 |[Minimum Incompatibility](src/main/kotlin/g1601_1700/s1681_minimum_incompatibility)| Hard | Array, Dynamic_Programming, Bit_Manipulation, Bitmask | 162 | 100.00 +| 1680 |[Concatenation of Consecutive Binary Numbers](src/main/kotlin/g1601_1700/s1680_concatenation_of_consecutive_binary_numbers)| Medium | Math, Bit_Manipulation, Simulation | 175 | 100.00 +| 1679 |[Max Number of K-Sum Pairs](src/main/kotlin/g1601_1700/s1679_max_number_of_k_sum_pairs)| Medium | Array, Hash_Table, Sorting, Two_Pointers | 468 | 92.86 +| 1678 |[Goal Parser Interpretation](src/main/kotlin/g1601_1700/s1678_goal_parser_interpretation)| Easy | String, Programming_Skills_I_Day_8_String | 136 | 88.24 +| 1675 |[Minimize Deviation in Array](src/main/kotlin/g1601_1700/s1675_minimize_deviation_in_array)| Hard | Array, Greedy, Heap_Priority_Queue, Ordered_Set | 769 | 100.00 +| 1674 |[Minimum Moves to Make Array Complementary](src/main/kotlin/g1601_1700/s1674_minimum_moves_to_make_array_complementary)| Medium | Array, Hash_Table, Prefix_Sum | 522 | 100.00 +| 1673 |[Find the Most Competitive Subsequence](src/main/kotlin/g1601_1700/s1673_find_the_most_competitive_subsequence)| Medium | Array, Greedy, Stack, Monotonic_Stack | 741 | 100.00 +| 1672 |[Richest Customer Wealth](src/main/kotlin/g1601_1700/s1672_richest_customer_wealth)| Easy | Array, Matrix, Programming_Skills_I_Day_6_Array | 155 | 94.54 +| 1671 |[Minimum Number of Removals to Make Mountain Array](src/main/kotlin/g1601_1700/s1671_minimum_number_of_removals_to_make_mountain_array)| Hard | Array, Dynamic_Programming, Greedy, Binary_Search | 264 | 100.00 +| 1670 |[Design Front Middle Back Queue](src/main/kotlin/g1601_1700/s1670_design_front_middle_back_queue)| Medium | Array, Design, Linked_List, Queue, Data_Stream | 267 | 100.00 +| 1669 |[Merge In Between Linked Lists](src/main/kotlin/g1601_1700/s1669_merge_in_between_linked_lists)| Medium | Linked_List | 531 | 66.67 +| 1668 |[Maximum Repeating Substring](src/main/kotlin/g1601_1700/s1668_maximum_repeating_substring)| Easy | String, String_Matching | 170 | 100.00 +| 1667 |[Fix Names in a Table](src/main/kotlin/g1601_1700/s1667_fix_names_in_a_table)| Easy | Database, SQL_I_Day_3_String_Processing_Functions | 1196 | 61.40 +| 1665 |[Minimum Initial Energy to Finish Tasks](src/main/kotlin/g1601_1700/s1665_minimum_initial_energy_to_finish_tasks)| Hard | Array, Sorting, Greedy | 823 | 100.00 +| 1664 |[Ways to Make a Fair Array](src/main/kotlin/g1601_1700/s1664_ways_to_make_a_fair_array)| Medium | Array, Dynamic_Programming | 475 | 100.00 +| 1663 |[Smallest String With A Given Numeric Value](src/main/kotlin/g1601_1700/s1663_smallest_string_with_a_given_numeric_value)| Medium | String, Greedy | 202 | 100.00 +| 1662 |[Check If Two String Arrays are Equivalent](src/main/kotlin/g1601_1700/s1662_check_if_two_string_arrays_are_equivalent)| Easy | Array, String | 144 | 86.84 +| 1661 |[Average Time of Process per Machine](src/main/kotlin/g1601_1700/s1661_average_time_of_process_per_machine)| Easy | Database | 429 | 71.35 +| 1659 |[Maximize Grid Happiness](src/main/kotlin/g1601_1700/s1659_maximize_grid_happiness)| Hard | Dynamic_Programming, Bit_Manipulation, Bitmask, Memoization | 181 | 100.00 +| 1658 |[Minimum Operations to Reduce X to Zero](src/main/kotlin/g1601_1700/s1658_minimum_operations_to_reduce_x_to_zero)| Medium | Array, Hash_Table, Binary_Search, Prefix_Sum, Sliding_Window | 532 | 50.00 +| 1657 |[Determine if Two Strings Are Close](src/main/kotlin/g1601_1700/s1657_determine_if_two_strings_are_close)| Medium | String, Hash_Table, Sorting | 287 | 100.00 +| 1656 |[Design an Ordered Stream](src/main/kotlin/g1601_1700/s1656_design_an_ordered_stream)| Easy | Array, Hash_Table, Design, Data_Stream | 487 | 91.67 +| 1655 |[Distribute Repeating Integers](src/main/kotlin/g1601_1700/s1655_distribute_repeating_integers)| Hard | Array, Dynamic_Programming, Bit_Manipulation, Backtracking, Bitmask | 445 | 100.00 +| 1654 |[Minimum Jumps to Reach Home](src/main/kotlin/g1601_1700/s1654_minimum_jumps_to_reach_home)| Medium | Array, Dynamic_Programming, Breadth_First_Search, Graph_Theory_I_Day_11_Breadth_First_Search | 192 | 100.00 +| 1653 |[Minimum Deletions to Make String Balanced](src/main/kotlin/g1601_1700/s1653_minimum_deletions_to_make_string_balanced)| Medium | String, Dynamic_Programming, Stack | 291 | 100.00 +| 1652 |[Defuse the Bomb](src/main/kotlin/g1601_1700/s1652_defuse_the_bomb)| Easy | Array | 160 | 100.00 +| 1649 |[Create Sorted Array through Instructions](src/main/kotlin/g1601_1700/s1649_create_sorted_array_through_instructions)| Hard | Array, Binary_Search, Ordered_Set, Divide_and_Conquer, Segment_Tree, Binary_Indexed_Tree, Merge_Sort | 571 | 100.00 +| 1648 |[Sell Diminishing-Valued Colored Balls](src/main/kotlin/g1601_1700/s1648_sell_diminishing_valued_colored_balls)| Medium | Array, Math, Sorting, Greedy, Binary_Search, Heap_Priority_Queue, Binary_Search_II_Day_19 | 509 | 100.00 +| 1647 |[Minimum Deletions to Make Character Frequencies Unique](src/main/kotlin/g1601_1700/s1647_minimum_deletions_to_make_character_frequencies_unique)| Medium | String, Sorting, Greedy | 252 | 100.00 +| 1646 |[Get Maximum in Generated Array](src/main/kotlin/g1601_1700/s1646_get_maximum_in_generated_array)| Easy | Array, Dynamic_Programming, Simulation | 142 | 100.00 +| 1643 |[Kth Smallest Instructions](src/main/kotlin/g1601_1700/s1643_kth_smallest_instructions)| Hard | Array, Dynamic_Programming, Math, Combinatorics | 171 | 100.00 +| 1642 |[Furthest Building You Can Reach](src/main/kotlin/g1601_1700/s1642_furthest_building_you_can_reach)| Medium | Array, Greedy, Heap_Priority_Queue | 457 | 71.43 +| 1641 |[Count Sorted Vowel Strings](src/main/kotlin/g1601_1700/s1641_count_sorted_vowel_strings)| Medium | Dynamic_Programming | 141 | 42.86 +| 1640 |[Check Array Formation Through Concatenation](src/main/kotlin/g1601_1700/s1640_check_array_formation_through_concatenation)| Easy | Array, Hash_Table | 154 | 100.00 +| 1639 |[Number of Ways to Form a Target String Given a Dictionary](src/main/kotlin/g1601_1700/s1639_number_of_ways_to_form_a_target_string_given_a_dictionary)| Hard | Array, String, Dynamic_Programming | 408 | 100.00 +| 1638 |[Count Substrings That Differ by One Character](src/main/kotlin/g1601_1700/s1638_count_substrings_that_differ_by_one_character)| Medium | String, Hash_Table, Dynamic_Programming | 143 | 100.00 +| 1637 |[Widest Vertical Area Between Two Points Containing No Points](src/main/kotlin/g1601_1700/s1637_widest_vertical_area_between_two_points_containing_no_points)| Medium | Array, Sorting | 616 | 100.00 +| 1636 |[Sort Array by Increasing Frequency](src/main/kotlin/g1601_1700/s1636_sort_array_by_increasing_frequency)| Easy | Array, Hash_Table, Sorting | 222 | 95.65 +| 1633 |[Percentage of Users Attended a Contest](src/main/kotlin/g1601_1700/s1633_percentage_of_users_attended_a_contest)| Easy | Database | 1556 | 93.74 +| 1632 |[Rank Transform of a Matrix](src/main/kotlin/g1601_1700/s1632_rank_transform_of_a_matrix)| Hard | Array, Greedy, Matrix, Graph, Union_Find, Topological_Sort | 807 | 100.00 +| 1631 |[Path With Minimum Effort](src/main/kotlin/g1601_1700/s1631_path_with_minimum_effort)| Medium | Array, Depth_First_Search, Breadth_First_Search, Binary_Search, Matrix, Heap_Priority_Queue, Union_Find | 384 | 100.00 +| 1630 |[Arithmetic Subarrays](src/main/kotlin/g1601_1700/s1630_arithmetic_subarrays)| Medium | Array, Sorting, Programming_Skills_II_Day_9 | 264 | 100.00 +| 1629 |[Slowest Key](src/main/kotlin/g1601_1700/s1629_slowest_key)| Easy | Array, String | 200 | 75.00 +| 1627 |[Graph Connectivity With Threshold](src/main/kotlin/g1601_1700/s1627_graph_connectivity_with_threshold)| Hard | Array, Math, Union_Find | 703 | 100.00 +| 1626 |[Best Team With No Conflicts](src/main/kotlin/g1601_1700/s1626_best_team_with_no_conflicts)| Medium | Array, Dynamic_Programming, Sorting | 370 | 100.00 +| 1625 |[Lexicographically Smallest String After Applying Operations](src/main/kotlin/g1601_1700/s1625_lexicographically_smallest_string_after_applying_operations)| Medium | String, Breadth_First_Search | 415 | 100.00 +| 1624 |[Largest Substring Between Two Equal Characters](src/main/kotlin/g1601_1700/s1624_largest_substring_between_two_equal_characters)| Easy | String, Hash_Table | 132 | 100.00 +| 1622 |[Fancy Sequence](src/main/kotlin/g1601_1700/s1622_fancy_sequence)| Hard | Math, Design, Segment_Tree | 1050 | 100.00 +| 1621 |[Number of Sets of K Non-Overlapping Line Segments](src/main/kotlin/g1601_1700/s1621_number_of_sets_of_k_non_overlapping_line_segments)| Medium | Dynamic_Programming, Math | 147 | 100.00 +| 1620 |[Coordinate With Maximum Network Quality](src/main/kotlin/g1601_1700/s1620_coordinate_with_maximum_network_quality)| Medium | Array, Enumeration | 233 | 100.00 +| 1619 |[Mean of Array After Removing Some Elements](src/main/kotlin/g1601_1700/s1619_mean_of_array_after_removing_some_elements)| Easy | Array, Sorting | 178 | 100.00 +| 1617 |[Count Subtrees With Max Distance Between Cities](src/main/kotlin/g1601_1700/s1617_count_subtrees_with_max_distance_between_cities)| Hard | Dynamic_Programming, Tree, Bit_Manipulation, Bitmask, Enumeration | 297 | 100.00 +| 1616 |[Split Two Strings to Make Palindrome](src/main/kotlin/g1601_1700/s1616_split_two_strings_to_make_palindrome)| Medium | String, Greedy, Two_Pointers | 277 | 100.00 +| 1615 |[Maximal Network Rank](src/main/kotlin/g1601_1700/s1615_maximal_network_rank)| Medium | Graph, Graph_Theory_I_Day_14_Graph_Theory | 282 | 100.00 +| 1614 |[Maximum Nesting Depth of the Parentheses](src/main/kotlin/g1601_1700/s1614_maximum_nesting_depth_of_the_parentheses)| Easy | String, Stack | 130 | 81.25 +| 1611 |[Minimum One Bit Operations to Make Integers Zero](src/main/kotlin/g1601_1700/s1611_minimum_one_bit_operations_to_make_integers_zero)| Hard | Dynamic_Programming, Bit_Manipulation, Memoization | 127 | 100.00 +| 1610 |[Maximum Number of Visible Points](src/main/kotlin/g1601_1700/s1610_maximum_number_of_visible_points)| Hard | Array, Math, Sorting, Sliding_Window, Geometry | 1343 | 100.00 +| 1609 |[Even Odd Tree](src/main/kotlin/g1601_1700/s1609_even_odd_tree)| Medium | Breadth_First_Search, Tree, Binary_Tree | 497 | 100.00 +| 1608 |[Special Array With X Elements Greater Than or Equal X](src/main/kotlin/g1601_1700/s1608_special_array_with_x_elements_greater_than_or_equal_x)| Easy | Array, Sorting, Binary_Search, Binary_Search_I_Day_7 | 147 | 81.82 | 1606 |[Find Servers That Handled Most Number of Requests](src/main/kotlin/g1601_1700/s1606_find_servers_that_handled_most_number_of_requests)| Hard | Array, Greedy, Heap_Priority_Queue, Ordered_Set | 973 | 33.33 | 1605 |[Find Valid Matrix Given Row and Column Sums](src/main/kotlin/g1601_1700/s1605_find_valid_matrix_given_row_and_column_sums)| Medium | Array, Greedy, Matrix | 574 | 100.00 | 1604 |[Alert Using Same Key-Card Three or More Times in a One Hour Period](src/main/kotlin/g1601_1700/s1604_alert_using_same_key_card_three_or_more_times_in_a_one_hour_period)| Medium | Array, String, Hash_Table, Sorting | 1063 | 20.00 @@ -1822,7 +1998,7 @@ | 1556 |[Thousand Separator](src/main/kotlin/g1501_1600/s1556_thousand_separator)| Easy | String | 131 | 100.00 | 1553 |[Minimum Number of Days to Eat N Oranges](src/main/kotlin/g1501_1600/s1553_minimum_number_of_days_to_eat_n_oranges)| Hard | Dynamic_Programming, Memoization | 153 | 100.00 | 1552 |[Magnetic Force Between Two Balls](src/main/kotlin/g1501_1600/s1552_magnetic_force_between_two_balls)| Medium | Array, Sorting, Binary_Search, Binary_Search_II_Day_4 | 636 | 100.00 -| 1551 |[Minimum Operations to Make Array Equal](src/main/kotlin/g1501_1600/s1551_minimum_operations_to_make_array_equal)| ||| +| 1551 |[Minimum Operations to Make Array Equal](src/main/kotlin/g1501_1600/s1551_minimum_operations_to_make_array_equal)| Medium | Math | 119 | 100.00 | 1550 |[Three Consecutive Odds](src/main/kotlin/g1501_1600/s1550_three_consecutive_odds)| Easy | Array | 154 | 90.00 | 1547 |[Minimum Cost to Cut a Stick](src/main/kotlin/g1501_1600/s1547_minimum_cost_to_cut_a_stick)| Hard | Array, Dynamic_Programming | 187 | 92.00 | 1546 |[Maximum Number of Non-Overlapping Subarrays With Sum Equals Target](src/main/kotlin/g1501_1600/s1546_maximum_number_of_non_overlapping_subarrays_with_sum_equals_target)| Medium | Array, Hash_Table, Greedy, Prefix_Sum | 560 | 100.00 @@ -1849,6 +2025,7 @@ | 1520 |[Maximum Number of Non-Overlapping Substrings](src/main/kotlin/g1501_1600/s1520_maximum_number_of_non_overlapping_substrings)| Hard | String, Greedy | 333 | 100.00 | 1519 |[Number of Nodes in the Sub-Tree With the Same Label](src/main/kotlin/g1501_1600/s1519_number_of_nodes_in_the_sub_tree_with_the_same_label)| Medium | Hash_Table, Depth_First_Search, Breadth_First_Search, Tree, Counting | 1130 | 87.50 | 1518 |[Water Bottles](src/main/kotlin/g1501_1600/s1518_water_bottles)| Easy | Math, Simulation | 116 | 100.00 +| 1517 |[Find Users With Valid E-Mails](src/main/kotlin/g1501_1600/s1517_find_users_with_valid_e_mails)| Easy | Database | 1278 | 77.30 | 1515 |[Best Position for a Service Centre](src/main/kotlin/g1501_1600/s1515_best_position_for_a_service_centre)| Hard | Math, Geometry, Randomized | 183 | 100.00 | 1514 |[Path with Maximum Probability](src/main/kotlin/g1501_1600/s1514_path_with_maximum_probability)| Medium | Heap_Priority_Queue, Graph, Shortest_Path | 681 | 100.00 | 1513 |[Number of Substrings With Only 1s](src/main/kotlin/g1501_1600/s1513_number_of_substrings_with_only_1s)| Medium | String, Math | 171 | 100.00 @@ -1961,6 +2138,7 @@ | 1381 |[Design a Stack With Increment Operation](src/main/kotlin/g1301_1400/s1381_design_a_stack_with_increment_operation)| Medium | Array, Stack, Design | 267 | 100.00 | 1380 |[Lucky Numbers in a Matrix](src/main/kotlin/g1301_1400/s1380_lucky_numbers_in_a_matrix)| Easy | Array, Matrix | 223 | 89.29 | 1379 |[Find a Corresponding Node of a Binary Tree in a Clone of That Tree](src/main/kotlin/g1301_1400/s1379_find_a_corresponding_node_of_a_binary_tree_in_a_clone_of_that_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 1 | 100.00 +| 1378 |[Replace Employee ID With The Unique Identifier](src/main/kotlin/g1301_1400/s1378_replace_employee_id_with_the_unique_identifier)| Easy | Database | 2452 | 54.86 | 1377 |[Frog Position After T Seconds](src/main/kotlin/g1301_1400/s1377_frog_position_after_t_seconds)| Hard | Depth_First_Search, Breadth_First_Search, Tree, Graph | 221 | 100.00 | 1376 |[Time Needed to Inform All Employees](src/main/kotlin/g1301_1400/s1376_time_needed_to_inform_all_employees)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Programming_Skills_II_Day_11, Graph_Theory_I_Day_9_Standard_Traversal | 915 | 37.62 | 1375 |[Number of Times Binary String Is Prefix-Aligned](src/main/kotlin/g1301_1400/s1375_number_of_times_binary_string_is_prefix_aligned)| Medium | Array | 327 | 100.00 diff --git a/src/main/kotlin/g0001_0100/s0093_restore_ip_addresses/readme.md b/src/main/kotlin/g0001_0100/s0093_restore_ip_addresses/readme.md index 83128548..9ad02db7 100644 --- a/src/main/kotlin/g0001_0100/s0093_restore_ip_addresses/readme.md +++ b/src/main/kotlin/g0001_0100/s0093_restore_ip_addresses/readme.md @@ -37,7 +37,7 @@ Given a string `s` containing only digits, return _all possible valid IP address ## Solution ```kotlin -class Solution() { +class Solution { fun restoreIpAddresses(s: String): List { val results: MutableList = ArrayList() step(s, 0, IntArray(4), 0, results) diff --git a/src/main/kotlin/g0601_0700/s0638_shopping_offers/readme.md b/src/main/kotlin/g0601_0700/s0638_shopping_offers/readme.md index 5581d1dd..ad630401 100644 --- a/src/main/kotlin/g0601_0700/s0638_shopping_offers/readme.md +++ b/src/main/kotlin/g0601_0700/s0638_shopping_offers/readme.md @@ -51,7 +51,7 @@ You cannot add more items, though only $9 for 2A ,2B and 1C. ## Solution ```kotlin -class Solution() { +class Solution { fun shoppingOffers( price: List, special: List>, diff --git a/src/main/kotlin/g1001_1100/s1039_minimum_score_triangulation_of_polygon/readme.md b/src/main/kotlin/g1001_1100/s1039_minimum_score_triangulation_of_polygon/readme.md index 957f43c4..4c912fdc 100644 --- a/src/main/kotlin/g1001_1100/s1039_minimum_score_triangulation_of_polygon/readme.md +++ b/src/main/kotlin/g1001_1100/s1039_minimum_score_triangulation_of_polygon/readme.md @@ -50,7 +50,7 @@ Return _the smallest possible total score that you can achieve with some triangu ## Solution ```kotlin -class Solution() { +class Solution { private val dp = Array(101) { IntArray(101) } fun minScoreTriangulation(values: IntArray): Int { val n = values.size diff --git a/src/main/kotlin/g1301_1400/s1378_replace_employee_id_with_the_unique_identifier/readme.md b/src/main/kotlin/g1301_1400/s1378_replace_employee_id_with_the_unique_identifier/readme.md new file mode 100644 index 00000000..7b6e06de --- /dev/null +++ b/src/main/kotlin/g1301_1400/s1378_replace_employee_id_with_the_unique_identifier/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) + +## 1378\. Replace Employee ID With The Unique Identifier + +Easy + +SQL Schema + +Table: `Employees` + + +---------------+---------+ + | Column Name | Type | + +---------------+---------+ + | id | int | + | name | varchar | + +---------------+---------+ + id is the primary key for this table. + Each row of this table contains the id and the name of an employee in a company. + +Table: `EmployeeUNI` + + +---------------+---------+ + | Column Name | Type | + +---------------+---------+ + | id | int | + | unique_id | int | + +---------------+---------+ + (id, unique_id) is the primary key for this table. + Each row of this table contains the id and the corresponding unique id of an employee in the company. + +Write an SQL query to show the **unique ID** of each user, If a user does not have a unique ID replace just show `null`. + +Return the result table in **any** order. + +The query result format is in the following example. + +**Example 1:** + +**Input:**, + + Employees table: + +----+----------+ + | id | name | + +----+----------+ + | 1 | Alice | + | 7 | Bob | + | 11 | Meir | + | 90 | Winston | + | 3 | Jonathan | + +----+----------+ + + EmployeeUNI table: + +----+-----------+ + | id | unique_id | + +----+-----------+ + | 3 | 1 | + | 11 | 2 | + | 90 | 3 | + +----+-----------+ + +**Output:** + + +-----------+----------+ + | unique_id | name | + +-----------+----------+ + | null | Alice | + | null | Bob | + | 2 | Meir | + | 3 | Winston | + | 1 | Jonathan | + +-----------+----------+ + +**Explanation:** + +Alice and Bob do not have a unique ID, We will show null instead. + +The unique ID of Meir is 2. + +The unique ID of Winston is 3. + +The unique ID of Jonathan is 1. + +## Solution + +```sql +# Write your MySQL query statement below +select u.unique_id, e.name +from Employees e +left join EmployeeUNI u +on e.id = u.id; +``` \ No newline at end of file diff --git a/src/main/kotlin/g1501_1600/s1517_find_users_with_valid_e_mails/readme.md b/src/main/kotlin/g1501_1600/s1517_find_users_with_valid_e_mails/readme.md new file mode 100644 index 00000000..2933d390 --- /dev/null +++ b/src/main/kotlin/g1501_1600/s1517_find_users_with_valid_e_mails/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) + +## 1517\. Find Users With Valid E-Mails + +Easy + +SQL Schema + +Table: `Users` + + +---------------+---------+ + | Column Name | Type | + +---------------+---------+ + | user_id | int | + | name | varchar | + | mail | varchar | + +---------------+---------+ + user_id is the primary key for this table. + This table contains information of the users signed up in a website. Some e-mails are invalid. + +Write an SQL query to find the users who have **valid emails**. + +A valid e-mail has a prefix name and a domain where: + +* **The prefix name** is a string that may contain letters (upper or lower case), digits, underscore `'_'`, period `'.'`, and/or dash `'-'`. The prefix name **must** start with a letter. +* **The domain** is `'@leetcode.com'`. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Users table: + +---------+-----------+-------------------------+ + | user_id | name | mail | + +---------+-----------+-------------------------+ + | 1 | Winston | winston@leetcode.com | + | 2 | Jonathan | jonathanisgreat | + | 3 | Annabelle | bella-@leetcode.com | + | 4 | Sally | sally.come@leetcode.com | + | 5 | Marwan | quarz#2020@leetcode.com | + | 6 | David | david69@gmail.com | + | 7 | Shapiro | .shapo@leetcode.com | + +---------+-----------+-------------------------+ + +**Output:** + + +---------+-----------+-------------------------+ + | user_id | name | mail | + +---------+-----------+-------------------------+ + | 1 | Winston | winston@leetcode.com | + | 3 | Annabelle | bella-@leetcode.com | + | 4 | Sally | sally.come@leetcode.com | + +---------+-----------+-------------------------+ + +**Explanation:** + +The mail of user 2 does not have a domain. + +The mail of user 5 has the # sign which is not allowed. + +The mail of user 6 does not have the leetcode domain. + +The mail of user 7 starts with a period. + +## Solution + +```sql +# Write your MySQL query statement below +select * from Users +where mail REGEXP '^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode.com' and mail LIKE '%@leetcode.com' +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1608_special_array_with_x_elements_greater_than_or_equal_x/readme.md b/src/main/kotlin/g1601_1700/s1608_special_array_with_x_elements_greater_than_or_equal_x/readme.md new file mode 100644 index 00000000..bf203dca --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1608_special_array_with_x_elements_greater_than_or_equal_x/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) + +## 1608\. Special Array With X Elements Greater Than or Equal X + +Easy + +You are given an array `nums` of non-negative integers. `nums` is considered **special** if there exists a number `x` such that there are **exactly** `x` numbers in `nums` that are **greater than or equal to** `x`. + +Notice that `x` **does not** have to be an element in `nums`. + +Return `x` _if the array is **special**, otherwise, return_ `-1`. It can be proven that if `nums` is special, the value for `x` is **unique**. + +**Example 1:** + +**Input:** nums = [3,5] + +**Output:** 2 + +**Explanation:** There are 2 values (3 and 5) that are greater than or equal to 2. + +**Example 2:** + +**Input:** nums = [0,0] + +**Output:** -1 + +**Explanation:** No numbers fit the criteria for x. + +If x = 0, there should be 0 numbers >= x, but there are 2. + +If x = 1, there should be 1 number >= x, but there are 0. + +If x = 2, there should be 2 numbers >= x, but there are 0. + +x cannot be greater since there are only 2 numbers in nums. + +**Example 3:** + +**Input:** nums = [0,4,3,0,4] + +**Output:** 3 + +**Explanation:** There are 3 values that are greater than or equal to 3. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `0 <= nums[i] <= 1000` + +## Solution + +```kotlin +class Solution { + fun specialArray(nums: IntArray): Int { + nums.sort() + val max = nums[nums.size - 1] + for (x in 1..max) { + var found = 0 + var i = nums.size - 1 + while (i >= 0 && nums[i] >= x) { + i-- + found++ + } + if (found == x) { + return x + } + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1609_even_odd_tree/readme.md b/src/main/kotlin/g1601_1700/s1609_even_odd_tree/readme.md new file mode 100644 index 00000000..94319b4f --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1609_even_odd_tree/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) + +## 1609\. Even Odd Tree + +Medium + +A binary tree is named **Even-Odd** if it meets the following conditions: + +* The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc. +* For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increasing** order (from left to right). +* For every **odd-indexed** level, all nodes at the level have **even** integer values in **strictly decreasing** order (from left to right). + +Given the `root` of a binary tree, _return_ `true` _if the binary tree is **Even-Odd**, otherwise return_ `false`_._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/15/sample_1_1966.png) + +**Input:** root = [1,10,4,3,null,7,9,12,8,6,null,null,2] + +**Output:** true + +**Explanation:** The node values on each level are: + +Level 0: [1] + +Level 1: [10,4] + +Level 2: [3,7,9] + +Level 3: [12,8,6,2] + +Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/09/15/sample_2_1966.png) + +**Input:** root = [5,4,2,3,3,7] + +**Output:** false + +**Explanation:** The node values on each level are: + +Level 0: [5] + +Level 1: [4,2] + +Level 2: [3,3,7] + +Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2020/09/22/sample_1_333_1966.png) + +**Input:** root = [5,9,1,3,5,7] + +**Output:** false + +**Explanation:** Node values in the level 1 should be even integers. + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 105]. +* 1 <= Node.val <= 106 + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private val comp: MutableList = ArrayList() + + fun isEvenOddTree(root: TreeNode?): Boolean { + return find(root, 0) + } + + private fun find(root: TreeNode?, height: Int): Boolean { + if (root == null) { + return true + } + if (height % 2 == 0 && root.`val` % 2 == 0 || height % 2 == 1 && root.`val` % 2 == 1) { + return false + } + if (comp.size == height) { + comp.add(root.`val`) + } else { + if (height % 2 == 0) { + if (comp[height] >= root.`val`) { + return false + } else { + comp[height] = root.`val` + } + } else { + if (comp[height] <= root.`val`) { + return false + } else { + comp[height] = root.`val` + } + } + } + return find(root.left, height + 1) && find(root.right, height + 1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1610_maximum_number_of_visible_points/readme.md b/src/main/kotlin/g1601_1700/s1610_maximum_number_of_visible_points/readme.md new file mode 100644 index 00000000..976bef86 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1610_maximum_number_of_visible_points/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) + +## 1610\. Maximum Number of Visible Points + +Hard + +You are given an array `points`, an integer `angle`, and your `location`, where location = [posx, posy] and points[i] = [xi, yi] both denote **integral coordinates** on the X-Y plane. + +Initially, you are facing directly east from your position. You **cannot move** from your position, but you can **rotate**. In other words, posx and posy cannot be changed. Your field of view in **degrees** is represented by `angle`, determining how wide you can see from any given view direction. Let `d` be the amount in degrees that you rotate counterclockwise. Then, your field of view is the **inclusive** range of angles `[d - angle/2, d + angle/2]`. + +Your browser does not support the video tag or this video format. + +You can **see** some set of points if, for each point, the **angle** formed by the point, your position, and the immediate east direction from your position is **in your field of view**. + +There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points. + +Return _the maximum number of points you can see_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/30/89a07e9b-00ab-4967-976a-c723b2aa8656.png) + +**Input:** points = \[\[2,1],[2,2],[3,3]], angle = 90, location = [1,1] + +**Output:** 3 + +**Explanation:** The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight. + +**Example 2:** + +**Input:** points = \[\[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1] + +**Output:** 4 + +**Explanation:** All points can be made visible in your field of view, including the one at your location. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2020/09/30/5010bfd3-86e6-465f-ac64-e9df941d2e49.png) + +**Input:** points = \[\[1,0],[2,1]], angle = 13, location = [1,1] + +**Output:** 1 + +**Explanation:** You can only see one of the two points, as shown above. + +**Constraints:** + +* 1 <= points.length <= 105 +* `points[i].length == 2` +* `location.length == 2` +* `0 <= angle < 360` +* 0 <= posx, posy, xi, yi <= 100 + +## Solution + +```kotlin +import kotlin.math.atan + +class Solution { + fun visiblePoints(points: List>, angle: Int, location: List): Int { + var max = 0 + var count = 0 + val angles: MutableList = ArrayList(points.size) + for (point in points) { + val a = calculateAngle(location, point) + if (a == 360.0) { + count++ + } else { + angles.add(a) + } + } + angles.sort() + var s = 0 + var e = 0 + var size: Int + val n = angles.size + while (s < n && max < n) { + while (true) { + val index = (e + 1) % n + if (s == index || (360 + angles[index] - angles[s]) % 360 > angle) { + break + } + e = index + } + size = if (e >= s) e - s + 1 else n - s + e + 1 + max = max.coerceAtLeast(size) + if (e == s) { + e++ + } + s++ + } + return max + count + } + + private fun calculateAngle(location: List, point: List): Double { + val x1 = location[0] + val y1 = location[1] + val x2 = point[0] + val y2 = point[1] + if (x1 == x2) { + if (y2 > y1) { + return 90.0 + } + return if (y2 < y1) { + 270.0 + } else 360.0 + } + var angle = Math.toDegrees(atan((y2 - y1).toDouble() / (x2 - x1))) + if (x2 > x1) { + angle = (angle + 360.0) % 360.0 + } else { + angle += 180.0 + } + return angle + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1611_minimum_one_bit_operations_to_make_integers_zero/readme.md b/src/main/kotlin/g1601_1700/s1611_minimum_one_bit_operations_to_make_integers_zero/readme.md new file mode 100644 index 00000000..f9aa3a89 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1611_minimum_one_bit_operations_to_make_integers_zero/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) + +## 1611\. Minimum One Bit Operations to Make Integers Zero + +Hard + +Given an integer `n`, you must transform it into `0` using the following operations any number of times: + +* Change the rightmost (0th) bit in the binary representation of `n`. +* Change the ith bit in the binary representation of `n` if the (i-1)th bit is set to `1` and the (i-2)th through 0th bits are set to `0`. + +Return _the minimum number of operations to transform_ `n` _into_ `0`_._ + +**Example 1:** + +**Input:** n = 3 + +**Output:** 2 + +**Explanation:** The binary representation of 3 is "11". + +"11" -> "01" with the 2nd operation since the 0th bit is 1. + +"01" -> "00" with the 1st operation. + +**Example 2:** + +**Input:** n = 6 + +**Output:** 4 + +**Explanation:** The binary representation of 6 is "110". + +"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0. + +"010" -> "011" with the 1st operation. + +"011" -> "001" with the 2nd operation since the 0th bit is 1. + +"001" -> "000" with the 1st operation. + +**Constraints:** + +* 0 <= n <= 109 + +## Solution + +```kotlin +import java.util.LinkedList + +@Suppress("NAME_SHADOWING") +class Solution { + fun minimumOneBitOperations(n: Int): Int { + return calc(calculateOneIndex(n)) + } + + private fun calc(indices: LinkedList): Int { + if (indices.isEmpty()) { + return 0 + } + val index = indices.removeLast() + return stepOfExp(index) - calc(indices) + } + + private fun calculateOneIndex(n: Int): LinkedList { + var n = n + val result = LinkedList() + var index = 1 + while (n > 0) { + if (n % 2 == 1) { + result.add(index) + } + n = n shr 1 + index++ + } + return result + } + + private fun stepOfExp(index: Int): Int { + var index = index + var result = 1 + while (index > 0) { + result = result shl 1 + index-- + } + return result - 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1614_maximum_nesting_depth_of_the_parentheses/readme.md b/src/main/kotlin/g1601_1700/s1614_maximum_nesting_depth_of_the_parentheses/readme.md new file mode 100644 index 00000000..d9284e28 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1614_maximum_nesting_depth_of_the_parentheses/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) + +## 1614\. Maximum Nesting Depth of the Parentheses + +Easy + +A string is a **valid parentheses string** (denoted **VPS**) if it meets one of the following: + +* It is an empty string `""`, or a single character not equal to `"("` or `")"`, +* It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are **VPS**'s, or +* It can be written as `(A)`, where `A` is a **VPS**. + +We can similarly define the **nesting depth** `depth(S)` of any VPS `S` as follows: + +* `depth("") = 0` +* `depth(C) = 0`, where `C` is a string with a single character not equal to `"("` or `")"`. +* `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are **VPS**'s. +* `depth("(" + A + ")") = 1 + depth(A)`, where `A` is a **VPS**. + +For example, `""`, `"()()"`, and `"()(()())"` are **VPS**'s (with nesting depths 0, 1, and 2), and `")("` and `"(()"` are not **VPS**'s. + +Given a **VPS** represented as string `s`, return _the **nesting depth** of_ `s`. + +**Example 1:** + +**Input:** s = "(1+(2\*3)+((8)/4))+1" + +**Output:** 3 + +**Explanation:** Digit 8 is inside of 3 nested parentheses in the string. + +**Example 2:** + +**Input:** s = "(1)+((2))+(((3)))" + +**Output:** 3 + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` consists of digits `0-9` and characters `'+'`, `'-'`, `'*'`, `'/'`, `'('`, and `')'`. +* It is guaranteed that parentheses expression `s` is a **VPS**. + +## Solution + +```kotlin +import java.util.Deque +import java.util.LinkedList + +class Solution { + fun maxDepth(s: String): Int { + val stack: Deque = LinkedList() + var maxDepth = 0 + for (c in s.toCharArray()) { + if (c == '(') { + stack.push(c) + } else if (c == ')') { + maxDepth = maxDepth.coerceAtLeast(stack.size) + stack.pop() + } + } + return maxDepth + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1615_maximal_network_rank/readme.md b/src/main/kotlin/g1601_1700/s1615_maximal_network_rank/readme.md new file mode 100644 index 00000000..21713d78 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1615_maximal_network_rank/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) + +## 1615\. Maximal Network Rank + +Medium + +There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi. + +The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either** city. If a road is directly connected to both cities, it is only counted **once**. + +The **maximal network rank** of the infrastructure is the **maximum network rank** of all pairs of different cities. + +Given the integer `n` and the array `roads`, return _the **maximal network rank** of the entire infrastructure_. + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2020/09/21/ex1.png)** + +**Input:** n = 4, roads = \[\[0,1],[0,3],[1,2],[1,3]] + +**Output:** 4 + +**Explanation:** The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once. + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2020/09/21/ex2.png)** + +**Input:** n = 5, roads = \[\[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]] + +**Output:** 5 + +**Explanation:** There are 5 roads that are connected to cities 1 or 2. + +**Example 3:** + +**Input:** n = 8, roads = \[\[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]] + +**Output:** 5 + +**Explanation:** The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected. + +**Constraints:** + +* `2 <= n <= 100` +* `0 <= roads.length <= n * (n - 1) / 2` +* `roads[i].length == 2` +* 0 <= ai, bi <= n-1 +* ai != bi +* Each pair of cities has **at most one** road connecting them. + +## Solution + +```kotlin +class Solution { + fun maximalNetworkRank(n: Int, roads: Array): Int { + val degrees = IntArray(n) + val connected = BooleanArray(40000) + for (r in roads) { + degrees[r[0]]++ + degrees[r[1]]++ + connected[(r[0] + 101) * (r[1] + 101) - 1] = true + } + var max = 0 + for (i in 0 until n) { + for (j in i + 1 until n) { + max = if (connected[(i + 101) * (j + 101) - 1]) { + max.coerceAtLeast(degrees[i] + degrees[j] - 1) + } else { + max.coerceAtLeast(degrees[i] + degrees[j]) + } + } + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1616_split_two_strings_to_make_palindrome/readme.md b/src/main/kotlin/g1601_1700/s1616_split_two_strings_to_make_palindrome/readme.md new file mode 100644 index 00000000..c6f179aa --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1616_split_two_strings_to_make_palindrome/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) + +## 1616\. Split Two Strings to Make Palindrome + +Medium + +You are given two strings `a` and `b` of the same length. Choose an index and split both strings **at the same index**, splitting `a` into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting `b` into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome. + +When you split a string `s` into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty. For example, if `s = "abc"`, then `"" + "abc"`, `"a" + "bc"`, `"ab" + "c"` , and `"abc" + ""` are valid splits. + +Return `true` _if it is possible to form_ _a palindrome string, otherwise return_ `false`. + +**Notice** that `x + y` denotes the concatenation of strings `x` and `y`. + +**Example 1:** + +**Input:** a = "x", b = "y" + +**Output:** true **Explaination:** If either a or b are palindromes the answer is true since you can split in the following way: + +aprefix = "", asuffix = "x" + +bprefix = "", bsuffix = "y" + +Then, aprefix + bsuffix = "" + "y" = "y", which is a palindrome. + +**Example 2:** + +**Input:** a = "xbdef", b = "xecab" + +**Output:** false + +**Example 3:** + +**Input:** a = "ulacfd", b = "jizalu" + +**Output:** true **Explaination:** Split them at index 3: + +aprefix = "ula", asuffix = "cfd" + +bprefix = "jiz", bsuffix = "alu" + +Then, aprefix + bsuffix = "ula" + "alu" = "ulaalu", which is a palindrome. + +**Constraints:** + +* 1 <= a.length, b.length <= 105 +* `a.length == b.length` +* `a` and `b` consist of lowercase English letters + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun checkPalindromeFormation(a: String, b: String): Boolean { + return check(a, b) || check(b, a) + } + + private fun check(a: String, b: String): Boolean { + var i = 0 + var j = b.length - 1 + while (j > i && a[i] == b[j]) { + ++i + --j + } + return isPalindrome(a, i, j) || isPalindrome(b, i, j) + } + + private fun isPalindrome(s: String, i: Int, j: Int): Boolean { + var i = i + var j = j + while (j > i && s[i] == s[j]) { + ++i + --j + } + return i >= j + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1617_count_subtrees_with_max_distance_between_cities/readme.md b/src/main/kotlin/g1601_1700/s1617_count_subtrees_with_max_distance_between_cities/readme.md new file mode 100644 index 00000000..0d7a6c73 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1617_count_subtrees_with_max_distance_between_cities/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) + +## 1617\. Count Subtrees With Max Distance Between Cities + +Hard + +There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between each pair of cities. In other words, the cities form a **tree**. + +A **subtree** is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. + +For each `d` from `1` to `n-1`, find the number of subtrees in which the **maximum distance** between any two cities in the subtree is equal to `d`. + +Return _an array of size_ `n-1` _where the_ dth _element **(1-indexed)** is the number of subtrees in which the **maximum distance** between any two cities is equal to_ `d`. + +**Notice** that the **distance** between the two cities is the number of edges in the path between them. + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2020/09/21/p1.png)** + +**Input:** n = 4, edges = \[\[1,2],[2,3],[2,4]] + +**Output:** [3,4,0] + +**Explanation:** + +The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1. + +The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2. + +No subtree has two nodes where the max distance between them is 3. + +**Example 2:** + +**Input:** n = 2, edges = \[\[1,2]] + +**Output:** [1] + +**Example 3:** + +**Input:** n = 3, edges = \[\[1,2],[2,3]] + +**Output:** [2,1] + +**Constraints:** + +* `2 <= n <= 15` +* `edges.length == n-1` +* `edges[i].length == 2` +* 1 <= ui, vi <= n +* All pairs (ui, vi) are distinct. + +## Solution + +```kotlin +import kotlin.math.pow + +class Solution { + private var ans = 0 + private var vis = 0 + + fun countSubgraphsForEachDiameter(n: Int, edges: Array): IntArray { + ans = 0 + vis = 0 + val dist = IntArray(n - 1) + val graph: MutableMap> = HashMap() + for (i in edges) { + graph.computeIfAbsent(1 shl i[0] - 1) { initialCapacity: Int? -> + ArrayList( + initialCapacity!! + ) + }.add(1 shl i[1] - 1) + graph.computeIfAbsent(1 shl i[1] - 1) { initialCapacity: Int? -> + ArrayList( + initialCapacity!! + ) + }.add(1 shl i[0] - 1) + } + val ps = 2.0.pow(n.toDouble()).toInt() - 1 + for (set in 3..ps) { + // is power of 2 + val isp2 = set != 0 && set and set - 1 == 0 + if (!isp2) { + ans = 0 + vis = 0 + dfs(graph, set, Integer.highestOneBit(set), -1) + if (vis == set) { + dist[ans - 1]++ + } + } + } + return dist + } + + private fun dfs(graph: Map>, set: Int, c: Int, p: Int): Int { + if (set and c == 0) { + return 0 + } + vis = vis or c + var fdist = 0 + var sdist = 0 + for (i in graph[c]!!) { + if (i != p) { + val dist = dfs(graph, set, i, c) + if (dist > fdist) { + sdist = fdist + fdist = dist + } else { + sdist = sdist.coerceAtLeast(dist) + } + } + } + ans = ans.coerceAtLeast(fdist + sdist) + return 1 + fdist + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1619_mean_of_array_after_removing_some_elements/readme.md b/src/main/kotlin/g1601_1700/s1619_mean_of_array_after_removing_some_elements/readme.md new file mode 100644 index 00000000..db5346de --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1619_mean_of_array_after_removing_some_elements/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) + +## 1619\. Mean of Array After Removing Some Elements + +Easy + +Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._ + +Answers within 10-5 of the **actual answer** will be considered accepted. + +**Example 1:** + +**Input:** arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3] + +**Output:** 2.00000 + +**Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2. + +**Example 2:** + +**Input:** arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0] + +**Output:** 4.00000 + +**Example 3:** + +**Input:** arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4] + +**Output:** 4.77778 + +**Constraints:** + +* `20 <= arr.length <= 1000` +* `arr.length` **is a multiple** of `20`. +* 0 <= arr[i] <= 105 + +## Solution + +```kotlin +import kotlin.math.roundToInt + +class Solution { + fun trimMean(arr: IntArray): Double { + arr.sort() + val n = arr.size + var sum: Long = 0 + var i = (n * 0.05).roundToInt() + while (i < n - n * 0.05) { + sum += arr[i].toLong() + i++ + } + return sum / (n - n * 0.1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1620_coordinate_with_maximum_network_quality/readme.md b/src/main/kotlin/g1601_1700/s1620_coordinate_with_maximum_network_quality/readme.md new file mode 100644 index 00000000..7fad3694 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1620_coordinate_with_maximum_network_quality/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) + +## 1620\. Coordinate With Maximum Network Quality + +Medium + +You are given an array of network towers `towers`, where towers[i] = [xi, yi, qi] denotes the ith network tower with location (xi, yi) and quality factor qi. All the coordinates are **integral coordinates** on the X-Y plane, and the distance between the two coordinates is the **Euclidean distance**. + +You are also given an integer `radius` where a tower is **reachable** if the distance is **less than or equal to** `radius`. Outside that distance, the signal becomes garbled, and the tower is **not reachable**. + +The signal quality of the ith tower at a coordinate `(x, y)` is calculated with the formula ⌊qi / (1 + d)⌋, where `d` is the distance between the tower and the coordinate. The **network quality** at a coordinate is the sum of the signal qualities from all the **reachable** towers. + +Return _the array_ [cx, cy] _representing the **integral** coordinate_ (cx, cy) _where the **network quality** is maximum. If there are multiple coordinates with the same **network quality**, return the lexicographically minimum **non-negative** coordinate._ + +**Note:** + +* A coordinate `(x1, y1)` is lexicographically smaller than `(x2, y2)` if either: + * `x1 < x2`, or + * `x1 == x2` and `y1 < y2`. +* `⌊val⌋` is the greatest integer less than or equal to `val` (the floor function). + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/22/untitled-diagram.png) + +**Input:** towers = \[\[1,2,5],[2,1,7],[3,1,9]], radius = 2 + +**Output:** [2,1] + +**Explanation:** At coordinate (2, 1) the total quality is 13. + +- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7 + +- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2 + +- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4 + +No other coordinate has a higher network quality. + +**Example 2:** + +**Input:** towers = \[\[23,11,21]], radius = 9 + +**Output:** [23,11] + +**Explanation:** Since there is only one tower, the network quality is highest right at the tower's location. + +**Example 3:** + +**Input:** towers = \[\[1,2,13],[2,1,7],[0,1,9]], radius = 2 + +**Output:** [1,2] + +**Explanation:** Coordinate (1, 2) has the highest network quality. + +**Constraints:** + +* `1 <= towers.length <= 50` +* `towers[i].length == 3` +* 0 <= xi, yi, qi <= 50 +* `1 <= radius <= 50` + +## Solution + +```kotlin +import kotlin.math.floor +import kotlin.math.sqrt + +class Solution { + fun bestCoordinate(towers: Array, radius: Int): IntArray { + val res = IntArray(2) + var maxQuality = 0.0 + var quality: Double + var finalX = 0 + var finalY = 0 + for (i in 0..50) { + for (j in 0..50) { + quality = 0.0 + for (tower in towers) { + val x = tower[0] - i + val y = tower[1] - j + val dist = sqrt(x.toDouble() * x + y * y) + if (dist <= radius) { + quality += floor(tower[2] / (1 + dist)) + } + } + if (maxQuality < quality) { + maxQuality = quality + finalX = i + finalY = j + } + } + } + res[0] = finalX + res[1] = finalY + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1621_number_of_sets_of_k_non_overlapping_line_segments/readme.md b/src/main/kotlin/g1601_1700/s1621_number_of_sets_of_k_non_overlapping_line_segments/readme.md new file mode 100644 index 00000000..822ef5c1 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1621_number_of_sets_of_k_non_overlapping_line_segments/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) + +## 1621\. Number of Sets of K Non-Overlapping Line Segments + +Medium + +Given `n` points on a 1-D plane, where the ith point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do not** have to cover all `n` points, and they are **allowed** to share endpoints. + +Return _the number of ways we can draw_ `k` _non-overlapping line segments__._ Since this number can be huge, return it **modulo** 109 + 7. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/07/ex1.png) + +**Input:** n = 4, k = 2 + +**Output:** 5 + +**Explanation:** The two line segments are shown in red and blue. The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}. + +**Example 2:** + +**Input:** n = 3, k = 1 + +**Output:** 3 + +**Explanation:** The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}. + +**Example 3:** + +**Input:** n = 30, k = 7 + +**Output:** 796297179 + +**Explanation:** The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179. + +**Constraints:** + +* `2 <= n <= 1000` +* `1 <= k <= n-1` + +## Solution + +```kotlin +class Solution { + fun numberOfSets(n: Int, k: Int): Int { + return if (n - 1 >= k) { + val dp = IntArray(k) + val sums = IntArray(k) + val mod = (1e9 + 7).toInt() + for (diff in 1 until n - k + 1) { + dp[0] = (diff + 1) * diff shr 1 + sums[0] = (sums[0] + dp[0]) % mod + for (segments in 2..k) { + dp[segments - 1] = (sums[segments - 2] + dp[segments - 1]) % mod + sums[segments - 1] = (sums[segments - 1] + dp[segments - 1]) % mod + } + } + dp[k - 1] + } else { + 0 + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1622_fancy_sequence/readme.md b/src/main/kotlin/g1601_1700/s1622_fancy_sequence/readme.md new file mode 100644 index 00000000..10821fd2 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1622_fancy_sequence/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) + +## 1622\. Fancy Sequence + +Hard + +Write an API that generates fancy sequences using the `append`, `addAll`, and `multAll` operations. + +Implement the `Fancy` class: + +* `Fancy()` Initializes the object with an empty sequence. +* `void append(val)` Appends an integer `val` to the end of the sequence. +* `void addAll(inc)` Increments all existing values in the sequence by an integer `inc`. +* `void multAll(m)` Multiplies all existing values in the sequence by an integer `m`. +* `int getIndex(idx)` Gets the current value at index `idx` (0-indexed) of the sequence **modulo** 109 + 7. If the index is greater or equal than the length of the sequence, return `-1`. + +**Example 1:** + +**Input** ["Fancy", "append", "addAll", "append", "multAll", "getIndex", "addAll", "append", "multAll", "getIndex", "getIndex", "getIndex"] [[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]] + +**Output:** [null, null, null, null, null, 10, null, null, null, 26, 34, 20] + +**Explanation:** + +Fancy fancy = new Fancy(); + +fancy.append(2); // fancy sequence: [2] + +fancy.addAll(3); // fancy sequence: [2+3] -> [5] + +fancy.append(7); // fancy sequence: [5, 7] + +fancy.multAll(2); // fancy sequence: [5\*2, 7\*2] -> [10, 14] + +fancy.getIndex(0); // return 10 + +fancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17] + +fancy.append(10); // fancy sequence: [13, 17, 10] + +fancy.multAll(2); // fancy sequence: [13\*2, 17\*2, 10\*2] -> [26, 34, 20] + +fancy.getIndex(0); // return 26 + +fancy.getIndex(1); // return 34 + +fancy.getIndex(2); // return 20 + +**Constraints:** + +* `1 <= val, inc, m <= 100` +* 0 <= idx <= 105 +* At most 105 calls total will be made to `append`, `addAll`, `multAll`, and `getIndex`. + +## Solution + +```kotlin +class Fancy { + private var values = IntArray(8) + private var add: Long = 0 + private var mult: Long = 1 + private var rMult: Long = 1 + private var size = 0 + private var inverses = cache() + fun append(`val`: Int) { + val result = (`val` - add + MOD) * rMult % MOD + if (size >= values.size) { + values = values.copyOf(size + (size shl 1)) + } + values[size++] = result.toInt() + } + + fun addAll(inc: Int) { + add = (add + inc) % MOD + } + + fun multAll(m: Int) { + mult = mult * m % MOD + add = add * m % MOD + rMult = rMult * inverses[m] % MOD + } + + fun getIndex(idx: Int): Int { + return if (idx >= size) { + -1 + } else ((mult * values[idx] + add) % MOD).toInt() + } + + private fun multiplicativeInverse(x: Int): Int { + var y: Long = 1 + val m = MOD.toLong() - 2 + var p = x.toLong() + var i = 0 + while (1L shl i < m) { + if (m shr i and 1L == 1L) { + y = y * p % MOD + } + i++ + p = p * p % MOD + } + return y.toInt() + } + + private fun cache(): IntArray { + inverses = IntArray(101) + inverses[0] = 0 + inverses[1] = 1 + for (i in 2 until inverses.size) { + inverses[i] = multiplicativeInverse(i) + } + return inverses + } + + companion object { + private const val MOD = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1624_largest_substring_between_two_equal_characters/readme.md b/src/main/kotlin/g1601_1700/s1624_largest_substring_between_two_equal_characters/readme.md new file mode 100644 index 00000000..4c4414d0 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1624_largest_substring_between_two_equal_characters/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) + +## 1624\. Largest Substring Between Two Equal Characters + +Easy + +Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. + +A **substring** is a contiguous sequence of characters within a string. + +**Example 1:** + +**Input:** s = "aa" + +**Output:** 0 + +**Explanation:** The optimal substring here is an empty substring between the two `'a's`. + +**Example 2:** + +**Input:** s = "abca" + +**Output:** 2 + +**Explanation:** The optimal substring here is "bc". + +**Example 3:** + +**Input:** s = "cbzxy" + +**Output:** -1 + +**Explanation:** There are no characters that appear twice in s. + +**Constraints:** + +* `1 <= s.length <= 300` +* `s` contains only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun maxLengthBetweenEqualCharacters(s: String): Int { + val lenS = s.length + val firstIndexesOf = IntArray(26) { -1 } + var longest = -1 + for (idx in 0 until lenS) { + val idxCh = (s[idx] - 'a') + if (firstIndexesOf[idxCh] < 0) { + firstIndexesOf[idxCh] = idx + } else { + val len = idx - firstIndexesOf[idxCh] + 1 - 2 + longest = maxOf(longest, len) + } + } + return longest + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1625_lexicographically_smallest_string_after_applying_operations/readme.md b/src/main/kotlin/g1601_1700/s1625_lexicographically_smallest_string_after_applying_operations/readme.md new file mode 100644 index 00000000..4d889e79 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1625_lexicographically_smallest_string_after_applying_operations/readme.md @@ -0,0 +1,137 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1625\. Lexicographically Smallest String After Applying Operations + +Medium + +You are given a string `s` of **even length** consisting of digits from `0` to `9`, and two integers `a` and `b`. + +You can apply either of the following two operations any number of times and in any order on `s`: + +* Add `a` to all odd indices of `s` **(0-indexed)**. Digits post `9` are cycled back to `0`. For example, if `s = "3456"` and `a = 5`, `s` becomes `"3951"`. +* Rotate `s` to the right by `b` positions. For example, if `s = "3456"` and `b = 1`, `s` becomes `"6345"`. + +Return _the **lexicographically smallest** string you can obtain by applying the above operations any number of times on_ `s`. + +A string `a` is lexicographically smaller than a string `b` (of the same length) 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`. For example, `"0158"` is lexicographically smaller than `"0190"` because the first position they differ is at the third letter, and `'5'` comes before `'9'`. + +**Example 1:** + +**Input:** s = "5525", a = 9, b = 2 + +**Output:** "2050" + +**Explanation:** We can apply the following operations: + +Start: "5525" + +Rotate: "2555" + +Add: "2454" + +Add: "2353" + +Rotate: "5323" + +Add: "5222" + +Add: "5121" + +Rotate: "2151" + +Add: "2050" + +There is no way to obtain a string that is lexicographically smaller then "2050". + +**Example 2:** + +**Input:** s = "74", a = 5, b = 1 + +**Output:** "24" + +**Explanation:** We can apply the following operations: + +Start: "74" + +Rotate: "47" + +Add: "42" + +Rotate: "24" + +There is no way to obtain a string that is lexicographically smaller then "24". + +**Example 3:** + +**Input:** s = "0011", a = 4, b = 2 + +**Output:** "0011" + +**Explanation:** There are no sequence of operations that will give us a lexicographically smaller string than "0011". + +**Constraints:** + +* `2 <= s.length <= 100` +* `s.length` is even. +* `s` consists of digits from `0` to `9` only. +* `1 <= a <= 9` +* `1 <= b <= s.length - 1` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + private var ans = "z" + + private fun dfs(s: String, a: Int, b: Int, set: HashSet) { + if (set.contains(s)) { + return + } + set.add(s) + val one = add(s, a) + val two = rotate(s, b) + dfs(one, a, b, set) + dfs(two, a, b, set) + } + + private fun add(s: String, a: Int): String { + var s = s + val temp = s.toCharArray() + var i = 1 + while (i < temp.size) { + var `val` = temp[i].code - '0'.code + `val` = (`val` + a) % 10 + temp[i] = (`val` + '0'.code).toChar() + i += 2 + } + s = String(temp) + if (ans > s) { + ans = s + } + return s + } + + private fun rotate(s: String, b: Int): String { + var s = s + var b = b + if (b < 0) { + b += s.length + } + b %= s.length + b = s.length - b + s = s.substring(b) + s.substring(0, b) + if (ans > s) { + ans = s + } + return s + } + + fun findLexSmallestString(s: String, a: Int, b: Int): String { + val set = HashSet() + dfs(s, a, b, set) + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1626_best_team_with_no_conflicts/readme.md b/src/main/kotlin/g1601_1700/s1626_best_team_with_no_conflicts/readme.md new file mode 100644 index 00000000..05b0b46c --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1626_best_team_with_no_conflicts/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) + +## 1626\. Best Team With No Conflicts + +Medium + +You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the **sum** of scores of all the players in the team. + +However, the basketball team is not allowed to have **conflicts**. A **conflict** exists if a younger player has a **strictly higher** score than an older player. A conflict does **not** occur between players of the same age. + +Given two lists, `scores` and `ages`, where each `scores[i]` and `ages[i]` represents the score and age of the ith player, respectively, return _the highest overall score of all possible basketball teams_. + +**Example 1:** + +**Input:** scores = [1,3,5,10,15], ages = [1,2,3,4,5] + +**Output:** 34 + +**Explanation:** You can choose all the players. + +**Example 2:** + +**Input:** scores = [4,5,6,5], ages = [2,1,2,1] + +**Output:** 16 + +**Explanation:** It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age. + +**Example 3:** + +**Input:** scores = [1,2,3,5], ages = [8,9,10,1] + +**Output:** 6 + +**Explanation:** It is best to choose the first 3 players. + +**Constraints:** + +* `1 <= scores.length, ages.length <= 1000` +* `scores.length == ages.length` +* 1 <= scores[i] <= 106 +* `1 <= ages[i] <= 1000` + +## Solution + +```kotlin +class Solution { + private class Player( + val age: Int, + val score: Int + ) : Comparable { + override fun compareTo(other: Player) = + if (age == other.age) { + other.score - score + } else { + other.age - age + } + } + + fun bestTeamScore(scores: IntArray, ages: IntArray): Int { + val playerList = mutableListOf() + repeat(scores.size) { + playerList.add( + Player( + age = ages[it], + score = scores[it] + ) + ) + } + + playerList.sort() + val dp = IntArray(scores.size) + var bestScore = 0 + for (i in scores.indices) { + val currentPlayer = playerList[i] + dp[i] = currentPlayer.score + for (j in 0 until i) { + if (playerList[j].score >= currentPlayer.score) { + dp[i] = maxOf(dp[i], dp[j] + currentPlayer.score) + } + } + bestScore = maxOf(bestScore, dp[i]) + } + + return bestScore + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1627_graph_connectivity_with_threshold/readme.md b/src/main/kotlin/g1601_1700/s1627_graph_connectivity_with_threshold/readme.md new file mode 100644 index 00000000..e406068e --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1627_graph_connectivity_with_threshold/readme.md @@ -0,0 +1,148 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1627\. Graph Connectivity With Threshold + +Hard + +We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an integer `z` such that all of the following are true: + +* `x % z == 0`, +* `y % z == 0`, and +* `z > threshold`. + +Given the two integers, `n` and `threshold`, and an array of `queries`, you must determine for each queries[i] = [ai, bi] if cities ai and bi are connected directly or indirectly. (i.e. there is some path between them). + +Return _an array_ `answer`_, where_ `answer.length == queries.length` _and_ `answer[i]` _is_ `true` _if for the_ ith _query, there is a path between_ ai _and_ bi_, or_ `answer[i]` _is_ `false` _if there is no path._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/09/ex1.jpg) + +**Input:** n = 6, threshold = 2, queries = \[\[1,4],[2,5],[3,6]] + +**Output:** [false,false,true] + +**Explanation:** The divisors for each number: + +1: 1 + +2: 1, 2 + +3: 1, 3 + +4: 1, 2, 4 + +5: 1, 5 + +6: 1, 2, 3, 6 + +Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the only ones directly connected. The result of each query: + +[1,4] 1 is not connected to 4 + +[2,5] 2 is not connected to 5 + +[3,6] 3 is connected to 6 through path 3--6 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/10/10/tmp.jpg) + +**Input:** n = 6, threshold = 0, queries = \[\[4,5],[3,4],[3,2],[2,6],[1,3]] + +**Output:** [true,true,true,true,true] + +**Explanation:** The divisors for each number are the same as the previous example. However, since the threshold is 0, all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2020/10/17/ex3.jpg) + +**Input:** n = 5, threshold = 1, queries = \[\[4,5],[4,5],[3,2],[2,3],[3,4]] + +**Output:** [false,false,false,false,false] + +**Explanation:** Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected. Please notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x]. + +**Constraints:** + +* 2 <= n <= 104 +* `0 <= threshold <= n` +* 1 <= queries.length <= 105 +* `queries[i].length == 2` +* 1 <= ai, bi <= cities +* ai != bi + +## Solution + +```kotlin +class Solution { + fun areConnected(n: Int, threshold: Int, queries: Array): List { + if (n < 1 || queries.isEmpty()) { + return ArrayList() + } + var j: Int + var k: Int + var x: Int + val set = DisjointSetUnion(n + 1) + val edges = queries.size + var i: Int = threshold + 1 + while (i <= n) { + k = n / i + x = i + j = 2 + while (j <= k) { + x += i + set.union(i, x) + j++ + } + i++ + } + val result: MutableList = ArrayList(edges) + for (query in queries) { + result.add(set.find(query[0]) == set.find(query[1])) + } + return result + } + + private class DisjointSetUnion(n: Int) { + private val rank: IntArray + private val parent: IntArray + + init { + rank = IntArray(n) + parent = IntArray(n) + for (i in 0 until n) { + rank[i] = 1 + parent[i] = i + } + } + + fun find(u: Int): Int { + var x = u + while (x != parent[x]) { + x = parent[x] + } + parent[u] = x + return x + } + + fun union(u: Int, v: Int) { + if (u != v) { + val x = find(u) + val y = find(v) + if (x != y) { + if (rank[x] > rank[y]) { + rank[x] += rank[y] + parent[y] = x + } else { + rank[y] += rank[x] + parent[x] = y + } + } + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1629_slowest_key/readme.md b/src/main/kotlin/g1601_1700/s1629_slowest_key/readme.md new file mode 100644 index 00000000..cf49ced6 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1629_slowest_key/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) + +## 1629\. Slowest Key + +Easy + +A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time. + +You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the ith key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the ith key was released. Both arrays are **0-indexed**. The 0th key was pressed at the time `0`, and every subsequent key was pressed at the **exact** time the previous key was released. + +The tester wants to know the key of the keypress that had the **longest duration**. The ith keypress had a **duration** of `releaseTimes[i] - releaseTimes[i - 1]`, and the 0th keypress had a duration of `releaseTimes[0]`. + +Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key **may not** have had the same **duration**. + +_Return the key of the keypress that had the **longest duration**. If there are multiple such keypresses, return the lexicographically largest key of the keypresses._ + +**Example 1:** + +**Input:** releaseTimes = [9,29,49,50], keysPressed = "cbcd" + +**Output:** "c" + +**Explanation:** The keypresses were as follows: + +Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9). + +Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29). + +Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49). + +Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50). + +The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20. 'c' is lexicographically larger than 'b', so the answer is 'c'. + +**Example 2:** + +**Input:** releaseTimes = [12,23,36,46,62], keysPressed = "spuda" + +**Output:** "a" + +**Explanation:** + +The keypresses were as follows: Keypress for 's' had a duration of 12. + +Keypress for 'p' had a duration of 23 - 12 = 11. + +Keypress for 'u' had a duration of 36 - 23 = 13. + +Keypress for 'd' had a duration of 46 - 36 = 10. + +Keypress for 'a' had a duration of 62 - 46 = 16. + +The longest of these was the keypress for 'a' with duration 16. + +**Constraints:** + +* `releaseTimes.length == n` +* `keysPressed.length == n` +* `2 <= n <= 1000` +* 1 <= releaseTimes[i] <= 109 +* `releaseTimes[i] < releaseTimes[i+1]` +* `keysPressed` contains only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun slowestKey(releaseTimes: IntArray, keysPressed: String): Char { + val map: MutableMap = HashMap() + for (i in releaseTimes.indices) { + val c = keysPressed[i] + val duration: Int = if (i == 0) { + releaseTimes[i] + } else { + releaseTimes[i] - releaseTimes[i - 1] + } + if (!map.containsKey(c)) { + map[c] = duration + } else { + val `val` = map[c]!! + if (duration > `val`) { + map[c] = duration + } + } + } + val map2: MutableMap> = HashMap() + for ((key, duration) in map) { + if (!map2.containsKey(duration)) { + map2[duration] = ArrayList() + } + map2[duration]!!.add(key) + } + var max = -1 + for ((key, chars) in map2) { + chars.sort() + map2[key] = chars + max = max.coerceAtLeast(key) + } + return map2[max]!![map2[max]!!.size - 1] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1630_arithmetic_subarrays/readme.md b/src/main/kotlin/g1601_1700/s1630_arithmetic_subarrays/readme.md new file mode 100644 index 00000000..fcb223f8 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1630_arithmetic_subarrays/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) + +## 1630\. Arithmetic Subarrays + +Medium + +A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0]` for all valid `i`. + +For example, these are **arithmetic** sequences: + +1, 3, 5, 7, 9 7, 7, 7, 7 3, -1, -5, -9 + +The following sequence is not **arithmetic**: + +1, 1, 2, 5, 7 + +You are given an array of `n` integers, `nums`, and two arrays of `m` integers each, `l` and `r`, representing the `m` range queries, where the ith query is the range `[l[i], r[i]]`. All the arrays are **0-indexed**. + +Return _a list of_ `boolean` _elements_ `answer`_, where_ `answer[i]` _is_ `true` _if the subarray_ `nums[l[i]], nums[l[i]+1], ... , nums[r[i]]` _can be **rearranged** to form an **arithmetic** sequence, and_ `false` _otherwise._ + +**Example 1:** + +**Input:** nums = `[4,6,5,9,3,7]`, l = `[0,0,2]`, r = `[2,3,5]` + +**Output:** `[true,false,true]` + +**Explanation:** + +In the 0th query, the subarray is [4,6,5]. + +This can be rearranged as [6,5,4], which is an arithmetic sequence. + +In the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence. + +In the 2nd query, the subarray is `[5,9,3,7]. This` can be rearranged as `[3,5,7,9]`, which is an arithmetic sequence. + +**Example 2:** + +**Input:** nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10] + +**Output:** [false,true,false,false,true,true] + +**Constraints:** + +* `n == nums.length` +* `m == l.length` +* `m == r.length` +* `2 <= n <= 500` +* `1 <= m <= 500` +* `0 <= l[i] < r[i] < n` +* -105 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun checkArithmeticSubarrays(nums: IntArray, l: IntArray, r: IntArray): List { + val result: MutableList = ArrayList() + val n = l.size + for (i in 0 until n) { + result.add(check(nums, l[i], r[i])) + } + return result + } + + private fun check(nums: IntArray, l: Int, r: Int): Boolean { + val n = r - l + if (n == 0) { + return true + } + var max = Int.MIN_VALUE + var min = Int.MAX_VALUE + for (i in l..r) { + max = max.coerceAtLeast(nums[i]) + min = min.coerceAtMost(nums[i]) + } + if ((max - min) % n != 0) { + return false + } + val diff = (max - min) / n + if (diff == 0) { + return true + } + val checked = BooleanArray(max - min + 1) + for (i in l..r) { + val currentDiff = nums[i] - min + if (checked[currentDiff] || currentDiff % diff != 0) { + return false + } + checked[currentDiff] = true + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1631_path_with_minimum_effort/readme.md b/src/main/kotlin/g1601_1700/s1631_path_with_minimum_effort/readme.md new file mode 100644 index 00000000..4e70b473 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1631_path_with_minimum_effort/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) + +## 1631\. Path With Minimum Effort + +Medium + +You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., **0-indexed**). You can move **up**, **down**, **left**, or **right**, and you wish to find a route that requires the minimum **effort**. + +A route's **effort** is the **maximum absolute difference** in heights between two consecutive cells of the route. + +Return _the minimum **effort** required to travel from the top-left cell to the bottom-right cell._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/04/ex1.png) + +**Input:** heights = \[\[1,2,2],[3,8,2],[5,3,5]] + +**Output:** 2 + +**Explanation:** The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells. This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/10/04/ex2.png) + +**Input:** heights = \[\[1,2,3],[3,8,4],[5,3,5]] + +**Output:** 1 + +**Explanation:** The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5]. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2020/10/04/ex3.png) + +**Input:** heights = \[\[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]] + +**Output:** 0 + +**Explanation:** This route does not require any effort. + +**Constraints:** + +* `rows == heights.length` +* `columns == heights[i].length` +* `1 <= rows, columns <= 100` +* 1 <= heights[i][j] <= 106 + +## Solution + +```kotlin +import java.util.PriorityQueue +import kotlin.math.abs + +class Solution { + private class Pair internal constructor(var row: Int, var col: Int, var diff: Int) : Comparable { + override fun compareTo(other: Pair): Int { + return diff - other.diff + } + } + + fun minimumEffortPath(heights: Array): Int { + val n = heights.size + val m = heights[0].size + val pq = PriorityQueue() + pq.add(Pair(0, 0, 0)) + val vis = Array(n) { BooleanArray(m) } + val dx = intArrayOf(-1, 0, 1, 0) + val dy = intArrayOf(0, 1, 0, -1) + var min = Int.MAX_VALUE + while (pq.isNotEmpty()) { + val p = pq.remove() + val row = p.row + val col = p.col + val diff = p.diff + if (vis[row][col]) { + continue + } + vis[row][col] = true + if (row == n - 1 && col == m - 1) { + min = min.coerceAtMost(diff) + } + for (i in 0..3) { + val r = row + dx[i] + val c = col + dy[i] + if (r < 0 || c < 0 || r >= n || c >= m || vis[r][c]) { + continue + } + pq.add( + Pair( + r, c, + diff.coerceAtLeast( + abs( + heights[r][c] - heights[row][col] + ) + ) + ) + ) + } + } + return min + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1632_rank_transform_of_a_matrix/readme.md b/src/main/kotlin/g1601_1700/s1632_rank_transform_of_a_matrix/readme.md new file mode 100644 index 00000000..51e88240 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1632_rank_transform_of_a_matrix/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) + +## 1632\. Rank Transform of a Matrix + +Hard + +Given an `m x n` `matrix`, return _a new matrix_ `answer` _where_ `answer[row][col]` _is the_ _**rank** of_ `matrix[row][col]`. + +The **rank** is an **integer** that represents how large an element is compared to other elements. It is calculated using the following rules: + +* The rank is an integer starting from `1`. +* If two elements `p` and `q` are in the **same row or column**, then: + * If `p < q` then `rank(p) < rank(q)` + * If `p == q` then `rank(p) == rank(q)` + * If `p > q` then `rank(p) > rank(q)` +* The **rank** should be as **small** as possible. + +The test cases are generated so that `answer` is unique under the given rules. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/18/rank1.jpg) + +**Input:** matrix = \[\[1,2],[3,4]] + +**Output:** [[1,2],[2,3]] + +**Explanation:** + +The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column. + +The rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1. + +The rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1. + +The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/10/18/rank2.jpg) + +**Input:** matrix = \[\[7,7],[7,7]] + +**Output:** [[1,1],[1,1]] + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2020/10/18/rank3.jpg) + +**Input:** matrix = \[\[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]] + +**Output:** [[4,2,3],[1,3,4],[5,1,6],[1,3,4]] + +**Constraints:** + +* `m == matrix.length` +* `n == matrix[i].length` +* `1 <= m, n <= 500` +* -109 <= matrix[row][col] <= 109 + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun matrixRankTransform(matrix: Array): Array { + val rowCount = matrix.size + val colCount = matrix[0].size + val nums = LongArray(rowCount * colCount) + var numsIdx = 0 + val rows = IntArray(rowCount) + val cols = IntArray(colCount) + for (r in rowCount - 1 downTo 0) { + for (c in colCount - 1 downTo 0) { + nums[numsIdx++] = matrix[r][c].toLong() shl 32 or (r.toLong() shl 16) or c.toLong() + } + } + nums.sort() + var nIdx = 0 + while (nIdx < numsIdx) { + val num = nums[nIdx] and -0x100000000L + var endIdx = nIdx + 1 + while (endIdx < numsIdx && nums[endIdx] and -0x100000000L == num) { + endIdx++ + } + doGroup(matrix, nums, nIdx, endIdx, rows, cols) + nIdx = endIdx + } + return matrix + } + + private fun doGroup( + matrix: Array, + nums: LongArray, + startIdx: Int, + endIdx: Int, + rows: IntArray, + cols: IntArray + ) { + if (startIdx + 1 == endIdx) { + val r = nums[startIdx].toInt() shr 16 and 0xFFFF + val c = nums[startIdx].toInt() and 0xFFFF + cols[c] = rows[r].coerceAtLeast(cols[c]) + 1 + rows[r] = cols[c] + matrix[r][c] = rows[r] + } else { + val rowCount = matrix.size + val ufind = IntArray(rowCount + matrix[0].size) + Arrays.fill(ufind, -1) + for (nIdx in startIdx until endIdx) { + val r = nums[nIdx].toInt() shr 16 and 0xFFFF + val c = nums[nIdx].toInt() and 0xFFFF + val pr = getIdx(ufind, r) + val pc = getIdx(ufind, rowCount + c) + if (pr != pc) { + ufind[pr] = ufind[pr].coerceAtMost(ufind[pc]) + .coerceAtMost( + -rows[r] + .coerceAtLeast(cols[c]) - 1 + ) + ufind[pc] = pr + } + } + for (nIdx in startIdx until endIdx) { + val r = nums[nIdx].toInt() shr 16 and 0xFFFF + val c = nums[nIdx].toInt() and 0xFFFF + cols[c] = -ufind[getIdx(ufind, r)] + rows[r] = cols[c] + matrix[r][c] = rows[r] + } + } + } + + private fun getIdx(ufind: IntArray, idx: Int): Int { + return if (ufind[idx] < 0) { + idx + } else { + ufind[idx] = getIdx(ufind, ufind[idx]) + ufind[idx] + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1633_percentage_of_users_attended_a_contest/readme.md b/src/main/kotlin/g1601_1700/s1633_percentage_of_users_attended_a_contest/readme.md new file mode 100644 index 00000000..5d4280e6 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1633_percentage_of_users_attended_a_contest/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) + +## 1633\. Percentage of Users Attended a Contest + +Easy + +SQL Schema + +Table: `Users` + + +-------------+---------+ + | Column Name | Type | + +-------------+---------+ + | user_id | int | + | user_name | varchar | + +-------------+---------+ + +user_id is the primary key for this table. Each row of this table contains the name and the id of a user. + +Table: `Register` + + +-------------+---------+ + | Column Name | Type | + +-------------+---------+ + | contest_id | int | + | user_id | int | + +-------------+---------+ + +(contest_id, user_id) is the primary key for this table. Each row of this table contains the id of a user and the contest they registered into. + +Write an SQL query to find the percentage of the users registered in each contest rounded to **two decimals**. + +Return the result table ordered by `percentage` in **descending order**. In case of a tie, order it by `contest_id` in **ascending order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** Users table: + + +---------+-----------+ + | user_id | user_name | + +---------+-----------+ + | 6 | Alice | + | 2 | Bob | + | 7 | Alex | + +---------+-----------+ + +Register table: + + +------------+---------+ + | contest_id | user_id | + +------------+---------+ + | 215 | 6 | + | 209 | 2 | + | 208 | 2 | + | 210 | 6 | + | 208 | 6 | + | 209 | 7 | + | 209 | 6 | + | 215 | 7 | + | 208 | 7 | + | 210 | 2 | + | 207 | 2 | + | 210 | 7 | + +------------+---------+ + +**Output:** + + +------------+------------+ + | contest_id | percentage | + +------------+------------+ + | 208 | 100.0 | + | 209 | 100.0 | + | 210 | 100.0 | + | 215 | 66.67 | + | 207 | 33.33 | + +------------+------------+ + +**Explanation:** + +All the users registered in contests 208, 209, and 210. + +The percentage is 100% and we sort them in the answer table by contest_id in ascending order. + +Alice and Alex registered in contest 215 and the percentage is ((2/3) * 100) = 66.67% + +Bob registered in contest 207 and the percentage is ((1/3) * 100) = 33.33% + +## Solution + +```sql +# Write your MySQL query statement below +select contest_id, +round(count(contest_id)/( + select count(distinct user_id) from Users +)*100.0,2) as percentage +from Register +group by contest_id +order by percentage desc, contest_id asc +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1636_sort_array_by_increasing_frequency/readme.md b/src/main/kotlin/g1601_1700/s1636_sort_array_by_increasing_frequency/readme.md new file mode 100644 index 00000000..1aaaeb9e --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1636_sort_array_by_increasing_frequency/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) + +## 1636\. Sort Array by Increasing Frequency + +Easy + +Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order. + +Return the _sorted array_. + +**Example 1:** + +**Input:** nums = [1,1,2,2,2,3] + +**Output:** [3,1,1,2,2,2] + +**Explanation:** '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3. + +**Example 2:** + +**Input:** nums = [2,3,1,3,2] + +**Output:** [1,3,3,2,2] + +**Explanation:** '2' and '3' both have a frequency of 2, so they are sorted in decreasing order. + +**Example 3:** + +**Input:** nums = [-1,1,-6,4,5,-6,1,4,1] + +**Output:** [5,-1,4,4,-6,-6,1,1,1] + +**Constraints:** + +* `1 <= nums.length <= 100` +* `-100 <= nums[i] <= 100` + +## Solution + +```kotlin +import java.util.Collections +import java.util.TreeMap + +class Solution { + fun frequencySort(nums: IntArray): IntArray { + val count: MutableMap = HashMap() + for (num in nums) { + count[num] = count.getOrDefault(num, 0) + 1 + } + val map = TreeMap>() + for ((key, freq) in count) { + map.putIfAbsent(freq, ArrayList()) + val list = map[freq]!! + list.add(key) + map[freq] = list + } + val result = IntArray(nums.size) + var i = 0 + for (entry in map.entries) { + val list = entry.value + list.sortWith(Collections.reverseOrder()) + var k = entry.key + var j = 0 + while (j < list.size) { + while (k-- > 0) { + result[i++] = list[j] + } + j++ + k = entry.key + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1637_widest_vertical_area_between_two_points_containing_no_points/readme.md b/src/main/kotlin/g1601_1700/s1637_widest_vertical_area_between_two_points_containing_no_points/readme.md new file mode 100644 index 00000000..15d98818 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1637_widest_vertical_area_between_two_points_containing_no_points/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) + +## 1637\. Widest Vertical Area Between Two Points Containing No Points + +Medium + +Given `n` `points` on a 2D plane where points[i] = [xi, yi], Return_ the **widest vertical area** between two points such that no points are inside the area._ + +A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the maximum width. + +Note that points **on the edge** of a vertical area **are not** considered included in the area. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/19/points3.png) + +**Input:** points = \[\[8,7],[9,9],[7,4],[9,7]] + +**Output:** 1 + +**Explanation:** Both the red and the blue area are optimal. + +**Example 2:** + +**Input:** points = \[\[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]] + +**Output:** 3 + +**Constraints:** + +* `n == points.length` +* 2 <= n <= 105 +* `points[i].length == 2` +* 0 <= xi, yi <= 109 + +## Solution + +```kotlin +class Solution { + fun maxWidthOfVerticalArea(points: Array): Int { + val xValues = IntArray(points.size) + for (i in points.indices) { + xValues[i] = points[i][0] + } + xValues.sort() + var max = 0 + for (j in 0 until xValues.size - 1) { + if (xValues[j + 1] - xValues[j] > max) { + max = xValues[j + 1] - xValues[j] + } + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1638_count_substrings_that_differ_by_one_character/readme.md b/src/main/kotlin/g1601_1700/s1638_count_substrings_that_differ_by_one_character/readme.md new file mode 100644 index 00000000..a377c92e --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1638_count_substrings_that_differ_by_one_character/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) + +## 1638\. Count Substrings That Differ by One Character + +Medium + +Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly** one character. + +For example, the underlined substrings in `"computer"` and `"computation"` only differ by the `'e'`/`'a'`, so this is a valid way. + +Return _the number of substrings that satisfy the condition above._ + +A **substring** is a contiguous sequence of characters within a string. + +**Example 1:** + +**Input:** s = "aba", t = "baba" + +**Output:** 6 + +**Explanation:** The following are the pairs of substrings from s and t that differ by exactly 1 character: + +("aba", "baba") + +("aba", "baba") + +("aba", "baba") + +("aba", "baba") + +("aba", "baba") + +("aba", "baba") + +The underlined portions are the substrings that are chosen from s and t. + +**Example 2:** + +**Input:** s = "ab", t = "bb" + +**Output:** 3 + +**Explanation:** The following are the pairs of substrings from s and t that differ by 1 character: + +("ab", "bb") + +("ab", "bb") + +("ab", "bb") + +The underlined portions are the substrings that are chosen from s and t. + +**Constraints:** + +* `1 <= s.length, t.length <= 100` +* `s` and `t` consist of lowercase English letters only. + +## Solution + +```kotlin +class Solution { + fun countSubstrings(s: String, t: String): Int { + var ans = 0 + val n = s.length + val m = t.length + val dp = Array(n + 1) { IntArray(m + 1) } + val tp = Array(n + 1) { IntArray(m + 1) } + for (i in n - 1 downTo 0) { + for (j in m - 1 downTo 0) { + if (s[i] == t[j]) { + dp[i][j] = dp[i + 1][j + 1] + 1 + tp[i][j] = tp[i + 1][j + 1] + } else { + tp[i][j] = dp[i + 1][j + 1] + 1 + } + ans += tp[i][j] + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1639_number_of_ways_to_form_a_target_string_given_a_dictionary/readme.md b/src/main/kotlin/g1601_1700/s1639_number_of_ways_to_form_a_target_string_given_a_dictionary/readme.md new file mode 100644 index 00000000..d6396461 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1639_number_of_ways_to_form_a_target_string_given_a_dictionary/readme.md @@ -0,0 +1,125 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1639\. Number of Ways to Form a Target String Given a Dictionary + +Hard + +You are given a list of strings of the **same length** `words` and a string `target`. + +Your task is to form `target` using the given `words` under the following rules: + +* `target` should be formed from left to right. +* To form the ith character (**0-indexed**) of `target`, you can choose the kth character of the jth string in `words` if `target[i] = words[j][k]`. +* Once you use the kth character of the jth string of `words`, you **can no longer** use the xth character of any string in `words` where `x <= k`. In other words, all characters to the left of or at index `k` become unusuable for every string. +* Repeat the process until you form the string `target`. + +**Notice** that you can use **multiple characters** from the **same string** in `words` provided the conditions above are met. + +Return _the number of ways to form `target` from `words`_. Since the answer may be too large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** words = ["acca","bbbb","caca"], target = "aba" + +**Output:** 6 + +**Explanation:** There are 6 ways to form target. + +"aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("caca") + +"aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("caca") + +"aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("acca") + +"aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("acca") + +"aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("acca") + +"aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("caca") + +**Example 2:** + +**Input:** words = ["abba","baab"], target = "bab" + +**Output:** 4 + +**Explanation:** There are 4 ways to form target. + +"bab" -> index 0 ("baab"), index 1 ("baab"), index 2 ("abba") + +"bab" -> index 0 ("baab"), index 1 ("baab"), index 3 ("baab") + +"bab" -> index 0 ("baab"), index 2 ("baab"), index 3 ("baab") + +"bab" -> index 1 ("abba"), index 2 ("baab"), index 3 ("baab") + +**Constraints:** + +* `1 <= words.length <= 1000` +* `1 <= words[i].length <= 1000` +* All strings in `words` have the same length. +* `1 <= target.length <= 1000` +* `words[i]` and `target` contain only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun numWays(words: Array, target: String): Int { + val counts = precompute(words) + val memo = Array(target.length) { arrayOfNulls(words[0].length) } + return solve(memo, counts, words, target, 0, 0) + } + + private fun precompute(words: Array): Array { + val counts = Array(words[0].length) { IntArray(26) } + for (word in words) { + for (idx in word.indices) { + counts[idx][word[idx].code - 'a'.code]++ + } + } + return counts + } + + private fun solve( + memo: Array>, + counts: Array, + words: Array, + target: String, + idx: Int, + len: Int + ): Int { + if (idx >= target.length) { + return 1 + } + if (len >= words[0].length || words[0].length - len < target.length - idx) { + return 0 + } + if (memo[idx][len] != null) { + return memo[idx][len]!! + } + var answer = 0 + answer += solve(memo, counts, words, target, idx, len + 1) + answer %= MOD + answer += ( + solve( + memo, + counts, + words, + target, + idx + 1, + len + 1 + ).toLong() * counts[len][target[idx].code - 'a'.code] % + MOD + ).toInt() + answer %= MOD + memo[idx][len] = answer + return memo[idx][len]!! + } + + companion object { + private const val MOD = 1e9.toInt() + 7 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1640_check_array_formation_through_concatenation/readme.md b/src/main/kotlin/g1601_1700/s1640_check_array_formation_through_concatenation/readme.md new file mode 100644 index 00000000..be74a0ba --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1640_check_array_formation_through_concatenation/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) + +## 1640\. Check Array Formation Through Concatenation + +Easy + +You are given an array of **distinct** integers `arr` and an array of integer arrays `pieces`, where the integers in `pieces` are **distinct**. Your goal is to form `arr` by concatenating the arrays in `pieces` **in any order**. However, you are **not** allowed to reorder the integers in each array `pieces[i]`. + +Return `true` _if it is possible_ _to form the array_ `arr` _from_ `pieces`. Otherwise, return `false`. + +**Example 1:** + +**Input:** arr = [15,88], pieces = \[\[88],[15]] + +**Output:** true + +**Explanation:** Concatenate [15] then [88] + +**Example 2:** + +**Input:** arr = [49,18,16], pieces = \[\[16,18,49]] + +**Output:** false + +**Explanation:** Even though the numbers match, we cannot reorder pieces[0]. + +**Example 3:** + +**Input:** arr = [91,4,64,78], pieces = \[\[78],[4,64],[91]] + +**Output:** true + +**Explanation:** Concatenate [91] then [4,64] then [78] + +**Constraints:** + +* `1 <= pieces.length <= arr.length <= 100` +* `sum(pieces[i].length) == arr.length` +* `1 <= pieces[i].length <= arr.length` +* `1 <= arr[i], pieces[i][j] <= 100` +* The integers in `arr` are **distinct**. +* The integers in `pieces` are **distinct** (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct). + +## Solution + +```kotlin +class Solution { + fun canFormArray(arr: IntArray, pieces: Array): Boolean { + for (piece in pieces) { + val first = piece[0] + val index = findIndex(arr, first) + if (index == -1) { + return false + } + var i = 0 + var j = index + while (i < piece.size && j < arr.size) { + if (arr[j] != piece[i]) { + return false + } + i++ + j++ + } + if (i != piece.size) { + return false + } + } + return true + } + + private fun findIndex(arr: IntArray, key: Int): Int { + for (i in arr.indices) { + if (arr[i] == key) { + return i + } + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1641_count_sorted_vowel_strings/readme.md b/src/main/kotlin/g1601_1700/s1641_count_sorted_vowel_strings/readme.md new file mode 100644 index 00000000..168b9a43 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1641_count_sorted_vowel_strings/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) + +## 1641\. Count Sorted Vowel Strings + +Medium + +Given an integer `n`, return _the number of strings of length_ `n` _that consist only of vowels (_`a`_,_ `e`_,_ `i`_,_ `o`_,_ `u`_) and are **lexicographically sorted**._ + +A string `s` is **lexicographically sorted** if for all valid `i`, `s[i]` is the same as or comes before `s[i+1]` in the alphabet. + +**Example 1:** + +**Input:** n = 1 + +**Output:** 5 + +**Explanation:** The 5 sorted strings that consist of vowels only are `["a","e","i","o","u"].` + +**Example 2:** + +**Input:** n = 2 + +**Output:** 15 + +**Explanation:** The 15 sorted strings that consist of vowels only are + +["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"]. + +Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet. + +**Example 3:** + +**Input:** n = 33 + +**Output:** 66045 + +**Constraints:** + +* `1 <= n <= 50` + +## Solution + +```kotlin +class Solution { + fun countVowelStrings(n: Int): Int { + if (n == 1) { + return 5 + } + var arr = intArrayOf(1, 1, 1, 1, 1) + var sum = 5 + for (i in 2..n) { + val copy = IntArray(5) + for (j in arr.indices) { + if (j == 0) { + copy[j] = sum + } else { + copy[j] = copy[j - 1] - arr[j - 1] + } + } + arr = copy.copyOf(5) + sum = 0 + for (k in arr) { + sum += k + } + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1642_furthest_building_you_can_reach/readme.md b/src/main/kotlin/g1601_1700/s1642_furthest_building_you_can_reach/readme.md new file mode 100644 index 00000000..c73dfe02 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1642_furthest_building_you_can_reach/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) + +## 1642\. Furthest Building You Can Reach + +Medium + +You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`. + +You start your journey from building `0` and move to the next building by possibly using bricks or ladders. + +While moving from building `i` to building `i+1` (**0-indexed**), + +* If the current building's height is **greater than or equal** to the next building's height, you do **not** need a ladder or bricks. +* If the current building's height is **less than** the next building's height, you can either use **one ladder** or `(h[i+1] - h[i])` **bricks**. + +_Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/27/q4.gif) + +**Input:** heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1 + +**Output:** 4 + +**Explanation:** Starting at building 0, you can follow these steps: + +- Go to building 1 without using ladders nor bricks since 4 >= 2. + +- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7. + +- Go to building 3 without using ladders nor bricks since 7 >= 6. + +- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9. + +It is impossible to go beyond building 4 because you do not have any more bricks or ladders. + +**Example 2:** + +**Input:** heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2 + +**Output:** 7 + +**Example 3:** + +**Input:** heights = [14,3,19,3], bricks = 17, ladders = 0 + +**Output:** 3 + +**Constraints:** + +* 1 <= heights.length <= 105 +* 1 <= heights[i] <= 106 +* 0 <= bricks <= 109 +* `0 <= ladders <= heights.length` + +## Solution + +```kotlin +import java.util.PriorityQueue + +@Suppress("NAME_SHADOWING") +class Solution { + fun furthestBuilding(heights: IntArray, bricks: Int, ladders: Int): Int { + var bricks = bricks + val minHeap = PriorityQueue() + var i = 0 + // we'll assume to use ladders for the first l jumps and adjust it afterwards + while (i < heights.size - 1 && minHeap.size < ladders) { + val diff = heights[i + 1] - heights[i] + if (diff > 0) { + minHeap.offer(diff) + } + i++ + } + while (i < heights.size - 1) { + val diff = heights[i + 1] - heights[i] + if (diff > 0) { + if (minHeap.isNotEmpty() && minHeap.peek() < diff) { + bricks -= minHeap.poll() + minHeap.offer(diff) + } else { + bricks -= diff + } + if (bricks < 0) { + return i + } + } + i++ + } + return i + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1643_kth_smallest_instructions/readme.md b/src/main/kotlin/g1601_1700/s1643_kth_smallest_instructions/readme.md new file mode 100644 index 00000000..ad623c39 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1643_kth_smallest_instructions/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) + +## 1643\. Kth Smallest Instructions + +Hard + +Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel **right** and **down**. You are going to help Bob by providing **instructions** for him to reach `destination`. + +The **instructions** are represented as a string, where each character is either: + +* `'H'`, meaning move horizontally (go **right**), or +* `'V'`, meaning move vertically (go **down**). + +Multiple **instructions** will lead Bob to `destination`. For example, if `destination` is `(2, 3)`, both `"HHHVV"` and `"HVHVH"` are valid **instructions**. + +However, Bob is very picky. Bob has a lucky number `k`, and he wants the kth **lexicographically smallest instructions** that will lead him to `destination`. `k` is **1-indexed**. + +Given an integer array `destination` and an integer `k`, return _the_ kth _**lexicographically smallest instructions** that will take Bob to_ `destination`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/12/ex1.png) + +**Input:** destination = [2,3], k = 1 + +**Output:** "HHHVV" + +**Explanation:** All the instructions that reach (2, 3) in lexicographic order are as follows: ["HHHVV", "HHVHV", "HHVVH", "HVHHV", "HVHVH", "HVVHH", "VHHHV", "VHHVH", "VHVHH", "VVHHH"]. + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2020/10/12/ex2.png)** + +**Input:** destination = [2,3], k = 2 + +**Output:** "HHVHV" + +**Example 3:** + +**![](https://assets.leetcode.com/uploads/2020/10/12/ex3.png)** + +**Input:** destination = [2,3], k = 3 + +**Output:** "HHVVH" + +**Constraints:** + +* `destination.length == 2` +* `1 <= row, column <= 15` +* `1 <= k <= nCr(row + column, row)`, where `nCr(a, b)` denotes `a` choose `b`. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun kthSmallestPath(destination: IntArray, k: Int): String { + var k = k + val sb = StringBuilder() + var v = destination[0] + var n = v + destination[1] + while (true) { + val range = choose(--n, v) + if (k <= range) { + sb.append('H') + } else { + sb.append('V') + v-- + k -= range + } + if (v == 0) { + for (i in 1..n) { + sb.append('H') + } + break + } else if (v == n) { + for (i in 1..v) { + sb.append('V') + } + break + } + } + return sb.toString() + } + + private fun choose(n: Int, k: Int): Int { + var k = k + if (n - k < k) { + k = n - k + } + var answer = 1 + for (i in 1..k) { + answer = answer * (n + 1 - i) / i + } + return answer + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1646_get_maximum_in_generated_array/readme.md b/src/main/kotlin/g1601_1700/s1646_get_maximum_in_generated_array/readme.md new file mode 100644 index 00000000..52fea908 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1646_get_maximum_in_generated_array/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) + +## 1646\. Get Maximum in Generated Array + +Easy + +You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way: + +* `nums[0] = 0` +* `nums[1] = 1` +* `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n` +* `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n` + +Return _the **maximum** integer in the array_ `nums`. + +**Example 1:** + +**Input:** n = 7 + +**Output:** 3 + +**Explanation:** According to the given rules: + +nums[0] = 0 + +nums[1] = 1 + +nums[(1 \* 2) = 2] = nums[1] = 1 + +nums[(1 \* 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2 + +nums[(2 \* 2) = 4] = nums[2] = 1 + +nums[(2 \* 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3 + +nums[(3 \* 2) = 6] = nums[3] = 2 + +nums[(3 \* 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3 + +Hence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3. + +**Example 2:** + +**Input:** n = 2 + +**Output:** 1 + +**Explanation:** According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1. + +**Example 3:** + +**Input:** n = 3 + +**Output:** 2 + +**Explanation:** According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2. + +**Constraints:** + +* `0 <= n <= 100` + +## Solution + +```kotlin +class Solution { + fun getMaximumGenerated(n: Int): Int { + if (n == 0) { + return 0 + } + val nums = IntArray(n + 1) + nums[0] = 0 + nums[1] = 1 + var max = 1 + for (i in 1..n / 2) { + nums[i * 2] = nums[i] + max = Math.max(max, nums[i]) + if (i * 2 + 1 <= n) { + nums[i * 2 + 1] = nums[i] + nums[i + 1] + max = Math.max(max, nums[i * 2 + 1]) + } + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1647_minimum_deletions_to_make_character_frequencies_unique/readme.md b/src/main/kotlin/g1601_1700/s1647_minimum_deletions_to_make_character_frequencies_unique/readme.md new file mode 100644 index 00000000..3586bf80 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1647_minimum_deletions_to_make_character_frequencies_unique/readme.md @@ -0,0 +1,64 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1647\. Minimum Deletions to Make Character Frequencies Unique + +Medium + +A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**. + +Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._ + +The **frequency** of a character in a string is the number of times it appears in the string. For example, in the string `"aab"`, the **frequency** of `'a'` is `2`, while the **frequency** of `'b'` is `1`. + +**Example 1:** + +**Input:** s = "aab" + +**Output:** 0 + +**Explanation:** `s` is already good. + +**Example 2:** + +**Input:** s = "aaabbbcc" + +**Output:** 2 + +**Explanation:** You can delete two 'b's resulting in the good string "aaabcc". Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc". + +**Example 3:** + +**Input:** s = "ceabaacb" + +**Output:** 2 + +**Explanation:** You can delete both 'c's resulting in the good string "eabaab". Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored). + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` contains only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun minDeletions(s: String): Int { + var cnt = 0 + val freq = IntArray(26) + val seen: MutableSet = HashSet() + for (c in s.toCharArray()) { + freq[c.code - 'a'.code]++ + } + for (i in 0..25) { + while (freq[i] > 0 && seen.contains(freq[i])) { + freq[i]-- + cnt++ + } + seen.add(freq[i]) + } + return cnt + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1648_sell_diminishing_valued_colored_balls/readme.md b/src/main/kotlin/g1601_1700/s1648_sell_diminishing_valued_colored_balls/readme.md new file mode 100644 index 00000000..3a149c5a --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1648_sell_diminishing_valued_colored_balls/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) + +## 1648\. Sell Diminishing-Valued Colored Balls + +Medium + +You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color. + +The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color **you currently have in your `inventory`. For example, if you own `6` yellow balls, the customer would pay `6` for the first yellow ball. After the transaction, there are only `5` yellow balls left, so the next yellow ball is then valued at `5` (i.e., the value of the balls decreases as you sell more to the customer). + +You are given an integer array, `inventory`, where `inventory[i]` represents the number of balls of the ith color that you initially own. You are also given an integer `orders`, which represents the total number of balls that the customer wants. You can sell the balls **in any order**. + +Return _the **maximum** total value that you can attain after selling_ `orders` _colored balls_. As the answer may be too large, return it **modulo** 109 + 7. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/05/jj.gif) + +**Input:** inventory = [2,5], orders = 4 + +**Output:** 14 + +**Explanation:** Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3). The maximum total value is 2 + 5 + 4 + 3 = 14. + +**Example 2:** + +**Input:** inventory = [3,5], orders = 6 + +**Output:** 19 + +**Explanation:** Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2). The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19. + +**Constraints:** + +* 1 <= inventory.length <= 105 +* 1 <= inventory[i] <= 109 +* 1 <= orders <= min(sum(inventory[i]), 109) + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun maxProfit(inventory: IntArray, orders: Int): Int { + var orders = orders + val n = inventory.size + val mod = 1e9.toLong() + 7 + var totalValue: Long = 0 + inventory.sort() + var count = 0 + for (i in n - 1 downTo 0) { + count++ + if (i == 0 || inventory[i] > inventory[i - 1]) { + var diff = (if (i == 0) inventory[i] else inventory[i] - inventory[i - 1]).toLong() + if (count * diff < orders) { + totalValue += (2L * inventory[i] - diff + 1) * diff * count / 2 % mod + orders -= (count * diff).toInt() + } else { + diff = (orders / count).toLong() + val remainder = (orders % count).toLong() + totalValue += (2L * inventory[i] - diff + 1) * diff * count / 2 % mod + totalValue += (inventory[i] - diff) * remainder % mod + totalValue %= mod + break + } + } + } + return totalValue.toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1649_create_sorted_array_through_instructions/readme.md b/src/main/kotlin/g1601_1700/s1649_create_sorted_array_through_instructions/readme.md new file mode 100644 index 00000000..14ea9aec --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1649_create_sorted_array_through_instructions/readme.md @@ -0,0 +1,134 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1649\. Create Sorted Array through Instructions + +Hard + +Given an integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from **left to right** in `instructions`, insert it into `nums`. The **cost** of each insertion is the **minimum** of the following: + +* The number of elements currently in `nums` that are **strictly less than** `instructions[i]`. +* The number of elements currently in `nums` that are **strictly greater than** `instructions[i]`. + +For example, if inserting element `3` into `nums = [1,2,3,5]`, the **cost** of insertion is `min(2, 1)` (elements `1` and `2` are less than `3`, element `5` is greater than `3`) and `nums` will become `[1,2,3,3,5]`. + +Return _the **total cost** to insert all elements from_ `instructions` _into_ `nums`. Since the answer may be large, return it **modulo** 109 + 7 + +**Example 1:** + +**Input:** instructions = [1,5,6,2] + +**Output:** 1 + +**Explanation:** Begin with nums = []. + +Insert 1 with cost min(0, 0) = 0, now nums = [1]. + +Insert 5 with cost min(1, 0) = 0, now nums = [1,5]. + +Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6]. + +Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6]. + +The total cost is 0 + 0 + 0 + 1 = 1. + +**Example 2:** + +**Input:** instructions = [1,2,3,6,5,4] + +**Output:** 3 + +**Explanation:** Begin with nums = []. + +Insert 1 with cost min(0, 0) = 0, now nums = [1]. + +Insert 2 with cost min(1, 0) = 0, now nums = [1,2]. + +Insert 3 with cost min(2, 0) = 0, now nums = [1,2,3]. + +Insert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6]. + +Insert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6]. + +Insert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6]. + +The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3. + +**Example 3:** + +**Input:** instructions = [1,3,3,3,2,4,2,1,2] + +**Output:** 4 + +**Explanation:** Begin with nums = []. + +Insert 1 with cost min(0, 0) = 0, now nums = [1]. + +Insert 3 with cost min(1, 0) = 0, now nums = [1,3]. + +Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3]. + +Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3]. + +Insert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3]. + +Insert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4]. + +Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4]. + +Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4]. + +Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4]. + +The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4. + +**Constraints:** + +* 1 <= instructions.length <= 105 +* 1 <= instructions[i] <= 105 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun createSortedArray(instructions: IntArray): Int { + var maxValue = 0 + for (num in instructions) { + maxValue = Math.max(maxValue, num) + } + val bit = IntArray(maxValue + 1) + var cost: Long = 0 + for (i in instructions.indices) { + updateBIT(bit, maxValue, instructions[i]) + cost += Math.min( + queryBIT(bit, instructions[i] - 1), + 1 + i - queryBIT(bit, instructions[i]) + ).toLong() + } + return (cost % MODULO).toInt() + } + + private fun updateBIT(bit: IntArray, maxValue: Int, x: Int) { + var x = x + while (x <= maxValue) { + bit[x] += 1 + x += x and -x + } + } + + private fun queryBIT(bit: IntArray, x: Int): Int { + var x = x + var sum = 0 + while (x > 0) { + sum += bit[x] + x -= x and -x + } + return sum + } + + companion object { + private const val MODULO = 1e9.toLong() + 7 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1652_defuse_the_bomb/readme.md b/src/main/kotlin/g1601_1700/s1652_defuse_the_bomb/readme.md new file mode 100644 index 00000000..a83ba116 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1652_defuse_the_bomb/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) + +## 1652\. Defuse the Bomb + +Easy + +You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`. + +To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**. + +* If `k > 0`, replace the ith number with the sum of the **next** `k` numbers. +* If `k < 0`, replace the ith number with the sum of the **previous** `k` numbers. +* If `k == 0`, replace the ith number with `0`. + +As `code` is circular, the next element of `code[n-1]` is `code[0]`, and the previous element of `code[0]` is `code[n-1]`. + +Given the **circular** array `code` and an integer key `k`, return _the decrypted code to defuse the bomb_! + +**Example 1:** + +**Input:** code = [5,7,1,4], k = 3 + +**Output:** [12,10,16,13] + +**Explanation:** Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around. + +**Example 2:** + +**Input:** code = [1,2,3,4], k = 0 + +**Output:** [0,0,0,0] + +**Explanation:** When k is zero, the numbers are replaced by 0. + +**Example 3:** + +**Input:** code = [2,4,9,3], k = -2 + +**Output:** [12,5,6,13] + +**Explanation:** The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of the **previous** numbers. + +**Constraints:** + +* `n == code.length` +* `1 <= n <= 100` +* `1 <= code[i] <= 100` +* `-(n - 1) <= k <= n - 1` + +## Solution + +```kotlin +class Solution { + fun decrypt(code: IntArray, k: Int): IntArray { + val result = IntArray(code.size) + val len = code.size + if (k == 0) { + for (i in code.indices) { + result[i] = 0 + } + } else if (k > 0) { + var kSum = 0 + for (i in 1..k) { + kSum += code[i] + } + result[0] = kSum + for (i in 1 until len) { + kSum -= code[i] + kSum += code[(i + k) % len] + result[i] = kSum + } + } else { + var kSum = 0 + val kVal = Math.abs(k) + for (i in len - 1 downTo len - kVal) { + kSum += code[i] + } + result[0] = kSum + for (i in 1 until len) { + kSum -= code[(len - kVal + i - 1) % len] + kSum += code[i - 1] + result[i] = kSum + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1653_minimum_deletions_to_make_string_balanced/readme.md b/src/main/kotlin/g1601_1700/s1653_minimum_deletions_to_make_string_balanced/readme.md new file mode 100644 index 00000000..07ef64ea --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1653_minimum_deletions_to_make_string_balanced/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) + +## 1653\. Minimum Deletions to Make String Balanced + +Medium + +You are given a string `s` consisting only of characters `'a'` and `'b'`. + +You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`. + +Return _the **minimum** number of deletions needed to make_ `s` _**balanced**_. + +**Example 1:** + +**Input:** s = "aababbab" + +**Output:** 2 + +**Explanation:** You can either: + +Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or + +Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb"). + +**Example 2:** + +**Input:** s = "bbaaaaabb" + +**Output:** 2 + +**Explanation:** The only solution is to delete the first two characters. + +**Constraints:** + +* 1 <= s.length <= 105 +* `s[i]` is `'a'` or `'b'`. + +## Solution + +```kotlin +class Solution { + fun minimumDeletions(s: String): Int { + var a = 0 + var b = 0 + for (ch in s.toCharArray()) { + if (ch == 'a') { + a++ + } else { + b = Math.max(a, b) + 1 + } + } + return s.length - Math.max(a, b) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1654_minimum_jumps_to_reach_home/readme.md b/src/main/kotlin/g1601_1700/s1654_minimum_jumps_to_reach_home/readme.md new file mode 100644 index 00000000..a1e5e604 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1654_minimum_jumps_to_reach_home/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) + +## 1654\. Minimum Jumps to Reach Home + +Medium + +A certain bug's home is on the x-axis at position `x`. Help them get there from position `0`. + +The bug jumps according to the following rules: + +* It can jump exactly `a` positions **forward** (to the right). +* It can jump exactly `b` positions **backward** (to the left). +* It cannot jump backward twice in a row. +* It cannot jump to any `forbidden` positions. + +The bug may jump forward **beyond** its home, but it **cannot jump** to positions numbered with **negative** integers. + +Given an array of integers `forbidden`, where `forbidden[i]` means that the bug cannot jump to the position `forbidden[i]`, and integers `a`, `b`, and `x`, return _the minimum number of jumps needed for the bug to reach its home_. If there is no possible sequence of jumps that lands the bug on position `x`, return `-1.` + +**Example 1:** + +**Input:** forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9 + +**Output:** 3 + +**Explanation:** 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home. + +**Example 2:** + +**Input:** forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11 + +**Output:** -1 + +**Example 3:** + +**Input:** forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7 + +**Output:** 2 + +**Explanation:** One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home. + +**Constraints:** + +* `1 <= forbidden.length <= 1000` +* `1 <= a, b, forbidden[i] <= 2000` +* `0 <= x <= 2000` +* All the elements in `forbidden` are distinct. +* Position `x` is not forbidden. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + private class Pair(var i: Int, var backward: Boolean) + + fun minimumJumps(forbidden: IntArray, a: Int, b: Int, x: Int): Int { + val limit = 2000 + 2 * b + 1 + val v = BooleanArray(limit) + for (num in forbidden) { + v[num] = true + } + var step = 0 + val q: Queue = LinkedList() + q.add(Pair(0, false)) + v[0] = true + while (q.isNotEmpty()) { + val size = q.size + for (i in 0 until size) { + val c = q.poll() + if (c.i == x) { + return step + } + if (!c.backward) { + val backward = c.i - b + if (backward == x) { + return step + 1 + } + if (backward > 0 && !v[backward]) { + q.offer(Pair(backward, true)) + v[backward] = true + } + } + val forward = c.i + a + if (forward == x) { + return step + 1 + } + if (forward < limit && !v[forward]) { + q.offer(Pair(forward, false)) + v[forward] = true + } + } + step++ + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1655_distribute_repeating_integers/readme.md b/src/main/kotlin/g1601_1700/s1655_distribute_repeating_integers/readme.md new file mode 100644 index 00000000..20b63896 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1655_distribute_repeating_integers/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) + +## 1655\. Distribute Repeating Integers + +Hard + +You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the ith customer ordered. Determine if it is possible to distribute `nums` such that: + +* The ith customer gets **exactly** `quantity[i]` integers, +* The integers the ith customer gets are **all equal**, and +* Every customer is satisfied. + +Return `true` _if it is possible to distribute_ `nums` _according to the above conditions_. + +**Example 1:** + +**Input:** nums = [1,2,3,4], quantity = [2] + +**Output:** false + +**Explanation:** The 0th customer cannot be given two different integers. + +**Example 2:** + +**Input:** nums = [1,2,3,3], quantity = [2] + +**Output:** true + +**Explanation:** The 0th customer is given [3,3]. The integers [1,2] are not used. + +**Example 3:** + +**Input:** nums = [1,1,2,2], quantity = [2,2] + +**Output:** true + +**Explanation:** The 0th customer is given [1,1], and the 1st customer is given [2,2]. + +**Constraints:** + +* `n == nums.length` +* 1 <= n <= 105 +* `1 <= nums[i] <= 1000` +* `m == quantity.length` +* `1 <= m <= 10` +* 1 <= quantity[i] <= 105 +* There are at most `50` unique values in `nums`. + +## Solution + +```kotlin +class Solution { + fun canDistribute(nums: IntArray, quantity: IntArray): Boolean { + val counter = count(nums) + quantity.sort() + return dfs(counter, quantity, quantity.size - 1) + } + + private fun dfs(counter: IntArray, quantity: IntArray, quantityId: Int): Boolean { + if (quantityId < 0) { + return true + } + for (i in counter.indices) { + if (i > 0 && counter[i] == counter[i - 1]) { + continue + } + if (counter[i] >= quantity[quantityId]) { + counter[i] -= quantity[quantityId] + if (dfs(counter, quantity, quantityId - 1)) { + return true + } + counter[i] += quantity[quantityId] + } + } + return false + } + + private fun count(nums: IntArray): IntArray { + val counter = IntArray(1001) + for (n in nums) { + counter[n]++ + } + counter.sort() + return counter.copyOfRange(counter.size - 50, counter.size) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1656_design_an_ordered_stream/readme.md b/src/main/kotlin/g1601_1700/s1656_design_an_ordered_stream/readme.md new file mode 100644 index 00000000..8493b659 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1656_design_an_ordered_stream/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) + +## 1656\. Design an Ordered Stream + +Easy + +There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`. + +Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each insertion. The concatenation of all the **chunks** should result in a list of the sorted values. + +Implement the `OrderedStream` class: + +* `OrderedStream(int n)` Constructs the stream to take `n` values. +* `String[] insert(int idKey, String value)` Inserts the pair `(idKey, value)` into the stream, then returns the **largest possible chunk** of currently inserted values that appear next in the order. + +**Example:** + +**![](https://assets.leetcode.com/uploads/2020/11/10/q1.gif)** + +**Input** ["OrderedStream", "insert", "insert", "insert", "insert", "insert"] + +[[5], [3, "ccccc"], [1, "aaaaa"], [2, "bbbbb"], [5, "eeeee"], [4, "ddddd"]] + +**Output:** [null, [], ["aaaaa"], ["bbbbb", "ccccc"], [], ["ddddd", "eeeee"]] + +**Explanation:** + + // Note that the values ordered by ID is ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"]. + OrderedStream os = new OrderedStream(5); + os.insert(3, "ccccc"); // Inserts (3, "ccccc"), returns []. + os.insert(1, "aaaaa"); // Inserts (1, "aaaaa"), returns ["aaaaa"]. + os.insert(2, "bbbbb"); // Inserts (2, "bbbbb"), returns ["bbbbb", "ccccc"]. + os.insert(5, "eeeee"); // Inserts (5, "eeeee"), returns []. + os.insert(4, "ddddd"); // Inserts (4, "ddddd"), returns ["ddddd", "eeeee"]. + // Concatentating all the chunks returned: + // [] + ["aaaaa"] + ["bbbbb", "ccccc"] + [] + ["ddddd", "eeeee"] = ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"] + // The resulting order is the same as the order above. + +**Constraints:** + +* `1 <= n <= 1000` +* `1 <= id <= n` +* `value.length == 5` +* `value` consists only of lowercase letters. +* Each call to `insert` will have a unique `id.` +* Exactly `n` calls will be made to `insert`. + +## Solution + +```kotlin +class OrderedStream(n: Int) { + private val str: Array + private var ptr = 0 + + init { + str = arrayOfNulls(n) + } + + fun insert(idKey: Int, value: String?): List { + str[idKey - 1] = value + val list: MutableList = ArrayList() + while (ptr < str.size && str[ptr] != null) { + list.add(str[ptr]) + ptr++ + } + return list + } +} +/* + * Your OrderedStream object will be instantiated and called as such: + * var obj = OrderedStream(n) + * var param_1 = obj.insert(idKey,value) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1657_determine_if_two_strings_are_close/readme.md b/src/main/kotlin/g1601_1700/s1657_determine_if_two_strings_are_close/readme.md new file mode 100644 index 00000000..96e720c2 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1657_determine_if_two_strings_are_close/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) + +## 1657\. Determine if Two Strings Are Close + +Medium + +Two strings are considered **close** if you can attain one from the other using the following operations: + +* Operation 1: Swap any two **existing** characters. + * For example, `abcde -> aecdb` +* Operation 2: Transform **every** occurrence of one **existing** character into another **existing** character, and do the same with the other character. + * For example, `aacabb -> bbcbaa` (all `a`'s turn into `b`'s, and all `b`'s turn into `a`'s) + +You can use the operations on either string as many times as necessary. + +Given two strings, `word1` and `word2`, return `true` _if_ `word1` _and_ `word2` _are **close**, and_ `false` _otherwise._ + +**Example 1:** + +**Input:** word1 = "abc", word2 = "bca" + +**Output:** true + +**Explanation:** You can attain word2 from word1 in 2 operations. + +Apply Operation 1: "abc" -> "acb" + +Apply Operation 1: "acb" -> "bca" + +**Example 2:** + +**Input:** word1 = "a", word2 = "aa" + +**Output:** false + +**Explanation:** It is impossible to attain word2 from word1, or vice versa, in any number of operations. + +**Example 3:** + +**Input:** word1 = "cabbba", word2 = "abbccc" + +**Output:** true + +**Explanation:** You can attain word2 from word1 in 3 operations. + +Apply Operation 1: "cabbba" -> "caabbb" + +`Apply Operation 2: "`caabbb" -> "baaccc" + +Apply Operation 2: "baaccc" -> "abbccc" + +**Constraints:** + +* 1 <= word1.length, word2.length <= 105 +* `word1` and `word2` contain only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun closeStrings(word1: String, word2: String): Boolean { + if (word1.length != word2.length) { + return false + } + if (word1 == word2) { + return true + } + val freq1 = IntArray(26) + val freq2 = IntArray(26) + for (c in word1.toCharArray()) { + freq1[c.code - 'a'.code]++ + } + for (c in word2.toCharArray()) { + freq2[c.code - 'a'.code]++ + } + for (i in 0..25) { + if (freq1[i] == 0 && freq2[i] != 0 || freq1[i] != 0 && freq2[i] == 0) { + return false + } + } + freq1.sort() + freq2.sort() + return freq1.contentEquals(freq2) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1658_minimum_operations_to_reduce_x_to_zero/readme.md b/src/main/kotlin/g1601_1700/s1658_minimum_operations_to_reduce_x_to_zero/readme.md new file mode 100644 index 00000000..fa96582f --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1658_minimum_operations_to_reduce_x_to_zero/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) + +## 1658\. Minimum Operations to Reduce X to Zero + +Medium + +You are given an integer array `nums` and an integer `x`. In one operation, you can either remove the leftmost or the rightmost element from the array `nums` and subtract its value from `x`. Note that this **modifies** the array for future operations. + +Return _the **minimum number** of operations to reduce_ `x` _to **exactly**_ `0` _if it is possible__, otherwise, return_ `-1`. + +**Example 1:** + +**Input:** nums = [1,1,4,2,3], x = 5 + +**Output:** 2 + +**Explanation:** The optimal solution is to remove the last two elements to reduce x to zero. + +**Example 2:** + +**Input:** nums = [5,6,7,8,9], x = 4 + +**Output:** -1 + +**Example 3:** + +**Input:** nums = [3,2,20,1,1,3], x = 10 + +**Output:** 5 + +**Explanation:** The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 104 +* 1 <= x <= 109 + +## Solution + +```kotlin +class Solution { + fun minOperations(nums: IntArray, x: Int): Int { + var totalArraySum = 0 + for (each in nums) { + totalArraySum += each + } + if (totalArraySum == x) { + return nums.size + } + val target = totalArraySum - x + // as we need to find value equal to x so that x-x=0, + // and we need to search the longest sub array with sum equal t0 total array sum -x; + var sum = 0 + var result = -1 + var start = 0 + for (end in nums.indices) { + sum += nums[end] + while (sum > target && start < nums.size) { + sum -= nums[start] + start++ + } + if (sum == target) { + result = Math.max(result, end + 1 - start) + } + } + return if (result == -1) { + result + } else { + nums.size - result + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1659_maximize_grid_happiness/readme.md b/src/main/kotlin/g1601_1700/s1659_maximize_grid_happiness/readme.md new file mode 100644 index 00000000..e827bdbe --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1659_maximize_grid_happiness/readme.md @@ -0,0 +1,148 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1659\. Maximize Grid Happiness + +Hard + +You are given four integers, `m`, `n`, `introvertsCount`, and `extrovertsCount`. You have an `m x n` grid, and there are two types of people: introverts and extroverts. There are `introvertsCount` introverts and `extrovertsCount` extroverts. + +You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you **do not** have to have all the people living in the grid. + +The **happiness** of each person is calculated as follows: + +* Introverts **start** with `120` happiness and **lose** `30` happiness for each neighbor (introvert or extrovert). +* Extroverts **start** with `40` happiness and **gain** `20` happiness for each neighbor (introvert or extrovert). + +Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell. + +The **grid happiness** is the **sum** of each person's happiness. Return _the **maximum possible grid happiness**._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/05/grid_happiness.png) + +**Input:** m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2 + +**Output:** 240 + +**Explanation:** Assume the grid is 1-indexed with coordinates (row, column). + +We can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3). + +- Introvert at (1,1) happiness: 120 (starting happiness) - (0 \* 30) (0 neighbors) = 120 + +- Extrovert at (1,3) happiness: 40 (starting happiness) + (1 \* 20) (1 neighbor) = 60 + +- Extrovert at (2,3) happiness: 40 (starting happiness) + (1 \* 20) (1 neighbor) = 60 + +The grid happiness is 120 + 60 + 60 = 240. + +The above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells. + +**Example 2:** + +**Input:** m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1 + +**Output:** 260 + +**Explanation:** Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1). + +- Introvert at (1,1) happiness: 120 (starting happiness) - (1 \* 30) (1 neighbor) = 90 + +- Extrovert at (2,1) happiness: 40 (starting happiness) + (2 \* 20) (2 neighbors) = 80 + +- Introvert at (3,1) happiness: 120 (starting happiness) - (1 \* 30) (1 neighbor) = 90 + +The grid happiness is 90 + 80 + 90 = 260. + +**Example 3:** + +**Input:** m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0 + +**Output:** 240 + +**Constraints:** + +* `1 <= m, n <= 5` +* `0 <= introvertsCount, extrovertsCount <= min(m * n, 6)` + +## Solution + +```kotlin +class Solution { + private var m = 0 + private var n = 0 + private lateinit var dp: Array>>> + private val notPlace = 0 + private val intro = 1 + private val extro = 2 + private var mod = 0 + + fun getMaxGridHappiness(m: Int, n: Int, introvertsCount: Int, extrovertsCount: Int): Int { + this.m = m + this.n = n + val numOfState = Math.pow(3.0, n.toDouble()).toInt() + dp = Array(m) { + Array(n) { + Array(introvertsCount + 1) { + Array(extrovertsCount + 1) { IntArray(numOfState) } + } + } + } + mod = numOfState / 3 + return dfs(0, 0, introvertsCount, extrovertsCount, 0) + } + + private fun dfs(x: Int, y: Int, ic: Int, ec: Int, state: Int): Int { + if (x == m) { + return 0 + } else if (y == n) { + return dfs(x + 1, 0, ic, ec, state) + } + if (dp[x][y][ic][ec][state] != 0) { + return dp[x][y][ic][ec][state] + } + // 1 - not place + var max = dfs(x, y + 1, ic, ec, state % mod * 3) + val up = state / mod + val left = state % 3 + // 2 - place intro + if (ic > 0) { + var temp = 120 + if (x > 0 && up != notPlace) { + temp -= 30 + temp += if (up == intro) -30 else 20 + } + if (y > 0 && left != notPlace) { + temp -= 30 + temp += if (left == intro) -30 else 20 + } + var nextState = state + nextState %= mod + nextState *= 3 + nextState += intro + max = Math.max(max, temp + dfs(x, y + 1, ic - 1, ec, nextState)) + } + // 3 - place extro + if (ec > 0) { + var temp = 40 + if (x > 0 && up != notPlace) { + temp += 20 + temp += if (up == intro) -30 else 20 + } + if (y > 0 && left != notPlace) { + temp += 20 + temp += if (left == intro) -30 else 20 + } + var nextState = state + nextState %= mod + nextState *= 3 + nextState += extro + max = Math.max(max, temp + dfs(x, y + 1, ic, ec - 1, nextState)) + } + dp[x][y][ic][ec][state] = max + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1661_average_time_of_process_per_machine/readme.md b/src/main/kotlin/g1601_1700/s1661_average_time_of_process_per_machine/readme.md new file mode 100644 index 00000000..3c743284 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1661_average_time_of_process_per_machine/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) + +## 1661\. Average Time of Process per Machine + +Easy + +SQL Schema + +Table: `Activity` + + +----------------+---------+ + | Column Name | Type | + +----------------+---------+ + | machine_id | int | + | process_id | int | + | activity_type | enum | + | timestamp | float | + +----------------+---------+ + The table shows the user activities for a factory website. + (machine_id, process_id, activity_type) is the primary key of this table. + machine_id is the ID of a machine. + process_id is the ID of a process running on the machine with ID machine_id. + activity_type is an ENUM of type ('start', 'end'). + timestamp is a float representing the current time in seconds. + 'start' means the machine starts the process at the given timestamp and 'end' means the machine ends the process at the given timestamp. + The 'start' timestamp will always be before the 'end' timestamp for every (machine_id, process_id) pair. + +There is a factory website that has several machines each running the **same number of processes**. Write an SQL query to find the **average time** each machine takes to complete a process. + +The time to complete a process is the `'end' timestamp` minus the `'start' timestamp`. The average time is calculated by the total time to complete every process on the machine divided by the number of processes that were run. + +The resulting table should have the `machine_id` along with the **average time** as `processing_time`, which should be **rounded to 3 decimal places**. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Activity table: + +------------+------------+---------------+-----------+ + | machine_id | process_id | activity_type | timestamp | + +------------+------------+---------------+-----------+ + | 0 | 0 | start | 0.712 | + | 0 | 0 | end | 1.520 | + | 0 | 1 | start | 3.140 | + | 0 | 1 | end | 4.120 | + | 1 | 0 | start | 0.550 | + | 1 | 0 | end | 1.550 | + | 1 | 1 | start | 0.430 | + | 1 | 1 | end | 1.420 | + | 2 | 0 | start | 4.100 | + | 2 | 0 | end | 4.512 | + | 2 | 1 | start | 2.500 | + | 2 | 1 | end | 5.000 | + +------------+------------+---------------+-----------+ + +**Output:** + + +------------+-----------------+ + | machine_id | processing_time | + +------------+-----------------+ + | 0 | 0.894 | + | 1 | 0.995 | + | 2 | 1.456 | + +------------+-----------------+ + +**Explanation:** + +There are 3 machines running 2 processes each. + +Machine 0's average time is ((1.520 - 0.712) + (4.120 - 3.140)) / 2 = 0.894 + +Machine 1's average time is ((1.550 - 0.550) + (1.420 - 0.430)) / 2 = 0.995 + +Machine 2's average time is ((4.512 - 4.100) + (5.000 - 2.500)) / 2 = 1.456 + +## Solution + +```sql +# Write your MySQL query statement below +select act1.machine_id,round(avg(act2.timestamp-act1.timestamp),3) as processing_time from activity act1 join activity act2 on act1.machine_id=act2.machine_id +where act1.process_id = act2.process_id and act1.activity_type ='start' +and act2.activity_type = 'end' group by act1.machine_id; +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1662_check_if_two_string_arrays_are_equivalent/readme.md b/src/main/kotlin/g1601_1700/s1662_check_if_two_string_arrays_are_equivalent/readme.md new file mode 100644 index 00000000..6b52f35b --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1662_check_if_two_string_arrays_are_equivalent/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) + +## 1662\. Check If Two String Arrays are Equivalent + +Easy + +Given two string arrays `word1` and `word2`, return `true` _if the two arrays **represent** the same string, and_ `false` _otherwise._ + +A string is **represented** by an array if the array elements concatenated **in order** forms the string. + +**Example 1:** + +**Input:** word1 = ["ab", "c"], word2 = ["a", "bc"] + +**Output:** true + +**Explanation:** + +word1 represents string "ab" + "c" -> "abc" + +word2 represents string "a" + "bc" -> "abc" + +The strings are the same, so return true. + +**Example 2:** + +**Input:** word1 = ["a", "cb"], word2 = ["ab", "c"] + +**Output:** false + +**Example 3:** + +**Input:** word1 = ["abc", "d", "defg"], word2 = ["abcddefg"] + +**Output:** true + +**Constraints:** + +* 1 <= word1.length, word2.length <= 103 +* 1 <= word1[i].length, word2[i].length <= 103 +* 1 <= sum(word1[i].length), sum(word2[i].length) <= 103 +* `word1[i]` and `word2[i]` consist of lowercase letters. + +## Solution + +```kotlin +class Solution { + fun arrayStringsAreEqual(word1: Array, word2: Array): Boolean { + val sb1 = StringBuilder() + for (word in word1) { + sb1.append(word) + } + val sb2 = StringBuilder() + for (word in word2) { + sb2.append(word) + } + return sb1.toString() == sb2.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1663_smallest_string_with_a_given_numeric_value/readme.md b/src/main/kotlin/g1601_1700/s1663_smallest_string_with_a_given_numeric_value/readme.md new file mode 100644 index 00000000..1ec54b66 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1663_smallest_string_with_a_given_numeric_value/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) + +## 1663\. Smallest String With A Given Numeric Value + +Medium + +The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on. + +The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string `"abe"` is equal to `1 + 2 + 5 = 8`. + +You are given two integers `n` and `k`. Return _the **lexicographically smallest string** with **length** equal to `n` and **numeric value** equal to `k`._ + +Note that a string `x` is lexicographically smaller than string `y` if `x` comes before `y` in dictionary order, that is, either `x` is a prefix of `y`, or if `i` is the first position such that `x[i] != y[i]`, then `x[i]` comes before `y[i]` in alphabetic order. + +**Example 1:** + +**Input:** n = 3, k = 27 + +**Output:** "aay" + +**Explanation:** The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3. + +**Example 2:** + +**Input:** n = 5, k = 73 + +**Output:** "aaszz" + +**Constraints:** + +* 1 <= n <= 105 +* `n <= k <= 26 * n` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun getSmallestString(n: Int, k: Int): String { + var n = n + var k = k + val res = CharArray(n) + res.fill('a') + k -= n + while (k > 0) { + --n + res[n] = res[n] + Math.min(25, k).toChar().code + k -= Math.min(25, k) + } + return String(res) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1664_ways_to_make_a_fair_array/readme.md b/src/main/kotlin/g1601_1700/s1664_ways_to_make_a_fair_array/readme.md new file mode 100644 index 00000000..9cb95dfa --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1664_ways_to_make_a_fair_array/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) + +## 1664\. Ways to Make a Fair Array + +Medium + +You are given an integer array `nums`. You can choose **exactly one** index (**0-indexed**) and remove the element. Notice that the index of the elements may change after the removal. + +For example, if `nums = [6,1,7,4,1]`: + +* Choosing to remove index `1` results in `nums = [6,7,4,1]`. +* Choosing to remove index `2` results in `nums = [6,1,4,1]`. +* Choosing to remove index `4` results in `nums = [6,1,7,4]`. + +An array is **fair** if the sum of the odd-indexed values equals the sum of the even-indexed values. + +Return the _**number** of indices that you could choose such that after the removal,_ `nums` _is **fair**._ + +**Example 1:** + +**Input:** nums = [2,1,6,4] + +**Output:** 1 + +**Explanation:** + +Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair. + +Remove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair. + +Remove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair. + +Remove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair. + +There is 1 index that you can remove to make nums fair. + +**Example 2:** + +**Input:** nums = [1,1,1] + +**Output:** 3 + +**Explanation:** You can remove any index and the remaining array is fair. + +**Example 3:** + +**Input:** nums = [1,2,3] + +**Output:** 0 + +**Explanation:** You cannot make a fair array after removing any index. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun waysToMakeFair(nums: IntArray): Int { + var res = 0 + val even = IntArray(nums.size) + val odd = IntArray(nums.size) + var oddSum = 0 + var evenSum = 0 + for (i in nums.indices) { + if (i % 2 == 0) { + evenSum += nums[i] + } else { + oddSum += nums[i] + } + even[i] = evenSum + odd[i] = oddSum + } + for (i in nums.indices) { + if (i == 0) { + evenSum = odd[nums.size - 1] - odd[0] + oddSum = even[nums.size - 1] - even[0] + } else { + oddSum = odd[i - 1] + even[nums.size - 1] - even[i] + evenSum = even[i - 1] + odd[nums.size - 1] - odd[i] + } + if (evenSum == oddSum) { + res++ + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1665_minimum_initial_energy_to_finish_tasks/readme.md b/src/main/kotlin/g1601_1700/s1665_minimum_initial_energy_to_finish_tasks/readme.md new file mode 100644 index 00000000..19fef918 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1665_minimum_initial_energy_to_finish_tasks/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) + +## 1665\. Minimum Initial Energy to Finish Tasks + +Hard + +You are given an array `tasks` where tasks[i] = [actuali, minimumi]: + +* actuali is the actual amount of energy you **spend to finish** the ith task. +* minimumi is the minimum amount of energy you **require to begin** the ith task. + +For example, if the task is `[10, 12]` and your current energy is `11`, you cannot start this task. However, if your current energy is `13`, you can complete this task, and your energy will be `3` after finishing it. + +You can finish the tasks in **any order** you like. + +Return _the **minimum** initial amount of energy you will need_ _to finish all the tasks_. + +**Example 1:** + +**Input:** tasks = \[\[1,2],[2,4],[4,8]] + +**Output:** 8 + +**Explanation:** + +Starting with 8 energy, we finish the tasks in the following order: + + - 3rd task. Now energy = 8 - 4 = 4. + + - 2nd task. Now energy = 4 - 2 = 2. + + - 1st task. Now energy = 2 - 1 = 1. + +Notice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task. + +**Example 2:** + +**Input:** tasks = \[\[1,3],[2,4],[10,11],[10,12],[8,9]] + +**Output:** 32 + +**Explanation:** + +Starting with 32 energy, we finish the tasks in the following order: + + - 1st task. Now energy = 32 - 1 = 31. + + - 2nd task. Now energy = 31 - 2 = 29. + + - 3rd task. Now energy = 29 - 10 = 19. + + - 4th task. Now energy = 19 - 10 = 9. + + - 5th task. Now energy = 9 - 8 = 1. + +**Example 3:** + +**Input:** tasks = \[\[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]] + +**Output:** 27 + +**Explanation:** + +Starting with 27 energy, we finish the tasks in the following order: + + - 5th task. Now energy = 27 - 5 = 22. + + - 2nd task. Now energy = 22 - 2 = 20. + + - 3rd task. Now energy = 20 - 3 = 17. + + - 1st task. Now energy = 17 - 1 = 16. + + - 4th task. Now energy = 16 - 4 = 12. + + - 6th task. Now energy = 12 - 6 = 6. + +**Constraints:** + +* 1 <= tasks.length <= 105 +* 1 <= actuali <= minimumi <= 104 + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun minimumEffort(tasks: Array): Int { + Arrays.sort(tasks) { a: IntArray, b: IntArray -> a[1] - a[0] - b[1] + b[0] } + var prev = 0 + for (item in tasks) { + prev = Math.max(prev + item[0], item[1]) + } + return prev + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1667_fix_names_in_a_table/readme.md b/src/main/kotlin/g1601_1700/s1667_fix_names_in_a_table/readme.md new file mode 100644 index 00000000..14fed621 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1667_fix_names_in_a_table/readme.md @@ -0,0 +1,53 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1667\. Fix Names in a Table + +Easy + +SQL Schema + +Table: `Users` + + +----------------+---------+ + | Column Name | Type | + +----------------+---------+ + | user_id | int | + | name | varchar | + +----------------+---------+ + user_id is the primary key for this table. + This table contains the ID and the name of the user. The name consists of only lowercase and uppercase characters. + +Write an SQL query to fix the names so that only the first character is uppercase and the rest are lowercase. + +Return the result table ordered by `user_id`. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Users table: + +---------+-------+ + | user_id | name | + +---------+-------+ + | 1 | aLice | + | 2 | bOB | + +---------+-------+ + +**Output:** + + +---------+-------+ + | user_id | name | + +---------+-------+ + | 1 | Alice | + | 2 | Bob | + +---------+-------+ + +## Solution + +```sql +# Write your MySQL query statement below +select user_id, concat(upper(substring(name, 1, 1)), lower(substring(name, 2))) as name from Users order by user_id +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1668_maximum_repeating_substring/readme.md b/src/main/kotlin/g1601_1700/s1668_maximum_repeating_substring/readme.md new file mode 100644 index 00000000..e1044129 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1668_maximum_repeating_substring/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) + +## 1668\. Maximum Repeating Substring + +Easy + +For a string `sequence`, a string `word` is **`k`\-repeating** if `word` concatenated `k` times is a substring of `sequence`. The `word`'s **maximum `k`\-repeating value** is the highest value `k` where `word` is `k`\-repeating in `sequence`. If `word` is not a substring of `sequence`, `word`'s maximum `k`\-repeating value is `0`. + +Given strings `sequence` and `word`, return _the **maximum `k`\-repeating value** of `word` in `sequence`_. + +**Example 1:** + +**Input:** sequence = "ababc", word = "ab" + +**Output:** 2 + +**Explanation:** "abab" is a substring in "ababc". + +**Example 2:** + +**Input:** sequence = "ababc", word = "ba" + +**Output:** 1 + +**Explanation:** "ba" is a substring in "ababc". "baba" is not a substring in "ababc". + +**Example 3:** + +**Input:** sequence = "ababc", word = "ac" + +**Output:** 0 + +**Explanation:** "ac" is not a substring in "ababc". + +**Constraints:** + +* `1 <= sequence.length <= 100` +* `1 <= word.length <= 100` +* `sequence` and `word` contains only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun maxRepeating(sequence: String, word: String): Int { + var k = 0 + val repeat = StringBuilder(word) + while (sequence.contains(repeat)) { + k++ + repeat.append(word) + } + return k + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1669_merge_in_between_linked_lists/readme.md b/src/main/kotlin/g1601_1700/s1669_merge_in_between_linked_lists/readme.md new file mode 100644 index 00000000..66aca3ae --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1669_merge_in_between_linked_lists/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) + +## 1669\. Merge In Between Linked Lists + +Medium + +You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively. + +Remove `list1`'s nodes from the ath node to the bth node, and put `list2` in their place. + +The blue edges and nodes in the following figure indicate the result: + +![](https://assets.leetcode.com/uploads/2020/11/05/fig1.png) + +_Build the result list and return its head._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/05/merge_linked_list_ex1.png) + +**Input:** list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002] + +**Output:** [0,1,2,1000000,1000001,1000002,5] + +**Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. + +The blue edges and nodes in the above figure indicate the result. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/11/05/merge_linked_list_ex2.png) + +**Input:** list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004] + +**Output:** [0,1,1000000,1000001,1000002,1000003,1000004,6] + +**Explanation:** The blue edges and nodes in the above figure indicate the result. + +**Constraints:** + +* 3 <= list1.length <= 104 +* `1 <= a <= b < list1.length - 1` +* 1 <= list2.length <= 104 + +## Solution + +```kotlin +import com_github_leetcode.ListNode + +/* + * Example: + * var li = ListNode(5) + * var v = li.`val` + * Definition for singly-linked list. + * class ListNode(var `val`: Int) { + * var next: ListNode? = null + * } + */ +@Suppress("NAME_SHADOWING") +class Solution { + fun mergeInBetween(list1: ListNode?, a: Int, b: Int, list2: ListNode?): ListNode? { + var list2 = list2 + var start = list1 + for (i in 1 until a) { + start = start!!.next + } + var end = start + for (i in a..b) { + end = end!!.next + } + start!!.next = list2 + while (list2!!.next != null) { + list2 = list2.next + } + list2.next = end!!.next + return list1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1670_design_front_middle_back_queue/readme.md b/src/main/kotlin/g1601_1700/s1670_design_front_middle_back_queue/readme.md new file mode 100644 index 00000000..78e03960 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1670_design_front_middle_back_queue/readme.md @@ -0,0 +1,130 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1670\. Design Front Middle Back Queue + +Medium + +Design a queue that supports `push` and `pop` operations in the front, middle, and back. + +Implement the `FrontMiddleBack` class: + +* `FrontMiddleBack()` Initializes the queue. +* `void pushFront(int val)` Adds `val` to the **front** of the queue. +* `void pushMiddle(int val)` Adds `val` to the **middle** of the queue. +* `void pushBack(int val)` Adds `val` to the **back** of the queue. +* `int popFront()` Removes the **front** element of the queue and returns it. If the queue is empty, return `-1`. +* `int popMiddle()` Removes the **middle** element of the queue and returns it. If the queue is empty, return `-1`. +* `int popBack()` Removes the **back** element of the queue and returns it. If the queue is empty, return `-1`. + +**Notice** that when there are **two** middle position choices, the operation is performed on the **frontmost** middle position choice. For example: + +* Pushing `6` into the middle of `[1, 2, 3, 4, 5]` results in `[1, 2, 6, 3, 4, 5]`. +* Popping the middle from `[1, 2, 3, 4, 5, 6]` returns `3` and results in `[1, 2, 4, 5, 6]`. + +**Example 1:** + +**Input:** ["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", "popFront", "popMiddle", "popMiddle", "popBack", "popFront"] + +[[], [1], [2], [3], [4], [], [], [], [], []] + +**Output:** [null, null, null, null, null, 1, 3, 4, 2, -1] + +**Explanation:** + + FrontMiddleBackQueue q = new FrontMiddleBackQueue(); q.pushFront(1); // [1] + q.pushBack(2); // [1, 2] + q.pushMiddle(3); // [1, 3, 2] + q.pushMiddle(4); // [1, 4, 3, 2] + q.popFront(); // return 1 -> [4, 3, 2] + q.popMiddle(); // return 3 -> [4, 2] + q.popMiddle(); // return 4 -> [2] + q.popBack(); // return 2 -> [] + q.popFront(); // return -1 -> [] (The queue is empty) + +**Constraints:** + +* 1 <= val <= 109 +* At most `1000` calls will be made to `pushFront`, `pushMiddle`, `pushBack`, `popFront`, `popMiddle`, and `popBack`. + +## Solution + +```kotlin +class FrontMiddleBackQueue { + private val queue = IntArray(1000) + private var cur = -1 + fun pushFront(`val`: Int) { + cur++ + for (i in cur downTo 1) { + queue[i] = queue[i - 1] + } + queue[0] = `val` + } + + fun pushMiddle(`val`: Int) { + if (cur < 0) { + pushFront(`val`) + return + } + cur++ + val mid = cur / 2 + for (i in cur downTo mid + 1) { + queue[i] = queue[i - 1] + } + queue[mid] = `val` + } + + fun pushBack(`val`: Int) { + if (cur < 0) { + pushFront(`val`) + return + } + cur++ + queue[cur] = `val` + } + + fun popFront(): Int { + if (cur < 0) { + return -1 + } + val result = queue[0] + for (i in 0 until cur) { + queue[i] = queue[i + 1] + } + cur-- + return result + } + + fun popMiddle(): Int { + if (cur < 0) { + return -1 + } + val mid = cur / 2 + val result = queue[mid] + for (i in mid until cur) { + queue[i] = queue[i + 1] + } + cur-- + return result + } + + fun popBack(): Int { + if (cur < 0) { + return -1 + } + val result = queue[cur] + cur-- + return result + } +} +/* + * Your FrontMiddleBackQueue object will be instantiated and called as such: + * var obj = FrontMiddleBackQueue() + * obj.pushFront(`val`) + * obj.pushMiddle(`val`) + * obj.pushBack(`val`) + * var param_4 = obj.popFront() + * var param_5 = obj.popMiddle() + * var param_6 = obj.popBack() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1671_minimum_number_of_removals_to_make_mountain_array/readme.md b/src/main/kotlin/g1601_1700/s1671_minimum_number_of_removals_to_make_mountain_array/readme.md new file mode 100644 index 00000000..ea981e82 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1671_minimum_number_of_removals_to_make_mountain_array/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) + +## 1671\. Minimum Number of Removals to Make Mountain Array + +Hard + +You may recall that an array `arr` is a **mountain array** if and only if: + +* `arr.length >= 3` +* There exists some index `i` (**0-indexed**) with `0 < i < arr.length - 1` such that: + * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` + * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` + +Given an integer array `nums`, return _the **minimum** number of elements to remove to make_ `nums` _a **mountain array**._ + +**Example 1:** + +**Input:** nums = [1,3,1] + +**Output:** 0 + +**Explanation:** The array itself is a mountain array so we do not need to remove any elements. + +**Example 2:** + +**Input:** nums = [2,1,1,5,6,2,3,1] + +**Output:** 3 + +**Explanation:** One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1]. + +**Constraints:** + +* `3 <= nums.length <= 1000` +* 1 <= nums[i] <= 109 +* It is guaranteed that you can make a mountain array out of `nums`. + +## Solution + +```kotlin +class Solution { + fun minimumMountainRemovals(nums: IntArray): Int { + val n = nums.size + // lbs -> longest bitomic subsequence + var lbs = 0 + val dp = IntArray(n) + // dp[i] -> lis end at index i, dp2[i] -> lds end at index i + val dp2 = IntArray(n) + var lis: MutableList = ArrayList() + // calculate longest increasing subsequence + for (i in 0 until n - 1) { + if (lis.isEmpty() || lis[lis.size - 1] < nums[i]) { + lis.add(nums[i]) + } else { + val idx = lis.binarySearch(nums[i]) + if (idx < 0) { + lis[-idx - 1] = nums[i] + } + } + dp[i] = lis.size + } + lis = ArrayList() + // calculate longest decreasing subsequence + for (i in n - 1 downTo 1) { + if (lis.isEmpty() || lis[lis.size - 1] < nums[i]) { + lis.add(nums[i]) + } else { + val idx = lis.binarySearch(nums[i]) + if (idx < 0) { + lis[-idx - 1] = nums[i] + } + } + dp2[i] = lis.size + if (dp[i] > 1 && dp2[i] > 1) { + lbs = Math.max(lbs, dp[i] + dp2[i] - 1) + } + } + return n - lbs + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1672_richest_customer_wealth/readme.md b/src/main/kotlin/g1601_1700/s1672_richest_customer_wealth/readme.md new file mode 100644 index 00000000..9caf8c59 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1672_richest_customer_wealth/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) + +## 1672\. Richest Customer Wealth + +Easy + +You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the ith customer has in the jth bank. Return _the **wealth** that the richest customer has._ + +A customer's **wealth** is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum **wealth**. + +**Example 1:** + +**Input:** accounts = \[\[1,2,3],[3,2,1]] + +**Output:** 6 + +**Explanation::** + +`1st customer has wealth = 1 + 2 + 3 = 6` + +`2nd customer has wealth = 3 + 2 + 1 = 6` + +Both customers are considered the richest with a wealth of 6 each, so return 6. + +**Example 2:** + +**Input:** accounts = \[\[1,5],[7,3],[3,5]] + +**Output:** 10 + +**Explanation:** + +1st customer has wealth = 6 + +2nd customer has wealth = 10 + +3rd customer has wealth = 8 + +The 2nd customer is the richest with a wealth of 10. + +**Example 3:** + +**Input:** accounts = \[\[2,8,7],[7,1,3],[1,9,5]] + +**Output:** 17 + +**Constraints:** + +* `m == accounts.length` +* `n == accounts[i].length` +* `1 <= m, n <= 50` +* `1 <= accounts[i][j] <= 100` + +## Solution + +```kotlin +class Solution { + fun maximumWealth(accounts: Array): Int { + var max = Int.MIN_VALUE + for (account in accounts) { + var sum = 0 + for (i in account) { + sum += i + } + max = Math.max(max, sum) + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1673_find_the_most_competitive_subsequence/readme.md b/src/main/kotlin/g1601_1700/s1673_find_the_most_competitive_subsequence/readme.md new file mode 100644 index 00000000..0395604d --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1673_find_the_most_competitive_subsequence/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) + +## 1673\. Find the Most Competitive Subsequence + +Medium + +Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. + +An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. + +We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`. + +**Example 1:** + +**Input:** nums = [3,5,2,6], k = 2 + +**Output:** [2,6] + +**Explanation:** Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive. + +**Example 2:** + +**Input:** nums = [2,4,3,3,5,4,9,6], k = 4 + +**Output:** [2,3,3,4] + +**Constraints:** + +* 1 <= nums.length <= 105 +* 0 <= nums[i] <= 109 +* `1 <= k <= nums.length` + +## Solution + +```kotlin +class Solution { + fun mostCompetitive(nums: IntArray, k: Int): IntArray { + val r = IntArray(k) + val n = nums.size + var j = 0 + for (i in 0 until n) { + if (i == 0) { + r[j] = nums[i] + j++ + } else { + var l = j - 1 + while (l >= 0 && nums[i] < r[l] && n - i >= k - l) { + l-- + } + j = l + 1 + if (j < k) { + r[j] = nums[i] + j++ + } + } + } + return r + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1674_minimum_moves_to_make_array_complementary/readme.md b/src/main/kotlin/g1601_1700/s1674_minimum_moves_to_make_array_complementary/readme.md new file mode 100644 index 00000000..96758a8e --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1674_minimum_moves_to_make_array_complementary/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) + +## 1674\. Minimum Moves to Make Array Complementary + +Medium + +You are given an integer array `nums` of **even** length `n` and an integer `limit`. In one move, you can replace any integer from `nums` with another integer between `1` and `limit`, inclusive. + +The array `nums` is **complementary** if for all indices `i` (**0-indexed**), `nums[i] + nums[n - 1 - i]` equals the same number. For example, the array `[1,2,3,4]` is complementary because for all indices `i`, `nums[i] + nums[n - 1 - i] = 5`. + +Return the _**minimum** number of moves required to make_ `nums` _**complementary**_. + +**Example 1:** + +**Input:** nums = [1,2,4,3], limit = 4 + +**Output:** 1 + +**Explanation:** In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed). + +nums[0] + nums[3] = 1 + 3 = 4. + +nums[1] + nums[2] = 2 + 2 = 4. + +nums[2] + nums[1] = 2 + 2 = 4. + +nums[3] + nums[0] = 3 + 1 = 4. + +Therefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary. + +**Example 2:** + +**Input:** nums = [1,2,2,1], limit = 2 + +**Output:** 2 + +**Explanation:** In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit. + +**Example 3:** + +**Input:** nums = [1,2,1,2], limit = 2 + +**Output:** 0 + +**Explanation:** nums is already complementary. + +**Constraints:** + +* `n == nums.length` +* 2 <= n <= 105 +* 1 <= nums[i] <= limit <= 105 +* `n` is even. + +## Solution + +```kotlin +class Solution { + fun minMoves(nums: IntArray, limit: Int): Int { + val delta = IntArray(2 * limit + 2) + val n = nums.size + for (i in 0 until n / 2) { + val a = nums[i] + val b = nums[n - 1 - i] + delta[2] += 2 + delta[Math.min(a, b) + 1]-- + delta[a + b]-- + delta[a + b + 1]++ + delta[Math.max(a, b) + limit + 1]++ + } + var res = 2 * n + var curr = 0 + for (i in 2..2 * limit) { + curr += delta[i] + res = Math.min(res, curr) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1675_minimize_deviation_in_array/readme.md b/src/main/kotlin/g1601_1700/s1675_minimize_deviation_in_array/readme.md new file mode 100644 index 00000000..a9cdb321 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1675_minimize_deviation_in_array/readme.md @@ -0,0 +1,77 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1675\. Minimize Deviation in Array + +Hard + +You are given an array `nums` of `n` positive integers. + +You can perform two types of operations on any element of the array any number of times: + +* If the element is **even**, **divide** it by `2`. + * For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].` +* If the element is **odd**, **multiply** it by `2`. + * For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].` + +The **deviation** of the array is the **maximum difference** between any two elements in the array. + +Return _the **minimum deviation** the array can have after performing some number of operations._ + +**Example 1:** + +**Input:** nums = [1,2,3,4] + +**Output:** 1 + +**Explanation:** You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1. + +**Example 2:** + +**Input:** nums = [4,1,5,20,3] + +**Output:** 3 + +**Explanation:** You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3. + +**Example 3:** + +**Input:** nums = [2,10,8] + +**Output:** 3 + +**Constraints:** + +* `n == nums.length` +* 2 <= n <= 105 +* 1 <= nums[i] <= 109 + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + fun minimumDeviation(nums: IntArray): Int { + val pq = PriorityQueue { a: Int, b: Int -> b - a } + var min = Int.MAX_VALUE + for (num in nums) { + val localNum = if (num % 2 == 1) { + num * 2 + } else { + num + } + min = Math.min(min, localNum) + pq.offer(localNum) + } + var diff = Int.MAX_VALUE + while (pq.peek() % 2 == 0) { + val max = pq.poll() + diff = Math.min(diff, max - min) + min = Math.min(max / 2, min) + pq.offer(max / 2) + } + return Math.min(diff, pq.peek() - min) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1678_goal_parser_interpretation/readme.md b/src/main/kotlin/g1601_1700/s1678_goal_parser_interpretation/readme.md new file mode 100644 index 00000000..f3c96ecf --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1678_goal_parser_interpretation/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) + +## 1678\. Goal Parser Interpretation + +Easy + +You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G"`, `"()"` and/or `"(al)"` in some order. The Goal Parser will interpret `"G"` as the string `"G"`, `"()"` as the string `"o"`, and `"(al)"` as the string `"al"`. The interpreted strings are then concatenated in the original order. + +Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`. + +**Example 1:** + +**Input:** command = "G()(al)" + +**Output:** "Goal" + +**Explanation:** The Goal Parser interprets the command as follows: + +G -> G + +() -> o + +(al) -> al + +The final concatenated result is "Goal". + +**Example 2:** + +**Input:** command = "G()()()()(al)" + +**Output:** "Gooooal" + +**Example 3:** + +**Input:** command = "(al)G(al)()()G" + +**Output:** "alGalooG" + +**Constraints:** + +* `1 <= command.length <= 100` +* `command` consists of `"G"`, `"()"`, and/or `"(al)"` in some order. + +## Solution + +```kotlin +class Solution { + fun interpret(command: String): String { + val sb = StringBuilder() + var i = 0 + while (i < command.length) { + if (command[i] == '(' && command[i + 1] == ')') { + sb.append("o") + i++ + } else if ((command[i] != '(' || command[i + 1] == ')') && + command[i] != ')' + ) { + sb.append(command[i]) + } + i++ + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1679_max_number_of_k_sum_pairs/readme.md b/src/main/kotlin/g1601_1700/s1679_max_number_of_k_sum_pairs/readme.md new file mode 100644 index 00000000..8d1b6061 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1679_max_number_of_k_sum_pairs/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) + +## 1679\. Max Number of K-Sum Pairs + +Medium + +You are given an integer array `nums` and an integer `k`. + +In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array. + +Return _the maximum number of operations you can perform on the array_. + +**Example 1:** + +**Input:** nums = [1,2,3,4], k = 5 + +**Output:** 2 + +**Explanation:** Starting with nums = [1,2,3,4]: + +- Remove numbers 1 and 4, then nums = [2,3] + +- Remove numbers 2 and 3, then nums = [] + +There are no more pairs that sum up to 5, hence a total of 2 operations. + +**Example 2:** + +**Input:** nums = [3,1,3,4,3], k = 6 + +**Output:** 1 + +**Explanation:** Starting with nums = [3,1,3,4,3]: + +- Remove the first two 3's, then nums = [1,4,3] + +There are no more pairs that sum up to 6, hence a total of 1 operation. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 109 +* 1 <= k <= 109 + +## Solution + +```kotlin +class Solution { + fun maxOperations(nums: IntArray, k: Int): Int { + nums.sort() + var start = 0 + var end = nums.size - 1 + var count = 0 + while (start < end) { + val sum = nums[start] + nums[end] + if (sum == k) { + count++ + start++ + end-- + } else if (sum < k) { + start++ + } else { + end-- + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1680_concatenation_of_consecutive_binary_numbers/readme.md b/src/main/kotlin/g1601_1700/s1680_concatenation_of_consecutive_binary_numbers/readme.md new file mode 100644 index 00000000..f8def19e --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1680_concatenation_of_consecutive_binary_numbers/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) + +## 1680\. Concatenation of Consecutive Binary Numbers + +Medium + +Given an integer `n`, return _the **decimal value** of the binary string formed by concatenating the binary representations of_ `1` _to_ `n` _in order, **modulo**_ 109 + 7. + +**Example 1:** + +**Input:** n = 1 + +**Output:** 1 + +**Explanation:** "1" in binary corresponds to the decimal value 1. + +**Example 2:** + +**Input:** n = 3 + +**Output:** 27 + +**Explanation:** In binary, 1, 2, and 3 corresponds to "1", "10", and "11". + +After concatenating them, we have "11011", which corresponds to the decimal value 27. + +**Example 3:** + +**Input:** n = 12 + +**Output:** 505379714 + +**Explanation:** The concatenation results in "1101110010111011110001001101010111100". + +The decimal value of that is 118505380540. + +After modulo 109 + 7, the result is 505379714. + +**Constraints:** + +* 1 <= n <= 105 + +## Solution + +```kotlin +class Solution { + fun concatenatedBinary(n: Int): Int { + // calculate the length of binary string + var length = 0 + var sum: Long = 0 + for (i in 1..n) { + if (i and i - 1 == 0) { + length++ + } + sum = sum shl length + sum += i.toLong() + if (sum > MOD) { + sum %= MOD + } + } + return (sum % MOD).toInt() + } + + companion object { + private const val MOD: Long = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1681_minimum_incompatibility/readme.md b/src/main/kotlin/g1601_1700/s1681_minimum_incompatibility/readme.md new file mode 100644 index 00000000..410629dc --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1681_minimum_incompatibility/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) + +## 1681\. Minimum Incompatibility + +Hard + +You are given an integer array `nums` and an integer `k`. You are asked to distribute this array into `k` subsets of **equal size** such that there are no two equal elements in the same subset. + +A subset's **incompatibility** is the difference between the maximum and minimum elements in that array. + +Return _the **minimum possible sum of incompatibilities** of the_ `k` _subsets after distributing the array optimally, or return_ `-1` _if it is not possible._ + +A subset is a group integers that appear in the array with no particular order. + +**Example 1:** + +**Input:** nums = [1,2,1,4], k = 2 + +**Output:** 4 + +**Explanation:** The optimal distribution of subsets is [1,2] and [1,4]. + +The incompatibility is (2-1) + (4-1) = 4. + +Note that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements. + +**Example 2:** + +**Input:** nums = [6,3,8,1,3,1,2,2], k = 4 + +**Output:** 6 + +**Explanation:** The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3]. + +The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6. + +**Example 3:** + +**Input:** nums = [5,3,3,6,3,3], k = 3 + +**Output:** -1 + +**Explanation:** It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset. + +**Constraints:** + +* `1 <= k <= nums.length <= 16` +* `nums.length` is divisible by `k` +* `1 <= nums[i] <= nums.length` + +## Solution + +```kotlin +class Solution { + private class Node { + var visited: BooleanArray = BooleanArray(17) + var size = 0 + var min = 20 + var max = 0 + } + + private lateinit var nodes: Array + private var size = 0 + private var result = 1000000 + private var currentSum = 0 + + fun minimumIncompatibility(nums: IntArray, k: Int): Int { + size = nums.size / k + nodes = arrayOfNulls(k) + for (i in 0 until k) { + nodes[i] = Node() + } + nums.sort() + currentSum = 0 + solve(nums, 0) + return if (result == 1000000) -1 else result + } + + private fun solve(nums: IntArray, idx: Int) { + if (idx == nums.size) { + result = currentSum + return + } + var minSize = size + var prevMin: Int + var prevMax: Int + var diff: Int + for (node in nodes) { + if (node!!.size == minSize || node.visited[nums[idx]]) { + continue + } + minSize = node.size + prevMin = node.min + prevMax = node.max + diff = prevMax - prevMin + node.min = Math.min(node.min, nums[idx]) + node.max = Math.max(node.max, nums[idx]) + node.size++ + node.visited[nums[idx]] = true + currentSum += if (prevMin == 20) { + node.max - node.min + } else { + node.max - node.min - diff + } + if (currentSum < result) { + solve(nums, idx + 1) + } + currentSum -= if (prevMin == 20) { + node.max - node.min + } else { + node.max - node.min - diff + } + node.visited[nums[idx]] = false + node.size-- + node.min = prevMin + node.max = prevMax + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1683_invalid_tweets/readme.md b/src/main/kotlin/g1601_1700/s1683_invalid_tweets/readme.md new file mode 100644 index 00000000..4f917746 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1683_invalid_tweets/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) + +## 1683\. Invalid Tweets + +Easy + +SQL Schema + +Table: `Tweets` + + +----------------+---------+ + | Column Name | Type | + +----------------+---------+ + | tweet_id | int | + | content | varchar | + +----------------+---------+ + tweet_id is the primary key for this table. + This table contains all the tweets in a social media app. + +Write an SQL query to find the IDs of the invalid tweets. The tweet is invalid if the number of characters used in the content of the tweet is **strictly greater** than `15`. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Tweets table: + +----------+----------------------------------+ + | tweet_id | content | + +----------+----------------------------------+ + | 1 | Vote for Biden | + | 2 | Let us make America great again! | + +----------+----------------------------------+ + +**Output:** + + +----------+ + | tweet_id | + +----------+ + | 2 | + +----------+ + +**Explanation:** + +Tweet 1 has length = 14. It is a valid tweet. + +Tweet 2 has length = 32. It is an invalid tweet. + +## Solution + +```sql +# Write your MySQL query statement below +SELECT tweet_id +FROM Tweets +WHERE LENGTH(content) > 15 +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1684_count_the_number_of_consistent_strings/readme.md b/src/main/kotlin/g1601_1700/s1684_count_the_number_of_consistent_strings/readme.md new file mode 100644 index 00000000..30d1119e --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1684_count_the_number_of_consistent_strings/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) + +## 1684\. Count the Number of Consistent Strings + +Easy + +You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`. + +Return _the number of **consistent** strings in the array_ `words`. + +**Example 1:** + +**Input:** allowed = "ab", words = ["ad","bd","aaab","baa","badab"] + +**Output:** 2 + +**Explanation:** Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'. + +**Example 2:** + +**Input:** allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"] + +**Output:** 7 + +**Explanation:** All strings are consistent. + +**Example 3:** + +**Input:** allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"] + +**Output:** 4 + +**Explanation:** Strings "cc", "acd", "ac", and "d" are consistent. + +**Constraints:** + +* 1 <= words.length <= 104 +* `1 <= allowed.length <= 26` +* `1 <= words[i].length <= 10` +* The characters in `allowed` are **distinct**. +* `words[i]` and `allowed` contain only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun countConsistentStrings(allowed: String, words: Array): Int { + var alwd = 0 + var res = 0 + for (i in 0 until allowed.length) { + alwd = alwd or (1 shl allowed[i].code) + } + for (word in words) { + var b = 0 + for (j in 0 until word.length) { + b = b or (1 shl word[j].code) + } + if (alwd or b == alwd) { + ++res + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1685_sum_of_absolute_differences_in_a_sorted_array/readme.md b/src/main/kotlin/g1601_1700/s1685_sum_of_absolute_differences_in_a_sorted_array/readme.md new file mode 100644 index 00000000..8678e33b --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1685_sum_of_absolute_differences_in_a_sorted_array/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) + +## 1685\. Sum of Absolute Differences in a Sorted Array + +Medium + +You are given an integer array `nums` sorted in **non-decreasing** order. + +Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._ + +In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**). + +**Example 1:** + +**Input:** nums = [2,3,5] + +**Output:** [4,3,5] + +**Explanation:** Assuming the arrays are 0-indexed, then + +result[0] = \|2-2\| + \|2-3\| + \|2-5\| = 0 + 1 + 3 = 4, + +result[1] = \|3-2\| + \|3-3\| + \|3-5\| = 1 + 0 + 2 = 3, + +result[2] = \|5-2\| + \|5-3\| + \|5-5\| = 3 + 2 + 0 = 5. + +**Example 2:** + +**Input:** nums = [1,4,6,8,10] + +**Output:** [24,15,13,15,21] + +**Constraints:** + +* 2 <= nums.length <= 105 +* 1 <= nums[i] <= nums[i + 1] <= 104 + +## Solution + +```kotlin +class Solution { + fun getSumAbsoluteDifferences(nums: IntArray): IntArray { + val len = nums.size + val preSums = IntArray(len) + for (i in 1 until len) { + preSums[i] = preSums[i - 1] + nums[i - 1] + } + val postSums = IntArray(len) + for (i in len - 2 downTo 0) { + postSums[i] = postSums[i + 1] + nums[i + 1] + } + val result = IntArray(len) + for (i in 0 until len) { + result[i] = nums[i] * i - preSums[i] + postSums[i] - nums[i] * (len - i - 1) + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1686_stone_game_vi/readme.md b/src/main/kotlin/g1601_1700/s1686_stone_game_vi/readme.md new file mode 100644 index 00000000..958bf2ca --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1686_stone_game_vi/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) + +## 1686\. Stone Game VI + +Medium + +Alice and Bob take turns playing a game, with Alice starting first. + +There are `n` stones in a pile. On each player's turn, they can **remove** a stone from the pile and receive points based on the stone's value. Alice and Bob may **value the stones differently**. + +You are given two integer arrays of length `n`, `aliceValues` and `bobValues`. Each `aliceValues[i]` and `bobValues[i]` represents how Alice and Bob, respectively, value the ith stone. + +The winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play **optimally**. Both players know the other's values. + +Determine the result of the game, and: + +* If Alice wins, return `1`. +* If Bob wins, return `-1`. +* If the game results in a draw, return `0`. + +**Example 1:** + +**Input:** aliceValues = [1,3], bobValues = [2,1] + +**Output:** 1 + +**Explanation:** If Alice takes stone 1 (0-indexed) first, Alice will receive 3 points. + +Bob can only choose stone 0, and will only receive 2 points. + +Alice wins. + +**Example 2:** + +**Input:** aliceValues = [1,2], bobValues = [3,1] + +**Output:** 0 + +**Explanation:** If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point. + +Draw. + +**Example 3:** + +**Input:** aliceValues = [2,4,3], bobValues = [1,6,7] + +**Output:** -1 + +**Explanation:** Regardless of how Alice plays, Bob will be able to have more points than Alice. + +For example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7. + +Bob wins. + +**Constraints:** + +* `n == aliceValues.length == bobValues.length` +* 1 <= n <= 105 +* `1 <= aliceValues[i], bobValues[i] <= 100` + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + private class Pair internal constructor(var a: Int, var b: Int) : Comparable { + var sum: Int + + init { + sum = a + b + } + + override fun compareTo(other: Pair): Int { + return other.sum - sum + } + } + + fun stoneGameVI(aliceValues: IntArray, bobValues: IntArray): Int { + val pq = PriorityQueue() + for (i in aliceValues.indices) { + pq.add(Pair(aliceValues[i], bobValues[i])) + } + var turn = true + var a = 0 + var b = 0 + while (pq.isNotEmpty()) { + if (turn) { + a += pq.poll().a + } else { + b += pq.poll().b + } + turn = !turn + } + return Integer.compare(a, b) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1687_delivering_boxes_from_storage_to_ports/readme.md b/src/main/kotlin/g1601_1700/s1687_delivering_boxes_from_storage_to_ports/readme.md new file mode 100644 index 00000000..5c2723a2 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1687_delivering_boxes_from_storage_to_ports/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) + +## 1687\. Delivering Boxes from Storage to Ports + +Hard + +You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a **limit** on the **number of boxes** and the **total weight** that it can carry. + +You are given an array `boxes`, where boxes[i] = [portsi, weighti], and three integers `portsCount`, `maxBoxes`, and `maxWeight`. + +* portsi is the port where you need to deliver the ith box and weightsi is the weight of the ith box. +* `portsCount` is the number of ports. +* `maxBoxes` and `maxWeight` are the respective box and weight limits of the ship. + +The boxes need to be delivered **in the order they are given**. The ship will follow these steps: + +* The ship will take some number of boxes from the `boxes` queue, not violating the `maxBoxes` and `maxWeight` constraints. +* For each loaded box **in order**, the ship will make a **trip** to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no **trip** is needed, and the box can immediately be delivered. +* The ship then makes a return **trip** to storage to take more boxes from the queue. + +The ship must end at storage after all the boxes have been delivered. + +Return _the **minimum** number of **trips** the ship needs to make to deliver all boxes to their respective ports._ + +**Example 1:** + +**Input:** boxes = \[\[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3 + +**Output:** 4 + +**Explanation:** The optimal strategy is as follows: + +- The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips. + +So the total number of trips is 4. + +Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box). + +**Example 2:** + +**Input:** boxes = \[\[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6 + +**Output:** 6 + +**Explanation:** The optimal strategy is as follows: - The ship takes the first box, goes to port 1, then returns to storage. 2 trips. - The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips. - The ship takes the fifth box, goes to port 3, then returns to storage. 2 trips. So the total number of trips is 2 + 2 + 2 = 6. + +**Example 3:** + +**Input:** boxes = \[\[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7 + +**Output:** 6 + +**Explanation:** The optimal strategy is as follows: + +- The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips. + +- The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips. + +- The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips. + +So the total number of trips is 2 + 2 + 2 = 6. + +**Constraints:** + +* 1 <= boxes.length <= 105 +* 1 <= portsCount, maxBoxes, maxWeight <= 105 +* 1 <= portsi <= portsCount +* 1 <= weightsi <= maxWeight + +## Solution + +```kotlin +@Suppress("UNUSED_PARAMETER") +class Solution { + fun boxDelivering(boxes: Array, portsCount: Int, maxBoxes: Int, maxWeight: Int): Int { + var t = 2 + var weight = 0 + val n = boxes.size + val dp = IntArray(n + 1) + dp[0] = 0 + var left = 0 + for (right in boxes.indices) { + weight += boxes[right][1] + if (right > 0 && boxes[right][0] != boxes[right - 1][0]) { + t++ + } + // checking if weight, boxes are less than or equal to max contraint + while (weight > maxWeight || right - left >= maxBoxes || left < right && dp[left] == dp[left + 1]) { + weight -= boxes[left][1] + if (boxes[left][0] != boxes[left + 1][0]) { + t-- + } + left++ + } + dp[right + 1] = dp[left] + t + } + return dp[n] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1688_count_of_matches_in_tournament/readme.md b/src/main/kotlin/g1601_1700/s1688_count_of_matches_in_tournament/readme.md new file mode 100644 index 00000000..f94ce6ec --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1688_count_of_matches_in_tournament/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) + +## 1688\. Count of Matches in Tournament + +Easy + +You are given an integer `n`, the number of teams in a tournament that has strange rules: + +* If the current number of teams is **even**, each team gets paired with another team. A total of `n / 2` matches are played, and `n / 2` teams advance to the next round. +* If the current number of teams is **odd**, one team randomly advances in the tournament, and the rest gets paired. A total of `(n - 1) / 2` matches are played, and `(n - 1) / 2 + 1` teams advance to the next round. + +Return _the number of matches played in the tournament until a winner is decided._ + +**Example 1:** + +**Input:** n = 7 + +**Output:** 6 + +**Explanation:** Details of the tournament: + +- 1st Round: Teams = 7, Matches = 3, and 4 teams advance. + +- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance. + +- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner. + +Total number of matches = 3 + 2 + 1 = 6. + +**Example 2:** + +**Input:** n = 14 + +**Output:** 13 + +**Explanation:** Details of the tournament: + +- 1st Round: Teams = 14, Matches = 7, and 7 teams advance. + +- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance. + +- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance. + +- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner. + +Total number of matches = 7 + 3 + 2 + 1 = 13. + +**Constraints:** + +* `1 <= n <= 200` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun numberOfMatches(n: Int): Int { + var n = n + var matches = 0 + while (n > 1) { + if (n % 2 == 0) { + matches += n / 2 + n /= 2 + } else { + matches += (n - 1) / 2 + n = (n + 1) / 2 + } + } + return matches + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1689_partitioning_into_minimum_number_of_deci_binary_numbers/readme.md b/src/main/kotlin/g1601_1700/s1689_partitioning_into_minimum_number_of_deci_binary_numbers/readme.md new file mode 100644 index 00000000..141c1a6e --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1689_partitioning_into_minimum_number_of_deci_binary_numbers/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) + +## 1689\. Partitioning Into Minimum Number Of Deci-Binary Numbers + +Medium + +A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. + +Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** numbers needed so that they sum up to_ `n`_._ + +**Example 1:** + +**Input:** n = "32" + +**Output:** 3 + +**Explanation:** 10 + 11 + 11 = 32 + +**Example 2:** + +**Input:** n = "82734" + +**Output:** 8 + +**Example 3:** + +**Input:** n = "27346209830709182346" + +**Output:** 9 + +**Constraints:** + +* 1 <= n.length <= 105 +* `n` consists of only digits. +* `n` does not contain any leading zeros and represents a positive integer. + +## Solution + +```kotlin +class Solution { + fun minPartitions(n: String): Int { + val tempArray = n.toCharArray() + var result = 0 + for (i in 0 until n.length) { + result = Math.max(result, tempArray[i].code - 48) + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1690_stone_game_vii/readme.md b/src/main/kotlin/g1601_1700/s1690_stone_game_vii/readme.md new file mode 100644 index 00000000..ab08184d --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1690_stone_game_vii/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) + +## 1690\. Stone Game VII + +Medium + +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, they can **remove** either the leftmost stone or the rightmost stone from the row and receive points equal to the **sum** of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove. + +Bob found that he will always lose this game (poor Bob, he always loses), so he decided to **minimize the score's difference**. Alice's goal is to **maximize the difference** in the score. + +Given an array of integers `stones` where `stones[i]` represents the value of the ith stone **from the left**, return _the **difference** in Alice and Bob's score if they both play **optimally**._ + +**Example 1:** + +**Input:** stones = [5,3,1,4,2] + +**Output:** 6 + +**Explanation:** + +- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4]. + +- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4]. + +- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4]. + +- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = [4]. + +- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = []. + +The score difference is 18 - 12 = 6. + +**Example 2:** + +**Input:** stones = [7,90,5,1,100,10,10,2] + +**Output:** 122 + +**Constraints:** + +* `n == stones.length` +* `2 <= n <= 1000` +* `1 <= stones[i] <= 1000` + +## Solution + +```kotlin +class Solution { + fun stoneGameVII(stones: IntArray): Int { + val n = stones.size + val dp = IntArray(n) + for (i in n - 1 downTo 0) { + var j = i + 1 + var sum = stones[i] + while (j < n) { + sum += stones[j] + dp[j] = Math.max(sum - stones[i] - dp[j], sum - stones[j] - dp[j - 1]) + j++ + } + } + return dp[n - 1] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1691_maximum_height_by_stacking_cuboids/readme.md b/src/main/kotlin/g1601_1700/s1691_maximum_height_by_stacking_cuboids/readme.md new file mode 100644 index 00000000..1ec1e441 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1691_maximum_height_by_stacking_cuboids/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) + +## 1691\. Maximum Height by Stacking Cuboids + +Hard + +Given `n` `cuboids` where the dimensions of the ith cuboid is cuboids[i] = [widthi, lengthi, heighti] (**0-indexed**). Choose a **subset** of `cuboids` and place them on each other. + +You can place cuboid `i` on cuboid `j` if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid. + +Return _the **maximum height** of the stacked_ `cuboids`. + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2019/10/21/image.jpg)** + +**Input:** cuboids = \[\[50,45,20],[95,37,53],[45,23,12]] + +**Output:** 190 + +**Explanation:** + +Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95. + +Cuboid 0 is placed next with the 45x20 side facing down with height 50. + +Cuboid 2 is placed next with the 23x12 side facing down with height 45. + +The total height is 95 + 50 + 45 = 190. + +**Example 2:** + +**Input:** cuboids = \[\[38,25,45],[76,35,3]] + +**Output:** 76 + +**Explanation:** + +You can't place any of the cuboids on the other. + +We choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76. + +**Example 3:** + +**Input:** cuboids = \[\[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]] + +**Output:** 102 + +**Explanation:** + +After rearranging the cuboids, you can see that all cuboids have the same dimension. + +You can place the 11x7 side down on all cuboids so their heights are 17. + +The maximum height of stacked cuboids is 6 \* 17 = 102. + +**Constraints:** + +* `n == cuboids.length` +* `1 <= n <= 100` +* 1 <= widthi, lengthi, heighti <= 100 + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun maxHeight(cuboids: Array): Int { + for (a in cuboids) { + a.sort() + } + Arrays.sort( + cuboids + ) { a: IntArray, b: IntArray -> + if (a[0] != b[0]) { + return@sort a[0] - b[0] + } else if (a[1] != b[1]) { + return@sort a[1] - b[1] + } + a[2] - b[2] + } + var ans = 0 + val dp = IntArray(cuboids.size) + for (i in cuboids.indices) { + dp[i] = cuboids[i][2] + for (j in 0 until i) { + if (cuboids[i][0] >= cuboids[j][0] && + cuboids[i][1] >= cuboids[j][1] && cuboids[i][2] >= cuboids[j][2] + ) { + dp[i] = Math.max(dp[i], cuboids[i][2] + dp[j]) + } + } + ans = Math.max(ans, dp[i]) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1693_daily_leads_and_partners/readme.md b/src/main/kotlin/g1601_1700/s1693_daily_leads_and_partners/readme.md new file mode 100644 index 00000000..4b229f67 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1693_daily_leads_and_partners/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) + +## 1693\. Daily Leads and Partners + +Easy + +SQL Schema + +Table: `DailySales` + + +-------------+---------+ + | Column Name | Type | + +-------------+---------+ + | date_id | date | + | make_name | varchar | + | lead_id | int | + | partner_id | int | + +-------------+---------+ + This table does not have a primary key. + This table contains the date and the name of the product sold and the IDs of the lead and partner it was sold to. + The name consists of only lowercase English letters. + +Write an SQL query that will, for each `date_id` and `make_name`, return the number of **distinct** `lead_id`'s and **distinct** `partner_id`'s. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + DailySales table: + +-----------+-----------+---------+------------+ + | date_id | make_name | lead_id | partner_id | + +-----------+-----------+---------+------------+ + | 2020-12-8 | toyota | 0 | 1 | + | 2020-12-8 | toyota | 1 | 0 | + | 2020-12-8 | toyota | 1 | 2 | + | 2020-12-7 | toyota | 0 | 2 | + | 2020-12-7 | toyota | 0 | 1 | + | 2020-12-8 | honda | 1 | 2 | + | 2020-12-8 | honda | 2 | 1 | + | 2020-12-7 | honda | 0 | 1 | + | 2020-12-7 | honda | 1 | 2 | + | 2020-12-7 | honda | 2 | 1 | + +-----------+-----------+---------+------------+ + +**Output:** + + +-----------+-----------+--------------+-----------------+ + | date_id | make_name | unique_leads | unique_partners | + +-----------+-----------+--------------+-----------------+ + | 2020-12-8 | toyota | 2 | 3 | + | 2020-12-7 | toyota | 1 | 2 | + | 2020-12-8 | honda | 2 | 2 | + | 2020-12-7 | honda | 3 | 2 | + +-----------+-----------+--------------+-----------------+ + +**Explanation:** + +For 2020-12-8, toyota gets leads = [0, 1] and partners = [0, 1, 2] while honda gets leads = [1, 2] and partners = [1, 2]. + +For 2020-12-7, toyota gets leads = [0] and partners = [1, 2] while honda gets leads = [0, 1, 2] and partners = [1, 2]. + +## Solution + +```sql +# Write your MySQL query statement below +select date_id, make_name, COUNT(DISTINCT lead_id) as unique_leads, COUNT(DISTINCT partner_id) as unique_partners from DailySales group by date_id, make_name +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1694_reformat_phone_number/readme.md b/src/main/kotlin/g1601_1700/s1694_reformat_phone_number/readme.md new file mode 100644 index 00000000..f2a7326d --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1694_reformat_phone_number/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) + +## 1694\. Reformat Phone Number + +Easy + +You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`. + +You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or fewer digits. The final digits are then grouped as follows: + +* 2 digits: A single block of length 2. +* 3 digits: A single block of length 3. +* 4 digits: Two blocks of length 2 each. + +The blocks are then joined by dashes. Notice that the reformatting process should **never** produce any blocks of length 1 and produce **at most** two blocks of length 2. + +Return _the phone number after formatting._ + +**Example 1:** + +**Input:** number = "1-23-45 6" + +**Output:** "123-456" + +**Explanation:** The digits are "123456".t + +Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123". + +Step 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is "456". + +Joining the blocks gives "123-456". + +**Example 2:** + +**Input:** number = "123 4-567" + +**Output:** "123-45-67" + +**Explanation:** The digits are "1234567". + +Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123". + +Step 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are "45" and "67". + +Joining the blocks gives "123-45-67". + +**Example 3:** + +**Input:** number = "123 4-5678" + +**Output:** "123-456-78" + +**Explanation:** The digits are "12345678". + +Step 1: The 1st block is "123". + +Step 2: The 2nd block is "456". + +Step 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is "78". + +Joining the blocks gives "123-456-78". + +**Constraints:** + +* `2 <= number.length <= 100` +* `number` consists of digits and the characters `'-'` and `' '`. +* There are at least **two** digits in `number`. + +## Solution + +```kotlin +class Solution { + fun reformatNumber(number: String): String { + val sb = StringBuilder() + for (c in number.toCharArray()) { + if (Character.isDigit(c)) { + sb.append(c) + } + } + val cleaned = sb.toString() + sb.setLength(0) + var i = 0 + while (i < cleaned.length) { + i += if (i + 4 == cleaned.length) { + sb.append(cleaned, i, i + 2) + sb.append("-") + sb.append(cleaned.substring(i + 2)) + break + } else if (i + 3 <= cleaned.length) { + sb.append(cleaned, i, i + 3) + sb.append("-") + 3 + } else { + sb.append(cleaned.substring(i)) + break + } + } + if (sb[sb.length - 1] == '-') { + sb.setLength(sb.length - 1) + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1695_maximum_erasure_value/readme.md b/src/main/kotlin/g1601_1700/s1695_maximum_erasure_value/readme.md new file mode 100644 index 00000000..4c94224a --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1695_maximum_erasure_value/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) + +## 1695\. Maximum Erasure Value + +Medium + +You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements. + +Return _the **maximum score** you can get by erasing **exactly one** subarray._ + +An array `b` is called to be a subarray of `a` if it forms a contiguous subsequence of `a`, that is, if it is equal to `a[l],a[l+1],...,a[r]` for some `(l,r)`. + +**Example 1:** + +**Input:** nums = [4,2,4,5,6] + +**Output:** 17 + +**Explanation:** The optimal subarray here is [2,4,5,6]. + +**Example 2:** + +**Input:** nums = [5,2,1,2,5,2,1,2,5] + +**Output:** 8 + +**Explanation:** The optimal subarray here is [5,2,1] or [1,2,5]. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun maximumUniqueSubarray(nums: IntArray): Int { + var ans = 0 + var sum = 0 + val seen = BooleanArray(10001) + var j = 0 + for (num in nums) { + while (seen[num]) { + seen[nums[j]] = false + sum -= nums[j++] + } + seen[num] = true + sum += num + ans = Math.max(sum, ans) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1696_jump_game_vi/readme.md b/src/main/kotlin/g1601_1700/s1696_jump_game_vi/readme.md new file mode 100644 index 00000000..0afa8d6d --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1696_jump_game_vi/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) + +## 1696\. Jump Game VI + +Medium + +You are given a **0-indexed** integer array `nums` and an integer `k`. + +You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**. + +You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array. + +Return _the **maximum score** you can get_. + +**Example 1:** + +**Input:** nums = [1,\-1,-2,4,-7,3], k = 2 + +**Output:** 7 + +**Explanation:** You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7. + +**Example 2:** + +**Input:** nums = [10,-5,-2,4,0,3], k = 3 + +**Output:** 17 + +**Explanation:** You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17. + +**Example 3:** + +**Input:** nums = [1,-5,-20,4,-1,3,-6,-3], k = 2 + +**Output:** 0 + +**Constraints:** + +* 1 <= nums.length, k <= 105 +* -104 <= nums[i] <= 104 + +## Solution + +```kotlin +import java.util.ArrayDeque +import java.util.Deque + +class Solution { + fun maxResult(nums: IntArray, k: Int): Int { + val deque: Deque = ArrayDeque() + deque.offer(intArrayOf(0, nums[0])) + for (i in 1 until nums.size) { + val max = deque.peek()[1] + val next = intArrayOf(i, max + nums[i]) + while (deque.isNotEmpty() && deque.peekLast()[1] <= next[1]) { + // PURGE FROM THE END + deque.pollLast() + } + deque.offer(next) + if (deque.peekFirst()[0] <= i - k) { + // PURGE FROM THE HEAD + deque.pollFirst() + } + } + return deque.peekLast()[1] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1697_checking_existence_of_edge_length_limited_paths/readme.md b/src/main/kotlin/g1601_1700/s1697_checking_existence_of_edge_length_limited_paths/readme.md new file mode 100644 index 00000000..6cb8c210 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1697_checking_existence_of_edge_length_limited_paths/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) + +## 1697\. Checking Existence of Edge Length Limited Paths + +Hard + +An undirected graph of `n` nodes is defined by `edgeList`, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be **multiple** edges between two nodes. + +Given an array `queries`, where queries[j] = [pj, qj, limitj], your task is to determine for each `queries[j]` whether there is a path between pj and qj such that each edge on the path has a distance **strictly less than** limitj . + +Return _a **boolean array**_ `answer`_, where_ `answer.length == queries.length` _and the_ jth _value of_ `answer` _is_ `true` _if there is a path for_ `queries[j]` _is_ `true`_, and_ `false` _otherwise_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/12/08/h.png) + +**Input:** n = 3, edgeList = \[\[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = \[\[0,1,2],[0,2,5]] + +**Output:** [false,true] + +**Explanation:** The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16. + +For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query. + +For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/12/08/q.png) + +**Input:** n = 5, edgeList = \[\[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = \[\[0,4,14],[1,4,13]] + +**Output:** [true,false] **Exaplanation:** The above figure shows the given graph. + +**Constraints:** + +* 2 <= n <= 105 +* 1 <= edgeList.length, queries.length <= 105 +* `edgeList[i].length == 3` +* `queries[j].length == 3` +* 0 <= ui, vi, pj, qj <= n - 1 +* ui != vi +* pj != qj +* 1 <= disi, limitj <= 109 +* There may be **multiple** edges between two nodes. + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + private class Dsu(n: Int) { + private val parent: IntArray + + init { + parent = IntArray(n) + parent.fill(-1) + } + + fun find(num: Int): Int { + if (parent[num] == -1) { + return num + } + parent[num] = find(parent[num]) + return parent[num] + } + + fun union(a: Int, b: Int) { + val p1 = find(a) + val p2 = find(b) + if (p1 != p2) { + parent[p2] = p1 + } + } + } + + fun distanceLimitedPathsExist(n: Int, edgeList: Array, queries: Array): BooleanArray { + Arrays.sort(edgeList) { o1: IntArray, o2: IntArray -> Integer.compare(o1[2], o2[2]) } + val data = Array(queries.size) { IntArray(4) } + for (i in queries.indices) { + data[i] = intArrayOf(queries[i][0], queries[i][1], queries[i][2], i) + } + Arrays.sort(data) { o1: IntArray, o2: IntArray -> Integer.compare(o1[2], o2[2]) } + val d = Dsu(n) + var j = 0 + val ans = BooleanArray(queries.size) + for (datum in data) { + while (j < edgeList.size && edgeList[j][2] < datum[2]) { + d.union(edgeList[j][0], edgeList[j][1]) + j++ + } + if (d.find(datum[0]) == d.find(datum[1])) { + ans[datum[3]] = true + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1601_1700/s1700_number_of_students_unable_to_eat_lunch/readme.md b/src/main/kotlin/g1601_1700/s1700_number_of_students_unable_to_eat_lunch/readme.md new file mode 100644 index 00000000..eb8f7753 --- /dev/null +++ b/src/main/kotlin/g1601_1700/s1700_number_of_students_unable_to_eat_lunch/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) + +## 1700\. Number of Students Unable to Eat Lunch + +Easy + +The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. + +The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a **stack**. At each step: + +* If the student at the front of the queue **prefers** the sandwich on the top of the stack, they will **take it** and leave the queue. +* Otherwise, they will **leave it** and go to the queue's end. + +This continues until none of the queue students want to take the top sandwich and are thus unable to eat. + +You are given two integer arrays `students` and `sandwiches` where `sandwiches[i]` is the type of the ith sandwich in the stack (`i = 0` is the top of the stack) and `students[j]` is the preference of the jth student in the initial queue (`j = 0` is the front of the queue). Return _the number of students that are unable to eat._ + +**Example 1:** + +**Input:** students = [1,1,0,0], sandwiches = [0,1,0,1] + +**Output:** 0 + +**Explanation:** + +- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1]. + +- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1]. + +- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1]. + +- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0]. + +- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1]. + +- Front student leaves the top sandwich and returns to the end of the line making students = [0,1]. + +- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1]. + +- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = []. + +Hence all students are able to eat. + +**Example 2:** + +**Input:** students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1] + +**Output:** 3 + +**Constraints:** + +* `1 <= students.length, sandwiches.length <= 100` +* `students.length == sandwiches.length` +* `sandwiches[i]` is `0` or `1`. +* `students[i]` is `0` or `1`. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + fun countStudents(students: IntArray, sandwiches: IntArray): Int { + val studentsQueue: Queue = LinkedList() + val sandwichesQueue: Queue = LinkedList() + for (i in sandwiches.indices) { + studentsQueue.add(students[i]) + sandwichesQueue.add(sandwiches[i]) + } + do { + if (studentsQueue.isNotEmpty()) { + if (studentsQueue.peek() == sandwichesQueue.peek()) { + studentsQueue.poll() + sandwichesQueue.poll() + } else { + if (!studentsQueue.contains(sandwichesQueue.peek())) { + break + } + studentsQueue.add(studentsQueue.poll()) + } + } + } while (studentsQueue.isNotEmpty()) + return studentsQueue.size + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1701_average_waiting_time/readme.md b/src/main/kotlin/g1701_1800/s1701_average_waiting_time/readme.md new file mode 100644 index 00000000..f3d40ae4 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1701_average_waiting_time/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) + +## 1701\. Average Waiting Time + +Medium + +There is a restaurant with a single chef. You are given an array `customers`, where customers[i] = [arrivali, timei]: + +* arrivali is the arrival time of the ith customer. The arrival times are sorted in **non-decreasing** order. +* timei is the time needed to prepare the order of the ith customer. + +When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers **in the order they were given in the input**. + +Return _the **average** waiting time of all customers_. Solutions within 10-5 from the actual answer are considered accepted. + +**Example 1:** + +**Input:** customers = \[\[1,2],[2,5],[4,3]] + +**Output:** 5.00000 + +**Explanation:** + +1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. + +2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. + +3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. So the average waiting time = (2 + 6 + 7) / 3 = 5. + +**Example 2:** + +**Input:** customers = \[\[5,2],[5,4],[10,3],[20,1]] + +**Output:** 3.25000 + +**Explanation:** + +1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. + +2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. + +3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. + +4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. + +**Constraints:** + +* 1 <= customers.length <= 105 +* 1 <= arrivali, timei <= 104 +* arrivali <= arrivali+1 + +## Solution + +```kotlin +class Solution { + fun averageWaitingTime(customers: Array): Double { + var ctime = 0 + var ans = 0.0 + for (customer in customers) { + if (customer[0] >= ctime) { + ctime = customer[0] + customer[1] + ans += (ctime - customer[0]) + } else { + ctime += customer[1] + ans += (ctime - customer[0]) + } + } + return Math.round(ans / customers.size * 100000.0) / 100000.0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1702_maximum_binary_string_after_change/readme.md b/src/main/kotlin/g1701_1800/s1702_maximum_binary_string_after_change/readme.md new file mode 100644 index 00000000..26d36606 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1702_maximum_binary_string_after_change/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) + +## 1702\. Maximum Binary String After Change + +Medium + +You are given a binary string `binary` consisting of only `0`'s or `1`'s. You can apply each of the following operations any number of times: + +* Operation 1: If the number contains the substring `"00"`, you can replace it with `"10"`. + * For example, `"00010" -> "10010`" +* Operation 2: If the number contains the substring `"10"`, you can replace it with `"01"`. + * For example, `"00010" -> "00001"` + +_Return the **maximum binary string** you can obtain after any number of operations. Binary string `x` is greater than binary string `y` if `x`'s decimal representation is greater than `y`'s decimal representation._ + +**Example 1:** + +**Input:** binary = "000110" + +**Output:** "111011" + +**Explanation:** A valid transformation sequence can be: + +"000110" -> "000101" + +"000101" -> "100101" + +"100101" -> "110101" + +"110101" -> "110011" + +"110011" -> "111011" + +**Example 2:** + +**Input:** binary = "01" + +**Output:** "01" + +**Explanation:** "01" cannot be transformed any further. + +**Constraints:** + +* 1 <= binary.length <= 105 +* `binary` consist of `'0'` and `'1'`. + +## Solution + +```kotlin +class Solution { + fun maximumBinaryString(binary: String): String { + val bs = binary.toCharArray() + var zcount = 0 + var pos = -1 + for (i in bs.indices.reversed()) { + if (bs[i] == '0') { + bs[i] = '1' + zcount++ + pos = i + } + } + if (pos >= 0) { + bs[pos + zcount - 1] = '0' + } + return String(bs) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1703_minimum_adjacent_swaps_for_k_consecutive_ones/readme.md b/src/main/kotlin/g1701_1800/s1703_minimum_adjacent_swaps_for_k_consecutive_ones/readme.md new file mode 100644 index 00000000..1fb1c207 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1703_minimum_adjacent_swaps_for_k_consecutive_ones/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) + +## 1703\. Minimum Adjacent Swaps for K Consecutive Ones + +Hard + +You are given an integer array, `nums`, and an integer `k`. `nums` comprises of only `0`'s and `1`'s. In one move, you can choose two **adjacent** indices and swap their values. + +Return _the **minimum** number of moves required so that_ `nums` _has_ `k` _**consecutive**_ `1`_'s_. + +**Example 1:** + +**Input:** nums = [1,0,0,1,0,1], k = 2 + +**Output:** 1 + +**Explanation:** In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's. + +**Example 2:** + +**Input:** nums = [1,0,0,0,0,0,1,1], k = 3 + +**Output:** 5 + +**Explanation:** In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1]. + +**Example 3:** + +**Input:** nums = [1,1,0,1], k = 2 + +**Output:** 0 + +**Explanation:** nums already has 2 consecutive 1's. + +**Constraints:** + +* 1 <= nums.length <= 105 +* `nums[i]` is `0` or `1`. +* `1 <= k <= sum(nums)` + +## Solution + +```kotlin +class Solution { + fun minMoves(nums: IntArray, k: Int): Int { + val len = nums.size + var cnt = 0 + var min = Long.MAX_VALUE + for (num in nums) { + if (num == 1) { + cnt++ + } + } + val arr = IntArray(cnt) + var idx = 0 + val sum = LongArray(cnt + 1) + for (i in 0 until len) { + if (nums[i] == 1) { + arr[idx++] = i + sum[idx] = sum[idx - 1] + i + } + } + var i = 0 + while (i + k - 1 < cnt) { + min = Math.min(min, getSum(arr, i, i + k - 1, sum)) + i++ + } + return min.toInt() + } + + private fun getSum(arr: IntArray, l: Int, h: Int, sum: LongArray): Long { + val mid = l + (h - l) / 2 + val k = h - l + 1 + val radius = mid - l + var res = sum[h + 1] - sum[mid + 1] - (sum[mid] - sum[l]) - (1 + radius) * radius + if (k % 2 == 0) { + res = res - arr[mid] - (radius + 1) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1704_determine_if_string_halves_are_alike/readme.md b/src/main/kotlin/g1701_1800/s1704_determine_if_string_halves_are_alike/readme.md new file mode 100644 index 00000000..74a93c36 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1704_determine_if_string_halves_are_alike/readme.md @@ -0,0 +1,59 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1704\. Determine if String Halves Are Alike + +Easy + +You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. + +Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. + +Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. + +**Example 1:** + +**Input:** s = "book" + +**Output:** true + +**Explanation:** a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike. + +**Example 2:** + +**Input:** s = "textbook" + +**Output:** false + +**Explanation:** a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. + +**Constraints:** + +* `2 <= s.length <= 1000` +* `s.length` is even. +* `s` consists of **uppercase and lowercase** letters. + +## Solution + +```kotlin +class Solution { + fun halvesAreAlike(s: String): Boolean { + return if (s.isEmpty()) { + false + } else countVowel(0, s.length / 2, s) == countVowel(s.length / 2, s.length, s) + } + + private fun countVowel(start: Int, end: Int, s: String): Int { + var c = 0 + for (i in start until end) { + val ch = s[i] + if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || + ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' + ) { + c++ + } + } + return c + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1705_maximum_number_of_eaten_apples/readme.md b/src/main/kotlin/g1701_1800/s1705_maximum_number_of_eaten_apples/readme.md new file mode 100644 index 00000000..3041e65a --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1705_maximum_number_of_eaten_apples/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) + +## 1705\. Maximum Number of Eaten Apples + +Medium + +There is a special kind of apple tree that grows apples every day for `n` days. On the ith day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`. + +You decided to eat **at most** one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days. + +Given two integer arrays `days` and `apples` of length `n`, return _the maximum number of apples you can eat._ + +**Example 1:** + +**Input:** apples = [1,2,3,5,2], days = [3,2,1,4,2] + +**Output:** 7 + +**Explanation:** You can eat 7 apples: + +- On the first day, you eat an apple that grew on the first day. + +- On the second day, you eat an apple that grew on the second day. + +- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. + +- On the fourth to the seventh days, you eat apples that grew on the fourth day. + +**Example 2:** + +**Input:** apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2] + +**Output:** 5 + +**Explanation:** You can eat 5 apples: + +- On the first to the third day you eat apples that grew on the first day. + +- Do nothing on the fouth and fifth days. + +- On the sixth and seventh days you eat apples that grew on the sixth day. + +**Constraints:** + +* `n == apples.length == days.length` +* 1 <= n <= 2 * 104 +* 0 <= apples[i], days[i] <= 2 * 104 +* `days[i] = 0` if and only if `apples[i] = 0`. + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + fun eatenApples(apples: IntArray, days: IntArray): Int { + val minHeap = PriorityQueue { a: IntArray, b: IntArray -> a[0] - b[0] } + var eatenApples = 0 + var i = 0 + while (i < apples.size || minHeap.isNotEmpty()) { + if (i < apples.size) { + minHeap.offer(intArrayOf(i + days[i], apples[i])) + } + while (minHeap.isNotEmpty() && (minHeap.peek()[0] <= i || minHeap.peek()[1] <= 0)) { + minHeap.poll() + } + if (minHeap.isNotEmpty()) { + eatenApples++ + minHeap.peek()[1]-- + } + i++ + } + return eatenApples + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1706_where_will_the_ball_fall/readme.md b/src/main/kotlin/g1701_1800/s1706_where_will_the_ball_fall/readme.md new file mode 100644 index 00000000..80d6e9a0 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1706_where_will_the_ball_fall/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) + +## 1706\. Where Will the Ball Fall + +Medium + +You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. + +Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. + +* A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. +* A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. + +We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V" shaped pattern between two boards or if a board redirects the ball into either wall of the box. + +Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ ith _column at the top, or `-1` _if the ball gets stuck in the box_._ + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2019/09/26/ball.jpg)** + +**Input:** grid = \[\[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]] + +**Output:** [1,-1,-1,-1,-1] + +**Explanation:** This example is shown in the photo. + +Ball b0 is dropped at column 0 and falls out of the box at column 1. + +Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. + +Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. + +Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. + +Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. + +**Example 2:** + +**Input:** grid = \[\[-1]] + +**Output:** [-1] + +**Explanation:** The ball gets stuck against the left wall. + +**Example 3:** + +**Input:** grid = \[\[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]] + +**Output:** [0,1,2,3,4,-1] + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `1 <= m, n <= 100` +* `grid[i][j]` is `1` or `-1`. + +## Solution + +```kotlin +class Solution { + fun findBall(grid: Array): IntArray { + val m = grid.size + val n = grid[0].size + val res = IntArray(n) + for (j in 0 until n) { + var currentJ = j + var currentI = 0 + while (currentJ < n && currentI < m) { + if (grid[currentI][currentJ] == 1) { + currentJ++ + if (currentJ < n && grid[currentI][currentJ] == 1) { + currentI++ + } else { + break + } + } else { + currentJ-- + if (currentJ >= 0 && grid[currentI][currentJ] == -1) { + currentI++ + } else { + break + } + } + } + if (currentI == m) { + res[j] = currentJ + } else { + res[j] = -1 + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1707_maximum_xor_with_an_element_from_array/readme.md b/src/main/kotlin/g1701_1800/s1707_maximum_xor_with_an_element_from_array/readme.md new file mode 100644 index 00000000..a654c7ff --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1707_maximum_xor_with_an_element_from_array/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) + +## 1707\. Maximum XOR With an Element From Array + +Hard + +You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where queries[i] = [xi, mi]. + +The answer to the ith query is the maximum bitwise `XOR` value of xi and any element of `nums` that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all `j` such that nums[j] <= mi. If all elements in `nums` are larger than mi, then the answer is `-1`. + +Return _an integer array_ `answer` _where_ `answer.length == queries.length` _and_ `answer[i]` _is the answer to the_ ith _query._ + +**Example 1:** + +**Input:** nums = [0,1,2,3,4], queries = \[\[3,1],[1,3],[5,6]] + +**Output:** [3,3,7] + +**Explanation:** + +1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3. + +2) 1 XOR 2 = 3. + +3) 5 XOR 2 = 7. + +**Example 2:** + +**Input:** nums = [5,2,4,6,6,3], queries = \[\[12,4],[8,1],[6,3]] + +**Output:** [15,-1,5] + +**Constraints:** + +* 1 <= nums.length, queries.length <= 105 +* `queries[i].length == 2` +* 0 <= nums[j], xi, mi <= 109 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + internal class QueryComparator : Comparator { + override fun compare(a: IntArray, b: IntArray): Int { + return a[1].compareTo(b[1]) + } + } + + internal class Node { + var zero: Node? = null + var one: Node? = null + } + + fun maximizeXor(nums: IntArray, queries: Array): IntArray { + nums.sort() + val len = queries.size + val queryWithIndex = Array(len) { IntArray(3) } + for (i in 0 until len) { + queryWithIndex[i][0] = queries[i][0] + queryWithIndex[i][1] = queries[i][1] + queryWithIndex[i][2] = i + } + queryWithIndex.sortWith(QueryComparator()) + var numId = 0 + val ans = IntArray(len) + val root = Node() + for (i in 0 until len) { + while (numId < nums.size && nums[numId] <= queryWithIndex[i][1]) { + addNumToTree(nums[numId], root) + numId++ + } + ans[queryWithIndex[i][2]] = maxXOR(queryWithIndex[i][0], root) + } + return ans + } + + private fun addNumToTree(num: Int, node: Node) { + var node: Node? = node + for (i in 31 downTo 0) { + val digit = num shr i and 1 + if (digit == 1) { + if (node!!.one == null) { + node.one = Node() + } + node = node.one + } else { + if (node!!.zero == null) { + node.zero = Node() + } + node = node.zero + } + } + } + + private fun maxXOR(num: Int, node: Node): Int { + var node: Node? = node + if (node!!.one == null && node.zero == null) { + return -1 + } + var ans = 0 + var i = 31 + while (i >= 0 && node != null) { + val digit = num shr i and 1 + if (digit == 1) { + if (node.zero != null) { + ans += 1 shl i + node = node.zero + } else { + node = node.one + } + } else { + if (node.one != null) { + ans += 1 shl i + node = node.one + } else { + node = node.zero + } + } + i-- + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1710_maximum_units_on_a_truck/readme.md b/src/main/kotlin/g1701_1800/s1710_maximum_units_on_a_truck/readme.md new file mode 100644 index 00000000..2017e5d6 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1710_maximum_units_on_a_truck/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) + +## 1710\. Maximum Units on a Truck + +Easy + +You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]: + +* numberOfBoxesi is the number of boxes of type `i`. +* numberOfUnitsPerBoxi is the number of units in each box of the type `i`. + +You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. + +Return _the **maximum** total number of **units** that can be put on the truck._ + +**Example 1:** + +**Input:** boxTypes = \[\[1,3],[2,2],[3,1]], truckSize = 4 + +**Output:** 8 + +**Explanation:** There are: + +- 1 box of the first type that contains 3 units. + +- 2 boxes of the second type that contain 2 units each. + +- 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8. + +**Example 2:** + +**Input:** boxTypes = \[\[5,10],[2,5],[4,7],[3,9]], truckSize = 10 + +**Output:** 91 + +**Constraints:** + +* `1 <= boxTypes.length <= 1000` +* 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000 +* 1 <= truckSize <= 106 + +## Solution + +```kotlin +import java.util.Arrays + +@Suppress("NAME_SHADOWING") +class Solution { + fun maximumUnits(boxTypes: Array, truckSize: Int): Int { + var truckSize = truckSize + Arrays.sort(boxTypes) { b1: IntArray, b2: IntArray -> Integer.compare(b2[1], b1[1]) } + var maxUnits = 0 + var i = 0 + while (truckSize > 0 && i < boxTypes.size) { + if (boxTypes[i][0] <= truckSize) { + maxUnits += boxTypes[i][0] * boxTypes[i][1] + truckSize -= boxTypes[i][0] + } else { + maxUnits += Math.min(truckSize, boxTypes[i][0]) * boxTypes[i][1] + truckSize -= Math.min(truckSize, boxTypes[i][0]) + } + i++ + } + return maxUnits + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1711_count_good_meals/readme.md b/src/main/kotlin/g1701_1800/s1711_count_good_meals/readme.md new file mode 100644 index 00000000..9c2147ff --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1711_count_good_meals/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) + +## 1711\. Count Good Meals + +Medium + +A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. + +You can pick **any** two different foods to make a good meal. + +Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the ith item of food, return _the number of different **good meals** you can make from this list modulo_ 109 + 7. + +Note that items with different indices are considered different even if they have the same deliciousness value. + +**Example 1:** + +**Input:** deliciousness = [1,3,5,7,9] + +**Output:** 4 + +**Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. + +**Example 2:** + +**Input:** deliciousness = [1,1,1,3,3,3,7] + +**Output:** 15 + +**Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. + +**Constraints:** + +* 1 <= deliciousness.length <= 105 +* 0 <= deliciousness[i] <= 220 + +## Solution + +```kotlin +class Solution { + fun countPairs(deliciousness: IntArray): Int { + val map = HashMap() + for (k in deliciousness) { + map[k] = map.getOrDefault(k, 0) + 1 + } + var result: Long = 0 + val it: MutableIterator> = map.entries.iterator() + while (it.hasNext()) { + val (key, value1) = it.next() + val value = value1.toLong() + for (j in 21 downTo 0) { + val find = (1 shl j) - key + if (find < 0) { + break + } + if (map.containsKey(find)) { + result += if (find == key) { + (value - 1) * value / 2 + } else { + value * map[find]!! + } + } + } + it.remove() + } + val mod = 1000000007 + return (result % mod).toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1712_ways_to_split_array_into_three_subarrays/readme.md b/src/main/kotlin/g1701_1800/s1712_ways_to_split_array_into_three_subarrays/readme.md new file mode 100644 index 00000000..c02a4117 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1712_ways_to_split_array_into_three_subarrays/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) + +## 1712\. Ways to Split Array Into Three Subarrays + +Medium + +A split of an integer array is **good** if: + +* The array is split into three **non-empty** contiguous subarrays - named `left`, `mid`, `right` respectively from left to right. +* The sum of the elements in `left` is less than or equal to the sum of the elements in `mid`, and the sum of the elements in `mid` is less than or equal to the sum of the elements in `right`. + +Given `nums`, an array of **non-negative** integers, return _the number of **good** ways to split_ `nums`. As the number may be too large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** nums = [1,1,1] + +**Output:** 1 + +**Explanation:** The only good way to split nums is [1] [1] [1]. + +**Example 2:** + +**Input:** nums = [1,2,2,2,5,0] + +**Output:** 3 + +**Explanation:** There are three good ways of splitting nums: + +[1] [2] [2,2,5,0] + +[1] [2,2] [2,5,0] + +[1,2] [2,2] [5,0] + +**Example 3:** + +**Input:** nums = [3,2,1] + +**Output:** 0 + +**Explanation:** There is no good way to split nums. + +**Constraints:** + +* 3 <= nums.length <= 105 +* 0 <= nums[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun waysToSplit(nums: IntArray): Int { + var sum = 0 + for (num in nums) { + sum += num + } + var cur = 0 + var res: Long = 0 + var i = 0 + var idx1 = 1 + var sum1 = nums[0] + var idx2 = 1 + var sum2 = nums[0] + while (i < nums.size) { + cur += nums[i] + val right = sum - cur + if (i == 0 || i == nums.size - 1) { + i++ + continue + } + while (idx1 <= i && sum1 <= cur - sum1) { + sum1 += nums[idx1++] + } + while (idx2 < idx1 && cur - sum2 > right) { + sum2 += nums[idx2++] + } + if (idx1 > idx2) { + res = (res + idx1 - idx2) % 1000000007 + } + i++ + } + return res.toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1713_minimum_operations_to_make_a_subsequence/readme.md b/src/main/kotlin/g1701_1800/s1713_minimum_operations_to_make_a_subsequence/readme.md new file mode 100644 index 00000000..b0b330ed --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1713_minimum_operations_to_make_a_subsequence/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) + +## 1713\. Minimum Operations to Make a Subsequence + +Hard + +You are given an array `target` that consists of **distinct** integers and another integer array `arr` that **can** have duplicates. + +In one operation, you can insert any integer at any position in `arr`. For example, if `arr = [1,4,1,2]`, you can add `3` in the middle and make it `[1,4,3,1,2]`. Note that you can insert the integer at the very beginning or end of the array. + +Return _the **minimum** number of operations needed to make_ `target` _a **subsequence** of_ `arr`_._ + +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:** target = [5,1,3], `arr` = [9,4,2,3,4] + +**Output:** 2 + +**Explanation:** You can add 5 and 1 in such a way that makes `arr` = [5,9,4,1,2,3,4], then target will be a subsequence of `arr`. + +**Example 2:** + +**Input:** target = [6,4,8,1,3,2], `arr` = [4,7,6,2,3,8,6,1] + +**Output:** 3 + +**Constraints:** + +* 1 <= target.length, arr.length <= 105 +* 1 <= target[i], arr[i] <= 109 +* `target` contains no duplicates. + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun minOperations(target: IntArray, arr: IntArray): Int { + val map: MutableMap = HashMap() + for (i in target.indices) { + map[target[i]] = i + } + val list: MutableList = ArrayList() + for (num in arr) { + if (map.containsKey(num)) { + list.add(map[num]) + } + } + return target.size - longestIncreasingSubsequence(list) + } + + private fun longestIncreasingSubsequence(list: MutableList): Int { + val n = list.size + var l = 0 + val arr = IntArray(n) + for (num in list) { + var index = Arrays.binarySearch(arr, 0, l, num!!) + if (index < 0) { + index = index.inv() + } + arr[index] = num + if (index == l) { + l++ + } + } + return l + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1716_calculate_money_in_leetcode_bank/readme.md b/src/main/kotlin/g1701_1800/s1716_calculate_money_in_leetcode_bank/readme.md new file mode 100644 index 00000000..9b98c061 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1716_calculate_money_in_leetcode_bank/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) + +## 1716\. Calculate Money in Leetcode Bank + +Easy + +Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. + +He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. + +Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ nth _day._ + +**Example 1:** + +**Input:** n = 4 + +**Output:** 10 + +**Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. + +**Example 2:** + +**Input:** n = 10 + +**Output:** 37 + +**Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. + +**Example 3:** + +**Input:** n = 20 + +**Output:** 96 + +**Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. + +**Constraints:** + +* `1 <= n <= 1000` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun totalMoney(n: Int): Int { + var n = n + var mondayMoney = 1 + var total = 0 + while (n > 0) { + var weekDays = 0 + var base = mondayMoney + while (weekDays < 7 && n > 0) { + total += base + base++ + weekDays++ + n-- + } + mondayMoney++ + } + return total + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1717_maximum_score_from_removing_substrings/readme.md b/src/main/kotlin/g1701_1800/s1717_maximum_score_from_removing_substrings/readme.md new file mode 100644 index 00000000..8527fbbb --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1717_maximum_score_from_removing_substrings/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) + +## 1717\. Maximum Score From Removing Substrings + +Medium + +You are given a string `s` and two integers `x` and `y`. You can perform two types of operations any number of times. + +* Remove substring `"ab"` and gain `x` points. + * For example, when removing `"ab"` from `"cabxbae"` it becomes `"cxbae"`. +* Remove substring `"ba"` and gain `y` points. + * For example, when removing `"ba"` from `"cabxbae"` it becomes `"cabxe"`. + +Return _the maximum points you can gain after applying the above operations on_ `s`. + +**Example 1:** + +**Input:** s = "cdbcbbaaabab", x = 4, y = 5 + +**Output:** 19 + +**Explanation:** + +- Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score. + +- Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score. + +- Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score. - Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score. Total score = 5 + 4 + 5 + 5 = 19. + +**Example 2:** + +**Input:** s = "aabbaaxybbaabb", x = 5, y = 4 + +**Output:** 20 + +**Constraints:** + +* 1 <= s.length <= 105 +* 1 <= x, y <= 104 +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun maximumGain(s: String, x: Int, y: Int): Int { + val v = s.toCharArray() + return if (x > y) { + helper(v, 'a', 'b', x) + helper(v, 'b', 'a', y) + } else { + helper(v, 'b', 'a', y) + helper(v, 'a', 'b', x) + } + } + + private fun helper(v: CharArray, c1: Char, c2: Char, score: Int): Int { + var left = -1 + var right = 0 + var res = 0 + while (right < v.size) { + if (v[right] != c2) { + left = right + } else { + while (left >= 0) { + val cl = v[left] + if (cl == '#') { + left-- + } else if (cl == c1) { + res += score + v[left] = '#' + v[right] = '#' + left-- + break + } else { + break + } + } + } + right++ + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1718_construct_the_lexicographically_largest_valid_sequence/readme.md b/src/main/kotlin/g1701_1800/s1718_construct_the_lexicographically_largest_valid_sequence/readme.md new file mode 100644 index 00000000..769453ea --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1718_construct_the_lexicographically_largest_valid_sequence/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) + +## 1718\. Construct the Lexicographically Largest Valid Sequence + +Medium + +Given an integer `n`, find a sequence that satisfies all of the following: + +* The integer `1` occurs once in the sequence. +* Each integer between `2` and `n` occurs twice in the sequence. +* For every integer `i` between `2` and `n`, the **distance** between the two occurrences of `i` is exactly `i`. + +The **distance** between two numbers on the sequence, `a[i]` and `a[j]`, is the absolute difference of their indices, `|j - i|`. + +Return _the **lexicographically largest** sequence__. It is guaranteed that under the given constraints, there is always a solution._ + +A sequence `a` is lexicographically larger than a sequence `b` (of the same length) if in the first position where `a` and `b` differ, sequence `a` has a number greater than the corresponding number in `b`. For example, `[0,1,9,0]` is lexicographically larger than `[0,1,5,6]` because the first position they differ is at the third number, and `9` is greater than `5`. + +**Example 1:** + +**Input:** n = 3 + +**Output:** [3,1,2,3,2] + +**Explanation:** [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence. + +**Example 2:** + +**Input:** n = 5 + +**Output:** [5,3,1,4,3,5,2,4,2] + +**Constraints:** + +* `1 <= n <= 20` + +## Solution + +```kotlin +class Solution { + fun constructDistancedSequence(n: Int): IntArray { + val result = IntArray(n * 2 - 1) + val visited = BooleanArray(n + 1) + backtracking(0, result, visited, n) + return result + } + + private fun backtracking(index: Int, result: IntArray, visited: BooleanArray, n: Int): Boolean { + if (index == result.size) { + return true + } + if (result[index] != 0) { + return backtracking(index + 1, result, visited, n) + } else { + for (i in n downTo 1) { + if (visited[i]) { + continue + } + visited[i] = true + result[index] = i + if (i == 1) { + if (backtracking(index + 1, result, visited, n)) { + return true + } + } else if (index + i < result.size && result[index + i] == 0) { + result[i + index] = i + if (backtracking(index + 1, result, visited, n)) { + return true + } + result[index + i] = 0 + } + result[index] = 0 + visited[i] = false + } + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1719_number_of_ways_to_reconstruct_a_tree/readme.md b/src/main/kotlin/g1701_1800/s1719_number_of_ways_to_reconstruct_a_tree/readme.md new file mode 100644 index 00000000..c3ac55d3 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1719_number_of_ways_to_reconstruct_a_tree/readme.md @@ -0,0 +1,168 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1719\. Number Of Ways To Reconstruct A Tree + +Hard + +You are given an array `pairs`, where pairs[i] = [xi, yi], and: + +* There are no duplicates. +* xi < yi + +Let `ways` be the number of rooted trees that satisfy the following conditions: + +* The tree consists of nodes whose values appeared in `pairs`. +* A pair [xi, yi] exists in `pairs` **if and only if** xi is an ancestor of yi or yi is an ancestor of xi. +* **Note:** the tree does not have to be a binary tree. + +Two ways are considered to be different if there is at least one node that has different parents in both ways. + +Return: + +* `0` if `ways == 0` +* `1` if `ways == 1` +* `2` if `ways > 1` + +A **rooted tree** is a tree that has a single root node, and all edges are oriented to be outgoing from the root. + +An **ancestor** of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/12/03/trees2.png) + +**Input:** pairs = \[\[1,2],[2,3]] + +**Output:** 1 + +**Explanation:** There is exactly one valid rooted tree, which is shown in the above figure. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/12/03/tree.png) + +**Input:** pairs = \[\[1,2],[2,3],[1,3]] + +**Output:** 2 + +**Explanation:** There are multiple valid rooted trees. Three of them are shown in the above figures. + +**Example 3:** + +**Input:** pairs = \[\[1,2],[2,3],[2,4],[1,5]] + +**Output:** 0 + +**Explanation:** There are no valid rooted trees. + +**Constraints:** + +* 1 <= pairs.length <= 105 +* 1 <= xi < yi <= 500 +* The elements in `pairs` are unique. + +## Solution + +```kotlin +class Solution { + fun checkWays(pairs: Array): Int { + val adj = Array(501) { IntArray(501) } + val set = HashSet() + for (pair in pairs) { + adj[pair[0]][pair[1]]++ + adj[pair[1]][pair[0]]++ + set.add(pair[0]) + set.add(pair[1]) + } + val n = set.size + val num = IntArray(501) + for (i in 0..500) { + for (j in 0..500) { + num[i] += adj[i][j] + } + } + var c = 0 + for (i in 0..500) { + if (num[i] == n - 1) { + c++ + } + } + for (j in 0..500) { + if (num[j] == n - 1) { + num[j] = 0 + for (k in 0..500) { + if (adj[j][k] > 0) { + adj[j][k] = 0 + adj[k][j] = 0 + num[k]-- + } + } + set.remove(j) + break + } + if (j == 500) { + return 0 + } + } + val res = search(adj, num, set) + return if (res == 1 && c > 1) { + 2 + } else res + } + + private fun search(adj: Array, num: IntArray, vals: HashSet): Int { + if (vals.isEmpty()) { + return 1 + } + var max = 0 + for (i in vals) { + if (num[i] > num[max]) { + max = i + } + } + val size = num[max] + if (size == 0) { + return 1 + } + var c = false + i@ for (i in vals) { + if (num[i] == num[max]) { + for (j in vals) { + if (j != i && num[j] == num[i] && adj[i][j] > 0) { + c = true + break@i + } + } + } + } + val set = HashSet() + for (j in 0..500) { + if (adj[max][j] > 0 && !vals.contains(j)) { + return 0 + } + if (adj[max][j] > 0) { + adj[max][j] = 0 + adj[j][max] = 0 + num[j]-- + set.add(j) + } + } + num[max] = 0 + val set2 = HashSet() + for (i in vals) { + if (!set.contains(i) && i != max) { + set2.add(i) + } + } + val res1 = search(adj, num, set) + val res2 = search(adj, num, set2) + if (res1 == 0 || res2 == 0) { + return 0 + } + return if (res1 == 2 || res2 == 2 || c) { + 2 + } else 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1720_decode_xored_array/readme.md b/src/main/kotlin/g1701_1800/s1720_decode_xored_array/readme.md new file mode 100644 index 00000000..e47b3f95 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1720_decode_xored_array/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) + +## 1720\. Decode XORed Array + +Easy + +There is a **hidden** integer array `arr` that consists of `n` non-negative integers. + +It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`. + +You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`. + +Return _the original array_ `arr`. It can be proved that the answer exists and is unique. + +**Example 1:** + +**Input:** encoded = [1,2,3], first = 1 + +**Output:** [1,0,2,1] + +**Explanation:** If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3] + +**Example 2:** + +**Input:** encoded = [6,2,7,3], first = 4 + +**Output:** [4,2,0,7,4] + +**Constraints:** + +* 2 <= n <= 104 +* `encoded.length == n - 1` +* 0 <= encoded[i] <= 105 +* 0 <= first <= 105 + +## Solution + +```kotlin +class Solution { + fun decode(encoded: IntArray, first: Int): IntArray { + val arr = IntArray(encoded.size + 1) + arr[0] = first + for (i in encoded.indices) { + arr[i + 1] = encoded[i] xor arr[i] + } + return arr + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1721_swapping_nodes_in_a_linked_list/readme.md b/src/main/kotlin/g1701_1800/s1721_swapping_nodes_in_a_linked_list/readme.md new file mode 100644 index 00000000..052ead96 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1721_swapping_nodes_in_a_linked_list/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) + +## 1721\. Swapping Nodes in a Linked List + +Medium + +You are given the `head` of a linked list, and an integer `k`. + +Return _the head of the linked list after **swapping** the values of the_ kth _node from the beginning and the_ kth _node from the end (the list is **1-indexed**)._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg) + +**Input:** head = [1,2,3,4,5], k = 2 + +**Output:** [1,4,3,2,5] + +**Example 2:** + +**Input:** head = [7,9,6,6,7,8,3,0,9,5], k = 5 + +**Output:** [7,9,6,6,8,7,3,0,9,5] + +**Constraints:** + +* The number of nodes in the list is `n`. +* 1 <= k <= n <= 105 +* `0 <= Node.val <= 100` + +## Solution + +```kotlin +import com_github_leetcode.ListNode + +/* + * Example: + * var li = ListNode(5) + * var v = li.`val` + * Definition for singly-linked list. + * class ListNode(var `val`: Int) { + * var next: ListNode? = null + * } + */ +@Suppress("NAME_SHADOWING") +class Solution { + fun swapNodes(head: ListNode?, k: Int): ListNode? { + var k: Int = k + var beg: ListNode? = null + var end: ListNode? = null + var node = head + while (node != null) { + k-- + if (k == 0) { + beg = node + end = head + } else if (end != null) { + end = end.next + } + node = node.next + } + if (beg != null) { + val tem = beg.`val` + beg.`val` = end!!.`val` + end.`val` = tem + } + return head + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1722_minimize_hamming_distance_after_swap_operations/readme.md b/src/main/kotlin/g1701_1800/s1722_minimize_hamming_distance_after_swap_operations/readme.md new file mode 100644 index 00000000..5d02bbdd --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1722_minimize_hamming_distance_after_swap_operations/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) + +## 1722\. Minimize Hamming Distance After Swap Operations + +Medium + +You are given two integer arrays, `source` and `target`, both of length `n`. You are also given an array `allowedSwaps` where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi **(0-indexed)** of array `source`. Note that you can swap elements at a specific pair of indices **multiple** times and in **any** order. + +The **Hamming distance** of two arrays of the same length, `source` and `target`, is the number of positions where the elements are different. Formally, it is the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]` **(0-indexed)**. + +Return _the **minimum Hamming distance** of_ `source` _and_ `target` _after performing **any** amount of swap operations on array_ `source`_._ + +**Example 1:** + +**Input:** source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = \[\[0,1],[2,3]] + +**Output:** 1 + +**Explanation:** source can be transformed the following way: + +- Swap indices 0 and 1: source = [2,1,3,4] + +- Swap indices 2 and 3: source = [2,1,4,3] + +The Hamming distance of source and target is 1 as they differ in 1 position: index 3. + +**Example 2:** + +**Input:** source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = [] + +**Output:** 2 + +**Explanation:** There are no allowed swaps. The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2. + +**Example 3:** + +**Input:** source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = \[\[0,4],[4,2],[1,3],[1,4]] + +**Output:** 0 + +**Constraints:** + +* `n == source.length == target.length` +* 1 <= n <= 105 +* 1 <= source[i], target[i] <= 105 +* 0 <= allowedSwaps.length <= 105 +* `allowedSwaps[i].length == 2` +* 0 <= ai, bi <= n - 1 +* ai != bi + +## Solution + +```kotlin +class Solution { + fun minimumHammingDistance(source: IntArray, target: IntArray, allowedSwaps: Array): Int { + var i: Int + val n = source.size + var weight = 0 + val parent = IntArray(n) + i = 0 + while (i < n) { + parent[i] = i + i++ + } + for (swap in allowedSwaps) { + union(swap[0], swap[1], parent) + } + val components = HashMap>() + i = 0 + while (i < n) { + find(i, parent) + val list = components.getOrDefault(parent[i], ArrayList()) + list.add(i) + components[parent[i]] = list + i++ + } + for ((_, value) in components) { + weight += getHammingDistance(source, target, value) + } + return weight + } + + private fun getHammingDistance(source: IntArray, target: IntArray, indices: List): Int { + val list1 = HashMap() + val list2 = HashMap() + for (i in indices) { + list1[target[i]] = 1 + list1.getOrDefault(target[i], 0) + list2[source[i]] = 1 + list2.getOrDefault(source[i], 0) + } + var size = indices.size + for ((key, value) in list1) { + size -= Math.min(value, list2.getOrDefault(key, 0)) + } + return size + } + + private fun union(x: Int, y: Int, parent: IntArray) { + if (x != y) { + val a = find(x, parent) + val b = find(y, parent) + if (a != b) { + parent[a] = b + } + } + } + + private fun find(x: Int, parent: IntArray): Int { + var y = x + while (y != parent[y]) { + y = parent[y] + } + parent[x] = y + return y + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1723_find_minimum_time_to_finish_all_jobs/readme.md b/src/main/kotlin/g1701_1800/s1723_find_minimum_time_to_finish_all_jobs/readme.md new file mode 100644 index 00000000..9fe9abb7 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1723_find_minimum_time_to_finish_all_jobs/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) + +## 1723\. Find Minimum Time to Finish All Jobs + +Hard + +You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the ith job. + +There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**. + +_Return the **minimum** possible **maximum working time** of any assignment._ + +**Example 1:** + +**Input:** jobs = [3,2,3], k = 3 + +**Output:** 3 + +**Explanation:** By assigning each person one job, the maximum time is 3. + +**Example 2:** + +**Input:** jobs = [1,2,4,7,8], k = 2 + +**Output:** 11 + +**Explanation:** Assign the jobs the following way: + +Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) + +Worker 2: 4, 7 (working time = 4 + 7 = 11) + +The maximum working time is 11. + +**Constraints:** + +* `1 <= k <= jobs.length <= 12` +* 1 <= jobs[i] <= 107 + +## Solution + +```kotlin +class Solution { + private var min = Int.MAX_VALUE + + fun minimumTimeRequired(jobs: IntArray, k: Int): Int { + backtraking(jobs, jobs.size - 1, IntArray(k)) + return min + } + + private fun backtraking(jobs: IntArray, j: Int, sum: IntArray) { + val max = getMax(sum) + if (max >= min) { + return + } + if (j < 0) { + min = max + return + } + for (i in sum.indices) { + if (i > 0 && sum[i] == sum[i - 1]) { + continue + } + sum[i] += jobs[j] + backtraking(jobs, j - 1, sum) + sum[i] -= jobs[j] + } + } + + private fun getMax(sum: IntArray): Int { + var max = Int.MIN_VALUE + for (j in sum) { + max = Math.max(max, j) + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1725_number_of_rectangles_that_can_form_the_largest_square/readme.md b/src/main/kotlin/g1701_1800/s1725_number_of_rectangles_that_can_form_the_largest_square/readme.md new file mode 100644 index 00000000..c2310558 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1725_number_of_rectangles_that_can_form_the_largest_square/readme.md @@ -0,0 +1,58 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1725\. Number Of Rectangles That Can Form The Largest Square + +Easy + +You are given an array `rectangles` where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi. + +You can cut the ith rectangle to form a square with a side length of `k` if both k <= li and k <= wi. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`. + +Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles. + +Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`. + +**Example 1:** + +**Input:** rectangles = \[\[5,8],[3,9],[5,12],[16,5]] + +**Output:** 3 + +**Explanation:** The largest squares you can get from each rectangle are of lengths [5,3,5,5]. The largest possible square is of length 5, and you can get it out of 3 rectangles. + +**Example 2:** + +**Input:** rectangles = \[\[2,3],[3,7],[4,3],[3,7]] + +**Output:** 3 + +**Constraints:** + +* `1 <= rectangles.length <= 1000` +* `rectangles[i].length == 2` +* 1 <= li, wi <= 109 +* li != wi + +## Solution + +```kotlin +class Solution { + fun countGoodRectangles(rectangles: Array): Int { + var maxSoFar = 0 + var count = 0 + for (rectangle in rectangles) { + val sqLen = Math.min(rectangle[0], rectangle[1]) + if (maxSoFar <= sqLen) { + if (maxSoFar < sqLen) { + maxSoFar = sqLen + count = 1 + } else { + count++ + } + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1726_tuple_with_same_product/readme.md b/src/main/kotlin/g1701_1800/s1726_tuple_with_same_product/readme.md new file mode 100644 index 00000000..d37f32bd --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1726_tuple_with_same_product/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) + +## 1726\. Tuple with Same Product + +Medium + +Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._ + +**Example 1:** + +**Input:** nums = [2,3,4,6] + +**Output:** 8 + +**Explanation:** There are 8 valid tuples: + +(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3) + +(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2) + +**Example 2:** + +**Input:** nums = [1,2,4,5,10] + +**Output:** 16 + +**Explanation:** There are 16 valid tuples: + +(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2) + +(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1) + +(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4) + +(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2) + +**Constraints:** + +* `1 <= nums.length <= 1000` +* 1 <= nums[i] <= 104 +* All elements in `nums` are **distinct**. + +## Solution + +```kotlin +class Solution { + fun tupleSameProduct(nums: IntArray): Int { + val ab = HashMap() + for (i in nums.indices) { + for (j in i + 1 until nums.size) { + ab[nums[i] * nums[j]] = ab.getOrDefault(nums[i] * nums[j], 0) + 1 + } + } + var count = 0 + for (entry: Map.Entry in ab.entries) { + val `val`: Int = entry.value + count += `val` * (`val` - 1) / 2 + } + return count * 8 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1727_largest_submatrix_with_rearrangements/readme.md b/src/main/kotlin/g1701_1800/s1727_largest_submatrix_with_rearrangements/readme.md new file mode 100644 index 00000000..7b61389f --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1727_largest_submatrix_with_rearrangements/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) + +## 1727\. Largest Submatrix With Rearrangements + +Medium + +You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order. + +Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40536-pm.png) + +**Input:** matrix = \[\[0,0,1],[1,1,1],[1,0,1]] + +**Output:** 4 + +**Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 4. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40852-pm.png) + +**Input:** matrix = \[\[1,0,1,0,1]] + +**Output:** 3 + +**Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 3. + +**Example 3:** + +**Input:** matrix = \[\[1,1,0],[1,0,1]] + +**Output:** 2 + +**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2. + +**Constraints:** + +* `m == matrix.length` +* `n == matrix[i].length` +* 1 <= m * n <= 105 +* `matrix[i][j]` is either `0` or `1`. + +## Solution + +```kotlin +class Solution { + fun largestSubmatrix(matrix: Array): Int { + val m: Int = matrix.size + val n: Int = matrix[0].size + for (i in 1 until m) { + for (j in 0 until n) { + if (matrix[i][j] != 0) { + matrix[i][j] = matrix[i - 1][j] + 1 + } + } + } + var count = 0 + for (ints: IntArray in matrix) { + ints.sort() + for (j in 1..n) { + count = Math.max(count, j * ints[n - j]) + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1728_cat_and_mouse_ii/readme.md b/src/main/kotlin/g1701_1800/s1728_cat_and_mouse_ii/readme.md new file mode 100644 index 00000000..a6867954 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1728_cat_and_mouse_ii/readme.md @@ -0,0 +1,162 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1728\. Cat and Mouse II + +Hard + +A game is played by a cat and a mouse named Cat and Mouse. + +The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food. + +* Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse). +* Floors are represented by the character `'.'` and can be walked on. +* Walls are represented by the character `'#'` and cannot be walked on. +* Food is represented by the character `'F'` and can be walked on. +* There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. + +Mouse and Cat play according to the following rules: + +* Mouse **moves first**, then they take turns to move. +* During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`. +* `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length. +* Staying in the same position is allowed. +* Mouse can jump over Cat. + +The game can end in 4 ways: + +* If Cat occupies the same position as Mouse, Cat wins. +* If Cat reaches the food first, Cat wins. +* If Mouse reaches the food first, Mouse wins. +* If Mouse cannot get to the food within 1000 turns, Cat wins. + +Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/12/sample_111_1955.png) + +**Input:** grid = ["####F","#C...","M...."], catJump = 1, mouseJump = 2 + +**Output:** true + +**Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/09/12/sample_2_1955.png) + +**Input:** grid = ["M.C...F"], catJump = 1, mouseJump = 4 + +**Output:** true + +**Example 3:** + +**Input:** grid = ["M.C...F"], catJump = 1, mouseJump = 3 + +**Output:** false + +**Constraints:** + +* `rows == grid.length` +* `cols = grid[i].length` +* `1 <= rows, cols <= 8` +* `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`. +* There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. +* `1 <= catJump, mouseJump <= 8` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + private val graphs: Array>> = arrayOf(arrayOf(), arrayOf()) + private var foodPos = 0 + private lateinit var memo: Array> + + fun canMouseWin(grid: Array, catJump: Int, mouseJump: Int): Boolean { + val m = grid.size + val n = grid[0].length + var mousePos = 0 + var catPos = 0 + for (i in 0 until m) { + for (j in 0 until n) { + val c = grid[i][j] + if (c == 'F') { + foodPos = i * n + j + } else if (c == 'C') { + catPos = i * n + j + } else if (c == 'M') { + mousePos = i * n + j + } + } + } + graphs[0] = buildGraph(mouseJump, grid) + graphs[1] = buildGraph(catJump, grid) + memo = Array(m * n) { Array(m * n) { IntArray(2) } } + for (i in 0 until m) { + for (j in 0 until n) { + val c = grid[i][j] + if (c == '#' || c == 'F') { + continue + } + val catTurn = 1 + dfs(i * n + j, foodPos, catTurn) + } + } + return memo[mousePos][catPos][MOUSE_TURN] < 0 + } + + private fun buildGraph(jump: Int, grid: Array): Array> { + val dirs = arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(0, -1)) + val m = grid.size + val n = grid[0].length + val graph: Array> = Array(m * n) { mutableListOf() } + for (i in 0 until m) { + for (j in 0 until n) { + val list: MutableList = ArrayList() + graph[i * n + j] = list + if (grid[i][j] == '#') { + continue + } + list.add(i * n + j) + for (dir in dirs) { + for (step in 1..jump) { + val x = i + dir[0] * step + val y = j + dir[1] * step + if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == '#') { + break + } + list.add(x * n + y) + } + } + } + } + return graph + } + + private fun dfs(p1: Int, p2: Int, turn: Int) { + var turn = turn + if (p1 == p2) { + return + } + if ((if (turn == 0) p2 else p1) == foodPos) { + return + } + if (memo[p1][p2][turn] < 0) { + return + } + memo[p1][p2][turn] = -1 + turn = turn xor 1 + for (w in graphs[turn][p2]) { + if (turn == MOUSE_TURN || ++memo[w][p1][turn] == graphs[turn][w].size) { + dfs(w, p1, turn) + } + } + } + + companion object { + private const val MOUSE_TURN = 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1729_find_followers_count/readme.md b/src/main/kotlin/g1701_1800/s1729_find_followers_count/readme.md new file mode 100644 index 00000000..122f28c6 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1729_find_followers_count/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) + +## 1729\. Find Followers Count + +Easy + +SQL Schema + +Table: `Followers` + + +-------------+------+ + | Column Name | Type | + +-------------+------+ + | user_id | int | + | follower_id | int | + +-------------+------+ + (user_id, follower_id) is the primary key for this table. + This table contains the IDs of a user and a follower in a social media app where the follower follows the user. + +Write an SQL query that will, for each user, return the number of followers. + +Return the result table ordered by `user_id`. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Followers table: + +---------+-------------+ + | user_id | follower_id | + +---------+-------------+ + | 0 | 1 | + | 1 | 0 | + | 2 | 0 | + | 2 | 1 | + +---------+-------------+ + +**Output:** + + +---------+----------------+ + | user_id | followers_count| + +---------+----------------+ + | 0 | 1 | + | 1 | 1 | + | 2 | 2 | + +---------+----------------+ + +**Explanation:** + +The followers of 0 are {1} + +The followers of 1 are {0} + +The followers of 2 are {0,1} + +## Solution + +```sql +# Write your MySQL query statement below +select user_id, count(follower_id) as followers_count +from followers +group by user_id +order by user_id +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1731_the_number_of_employees_which_report_to_each_employee/readme.md b/src/main/kotlin/g1701_1800/s1731_the_number_of_employees_which_report_to_each_employee/readme.md new file mode 100644 index 00000000..80c9e009 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1731_the_number_of_employees_which_report_to_each_employee/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) + +## 1731\. The Number of Employees Which Report to Each Employee + +Easy + +SQL Schema + +Table: `Employees` + + +-------------+----------+ + | Column Name | Type | + +-------------+----------+ + | employee_id | int | + | name | varchar | + | reports_to | int | + | age | int | + +-------------+----------+ + employee_id is the primary key for this table. + This table contains information about the employees and the id of the manager they report to. + Some employees do not report to anyone (reports_to is null). + +For this problem, we will consider a **manager** an employee who has at least 1 other employee reporting to them. + +Write an SQL query to report the ids and the names of all **managers**, the number of employees who report **directly** to them, and the average age of the reports rounded to the nearest integer. + +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 | reports_to | age | + +-------------+---------+------------+-----+ + | 9 | Hercy | null | 43 | + | 6 | Alice | 9 | 41 | + | 4 | Bob | 9 | 36 | + | 2 | Winston | null | 37 | + +-------------+---------+------------+-----+ + +**Output:** + + +-------------+-------+---------------+-------------+ + | employee_id | name | reports_count | average_age | + +-------------+-------+---------------+-------------+ + | 9 | Hercy | 2 | 39 | + +-------------+-------+---------------+-------------+ + +**Explanation:** + +Hercy has 2 people report directly to him, Alice and Bob. + +Their average age is (41+36)/2 = 38.5, which is 39 after rounding it to the nearest integer. + +## Solution + +```sql +# Write your MySQL query statement below +SELECT + t1.employee_id, + t1.name, + count(t2.reports_to) as reports_count, + ROUND(avg(t2.age)) as average_age +FROM + Employees t1 +INNER JOIN Employees t2 on t1.employee_id = t2.reports_to +GROUP BY 1, 2 +ORDER BY employee_id +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1732_find_the_highest_altitude/readme.md b/src/main/kotlin/g1701_1800/s1732_find_the_highest_altitude/readme.md new file mode 100644 index 00000000..2e8fde50 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1732_find_the_highest_altitude/readme.md @@ -0,0 +1,48 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1732\. Find the Highest Altitude + +Easy + +There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. + +You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i` and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._ + +**Example 1:** + +**Input:** gain = [-5,1,5,0,-7] + +**Output:** 1 + +**Explanation:** The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. + +**Example 2:** + +**Input:** gain = [-4,-3,-2,-1,4,3,2] + +**Output:** 0 + +**Explanation:** The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0. + +**Constraints:** + +* `n == gain.length` +* `1 <= n <= 100` +* `-100 <= gain[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun largestAltitude(gain: IntArray): Int { + var max = 0 + val altitudes = IntArray(gain.size + 1) + for (i in gain.indices) { + altitudes[i + 1] = altitudes[i] + gain[i] + max = Math.max(max, altitudes[i + 1]) + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1733_minimum_number_of_people_to_teach/readme.md b/src/main/kotlin/g1701_1800/s1733_minimum_number_of_people_to_teach/readme.md new file mode 100644 index 00000000..e927e781 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1733_minimum_number_of_people_to_teach/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) + +## 1733\. Minimum Number of People to Teach + +Medium + +On a social network consisting of `m` users and some friendships between users, two users can communicate with each other if they know a common language. + +You are given an integer `n`, an array `languages`, and an array `friendships` where: + +* There are `n` languages numbered `1` through `n`, +* `languages[i]` is the set of languages the ith user knows, and +* friendships[i] = [ui, vi] denotes a friendship between the users ui and vi. + +You can choose **one** language and teach it to some users so that all friends can communicate with each other. Return _the_ _**minimum**_ _number of users you need to teach._ + +Note that friendships are not transitive, meaning if `x` is a friend of `y` and `y` is a friend of `z`, this doesn't guarantee that `x` is a friend of `z`. + +**Example 1:** + +**Input:** n = 2, languages = \[\[1],[2],[1,2]], friendships = \[\[1,2],[1,3],[2,3]] + +**Output:** 1 + +**Explanation:** You can either teach user 1 the second language or user 2 the first language. + +**Example 2:** + +**Input:** n = 3, languages = \[\[2],[1,3],[1,2],[3]], friendships = \[\[1,4],[1,2],[3,4],[2,3]] + +**Output:** 2 + +**Explanation:** Teach the third language to users 1 and 3, yielding two users to teach. + +**Constraints:** + +* `2 <= n <= 500` +* `languages.length == m` +* `1 <= m <= 500` +* `1 <= languages[i].length <= n` +* `1 <= languages[i][j] <= n` +* 1 <= ui < vi <= languages.length +* `1 <= friendships.length <= 500` +* All tuples (ui, vi) are unique +* `languages[i]` contains only unique values + +## Solution + +```kotlin +class Solution { + fun minimumTeachings(n: Int, languages: Array, friendships: Array): Int { + val m: Int = languages.size + val speak: Array = Array(m + 1) { BooleanArray(n + 1) } + val teach: Array = Array(m + 1) { BooleanArray(n + 1) } + for (user in 0 until m) { + val userLanguages: IntArray = languages[user] + for (userLanguage: Int in userLanguages) { + speak[user + 1][userLanguage] = true + } + } + val listToTeach: MutableList = ArrayList() + for (friend: IntArray in friendships) { + val userA: Int = friend[0] + val userB: Int = friend[1] + var hasCommonLanguage = false + for (language in 1..n) { + if (speak[userA][language] && speak[userB][language]) { + hasCommonLanguage = true + break + } + } + if (!hasCommonLanguage) { + for (language in 1..n) { + if (!speak[userA][language]) { + teach[userA][language] = true + } + if (!speak[userB][language]) { + teach[userB][language] = true + } + } + listToTeach.add(friend) + } + } + var minLanguage: Int = Int.MAX_VALUE + var languageToTeach = 0 + for (language in 1..n) { + var count = 0 + for (user in 1..m) { + if (teach[user][language]) { + count++ + } + } + if (count < minLanguage) { + minLanguage = count + languageToTeach = language + } + } + val setToTeach: MutableSet = HashSet() + for (friend: IntArray in listToTeach) { + val userA: Int = friend[0] + val userB: Int = friend[1] + if (!speak[userA][languageToTeach]) { + setToTeach.add(userA) + } + if (!speak[userB][languageToTeach]) { + setToTeach.add(userB) + } + } + return setToTeach.size + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1734_decode_xored_permutation/readme.md b/src/main/kotlin/g1701_1800/s1734_decode_xored_permutation/readme.md new file mode 100644 index 00000000..f739c1f3 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1734_decode_xored_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) + +## 1734\. Decode XORed Permutation + +Medium + +There is an integer array `perm` that is a permutation of the first `n` positive integers, where `n` is always **odd**. + +It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = perm[i] XOR perm[i + 1]`. For example, if `perm = [1,3,2]`, then `encoded = [2,1]`. + +Given the `encoded` array, return _the original array_ `perm`. It is guaranteed that the answer exists and is unique. + +**Example 1:** + +**Input:** encoded = [3,1] + +**Output:** [1,2,3] + +**Explanation:** If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1] + +**Example 2:** + +**Input:** encoded = [6,5,4,6] + +**Output:** [2,4,1,5,3] + +**Constraints:** + +* 3 <= n < 105 +* `n` is odd. +* `encoded.length == n - 1` + +## Solution + +```kotlin +class Solution { + fun decode(encoded: IntArray): IntArray { + val decoded = IntArray(encoded.size + 1) + run { + var i = 1 + while (i < encoded.size) { + decoded[0] = decoded[0] xor encoded[i] + decoded[0] = decoded[0] xor i + decoded[0] = decoded[0] xor (i + 1) + i += 2 + } + } + decoded[0] = decoded[0] xor decoded.size + for (i in 1 until decoded.size) { + decoded[i] = decoded[i - 1] xor encoded[i - 1] + } + return decoded + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1735_count_ways_to_make_array_with_product/readme.md b/src/main/kotlin/g1701_1800/s1735_count_ways_to_make_array_with_product/readme.md new file mode 100644 index 00000000..0e55ee45 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1735_count_ways_to_make_array_with_product/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) + +## 1735\. Count Ways to Make Array With Product + +Hard + +You are given a 2D integer array, `queries`. For each `queries[i]`, where queries[i] = [ni, ki], find the number of different ways you can place positive integers into an array of size ni such that the product of the integers is ki. As the number of ways may be too large, the answer to the ith query is the number of ways **modulo** 109 + 7. + +Return _an integer array_ `answer` _where_ `answer.length == queries.length`_, and_ `answer[i]` _is the answer to the_ ith _query._ + +**Example 1:** + +**Input:** queries = \[\[2,6],[5,1],[73,660]] + +**Output:** [4,1,50734910] + +**Explanation:** Each query is independent. + +[2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1]. + +[5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1]. + +[73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109 + 7 = 50734910. + +**Example 2:** + +**Input:** queries = \[\[1,1],[2,2],[3,3],[4,4],[5,5]] + +**Output:** [1,2,3,10,5] + +**Constraints:** + +* 1 <= queries.length <= 104 +* 1 <= ni, ki <= 104 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + private lateinit var tri: Array + private var primes: List? = null + + fun waysToFillArray(queries: Array): IntArray { + val len: Int = queries.size + val res = IntArray(len) + primes = getPrimes(100) + tri = getTri(10015, 15) + for (i in 0 until len) { + res[i] = calculate(queries[i][0], queries[i][1]) + } + return res + } + + private fun getPrimes(limit: Int): List { + val notPrime = BooleanArray(limit + 1) + val res: MutableList = ArrayList() + for (i in 2..limit) { + if (!notPrime[i]) { + res.add(i) + var j: Int = i * i + while (j <= limit) { + notPrime[j] = true + j += i + } + } + } + return res + } + + private fun getTri(m: Int, n: Int): Array { + val res: Array = Array(m + 1) { LongArray(n + 1) } + for (i in 0..m) { + res[i][0] = 1 + for (j in 1..Math.min(n, i)) { + res[i][j] = (res[i - 1][j - 1] + res[i - 1][j]) % MOD + } + } + return res + } + + private fun calculate(n: Int, target: Int): Int { + var target: Int = target + var res: Long = 1 + for (prime: Int in primes!!) { + if (prime > target) { + break + } + var cnt = 0 + while (target % prime == 0) { + cnt++ + target /= prime + } + res = (res * tri[cnt + n - 1][cnt]) % MOD + } + return if (target > 1) (res * n % MOD).toInt() else res.toInt() + } + + companion object { + private val MOD: Int = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1736_latest_time_by_replacing_hidden_digits/readme.md b/src/main/kotlin/g1701_1800/s1736_latest_time_by_replacing_hidden_digits/readme.md new file mode 100644 index 00000000..3d11ee1c --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1736_latest_time_by_replacing_hidden_digits/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) + +## 1736\. Latest Time by Replacing Hidden Digits + +Easy + +You are given a string `time` in the form of `hh:mm`, where some of the digits in the string are hidden (represented by `?`). + +The valid times are those inclusively between `00:00` and `23:59`. + +Return _the latest valid time you can get from_ `time` _by replacing the hidden_ _digits_. + +**Example 1:** + +**Input:** time = "2?:?0" + +**Output:** "23:50" + +**Explanation:** The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50. + +**Example 2:** + +**Input:** time = "0?:3?" + +**Output:** "09:39" + +**Example 3:** + +**Input:** time = "1?:22" + +**Output:** "19:22" + +**Constraints:** + +* `time` is in the format `hh:mm`. +* It is guaranteed that you can produce a valid time from the given string. + +## Solution + +```kotlin +class Solution { + fun maximumTime(time: String): String { + val sb: StringBuilder = StringBuilder() + val strs: Array = time.split(":").dropLastWhile({ it.isEmpty() }).toTypedArray() + val hour: String = strs[0] + val min: String = strs[1] + if (hour[0] == '?') { + if (hour[1] == '?') { + sb.append("23") + } else if (hour[1] > '3') { + sb.append("1") + sb.append(hour[1]) + } else { + sb.append("2") + sb.append(hour[1]) + } + } else if (hour[0] == '0' || hour[0] == '1') { + if (hour[1] == '?') { + sb.append(hour[0]) + sb.append("9") + } else { + sb.append(hour) + } + } else if (hour[0] == '2') { + if (hour[1] == '?') { + sb.append("23") + } else { + sb.append(hour) + } + } + sb.append(":") + if (min[0] == '?') { + if (min[1] == '?') { + sb.append("59") + } else { + sb.append("5") + sb.append(min[1]) + } + return sb.toString() + } + sb.append(min[0]) + if (min[1] == '?') { + sb.append("9") + } else { + sb.append(min[1]) + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1737_change_minimum_characters_to_satisfy_one_of_three_conditions/readme.md b/src/main/kotlin/g1701_1800/s1737_change_minimum_characters_to_satisfy_one_of_three_conditions/readme.md new file mode 100644 index 00000000..5abc8ecb --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1737_change_minimum_characters_to_satisfy_one_of_three_conditions/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) + +## 1737\. Change Minimum Characters to Satisfy One of Three Conditions + +Medium + +You are given two strings `a` and `b` that consist of lowercase letters. In one operation, you can change any character in `a` or `b` to **any lowercase letter**. + +Your goal is to satisfy **one** of the following three conditions: + +* **Every** letter in `a` is **strictly less** than **every** letter in `b` in the alphabet. +* **Every** letter in `b` is **strictly less** than **every** letter in `a` in the alphabet. +* **Both** `a` and `b` consist of **only one** distinct letter. + +Return _the **minimum** number of operations needed to achieve your goal._ + +**Example 1:** + +**Input:** a = "aba", b = "caa" + +**Output:** 2 + +**Explanation:** Consider the best way to make each condition true: + +1) Change b to "ccc" in 2 operations, then every letter in a is less than every letter in b. + +2) Change a to "bbb" and b to "aaa" in 3 operations, then every letter in b is less than every letter in a. + +3) Change a to "aaa" and b to "aaa" in 2 operations, then a and b consist of one distinct letter. The best way was done in 2 operations (either condition 1 or condition 3). + +**Example 2:** + +**Input:** a = "dabadd", b = "cda" + +**Output:** 3 + +**Explanation:** The best way is to make condition 1 true by changing b to "eee". + +**Constraints:** + +* 1 <= a.length, b.length <= 105 +* `a` and `b` consist only of lowercase letters. + +## Solution + +```kotlin +class Solution { + fun minCharacters(a: String, b: String): Int { + val array1 = IntArray(26) + val array2 = IntArray(26) + val l1: Int = a.length + val l2: Int = b.length + for (i: Char in a.toCharArray()) { + array1[i.code - 'a'.code]++ + } + for (i: Char in b.toCharArray()) { + array2[i.code - 'a'.code]++ + } + var min: Int = Int.MAX_VALUE + var t1 = 0 + var t2 = 0 + var max: Int = -1 + for (i in 0..24) { + t1 += array1[i] + t2 += array2[i] + min = Math.min(min, Math.min(t1 + l2 - t2, t2 + l1 - t1)) + max = Math.max(max, array1[i] + array2[i]) + } + max = Math.max(max, array1[25] + array2[25]) + return Math.min(min, l1 + l2 - max) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1738_find_kth_largest_xor_coordinate_value/readme.md b/src/main/kotlin/g1701_1800/s1738_find_kth_largest_xor_coordinate_value/readme.md new file mode 100644 index 00000000..44900039 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1738_find_kth_largest_xor_coordinate_value/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) + +## 1738\. Find Kth Largest XOR Coordinate Value + +Medium + +You are given a 2D `matrix` of size `m x n`, consisting of non-negative integers. You are also given an integer `k`. + +The **value** of coordinate `(a, b)` of the matrix is the XOR of all `matrix[i][j]` where `0 <= i <= a < m` and `0 <= j <= b < n` **(0-indexed)**. + +Find the kth largest value **(1-indexed)** of all the coordinates of `matrix`. + +**Example 1:** + +**Input:** matrix = \[\[5,2],[1,6]], k = 1 + +**Output:** 7 + +**Explanation:** The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value. + +**Example 2:** + +**Input:** matrix = \[\[5,2],[1,6]], k = 2 + +**Output:** 5 + +**Explanation:** The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value. + +**Example 3:** + +**Input:** matrix = \[\[5,2],[1,6]], k = 3 + +**Output:** 4 + +**Explanation:** The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value. + +**Constraints:** + +* `m == matrix.length` +* `n == matrix[i].length` +* `1 <= m, n <= 1000` +* 0 <= matrix[i][j] <= 106 +* `1 <= k <= m * n` + +## Solution + +```kotlin +class Solution { + fun kthLargestValue(matrix: Array, k: Int): Int { + var t = 0 + val rows: Int = matrix.size + val cols: Int = matrix[0].size + val prefixXor: Array = Array(rows + 1) { IntArray(cols + 1) } + val array = IntArray(rows * cols) + for (r in 1..rows) { + for (c in 1..cols) { + prefixXor[r][c] = ( + matrix[r - 1][c - 1] + xor prefixXor[r - 1][c] + xor prefixXor[r][c - 1] + xor prefixXor[r - 1][c - 1] + ) + array[t++] = prefixXor[r][c] + } + } + val target: Int = array.size - k + quickSelect(array, 0, array.size - 1, target) + return array[target] + } + + private fun quickSelect(array: IntArray, left: Int, right: Int, target: Int): Int { + if (left == right) { + return left + } + val pivot: Int = array[right] + var j: Int = left + var k: Int = right - 1 + while (j <= k) { + if (array[j] < pivot) { + j++ + } else if (array[k] > pivot) { + k-- + } else { + swap(array, j++, k--) + } + } + swap(array, j, right) + return if (j == target) { + j + } else if (j > target) { + quickSelect(array, left, j - 1, target) + } else { + quickSelect(array, j + 1, right, target) + } + } + + private fun swap(array: IntArray, i: Int, j: Int) { + val tmp: Int = array[i] + array[i] = array[j] + array[j] = tmp + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1739_building_boxes/readme.md b/src/main/kotlin/g1701_1800/s1739_building_boxes/readme.md new file mode 100644 index 00000000..abe2c5a7 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1739_building_boxes/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) + +## 1739\. Building Boxes + +Hard + +You have a cubic storeroom where the width, length, and height of the room are all equal to `n` units. You are asked to place `n` boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes: + +* You can place the boxes anywhere on the floor. +* If box `x` is placed on top of the box `y`, then each side of the four vertical sides of the box `y` **must** either be adjacent to another box or to a wall. + +Given an integer `n`, return _the **minimum** possible number of boxes touching the floor._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/01/04/3-boxes.png) + +**Input:** n = 3 + +**Output:** 3 + +**Explanation:** The figure above is for the placement of the three boxes. These boxes are placed in the corner of the room, where the corner is on the left side. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/01/04/4-boxes.png) + +**Input:** n = 4 + +**Output:** 3 + +**Explanation:** The figure above is for the placement of the four boxes. These boxes are placed in the corner of the room, where the corner is on the left side. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/01/04/10-boxes.png) + +**Input:** n = 10 + +**Output:** 6 + +**Explanation:** The figure above is for the placement of the ten boxes. These boxes are placed in the corner of the room, where the corner is on the back side. + +**Constraints:** + +* 1 <= n <= 109 + +## Solution + +```kotlin +class Solution { + fun minimumBoxes(n: Int): Int { + val k: Int = findLargestTetrahedralNotGreaterThan(n) + val used: Int = tetrahedral(k) + val floor: Int = triangular(k) + val unused: Int = (n - used) + if (unused == 0) { + return floor + } + val r: Int = findSmallestTriangularNotLessThan(unused) + return (floor + r) + } + + private fun findLargestTetrahedralNotGreaterThan(te: Int): Int { + var a: Int = Math.ceil(Math.pow(product(6, te.toLong()).toDouble(), ONE_THIRD)).toInt() + while (tetrahedral(a) > te) { + a-- + } + return a + } + + private fun findSmallestTriangularNotLessThan(t: Int): Int { + var a: Int = -1 + Math.floor(Math.sqrt(product(t.toLong(), 2).toDouble())).toInt() + while (triangular(a) < t) { + a++ + } + return a + } + + private fun tetrahedral(a: Int): Int { + return ratio(product(a.toLong(), (a + 1).toLong(), (a + 2).toLong()), 6).toInt() + } + + private fun triangular(a: Int): Int { + return ratio(product(a.toLong(), (a + 1).toLong()), 2).toInt() + } + + private fun product(vararg vals: Long): Long { + var product: Long = 1L + for (`val`: Long in vals) { + product *= `val` + } + return product + } + + private fun ratio(a: Long, b: Long): Long { + return (a / b) + } + + companion object { + val ONE_THIRD: Double = 1.0 / 3.0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1741_find_total_time_spent_by_each_employee/readme.md b/src/main/kotlin/g1701_1800/s1741_find_total_time_spent_by_each_employee/readme.md new file mode 100644 index 00000000..f82a2236 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1741_find_total_time_spent_by_each_employee/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) + +## 1741\. Find Total Time Spent by Each Employee + +Easy + +SQL Schema + +Table: `Employees` + + +-------------+------+ + | Column Name | Type | + +-------------+------+ + | emp_id | int | + | event_day | date | + | in_time | int | + | out_time | int | + +-------------+------+ + (emp_id, event_day, in_time) is the primary key of this table. + The table shows the employees' entries and exits in an office. + event_day is the day at which this event happened, in_time is the minute at which the employee entered the office, and out_time is the minute at which they left the office. + in_time and out_time are between 1 and 1440. + It is guaranteed that no two events on the same day intersect in time, and in_time < out_time. + +Write an SQL query to calculate the total time **in minutes** spent by each employee on each day at the office. Note that within one day, an employee can enter and leave more than once. The time spent in the office for a single entry is `out_time - in_time`. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Employees table: + +--------+------------+---------+----------+ + | emp_id | event_day | in_time | out_time | + +--------+------------+---------+----------+ + | 1 | 2020-11-28 | 4 | 32 | + | 1 | 2020-11-28 | 55 | 200 | + | 1 | 2020-12-03 | 1 | 42 | + | 2 | 2020-11-28 | 3 | 33 | + | 2 | 2020-12-09 | 47 | 74 | + +--------+------------+---------+----------+ + +**Output:** + + +------------+--------+------------+ + | day | emp_id | total_time | + +------------+--------+------------+ + | 2020-11-28 | 1 | 173 | + | 2020-11-28 | 2 | 30 | + | 2020-12-03 | 1 | 41 | + | 2020-12-09 | 2 | 27 | + +------------+--------+------------+ + +**Explanation:** + +Employee 1 has three events: two on day 2020-11-28 with a total of (32 - 4) + (200 - 55) = 173, and one on day 2020-12-03 with a total of (42 - 1) = 41. + +Employee 2 has two events: one on day 2020-11-28 with a total of (33 - 3) = 30, and one on day 2020-12-09 with a total of (74 - 47) = 27. + +## Solution + +```sql +# Write your MySQL query statement below +SELECT event_day AS "day", emp_id, SUM(out_time) - SUM(in_time) AS total_time +FROM Employees +GROUP BY event_day, emp_id +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1742_maximum_number_of_balls_in_a_box/readme.md b/src/main/kotlin/g1701_1800/s1742_maximum_number_of_balls_in_a_box/readme.md new file mode 100644 index 00000000..d29f32f0 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1742_maximum_number_of_balls_in_a_box/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) + +## 1742\. Maximum Number of Balls in a Box + +Easy + +You are working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`. + +Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number `321` will be put in the box number `3 + 2 + 1 = 6` and the ball number `10` will be put in the box number `1 + 0 = 1`. + +Given two integers `lowLimit` and `highLimit`, return _the number of balls in the box with the most balls._ + +**Example 1:** + +**Input:** lowLimit = 1, highLimit = 10 + +**Output:** 2 + +**Explanation:** + +Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... + +Ball Count: 2 1 1 1 1 1 1 1 1 0 0 ... + +Box 1 has the most number of balls with 2 balls. + +**Example 2:** + +**Input:** lowLimit = 5, highLimit = 15 + +**Output:** 2 + +**Explanation:** + +Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... + +Ball Count: 1 1 1 1 2 2 1 1 1 0 0 ... + +Boxes 5 and 6 have the most number of balls with 2 balls in each. + +**Example 3:** + +**Input:** lowLimit = 19, highLimit = 28 + +**Output:** 2 + +**Explanation:** + +Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ... + +Ball Count: 0 1 1 1 1 1 1 1 1 2 0 0 ... + +Box 10 has the most number of balls with 2 balls. + +**Constraints:** + +* 1 <= lowLimit <= highLimit <= 105 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun countBalls(lowLimit: Int, highLimit: Int): Int { + var maxValue: Int + val countArray = IntArray(46) + var currentSum: Int = getDigitSum(lowLimit) + countArray[currentSum]++ + maxValue = 1 + for (i in lowLimit + 1..highLimit) { + if (i % 10 == 0) { + currentSum = getDigitSum(i) + } else { + currentSum++ + } + countArray[currentSum]++ + if (countArray[currentSum] > maxValue) { + maxValue = countArray[currentSum] + } + } + return maxValue + } + + private fun getDigitSum(num: Int): Int { + var num: Int = num + var currentSum = 0 + while (num > 0) { + currentSum += num % 10 + num /= 10 + } + return currentSum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1743_restore_the_array_from_adjacent_pairs/readme.md b/src/main/kotlin/g1701_1800/s1743_restore_the_array_from_adjacent_pairs/readme.md new file mode 100644 index 00000000..c976f367 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1743_restore_the_array_from_adjacent_pairs/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) + +## 1743\. Restore the Array From Adjacent Pairs + +Medium + +There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. + +You are given a 2D integer array `adjacentPairs` of size `n - 1` where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in `nums`. + +It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. + +Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. + +**Example 1:** + +**Input:** adjacentPairs = \[\[2,1],[3,4],[3,2]] + +**Output:** [1,2,3,4] + +**Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs[i] may not be in left-to-right order. + +**Example 2:** + +**Input:** adjacentPairs = \[\[4,-2],[1,4],[-3,1]] + +**Output:** [-2,4,1,-3] + +**Explanation:** There can be negative numbers. Another solution is [-3,1,4,-2], which would also be accepted. + +**Example 3:** + +**Input:** adjacentPairs = \[\[100000,-100000]] + +**Output:** [100000,-100000] + +**Constraints:** + +* `nums.length == n` +* `adjacentPairs.length == n - 1` +* `adjacentPairs[i].length == 2` +* 2 <= n <= 105 +* -105 <= nums[i], ui, vi <= 105 +* There exists some `nums` that has `adjacentPairs` as its pairs. + +## Solution + +```kotlin +class Solution { + fun restoreArray(adjacentPairs: Array): IntArray { + if (adjacentPairs.isEmpty()) { + return IntArray(0) + } + if (adjacentPairs.size == 1) { + return adjacentPairs[0] + } + val graph: MutableMap> = HashMap() + for (pair: IntArray in adjacentPairs) { + graph.computeIfAbsent(pair[0]) { _: Int? -> ArrayList() }.add(pair[1]) + graph.computeIfAbsent(pair[1]) { _: Int? -> ArrayList() }.add(pair[0]) + } + val res = IntArray(graph.size) + for (entry: Map.Entry> in graph.entries) { + if (entry.value.size == 1) { + res[0] = entry.key + break + } + } + res[1] = graph[res[0]]!![0] + for (i in 2 until res.size) { + for (cur: Int in graph[res[i - 1]]!!) { + if (cur != res[i - 2]) { + res[i] = cur + break + } + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1744_can_you_eat_your_favorite_candy_on_your_favorite_day/readme.md b/src/main/kotlin/g1701_1800/s1744_can_you_eat_your_favorite_candy_on_your_favorite_day/readme.md new file mode 100644 index 00000000..358038da --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1744_can_you_eat_your_favorite_candy_on_your_favorite_day/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) + +## 1744\. Can You Eat Your Favorite Candy on Your Favorite Day? + +Medium + +You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the ith type you have. You are also given a 2D array `queries` where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]. + +You play a game with the following rules: + +* You start eating candies on day `**0**`. +* You **cannot** eat **any** candy of type `i` unless you have eaten **all** candies of type `i - 1`. +* You must eat **at least** **one** candy per day until you have eaten all the candies. + +Construct a boolean array `answer` such that `answer.length == queries.length` and `answer[i]` is `true` if you can eat a candy of type favoriteTypei on day favoriteDayi without eating **more than** dailyCapi candies on **any** day, and `false` otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2. + +Return _the constructed array_ `answer`. + +**Example 1:** + +**Input:** candiesCount = [7,4,5,3,8], queries = \[\[0,2,2],[4,2,4],[2,13,1000000000]] + +**Output:** [true,false,true] + +**Explanation:** + +1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2. + +2- You can eat at most 4 candies each day. + +If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1. + +On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2. + +3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13. + +**Example 2:** + +**Input:** candiesCount = [5,2,6,4,1], queries = \[\[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]] + +**Output:** [false,true,true,false,false] + +**Constraints:** + +* 1 <= candiesCount.length <= 105 +* 1 <= candiesCount[i] <= 105 +* 1 <= queries.length <= 105 +* `queries[i].length == 3` +* 0 <= favoriteTypei < candiesCount.length +* 0 <= favoriteDayi <= 109 +* 1 <= dailyCapi <= 109 + +## Solution + +```kotlin +class Solution { + fun canEat(candiesCount: IntArray, queries: Array): BooleanArray { + val result = BooleanArray(queries.size) + val candiesComm = LongArray(candiesCount.size + 1) + for (i in 1..candiesCount.size) { + candiesComm[i] = candiesComm[i - 1] + candiesCount[i - 1] + } + for (i in queries.indices) { + val type: Int = queries[i][0] + val day: Long = queries[i][1].toLong() + val cap: Long = queries[i][2].toLong() + result[i] = ((day + 1) * cap > candiesComm[type]) && day < candiesComm[type + 1] + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1745_palindrome_partitioning_iv/readme.md b/src/main/kotlin/g1701_1800/s1745_palindrome_partitioning_iv/readme.md new file mode 100644 index 00000000..aaab0c2b --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1745_palindrome_partitioning_iv/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) + +## 1745\. Palindrome Partitioning IV + +Hard + +Given a string `s`, return `true` _if it is possible to split the string_ `s` _into three **non-empty** palindromic substrings. Otherwise, return_ `false`. + +A string is said to be palindrome if it the same string when reversed. + +**Example 1:** + +**Input:** s = "abcbdd" + +**Output:** true + +**Explanation:** "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes. + +**Example 2:** + +**Input:** s = "bcbddxy" + +**Output:** false + +**Explanation:** s cannot be split into 3 palindromes. + +**Constraints:** + +* `3 <= s.length <= 2000` +* `s` consists only of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun checkPartitioning(s: String): Boolean { + val len: Int = s.length + val ch: CharArray = s.toCharArray() + val dp = IntArray(len + 1) + dp[0] = 0x01 + for (i in 0 until len) { + for (l: Int in intArrayOf(i - 1, i)) { + var r: Int = i + var localL = l + while ((localL >= 0) && (r < len) && (ch[localL] == ch[r])) { + dp[r + 1] = dp[r + 1] or (dp[localL] shl 1) + localL-- + r++ + } + } + } + return (dp[len] and 0x08) == 0x08 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1748_sum_of_unique_elements/readme.md b/src/main/kotlin/g1701_1800/s1748_sum_of_unique_elements/readme.md new file mode 100644 index 00000000..3380c9fc --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1748_sum_of_unique_elements/readme.md @@ -0,0 +1,59 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1748\. Sum of Unique Elements + +Easy + +You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. + +Return _the **sum** of all the unique elements of_ `nums`. + +**Example 1:** + +**Input:** nums = [1,2,3,2] + +**Output:** 4 + +**Explanation:** The unique elements are [1,3], and the sum is 4. + +**Example 2:** + +**Input:** nums = [1,1,1,1,1] + +**Output:** 0 + +**Explanation:** There are no unique elements, and the sum is 0. + +**Example 3:** + +**Input:** nums = [1,2,3,4,5] + +**Output:** 15 + +**Explanation:** The unique elements are [1,2,3,4,5], and the sum is 15. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `1 <= nums[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun sumOfUnique(nums: IntArray): Int { + val map: MutableMap = HashMap() + var sum: Int = 0 + for (num: Int in nums) { + map.put(num, map.getOrDefault(num, 0) + 1) + } + for (entry: Map.Entry in map.entries) { + if (entry.value == 1) { + sum += entry.key + } + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1749_maximum_absolute_sum_of_any_subarray/readme.md b/src/main/kotlin/g1701_1800/s1749_maximum_absolute_sum_of_any_subarray/readme.md new file mode 100644 index 00000000..306e2114 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1749_maximum_absolute_sum_of_any_subarray/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) + +## 1749\. Maximum Absolute Sum of Any Subarray + +Medium + +You are given an integer array `nums`. The **absolute sum** of a subarray [numsl, numsl+1, ..., numsr-1, numsr] is abs(numsl + numsl+1 + ... + numsr-1 + numsr). + +Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`. + +Note that `abs(x)` is defined as follows: + +* If `x` is a negative integer, then `abs(x) = -x`. +* If `x` is a non-negative integer, then `abs(x) = x`. + +**Example 1:** + +**Input:** nums = [1,-3,2,3,-4] + +**Output:** 5 + +**Explanation:** The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5. + +**Example 2:** + +**Input:** nums = [2,-5,1,-4,3,-2] + +**Output:** 8 + +**Explanation:** The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8. + +**Constraints:** + +* 1 <= nums.length <= 105 +* -104 <= nums[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun maxAbsoluteSum(nums: IntArray): Int { + var min: Int = 0 + var max: Int = 0 + var s: Int = 0 + for (num: Int in nums) { + s += num + min = Math.min(min, s) + max = Math.max(max, s) + } + return max - min + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1750_minimum_length_of_string_after_deleting_similar_ends/readme.md b/src/main/kotlin/g1701_1800/s1750_minimum_length_of_string_after_deleting_similar_ends/readme.md new file mode 100644 index 00000000..2ebd0bb9 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1750_minimum_length_of_string_after_deleting_similar_ends/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) + +## 1750\. Minimum Length of String After Deleting Similar Ends + +Medium + +Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: + +1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. +2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. +3. The prefix and the suffix should not intersect at any index. +4. The characters from the prefix and suffix must be the same. +5. Delete both the prefix and the suffix. + +Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_. + +**Example 1:** + +**Input:** s = "ca" + +**Output:** 2 + +**Explanation:** You can't remove any characters, so the string stays as is. + +**Example 2:** + +**Input:** s = "cabaabac" + +**Output:** 0 + +**Explanation:** An optimal sequence of operations is: + +- Take prefix = "c" and suffix = "c" and remove them, s = "abaaba". + +- Take prefix = "a" and suffix = "a" and remove them, s = "baab". + +- Take prefix = "b" and suffix = "b" and remove them, s = "aa". + +- Take prefix = "a" and suffix = "a" and remove them, s = "". + +**Example 3:** + +**Input:** s = "aabccabba" + +**Output:** 3 + +**Explanation:** An optimal sequence of operations is: + +- Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb". + +- Take prefix = "b" and suffix = "bb" and remove them, s = "cca". + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` only consists of characters `'a'`, `'b'`, and `'c'`. + +## Solution + +```kotlin +class Solution { + fun minimumLength(s: String): Int { + var i = 0 + var j: Int = s.length - 1 + if (s[i] == s[j]) { + while (i < j && s[i] == s[j]) { + val c: Char = s[i] + i++ + while (c == s[i] && i < j) { + i++ + } + j-- + while (c == s[j] && i < j) { + j-- + } + } + } + return if (i <= j) s.substring(i, j).length + 1 else 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1751_maximum_number_of_events_that_can_be_attended_ii/readme.md b/src/main/kotlin/g1701_1800/s1751_maximum_number_of_events_that_can_be_attended_ii/readme.md new file mode 100644 index 00000000..08b699f7 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1751_maximum_number_of_events_that_can_be_attended_ii/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) + +## 1751\. Maximum Number of Events That Can Be Attended II + +Hard + +You are given an array of `events` where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei. You are also given an integer `k` which represents the maximum number of events you can attend. + +You can only attend one event at a time. If you choose to attend an event, you must attend the **entire** event. Note that the end day is **inclusive**: that is, you cannot attend two events where one of them starts and the other ends on the same day. + +Return _the **maximum sum** of values that you can receive by attending events._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60048-pm.png) + +**Input:** events = \[\[1,2,4],[3,4,3],[2,3,1]], k = 2 + +**Output:** 7 + +**Explanation:** Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60150-pm.png) + +**Input:** events = \[\[1,2,4],[3,4,3],[2,3,10]], k = 2 + +**Output:** 10 + +**Explanation:** Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do **not** have to attend k events. + +**Example 3:** + +**![](https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60703-pm.png)** + +**Input:** events = \[\[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3 + +**Output:** 9 + +**Explanation:** Although the events do not overlap, you can only attend 3 events. Pick the highest valued three. + +**Constraints:** + +* `1 <= k <= events.length` +* 1 <= k * events.length <= 106 +* 1 <= startDayi <= endDayi <= 109 +* 1 <= valuei <= 106 + +## Solution + +```kotlin +import java.util.Arrays + +@Suppress("NAME_SHADOWING") +class Solution { + fun maxValue(events: Array, k: Int): Int { + if (k == 1) { + val value = Arrays.stream(events).max({ a: IntArray, b: IntArray -> a[2].compareTo(b[2]) }) + return if (value.isPresent) { + value.get()[2] + } else { + throw NullPointerException() + } + } + val n = events.size + Arrays.sort(events, { a: IntArray, b: IntArray -> a[0].compareTo(b[0]) }) + val memo = Array(n) { IntArray(k + 1) } + return dfs(events, 0, k, memo) + } + + private fun dfs(events: Array, i: Int, k: Int, memo: Array): Int { + if (k == 0 || i >= events.size) { + return 0 + } + if (memo[i][k] > 0) { + return memo[i][k] + } + val idx = binarySearch(events, events[i][1] + 1, i + 1) + val use = events[i][2] + dfs(events, idx, k - 1, memo) + val notUse = dfs(events, i + 1, k, memo) + val res = Math.max(use, notUse) + memo[i][k] = res + return res + } + + private fun binarySearch(events: Array, i: Int, st: Int): Int { + var st = st + if (st >= events.size) { + return st + } + var end = events.size - 1 + while (st < end) { + val mid = st + (end - st) / 2 + if (events[mid][0] < i) { + st = mid + 1 + } else { + end = mid + } + } + return if (events[st][0] >= i) st else st + 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1752_check_if_array_is_sorted_and_rotated/readme.md b/src/main/kotlin/g1701_1800/s1752_check_if_array_is_sorted_and_rotated/readme.md new file mode 100644 index 00000000..10f1a257 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1752_check_if_array_is_sorted_and_rotated/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) + +## 1752\. Check if Array Is Sorted and Rotated + +Easy + +Given an array `nums`, return `true` _if the array was originally sorted in non-decreasing order, then rotated **some** number of positions (including zero)_. Otherwise, return `false`. + +There may be **duplicates** in the original array. + +**Note:** An array `A` rotated by `x` positions results in an array `B` of the same length such that `A[i] == B[(i+x) % A.length]`, where `%` is the modulo operation. + +**Example 1:** + +**Input:** nums = [3,4,5,1,2] + +**Output:** true + +**Explanation:** [1,2,3,4,5] is the original sorted array. You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2]. + +**Example 2:** + +**Input:** nums = [2,1,3,4] + +**Output:** false + +**Explanation:** There is no sorted array once rotated that can make nums. + +**Example 3:** + +**Input:** nums = [1,2,3] + +**Output:** true + +**Explanation:** [1,2,3] is the original sorted array. You can rotate the array by x = 0 positions (i.e. no rotation) to make nums. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `1 <= nums[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun check(nums: IntArray): Boolean { + var checker = 0 + for (i in 1 until nums.size) { + if (nums[i - 1] > nums[i]) { + checker++ + } + } + // checking if the last element is greater than the first + if (nums[nums.size - 1] > nums[0]) { + checker++ + } + return checker <= 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1753_maximum_score_from_removing_stones/readme.md b/src/main/kotlin/g1701_1800/s1753_maximum_score_from_removing_stones/readme.md new file mode 100644 index 00000000..65edd584 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1753_maximum_score_from_removing_stones/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) + +## 1753\. Maximum Score From Removing Stones + +Medium + +You are playing a solitaire game with **three piles** of stones of sizes `a`, `b`, and `c` respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game stops when there are **fewer than two non-empty** piles (meaning there are no more available moves). + +Given three integers `a`, `b`, and `c`, return _the_ **_maximum_** _**score** you can get._ + +**Example 1:** + +**Input:** a = 2, b = 4, c = 6 + +**Output:** 6 + +**Explanation:** The starting state is (2, 4, 6). One optimal set of moves is: + +- Take from 1st and 3rd piles, state is now (1, 4, 5) + +- Take from 1st and 3rd piles, state is now (0, 4, 4) + +- Take from 2nd and 3rd piles, state is now (0, 3, 3) + +- Take from 2nd and 3rd piles, state is now (0, 2, 2) + +- Take from 2nd and 3rd piles, state is now (0, 1, 1) + +- Take from 2nd and 3rd piles, state is now (0, 0, 0) + +There are fewer than two non-empty piles, so the game ends. Total: 6 points. + +**Example 2:** + +**Input:** a = 4, b = 4, c = 6 + +**Output:** 7 + +**Explanation:** The starting state is (4, 4, 6). One optimal set of moves is: + +- Take from 1st and 2nd piles, state is now (3, 3, 6) + +- Take from 1st and 3rd piles, state is now (2, 3, 5) + +- Take from 1st and 3rd piles, state is now (1, 3, 4) + +- Take from 1st and 3rd piles, state is now (0, 3, 3) + +- Take from 2nd and 3rd piles, state is now (0, 2, 2) + +- Take from 2nd and 3rd piles, state is now (0, 1, 1) + +- Take from 2nd and 3rd piles, state is now (0, 0, 0) + +There are fewer than two non-empty piles, so the game ends. Total: 7 points. + +**Example 3:** + +**Input:** a = 1, b = 8, c = 8 + +**Output:** 8 + +**Explanation:** One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty. After that, there are fewer than two non-empty piles, so the game ends. + +**Constraints:** + +* 1 <= a, b, c <= 105 + +## Solution + +```kotlin +class Solution { + fun maximumScore(a: Int, b: Int, c: Int): Int { + val nums = intArrayOf(a, b, c) + nums.sort() + return if (nums[0] + nums[1] < nums[2]) { + nums[0] + nums[1] + } else { + (nums[0] + nums[1] + nums[2]) / 2 + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1754_largest_merge_of_two_strings/readme.md b/src/main/kotlin/g1701_1800/s1754_largest_merge_of_two_strings/readme.md new file mode 100644 index 00000000..6aca26d9 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1754_largest_merge_of_two_strings/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) + +## 1754\. Largest Merge Of Two Strings + +Medium + +You are given two strings `word1` and `word2`. You want to construct a string `merge` in the following way: while either `word1` or `word2` are non-empty, choose **one** of the following options: + +* If `word1` is non-empty, append the **first** character in `word1` to `merge` and delete it from `word1`. + * For example, if `word1 = "abc"` and `merge = "dv"`, then after choosing this operation, `word1 = "bc"` and `merge = "dva"`. +* If `word2` is non-empty, append the **first** character in `word2` to `merge` and delete it from `word2`. + * For example, if `word2 = "abc"` and `merge = ""`, then after choosing this operation, `word2 = "bc"` and `merge = "a"`. + +Return _the lexicographically **largest**_ `merge` _you can construct_. + +A string `a` is lexicographically larger than a string `b` (of the same length) if in the first position where `a` and `b` differ, `a` has a character strictly larger than the corresponding character in `b`. For example, `"abcd"` is lexicographically larger than `"abcc"` because the first position they differ is at the fourth character, and `d` is greater than `c`. + +**Example 1:** + +**Input:** word1 = "cabaa", word2 = "bcaaa" + +**Output:** "cbcabaaaaa" + +**Explanation:** One way to get the lexicographically largest merge is: + +- Take from word1: merge = "c", word1 = "abaa", word2 = "bcaaa" + +- Take from word2: merge = "cb", word1 = "abaa", word2 = "caaa" + +- Take from word2: merge = "cbc", word1 = "abaa", word2 = "aaa" + +- Take from word1: merge = "cbca", word1 = "baa", word2 = "aaa" + +- Take from word1: merge = "cbcab", word1 = "aa", word2 = "aaa" + +- Append the remaining 5 a's from word1 and word2 at the end of merge. + +**Example 2:** + +**Input:** word1 = "abcabc", word2 = "abdcaba" + +**Output:** "abdcabcabcaba" + +**Constraints:** + +* `1 <= word1.length, word2.length <= 3000` +* `word1` and `word2` consist only of lowercase English letters. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun largestMerge(word1: String, word2: String): String { + val a = word1.toCharArray() + val b = word2.toCharArray() + val sb = StringBuilder() + var i = 0 + var j = 0 + while (i < a.size && j < b.size) { + if (a[i] == b[j]) { + val first = go(a, i, b, j) + if (first) { + sb.append(a[i]) + i++ + } else { + sb.append(b[j]) + j++ + } + } else { + if (a[i] > b[j]) { + sb.append(a[i]) + i++ + } else { + sb.append(b[j]) + j++ + } + } + } + while (i < a.size) { + sb.append(a[i++]) + } + while (j < b.size) { + sb.append(b[j++]) + } + return sb.toString() + } + + private fun go(a: CharArray, i: Int, b: CharArray, j: Int): Boolean { + var i = i + var j = j + while (i < a.size && j < b.size && a[i] == b[j]) { + i++ + j++ + } + if (i == a.size) { + return false + } + return if (j == b.size) { + true + } else a[i] > b[j] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1755_closest_subsequence_sum/readme.md b/src/main/kotlin/g1701_1800/s1755_closest_subsequence_sum/readme.md new file mode 100644 index 00000000..fdf9c1fc --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1755_closest_subsequence_sum/readme.md @@ -0,0 +1,89 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1755\. Closest Subsequence Sum + +Hard + +You are given an integer array `nums` and an integer `goal`. + +You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`. + +Return _the **minimum** possible value of_ `abs(sum - goal)`. + +Note that a subsequence of an array is an array formed by removing some elements **(possibly all or none)** of the original array. + +**Example 1:** + +**Input:** nums = [5,-7,3,5], goal = 6 + +**Output:** 0 + +**Explanation:** Choose the whole array as a subsequence, with a sum of 6. This is equal to the goal, so the absolute difference is 0. + +**Example 2:** + +**Input:** nums = [7,-9,15,-2], goal = -5 + +**Output:** 1 + +**Explanation:** Choose the subsequence [7,-9,-2], with a sum of -4. The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum. + +**Example 3:** + +**Input:** nums = [1,2,3], goal = -7 + +**Output:** 7 + +**Constraints:** + +* `1 <= nums.length <= 40` +* -107 <= nums[i] <= 107 +* -109 <= goal <= 109 + +## Solution + +```kotlin +class Solution { + private var idx = 0 + private var sum = 0 + fun minAbsDifference(nums: IntArray, goal: Int): Int { + val n = nums.size + val nFirst = Math.pow(2.0, n.toDouble() / 2).toInt() + val nSecond = Math.pow(2.0, (n - n / 2).toDouble()).toInt() + val first = IntArray(nFirst) + val second = IntArray(nSecond) + helper(nums, first, 0, n / 2 - 1) + sum = 0 + idx = sum + helper(nums, second, n / 2, n - 1) + first.sort() + second.sort() + var low = 0 + var high = nSecond - 1 + var ans = Int.MAX_VALUE + while (low < nFirst && high >= 0) { + val localSum = first[low] + second[high] + ans = Math.min(ans, Math.abs(localSum - goal)) + if (ans == 0) { + break + } + if (localSum < goal) { + low++ + } else { + high-- + } + } + return ans + } + + private fun helper(nums: IntArray, arr: IntArray, start: Int, end: Int) { + for (i in start..end) { + sum += nums[i] + arr[idx++] = sum + helper(nums, arr, i + 1, end) + sum -= nums[i] + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1757_recyclable_and_low_fat_products/readme.md b/src/main/kotlin/g1701_1800/s1757_recyclable_and_low_fat_products/readme.md new file mode 100644 index 00000000..eb54637d --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1757_recyclable_and_low_fat_products/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) + +## 1757\. Recyclable and Low Fat Products + +Easy + +SQL Schema + +Table: `Products` + + +-------------+---------+ + | Column Name | Type | + +-------------+---------+ + | product_id | int | + | low_fats | enum | + | recyclable | enum | + +-------------+---------+ + product_id is the primary key for this table. + low_fats is an ENUM of type ('Y', 'N') where 'Y' means this product is low fat and 'N' means it is not. + recyclable is an ENUM of types ('Y', 'N') where 'Y' means this product is recyclable and 'N' means it is not. + +Write an SQL query to find the ids of products that are both low fat and recyclable. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Products table: + +-------------+----------+------------+ + | product_id | low_fats | recyclable | + +-------------+----------+------------+ + | 0 | Y | N | + | 1 | Y | Y | + | 2 | N | Y | + | 3 | Y | Y | + | 4 | N | N | + +-------------+----------+------------+ + +**Output:** + + +-------------+ + | product_id | + +-------------+ + | 1 | + | 3 | + +-------------+ + +**Explanation:** Only products 1 and 3 are both low fat and recyclable. + +## Solution + +```sql +# Write your MySQL query statement below +select product_id from Products +where low_fats='Y' and recyclable='Y' +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1758_minimum_changes_to_make_alternating_binary_string/readme.md b/src/main/kotlin/g1701_1800/s1758_minimum_changes_to_make_alternating_binary_string/readme.md new file mode 100644 index 00000000..7d289e09 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1758_minimum_changes_to_make_alternating_binary_string/readme.md @@ -0,0 +1,64 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1758\. Minimum Changes To Make Alternating Binary String + +Easy + +You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa. + +The string is called alternating if no two adjacent characters are equal. For example, the string `"010"` is alternating, while the string `"0100"` is not. + +Return _the **minimum** number of operations needed to make_ `s` _alternating_. + +**Example 1:** + +**Input:** s = "0100" + +**Output:** 1 + +**Explanation:** If you change the last character to '1', s will be "0101", which is alternating. + +**Example 2:** + +**Input:** s = "10" + +**Output:** 0 + +**Explanation:** s is already alternating. + +**Example 3:** + +**Input:** s = "1111" + +**Output:** 2 + +**Explanation:** You need two operations to reach "0101" or "1010". + +**Constraints:** + +* 1 <= s.length <= 104 +* `s[i]` is either `'0'` or `'1'`. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun minOperations(s: String): Int { + return Math.min(countFlips(s, '0'), countFlips(s, '1')) + } + + private fun countFlips(s: String, next: Char): Int { + var next = next + var count = 0 + for (c in s.toCharArray()) { + if (next != c) { + count++ + } + next = if (next == '0') '1' else '0' + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1759_count_number_of_homogenous_substrings/readme.md b/src/main/kotlin/g1701_1800/s1759_count_number_of_homogenous_substrings/readme.md new file mode 100644 index 00000000..795e0b13 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1759_count_number_of_homogenous_substrings/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) + +## 1759\. Count Number of Homogenous Substrings + +Medium + +Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** 109 + 7. + +A string is **homogenous** if all the characters of the string are the same. + +A **substring** is a contiguous sequence of characters within a string. + +**Example 1:** + +**Input:** s = "abbcccaa" + +**Output:** 13 + +**Explanation:** The homogenous substrings are listed as below: + +"a" appears 3 times. + +"aa" appears 1 time. + +"b" appears 2 times. + +"bb" appears 1 time. + +"c" appears 3 times. + +"cc" appears 2 times. + +"ccc" appears 1 time. + +3 + 1 + 2 + 1 + 3 + 2 + 1 = 13. + +**Example 2:** + +**Input:** s = "xy" + +**Output:** 2 + +**Explanation:** The homogenous substrings are "x" and "y". + +**Example 3:** + +**Input:** s = "zzzzz" + +**Output:** 15 + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` consists of lowercase letters. + +## Solution + +```kotlin +class Solution { + fun countHomogenous(s: String): Int { + var total = 0 + var count = 0 + for (i in 0 until s.length) { + if (i > 0 && s[i] == s[i - 1]) { + count++ + } else { + count = 1 + } + total = (total + count) % 1000000007 + } + return total + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1760_minimum_limit_of_balls_in_a_bag/readme.md b/src/main/kotlin/g1701_1800/s1760_minimum_limit_of_balls_in_a_bag/readme.md new file mode 100644 index 00000000..f18abd6c --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1760_minimum_limit_of_balls_in_a_bag/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) + +## 1760\. Minimum Limit of Balls in a Bag + +Medium + +You are given an integer array `nums` where the ith bag contains `nums[i]` balls. You are also given an integer `maxOperations`. + +You can perform the following operation at most `maxOperations` times: + +* Take any bag of balls and divide it into two new bags with a **positive** number of balls. + * For example, a bag of `5` balls can become two new bags of `1` and `4` balls, or two new bags of `2` and `3` balls. + +Your penalty is the **maximum** number of balls in a bag. You want to **minimize** your penalty after the operations. + +Return _the minimum possible penalty after performing the operations_. + +**Example 1:** + +**Input:** nums = [9], maxOperations = 2 + +**Output:** 3 + +**Explanation:** + +- Divide the bag with 9 balls into two bags of sizes 6 and 3. [**9**] -> [6,3]. + +- Divide the bag with 6 balls into two bags of sizes 3 and 3. [**6**,3] -> [3,3,3]. The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3. + +**Example 2:** + +**Input:** nums = [2,4,8,2], maxOperations = 4 + +**Output:** 2 + +**Explanation:** + +- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,**8**,2] -> [2,4,4,4,2]. + +- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,**4**,4,4,2] -> [2,2,2,4,4,2]. + +- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,**4**,4,2] -> [2,2,2,2,2,4,2]. + +- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,**4**,2] -> [2,2,2,2,2,2,2,2]. The bag with the most number of balls has 2 balls, so your penalty is 2 an you should return 2. + +**Example 3:** + +**Input:** nums = [7,17], maxOperations = 2 + +**Output:** 7 + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= maxOperations, nums[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun minimumSize(nums: IntArray, maxOperations: Int): Int { + var left = 1 + var right = 1000000000 + while (left < right) { + val mid = left + (right - left) / 2 + if (operations(nums, mid) > maxOperations) { + left = mid + 1 + } else { + right = mid + } + } + return left + } + + private fun operations(nums: IntArray, mid: Int): Int { + var operations = 0 + for (num in nums) { + operations += (num - 1) / mid + } + return operations + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1761_minimum_degree_of_a_connected_trio_in_a_graph/readme.md b/src/main/kotlin/g1701_1800/s1761_minimum_degree_of_a_connected_trio_in_a_graph/readme.md new file mode 100644 index 00000000..e6a23b6d --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1761_minimum_degree_of_a_connected_trio_in_a_graph/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) + +## 1761\. Minimum Degree of a Connected Trio in a Graph + +Hard + +You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. + +A **connected trio** is a set of **three** nodes where there is an edge between **every** pair of them. + +The **degree of a connected trio** is the number of edges where one endpoint is in the trio, and the other is not. + +Return _the **minimum** degree of a connected trio in the graph, or_ `-1` _if the graph has no connected trios._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/01/26/trios1.png) + +**Input:** n = 6, edges = \[\[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]] + +**Output:** 3 + +**Explanation:** There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/01/26/trios2.png) + +**Input:** n = 7, edges = \[\[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]] + +**Output:** 0 + +**Explanation:** There are exactly three trios: + +1) [1,4,3] with degree 0. + +2) [2,5,6] with degree 2. + +3) [5,6,7] with degree 2. + +**Constraints:** + +* `2 <= n <= 400` +* `edges[i].length == 2` +* `1 <= edges.length <= n * (n-1) / 2` +* 1 <= ui, vi <= n +* ui != vi +* There are no repeated edges. + +## Solution + +```kotlin +class Solution { + fun minTrioDegree(n: Int, edges: Array): Int { + val degrees = IntArray(n + 1) + val adjMatrix = Array(n + 1) { IntArray(n + 1) } + for (edge in edges) { + adjMatrix[edge[0]][edge[1]] = 1 + adjMatrix[edge[1]][edge[0]] = 1 + degrees[edge[0]]++ + degrees[edge[1]]++ + } + var minTrios = Int.MAX_VALUE + for (i in 1..n) { + for (j in i + 1..n) { + if (adjMatrix[i][j] == 0) { + continue + } + for (k in j + 1..n) { + if (adjMatrix[j][k] == 0 || adjMatrix[i][k] == 0) { + continue + } + val trioDegree = degrees[i] + degrees[j] + degrees[k] - 6 + minTrios = Math.min(minTrios, trioDegree) + } + } + } + return if (minTrios == Int.MAX_VALUE) -1 else minTrios + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1763_longest_nice_substring/readme.md b/src/main/kotlin/g1701_1800/s1763_longest_nice_substring/readme.md new file mode 100644 index 00000000..d6a38c8c --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1763_longest_nice_substring/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) + +## 1763\. Longest Nice Substring + +Easy + +A string `s` is **nice** if, for every letter of the alphabet that `s` contains, it appears **both** in uppercase and lowercase. For example, `"abABB"` is nice because `'A'` and `'a'` appear, and `'B'` and `'b'` appear. However, `"abA"` is not because `'b'` appears, but `'B'` does not. + +Given a string `s`, return _the longest **substring** of `s` that is **nice**. If there are multiple, return the substring of the **earliest** occurrence. If there are none, return an empty string_. + +**Example 1:** + +**Input:** s = "YazaAay" + +**Output:** "aAa" + +**Explanation:** "aAa" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear. "aAa" is the longest nice substring. + +**Example 2:** + +**Input:** s = "Bb" + +**Output:** "Bb" + +**Explanation:** "Bb" is a nice string because both 'B' and 'b' appear. The whole string is a substring. + +**Example 3:** + +**Input:** s = "c" + +**Output:** "" + +**Explanation:** There are no nice substrings. + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` consists of uppercase and lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun longestNiceSubstring(s: String): String { + val index = isNotNiceString(s) + if (index == -1) { + return s + } + val left = longestNiceSubstring(s.substring(0, index)) + val right = longestNiceSubstring(s.substring(index + 1)) + return if (left.length >= right.length) left else right + } + + private fun isNotNiceString(s: String): Int { + val set: MutableSet = HashSet() + for (c in s.toCharArray()) { + set.add(c) + } + for (i in 0 until s.length) { + val c = s[i] + if (!set.contains(c.lowercaseChar()) || + !set.contains(c.uppercaseChar()) + ) { + return i + } + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1764_form_array_by_concatenating_subarrays_of_another_array/readme.md b/src/main/kotlin/g1701_1800/s1764_form_array_by_concatenating_subarrays_of_another_array/readme.md new file mode 100644 index 00000000..b2bfee36 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1764_form_array_by_concatenating_subarrays_of_another_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) + +## 1764\. Form Array by Concatenating Subarrays of Another Array + +Medium + +You are given a 2D integer array `groups` of length `n`. You are also given an integer array `nums`. + +You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the ith subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, the (i-1)th subarray appears **before** the ith subarray in `nums` (i.e. the subarrays must be in the same order as `groups`). + +Return `true` _if you can do this task, and_ `false` _otherwise_. + +Note that the subarrays are **disjoint** if and only if there is no index `k` such that `nums[k]` belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array. + +**Example 1:** + +**Input:** groups = \[\[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0] + +**Output:** true + +**Explanation:** You can choose the 0th subarray as [1,-1,0,**1,-1,-1**,3,-2,0] and the 1st one as [1,-1,0,1,-1,-1,**3,-2,0**]. These subarrays are disjoint as they share no common nums[k] element. + +**Example 2:** + +**Input:** groups = \[\[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2] + +**Output:** false + +**Explanation:** Note that choosing the subarrays [**1,2,3,4**,10,-2] and [1,2,3,4,**10,-2**] is incorrect because they are not in the same order as in groups. [10,-2] must come before [1,2,3,4]. + +**Example 3:** + +**Input:** groups = \[\[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7] + +**Output:** false + +**Explanation:** Note that choosing the subarrays [7,7,**1,2,3**,4,7,7] and [7,7,1,2,**3,4**,7,7] is invalid because they are not disjoint. They share a common elements nums[4] (0-indexed). + +**Constraints:** + +* `groups.length == n` +* 1 <= n <= 103 +* 1 <= groups[i].length, sum(groups[i].length) <= 103 +* 1 <= nums.length <= 103 +* -107 <= groups[i][j], nums[k] <= 107 + +## Solution + +```kotlin +class Solution { + fun canChoose(groups: Array, nums: IntArray): Boolean { + var prev = 0 + for (i in groups.indices) { + val temp = IntArray(groups[i].size) + if (prev + groups[i].size > nums.size) { + return false + } + var index = 0 + var j: Int + j = prev + while (j < prev + groups[i].size) { + temp[index++] = nums[j] + j++ + } + if (temp.contentEquals(groups[i])) { + prev = j + continue + } + var k: Int = j + while (k < nums.size) { + var l: Int + l = 0 + while (l < temp.size - 1) { + temp[l] = temp[l + 1] + l++ + } + temp[l] = nums[k] + if (temp.contentEquals(groups[i])) { + prev = k + 1 + break + } + k++ + } + if (k == nums.size) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1765_map_of_highest_peak/readme.md b/src/main/kotlin/g1701_1800/s1765_map_of_highest_peak/readme.md new file mode 100644 index 00000000..d6f4fa0b --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1765_map_of_highest_peak/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) + +## 1765\. Map of Highest Peak + +Medium + +You are given an integer matrix `isWater` of size `m x n` that represents a map of **land** and **water** cells. + +* If `isWater[i][j] == 0`, cell `(i, j)` is a **land** cell. +* If `isWater[i][j] == 1`, cell `(i, j)` is a **water** cell. + +You must assign each cell a height in a way that follows these rules: + +* The height of each cell must be non-negative. +* If the cell is a **water** cell, its height must be `0`. +* Any two adjacent cells must have an absolute height difference of **at most** `1`. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). + +Find an assignment of heights such that the maximum height in the matrix is **maximized**. + +Return _an integer matrix_ `height` _of size_ `m x n` _where_ `height[i][j]` _is cell_ `(i, j)`_'s height. If there are multiple solutions, return **any** of them_. + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82045-am.png)** + +**Input:** isWater = \[\[0,1],[0,0]] + +**Output:** [[1,0],[2,1]] + +**Explanation:** The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82050-am.png)** + +**Input:** isWater = \[\[0,0,1],[1,0,0],[0,0,0]] + +**Output:** [[1,1,0],[0,1,1],[1,2,2]] + +**Explanation:** A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted. + +**Constraints:** + +* `m == isWater.length` +* `n == isWater[i].length` +* `1 <= m, n <= 1000` +* `isWater[i][j]` is `0` or `1`. +* There is at least **one** water cell. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + private val dir = intArrayOf(0, 1, 0, -1, 0) + + fun highestPeak(isWater: Array): Array { + var h = 1 + var q: Queue = LinkedList() + for (i in isWater.indices) { + for (j in isWater[0].indices) { + isWater[i][j] = if (isWater[i][j] == 1) 0 else -1 + if (isWater[i][j] == 0) { + q.add(intArrayOf(i, j)) + } + } + } + while (q.isNotEmpty()) { + val q1: Queue = LinkedList() + for (cur in q) { + val x = cur[0] + val y = cur[1] + for (i in 0..3) { + val nx = x + dir[i] + val ny = y + dir[i + 1] + if (nx >= 0 && nx < isWater.size && ny >= 0 && ny < isWater[0].size && isWater[nx][ny] == -1) { + isWater[nx][ny] = h + q1.add(intArrayOf(nx, ny)) + } + } + } + h++ + q = q1 + } + return isWater + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1766_tree_of_coprimes/readme.md b/src/main/kotlin/g1701_1800/s1766_tree_of_coprimes/readme.md new file mode 100644 index 00000000..b40689d2 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1766_tree_of_coprimes/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) + +## 1766\. Tree of Coprimes + +Hard + +There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` edges. Each node has a value associated with it, and the **root** of the tree is node `0`. + +To represent this tree, you are given an integer array `nums` and a 2D array `edges`. Each `nums[i]` represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree. + +Two values `x` and `y` are **coprime** if `gcd(x, y) == 1` where `gcd(x, y)` is the **greatest common divisor** of `x` and `y`. + +An ancestor of a node `i` is any other node on the shortest path from node `i` to the **root**. A node is **not** considered an ancestor of itself. + +Return _an array_ `ans` _of size_ `n`, _where_ `ans[i]` _is the closest ancestor to node_ `i` _such that_ `nums[i]` _and_ `nums[ans[i]]` are **coprime**, or `-1` _if there is no such ancestor_. + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2021/01/06/untitled-diagram.png)** + +**Input:** nums = [2,3,3,2], edges = \[\[0,1],[1,2],[1,3]] + +**Output:** [-1,0,0,1] + +**Explanation:** In the above figure, each node's value is in parentheses. + +- Node 0 has no coprime ancestors. + +- Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1). - Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor. + +- Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its closest valid ancestor. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/01/06/untitled-diagram1.png) + +**Input:** nums = [5,6,10,2,3,6,15], edges = \[\[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]] + +**Output:** [-1,0,-1,0,0,0,-1] + +**Constraints:** + +* `nums.length == n` +* `1 <= nums[i] <= 50` +* 1 <= n <= 105 +* `edges.length == n - 1` +* `edges[j].length == 2` +* 0 <= uj, vj < n +* uj != vj + +## Solution + +```kotlin +@Suppress("kotlin:S107") +class Solution { + private fun dfs( + v2n: IntArray, + v2d: IntArray, + depth: Int, + parent: Int, + node: Int, + ans: IntArray, + nums: IntArray, + neighbors: Array> + ) { + var d = Int.MIN_VALUE + var n = -1 + val v = nums[node] + for (i in 1..50) { + if (v2n[i] != -1 && v2d[i] > d && gcd(i, v) == 1) { + d = v2d[i] + n = v2n[i] + } + } + ans[node] = n + val v2NOld = v2n[v] + val v2DOld = v2d[v] + v2n[v] = node + v2d[v] = depth + for (child in neighbors[node]) { + if (child == parent) { + continue + } + dfs(v2n, v2d, depth + 1, node, child, ans, nums, neighbors) + } + v2n[v] = v2NOld + v2d[v] = v2DOld + } + + private fun gcd(x: Int, y: Int): Int { + return if (x == 0) y else gcd(y % x, x) + } + + fun getCoprimes(nums: IntArray, edges: Array): IntArray { + val n = nums.size + val neighbors: Array> = Array(n) { ArrayList() } + for (i in 0 until n) { + neighbors[i] = ArrayList() + } + for (edge in edges) { + neighbors[edge[0]].add(edge[1]) + neighbors[edge[1]].add(edge[0]) + } + val ans = IntArray(n) + val v2n = IntArray(51) + val v2d = IntArray(51) + v2n.fill(-1) + dfs(v2n, v2d, 0, -1, 0, ans, nums, neighbors) + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1768_merge_strings_alternately/readme.md b/src/main/kotlin/g1701_1800/s1768_merge_strings_alternately/readme.md new file mode 100644 index 00000000..640e054b --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1768_merge_strings_alternately/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) + +## 1768\. Merge Strings Alternately + +Easy + +You are given two strings `word1` and `word2`. Merge the strings by adding letters in alternating order, starting with `word1`. If a string is longer than the other, append the additional letters onto the end of the merged string. + +Return _the merged string._ + +**Example 1:** + +**Input:** word1 = "abc", word2 = "pqr" + +**Output:** "apbqcr" + +**Explanation:** The merged string will be merged as so: + +word1: a b c + +word2: p q r + +merged: a p b q c r + +**Example 2:** + +**Input:** word1 = "ab", word2 = "pqrs" + +**Output:** "apbqrs" + +**Explanation:** Notice that as word2 is longer, "rs" is appended to the end. + +word1: a b + +word2: p q r s + +merged: a p b q r s + +**Example 3:** + +**Input:** word1 = "abcd", word2 = "pq" + +**Output:** "apbqcd" + +**Explanation:** Notice that as word1 is longer, "cd" is appended to the end. + +word1: a b c d + +word2: p q + +merged: a p b q c d + +**Constraints:** + +* `1 <= word1.length, word2.length <= 100` +* `word1` and `word2` consist of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun mergeAlternately(word1: String, word2: String): String { + val size1 = word1.length + val size2 = word2.length + val min = Math.min(size1, size2) + val sb = StringBuilder() + for (i in 0 until min) { + sb.append(word1[i]) + sb.append(word2[i]) + } + if (min == size1) { + sb.append(word2, size1, size2) + } + if (min == size2) { + sb.append(word1, size2, size1) + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1769_minimum_number_of_operations_to_move_all_balls_to_each_box/readme.md b/src/main/kotlin/g1701_1800/s1769_minimum_number_of_operations_to_move_all_balls_to_each_box/readme.md new file mode 100644 index 00000000..a9c74c98 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1769_minimum_number_of_operations_to_move_all_balls_to_each_box/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) + +## 1769\. Minimum Number of Operations to Move All Balls to Each Box + +Medium + +You have `n` boxes. You are given a binary string `boxes` of length `n`, where `boxes[i]` is `'0'` if the ith box is **empty**, and `'1'` if it contains **one** ball. + +In one operation, you can move **one** ball from a box to an adjacent box. Box `i` is adjacent to box `j` if `abs(i - j) == 1`. Note that after doing so, there may be more than one ball in some boxes. + +Return an array `answer` of size `n`, where `answer[i]` is the **minimum** number of operations needed to move all the balls to the ith box. + +Each `answer[i]` is calculated considering the **initial** state of the boxes. + +**Example 1:** + +**Input:** boxes = "110" + +**Output:** [1,1,3] + +**Explanation:** The answer for each box is as follows: + +1) First box: you will have to move one ball from the second box to the first box in one operation. + +2) Second box: you will have to move one ball from the first box to the second box in one operation. + +3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation. + +**Example 2:** + +**Input:** boxes = "001011" + +**Output:** [11,8,5,4,3,4] + +**Constraints:** + +* `n == boxes.length` +* `1 <= n <= 2000` +* `boxes[i]` is either `'0'` or `'1'`. + +## Solution + +```kotlin +class Solution { + fun minOperations(boxes: String): IntArray { + var countFromLeft = 0 + var countFromRight = 0 + var moves = 0 + val result = IntArray(boxes.length) + for (c in boxes.toCharArray()) { + moves += countFromLeft + if (c == '1') { + countFromLeft++ + } + } + for (i in boxes.length - 1 downTo 0) { + val c = boxes[i] + result[i] = moves + if (c == '1') { + countFromLeft-- + countFromRight++ + } + moves -= countFromLeft + moves += countFromRight + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1770_maximum_score_from_performing_multiplication_operations/readme.md b/src/main/kotlin/g1701_1800/s1770_maximum_score_from_performing_multiplication_operations/readme.md new file mode 100644 index 00000000..8059fe37 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1770_maximum_score_from_performing_multiplication_operations/readme.md @@ -0,0 +1,84 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1770\. Maximum Score from Performing Multiplication Operations + +Medium + +You are given two integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`. The arrays are **1-indexed**. + +You begin with a score of `0`. You want to perform **exactly** `m` operations. On the ith operation **(1-indexed)**, you will: + +* Choose one integer `x` from **either the start or the end** of the array `nums`. +* Add `multipliers[i] * x` to your score. +* Remove `x` from the array `nums`. + +Return _the **maximum** score after performing_ `m` _operations._ + +**Example 1:** + +**Input:** nums = [1,2,3], multipliers = [3,2,1] + +**Output:** 14 + +**Explanation:** An optimal solution is as follows: + +- Choose from the end, [1,2,**3**], adding 3 \* 3 = 9 to the score. + +- Choose from the end, [1,**2**], adding 2 \* 2 = 4 to the score. + +- Choose from the end, [**1**], adding 1 \* 1 = 1 to the score. + +The total score is 9 + 4 + 1 = 14. + +**Example 2:** + +**Input:** nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6] + +**Output:** 102 + +**Explanation:** An optimal solution is as follows: + +- Choose from the start, [**\-5**,-3,-3,-2,7,1], adding -5 \* -10 = 50 to the score. + +- Choose from the start, [**\-3**,-3,-2,7,1], adding -3 \* -5 = 15 to the score. + +- Choose from the start, [**\-3**,-2,7,1], adding -3 \* 3 = -9 to the score. + +- Choose from the end, [-2,7,**1**], adding 1 \* 4 = 4 to the score. + +- Choose from the end, [-2,**7**], adding 7 \* 6 = 42 to the score. + +The total score is 50 + 15 - 9 + 4 + 42 = 102. + +**Constraints:** + +* `n == nums.length` +* `m == multipliers.length` +* 1 <= m <= 103 +* m <= n <= 105 +* `-1000 <= nums[i], multipliers[i] <= 1000` + +## Solution + +```kotlin +class Solution { + fun maximumScore(nums: IntArray, multipliers: IntArray): Int { + val n = nums.size + val m = multipliers.size + var row = m + val dp = IntArray(m) + var prev = IntArray(m + 1) + while (--row >= 0) { + for (i in 0..row) { + dp[i] = Math.max( + prev[i] + multipliers[row] * nums[n - row + i - 1], + prev[i + 1] + multipliers[row] * nums[i] + ) + } + prev = dp + } + return dp[0] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1771_maximize_palindrome_length_from_subsequences/readme.md b/src/main/kotlin/g1701_1800/s1771_maximize_palindrome_length_from_subsequences/readme.md new file mode 100644 index 00000000..2b760282 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1771_maximize_palindrome_length_from_subsequences/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) + +## 1771\. Maximize Palindrome Length From Subsequences + +Hard + +You are given two strings, `word1` and `word2`. You want to construct a string in the following manner: + +* Choose some **non-empty** subsequence `subsequence1` from `word1`. +* Choose some **non-empty** subsequence `subsequence2` from `word2`. +* Concatenate the subsequences: `subsequence1 + subsequence2`, to make the string. + +Return _the **length** of the longest **palindrome** that can be constructed in the described manner._ If no palindromes can be constructed, return `0`. + +A **subsequence** of a string `s` is a string that can be made by deleting some (possibly none) characters from `s` without changing the order of the remaining characters. + +A **palindrome** is a string that reads the same forward as well as backward. + +**Example 1:** + +**Input:** word1 = "cacb", word2 = "cbba" + +**Output:** 5 + +**Explanation:** Choose "ab" from word1 and "cba" from word2 to make "abcba", which is a palindrome. + +**Example 2:** + +**Input:** word1 = "ab", word2 = "ab" + +**Output:** 3 + +**Explanation:** Choose "ab" from word1 and "a" from word2 to make "aba", which is a palindrome. + +**Example 3:** + +**Input:** word1 = "aa", word2 = "bb" + +**Output:** 0 + +**Explanation:** You cannot construct a palindrome from the described method, so return 0. + +**Constraints:** + +* `1 <= word1.length, word2.length <= 1000` +* `word1` and `word2` consist of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun longestPalindrome(word1: String, word2: String): Int { + val len1 = word1.length + val len2 = word2.length + val len = len1 + len2 + val word = word1 + word2 + val dp = Array(len) { IntArray(len) } + var max = 0 + val arr = word.toCharArray() + for (d in 1..len) { + var i = 0 + while (i + d - 1 < len) { + if (arr[i] == arr[i + d - 1]) { + dp[i][i + d - 1] = if (d == 1) 1 else Math.max(dp[i + 1][i + d - 2] + 2, dp[i][i + d - 1]) + if (i < len1 && i + d - 1 >= len1) { + max = Math.max(max, dp[i][i + d - 1]) + } + } else { + dp[i][i + d - 1] = Math.max(dp[i + 1][i + d - 1], dp[i][i + d - 2]) + } + i++ + } + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1773_count_items_matching_a_rule/readme.md b/src/main/kotlin/g1701_1800/s1773_count_items_matching_a_rule/readme.md new file mode 100644 index 00000000..e5875820 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1773_count_items_matching_a_rule/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) + +## 1773\. Count Items Matching a Rule + +Easy + +You are given an array `items`, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, `ruleKey` and `ruleValue`. + +The ith item is said to match the rule if **one** of the following is true: + +* `ruleKey == "type"` and ruleValue == typei. +* `ruleKey == "color"` and ruleValue == colori. +* `ruleKey == "name"` and ruleValue == namei. + +Return _the number of items that match the given rule_. + +**Example 1:** + +**Input:** items = \[\["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver" + +**Output:** 1 + +**Explanation:** There is only one item matching the given rule, which is ["computer","silver","lenovo"]. + +**Example 2:** + +**Input:** items = \[\["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone" + +**Output:** 2 + +**Explanation:** There are only two items matching the given rule, which are ["phone","blue","pixel"] and ["phone","gold","iphone"]. Note that the item ["computer","silver","phone"] does not match. + +**Constraints:** + +* 1 <= items.length <= 104 +* 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10 +* `ruleKey` is equal to either `"type"`, `"color"`, or `"name"`. +* All strings consist only of lowercase letters. + +## Solution + +```kotlin +class Solution { + fun countMatches(items: List>, ruleKey: String, ruleValue: String): Int { + var ans = 0 + var checkRuleNum = 0 + if (ruleKey == "color") { + checkRuleNum = 1 + } else if (ruleKey == "name") { + checkRuleNum = 2 + } + for (item in items) { + if (item[checkRuleNum] == ruleValue) { + ans++ + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1774_closest_dessert_cost/readme.md b/src/main/kotlin/g1701_1800/s1774_closest_dessert_cost/readme.md new file mode 100644 index 00000000..622ec143 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1774_closest_dessert_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) + +## 1774\. Closest Dessert Cost + +Medium + +You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert: + +* There must be **exactly one** ice cream base. +* You can add **one or more** types of topping or have no toppings at all. +* There are **at most two** of **each type** of topping. + +You are given three inputs: + +* `baseCosts`, an integer array of length `n`, where each `baseCosts[i]` represents the price of the ith ice cream base flavor. +* `toppingCosts`, an integer array of length `m`, where each `toppingCosts[i]` is the price of **one** of the ith topping. +* `target`, an integer representing your target price for dessert. + +You want to make a dessert with a total cost as close to `target` as possible. + +Return _the closest possible cost of the dessert to_ `target`. If there are multiple, return _the **lower** one._ + +**Example 1:** + +**Input:** baseCosts = [1,7], toppingCosts = [3,4], target = 10 + +**Output:** 10 + +**Explanation:** Consider the following combination (all 0-indexed): + +- Choose base 1: cost 7 + +- Take 1 of topping 0: cost 1 x 3 = 3 + +- Take 0 of topping 1: cost 0 x 4 = 0 + +Total: 7 + 3 + 0 = 10. + +**Example 2:** + +**Input:** baseCosts = [2,3], toppingCosts = [4,5,100], target = 18 + +**Output:** 17 + +**Explanation:** Consider the following combination (all 0-indexed): - Choose base 1: cost 3 - Take 1 of topping 0: cost 1 x 4 = 4 - Take 2 of topping 1: cost 2 x 5 = 10 - Take 0 of topping 2: cost 0 x 100 = 0 Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18. + +**Example 3:** + +**Input:** baseCosts = [3,10], toppingCosts = [2,5], target = 9 + +**Output:** 8 + +**Explanation:** It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost. + +**Constraints:** + +* `n == baseCosts.length` +* `m == toppingCosts.length` +* `1 <= n, m <= 10` +* 1 <= baseCosts[i], toppingCosts[i] <= 104 +* 1 <= target <= 104 + +## Solution + +```kotlin +class Solution { + private var finalValue = Int.MAX_VALUE + + fun closestCost(baseCosts: IntArray, toppingCosts: IntArray, target: Int): Int { + for (baseCost in baseCosts) { + closestCost(baseCost, toppingCosts, target, 0) + } + return finalValue + } + + private fun closestCost(curCost: Int, toppingCosts: IntArray, target: Int, index: Int) { + if (index >= toppingCosts.size || curCost >= target) { + if (Math.abs(target - curCost) < Math.abs(target - finalValue)) { + finalValue = curCost + } else if (Math.abs(target - curCost) == Math.abs(target - finalValue) && + target < finalValue + ) { + finalValue = curCost + } + return + } + closestCost(curCost, toppingCosts, target, index + 1) + closestCost(curCost + toppingCosts[index], toppingCosts, target, index + 1) + closestCost(curCost + toppingCosts[index] * 2, toppingCosts, target, index + 1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1775_equal_sum_arrays_with_minimum_number_of_operations/readme.md b/src/main/kotlin/g1701_1800/s1775_equal_sum_arrays_with_minimum_number_of_operations/readme.md new file mode 100644 index 00000000..b0572cba --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1775_equal_sum_arrays_with_minimum_number_of_operations/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) + +## 1775\. Equal Sum Arrays With Minimum Number of Operations + +Medium + +You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive. + +In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive. + +Return _the minimum number of operations required to make the sum of values in_ `nums1` _equal to the sum of values in_ `nums2`_._ Return `-1` if it is not possible to make the sum of the two arrays equal. + +**Example 1:** + +**Input:** nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2] + +**Output:** 3 + +**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. + +- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [**6**,1,2,2,2,2]. + +- Change nums1[5] to 1. nums1 = [1,2,3,4,5,**1**], nums2 = [6,1,2,2,2,2]. + +- Change nums1[2] to 2. nums1 = [1,2,**2**,4,5,1], nums2 = [6,1,2,2,2,2]. + +**Example 2:** + +**Input:** nums1 = [1,1,1,1,1,1,1], nums2 = [6] + +**Output:** -1 + +**Explanation:** There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal. + +**Example 3:** + +**Input:** nums1 = [6,6], nums2 = [1] + +**Output:** 3 + +**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. + +- Change nums1[0] to 2. nums1 = [**2**,6], nums2 = [1]. + +- Change nums1[1] to 2. nums1 = [2,**2**], nums2 = [1]. + +- Change nums2[0] to 4. nums1 = [2,2], nums2 = [**4**]. + +**Constraints:** + +* 1 <= nums1.length, nums2.length <= 105 +* `1 <= nums1[i], nums2[i] <= 6` + +## Solution + +```kotlin +class Solution { + fun minOperations(nums1: IntArray, nums2: IntArray): Int { + val longer = if (nums1.size > nums2.size) nums1 else nums2 + val shorter = if (nums1.size > nums2.size) nums2 else nums1 + if (longer.size > shorter.size * 6) { + return -1 + } + longer.sort() + shorter.sort() + var i = 0 + var j = 0 + var diff = 0 + while (i < longer.size || j < shorter.size) { + if (i < longer.size) { + diff += longer[i++] + } + if (j < shorter.size) { + diff -= shorter[j++] + } + } + var minOps = 0 + i = 0 + j = shorter.size - 1 + return if (diff < 0) { + while (diff < 0) { + diff += if (i < longer.size && j >= 0) { + if (6 - longer[i] < shorter[j] - 1) { + shorter[j--] - 1 + } else { + 6 - longer[i++] + } + } else if (i < longer.size) { + 6 - longer[i++] + } else { + shorter[j--] - 1 + } + minOps++ + } + minOps + } else if (diff > 0) { + i = longer.size - 1 + j = 0 + while (diff > 0) { + diff -= if (i >= 0 && j < shorter.size) { + if (longer[i] - 1 > 6 - shorter[j]) { + longer[i--] - 1 + } else { + 6 - shorter[j++] + } + } else if (i >= 0) { + longer[i--] - 1 + } else { + 6 - shorter[j++] + } + minOps++ + } + minOps + } else { + minOps + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1776_car_fleet_ii/readme.md b/src/main/kotlin/g1701_1800/s1776_car_fleet_ii/readme.md new file mode 100644 index 00000000..464f46ec --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1776_car_fleet_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) + +## 1776\. Car Fleet II + +Hard + +There are `n` cars traveling at different speeds in the same direction along a one-lane road. You are given an array `cars` of length `n`, where cars[i] = [positioni, speedi] represents: + +* positioni is the distance between the ith car and the beginning of the road in meters. It is guaranteed that positioni < positioni+1. +* speedi is the initial speed of the ith car in meters per second. + +For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the **slowest** car in the fleet. + +Return an array `answer`, where `answer[i]` is the time, in seconds, at which the ith car collides with the next car, or `-1` if the car does not collide with the next car. Answers within 10-5 of the actual answers are accepted. + +**Example 1:** + +**Input:** cars = \[\[1,2],[2,1],[4,3],[7,2]] + +**Output:** [1.00000,-1.00000,3.00000,-1.00000] + +**Explanation:** After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s. + +**Example 2:** + +**Input:** cars = \[\[3,4],[5,4],[6,3],[9,1]] + +**Output:** [2.00000,1.00000,1.50000,-1.00000] + +**Constraints:** + +* 1 <= cars.length <= 105 +* 1 <= positioni, speedi <= 106 +* positioni < positioni+1 + +## Solution + +```kotlin +import java.util.Deque +import java.util.LinkedList + +class Solution { + fun getCollisionTimes(cars: Array): DoubleArray { + val stack: Deque = LinkedList() + val n = cars.size + val ans = DoubleArray(n) + for (i in n - 1 downTo 0) { + ans[i] = -1.0 + val presentCar = cars[i] + val presentCarSpeed = presentCar[1] + while (stack.isNotEmpty()) { + val previousCar = stack.peekLast() + val previousCarSpeed = cars[previousCar][1] + if (presentCarSpeed > previousCarSpeed && + ( + ans[previousCar] == -1.0 || + catchTime(cars, i, previousCar) <= ans[previousCar] + ) + ) { + ans[i] = catchTime(cars, i, previousCar) + break + } + stack.pollLast() + } + stack.offerLast(i) + } + return ans + } + + private fun catchTime(cars: Array, presentCar: Int, previousCar: Int): Double { + val dist = cars[previousCar][0] - cars[presentCar][0] + val speed = cars[presentCar][1] - cars[previousCar][1] + return 1.0 * dist / speed + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1779_find_nearest_point_that_has_the_same_x_or_y_coordinate/readme.md b/src/main/kotlin/g1701_1800/s1779_find_nearest_point_that_has_the_same_x_or_y_coordinate/readme.md new file mode 100644 index 00000000..618e582b --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1779_find_nearest_point_that_has_the_same_x_or_y_coordinate/readme.md @@ -0,0 +1,64 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1779\. Find Nearest Point That Has the Same X or Y Coordinate + +Easy + +You are given two integers, `x` and `y`, which represent your current location on a Cartesian grid: `(x, y)`. You are also given an array `points` where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is **valid** if it shares the same x-coordinate or the same y-coordinate as your location. + +Return _the index **(0-indexed)** of the **valid** point with the smallest **Manhattan distance** from your current location_. If there are multiple, return _the valid point with the **smallest** index_. If there are no valid points, return `-1`. + +The **Manhattan distance** between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2). + +**Example 1:** + +**Input:** x = 3, y = 4, points = \[\[1,2],[3,1],[2,4],[2,3],[4,4]] + +**Output:** 2 + +**Explanation:** Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2. + +**Example 2:** + +**Input:** x = 3, y = 4, points = \[\[3,4]] + +**Output:** 0 + +**Explanation:** The answer is allowed to be on the same location as your current location. + +**Example 3:** + +**Input:** x = 3, y = 4, points = \[\[2,3]] + +**Output:** -1 + +**Explanation:** There are no valid points. + +**Constraints:** + +* 1 <= points.length <= 104 +* `points[i].length == 2` +* 1 <= x, y, ai, bi <= 104 + +## Solution + +```kotlin +class Solution { + fun nearestValidPoint(x: Int, y: Int, points: Array): Int { + var nearestManDistance = Int.MAX_VALUE + var result = -1 + for (i in points.indices) { + val point = points[i] + if (point[0] == x || point[1] == y) { + val distance = Math.abs(point[0] - x) + Math.abs(point[1] - y) + if (distance < nearestManDistance) { + result = i + nearestManDistance = distance + } + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1780_check_if_number_is_a_sum_of_powers_of_three/readme.md b/src/main/kotlin/g1701_1800/s1780_check_if_number_is_a_sum_of_powers_of_three/readme.md new file mode 100644 index 00000000..57585953 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1780_check_if_number_is_a_sum_of_powers_of_three/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) + +## 1780\. Check if Number is a Sum of Powers of Three + +Medium + +Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`. + +An integer `y` is a power of three if there exists an integer `x` such that y == 3x. + +**Example 1:** + +**Input:** n = 12 + +**Output:** true + +**Explanation:** 12 = 31 + 32 + +**Example 2:** + +**Input:** n = 91 + +**Output:** true + +**Explanation:** 91 = 30 + 32 + 34 + +**Example 3:** + +**Input:** n = 21 + +**Output:** false + +**Constraints:** + +* 1 <= n <= 107 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun checkPowersOfThree(n: Int): Boolean { + var n = n + while (n != 0) { + val rem = n % 3 + n /= 3 + if (rem == 2 || n == 2) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1781_sum_of_beauty_of_all_substrings/readme.md b/src/main/kotlin/g1701_1800/s1781_sum_of_beauty_of_all_substrings/readme.md new file mode 100644 index 00000000..6c0447ca --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1781_sum_of_beauty_of_all_substrings/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) + +## 1781\. Sum of Beauty of All Substrings + +Medium + +The **beauty** of a string is the difference in frequencies between the most frequent and least frequent characters. + +* For example, the beauty of `"abaacc"` is `3 - 1 = 2`. + +Given a string `s`, return _the sum of **beauty** of all of its substrings._ + +**Example 1:** + +**Input:** s = "aabcb" + +**Output:** 5 + +**Explanation:** The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1. + +**Example 2:** + +**Input:** s = "aabcbaa" + +**Output:** 17 + +**Constraints:** + +* `1 <= s.length <= 500` +* `s` consists of only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun beautySum(s: String): Int { + var beauty = 0 + for (i in s.indices) { + val numCountOfFreq = IntArray(s.length + 1 - i) + val charFreq = IntArray(26) + charFreq[s[i].code - 'a'.code] = 1 + numCountOfFreq[1] = 1 + var min = 1 + var max = 1 + for (j in i + 1 until s.length) { + val c = s[j] + charFreq[c.code - 'a'.code]++ + val freq = charFreq[c.code - 'a'.code] + numCountOfFreq[freq - 1]-- + numCountOfFreq[freq]++ + if (numCountOfFreq[min] == 0) { + min++ + } + if (min > freq) { + min = freq + } + if (max < freq) { + max = freq + } + beauty += max - min + } + } + return beauty + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1782_count_pairs_of_nodes/readme.md b/src/main/kotlin/g1701_1800/s1782_count_pairs_of_nodes/readme.md new file mode 100644 index 00000000..cebbe89d --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1782_count_pairs_of_nodes/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) + +## 1782\. Count Pairs Of Nodes + +Hard + +You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where edges[i] = [ui, vi] indicates that there is an **undirected** edge between ui and vi. You are also given an integer array `queries`. + +Let `incident(a, b)` be defined as the **number of edges** that are connected to **either** node `a` or `b`. + +The answer to the jth query is the **number of pairs** of nodes `(a, b)` that satisfy **both** of the following conditions: + +* `a < b` +* `incident(a, b) > queries[j]` + +Return _an array_ `answers` _such that_ `answers.length == queries.length` _and_ `answers[j]` _is the answer of the_ jth _query_. + +Note that there can be **multiple edges** between the same two nodes. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/06/08/winword_2021-06-08_00-58-39.png) + +**Input:** n = 4, edges = \[\[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3] + +**Output:** [6,5] + +**Explanation:** The calculations for incident(a, b) are shown in the table above. The answers for each of the queries are as follows: + +- answers[0] = 6. All the pairs have an incident(a, b) value greater than 2. + +- answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3. + +**Example 2:** + +**Input:** n = 5, edges = \[\[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5] + +**Output:** [10,10,9,8,6] + +**Constraints:** + +* 2 <= n <= 2 * 104 +* 1 <= edges.length <= 105 +* 1 <= ui, vi <= n +* ui != vi +* `1 <= queries.length <= 20` +* `0 <= queries[j] < edges.length` + +## Solution + +```kotlin +class Solution { + fun countPairs(n: Int, edges: Array, queries: IntArray): IntArray { + val edgeCount: MutableMap = HashMap() + val degree = IntArray(n) + for (e in edges) { + val u = e[0] - 1 + val v = e[1] - 1 + degree[u]++ + degree[v]++ + val eId = Math.min(u, v) * n + Math.max(u, v) + edgeCount[eId] = edgeCount.getOrDefault(eId, 0) + 1 + } + val degreeCount: MutableMap = HashMap() + var maxDegree = 0 + for (d in degree) { + degreeCount[d] = degreeCount.getOrDefault(d, 0) + 1 + maxDegree = Math.max(maxDegree, d) + } + val count = IntArray(2 * maxDegree + 1) + for (d1 in degreeCount.entries) { + for (d2 in degreeCount.entries) { + count[d1.key + d2.key] += if (d1 === d2) d1.value * (d1.value - 1) else d1.value * d2.value + } + } + for (i in count.indices) { + count[i] /= 2 + } + for ((key, value) in edgeCount) { + val u = key / n + val v = key % n + count[degree[u] + degree[v]]-- + count[degree[u] + degree[v] - value]++ + } + for (i in count.size - 2 downTo 0) { + count[i] += count[i + 1] + } + val res = IntArray(queries.size) + for (q in queries.indices) { + res[q] = if (queries[q] + 1 >= count.size) 0 else count[queries[q] + 1] + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1784_check_if_binary_string_has_at_most_one_segment_of_ones/readme.md b/src/main/kotlin/g1701_1800/s1784_check_if_binary_string_has_at_most_one_segment_of_ones/readme.md new file mode 100644 index 00000000..7a0c66a8 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1784_check_if_binary_string_has_at_most_one_segment_of_ones/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) + +## 1784\. Check if Binary String Has at Most One Segment of Ones + +Easy + +Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`. + +**Example 1:** + +**Input:** s = "1001" + +**Output:** false + +**Explanation:** The ones do not form a contiguous segment. + +**Example 2:** + +**Input:** s = "110" + +**Output:** true + +**Constraints:** + +* `1 <= s.length <= 100` +* `s[i]` is either `'0'` or `'1'`. +* `s[0]` is `'1'`. + +## Solution + +```kotlin +class Solution { + fun checkOnesSegment(s: String): Boolean { + var metOne = false + var i = 0 + while (i < s.length) { + if (s[i] == '1' && metOne) { + return false + } + if (s[i] == '1') { + metOne = true + while (i < s.length && s[i] == '1') { + i++ + } + } + i++ + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1785_minimum_elements_to_add_to_form_a_given_sum/readme.md b/src/main/kotlin/g1701_1800/s1785_minimum_elements_to_add_to_form_a_given_sum/readme.md new file mode 100644 index 00000000..6d8d395e --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1785_minimum_elements_to_add_to_form_a_given_sum/readme.md @@ -0,0 +1,48 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1785\. Minimum Elements to Add to Form a Given Sum + +Medium + +You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`. + +Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal`. The array must maintain its property that `abs(nums[i]) <= limit`. + +Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise. + +**Example 1:** + +**Input:** nums = [1,-1,1], limit = 3, goal = -4 + +**Output:** 2 + +**Explanation:** You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4. + +**Example 2:** + +**Input:** nums = [1,-10,9,1], limit = 100, goal = 0 + +**Output:** 1 + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= limit <= 106 +* `-limit <= nums[i] <= limit` +* -109 <= goal <= 109 + +## Solution + +```kotlin +class Solution { + fun minElements(nums: IntArray, limit: Int, goal: Int): Int { + var sum: Long = 0 + for (num in nums) { + sum += num.toLong() + } + val diff = Math.abs(goal - sum) + return if (diff % limit == 0L) (diff / limit).toInt() else (diff / limit + 1).toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1786_number_of_restricted_paths_from_first_to_last_node/readme.md b/src/main/kotlin/g1701_1800/s1786_number_of_restricted_paths_from_first_to_last_node/readme.md new file mode 100644 index 00000000..06bc9282 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1786_number_of_restricted_paths_from_first_to_last_node/readme.md @@ -0,0 +1,130 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1786\. Number of Restricted Paths From First to Last Node + +Medium + +There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti. + +A path from node `start` to node `end` is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where `0 <= i <= k-1`. + +The distance of a path is the sum of the weights on the edges of the path. Let `distanceToLastNode(x)` denote the shortest distance of a path between node `n` and node `x`. A **restricted path** is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1) where `0 <= i <= k-1`. + +Return _the number of restricted paths from node_ `1` _to node_ `n`. Since that number may be too large, return it **modulo** 109 + 7. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex1.png) + +**Input:** n = 5, edges = \[\[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]] + +**Output:** 3 + +**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The three restricted paths are: + +1) 1 --> 2 --> 5 + +2) 1 --> 2 --> 3 --> 5 + +3) 1 --> 3 --> 5 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex22.png) + +**Input:** n = 7, edges = \[\[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]] + +**Output:** 1 + +**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The only restricted path is 1 --> 3 --> 7. + +**Constraints:** + +* 1 <= n <= 2 * 104 +* n - 1 <= edges.length <= 4 * 104 +* `edges[i].length == 3` +* 1 <= ui, vi <= n +* ui != vi +* 1 <= weighti <= 105 +* There is at most one edge between any two nodes. +* There is at least one path between any two nodes. + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + private class Pair(var v: Int, var cwt: Int) : Comparable { + override fun compareTo(other: Pair): Int { + return cwt - other.cwt + } + } + + private class Edge(var v: Int, var wt: Int) + + private lateinit var dtl: IntArray + private lateinit var dp: IntArray + + fun countRestrictedPaths(n: Int, edges: Array): Int { + val graph = buildGraph(n, edges) + val pq = PriorityQueue() + val vis = BooleanArray(n + 1) + dtl = IntArray(n + 1) + pq.add(Pair(n, 0)) + while (pq.isNotEmpty()) { + val rem = pq.remove() + if (vis[rem.v]) { + continue + } + dtl[rem.v] = rem.cwt + vis[rem.v] = true + for (edge in graph[rem.v]) { + if (!vis[edge.v]) { + pq.add(Pair(edge.v, rem.cwt + edge.wt)) + } + } + } + dp = IntArray(n + 1) + return dfs(graph, 1, BooleanArray(n + 1), n) + } + + private fun dfs(graph: List>, vtx: Int, vis: BooleanArray, n: Int): Int { + if (vtx == n) { + return 1 + } + var ans: Long = 0 + vis[vtx] = true + for (edge in graph[vtx]) { + if (!vis[edge.v] && dtl[edge.v] < dtl[vtx]) { + val x = dfs(graph, edge.v, vis, n) + ans = (ans + x) % M + } else if (dtl[edge.v] < dtl[vtx] && vis[edge.v]) { + ans = (ans + dp[edge.v]) % M + } + } + dp[vtx] = ans.toInt() + return ans.toInt() + } + + private fun buildGraph(n: Int, edges: Array): List> { + val graph: MutableList> = ArrayList() + for (i in 0..n) { + graph.add(ArrayList()) + } + for (edge in edges) { + val u = edge[0] + val v = edge[1] + val wt = edge[2] + graph[u].add(Edge(v, wt)) + graph[v].add(Edge(u, wt)) + } + return graph + } + + companion object { + private const val M = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1787_make_the_xor_of_all_segments_equal_to_zero/readme.md b/src/main/kotlin/g1701_1800/s1787_make_the_xor_of_all_segments_equal_to_zero/readme.md new file mode 100644 index 00000000..1e010e31 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1787_make_the_xor_of_all_segments_equal_to_zero/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) + +## 1787\. Make the XOR of All Segments Equal to Zero + +Hard + +You are given an array `nums` and an integer `k`. The XOR of a segment `[left, right]` where `left <= right` is the `XOR` of all the elements with indices between `left` and `right`, inclusive: `nums[left] XOR nums[left+1] XOR ... XOR nums[right]`. + +Return _the minimum number of elements to change in the array_ such that the `XOR` of all segments of size `k` is equal to zero. + +**Example 1:** + +**Input:** nums = [1,2,0,3,0], k = 1 + +**Output:** 3 + +**Explanation:** Modify the array from [**1**,**2**,0,**3**,0] to from [**0**,**0**,0,**0**,0]. + +**Example 2:** + +**Input:** nums = [3,4,5,2,1,7,3,4,7], k = 3 + +**Output:** 3 + +**Explanation:** Modify the array from [3,4,**5**,**2**,**1**,7,3,4,7] to [3,4,**7**,**3**,**4**,7,3,4,7]. + +**Example 3:** + +**Input:** nums = [1,2,4,1,2,5,1,2,6], k = 3 + +**Output:** 3 + +**Explanation:** Modify the array from [1,2,**4,**1,2,**5**,1,2,**6**] to [1,2,**3**,1,2,**3**,1,2,**3**]. + +**Constraints:** + +* `1 <= k <= nums.length <= 2000` +* 0 <= nums[i] < 210 + +## Solution + +```kotlin +class Solution { + fun minChanges(nums: IntArray, k: Int): Int { + val n = nums.size + val fre = Array(k) { IntArray(1024) } + for (i in 0 until n) { + fre[i % k][nums[i]]++ + } + var dp = IntArray(1024) + dp.fill(-n) + dp[0] = 0 + var max = 0 + for (i in 0 until k) { + val dp2 = IntArray(1024) + dp2.fill(max) + var max2 = 0 + for (xor in 0..1023) { + var al = i + while (al < n) { + dp2[xor] = Math.max(dp2[xor], dp[xor xor nums[al]] + fre[i][nums[al]]) + al += k + } + max2 = Math.max(max2, dp2[xor]) + } + max = max2 + dp = dp2 + } + return n - dp[0] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1789_primary_department_for_each_employee/readme.md b/src/main/kotlin/g1701_1800/s1789_primary_department_for_each_employee/readme.md new file mode 100644 index 00000000..27f876e4 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1789_primary_department_for_each_employee/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) + +## 1789\. Primary Department for Each Employee + +Easy + +SQL Schema + +Table: `Employee` + + +---------------+---------+ + | Column Name | Type | + +---------------+---------+ + | employee_id | int | + | department_id | int | + | primary_flag | varchar | + +---------------+---------+ + (employee_id, department_id) is the primary key for this table. + employee_id is the id of the employee. + department_id is the id of the department to which the employee belongs. + primary_flag is an ENUM of type ('Y', 'N'). If the flag is 'Y', the department is the primary department for the employee. + If the flag is 'N', the department is not the primary. + +Employees can belong to multiple departments. When the employee joins other departments, they need to decide which department is their primary department. Note that when an employee belongs to only one department, their primary column is `'N'`. + +Write an SQL query to report all the employees with their primary department. For employees who belong to one department, report their only department. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Employee table: + +-------------+---------------+--------------+ + | employee_id | department_id | primary_flag | + +-------------+---------------+--------------+ + | 1 | 1 | N | + | 2 | 1 | Y | + | 2 | 2 | N | + | 3 | 3 | N | + | 4 | 2 | N | + | 4 | 3 | Y | + | 4 | 4 | N | + +-------------+---------------+--------------+ + +**Output:** + + +-------------+---------------+ + | employee_id | department_id | + +-------------+---------------+ + | 1 | 1 | + | 2 | 1 | + | 3 | 3 | + | 4 | 3 | + +-------------+---------------+ + +**Explanation:** + +- The Primary department for employee 1 is 1. + +- The Primary department for employee 2 is 1. + +- The Primary department for employee 3 is 3. + +- The Primary department for employee 4 is 3. + +## Solution + +```sql +# Write your MySQL query statement below +select e1.employee_id, case when e2.department_id is null then e1.department_id else e2.department_id end as department_id +from employee e1 +left join (select * from employee where primary_flag = 'Y')e2 on e1.employee_id = e2.employee_id +group by e1.employee_id, department_id +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1790_check_if_one_string_swap_can_make_strings_equal/readme.md b/src/main/kotlin/g1701_1800/s1790_check_if_one_string_swap_can_make_strings_equal/readme.md new file mode 100644 index 00000000..d1e8049a --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1790_check_if_one_string_swap_can_make_strings_equal/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) + +## 1790\. Check if One String Swap Can Make Strings Equal + +Easy + +You are given two strings `s1` and `s2` of equal length. A **string swap** is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. + +Return `true` _if it is possible to make both strings equal by performing **at most one string swap** on **exactly one** of the strings._ Otherwise, return `false`. + +**Example 1:** + +**Input:** s1 = "bank", s2 = "kanb" + +**Output:** true + +**Explanation:** For example, swap the first character with the last character of s2 to make "bank". + +**Example 2:** + +**Input:** s1 = "attack", s2 = "defend" + +**Output:** false + +**Explanation:** It is impossible to make them equal with one string swap. + +**Example 3:** + +**Input:** s1 = "kelb", s2 = "kelb" + +**Output:** true + +**Explanation:** The two strings are already equal, so no string swap operation is required. + +**Constraints:** + +* `1 <= s1.length, s2.length <= 100` +* `s1.length == s2.length` +* `s1` and `s2` consist of only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun areAlmostEqual(s1: String, s2: String): Boolean { + var i1 = -1 + var i2 = -1 + // We go though the two strings + for (i in 0 until s1.length) { + // check if each char is the same. + if (s1[i] == s2[i]) { + continue + } + // When there are more than 2 char different., we return false; + if (i2 != -1) { + return false + } + // If there is char that is different, we record the index. + if (i1 == -1) { + i1 = i + } else { + // If there is char that is different, we record the index. + i2 = i + } + } + // When three is no different char, we return true; + if (i1 == i2) { + return true + } + // When there is 1 char different, we return false; + return if (i2 == -1) { + false + } else s1[i1] == s2[i2] && s1[i2] == s2[i1] + // When there are 2 char different, and swap them can make two string equal, we return true; + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1791_find_center_of_star_graph/readme.md b/src/main/kotlin/g1701_1800/s1791_find_center_of_star_graph/readme.md new file mode 100644 index 00000000..d5f618eb --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1791_find_center_of_star_graph/readme.md @@ -0,0 +1,47 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1791\. Find Center of Star Graph + +Easy + +There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node. + +You are given a 2D integer array `edges` where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/24/star_graph.png) + +**Input:** edges = \[\[1,2],[2,3],[4,2]] + +**Output:** 2 + +**Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center. + +**Example 2:** + +**Input:** edges = \[\[1,2],[5,1],[1,3],[1,4]] + +**Output:** 1 + +**Constraints:** + +* 3 <= n <= 105 +* `edges.length == n - 1` +* `edges[i].length == 2` +* 1 <= ui, vi <= n +* ui != vi +* The given `edges` represent a valid star graph. + +## Solution + +```kotlin +class Solution { + fun findCenter(edges: Array): Int { + return if (edges[0][0] == edges[1][0] || edges[0][0] == edges[1][1]) { + edges[0][0] + } else edges[0][1] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1792_maximum_average_pass_ratio/readme.md b/src/main/kotlin/g1701_1800/s1792_maximum_average_pass_ratio/readme.md new file mode 100644 index 00000000..351a5ee3 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1792_maximum_average_pass_ratio/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) + +## 1792\. Maximum Average Pass Ratio + +Medium + +There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam. + +You are also given an integer `extraStudents`. There are another `extraStudents` brilliant students that are **guaranteed** to pass the exam of any class they are assigned to. You want to assign each of the `extraStudents` students to a class in a way that **maximizes** the **average** pass ratio across **all** the classes. + +The **pass ratio** of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The **average pass ratio** is the sum of pass ratios of all the classes divided by the number of the classes. + +Return _the **maximum** possible average pass ratio after assigning the_ `extraStudents` _students._ Answers within 10-5 of the actual answer will be accepted. + +**Example 1:** + +**Input:** classes = \[\[1,2],[3,5],[2,2]], `extraStudents` = 2 + +**Output:** 0.78333 + +**Explanation:** You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. + +**Example 2:** + +**Input:** classes = \[\[2,4],[3,9],[4,5],[2,10]], `extraStudents` = 4 + +**Output:** 0.53485 + +**Constraints:** + +* 1 <= classes.length <= 105 +* `classes[i].length == 2` +* 1 <= passi <= totali <= 105 +* 1 <= extraStudents <= 105 + +## Solution + +```kotlin +import java.util.PriorityQueue + +@Suppress("NAME_SHADOWING") +class Solution { + fun maxAverageRatio(classes: Array, extraStudents: Int): Double { + var extraStudents = extraStudents + val heap = PriorityQueue { o1: DoubleArray, o2: DoubleArray -> java.lang.Double.compare(o2[0], o1[0]) } + for (clas in classes) { + val delta = profit(clas[0].toDouble(), clas[1].toDouble()) + heap.offer(doubleArrayOf(delta, clas[0].toDouble(), clas[1].toDouble())) + } + while (extraStudents >= 1) { + val temp = heap.poll() + val pass = temp[1] + 1 + val total = temp[2] + 1 + val delta = profit(pass, total) + heap.offer(doubleArrayOf(delta, pass, total)) + extraStudents-- + } + var average = 0.0 + while (heap.isNotEmpty()) { + val temp = heap.poll() + average += temp[1] / temp[2] + } + return average / classes.size + } + + // O(1) + private fun profit(a: Double, b: Double): Double { + return (a + 1) / (b + 1) - a / b + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1793_maximum_score_of_a_good_subarray/readme.md b/src/main/kotlin/g1701_1800/s1793_maximum_score_of_a_good_subarray/readme.md new file mode 100644 index 00000000..9dfcdf1e --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1793_maximum_score_of_a_good_subarray/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) + +## 1793\. Maximum Score of a Good Subarray + +Hard + +You are given an array of integers `nums` **(0-indexed)** and an integer `k`. + +The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`. + +Return _the maximum possible **score** of a **good** subarray._ + +**Example 1:** + +**Input:** nums = [1,4,3,7,4,5], k = 3 + +**Output:** 15 + +**Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15. + +**Example 2:** + +**Input:** nums = [5,5,4,5,4,1,1,1], k = 0 + +**Output:** 20 + +**Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 2 * 104 +* `0 <= k < nums.length` + +## Solution + +```kotlin +class Solution { + fun maximumScore(nums: IntArray, k: Int): Int { + var i = k + var j = k + var res = nums[k] + var min = nums[k] + var goLeft: Boolean + while (i >= 1 || j < nums.size - 1) { + // sub array [i...j] is already traversed. Either goLeft or goRight to increase the + // sequence + goLeft = if (i == 0) { + false + } else if (j == nums.size - 1) { + true + } else { + nums[j + 1] <= nums[i - 1] + } + min = if (goLeft) Math.min(min, nums[i - 1]) else Math.min(min, nums[j + 1]) + if (goLeft) { + while (i >= 1 && min <= nums[i - 1]) { + i-- + } + } else { + while (j < nums.size - 1 && min <= nums[j + 1]) { + j++ + } + } + res = Math.max(res, min * (j - i + 1)) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1795_rearrange_products_table/readme.md b/src/main/kotlin/g1701_1800/s1795_rearrange_products_table/readme.md new file mode 100644 index 00000000..50b4319c --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1795_rearrange_products_table/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) + +## 1795\. Rearrange Products Table + +Easy + +SQL Schema + +Table: `Products` + + +-------------+---------+ + | Column Name | Type | + +-------------+---------+ + | product_id | int | + | store1 | int | + | store2 | int | + | store3 | int | + +-------------+---------+ + product_id is the primary key for this table. + Each row in this table indicates the product's price in 3 different stores: store1, store2, and store3. + If the product is not available in a store, the price will be null in that store's column. + +Write an SQL query to rearrange the `Products` table so that each row has `(product_id, store, price)`. If a product is not available in a store, do **not** include a row with that `product_id` and `store` combination in the result table. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Products table: + +------------+--------+--------+--------+ + | product_id | store1 | store2 | store3 | + +------------+--------+--------+--------+ + | 0 | 95 | 100 | 105 | + | 1 | 70 | null | 80 | + +------------+--------+--------+--------+ + +**Output:** + + +------------+--------+-------+ + | product_id | store | price | + +------------+--------+-------+ + | 0 | store1 | 95 | + | 0 | store2 | 100 | + | 0 | store3 | 105 | + | 1 | store1 | 70 | + | 1 | store3 | 80 | + +------------+--------+-------+ + +**Explanation:** + + Product 0 is available in all three stores with prices 95, 100, and 105 respectively. + Product 1 is available in store1 with price 70 and store3 with price 80. The product is not available in store2. + +## Solution + +```sql +# Write your MySQL query statement below +SELECT product_id, 'store1' AS store, store1 AS price +FROM Products +WHERE store1 IS NOT NULL +UNION +SELECT product_id, 'store2' AS store, store2 AS price +FROM Products +WHERE store2 IS NOT NULL +UNION +SELECT product_id, 'store3' AS store, store3 AS price +FROM Products +WHERE store3 IS NOT NULL; +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1796_second_largest_digit_in_a_string/readme.md b/src/main/kotlin/g1701_1800/s1796_second_largest_digit_in_a_string/readme.md new file mode 100644 index 00000000..3a814214 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1796_second_largest_digit_in_a_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) + +## 1796\. Second Largest Digit in a String + +Easy + +Given an alphanumeric string `s`, return _the **second largest** numerical digit that appears in_ `s`_, or_ `-1` _if it does not exist_. + +An **alphanumeric** string is a string consisting of lowercase English letters and digits. + +**Example 1:** + +**Input:** s = "dfa12321afd" + +**Output:** 2 + +**Explanation:** The digits that appear in s are [1, 2, 3]. The second largest digit is 2. + +**Example 2:** + +**Input:** s = "abc1111" + +**Output:** -1 + +**Explanation:** The digits that appear in s are [1]. There is no second largest digit. + +**Constraints:** + +* `1 <= s.length <= 500` +* `s` consists of only lowercase English letters and/or digits. + +## Solution + +```kotlin +class Solution { + fun secondHighest(s: String): Int { + var largest = -1 + var sl = -1 + for (ch in s.toCharArray()) { + if (Character.isDigit(ch)) { + val n = ch.code - '0'.code + if (n > largest) { + sl = largest + largest = n + } else if (n > sl && n < largest) { + sl = n + } + } + } + return sl + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1797_design_authentication_manager/readme.md b/src/main/kotlin/g1701_1800/s1797_design_authentication_manager/readme.md new file mode 100644 index 00000000..a3c1fbc8 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1797_design_authentication_manager/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) + +## 1797\. Design Authentication Manager + +Medium + +There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire `timeToLive` seconds after the `currentTime`. If the token is renewed, the expiry time will be **extended** to expire `timeToLive` seconds after the (potentially different) `currentTime`. + +Implement the `AuthenticationManager` class: + +* `AuthenticationManager(int timeToLive)` constructs the `AuthenticationManager` and sets the `timeToLive`. +* `generate(string tokenId, int currentTime)` generates a new token with the given `tokenId` at the given `currentTime` in seconds. +* `renew(string tokenId, int currentTime)` renews the **unexpired** token with the given `tokenId` at the given `currentTime` in seconds. If there are no unexpired tokens with the given `tokenId`, the request is ignored, and nothing happens. +* `countUnexpiredTokens(int currentTime)` returns the number of **unexpired** tokens at the given currentTime. + +Note that if a token expires at time `t`, and another action happens on time `t` (`renew` or `countUnexpiredTokens`), the expiration takes place **before** the other actions. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/25/copy-of-pc68_q2.png) + +**Input** + +["AuthenticationManager", "`renew`", "generate", "`countUnexpiredTokens`", "generate", "`renew`", "`renew`", "`countUnexpiredTokens`"] + +[[5], ["aaa", 1], ["aaa", 2], [6], ["bbb", 7], ["aaa", 8], ["bbb", 10], [15]] + +**Output:** [null, null, null, 1, null, null, null, 0] + +**Explanation:** + +AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with `timeToLive` = 5 seconds. + +authenticationManager.`renew`("aaa", 1); // No token exists with tokenId "aaa" at time 1, so nothing happens. + +authenticationManager.generate("aaa", 2); // Generates a new token with tokenId "aaa" at time 2. + +authenticationManager.`countUnexpiredTokens`(6); // The token with tokenId "aaa" is the only unexpired one at time 6, so return 1. + +authenticationManager.generate("bbb", 7); // Generates a new token with tokenId "bbb" at time 7. + +authenticationManager.`renew`("aaa", 8); // The token with tokenId "aaa" expired at time 7, and 8 >= 7, so at time 8 the `renew` request is ignored, and nothing happens. + +authenticationManager.`renew`("bbb", 10); // The token with tokenId "bbb" is unexpired at time 10, so the `renew` request is fulfilled and now the token will expire at time 15. + +authenticationManager.`countUnexpiredTokens`(15); // The token with tokenId "bbb" expires at time 15, and the token with tokenId "aaa" expired at time 7, so currently no token is unexpired, so return 0. + +**Constraints:** + +* 1 <= timeToLive <= 108 +* 1 <= currentTime <= 108 +* `1 <= tokenId.length <= 5` +* `tokenId` consists only of lowercase letters. +* All calls to `generate` will contain unique values of `tokenId`. +* The values of `currentTime` across all the function calls will be **strictly increasing**. +* At most `2000` calls will be made to all functions combined. + +## Solution + +```kotlin +import java.util.ArrayDeque +import java.util.Deque + +class AuthenticationManager(var timeToLive: Int) { + private var expireMap: MutableMap = HashMap() + private var deque: Deque = ArrayDeque() + + fun generate(tokenId: String, currentTime: Int) { + expireMap[tokenId] = currentTime + timeToLive + deque.offerLast(Item(tokenId, currentTime + timeToLive)) + } + + fun renew(tokenId: String, currentTime: Int) { + update(currentTime) + if (expireMap.containsKey(tokenId)) { + deque.offerLast(Item(tokenId, currentTime + timeToLive)) + expireMap[tokenId] = currentTime + timeToLive + } + } + + fun countUnexpiredTokens(currentTime: Int): Int { + update(currentTime) + return expireMap.size + } + + private fun update(curTime: Int) { + while (deque.isNotEmpty() && deque.peekFirst().time <= curTime) { + val id = deque.peekFirst().id + val time = deque.peekFirst().time + if (expireMap.containsKey(id) && expireMap[id] == time) { + expireMap.remove(deque.pollFirst().id) + } else { + deque.pollFirst() + } + } + } + + private class Item(var id: String, var time: Int) +} +/* + * Your AuthenticationManager object will be instantiated and called as such: + * var obj = AuthenticationManager(timeToLive) + * obj.generate(tokenId,currentTime) + * obj.renew(tokenId,currentTime) + * var param_3 = obj.countUnexpiredTokens(currentTime) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1798_maximum_number_of_consecutive_values_you_can_make/readme.md b/src/main/kotlin/g1701_1800/s1798_maximum_number_of_consecutive_values_you_can_make/readme.md new file mode 100644 index 00000000..4039d000 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1798_maximum_number_of_consecutive_values_you_can_make/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) + +## 1798\. Maximum Number of Consecutive Values You Can Make + +Medium + +You are given an integer array `coins` of length `n` which represents the `n` coins that you own. The value of the ith coin is `coins[i]`. You can **make** some value `x` if you can choose some of your `n` coins such that their values sum up to `x`. + +Return the _maximum number of consecutive integer values that you **can** **make** with your coins **starting** from and **including**_ `0`. + +Note that you may have multiple coins of the same value. + +**Example 1:** + +**Input:** coins = [1,3] + +**Output:** 2 + +**Explanation:** You can make the following values: + +- 0: take [] + +- 1: take [1] + +You can make 2 consecutive integer values starting from 0. + +**Example 2:** + +**Input:** coins = [1,1,1,4] + +**Output:** 8 + +**Explanation:** You can make the following values: + +- 0: take [] + +- 1: take [1] + +- 2: take [1,1] + +- 3: take [1,1,1] + +- 4: take [4] + +- 5: take [4,1] + +- 6: take [4,1,1] + +- 7: take [4,1,1,1] + +You can make 8 consecutive integer values starting from 0. + +**Example 3:** + +**Input:** nums = [1,4,10,3,1] + +**Output:** 20 + +**Constraints:** + +* `coins.length == n` +* 1 <= n <= 4 * 104 +* 1 <= coins[i] <= 4 * 104 + +## Solution + +```kotlin +class Solution { + fun getMaximumConsecutive(coins: IntArray): Int { + val count = IntArray(40001) + for (c in coins) { + count[c]++ + } + var res = 1 + var i = 1 + while (i < count.size && i <= res) { + res += i * count[i] + i++ + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1701_1800/s1799_maximize_score_after_n_operations/readme.md b/src/main/kotlin/g1701_1800/s1799_maximize_score_after_n_operations/readme.md new file mode 100644 index 00000000..96cb7bd6 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1799_maximize_score_after_n_operations/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) + +## 1799\. Maximize Score After N Operations + +Hard + +You are given `nums`, an array of positive integers of size `2 * n`. You must perform `n` operations on this array. + +In the ith operation **(1-indexed)**, you will: + +* Choose two elements, `x` and `y`. +* Receive a score of `i * gcd(x, y)`. +* Remove `x` and `y` from `nums`. + +Return _the maximum score you can receive after performing_ `n` _operations._ + +The function `gcd(x, y)` is the greatest common divisor of `x` and `y`. + +**Example 1:** + +**Input:** nums = [1,2] + +**Output:** 1 + +**Explanation:** The optimal choice of operations is: + +v(1 \* gcd(1, 2)) = 1 + +**Example 2:** + +**Input:** nums = [3,4,6,8] + +**Output:** 11 + +**Explanation:** The optimal choice of operations is: + +(1 \* gcd(3, 6)) + (2 \* gcd(4, 8)) = 3 + 8 = 11 + +**Example 3:** + +**Input:** nums = [1,2,3,4,5,6] + +**Output:** 14 + +**Explanation:** The optimal choice of operations is: + +(1 \* gcd(1, 5)) + (2 \* gcd(2, 4)) + (3 \* gcd(3, 6)) = 1 + 4 + 9 = 14 + +**Constraints:** + +* `1 <= n <= 7` +* `nums.length == 2 * n` +* 1 <= nums[i] <= 106 + +## Solution + +```kotlin +class Solution { + fun maxScore(nums: IntArray): Int { + val n = nums.size + val memo = arrayOfNulls(1 shl n) + return helper(1, 0, nums, memo) + } + + private fun helper(operationNumber: Int, mask: Int, nums: IntArray, memo: Array): Int { + val n = nums.size + if (memo[mask] != null) { + return memo[mask]!! + } + if (operationNumber > n / 2) { + return 0 + } + var maxScore = Int.MIN_VALUE + for (i in 0 until n) { + if (mask and (1 shl i) == 0) { + for (j in i + 1 until n) { + if (mask and (1 shl j) == 0) { + val score = operationNumber * gcd(nums[i], nums[j]) + val score2 = helper(operationNumber + 1, mask or (1 shl i) or (1 shl j), nums, memo) + maxScore = Math.max(maxScore, score + score2) + } + } + } + } + memo[mask] = maxScore + return maxScore + } + + 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/g1701_1800/s1800_maximum_ascending_subarray_sum/readme.md b/src/main/kotlin/g1701_1800/s1800_maximum_ascending_subarray_sum/readme.md new file mode 100644 index 00000000..a6bb3fe3 --- /dev/null +++ b/src/main/kotlin/g1701_1800/s1800_maximum_ascending_subarray_sum/readme.md @@ -0,0 +1,64 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1800\. Maximum Ascending Subarray Sum + +Easy + +Given an array of positive integers `nums`, return the _maximum possible sum of an **ascending** subarray in_ `nums`. + +A subarray is defined as a contiguous sequence of numbers in an array. + +A subarray [numsl, numsl+1, ..., numsr-1, numsr] is **ascending** if for all `i` where `l <= i < r`, numsi < numsi+1. Note that a subarray of size `1` is **ascending**. + +**Example 1:** + +**Input:** nums = [10,20,30,5,10,50] + +**Output:** 65 + +**Explanation:** [5,10,50] is the ascending subarray with the maximum sum of 65. + +**Example 2:** + +**Input:** nums = [10,20,30,40,50] + +**Output:** 150 + +**Explanation:** [10,20,30,40,50] is the ascending subarray with the maximum sum of 150. + +**Example 3:** + +**Input:** nums = [12,17,15,13,10,11,12] + +**Output:** 33 + +**Explanation:** [10,11,12] is the ascending subarray with the maximum sum of 33. + +**Constraints:** + +* `1 <= nums.length <= 100` +* `1 <= nums[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun maxAscendingSum(nums: IntArray): Int { + var maxSum = nums[0] + var i = 0 + var j = i + 1 + while (i < nums.size - 1 && j < nums.size) { + var sum = nums[j - 1] + while (j < nums.size && nums[j] - nums[j - 1] > 0) { + sum += nums[j] + j++ + } + i = j + maxSum = Math.max(maxSum, sum) + j++ + } + return maxSum + } +} +``` \ No newline at end of file