aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore1
-rw-r--r--apply_operations_arr_max_sqr.c37
-rw-r--r--apply_operations_arr_max_sqr.py31
-rw-r--r--build_arr_permutation.c31
-rw-r--r--build_arr_permutation.py23
-rw-r--r--candy.c65
-rw-r--r--closest_node_2_nodes.c78
-rw-r--r--closest_node_2_nodes.py46
-rw-r--r--count_complete_subarr_arr.c50
-rw-r--r--count_complete_subarr_arr.py35
-rw-r--r--count_hidden_sequences.c29
-rw-r--r--count_hidden_sequences.py30
-rw-r--r--count_interesting_subarr.c83
-rw-r--r--count_interesting_subarr.py34
-rw-r--r--count_largest_group.c37
-rw-r--r--count_largest_group.py39
-rw-r--r--count_num_arr_k_match_elem.c48
-rw-r--r--count_num_arr_k_match_elem.py28
-rw-r--r--count_num_balanced_perm.c78
-rw-r--r--count_num_balanced_perm.py55
-rw-r--r--count_num_ideal_arr.c36
-rw-r--r--count_num_ideal_arr.py38
-rw-r--r--count_number_powerful_integers.cpp41
-rw-r--r--count_subarr_fixed_bound.c19
-rw-r--r--count_subarr_fixed_bound.py8
-rw-r--r--count_subarr_len_three_cond.c22
-rw-r--r--count_subarr_len_three_cond.py22
-rw-r--r--count_subarr_max_elem_k.c20
-rw-r--r--count_subarr_max_elem_k.py16
-rw-r--r--count_subarr_score_less_k.c26
-rw-r--r--count_subarr_score_less_k.py31
-rw-r--r--create_sorted_arr_instr.c51
-rw-r--r--create_sorted_arr_instr.py48
-rw-r--r--distribute_candies_children2.c22
-rw-r--r--distribute_candies_children2.py35
-rw-r--r--div_non_div_sum_diff.c19
-rw-r--r--div_non_div_sum_diff.py25
-rw-r--r--divide_array_max_diff.c69
-rw-r--r--divide_array_max_diff.py17
-rw-r--r--divide_string_groups_k.c47
-rw-r--r--divide_string_groups_k.py42
-rw-r--r--domino_tromino_tiling.c31
-rw-r--r--domino_tromino_tiling.py34
-rw-r--r--find_lex_large_str_box1.c40
-rw-r--r--find_lex_large_str_box1.py30
-rw-r--r--find_max_sum_node_val.c45
-rw-r--r--find_min_time_reach_last_room1.c85
-rw-r--r--find_min_time_reach_last_room1.py41
-rw-r--r--find_min_time_reach_last_room2.c150
-rw-r--r--find_min_time_reach_last_room2.py43
-rw-r--r--find_num_even_digit.c27
-rw-r--r--find_num_even_digit.py21
-rw-r--r--find_original_typed_str1.c26
-rw-r--r--find_original_typed_str1.py28
-rw-r--r--find_subseq_len_k_large_sum.c62
-rw-r--r--find_subseq_len_k_large_sum.py32
-rw-r--r--find_words_contain_char.c40
-rw-r--r--find_words_contain_char.py24
-rw-r--r--finding_3_digit_even_num.c59
-rw-r--r--finding_3_digit_even_num.py32
-rw-r--r--fizz_buzz_multithread.c145
-rw-r--r--fizz_buzz_multithread.py94
-rw-r--r--generate_binary_string_without_adj_0.c55
-rw-r--r--generate_binary_string_without_adj_0.py36
-rw-r--r--kth_smallest_product_sort_arr.c95
-rw-r--r--kth_smallest_product_sort_arr.py45
-rw-r--r--largest_colour_val_dir_graph.c115
-rw-r--r--largest_colour_val_dir_graph.py57
-rw-r--r--leetcode.h1
-rw-r--r--lex_min_str_rem_star.c141
-rw-r--r--lex_min_str_rem_star.py46
-rw-r--r--lex_smallest_beaut_str.c47
-rw-r--r--lex_smallest_beaut_str.py36
-rw-r--r--lexicographical_numbers.c33
-rw-r--r--lexicographically_small_string.c44
-rw-r--r--lexicographically_smallest_equivalent_str.c46
-rw-r--r--lexicographically_smallest_equivalent_str.py49
-rw-r--r--longest_binary_subseq_leq_k.c30
-rw-r--r--longest_binary_subseq_leq_k.py29
-rw-r--r--longest_harmonious_subseq.c62
-rw-r--r--longest_harmonious_subseq.py26
-rw-r--r--longest_palindrome_concat_two_word.c36
-rw-r--r--longest_palindrome_concat_two_word.py46
-rw-r--r--longest_subseq_repeat_k_time.c100
-rw-r--r--longest_subseq_repeat_k_time.py45
-rw-r--r--longest_unequal_adjacent_group1.c39
-rw-r--r--longest_unequal_adjacent_group1.py33
-rw-r--r--longest_unequal_adjacent_group2.c116
-rw-r--r--longest_unequal_adjacent_group2.py50
-rw-r--r--max_candies_from_boxes.c84
-rw-r--r--max_candies_from_boxes.py60
-rw-r--r--max_diff_between_adj_elem.c23
-rw-r--r--max_diff_between_adj_elem.py27
-rw-r--r--max_diff_between_incr_elem.c25
-rw-r--r--max_diff_between_incr_elem.py28
-rw-r--r--max_diff_even_odd_freq1.c31
-rw-r--r--max_diff_even_odd_freq1.py33
-rw-r--r--max_diff_even_odd_freq2.c120
-rw-r--r--max_diff_even_odd_freq2.py78
-rw-r--r--max_diff_remap_digit.c30
-rw-r--r--max_diff_remap_digit.py26
-rw-r--r--max_manhattan_dist_k_change.c39
-rw-r--r--max_manhattan_dist_k_change.py35
-rw-r--r--max_num_tasks_assign.py64
-rw-r--r--max_path_quality_graph.c91
-rw-r--r--max_path_quality_graph.py66
-rw-r--r--maximise_num_target_node_tree1.py64
-rw-r--r--maximise_num_target_node_tree2.c139
-rw-r--r--maximise_num_target_node_tree2.py63
-rw-r--r--min_del_make_str_special.c30
-rw-r--r--min_del_make_str_special.py33
-rw-r--r--min_domino_rotation_eq_row.c40
-rw-r--r--min_domino_rotation_eq_row.py30
-rw-r--r--min_equal_sum_two_arr.c35
-rw-r--r--min_equal_sum_two_arr.py30
-rw-r--r--min_max_diff_pair.c18
-rw-r--r--min_max_diff_pair.py42
-rw-r--r--min_ops_make_int_zero.c36
-rw-r--r--min_ops_make_int_zero.py39
-rw-r--r--num_equivalent_domino_pair.c35
-rw-r--r--num_equivalent_domino_pair.py27
-rw-r--r--num_subseq_satisfy.c58
-rw-r--r--num_subseq_satisfy.py36
-rw-r--r--other/01_matrix.cpp34
-rw-r--r--other/132_pattern.cpp32
-rw-r--r--other/3sum_closest.cpp31
-rw-r--r--other/add_arr_form_int.cpp44
-rw-r--r--other/add_binary.cpp30
-rw-r--r--other/add_digits.cpp26
-rw-r--r--other/add_row_tree.cpp29
-rw-r--r--other/add_search_words_data.cpp35
-rw-r--r--other/add_space_string.cpp36
-rw-r--r--other/add_two_num2.cpp56
-rw-r--r--other/additive_number.cpp54
-rw-r--r--other/all_nodes_binary_tree.cpp53
-rw-r--r--other/all_path_src_target.cpp30
-rw-r--r--other/all_path_src_target.rs54
-rw-r--r--other/all_possible_full_tree.cpp40
-rw-r--r--other/alphabet_board_path.cpp44
-rw-r--r--other/ancestors_node_acyclic_graph.cpp58
-rw-r--r--other/arithmetic_progression.cpp44
-rw-r--r--other/arithmetic_slices2.cpp35
-rw-r--r--other/arithmetic_slices2.rs30
-rw-r--r--other/asteroid_collision.cpp52
-rw-r--r--other/avg_levels_bst.cpp24
-rw-r--r--other/avg_salary.cpp32
-rw-r--r--other/bag_of_tokens.cpp27
-rw-r--r--other/balanced_num.cpp55
-rw-r--r--other/basic_calculator.cpp37
-rw-r--r--other/basic_calculator.rs29
-rw-r--r--other/best_buy_sell_stock.cpp31
-rw-r--r--other/best_team_no_conflict.cpp28
-rw-r--r--other/binary_search.cpp27
-rw-r--r--other/binary_tree_factors.cpp31
-rw-r--r--other/binary_tree_inorder.cpp23
-rw-r--r--other/binary_tree_level_traverse.cpp31
-rw-r--r--other/binary_tree_preorder.cpp28
-rw-r--r--other/binary_tree_preorder.rs35
-rw-r--r--other/binary_tree_pruning.cpp15
-rw-r--r--other/binary_tree_right_view.cpp24
-rw-r--r--other/binary_tree_traversal.cpp24
-rw-r--r--other/binary_tree_zigzag.cpp36
-rw-r--r--other/boats_save_people.cpp35
-rw-r--r--other/brainpower.cpp37
-rw-r--r--other/break_palindrom.cpp33
-rw-r--r--other/browser_history.cpp45
-rw-r--r--other/bt_max_path_sum.cpp31
-rw-r--r--other/bt_max_path_sum.rs38
-rw-r--r--other/buddy_strings.cpp46
-rw-r--r--other/build_matrix_conditions.cpp98
-rw-r--r--other/bulb_switcher.cpp19
-rw-r--r--other/buy_sell_stock.cpp34
-rw-r--r--other/buy_sell_stock.rs33
-rw-r--r--other/buy_sell_stock_fee.cpp35
-rw-r--r--other/can_place_flower.cpp35
-rw-r--r--other/candy.cpp37
-rw-r--r--other/capacity_ship_d_day.cpp50
-rw-r--r--other/cheapest_flight_k_stop.cpp46
-rw-r--r--other/check_complete_bt.cpp26
-rw-r--r--other/check_existence_edge.cpp68
-rw-r--r--other/check_knight_config.cpp59
-rw-r--r--other/check_pangram_sentence.cpp19
-rw-r--r--other/check_pangram_sentence.rs21
-rw-r--r--other/check_straight_line.cpp35
-rw-r--r--other/check_string_cont_k.cpp30
-rw-r--r--other/check_two_str_arr.cpp26
-rw-r--r--other/check_two_str_arr.rs19
-rw-r--r--other/check_valid_partition.cpp50
-rw-r--r--other/climbing_stairs.cpp31
-rw-r--r--other/climbing_stairs.rs16
-rw-r--r--other/clone_graph.cpp55
-rw-r--r--other/closest_node_2_nodes.cpp55
-rw-r--r--other/closest_node_2_nodes.rs45
-rw-r--r--other/coin_change.cpp22
-rw-r--r--other/coin_change2.cpp31
-rw-r--r--other/combination_sum3.cpp38
-rw-r--r--other/combination_sum4.cpp24
-rw-r--r--other/combinations.cpp39
-rw-r--r--other/concatenated_words.cpp75
-rw-r--r--other/concatenation_binary_num.cpp38
-rw-r--r--other/construct_array_multiple_sum.cpp30
-rw-r--r--other/construct_bt_io_po.cpp31
-rw-r--r--other/construct_quad_tree.cpp75
-rw-r--r--other/construct_string_binary_tree.cpp21
-rw-r--r--other/contains_duplicate2.cpp24
-rw-r--r--other/contains_duplicate2.rs21
-rw-r--r--other/contains_duplicate3.cpp52
-rw-r--r--other/contains_virus.cpp77
-rw-r--r--other/continuous_subarr_sum.cpp31
-rw-r--r--other/continuous_subarr_sum.rs24
-rw-r--r--other/convert_sorted_bst.cpp29
-rw-r--r--other/cost_hire_k_worker.cpp48
-rw-r--r--other/count_all_pickup_delivery.cpp23
-rw-r--r--other/count_and_say.cpp26
-rw-r--r--other/count_and_say.rs32
-rw-r--r--other/count_complete_tree_node.cpp18
-rw-r--r--other/count_complete_tree_node.rs51
-rw-r--r--other/count_distinct_int.cpp40
-rw-r--r--other/count_distinct_int.rs35
-rw-r--r--other/count_good_nodes_bst.cpp22
-rw-r--r--other/count_ints_even_sum.cpp26
-rw-r--r--other/count_negative_num_matrix.cpp37
-rw-r--r--other/count_odd_num_interval_range.cpp24
-rw-r--r--other/count_possible_routes.cpp42
-rw-r--r--other/count_sorted_vowel.cpp20
-rw-r--r--other/count_unreach_node.cpp48
-rw-r--r--other/count_vowels_permutation.cpp30
-rw-r--r--other/count_ways_build_strs.cpp38
-rw-r--r--other/couples_holding_hands.cpp38
-rw-r--r--other/course_schedule.cpp44
-rw-r--r--other/course_schedule_3.cpp27
-rw-r--r--other/create_bt_from_desc.cpp40
-rw-r--r--other/daily_temps.cpp28
-rw-r--r--other/daily_temps.rs28
-rw-r--r--other/data_stream_disjoint_interval.cpp45
-rw-r--r--other/decode_ways.cpp23
-rw-r--r--other/decode_xor_array.cpp35
-rw-r--r--other/delete_col_sorted.cpp26
-rw-r--r--other/delete_col_sorted.rs25
-rw-r--r--other/delete_middle_node.cpp16
-rw-r--r--other/delete_middle_node.rs52
-rw-r--r--other/delete_node_link_list.cpp10
-rw-r--r--other/delete_operation_2string.cpp26
-rw-r--r--other/design_circular_queue.cpp53
-rw-r--r--other/design_food_rating_sys.cpp40
-rw-r--r--other/design_number_container.cpp39
-rw-r--r--other/design_parking_system.cpp40
-rw-r--r--other/design_underground_system.cpp20
-rw-r--r--other/detect_capital.cpp21
-rw-r--r--other/detect_capital.rs20
-rw-r--r--other/determine_string_halves.cpp25
-rw-r--r--other/determine_string_halves.rs18
-rw-r--r--other/determine_strings_close.cpp28
-rw-r--r--other/determine_strings_close.rs25
-rw-r--r--other/detonate_max_bombs.cpp61
-rw-r--r--other/diff_two_array.cpp35
-rw-r--r--other/discount_n_orders.cpp27
-rw-r--r--other/divide_nodes_max_groups.cpp75
-rw-r--r--other/domino_tromino_tiling.cpp28
-rw-r--r--other/domino_tromino_tiling.rs20
-rw-r--r--other/earliest_possible_full_bloom.cpp26
-rw-r--r--other/earliest_possible_full_bloom.rs20
-rw-r--r--other/edit_distance.cpp41
-rw-r--r--other/eliminate_monsters.cpp31
-rw-r--r--other/encode_decode_tinyurl.cpp43
-rw-r--r--other/equal_row_col_pair.cpp34
-rw-r--r--other/erect_fence.cpp29
-rw-r--r--other/erect_fence.rs27
-rw-r--r--other/eval_reverse_polish_notation.cpp46
-rw-r--r--other/eval_reverse_polish_notation.rs29
-rw-r--r--other/eventual_safe_states.cpp54
-rw-r--r--other/excel_sheet_column_title.cpp39
-rw-r--r--other/extra_char_string.cpp50
-rw-r--r--other/fair_distribution_cookie.cpp45
-rw-r--r--other/far_from_land.cpp44
-rw-r--r--other/fibonacci_number.cpp20
-rw-r--r--other/find_all_anagrams.cpp40
-rw-r--r--other/find_building_alice_bob_meet.cpp59
-rw-r--r--other/find_critical_edge_tree.cpp101
-rw-r--r--other/find_duplicate_file.cpp30
-rw-r--r--other/find_duplicate_subtree.cpp30
-rw-r--r--other/find_first_last_array.cpp22
-rw-r--r--other/find_groups_farmland.cpp43
-rw-r--r--other/find_highest_altitude.cpp31
-rw-r--r--other/find_k_beauty_num.cpp16
-rw-r--r--other/find_k_closest_elements.cpp37
-rw-r--r--other/find_k_pair_sum.cpp50
-rw-r--r--other/find_max_sum_node_val.cpp43
-rw-r--r--other/find_median_data_stream.cpp29
-rw-r--r--other/find_median_data_stream.rs41
-rw-r--r--other/find_orig_array_double.cpp19
-rw-r--r--other/find_path_graph.cpp28
-rw-r--r--other/find_path_graph.rs48
-rw-r--r--other/find_player_zero_one_loss.cpp21
-rw-r--r--other/find_player_zero_one_loss.rs14
-rw-r--r--other/find_replace_pattern.cpp32
-rw-r--r--other/find_safest_path_grid.cpp89
-rw-r--r--other/find_score_arr_mark.cpp40
-rw-r--r--other/find_smallest_letter.cpp34
-rw-r--r--other/find_town_judge.cpp46
-rw-r--r--other/first_missing_positive.cpp12
-rw-r--r--other/first_unique_char_string.cpp22
-rw-r--r--other/flatten_binary_to_linked.cpp21
-rw-r--r--other/flip_string_monotone_increase.cpp36
-rw-r--r--other/freedom_trail.cpp55
-rw-r--r--other/frog_jump.cpp47
-rw-r--r--other/fruit_into_baskets.cpp41
-rw-r--r--other/furthest_building_reach.cpp32
-rw-r--r--other/gas_station.cpp25
-rw-r--r--other/gas_station.rs26
-rw-r--r--other/greatest_common_div_string.cpp36
-rw-r--r--other/greatest_sum_div_three.cpp43
-rw-r--r--other/group_anagrams.cpp18
-rw-r--r--other/group_anagrams.rs15
-rw-r--r--other/guess_number_high_low.cpp22
-rw-r--r--other/guess_number_high_low.rs22
-rw-r--r--other/hand_of_straights.cpp30
-rw-r--r--other/happy_number.cpp37
-rw-r--r--other/house_robber.cpp21
-rw-r--r--other/house_robber.rs18
-rw-r--r--other/idx_first_occur_str.cpp51
-rw-r--r--other/image_overlap.cpp23
-rw-r--r--other/image_overlap.rs35
-rw-r--r--other/implement_queue_stacks.cpp32
-rw-r--r--other/increasing_triplet_subsequence.cpp26
-rw-r--r--other/inform_employees.cpp44
-rw-r--r--other/insert_delete_getrandom.cpp45
-rw-r--r--other/insert_delete_getrandom.rs55
-rw-r--r--other/insert_interval.cpp39
-rw-r--r--other/int_roman.cpp22
-rw-r--r--other/int_roman.rs26
-rw-r--r--other/integer_break.cpp20
-rw-r--r--other/interleaving_string.cpp39
-rw-r--r--other/invert_binary_tree.cpp26
-rw-r--r--other/ipo.cpp52
-rw-r--r--other/is_graph_biparite.cpp52
-rw-r--r--other/jump_game.cpp24
-rw-r--r--other/jump_game.rs18
-rw-r--r--other/jump_game3.cpp27
-rw-r--r--other/jump_game3.rs35
-rw-r--r--other/jump_game4.cpp52
-rw-r--r--other/jump_game6.cpp26
-rw-r--r--other/k_inverse_pairs.cpp24
-rw-r--r--other/k_radius_subarr.cpp45
-rw-r--r--other/keys_and_rooms.cpp32
-rw-r--r--other/keys_and_rooms.rs23
-rw-r--r--other/kids_max_num_candy.cpp42
-rw-r--r--other/knight_probability_chessboard.cpp41
-rw-r--r--other/koko_eating_bananas.cpp30
-rw-r--r--other/kth_element_in_stream.cpp32
-rw-r--r--other/kth_largest_element.cpp25
-rw-r--r--other/kth_largest_element_stream.cpp43
-rw-r--r--other/kth_missing_pos_num.cpp30
-rw-r--r--other/kth_smallest_lexicographical.cpp31
-rw-r--r--other/kth_smallest_sorted_matrix.cpp30
-rw-r--r--other/largest_colour_value_graph.cpp87
-rw-r--r--other/largest_int_add_target.cpp29
-rw-r--r--other/largest_multiple_three.cpp37
-rw-r--r--other/largest_odd_num_string.cpp28
-rw-r--r--other/largest_perimeter_triangle.cpp18
-rw-r--r--other/last_day_cross.cpp62
-rw-r--r--other/leaf_similar_trees.cpp28
-rw-r--r--other/leaf_similar_trees.rs44
-rw-r--r--other/letter_combo_number.cpp32
-rw-r--r--other/lexicographical_numbers.cpp43
-rw-r--r--other/lexicographically_small_string.cpp42
-rw-r--r--other/lfu_cache.cpp69
-rw-r--r--other/linked_list_cycle2.cpp31
-rw-r--r--other/linked_list_random.cpp40
-rw-r--r--other/longest_arithmetic_subseq.cpp37
-rw-r--r--other/longest_arithmetic_subseq_diff.cpp33
-rw-r--r--other/longest_common_subseq.cpp20
-rw-r--r--other/longest_common_subseq.rs23
-rw-r--r--other/longest_consecutive_sequence.cpp36
-rw-r--r--other/longest_cycle_graph.cpp58
-rw-r--r--other/longest_happy_string.cpp33
-rw-r--r--other/longest_increasing_subseq.cpp48
-rw-r--r--other/longest_palindrome_concat.cpp29
-rw-r--r--other/longest_palindrome_concat.rs39
-rw-r--r--other/longest_palindromic_subseq.cpp35
-rw-r--r--other/longest_palindromic_substr.cpp35
-rw-r--r--other/longest_path_diff_adjacent_char.cpp48
-rw-r--r--other/longest_path_diff_adjacent_char.rs77
-rw-r--r--other/longest_string_chain.cpp34
-rw-r--r--other/longest_subarr_ones.cpp31
-rw-r--r--other/longest_subseq_lim_sum.cpp31
-rw-r--r--other/longest_subseq_lim_sum.rs17
-rw-r--r--other/longest_substring_no_repeat.cpp29
-rw-r--r--other/longest_valid_course.cpp49
-rw-r--r--other/longest_valid_parentheses.cpp41
-rw-r--r--other/longest_word_dict.cpp31
-rw-r--r--other/longest_zigzag_bt.cpp46
-rw-r--r--other/lowest_common_ancestor.cpp33
-rw-r--r--other/lowest_common_ancestor_bst.cpp17
-rw-r--r--other/lru_cache.cpp60
-rw-r--r--other/magnetic_force_2_balls.cpp46
-rw-r--r--other/make_array_increasing.cpp59
-rw-r--r--other/make_string_great.cpp29
-rw-r--r--other/make_string_great.rs21
-rw-r--r--other/make_sum_divisible_p.cpp36
-rw-r--r--other/marbles_in_bags.cpp48
-rw-r--r--other/matchsticks_square.cpp46
-rw-r--r--other/matrix_diagonal_sum.cpp33
-rw-r--r--other/max_69.cpp21
-rw-r--r--other/max_69.rs11
-rw-r--r--other/max_area_cake.cpp25
-rw-r--r--other/max_area_island.cpp24
-rw-r--r--other/max_average_pass_ration.cpp57
-rw-r--r--other/max_bags_rocks.cpp22
-rw-r--r--other/max_bags_rocks.rs20
-rw-r--r--other/max_consecutive_ones3.cpp27
-rw-r--r--other/max_depth_binary_tree.cpp19
-rw-r--r--other/max_diff_node_ancestor.cpp22
-rw-r--r--other/max_diff_node_ancestor.rs61
-rw-r--r--other/max_distance_closest_person.cpp39
-rw-r--r--other/max_erasure_value.cpp26
-rw-r--r--other/max_ice_cream_bars.cpp39
-rw-r--r--other/max_ice_cream_bars.rs27
-rw-r--r--other/max_len_concat_str.cpp30
-rw-r--r--other/max_len_concat_str.rs29
-rw-r--r--other/max_length_pair_chain.cpp33
-rw-r--r--other/max_length_repeated_subarr.cpp26
-rw-r--r--other/max_network_rank.cpp44
-rw-r--r--other/max_num_events_attended2.cpp46
-rw-r--r--other/max_num_ksum_pair.cpp22
-rw-r--r--other/max_num_tasks_assign.cpp68
-rw-r--r--other/max_num_vowel_substr.cpp30
-rw-r--r--other/max_performance_team.cpp33
-rw-r--r--other/max_points_from_cards.cpp23
-rw-r--r--other/max_points_line.cpp50
-rw-r--r--other/max_points_line.rs91
-rw-r--r--other/max_product_3num.cpp40
-rw-r--r--other/max_product_split_bt.cpp19
-rw-r--r--other/max_product_split_bt.rs43
-rw-r--r--other/max_product_word_len.cpp31
-rw-r--r--other/max_profit_job.cpp28
-rw-r--r--other/max_profit_job.rs30
-rw-r--r--other/max_running_time_n_computer.cpp35
-rw-r--r--other/max_score_good_subarr.cpp36
-rw-r--r--other/max_score_mult_opp.cpp31
-rw-r--r--other/max_score_n_operations.cpp59
-rw-r--r--other/max_score_node_sequence.cpp43
-rw-r--r--other/max_subarray.cpp32
-rw-r--r--other/max_subseq_score.cpp47
-rw-r--r--other/max_sum_3_noverlap_subarr.cpp57
-rw-r--r--other/max_sum_binary_tree.cpp26
-rw-r--r--other/max_sum_circular_subarr.cpp49
-rw-r--r--other/max_sum_rectangle.cpp33
-rw-r--r--other/max_total_importance_road.cpp34
-rw-r--r--other/max_tranfer_requests.cpp46
-rw-r--r--other/max_twin_sum_list.cpp41
-rw-r--r--other/max_units_truck.cpp20
-rw-r--r--other/max_val_k_coin_pile.cpp42
-rw-r--r--other/max_value_give_idx.cpp43
-rw-r--r--other/max_width_binary_tree.cpp40
-rw-r--r--other/maximise_confusion_exam.cpp41
-rw-r--r--other/maximise_grid_happiness.cpp66
-rw-r--r--other/merge_sorted_array.cpp33
-rw-r--r--other/merge_sorted_array.rs14
-rw-r--r--other/merge_string_alt.cpp32
-rw-r--r--other/middle_linked_list.cpp18
-rw-r--r--other/middle_linked_list.rs28
-rw-r--r--other/min_abs_diff_bst.cpp27
-rw-r--r--other/min_ascii_strs.cpp38
-rw-r--r--other/min_avg_diff.cpp27
-rw-r--r--other/min_avg_diff.rs23
-rw-r--r--other/min_cost_arr_equal.cpp44
-rw-r--r--other/min_cost_change_expr.cpp40
-rw-r--r--other/min_cost_climbing_stairs.cpp16
-rw-r--r--other/min_cost_convert_string1.cpp51
-rw-r--r--other/min_cost_cut_stick.cpp45
-rw-r--r--other/min_cost_ticket.cpp42
-rw-r--r--other/min_cost_walk_weight_graph.cpp72
-rw-r--r--other/min_deletions_unique_char.cpp28
-rw-r--r--other/min_depth_binary_tree.cpp34
-rw-r--r--other/min_deviation_arr.cpp36
-rw-r--r--other/min_difficulty_schedule.cpp36
-rw-r--r--other/min_dist_bst_node.cpp20
-rw-r--r--other/min_dist_target_element.cpp20
-rw-r--r--other/min_falling_path_sum.cpp45
-rw-r--r--other/min_falling_path_sum.rs23
-rw-r--r--other/min_flips_abc.cpp22
-rw-r--r--other/min_fuel_report_captial.cpp50
-rw-r--r--other/min_genetic_mutation.cpp33
-rw-r--r--other/min_genetic_mutation.rs53
-rw-r--r--other/min_incr_arr_unique.cpp32
-rw-r--r--other/min_insertion_make_palindrome.cpp32
-rw-r--r--other/min_jump_reach_home.cpp44
-rw-r--r--other/min_max_array.cpp43
-rw-r--r--other/min_max_diff_pair.cpp47
-rw-r--r--other/min_move_palindrome.cpp34
-rw-r--r--other/min_moves_equal_array2.cpp18
-rw-r--r--other/min_num_arrow_balloon.cpp30
-rw-r--r--other/min_num_arrow_balloon.rs20
-rw-r--r--other/min_num_days_disconnect_island.cpp62
-rw-r--r--other/min_num_opp_arr_cont.cpp22
-rw-r--r--other/min_num_refueling_stops.cpp22
-rw-r--r--other/min_num_remove_mountain_arr.cpp51
-rw-r--r--other/min_num_vertices_node.cpp34
-rw-r--r--other/min_one_bit_0.cpp18
-rw-r--r--other/min_one_bit_0.rs29
-rw-r--r--other/min_operations_x_zero.cpp27
-rw-r--r--other/min_path_sum.cpp29
-rw-r--r--other/min_rounds_complete_all_tasks.cpp27
-rw-r--r--other/min_rounds_complete_all_tasks.rs30
-rw-r--r--other/min_score_path_city.cpp32
-rw-r--r--other/min_size_subarr_sum.cpp32
-rw-r--r--other/min_speed_arrive_time.cpp47
-rw-r--r--other/min_stack.cpp23
-rw-r--r--other/min_swap_group_1.cpp40
-rw-r--r--other/min_time_apples_tree.cpp39
-rw-r--r--other/min_time_apples_tree.rs47
-rw-r--r--other/min_time_complete_trip.cpp36
-rw-r--r--other/min_time_rope_colorful.cpp25
-rw-r--r--other/min_time_visit_cell_grid.cpp52
-rw-r--r--other/min_window_substring.cpp37
-rw-r--r--other/min_window_substring.rs43
-rw-r--r--other/mirror_reflection.cpp21
-rw-r--r--other/missing_number.cpp18
-rw-r--r--other/modify_graph_edge_weight.cpp91
-rw-r--r--other/most_stones_remove.cpp47
-rw-r--r--other/most_stones_remove.rs69
-rw-r--r--other/most_water.cpp21
-rw-r--r--other/my_calendar.cpp31
-rw-r--r--other/my_calendar2.cpp56
-rw-r--r--other/my_calendar3.cpp21
-rw-r--r--other/n_ary_tree_traverse.cpp25
-rw-r--r--other/n_queens2.cpp35
-rw-r--r--other/naming_company.cpp37
-rw-r--r--other/nearest_exit_maze.cpp37
-rw-r--r--other/nearest_exit_maze.rs37
-rw-r--r--other/new_21_game.cpp40
-rw-r--r--other/next_greater_element2.cpp43
-rw-r--r--other/next_permutation.cpp37
-rw-r--r--other/non_decreasing_array.cpp27
-rw-r--r--other/non_decreasing_subseq.cpp46
-rw-r--r--other/non_overlapping_interval.cpp38
-rw-r--r--other/nth_tribonacci_number.cpp61
-rw-r--r--other/num_bad_pairs.cpp28
-rw-r--r--other/num_bad_pairs.rs30
-rw-r--r--other/num_closed_islands.cpp61
-rw-r--r--other/num_cut_pizza.cpp58
-rw-r--r--other/num_dice_roll_target_sum.cpp21
-rw-r--r--other/num_enclaves.cpp45
-rw-r--r--other/num_even_nums.cpp29
-rw-r--r--other/num_good_path.cpp75
-rw-r--r--other/num_increasing_path.cpp54
-rw-r--r--other/num_longest_incr_subseq.cpp53
-rw-r--r--other/num_matching_subsequence.cpp34
-rw-r--r--other/num_music_playlists.cpp40
-rw-r--r--other/num_nodes_sub_tree.cpp47
-rw-r--r--other/num_nodes_sub_tree.rs39
-rw-r--r--other/num_op_connect_network.cpp41
-rw-r--r--other/num_people_aware_secret.cpp27
-rw-r--r--other/num_same_consecutive_diff.cpp32
-rw-r--r--other/num_smaller_num_self.cpp44
-rw-r--r--other/num_squareful_arrays.cpp59
-rw-r--r--other/num_subseq_satisfy.cpp34
-rw-r--r--other/num_to_hex_binary.cpp55
-rw-r--r--other/num_valid_words_puzzle.cpp40
-rw-r--r--other/num_ways_arrive_dest.cpp62
-rw-r--r--other/num_ways_dict.cpp35
-rw-r--r--other/num_ways_remain_place.cpp32
-rw-r--r--other/num_ways_reorder_array.cpp57
-rw-r--r--other/num_weak_char_game.cpp23
-rw-r--r--other/num_zero_filled_subarr.cpp29
-rw-r--r--other/number_1bits.cpp20
-rw-r--r--other/number_atoms.cpp75
-rw-r--r--other/number_islands.cpp30
-rw-r--r--other/number_provinces.cpp41
-rw-r--r--other/number_steps_to_0.cpp20
-rw-r--r--other/number_submatrices_sum_target.cpp24
-rw-r--r--other/odd_even_linke_list.cpp22
-rw-r--r--other/odd_even_linke_list.rs38
-rw-r--r--other/ones_and_zeroes.cpp36
-rw-r--r--other/online_stock_span.cpp43
-rw-r--r--other/online_stock_span.rs51
-rw-r--r--other/optimal_partition_string.cpp31
-rw-r--r--other/orderly_queue.cpp20
-rw-r--r--other/orderly_queue.rs22
-rw-r--r--other/out_of_bounds_paths.cpp35
-rw-r--r--other/pacific_atlantic_water_flow.cpp38
-rw-r--r--other/paint_house3.cpp34
-rw-r--r--other/painting_grid_three_colour.cpp58
-rw-r--r--other/painting_walls.cpp50
-rw-r--r--other/pairs_spells_potions.cpp45
-rw-r--r--other/palindrome_linked_list.cpp32
-rw-r--r--other/palindrome_number.rs24
-rw-r--r--other/palindrome_pairs.cpp38
-rw-r--r--other/palindrome_partitioning.cpp50
-rw-r--r--other/parallel_courses3.cpp54
-rw-r--r--other/partition_array_max_sum.cpp36
-rw-r--r--other/partition_array_pivot.rs32
-rw-r--r--other/partition_list.cpp20
-rw-r--r--other/partition_min_binary_array.cpp18
-rw-r--r--other/pascals_triangle.cpp19
-rw-r--r--other/path_max_probability.cpp52
-rw-r--r--other/path_min_effort.cpp34
-rw-r--r--other/path_min_effort1.cpp42
-rw-r--r--other/path_sum.cpp23
-rw-r--r--other/path_sum2.cpp25
-rw-r--r--other/peak_idx_mountain_arr.cpp25
-rw-r--r--other/peeking_iterator.cpp32
-rw-r--r--other/percentage_letter_string.cpp20
-rw-r--r--other/perfect_squares.cpp23
-rw-r--r--other/perfect_squares.rs21
-rw-r--r--other/permutation_in_string.cpp47
-rw-r--r--other/permutation_sequence.cpp25
-rw-r--r--other/permutations.cpp26
-rw-r--r--other/permutations2.cpp29
-rw-r--r--other/poor-pigs.cpp8
-rw-r--r--other/possible_bipartition.cpp45
-rw-r--r--other/possible_bipartition.rs40
-rw-r--r--other/power_3.cpp19
-rw-r--r--other/power_of_four.cpp24
-rw-r--r--other/power_of_four.rs24
-rw-r--r--other/power_of_two.cpp11
-rw-r--r--other/predict_winner.cpp40
-rw-r--r--other/prefix_suffix_search.cpp26
-rw-r--r--other/profitable_schemes.cpp71
-rw-r--r--other/pseudo_palindrome_binary_tree.cpp29
-rw-r--r--other/push_dominoes.cpp31
-rw-r--r--other/queue_reconstruction.cpp20
-rw-r--r--other/range_sum_bst.cpp22
-rw-r--r--other/range_sum_bst.rs38
-rw-r--r--other/range_sum_query_2d.cpp40
-rw-r--r--other/range_sum_query_mutable.cpp61
-rw-r--r--other/ransom_note.cpp23
-rw-r--r--other/rectangle_area.cpp16
-rw-r--r--other/rectangle_area.rs14
-rw-r--r--other/rectangle_fewest_squares.cpp51
-rw-r--r--other/reduce_array_size_half.cpp30
-rw-r--r--other/reducing_dishes.cpp37
-rw-r--r--other/remove_adjacent_dup.cpp37
-rw-r--r--other/remove_adjacent_dup_str.cpp20
-rw-r--r--other/remove_adjacent_dup_str.rs20
-rw-r--r--other/remove_boxes.cpp40
-rw-r--r--other/remove_dupplicate.cpp22
-rw-r--r--other/remove_dupplicate.rs24
-rw-r--r--other/remove_element.cpp28
-rw-r--r--other/remove_element.rs22
-rw-r--r--other/remove_max_num_edge_traverse.cpp58
-rw-r--r--other/remove_nth_node.cpp18
-rw-r--r--other/remove_palindromic_subsequence.cpp19
-rw-r--r--other/remove_star_string.cpp40
-rw-r--r--other/remove_stones.cpp24
-rw-r--r--other/remove_stones.rs26
-rw-r--r--other/remove_subfolder_filesystem.cpp48
-rw-r--r--other/remove_substring.cpp25
-rw-r--r--other/reorder_route_city_zero.cpp48
-rw-r--r--other/reordered_power2.cpp24
-rw-r--r--other/reorganise_string.cpp41
-rw-r--r--other/repeated_substring_pattern.cpp31
-rw-r--r--other/restore_array.cpp37
-rw-r--r--other/restore_ip_addr.cpp56
-rw-r--r--other/reverse_integer.cpp30
-rw-r--r--other/reverse_linked_list.cpp16
-rw-r--r--other/reverse_linked_list2.cpp26
-rw-r--r--other/reverse_string.cpp15
-rw-r--r--other/reverse_string2.cpp34
-rw-r--r--other/reverse_string3.cpp21
-rw-r--r--other/reverse_vowel_string.cpp20
-rw-r--r--other/reverse_vowel_string.rs33
-rw-r--r--other/reverse_word_string.cpp30
-rw-r--r--other/reverse_word_string.rs31
-rw-r--r--other/roman_2_int.cpp43
-rw-r--r--other/rotate_function.cpp29
-rw-r--r--other/rotate_image.cpp18
-rw-r--r--other/rotate_image.rs27
-rw-r--r--other/running_sum_1d_array.cpp18
-rw-r--r--other/same_tree.cpp14
-rw-r--r--other/same_tree.rs71
-rw-r--r--other/satisfiability_eqaulity.cpp33
-rw-r--r--other/scramble_string.cpp55
-rw-r--r--other/search_2d_matrix.cpp35
-rw-r--r--other/search_2d_matrix2.cpp20
-rw-r--r--other/search_rotated_array.cpp37
-rw-r--r--other/search_rotated_array2.cpp48
-rw-r--r--other/search_suggestion_sys.cpp26
-rw-r--r--other/set_matrix_0.rs44
-rw-r--r--other/set_mismatch.cpp19
-rw-r--r--other/set_mismatch.rs37
-rw-r--r--other/short_encoding_words.cpp21
-rw-r--r--other/shortest_bridge.cpp82
-rw-r--r--other/shortest_dist_road_addition1.cpp48
-rw-r--r--other/shortest_path_alternate_color.cpp56
-rw-r--r--other/shortest_path_binary_matrix.cpp55
-rw-r--r--other/shortest_path_grid_obstacle.cpp48
-rw-r--r--other/shortest_path_grid_obstacle.rs38
-rw-r--r--other/shortest_path_keys.cpp109
-rw-r--r--other/shortest_path_vis_nodes.cpp62
-rw-r--r--other/shortest_unsorted_subarr.cpp30
-rw-r--r--other/shuffle_the_array.cpp39
-rw-r--r--other/similar_string_group.cpp63
-rw-r--r--other/simplify_path.cpp33
-rw-r--r--other/single_element_sorted_arr.cpp33
-rw-r--r--other/single_number.cpp38
-rw-r--r--other/single_number.rs22
-rw-r--r--other/single_number2.cpp29
-rw-r--r--other/single_product_array.cpp35
-rw-r--r--other/single_threaded_cpu.cpp31
-rw-r--r--other/single_threaded_cpu.rs59
-rw-r--r--other/skyline_problem.cpp28
-rw-r--r--other/sliding_puzzle.cpp53
-rw-r--r--other/sliding_window_max.cpp38
-rw-r--r--other/smallest_num_set.cpp45
-rw-r--r--other/smallest_string_swaps.cpp55
-rw-r--r--other/smallest_sufficient_team.cpp61
-rw-r--r--other/snakes_ladders.cpp47
-rw-r--r--other/snapshot_array.cpp42
-rw-r--r--other/sort_array.cpp27
-rw-r--r--other/sort_array_parity.cpp46
-rw-r--r--other/sort_char_freq.cpp26
-rw-r--r--other/sort_char_freq.rs16
-rw-r--r--other/sort_items_dependencies.cpp74
-rw-r--r--other/sort_matrix_diagonal.cpp21
-rw-r--r--other/sorted_arrary_bst.cpp21
-rw-r--r--other/soup_servings.cpp54
-rw-r--r--other/spiral_matrix.cpp37
-rw-r--r--other/spiral_matrix2.cpp26
-rw-r--r--other/split_array_consec_subseq.cpp33
-rw-r--r--other/stack_using_queues.cpp24
-rw-r--r--other/stamping_sequence.cpp34
-rw-r--r--other/steps_arr_increasing.cpp32
-rw-r--r--other/stone_game2.cpp39
-rw-r--r--other/stone_game3.cpp46
-rw-r--r--other/stone_game4.cpp16
-rw-r--r--other/strange_printer.cpp32
-rw-r--r--other/string_compression.cpp31
-rw-r--r--other/string_compression.rs38
-rw-r--r--other/string_compression2.cpp37
-rw-r--r--other/string_compression2.rs54
-rw-r--r--other/string_without_3a3b.cpp38
-rw-r--r--other/subarr_fixed_bound.cpp33
-rw-r--r--other/subarr_product_less_k.cpp23
-rw-r--r--other/subarr_sum_divisible_k.cpp32
-rw-r--r--other/substr_largest_variance.cpp48
-rw-r--r--other/sum_dist_tree.cpp45
-rw-r--r--other/sum_dist_tree.rs49
-rw-r--r--other/sum_even_num_queries.cpp22
-rw-r--r--other/sum_root_leaf_num.cpp42
-rw-r--r--other/sum_subarr_mins.cpp30
-rw-r--r--other/sum_subarr_mins.rs37
-rw-r--r--other/sum_subset_xor.cpp33
-rw-r--r--other/summary_ranges.cpp47
-rw-r--r--other/swap_node_linked_list.cpp45
-rw-r--r--other/swap_nodes_pairs.cpp21
-rw-r--r--other/symmetric_tree.cpp33
-rw-r--r--other/tallest_billboard.cpp26
-rw-r--r--other/task_scheduler.cpp36
-rw-r--r--other/text_justification.cpp56
-rw-r--r--other/thousand_separator.cpp20
-rw-r--r--other/time_base_key_val.cpp32
-rw-r--r--other/toeplitz_matrix.cpp30
-rw-r--r--other/toeplitz_matrix.rs22
-rw-r--r--other/top_k_freq_element.cpp18
-rw-r--r--other/top_k_freq_element.rs32
-rw-r--r--other/top_k_freq_words.cpp29
-rw-r--r--other/top_k_freq_words.rs26
-rw-r--r--other/transpose_matrix.cpp20
-rw-r--r--other/trapping_rain_water.cpp33
-rw-r--r--other/trie_prefix.cpp45
-rw-r--r--other/two_sum.cpp35
-rw-r--r--other/two_sum_2.cpp33
-rw-r--r--other/two_sum_4.cpp24
-rw-r--r--other/ugly_number.cpp21
-rw-r--r--other/ugly_number.rs19
-rw-r--r--other/uncrossed_lines.cpp39
-rw-r--r--other/unique_bst.cpp23
-rw-r--r--other/unique_bst2.cpp34
-rw-r--r--other/unique_morse_code_words.cpp25
-rw-r--r--other/unique_num_occurrences.cpp24
-rw-r--r--other/unique_num_occurrences.rs20
-rw-r--r--other/unique_paths.cpp22
-rw-r--r--other/unique_paths2.cpp39
-rw-r--r--other/unique_paths3.cpp38
-rw-r--r--other/unique_paths3.rs40
-rw-r--r--other/utf8_validation.cpp38
-rw-r--r--other/valid_anagram.cpp29
-rw-r--r--other/valid_arrangement_pairs.cpp73
-rw-r--r--other/valid_number.cpp45
-rw-r--r--other/valid_parentheses.cpp43
-rw-r--r--other/valid_stack_seq.cpp32
-rw-r--r--other/valid_sudoku.cpp38
-rw-r--r--other/valid_sudoku.rs27
-rw-r--r--other/validate_bst.cpp24
-rw-r--r--other/verify_alien_dict.cpp42
-rw-r--r--other/vertical_order_bst.cpp29
-rw-r--r--other/ways_to_paint_nx3_grid.cpp20
-rw-r--r--other/where_will_ball_fall.cpp50
-rw-r--r--other/where_will_ball_fall.rs38
-rw-r--r--other/wiggle_subsequence.cpp23
-rw-r--r--other/word_break.cpp38
-rw-r--r--other/word_ladder.cpp39
-rw-r--r--other/word_ladder2.cpp47
-rw-r--r--other/word_pattern.cpp25
-rw-r--r--other/word_pattern.rs26
-rw-r--r--other/word_search.cpp53
-rw-r--r--other/word_search2.cpp70
-rw-r--r--other/word_search2.rs59
-rw-r--r--other/word_subsets.cpp57
-rw-r--r--other/zigzag_conversion.cpp43
-rw-r--r--painting_grid_three_colours.c78
-rw-r--r--painting_grid_three_colours.py42
-rw-r--r--partition_arr_max_diff_k.c32
-rw-r--r--partition_arr_max_diff_k.py34
-rw-r--r--push_dominoes.c47
-rw-r--r--push_dominoes.py32
-rw-r--r--rabbits_in_forest.c36
-rw-r--r--rabbits_in_forest.py30
-rw-r--r--random_pick_weight.c57
-rw-r--r--random_pick_weight.py36
-rw-r--r--res_str_adj_remove.c42
-rw-r--r--res_str_adj_remove.py38
-rw-r--r--self_dividing_numbers.c53
-rw-r--r--self_dividing_numbers.py30
-rw-r--r--set_matrix_zeroes.c44
-rw-r--r--set_matrix_zeroes.py34
-rw-r--r--snakes_ladders.c82
-rw-r--r--snakes_ladders.py65
-rw-r--r--sum_k_mirror_num.c60
-rw-r--r--sum_k_mirror_num.py277
-rw-r--r--three_consecutive_odds.c8
-rw-r--r--three_consecutive_odds.py10
-rw-r--r--total_char_str_transform1.c40
-rw-r--r--total_char_str_transform1.py31
-rw-r--r--total_char_str_transform2.c79
-rw-r--r--total_char_str_transform2.py122
-rw-r--r--type_of_triangle.c36
-rw-r--r--type_of_triangle.py29
-rw-r--r--using_robot_print_lex_small_str.c67
-rw-r--r--using_robot_print_lex_small_str.py35
-rw-r--r--valid_square.c46
-rw-r--r--valid_square.py41
-rw-r--r--zero_array_transformation1.c45
-rw-r--r--zero_array_transformation1.py36
-rw-r--r--zero_array_transformation3.c127
-rw-r--r--zero_array_transformation3.py41
838 files changed, 7321 insertions, 24643 deletions
diff --git a/.gitignore b/.gitignore
index 11a3bd5..477729e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
a.out
.gdb_history
__pycache__
+.venv
diff --git a/apply_operations_arr_max_sqr.c b/apply_operations_arr_max_sqr.c
new file mode 100644
index 0000000..150c721
--- /dev/null
+++ b/apply_operations_arr_max_sqr.c
@@ -0,0 +1,37 @@
+// 2897. Apply Operations on Array to Maximize Sum of Squares
+#include "leetcode.h"
+
+/*
+ * you are given a 0-indexed integer array 'nums' and a positive integer 'k'.
+ * you can do the following operation on the array any number of times: choose
+ * any two distinct indices 'i' and 'j' and simultaneously update the values of
+ * 'nums[i]' to '(nums[i] & nums[j])' and 'nums[j]' to '(nums[i] | nums[j])'.
+ * you have to choose 'k' elements from the final array and calcluate the sum of
+ * their squares. return the maximum sum of squares you can achieve. since the
+ * answer can be very large, return it modulo 10^9+7.
+ */
+
+int maxSum(int *nums, int numsSize, int k) {
+ int cnt[32] = {0};
+ for (int i = 0; i < numsSize; i++)
+ for (int j = 0; j < 32; j++)
+ if (nums[i] & (1 << j))
+ cnt[j]++;
+ int ans = 0, mod = 1e9 + 7;
+ for (int i = 0; i < k; i++) {
+ int curr = 0;
+ for (int j = 0; j < 32; j++)
+ if (cnt[j] > 0) {
+ cnt[j]--;
+ curr += 1 << j;
+ }
+ ans = (ans + 1L * curr * curr % mod) % mod;
+ }
+ return ans;
+}
+
+int main() {
+ int n1[] = {2, 6, 5, 8}, n2[] = {4, 5, 4, 7};
+ printf("%d\n", maxSum(n1, ARRAY_SIZE(n1), 2)); // expect: 261
+ printf("%d\n", maxSum(n2, ARRAY_SIZE(n2), 3)); // expect: 90
+}
diff --git a/apply_operations_arr_max_sqr.py b/apply_operations_arr_max_sqr.py
new file mode 100644
index 0000000..e3b5ade
--- /dev/null
+++ b/apply_operations_arr_max_sqr.py
@@ -0,0 +1,31 @@
+# 2897. Apply Operations on Array to Maximize Sum of Squares
+from collections import Counter
+
+"""
+you are given a 0-indexed integer array 'nums' and a positive integer 'k'.
+you can do the following operation on the array any number of times: choose
+any two distinct indices 'i' and 'j' and simultaneously update the values of
+'nums[i]' to '(nums[i] & nums[j])' and 'nums[j]' to '(nums[i] | nums[j])'.
+you have to choose 'k' elements from the final array and calcluate the sum of
+their squares. return the maximum sum of squares you can achieve. since the
+answer can be very large, return it modulo 10^9+7.
+"""
+
+
+class Solution(object):
+ def maxSum(self, nums, k):
+ """
+ :type nums: List[int]
+ :type k: int
+ :rtype: int
+ """
+ cnt = Counter(i for j in nums for i in range(32) if j & (1 << i))
+ return sum(sum((cnt[i] > j) << i for i in range(32)) ** 2 for j in range(k)) % (
+ 10**9 + 7
+ )
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.maxSum(nums=[2, 6, 5, 8], k=2))
+ print(obj.maxSum(nums=[4, 5, 4, 7], k=3))
diff --git a/build_arr_permutation.c b/build_arr_permutation.c
new file mode 100644
index 0000000..379e989
--- /dev/null
+++ b/build_arr_permutation.c
@@ -0,0 +1,31 @@
+// 1920. Build Array from Permutation
+#include "leetcode.h"
+
+/*
+ * given a 0-based permutation 'nums', build an array 'ans' of the same length
+ * where 'ans[i] = nums[nums[i]]' for each '0 <= i < nums.len' and return it. a
+ * 0-based permutation 'nums' is an array of distinct integers from 0 to
+ * 'nums.len - 1'.
+ */
+
+int *buildArray(int *nums, int numsSize, int *returnSize) {
+ *returnSize = numsSize;
+ for (int i = 0; i < numsSize; i++)
+ nums[i] += (nums[nums[i]] & 1023) << 10;
+ for (int i = 0; i < numsSize; i++)
+ nums[i] >>= 10;
+ return nums;
+}
+
+int main() {
+ int n1[] = {0, 2, 1, 5, 3, 4}, rs1;
+ int n2[] = {5, 0, 1, 2, 3, 4}, rs2;
+ int *ba1 = buildArray(n1, ARRAY_SIZE(n1), &rs1);
+ int *ba2 = buildArray(n2, ARRAY_SIZE(n2), &rs2);
+ for (int i = 0; i < rs1; i++)
+ printf("%d ", ba1[i]); // expect: 0 1 2 4 5 3
+ printf("\n");
+ for (int i = 0; i < rs2; i++)
+ printf("%d ", ba2[i]); // expect: 4 5 0 1 2 3
+ printf("\n");
+}
diff --git a/build_arr_permutation.py b/build_arr_permutation.py
new file mode 100644
index 0000000..3b3baa7
--- /dev/null
+++ b/build_arr_permutation.py
@@ -0,0 +1,23 @@
+# 1920. Build Array from Permutation
+
+"""
+given a 0-based permutation 'nums', build an array 'ans' of the same length
+where 'ans[i] = nums[nums[i]]' for each '0 <= i < nums.len' and return it. a
+0-based permutation 'nums' is an array of distinct integers from 0 to
+'nums.len - 1'.
+"""
+
+
+class Solution(object):
+ def buildArray(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: List[int]
+ """
+ return [nums[i] for i in nums]
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.buildArray(nums=[0, 2, 1, 5, 3, 4]))
+ print(obj.buildArray(nums=[5, 0, 1, 2, 3, 4]))
diff --git a/candy.c b/candy.c
index 318aa2f..4afb5ae 100644
--- a/candy.c
+++ b/candy.c
@@ -1,6 +1,5 @@
// 135. Candy
-#include <stdio.h>
-#include <stdlib.h>
+#include "leetcode.h"
/*
* there are 'n' children standing in a line. each child is assigned a rating
@@ -12,48 +11,34 @@
* candies to the children
*/
-int candy(int *ratings, int ratings_size) {
- if (!ratings_size)
- return 0;
- int *a = (int *)malloc(sizeof(int) * ratings_size);
- a[0] = 1;
- for (int i = 1; i < ratings_size; i++) {
- if (ratings[i - 1] < ratings[i])
- a[i] = a[i - 1] + 1;
- else if (ratings[i - 1] == ratings[i])
- a[i] = 1;
- else {
- int j = i - 1, k = 1, n;
- while (j < ratings_size - 1 && ratings[j] > ratings[j + 1])
- k++, j++;
- if (a[i - 1] >= k) {
- n = k - 1;
- j = i;
- while (j < i + k - 1) {
- a[j] = n;
- n--;
- j++;
- }
- } else {
- n = k;
- j = i - 1;
- while (j < i + k - 1) {
- a[j] = n;
- n--;
- j++;
- }
- }
- i = j - 1;
+int candy(int *ratings, int ratingsSize) {
+ int candy = ratingsSize, i = 1;
+ while (i < ratingsSize) {
+ if (ratings[i] == ratings[i - 1]) {
+ i++;
+ continue;
}
+ int peak = 0;
+ while (ratings[i] > ratings[i - 1]) {
+ peak++;
+ candy += peak;
+ i++;
+ if (i == ratingsSize)
+ return candy;
+ }
+ int valley = 0;
+ while (i < ratingsSize && ratings[i] < ratings[i - 1]) {
+ valley++;
+ candy += valley;
+ i++;
+ }
+ candy -= fmin(peak, valley);
}
- int ans = 0;
- for (int i = 0; i < ratings_size; i++)
- ans += a[i];
- return ans;
+ return candy;
}
int main() {
int r1[] = {1, 0, 2}, r2[] = {1, 2, 2};
- printf("%d\n", candy(r1, 3)); // expect: 5
- printf("%d\n", candy(r2, 3)); // expect: 4
+ printf("%d\n", candy(r1, ARRAY_SIZE(r1))); // expect: 5
+ printf("%d\n", candy(r2, ARRAY_SIZE(r2))); // expect: 4
}
diff --git a/closest_node_2_nodes.c b/closest_node_2_nodes.c
index 85801e9..444505c 100644
--- a/closest_node_2_nodes.c
+++ b/closest_node_2_nodes.c
@@ -1,50 +1,46 @@
// 2359. Find Closest Node to Given Two Nodes
-#include <limits.h>
-#include <math.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
+#include "leetcode.h"
-int closestMeetingNode(int *edges, int edgesSize, int node1, int node2) {
- int n = edgesSize, *path1 = malloc(n * sizeof(int)),
- *path2 = malloc(n * sizeof(int));
- memset(path1, -1, n * sizeof(int));
- memset(path2, -1, n * sizeof(int));
- int p = node1, step = 0;
- while (1) {
- path1[p] = step;
- step++;
- p = edges[p];
- if (p == -1)
- break;
- if (path1[p] != -1)
- break;
+/*
+ * you are given a directed graph of 'n' nodes numbered from 0 to 'n - 1', where
+ * each node has at most one outgoing edge. the graph is represented with a
+ * given 0-indexed array 'edges' of size 'n', indicating that there is a
+ * directed edge from node 'i' to node 'edges[i]'. if there is no outgoing edge
+ * from 'i' then 'edges[i] == -1'. you are also given two integers 'node1' and
+ * 'node2'. return the indes of the node that can be reached from both 'node1'
+ * and 'node2' such that the maximum between the distance from 'node1' to that
+ * node and from 'node2' to that node is minimised
+ */
+
+void dfs(int node, int dist, int *edge, int *n) {
+ while (node != -1 && n[node] == -1) {
+ n[node] = dist++;
+ node = edge[node];
}
- p = node2;
- step = 0;
- while (1) {
- path2[p] = step;
- step++;
- p = edges[p];
- if (p == -1)
- break;
- if (path2[p] != -1)
- break;
+}
+
+int closestMeetingNode(int *edges, int edgesSize, int node1, int node2) {
+ int ans = -1, dist = INT_MAX;
+ int *n1 = (int *)malloc(edgesSize * sizeof(int));
+ int *n2 = (int *)malloc(edgesSize * sizeof(int));
+ for (int i = 0; i < edgesSize; i++) {
+ n1[i] = -1;
+ n2[i] = -1;
}
- int min = INT_MAX, ans = -1;
- for (int i = 0; i < n; i++)
- if (path1[i] != -1 && path2[i] != -1)
- if (fmax(path1[i], path2[i]) < min) {
- min = fmax(path1[i], path2[i]);
- ans = i;
- }
- free(path1);
- free(path2);
+ dfs(node1, 0, edges, n1);
+ dfs(node2, 0, edges, n2);
+ for (int i = 0; i < edgesSize; ++i)
+ if (fmin(n1[i], n2[i]) >= 0 && fmax(n1[i], n2[i]) < dist) {
+ dist = fmax(n1[i], n2[i]);
+ ans = i;
+ }
+ free(n1);
+ free(n2);
return ans;
}
int main() {
- int edges1[] = {2, 2, 3, -1}, edges2[] = {1, 2, -1};
- printf("%d\n", closestMeetingNode(edges1, 3, 0, 2)); // expect: 2
- printf("%d\n", closestMeetingNode(edges2, 3, 0, 2)); // expect: 2
+ int e1[] = {2, 2, 3, -1}, e2[] = {1, 2, -1};
+ printf("%d\n", closestMeetingNode(e1, ARRAY_SIZE(e1), 0, 1)); // expect: 2
+ printf("%d\n", closestMeetingNode(e2, ARRAY_SIZE(e2), 0, 2)); // expect: 2
}
diff --git a/closest_node_2_nodes.py b/closest_node_2_nodes.py
new file mode 100644
index 0000000..a271f84
--- /dev/null
+++ b/closest_node_2_nodes.py
@@ -0,0 +1,46 @@
+# 2359. Find Closest Node to Given Two Nodes
+
+"""
+you are given a directed graph of 'n' nodes numbered from 0 to 'n - 1', where
+each node has at most one outgoing edge. the graph is represented with a
+given 0-indexed array 'edges' of size 'n', indicating that there is a
+directed edge from node 'i' to node 'edges[i]'. if there is no outgoing edge
+from 'i' then 'edges[i] == -1'. you are also given two integers 'node1' and
+'node2'. return the indes of the node that can be reached from both 'node1'
+and 'node2' such that the maximum between the distance from 'node1' to that
+node and from 'node2' to that node is minimised
+"""
+
+
+class Solution(object):
+ def dfs(self, node, edges, dist, vis):
+ vis[node] = True
+ neigh = edges[node]
+ if neigh != -1 and vis[neigh] == False:
+ dist[neigh] = dist[node] + 1
+ self.dfs(neigh, edges, dist, vis)
+
+ def closestMeetingNode(self, edges, node1, node2):
+ """
+ :type edges: List[int]
+ :type node1: int
+ :type node2: int
+ :rtype: int
+ """
+ n, ans = len(edges), -1
+ min_dist = float("inf")
+ n1, n2 = [0] * n, [0] * n
+ v1, v2 = [False] * n, [False] * n
+ self.dfs(node1, edges, n1, v1)
+ self.dfs(node2, edges, n2, v2)
+ for i in range(n):
+ if v1[i] and v2[i] and min_dist > max(n1[i], n2[i]):
+ min_dist = max(n1[i], n2[i])
+ ans = i
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.closestMeetingNode(edges=[2, 2, 3, -1], node1=0, node2=1))
+ print(obj.closestMeetingNode(edges=[1, 2, -1], node1=0, node2=2))
diff --git a/count_complete_subarr_arr.c b/count_complete_subarr_arr.c
new file mode 100644
index 0000000..bd16ad4
--- /dev/null
+++ b/count_complete_subarr_arr.c
@@ -0,0 +1,50 @@
+// 2799. Count Complete Subarrays in an Array
+#include "leetcode.h"
+
+/*
+ * you are given an array 'nums' consisting of positive integers. we call a
+ * subarray of an array complete if the following condition is satisfied. the
+ * number of distinct elements in the subarray is equal to the number of
+ * distinct elements in the whole array. return the number of complete
+ * subarrays. a subarray is a contiguous non-empty part of an array.
+ */
+
+int countCompleteSubarrays(int *nums, int numsSize) {
+ int elem[2001] = {0}, distinct = 0, ans = 0;
+ for (int i = 0; i < numsSize; i++) {
+ if (!elem[nums[i]])
+ distinct++;
+ elem[nums[i]]++;
+ }
+ int low = 0, high = 0, curr = 0;
+ memset(elem, 0, sizeof(elem));
+ while (curr < distinct) {
+ if (!elem[nums[high]])
+ curr++;
+ elem[nums[high]]++;
+ high++;
+ }
+ ans += numsSize - high + 1;
+ while (low < numsSize) {
+ elem[nums[low]]--;
+ if (!elem[nums[low]])
+ curr--;
+ while (high < numsSize && curr < distinct) {
+ if (!elem[nums[high]])
+ curr++;
+ elem[nums[high]]++;
+ high++;
+ }
+ if (curr < distinct)
+ break;
+ ans += numsSize - high + 1;
+ low++;
+ }
+ return ans;
+}
+
+int main() {
+ int n1[] = {1, 3, 1, 2, 2}, n2[] = {5, 5, 5, 5};
+ printf("%d\n", countCompleteSubarrays(n1, ARRAY_SIZE(n1))); // expect: 4
+ printf("%d\n", countCompleteSubarrays(n2, ARRAY_SIZE(n2))); // expect: 10
+}
diff --git a/count_complete_subarr_arr.py b/count_complete_subarr_arr.py
new file mode 100644
index 0000000..ca0371d
--- /dev/null
+++ b/count_complete_subarr_arr.py
@@ -0,0 +1,35 @@
+# 2799. Count Complete Subarrays in an Array
+from collections import Counter
+
+"""
+you are given an array 'nums' consisting of positive integers. we call a
+subarray of an array complete if the following condition is satisfied. the
+number of distinct elements in the subarray is equal to the number of
+distinct elements in the whole array. return the number of complete
+subarrays. a subarray is a contiguous non-empty part of an array.
+"""
+
+
+class Solution(object):
+ def countCompleteSubarrays(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ n, k, i = len(nums), len(set(nums)), 0
+ ans, cnt = 0, Counter()
+ for j in range(n):
+ cnt[nums[j]] += 1
+ while len(cnt) == k:
+ cnt[nums[i]] -= 1
+ if cnt[nums[i]] == 0:
+ del cnt[nums[i]]
+ i += 1
+ ans += i
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.countCompleteSubarrays(nums=[1, 3, 1, 2, 2]))
+ print(obj.countCompleteSubarrays(nums=[5, 5, 5, 5]))
diff --git a/count_hidden_sequences.c b/count_hidden_sequences.c
new file mode 100644
index 0000000..0d8c2e1
--- /dev/null
+++ b/count_hidden_sequences.c
@@ -0,0 +1,29 @@
+// 2145. Count the Hidden Sequences
+#include "leetcode.h"
+
+/*
+ * you are given a 0-indexed array of 'n' integers 'differences', which
+ * describes the differences between each pair of consecutive integers of a
+ * hidden sequence of length '(n + 1)'. you are further given two integers
+ * 'lower' and 'upper' that describe the inclusive range of values '[lower,
+ * upper]' that the hidden sequence can contain. return the number of possible
+ * hidden sequences there are. if there are no possible sequences, return 0.
+ */
+
+int numberOfArrays(int *differences, int differencesSize, int lower,
+ int upper) {
+ long long cnt = 0, a = 0, b = 0;
+ for (int i = 0; i < differencesSize; i++) {
+ cnt += differences[i];
+ a = fmax(a, cnt);
+ b = fmin(b, cnt);
+ }
+ return fmax(0L, (upper - lower) - (a - b) + 1);
+}
+
+int main() {
+ int d1[] = {1, -3, 4}, d2[] = {3, -4, 5, 1, -2}, d3[] = {4, -7, 2};
+ printf("%d\n", numberOfArrays(d1, ARRAY_SIZE(d1), 1, 6)); // expect: 2
+ printf("%d\n", numberOfArrays(d2, ARRAY_SIZE(d2), -4, 5)); // expect: 4
+ printf("%d\n", numberOfArrays(d3, ARRAY_SIZE(d3), 3, 6)); // expect: 0
+}
diff --git a/count_hidden_sequences.py b/count_hidden_sequences.py
new file mode 100644
index 0000000..c229f7a
--- /dev/null
+++ b/count_hidden_sequences.py
@@ -0,0 +1,30 @@
+# 2145. Count the Hidden Sequences
+from itertools import accumulate
+
+"""
+you are given a 0-indexed array of 'n' integers 'differences', which
+describes the differences between each pair of consecutive integers of a
+hidden sequence of length '(n + 1)'. you are further given two integers
+'lower' and 'upper' that describe the inclusive range of values '[lower,
+upper]' that the hidden sequence can contain. return the number of possible
+hidden sequences there are. if there are no possible sequences, return 0.
+"""
+
+
+class Solution(object):
+ def numberOfcntrrays(self, differences, lower, upper):
+ """
+ :type differences: List[int]
+ :type lower: int
+ :type upper: int
+ :rtype: int
+ """
+ cnt = list(accumulate(differences, initial=0))
+ return max(0, (upper - lower) - (max(cnt) - min(cnt)) + 1)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.numberOfcntrrays(differences=[1, -3, 4], lower=1, upper=6))
+ print(obj.numberOfcntrrays(differences=[3, -4, 5, 1, -2], lower=-4, upper=5))
+ print(obj.numberOfcntrrays(differences=[4, -7, 2], lower=3, upper=6))
diff --git a/count_interesting_subarr.c b/count_interesting_subarr.c
new file mode 100644
index 0000000..0a379d5
--- /dev/null
+++ b/count_interesting_subarr.c
@@ -0,0 +1,83 @@
+// 2845. Count of Interesting Subarrays
+#include "leetcode.h"
+
+/*
+ * you are given a 0-indexed integer array 'nums', an integer 'modulo', and an
+ * integer 'k'. your task is to find the count of the subarrays that are
+ * interesting. a subarray 'nums[l..r]' is interesting if the following
+ * condition holds: let 'cnt' be the number of indices 'i' in the range '[l, r]'
+ * such that 'nums[i] % modulo == k'. then 'cnt % modulo == k'. return an
+ * integer denoting the count of interesting subarrays.
+ */
+
+struct pair {
+ int key;
+ int val;
+};
+
+struct hash {
+ struct pair *pairs;
+ int size;
+ int max;
+};
+
+struct hash *hash_init(int size) {
+ struct hash *new = (struct hash *)malloc(sizeof(struct hash));
+ new->pairs = (struct pair *)malloc(size * sizeof(struct pair));
+ new->size = 0;
+ new->max = size;
+ return new;
+}
+
+int get(struct hash *obj, int key) {
+ for (int i = 0; i < obj->size; i++)
+ if (obj->pairs[i].key == key)
+ return obj->pairs[i].val;
+ return 0;
+}
+
+void put(struct hash *obj, int key, int val) {
+ for (int i = 0; i < obj->size; i++)
+ if (obj->pairs[i].key == key) {
+ obj->pairs[i].val = val;
+ return;
+ }
+ if (obj->size == obj->max) {
+ obj->max *= 2;
+ obj->pairs =
+ (struct pair *)realloc(obj->pairs, obj->max * sizeof(struct pair));
+ }
+ obj->pairs[obj->size].key = key;
+ obj->pairs[obj->size].val = val;
+ obj->size++;
+}
+
+void hash_free(struct hash *obj) {
+ free(obj->pairs);
+ free(obj);
+}
+
+long long countInterestingSubarrays(int *nums, int numsSize, int modulo,
+ int k) {
+ int cnt = 0;
+ struct hash *map = hash_init(numsSize);
+ put(map, 0, 1);
+ long long ans = 0;
+ for (int i = 0; i < numsSize; i++) {
+ cnt += (nums[i] % modulo == k);
+ int k1 = cnt % modulo;
+ int k2 = (k1 - k + modulo) % modulo;
+ ans += get(map, k2);
+ put(map, k1, get(map, k1) + 1);
+ }
+ hash_free(map);
+ return ans;
+}
+
+int main() {
+ int n1[] = {3, 2, 4}, n2[] = {3, 1, 9, 6};
+ printf("%lld\n",
+ countInterestingSubarrays(n1, ARRAY_SIZE(n1), 2, 1)); // expect: 3
+ printf("%lld\n",
+ countInterestingSubarrays(n2, ARRAY_SIZE(n2), 3, 0)); // expect: 2
+}
diff --git a/count_interesting_subarr.py b/count_interesting_subarr.py
new file mode 100644
index 0000000..9e76d99
--- /dev/null
+++ b/count_interesting_subarr.py
@@ -0,0 +1,34 @@
+# 2845. Count of Interesting Subarrays
+from collections import Counter
+
+"""
+you are given a 0-indexed integer array 'nums', an integer 'modulo', and an
+integer 'k'. your task is to find the count of the subarrays that are
+interesting. a subarray 'nums[l..r]' is interesting if the following
+condition holds: let 'cnt' be the number of indices 'i' in the range '[l, r]'
+such that 'nums[i] % modulo == k'. then 'cnt % modulo == k'. return an
+integer denoting the count of interesting subarrays.
+"""
+
+
+class Solution(object):
+ def countInterestingSubarrays(self, nums, modulo, k):
+ """
+ :type nums: List[int]
+ :type modulo: int
+ :type k: int
+ :rtype: int
+ """
+ ans, cnt = 0, 0
+ m = Counter({0: 1})
+ for i in nums:
+ cnt = (cnt + (1 if i % modulo == k else 0)) % modulo
+ ans += m[(cnt - k) % modulo]
+ m[cnt] += 1
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.countInterestingSubarrays(nums=[3, 2, 4], modulo=2, k=1))
+ print(obj.countInterestingSubarrays(nums=[3, 1, 9, 6], modulo=3, k=0))
diff --git a/count_largest_group.c b/count_largest_group.c
new file mode 100644
index 0000000..4d9063b
--- /dev/null
+++ b/count_largest_group.c
@@ -0,0 +1,37 @@
+// 1399. Count Largest Group
+#include "leetcode.h"
+
+/*
+ * you are given an integer 'n'. each number from 1 to 'n' is grouped according
+ * to the sum of its digits. return the number of groups that have the largest
+ * size.
+ */
+
+int get_num(int n) {
+ int res = 0;
+ while (n) {
+ res += n % 10;
+ n /= 10;
+ }
+ return res;
+}
+
+int countLargestGroup(int n) {
+ int arr[37] = {0}, max = 0;
+ for (int i = 1; i <= n; i++) {
+ int curr = get_num(i);
+ arr[curr]++;
+ if (arr[curr] > max)
+ max = arr[curr];
+ }
+ int cnt = 0;
+ for (int i = 1; i <= 36; i++)
+ if (arr[i] == max)
+ cnt++;
+ return cnt;
+}
+
+int main() {
+ printf("%d\n", countLargestGroup(13)); // expect: 4
+ printf("%d\n", countLargestGroup(2)); // expect: 2
+}
diff --git a/count_largest_group.py b/count_largest_group.py
new file mode 100644
index 0000000..3158100
--- /dev/null
+++ b/count_largest_group.py
@@ -0,0 +1,39 @@
+# 1399. Count Largest Group
+
+"""
+you are given an integer 'n'. each number from 1 to 'n' is grouped according
+to the sum of its digits. return the number of groups that have the largest
+size.
+"""
+
+
+class Solution(object):
+ def get_num(self, n):
+ res = 0
+ while n != 0:
+ res += n % 10
+ n //= 10
+ return res
+
+ def countLargestGroup(self, n):
+ """
+ :type n: int
+ :rtype: int
+ """
+ arr, m = [0] * 37, 0
+ for i in range(1, n + 1):
+ curr = self.get_num(i)
+ arr[curr] += 1
+ if arr[curr] > m:
+ m = arr[curr]
+ cnt = 0
+ for i in range(37):
+ if arr[i] == m:
+ cnt += 1
+ return cnt
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.countLargestGroup(n=13))
+ print(obj.countLargestGroup(n=2))
diff --git a/count_num_arr_k_match_elem.c b/count_num_arr_k_match_elem.c
new file mode 100644
index 0000000..dd8838e
--- /dev/null
+++ b/count_num_arr_k_match_elem.c
@@ -0,0 +1,48 @@
+// 3405. Count the Number of Arrays with K Matching Adjacent Elements
+#include "leetcode.h"
+
+/*
+ * you are given three integers 'n', 'm', and 'k'. a good array 'arr' of size
+ * 'n' is defined as follows: each element in 'arr' is in inclusive range '[1,
+ * m]', and exactly 'k' indices 'i' where '1 <= i < n' satisfy the condition
+ * 'arr[i - 1] == arr[i]'. return the number of good arrays that can be formed.
+ * since the answer may be very large, return it modulo 10^9+7.
+ */
+
+const int mod = 1e9 + 7;
+
+long long mult(long long n, long long m) { return (n * m) % mod; }
+
+long long power(long long n, long long m) {
+ long long res = 1, base = n;
+ while (m > 0) {
+ if (m & 1)
+ res = mult(res, base);
+ base = mult(base, base);
+ m >>= 1;
+ }
+ return res;
+}
+
+long long inv(long long n) { return power(n, mod - 2); }
+
+long long factorial(long long n) {
+ long long res = 1;
+ for (long long i = 2; i <= n; ++i)
+ res = mult(res, i);
+ return res;
+}
+
+long long combine(long long n, long long m) {
+ return mult(factorial(n), inv(mult(factorial(m), factorial(n - m))));
+}
+
+int countGoodArrays(int n, int m, int k) {
+ return mult(mult(combine(n - 1, n - 1 - k), m), power(m - 1, n - 1 - k));
+}
+
+int main() {
+ printf("%d\n", countGoodArrays(3, 2, 1)); // expect: 4
+ printf("%d\n", countGoodArrays(4, 2, 2)); // expect: 6
+ printf("%d\n", countGoodArrays(5, 2, 0)); // expect: 2
+}
diff --git a/count_num_arr_k_match_elem.py b/count_num_arr_k_match_elem.py
new file mode 100644
index 0000000..a3bc73f
--- /dev/null
+++ b/count_num_arr_k_match_elem.py
@@ -0,0 +1,28 @@
+# 3405. Count the Number of Arrays with K Matching Adjacent Elements
+from math import comb
+
+"""
+you are given three integers 'n', 'm', and 'k'. a good array 'arr' of size
+'n' is defined as follows: each element in 'arr' is in inclusive range '[1,
+m]', and exactly 'k' indices 'i' where '1 <= i < n' satisfy the condition
+'arr[i - 1] == arr[i]'. return the number of good arrays that can be formed.
+since the answer may be very large, return it modulo 10^9+7.
+"""
+
+
+class Solution(object):
+ def countGoodArrays(self, n, m, k):
+ """
+ :type n: int
+ :type m: int
+ :type k: int
+ :rtype: int
+ """
+ return m * pow(m - 1, n - k - 1, mod := 1**9 + 7) * comb(n - 1, k) % mod
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.countGoodArrays(n=3, m=2, k=1))
+ print(obj.countGoodArrays(n=4, m=2, k=2))
+ print(obj.countGoodArrays(n=5, m=2, k=0))
diff --git a/count_num_balanced_perm.c b/count_num_balanced_perm.c
new file mode 100644
index 0000000..203f8c2
--- /dev/null
+++ b/count_num_balanced_perm.c
@@ -0,0 +1,78 @@
+// 3343. Count Number of Balanced Permutations
+#include "leetcode.h"
+
+/*
+ * you are given a string 'num'. a string of digits is called balanced if the
+ * sum of the digits at even indices is equal to the sum of the digits at odd
+ * indices. return the number of distinct permutations of 'num' that are
+ * balanced. since the answer may be very large, return it modulo 10e9+7. a
+ * permutation is a rearrangement of all the characters of a string.
+ */
+
+static int mod = 1e9 + 7;
+
+long long mod_exp(long long base, long long exp) {
+ long long res = 1;
+ base %= mod;
+ while (exp) {
+ if (exp & 1)
+ res = (res * base) % mod;
+ base = (base * base) % mod;
+ exp >>= 1;
+ }
+ return res;
+}
+
+int countBalancedPermutations(char *num) {
+ int n = strlen(num), freq[10] = {0};
+ for (int i = 0; i < n; i++)
+ freq[num[i] - '0']++;
+ int even_cnt = (n + 1) / 2, odd_cnt = n - even_cnt, sum = 0;
+ for (int i = 0; i < 10; i++)
+ sum += i * freq[i];
+ if (sum & 1)
+ return 0;
+ int target = sum / 2, max = n;
+ long long *fac = (long long *)malloc((max + 1) * sizeof(long long));
+ long long *ifac = (long long *)malloc((max + 1) * sizeof(long long));
+ fac[0] = 1;
+ for (int i = 1; i <= max; i++)
+ fac[i] = (fac[i - 1] * i) % mod;
+ ifac[max] = mod_exp(fac[max], mod - 2);
+ for (int i = max - 1; i >= 0; i--)
+ ifac[i] = (ifac[i + 1] * (i + 1)) % mod;
+ long long dp[11][42][730] = {{{0}}};
+ dp[0][0][0] = 1;
+ for (int i = 0; i < 10; i++) {
+ for (int j = 0; j <= even_cnt; j++) {
+ for (int k = 0; k <= target; k++) {
+ if (!dp[i][j][k])
+ continue;
+ int curr = freq[i];
+ for (int l = 0; l <= curr; l++) {
+ if (j + l > even_cnt)
+ break;
+ int ns = k + i * l;
+ if (ns > target)
+ break;
+ long long coef = (ifac[l] * ifac[curr - l]) % mod;
+ dp[i + 1][j + l][ns] =
+ (dp[i + 1][j + l][ns] + dp[i][j][k] * coef) % mod;
+ }
+ }
+ }
+ }
+ long long ans = dp[10][even_cnt][target];
+ ans = (ans * fac[even_cnt]) % mod;
+ ans = (ans * fac[odd_cnt]) % mod;
+ free(fac);
+ free(ifac);
+ return (int)ans;
+}
+
+int main() {
+ char *n1 = "123", *n2 = "112", *n3 = "12345";
+ printf("%d\n", countBalancedPermutations(n1)); // expect: 2
+ printf("%d\n", countBalancedPermutations(n2)); // expect: 1
+ printf("%d\n", countBalancedPermutations(n3)); // expect: 0
+}
diff --git a/count_num_balanced_perm.py b/count_num_balanced_perm.py
new file mode 100644
index 0000000..eebf3d7
--- /dev/null
+++ b/count_num_balanced_perm.py
@@ -0,0 +1,55 @@
+# 3343. Count Number of Balanced Permutations
+from collections import Counter
+from math import comb
+
+"""
+you are given a string 'num'. a string of digits is called balanced if the
+sum of the digits at even indices is equal to the sum of the digits at odd
+indices. return the number of distinct permutations of 'num' that are
+balanced. since the answer may be very large, return it modulo 10e9+7. a
+permutation is a rearrangement of all the characters of a string.
+"""
+
+
+class Solution(object):
+ def countBalancedPermutations(self, num):
+ """
+ :type num: str
+ :rtype: int
+ """
+ mod, n = 10**9 + 7, len(num)
+ total = sum(int(i) for i in num)
+ if total % 2:
+ return 0
+ fac = [1] * (n + 1)
+ ifac = [1] * (n + 1)
+ inv = [1] * (n + 1)
+ for i in range(1, n + 1):
+ fac[i] = fac[i - 1] * i % mod
+ for i in range(2, n + 1):
+ inv[i] = mod - (mod // i) * inv[mod % i] % mod
+ for i in range(1, n + 1):
+ ifac[i] = ifac[i - 1] * inv[i] % mod
+ half_sum = total // 2
+ half_len = n // 2
+ dp = [[0] * (half_len + 1) for _ in range(half_sum + 1)]
+ dp[0][0] = 1
+ digits = [0] * 10
+ for c in num:
+ d = int(c)
+ digits[d] += 1
+ for i in range(half_sum, d - 1, -1):
+ for j in range(half_len, 0, -1):
+ dp[i][j] = (dp[i][j] + dp[i - d][j - 1]) % mod
+ ans = dp[half_sum][half_len]
+ ans = ans * fac[half_len] % mod * fac[n - half_len] % mod
+ for cnt in digits:
+ ans = ans * ifac[cnt] % mod
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.countBalancedPermutations(num="123"))
+ print(obj.countBalancedPermutations(num="112"))
+ print(obj.countBalancedPermutations(num="12345"))
diff --git a/count_num_ideal_arr.c b/count_num_ideal_arr.c
new file mode 100644
index 0000000..298b1da
--- /dev/null
+++ b/count_num_ideal_arr.c
@@ -0,0 +1,36 @@
+// 2338. Count the Number of Ideal Arrays
+#include "leetcode.h"
+
+/*
+ * you are given two integers 'n' and 'maxValue' which are used to describe an
+ * ideal array. a 0-indexed integer array 'arr' of length 'n' is considered
+ * ideal if the following conditions hold true: every 'arr[i]' is a value from 1
+ * to 'maxValue' for '0 <= i < n', and every 'arr[i]' is divisble by 'arr[i -
+ * 1]'. return the number of distinct ideal arrays of length 'n'. since the
+ * answer may be very large, return it modulo 10^9+7.
+ */
+
+int idealArrays(int n, int maxValue) {
+ int cmb[10001][14] = {1}, cnt[10001][14] = {}, mod = 1e9 + 7;
+ if (!cmb[1][1]) {
+ for (int i = 1; i <= 10000; ++i)
+ for (int j = 0; j < 14; ++j)
+ cmb[i][j] = !j ? 1 : (cmb[i - 1][j - 1] + cmb[i - 1][j]) % mod;
+ for (int i = 1; i <= 10000; ++i) {
+ ++cnt[i][0];
+ for (int j = 2 * i; j <= 10000; j += i)
+ for (int k = 0; cnt[i][k]; ++k)
+ cnt[j][k + 1] += cnt[i][k];
+ }
+ }
+ int ans = 0;
+ for (int i = 1; i <= maxValue; ++i)
+ for (int j = 0; j < fmin(14, n) && cnt[i][j]; ++j)
+ ans = (1LL * cnt[i][j] * cmb[n - 1][j] + ans) % mod;
+ return ans;
+}
+
+int main() {
+ printf("%d\n", idealArrays(2, 5)); // expect: 10
+ printf("%d\n", idealArrays(5, 3)); // expect: 11
+}
diff --git a/count_num_ideal_arr.py b/count_num_ideal_arr.py
new file mode 100644
index 0000000..6966711
--- /dev/null
+++ b/count_num_ideal_arr.py
@@ -0,0 +1,38 @@
+# 2338. Count the Number of Ideal Arrays
+from collections import Counter
+from math import comb
+
+"""
+you are given two integers 'n' and 'maxValue' which are used to describe an
+ideal array. a 0-indexed integer array 'arr' of length 'n' is considered
+ideal if the following conditions hold true: every 'arr[i]' is a value from 1
+to 'maxValue' for '0 <= i < n', and every 'arr[i]' is divisble by 'arr[i -
+1]'. return the number of distinct ideal arrays of length 'n'. since the
+answer may be very large, return it modulo 10^9+7.
+"""
+
+
+class Solution(object):
+ def idealArrays(self, n, maxValue):
+ """
+ :type n: int
+ :type maxValue: int
+ :rtype: int
+ """
+ ans = maxValue
+ freq = {i: 1 for i in range(1, maxValue + 1)}
+ for i in range(1, n):
+ tmp = Counter()
+ for j in freq:
+ for k in range(2, maxValue // j + 1):
+ ans += comb(n - 1, i) * freq[j]
+ tmp[k * j] += freq[j]
+ freq = tmp
+ ans %= 10**9 + 7
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.idealArrays(n=2, maxValue=5))
+ print(obj.idealArrays(n=5, maxValue=3))
diff --git a/count_number_powerful_integers.cpp b/count_number_powerful_integers.cpp
deleted file mode 100644
index 2d5981d..0000000
--- a/count_number_powerful_integers.cpp
+++ /dev/null
@@ -1,41 +0,0 @@
-// 2999. Count the Number of Powerful Integers
-#include "leetcode.h"
-
-/*
- * you are given three integers 'start', 'finish', and 'limit'. you are also
- * given a 0-indexed string 's' representing a positive integer. a positive
- * integer 'x' is called powerful if it ends with 's' and each digit in 'x' is
- * at most 'limit'. return the total number of powerful integers in the range
- * '[start .. finish]'. a string 'x' is a suffix of a string 'y' if and only if
- * 'x' is a substring of 'y' that starts from some index in 'y' and extends to
- * the index 'y.length - 1'.
- */
-
-class Solution {
-private:
- long long cnt[16];
- long long get_cnt(char l, const string &n, const string &s) {
- long long res = cnt[n.size() - 1], i = 0, size = n.size() - s.size();
- do
- res += i == size ? n.substr(i) >= s
- : cnt[n.size() - i - 1] * (min(l, n[i]) - '1' + (i > 0));
- while (i < size && n[i++] < l);
- return res;
- }
-
-public:
- long long numberOfPowerfulInt(long long start, long long finish, int limit,
- string s) {
- for (int i = s.size(); i < 16; ++i)
- cnt[i] = i == s.size() ? 1 : cnt[i - 1] * (limit + 1);
- return get_cnt(limit + '1', to_string(finish), s) -
- get_cnt(limit + '1', to_string(start - 1), s);
- }
-};
-
-int main() {
- Solution obj;
- printf("%lld\n", obj.numberOfPowerfulInt(1, 6000, 4, "124")); // expect: 5
- printf("%lld\n", obj.numberOfPowerfulInt(15, 215, 6, "")); // expect: 2
- printf("%lld\n", obj.numberOfPowerfulInt(1000, 2000, 4, "3000")); // expect: 0
-}
diff --git a/count_subarr_fixed_bound.c b/count_subarr_fixed_bound.c
index 569fac4..1685be6 100644
--- a/count_subarr_fixed_bound.c
+++ b/count_subarr_fixed_bound.c
@@ -11,18 +11,15 @@
long long countSubarrays(int *nums, int numsSize, int minK, int maxK) {
long long ans = 0;
- int last_min = -1, last_max = -1, start = 0;
- for (int i = 0; i < numsSize; i++) {
- if (nums[i] > maxK || nums[i] < minK)
- start = i + 1;
- if (nums[i] == maxK)
- last_max = i;
+ int bad = -1, prev_min = -1, prev_max = -1;
+ for (int i = 0; i < numsSize; ++i) {
+ if (nums[i] < minK || nums[i] > maxK)
+ bad = i;
if (nums[i] == minK)
- last_min = i;
- int pos = fmin(last_max, last_min);
- if (start > pos)
- continue;
- ans += pos - start + 1;
+ prev_min = i;
+ if (nums[i] == maxK)
+ prev_max = i;
+ ans += fmax(0L, fmin(prev_min, prev_max) - bad);
}
return ans;
}
diff --git a/count_subarr_fixed_bound.py b/count_subarr_fixed_bound.py
index 44fd99c..7409f42 100644
--- a/count_subarr_fixed_bound.py
+++ b/count_subarr_fixed_bound.py
@@ -17,15 +17,15 @@ class Solution(object):
:type maxK: int
:rtype: int
"""
- ans, last_min, last_max, bad = 0, -1, -1, -1
+ ans, prev_min, prev_max, bad = 0, -1, -1, -1
for i, a in enumerate(nums):
if not minK <= a <= maxK:
bad = i
if a == minK:
- last_min = i
+ prev_min = i
if a == maxK:
- last_max = i
- ans += max(0, min(last_min, last_max) - bad)
+ prev_max = i
+ ans += max(0, min(prev_min, prev_max) - bad)
return ans
diff --git a/count_subarr_len_three_cond.c b/count_subarr_len_three_cond.c
new file mode 100644
index 0000000..3d61dd8
--- /dev/null
+++ b/count_subarr_len_three_cond.c
@@ -0,0 +1,22 @@
+// 3392. Count Subarrays of Length Three With a Condition
+#include "leetcode.h"
+
+/*
+ * given an integer array 'nums', return the number of subarrays of length 3
+ * such that the sum of the first and third number equals exactly half of the
+ * second number.
+ */
+
+int countSubarrays(int *nums, int numsSize) {
+ int cnt = 0;
+ for (int i = 1; i < numsSize - 1; ++i)
+ if (2 * (nums[i - 1] + nums[i + 1]) == nums[i])
+ cnt++;
+ return cnt;
+}
+
+int main() {
+ int n1[] = {1, 2, 1, 4, 1}, n2[] = {1, 1, 1};
+ printf("%d\n", countSubarrays(n1, ARRAY_SIZE(n1))); // expect: 1
+ printf("%d\n", countSubarrays(n2, ARRAY_SIZE(n2))); // expect: 0
+}
diff --git a/count_subarr_len_three_cond.py b/count_subarr_len_three_cond.py
new file mode 100644
index 0000000..cb542bd
--- /dev/null
+++ b/count_subarr_len_three_cond.py
@@ -0,0 +1,22 @@
+# 3392. Count Subarrays of Length Three With a Condition
+
+"""
+given an integer array 'nums', return the number of subarrays of length 3
+such that the sum of the first and third number equals exactly half of the
+second number.
+"""
+
+
+class Solution(object):
+ def countSubarrays(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ return sum(l + r << 1 == m for l, m, r in zip(nums, nums[1:], nums[2:]))
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.countSubarrays(nums=[1, 2, 1, 4, 1]))
+ print(obj.countSubarrays(nums=[1, 1, 1]))
diff --git a/count_subarr_max_elem_k.c b/count_subarr_max_elem_k.c
index e6bf5ad..4768843 100644
--- a/count_subarr_max_elem_k.c
+++ b/count_subarr_max_elem_k.c
@@ -9,19 +9,15 @@
*/
long long countSubarrays(int *nums, int numsSize, int k) {
- int max = 0, cnt = 0, idx[numsSize];
+ int max = -1, curr = 0;
long long ans = 0;
- for (int i = 0; i < numsSize; i++)
- max = max > nums[i];
- for (int i = 0; i < numsSize; i++)
- if (nums[i] == max)
- idx[cnt++] = i;
- for (int i = 0; i <= cnt - k; i++) {
- long long left = idx[i], right = idx[i + k - 1],
- bound = i - 1 >= 0 ? idx[i - 1] : -1;
- if (!i)
- bound = -1;
- ans += (left - bound) * (numsSize - right);
+ for (int i = 0; i < numsSize; ++i)
+ max = nums[i] > max ? nums[i] : max;
+ for (int l = 0, r = 0; r < numsSize; r++) {
+ curr += nums[r] == max;
+ while (curr >= k)
+ curr -= nums[l++] == max;
+ ans += l;
}
return ans;
}
diff --git a/count_subarr_max_elem_k.py b/count_subarr_max_elem_k.py
index 8f734f2..7852d49 100644
--- a/count_subarr_max_elem_k.py
+++ b/count_subarr_max_elem_k.py
@@ -15,18 +15,18 @@ class Solution(object):
:type k: int
:rtype: int
"""
+ ans, curr, l = 0, 0, 0
m = max(nums)
- ans, curr, i = 0, 0, 0
- for j in range(len(nums)):
- curr += nums[j] == m
+ for r in range(len(nums)):
+ curr += nums[r] == m
while curr >= k:
- curr -= nums[i] == m
- i += 1
- ans += i
+ curr -= nums[l] == m
+ l += 1
+ ans += l
return ans
if __name__ == "__main__":
obj = Solution()
- print(obj.countSubarrays(nums=[1, 3, 2, 3, 3], k=2)) # expect: 6
- print(obj.countSubarrays(nums=[1, 4, 2, 1], k=3)) # expect: 0
+ print(obj.countSubarrays(nums=[1, 3, 2, 3, 3], k=2))
+ print(obj.countSubarrays(nums=[1, 4, 2, 1], k=3))
diff --git a/count_subarr_score_less_k.c b/count_subarr_score_less_k.c
new file mode 100644
index 0000000..5c454d1
--- /dev/null
+++ b/count_subarr_score_less_k.c
@@ -0,0 +1,26 @@
+// 2302. Count Subarrays With Score Less Than K
+#include "leetcode.h"
+
+/*
+ * the score of an array is defined as the product of its sum and its length.
+ * given a positive integer array 'nums' and an integer 'k', return the number
+ * of non-empty subarrays of 'nums' whose score is strictly less than 'k'. a
+ * subarray is a contiguous sequence of elements within an array.
+ */
+
+long long countSubarrays(int *nums, int numsSize, long long k) {
+ long long ans = 0, curr = 0;
+ for (int j = 0, i = 0; j < numsSize; ++j) {
+ curr += nums[j];
+ while (curr * (j - i + 1) >= k)
+ curr -= nums[i++];
+ ans += j - i + 1;
+ }
+ return ans;
+}
+
+int main() {
+ int n1[] = {2, 1, 4, 3, 5}, n2[] = {1, 1, 1};
+ printf("%lld\n", countSubarrays(n1, ARRAY_SIZE(n1), 10)); // expect: 6
+ printf("%lld\n", countSubarrays(n2, ARRAY_SIZE(n2), 5)); // expect: 5
+}
diff --git a/count_subarr_score_less_k.py b/count_subarr_score_less_k.py
new file mode 100644
index 0000000..d60cb4b
--- /dev/null
+++ b/count_subarr_score_less_k.py
@@ -0,0 +1,31 @@
+# 2302. Count Subarrays With Score Less Than K
+
+"""
+the score of an array is defined as the product of its sum and its length.
+given a positive integer array 'nums' and an integer 'k', return the number
+of non-empty subarrays of 'nums' whose score is strictly less than 'k'. a
+subarray is a contiguous sequence of elements within an array.
+"""
+
+
+class Solution(object):
+ def countSubarrays(self, nums, k):
+ """
+ :type nums: List[int]
+ :type k: int
+ :rtype: int
+ """
+ ans, curr, i = 0, 0, 0
+ for j in range(len(nums)):
+ curr += nums[j]
+ while curr * (j - i + 1) >= k:
+ curr -= nums[i]
+ i += 1
+ ans += j - i + 1
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.countSubarrays(nums=[2, 1, 4, 3, 5], k=10))
+ print(obj.countSubarrays(nums=[1, 1, 1], k=5))
diff --git a/create_sorted_arr_instr.c b/create_sorted_arr_instr.c
new file mode 100644
index 0000000..2a3624d
--- /dev/null
+++ b/create_sorted_arr_instr.c
@@ -0,0 +1,51 @@
+// 1649. Create Sorted Array through Instructions
+#include "leetcode.h"
+
+/*
+ * 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]'. return the total cost to insert all
+ * elements from 'instructions' into 'nums'. since the answer may be large,
+ * return it modulo 10^9 + 7
+ */
+
+static int arr[10001];
+
+void update(int x) {
+ while (x < 10001) {
+ arr[x]++;
+ x += x & -x;
+ }
+}
+
+int get(int x) {
+ int res = 0;
+ while (x > 0) {
+ res += arr[x];
+ x -= x & -x;
+ }
+ return res;
+}
+
+int createSortedArray(int *instructions, int instructionsSize) {
+ memset(arr, 0, sizeof(arr));
+ int ans = 0, mod = 1e9 + 7;
+ for (int i = 0; i < instructionsSize; i++) {
+ ans =
+ (ans + fmin(get(instructions[i] - 1), i - get(instructions[i]))) % mod;
+ update(instructions[i]);
+ }
+ return ans;
+}
+
+int main() {
+ int i1[] = {1, 5, 6, 2}, i2[] = {1, 2, 3, 6, 5, 4},
+ i3[] = {1, 2, 3, 3, 2, 4, 2, 1, 2};
+ printf("%d\n", createSortedArray(i1, ARRAY_SIZE(i1))); // expect: 1
+ printf("%d\n", createSortedArray(i2, ARRAY_SIZE(i2))); // expect: 3
+ printf("%d\n", createSortedArray(i3, ARRAY_SIZE(i3))); // expect: 4
+}
diff --git a/create_sorted_arr_instr.py b/create_sorted_arr_instr.py
new file mode 100644
index 0000000..b354c73
--- /dev/null
+++ b/create_sorted_arr_instr.py
@@ -0,0 +1,48 @@
+# 1649. Create Sorted Array through Instructions
+
+"""
+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]'. return the total cost to insert all
+elements from 'instructions' into 'nums'. since the answer may be large,
+return it modulo 10^9 + 7
+"""
+
+
+class Solution(object):
+ def createSortedArray(self, instructions):
+ """
+ :type instructions: List[int]
+ :rtype: int
+ """
+ m = max(instructions)
+ arr = [0] * (m + 1)
+
+ def update(x):
+ while x <= m:
+ arr[x] += 1
+ x += x & -x
+
+ def get(x):
+ res = 0
+ while x > 0:
+ res += arr[x]
+ x -= x & -x
+ return res
+
+ ans = 0
+ for i, j in enumerate(instructions):
+ ans += min(get(j - 1), i - get(j))
+ update(j)
+ return ans % (10**9 + 7)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.createSortedArray(instructions=[1, 5, 6, 2]))
+ print(obj.createSortedArray(instructions=[1, 2, 3, 6, 5, 4]))
+ print(obj.createSortedArray(instructions=[1, 3, 3, 3, 2, 4, 2, 1, 2]))
diff --git a/distribute_candies_children2.c b/distribute_candies_children2.c
new file mode 100644
index 0000000..1275d6a
--- /dev/null
+++ b/distribute_candies_children2.c
@@ -0,0 +1,22 @@
+// 2929. Distribute Candies Among Children II
+#include "leetcode.h"
+
+/*
+ * you are given two positive integers 'n' and 'limit'. return the total number
+ * of ways to distritube 'n' candies among 3 children such that no child gets
+ * more than 'limit' candies.
+ */
+
+long long distributeCandies(int n, int limit) {
+ long long cnt = 0;
+ for (int i = fmax(0, n - 2 * limit); i <= fmin(limit, n); i++) {
+ int j = fmin(limit, n - i) - fmax(0, n - i - limit) + 1;
+ cnt += fmax(0, j);
+ }
+ return cnt;
+}
+
+int main() {
+ printf("%lld\n", distributeCandies(5, 2)); // expect: 3
+ printf("%lld\n", distributeCandies(3, 3)); // expect: 10
+}
diff --git a/distribute_candies_children2.py b/distribute_candies_children2.py
new file mode 100644
index 0000000..6123df8
--- /dev/null
+++ b/distribute_candies_children2.py
@@ -0,0 +1,35 @@
+# 2929. Distribute Candies Among Children II
+from math import comb
+
+"""
+you are given two positive integers 'n' and 'limit'. return the total number
+of ways to distritube 'n' candies among 3 children such that no child gets
+more than 'limit' candies.
+"""
+
+
+class Solution(object):
+ def distributeCandies(self, n, limit):
+ """
+ :type n: int
+ :type limit: int
+ :rtype: int
+ """
+ ans = (n + 2) * (n + 1) // 2
+ for i in range(1, 4):
+ if n - i * (limit + 1) < 0:
+ break
+ ans += (
+ (-1) ** i
+ * comb(3, i)
+ * (n - i * (limit + 1) + 2)
+ * (n - i * (limit + 1) + 1)
+ // 2
+ )
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.distributeCandies(n=5, limit=2))
+ print(obj.distributeCandies(n=3, limit=3))
diff --git a/div_non_div_sum_diff.c b/div_non_div_sum_diff.c
new file mode 100644
index 0000000..90ecdc6
--- /dev/null
+++ b/div_non_div_sum_diff.c
@@ -0,0 +1,19 @@
+// 2894. Divisible and Non-divisible Sums Difference
+#include "leetcode.h"
+
+/*
+ * you are given a positive integers 'n' and 'm'. define two integers as
+ * follows: 'num1': the sum of all integers in the range '[1, n]' that are not
+ * divisible by 'm'. 'num2': the sum of all integers in the range '[1, n]' that
+ * are divisible by 'm'. return the integer 'num1 - num2'
+ */
+
+int differenceOfSums(int n, int m) {
+ return (1 + n) * n / 2 - (1 + n / m) * (n / m) * m;
+}
+
+int main() {
+ printf("%d\n", differenceOfSums(10, 3)); // expect: 19
+ printf("%d\n", differenceOfSums(5, 6)); // expect: 15
+ printf("%d\n", differenceOfSums(5, 1)); // expect: -15
+}
diff --git a/div_non_div_sum_diff.py b/div_non_div_sum_diff.py
new file mode 100644
index 0000000..51d7cac
--- /dev/null
+++ b/div_non_div_sum_diff.py
@@ -0,0 +1,25 @@
+# 2894. Divisible and Non-divisible Sums Difference
+
+"""
+you are given a positive integers 'n' and 'm'. define two integers as
+follows: 'num1': the sum of all integers in the range '[1, n]' that are not
+divisible by 'm'. 'num2': the sum of all integers in the range '[1, n]' that
+are divisible by 'm'. return the integer 'num1 - num2'
+"""
+
+
+class Solution(object):
+ def differenceOfSums(self, n, m):
+ """
+ :type n: int
+ :type m: int
+ :rtype: int
+ """
+ return (1 + n) * n // 2 - (1 + n // m) * (n // m) * m
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.differenceOfSums(n=10, m=3))
+ print(obj.differenceOfSums(n=5, m=6))
+ print(obj.differenceOfSums(n=5, m=1))
diff --git a/divide_array_max_diff.c b/divide_array_max_diff.c
index 72e8648..8c510b3 100644
--- a/divide_array_max_diff.c
+++ b/divide_array_max_diff.c
@@ -11,25 +11,66 @@
* return any of them
*/
-int cmp(const void *a, const void *b) { return (*(int *)a) - (*(int *)b); }
+int cmp(const void *a, const void *b) { return (*(int *)a - *(int *)b); }
int **divideArray(int *nums, int numsSize, int k, int *returnSize,
int **returnColumnSizes) {
- int num_arr = numsSize / 3;
- int **ans = (int **)calloc(num_arr, sizeof(int *));
- *returnColumnSizes = (int *)calloc(num_arr, sizeof(int));
- *returnSize = 0;
qsort(nums, numsSize, sizeof(int), cmp);
- for (int i = 0; i < num_arr; i++) {
- ans[i] = (int *)calloc(3, sizeof(int));
- (*returnColumnSizes)[i] = 3;
- for (int j = 0; j < 3; j++) {
- int idx = i * 3 + j;
- if (j && nums[idx] - nums[i * 3] > k)
- return ans;
- ans[i][j] = nums[idx];
+ int **ans = (int **)malloc((numsSize / 3) * sizeof(int *)), rs = 0;
+ for (int i = 2; i < numsSize; i += 3) {
+ if (nums[i] - nums[i - 2] > k) {
+ *returnSize = 0;
+ return NULL;
}
+ ans[rs] = (int *)malloc(3 * sizeof(int));
+ ans[rs][0] = nums[i - 2];
+ ans[rs][1] = nums[i - 1];
+ ans[rs][2] = nums[i];
+ rs++;
}
- *returnSize = num_arr;
+ *returnSize = rs;
+ *returnColumnSizes = (int *)malloc(rs * sizeof(int));
+ for (int i = 0; i < rs; i++)
+ (*returnColumnSizes)[i] = 3;
return ans;
}
+
+int main() {
+ int n1[] = {1, 3, 4, 8, 7, 9, 3, 5, 1}, rs1, *rcs1;
+ int n2[] = {2, 4, 2, 2, 5, 2}, rs2, *rcs2;
+ int n3[] = {4, 2, 9, 8, 2, 12, 7, 12, 10, 5, 8, 5, 5, 7, 9, 2, 5, 11}, rs3,
+ *rcs3;
+ int **da1 = divideArray(n1, ARRAY_SIZE(n1), 2, &rs1, &rcs1);
+ int **da2 = divideArray(n2, ARRAY_SIZE(n2), 2, &rs2, &rcs2);
+ int **da3 = divideArray(n3, ARRAY_SIZE(n3), 14, &rs3, &rcs3);
+ for (int i = 0; i < rs1; i++) {
+ for (int j = 0; j < rcs1[i]; j++)
+ printf("%d ", da1[i][j]); // expect: [[1,1,3],[3,4,5],[7,8,9]]
+ printf("\n");
+ }
+ printf("\n");
+ for (int i = 0; i < rs2; i++) {
+ for (int j = 0; j < rcs2[i]; j++)
+ printf("%d ", da2[i][j]); // expect: null
+ printf("\n");
+ }
+ printf("\n");
+ for (int i = 0; i < rs3; i++) {
+ for (int j = 0; j < rcs3[i]; j++)
+ printf(
+ "%d ",
+ da3[i][j]); // expect:
+ // [[2,2,12],[4,8,5],[5,9,7],[7,8,5],[5,9,10],[11,12,2]]
+ printf("\n");
+ }
+ printf("\n");
+ for (int i = 0; i < rs1; i++)
+ free(da1[i]), free(rcs1);
+ free(da1);
+ for (int i = 0; i < rs2; i++)
+ free(da2[i]), free(rcs2);
+ free(da1);
+ for (int i = 0; i < rs3; i++)
+ free(da3[i]), free(rcs3);
+ free(da1);
+}
diff --git a/divide_array_max_diff.py b/divide_array_max_diff.py
index 41a2a22..3bdf682 100644
--- a/divide_array_max_diff.py
+++ b/divide_array_max_diff.py
@@ -18,18 +18,12 @@ class Solution(object):
:type k: int
:rtype: List[List[int]]
"""
- size = len(nums)
- if size % 3 != 0:
- return []
nums.sort()
ans = []
- group_idx = 0
- for i in range(0, size, 3):
- if i + 2 < size and nums[i + 2] - nums[i] <= k:
- ans.append([nums[i], nums[i + 1], nums[i + 2]])
- group_idx += 1
- else:
+ for i in range(2, len(nums), 3):
+ if nums[i] - nums[i - 2] > k:
return []
+ ans.append([nums[i - 2], nums[i - 1], nums[i]])
return ans
@@ -37,3 +31,8 @@ if __name__ == "__main__":
obj = Solution()
print(obj.divideArray(nums=[1, 3, 4, 8, 7, 9, 3, 5, 1], k=2))
print(obj.divideArray(nums=[1, 3, 3, 2, 7, 3], k=3))
+ print(
+ obj.divideArray(
+ nums=[4, 2, 9, 8, 2, 12, 7, 12, 10, 5, 8, 5, 5, 7, 9, 2, 5, 11], k=14
+ )
+ )
diff --git a/divide_string_groups_k.c b/divide_string_groups_k.c
new file mode 100644
index 0000000..1565b83
--- /dev/null
+++ b/divide_string_groups_k.c
@@ -0,0 +1,47 @@
+// 2138. Divide a String Into Groups of Size k
+#include "leetcode.h"
+
+/*
+ * a string 's' can be partitioned into groups of size 'k' using the following
+ * procedure: the first group consists of the first 'k' characters of the
+ * string, the second group consists of the next 'k' characters of the string,
+ * ans so on. each element can be a part of exactly one group. for the last
+ * group, if the string does not have 'k' characters remaining, a character
+ * 'fill' is used to complete the group. note that the partition is done so that
+ * after removing the 'fill' character from the last group, and concatenating
+ * all the groups in oder, the resultant string should be 's'. given a string
+ * 's', the size of each group 'k', and the character 'fill', return a string
+ * array denoting the composition of every group 's' has been divided into.
+ */
+
+char **divideString(char *s, int k, char fill, int *returnSize) {
+ int n = strlen(s), groups = (n + k - 1) / k;
+ char **ans = (char **)malloc(groups * sizeof(char *));
+ *returnSize = groups;
+ for (int i = 0; i < groups; i++) {
+ ans[i] = (char *)malloc((k + 1) * sizeof(char));
+ for (int j = 0; j < k; j++) {
+ int idx = i * k + j;
+ ans[i][j] = idx < n ? s[idx] : fill;
+ }
+ ans[i][k] = '\0';
+ }
+ return ans;
+}
+
+int main() {
+ char *s1 = "abcdefghi", *s2 = "abcdefghij";
+ int rs1, rs2;
+ char **ds1 = divideString(s1, 3, 'x', &rs1);
+ char **ds2 = divideString(s2, 3, 'x', &rs2);
+ for (int i = 0; i < rs1; i++)
+ printf("%s ", ds1[i]); // expect: ["abc","def","ghi"]
+ printf("\n");
+ for (int i = 0; i < rs2; i++)
+ printf("%s ", ds2[i]); // expect: ["abc","def","ghi","jxx"]
+ printf("\n");
+ for (int i = 0; i < rs1; i++)
+ free(ds1[i]);
+ for (int i = 0; i < rs2; i++)
+ free(ds2[i]);
+}
diff --git a/divide_string_groups_k.py b/divide_string_groups_k.py
new file mode 100644
index 0000000..2158483
--- /dev/null
+++ b/divide_string_groups_k.py
@@ -0,0 +1,42 @@
+# 2138. Divide a String Into Groups of Size k
+
+"""
+a string 's' can be partitioned into groups of size 'k' using the following
+procedure: the first group consists of the first 'k' characters of the
+string, the second group consists of the next 'k' characters of the string,
+ans so on. each element can be a part of exactly one group. for the last
+group, if the string does not have 'k' characters remaining, a character
+'fill' is used to complete the group. note that the partition is done so that
+after removing the 'fill' character from the last group, and concatenating
+all the groups in oder, the resultant string should be 's'. given a string
+'s', the size of each group 'k', and the character 'fill', return a string
+array denoting the composition of every group 's' has been divided into.
+"""
+
+
+class Solution(object):
+ def divideString(self, s, k, fill):
+ """
+ :type s: str
+ :type k: int
+ :type fill: str
+ :rtype: List[str]
+ """
+ n = len(s)
+ groups, ans = (n + k - 1) // k, []
+ for i in range(groups):
+ curr = ""
+ for j in range(k):
+ idx = i * k + j
+ if idx < n:
+ curr += s[idx]
+ else:
+ curr += fill
+ ans.append(curr)
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.divideString(s="abcdefghi", k=3, fill="x"))
+ print(obj.divideString(s="abcdefghij", k=3, fill="x"))
diff --git a/domino_tromino_tiling.c b/domino_tromino_tiling.c
new file mode 100644
index 0000000..d8bd02b
--- /dev/null
+++ b/domino_tromino_tiling.c
@@ -0,0 +1,31 @@
+// 790. Domino and Tromino Tiling
+#include "leetcode.h"
+
+/*
+ * you have two types of tiles: a '2 x 1' domino shape and a tromino shape. you
+ * may rotate these shapes. given an integer 'n', return the number of ways to
+ * tile a '2 x n' board. since the answer may be very large, return it modulo
+ * 10^9+7. in a tiling, every square must be tiled by a tile. two tilings are
+ * different if and only if there are two 4-directionally adjacent cells on the
+ * board such that exactly one of the tilings has both squares occupied by a
+ * tile.
+ */
+
+int numTilings(int n) {
+ static int mod = 1e9 + 7;
+ if (n <= 2)
+ return n;
+ int x = 1, y = 2, z = 5, m;
+ for (int i = 4; i <= n; ++i) {
+ m = (2LL * z + x) % mod;
+ x ^= y ^= x ^= y;
+ y ^= z ^= y ^= z;
+ z ^= m ^= z ^= m;
+ }
+ return z;
+}
+
+int main() {
+ printf("%d\n", numTilings(3)); // expect: 5
+ printf("%d\n", numTilings(1)); // expect: 1
+}
diff --git a/domino_tromino_tiling.py b/domino_tromino_tiling.py
new file mode 100644
index 0000000..bd1c25e
--- /dev/null
+++ b/domino_tromino_tiling.py
@@ -0,0 +1,34 @@
+# 790. Domino and Tromino Tiling
+
+"""
+you have two types of tiles: a '2 x 1' domino shape and a tromino shape. you
+may rotate these shapes. given an integer 'n', return the number of ways to
+tile a '2 x n' board. since the answer may be very large, return it modulo
+10^9+7. in a tiling, every square must be tiled by a tile. two tilings are
+different if and only if there are two 4-directionally adjacent cells on the
+board such that exactly one of the tilings has both squares occupied by a
+tile.
+"""
+
+
+class Solution(object):
+ def numTilings(self, n):
+ """
+ :type n: int
+ :rtype: int
+ """
+ mod = 10**9 + 7
+ if n <= 2:
+ return n
+ f_prev, g_prev, f_prev2, g_prev2 = 2, 2, 1, 1
+ for i in range(3, n + 1):
+ filled = f_prev + f_prev2 + 2 * g_prev2
+ gap = f_prev + g_prev
+ f_prev2, f_prev, g_prev2, g_prev = f_prev, filled, g_prev, gap
+ return f_prev % mod
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.numTilings(n=3))
+ print(obj.numTilings(n=1))
diff --git a/find_lex_large_str_box1.c b/find_lex_large_str_box1.c
new file mode 100644
index 0000000..8cc8df1
--- /dev/null
+++ b/find_lex_large_str_box1.c
@@ -0,0 +1,40 @@
+// 3403. Find the Lexicographically Largest String From the Box I
+#include "leetcode.h"
+
+/*
+ * you are given a string 'word', and an integer 'numFriends'. alice is
+ * organising a game for her 'numFriends' friends. there are multiple rounds in
+ * the game, where each round: 'word' is split into 'numFriends' non-empty
+ * strings such that no previous round has the exact same split, and all the
+ * split words are put into a box. find the lexicographically largest string
+ * from the box after all rounds are finished.
+ */
+
+char *answerString(char *word, int numFriends) {
+ int n = strlen(word), m = n - (numFriends - 1);
+ if (numFriends == 1) {
+ char *ans = (char *)malloc((n + 1) * sizeof(char));
+ strcpy(ans, word);
+ return ans;
+ }
+ char *ans = (char *)malloc((m + 1) * sizeof(char));
+ ans[0] = '\0';
+ for (int i = 0; i < m; ++i) {
+ int k = n - i < m ? n - i : m;
+ char *tmp = (char *)malloc((k + 1) * sizeof(char));
+ strncpy(tmp, word + i, k);
+ tmp[k] = '\0';
+ if (strcmp(ans, tmp) < 0) {
+ free(ans);
+ ans = tmp;
+ } else
+ free(tmp);
+ }
+ return ans;
+}
+
+int main() {
+ char *w1 = "dbca", *w2 = "gggg";
+ printf("%s\n", answerString(w1, 2)); // expect: dbc
+ printf("%s\n", answerString(w2, 4)); // expect: g
+}
diff --git a/find_lex_large_str_box1.py b/find_lex_large_str_box1.py
new file mode 100644
index 0000000..1b29d1f
--- /dev/null
+++ b/find_lex_large_str_box1.py
@@ -0,0 +1,30 @@
+# 3403. Find the Lexicographically Largest String From the Box I
+
+"""
+you are given a string 'word', and an integer 'numFriends'. alice is
+organising a game for her 'numFriends' friends. there are multiple rounds in
+the game, where each round: 'word' is split into 'numFriends' non-empty
+strings such that no previous round has the exact same split, and all the
+split words are put into a box. find the lexicographically largest string
+from the box after all rounds are finished.
+"""
+
+
+class Solution(object):
+ def answerString(self, word, numFriends):
+ """
+ :type word: str
+ :type numFriends: int
+ :rtype: str
+ """
+ n = len(word)
+ m = n - numFriends + 1
+ if numFriends == 1:
+ return word
+ return max(word[i : i + m] for i in range(n))
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.answerString(word="dbca", numFriends=2))
+ print(obj.answerString(word="gggg", numFriends=4))
diff --git a/find_max_sum_node_val.c b/find_max_sum_node_val.c
new file mode 100644
index 0000000..6005bc7
--- /dev/null
+++ b/find_max_sum_node_val.c
@@ -0,0 +1,45 @@
+// 3068. Find the Maximum Sum of Node Values
+#include "leetcode.h"
+
+/*
+ * there exists an undirected tree with 'n' nodes numbered 0 to 'n - 1'. you are
+ * given a 0-indexed 2d integer array 'edges' of length 'n - 1', where 'edges[i]
+ * = [ui,vi]' indicates that there is an edge between nodes 'ui' and 'vi' in the
+ * tree. you are also given a positive integer 'k' and a 0 indexed array of non
+ * negative integers 'nums' of length 'n' where 'nums[i]' represents the value
+ * of the node numbered 'i'. return the maximum possible sum of the values alice
+ * can achieve by performing the operation any number of times.
+ */
+
+long long maximumValueSum(int *nums, int numsSize, int k, int **edges,
+ int edgesSize, int *edgesColSize) {
+ long long ans = 0;
+ int u = 1 << 30, v = 0;
+ for (int i = 0; i < numsSize; i++) {
+ int curr = nums[i] ^ k;
+ ans += fmax(nums[i], curr);
+ u ^= nums[i] < curr;
+ v = fmin(v, abs(nums[i] - curr));
+ }
+ return ans - u * v;
+}
+
+int main() {
+ int n1[] = {1, 2, 1}, e1i[2][2] = {{0, 1}, {0, 2}};
+ int n2[] = {2, 3}, e2i[1][2] = {{0, 1}};
+ int n3[] = {7, 7, 7, 7, 7, 7},
+ e3i[5][2] = {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}};
+ struct two_d_arr e1, e2, e3;
+ two_d_arr_init(&e1, ARRAY_SIZE(e1i), ARRAY_SIZE(e1i[0]), e1i);
+ two_d_arr_init(&e1, ARRAY_SIZE(e1i), ARRAY_SIZE(e1i[0]), e1i);
+ two_d_arr_init(&e1, ARRAY_SIZE(e1i), ARRAY_SIZE(e1i[0]), e1i);
+ printf("%lld\n", maximumValueSum(n1, ARRAY_SIZE(n1), 3, e1.arr, e1.row_size,
+ e1.col_size)); // expect: 6
+ printf("%lld\n", maximumValueSum(n2, ARRAY_SIZE(n2), 7, e2.arr, e2.row_size,
+ e2.col_size)); // expect: 9
+ printf("%lld\n", maximumValueSum(n3, ARRAY_SIZE(n3), 3, e3.arr, e3.row_size,
+ e3.col_size)); // expect: 42
+ two_d_arr_free(&e1);
+ two_d_arr_free(&e2);
+ two_d_arr_free(&e3);
+}
diff --git a/find_min_time_reach_last_room1.c b/find_min_time_reach_last_room1.c
new file mode 100644
index 0000000..e632ae4
--- /dev/null
+++ b/find_min_time_reach_last_room1.c
@@ -0,0 +1,85 @@
+// 3341. Find Minimum Time to Reach Last Room I
+#include "leetcode.h"
+
+/*
+ * there is a dungeo with 'n x m' rooms arranged as a grid. you are given a 2d
+ * array 'moveTime' of size 'n x m' where 'moveTime[i][j]' represents the
+ * minimum time in seconds when you can start moving to that room. you start
+ * from the room at '(0, 0)' at time 't = 0' and can move to an adjacent room.
+ * moving between adjacent rooms takes exactly one second. return the minimum
+ * time to reach the room 'n - 1, m - 1'.
+ */
+
+int minTimeToReach(int **moveTime, int moveTimeSize, int *moveTimeColSize) {
+ int n = moveTimeSize, m = moveTimeColSize[0];
+ if (!n)
+ return -1;
+ int total = n * m, *dp = (int *)malloc(total * sizeof(int));
+ for (int i = 0; i < total; i++)
+ dp[i] = INT_MAX;
+ dp[0] = 0;
+ int *heap = (int *)malloc(total * sizeof(int)), hsize = 0;
+ heap[hsize++] = 0;
+ int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
+ while (hsize) {
+ int u = heap[0];
+ heap[0] = heap[--hsize];
+ int i = 0;
+ while (1) {
+ int l = 2 * i + 1, r = 2 * i + 2, best = i;
+ if (l < hsize && dp[heap[l]] < dp[heap[best]])
+ best = l;
+ if (r < hsize && dp[heap[r]] < dp[heap[best]])
+ best = r;
+ if (best == i)
+ break;
+ int tmp = heap[i];
+ heap[i] = heap[best];
+ heap[best] = tmp;
+ i = best;
+ }
+ if (u == total - 1)
+ break;
+ int t = dp[u], x = u / m, y = u % m;
+ for (int d = 0; d < 4; d++) {
+ int nx = x + dirs[d][0], ny = y + dirs[d][1];
+ if (nx < 0 || nx >= n || ny < 0 || ny >= m)
+ continue;
+ int idx = nx * m + ny;
+ int w = (moveTime[nx][ny] > t ? moveTime[nx][ny] : t) + 1;
+ if (w < dp[idx]) {
+ dp[idx] = w;
+ int j = hsize;
+ heap[hsize++] = idx;
+ while (j > 0 && dp[heap[j]] < dp[heap[(j - 1) / 2]]) {
+ int p = (j - 1) / 2, tmp = heap[j];
+ heap[j] = heap[p];
+ heap[p] = tmp;
+ j = p;
+ }
+ }
+ }
+ }
+ int ans = dp[total - 1];
+ free(dp);
+ free(heap);
+ return ans;
+}
+
+int main() {
+ int mt1i[2][2] = {{0, 4}, {4, 4}}, mt2i[2][3] = {{0, 0, 0}, {0, 0, 0}},
+ mt3i[2][2] = {{0, 1}, {1, 2}};
+ struct two_d_arr mt1, mt2, mt3;
+ two_d_arr_init(&mt1, ARRAY_SIZE(mt1i), ARRAY_SIZE(mt1i[0]), mt1i);
+ two_d_arr_init(&mt2, ARRAY_SIZE(mt2i), ARRAY_SIZE(mt2i[0]), mt2i);
+ two_d_arr_init(&mt3, ARRAY_SIZE(mt3i), ARRAY_SIZE(mt3i[0]), mt3i);
+ printf("%d\n",
+ minTimeToReach(mt1.arr, mt1.row_size, mt1.col_size)); // expect: 6
+ printf("%d\n",
+ minTimeToReach(mt2.arr, mt2.row_size, mt2.col_size)); // expect: 3
+ printf("%d\n",
+ minTimeToReach(mt3.arr, mt3.row_size, mt3.col_size)); // expect: 3
+ two_d_arr_free(&mt1);
+ two_d_arr_free(&mt2);
+ two_d_arr_free(&mt3);
+}
diff --git a/find_min_time_reach_last_room1.py b/find_min_time_reach_last_room1.py
new file mode 100644
index 0000000..3ce1848
--- /dev/null
+++ b/find_min_time_reach_last_room1.py
@@ -0,0 +1,41 @@
+# 3341. Find Minimum Time to Reach Last Room I
+import heapq
+
+"""
+there is a dungeo with 'n x m' rooms arranged as a grid. you are given a 2d
+array 'moveTime' of size 'n x m' where 'moveTime[i][j]' represents the
+minimum time in seconds when you can start moving to that room. you start
+from the room at '(0, 0)' at time 't = 0' and can move to an anyacent room.
+moving between anyacent rooms takes exactly one second. return the minimum
+time to reach the room 'n - 1, m - 1'.
+"""
+
+
+class Solution(object):
+ def minTimeToReach(self, moveTime):
+ """
+ :type moveTime: List[List[int]]
+ :rtype: int
+ """
+ n, m = len(moveTime), len(moveTime[0])
+ dp = [["inf"] * m for i in range(n)]
+ h = [[0, 1, 0, 0]]
+ moveTime[0][0] = -1
+ while h:
+ t, c, i, j = heapq.heappop(h)
+ if t >= dp[i][j]:
+ continue
+ if i == n - 1 and j == m - 1:
+ return t
+ dp[i][j] = t
+ for nx, ny in [[1, 0], [0, 1], [-1, 0], [0, -1]]:
+ x, y = i + nx, j + ny
+ if 0 <= x < n and 0 <= y < m and dp[x][y] == "inf":
+ heapq.heappush(h, [max(moveTime[x][y] + c, t + c), 2 - c, x, y])
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.minTimeToReach(moveTime=[[0, 4], [4, 4]]))
+ print(obj.minTimeToReach(moveTime=[[0, 0, 0], [0, 0, 0]]))
+ print(obj.minTimeToReach(moveTime=[[0, 1], [1, 2]]))
diff --git a/find_min_time_reach_last_room2.c b/find_min_time_reach_last_room2.c
new file mode 100644
index 0000000..a81e83a
--- /dev/null
+++ b/find_min_time_reach_last_room2.c
@@ -0,0 +1,150 @@
+// 3342. Find Minimum Time to Reach Last Room II
+#include "leetcode.h"
+
+/*
+ * there is a dungeon with 'n x m' rooms arranged as a grid. you are given a 2d
+ * array 'moveTime' of size 'n x m' where 'moveTime[i][j]' represents the
+ * minimum time in seconds when you can start moving to that room. you start
+ * from the room '(0, 0)' at time 't = 0' and can move to an adjacent room.
+ * moving between adjacent rooms takes one second for one move and two seconds
+ * for the next, alternating between the two. return the minimum time to reach
+ * the room '(n - 1, m - 1)'.
+ */
+
+#define VIS 0x80000000
+#define MASK 0x7FFFFFFF
+
+struct grid {
+ int row;
+ int col;
+};
+
+void heap_down(struct grid *start, struct grid *end, struct grid *curr,
+ int **moveTime) {
+ struct grid *child = 1 + start + ((curr - start) << 1);
+ if (child <= end) {
+ if (child < end) {
+ struct grid *next = child + 1;
+ if ((MASK & moveTime[child->row][child->col]) <
+ (MASK & moveTime[curr->row][curr->col]))
+ child++;
+ }
+ if ((MASK & moveTime[child->row][child->col]) <
+ (MASK & moveTime[curr->row][curr->col])) {
+ child->col ^= curr->col;
+ curr->col ^= child->col;
+ child->col ^= curr->col;
+ child->row ^= curr->row;
+ curr->row ^= child->row;
+ child->row ^= curr->row;
+ heap_down(start, end, child, moveTime);
+ }
+ }
+}
+
+void heap_up(struct grid *start, struct grid *curr, int **moveTime) {
+ if (start < curr) {
+ struct grid *parent = start + ((curr - 1 - start) >> 1);
+ if ((MASK & moveTime[curr->row][curr->col]) <
+ (MASK & moveTime[parent->row][parent->col])) {
+ curr->col ^= parent->col;
+ parent->col ^= curr->col;
+ curr->col ^= parent->col;
+ curr->row ^= parent->row;
+ parent->row ^= curr->row;
+ curr->row ^= parent->row;
+ heap_up(start, parent, moveTime);
+ }
+ }
+}
+
+int minTimeToReach(int **moveTime, int moveTimeSize, int *moveTimeColSize) {
+ struct grid ast[moveTimeSize * (*moveTimeColSize)], *pst = ast;
+ pst->col = 0;
+ (pst++)->row = 0;
+ moveTime[0][0] = VIS;
+ int ans = 0;
+ int n = moveTimeSize - 1, m = *moveTimeColSize - 1;
+ while (ast < pst) {
+ char move = (ast->col + ast->row) % 2 ? 2 : 1;
+ int time = MASK & moveTime[ast->row][ast->col];
+ if (ast->row) {
+ int next = ast->row - 1, *curr = ast->col + moveTime[next];
+ if (0 <= *curr) {
+ if (time > *curr)
+ *curr = time;
+ *curr += move;
+ *curr |= VIS;
+ pst->col = ast->col;
+ pst->row = next;
+ heap_up(ast, pst++, moveTime);
+ }
+ }
+ if (ast->col) {
+ int next = ast->col - 1, *curr = next + moveTime[ast->row];
+ if (0 <= *curr) {
+ if (time > *curr)
+ *curr = time;
+ *curr += move;
+ *curr |= VIS;
+ pst->col = next;
+ pst->row = ast->row;
+ heap_up(ast, pst++, moveTime);
+ }
+ }
+ if (m > ast->col) {
+ int next = ast->col + 1, *curr = next + moveTime[ast->row];
+ if (0 <= *curr) {
+ if (time > *curr)
+ *curr = time;
+ *curr += move;
+ if (m == next && n == ast->row) {
+ ans = *curr;
+ break;
+ }
+ *curr |= VIS;
+ pst->col = next;
+ pst->row = ast->row;
+ heap_up(ast, pst++, moveTime);
+ }
+ }
+ if (n > ast->row) {
+ int next = ast->row + 1, *curr = ast->col + moveTime[next];
+ if (0 <= *curr) {
+ if (time > *curr)
+ *curr = time;
+ *curr += move;
+ if (n == next && m == ast->col) {
+ ans = *curr;
+ break;
+ }
+ *curr |= VIS;
+ pst->col = ast->col;
+ pst->row = next;
+ heap_up(ast, pst++, moveTime);
+ }
+ }
+ ast->col = (--pst)->col;
+ ast->row = pst->row;
+ heap_down(ast, pst - 1, ast, moveTime);
+ }
+ return ans;
+}
+
+int main() {
+ int mt1i[2][2] = {{0, 4}, {4, 4}}, mt2i[2][4] = {{0, 0, 0, 0}, {0, 0, 0, 0}},
+ mt3i[2][2] = {{0, 1}, {1, 2}};
+ struct two_d_arr mt1, mt2, mt3;
+ two_d_arr_init(&mt1, ARRAY_SIZE(mt1i), ARRAY_SIZE(mt1i[0]), mt1i);
+ two_d_arr_init(&mt2, ARRAY_SIZE(mt2i), ARRAY_SIZE(mt2i[0]), mt2i);
+ two_d_arr_init(&mt3, ARRAY_SIZE(mt3i), ARRAY_SIZE(mt3i[0]), mt3i);
+ printf("%d\n",
+ minTimeToReach(mt1.arr, mt1.row_size, mt1.col_size)); // expect: 7
+ printf("%d\n",
+ minTimeToReach(mt2.arr, mt2.row_size, mt2.col_size)); // expect: 6
+ printf("%d\n",
+ minTimeToReach(mt3.arr, mt3.row_size, mt3.col_size)); // expect: 4
+ two_d_arr_free(&mt1);
+ two_d_arr_free(&mt2);
+ two_d_arr_free(&mt3);
+}
diff --git a/find_min_time_reach_last_room2.py b/find_min_time_reach_last_room2.py
new file mode 100644
index 0000000..11bf407
--- /dev/null
+++ b/find_min_time_reach_last_room2.py
@@ -0,0 +1,43 @@
+# 3342. Find Minimum Time to Reach Last Room II
+import heapq
+
+"""
+there is a dungeon with 'n x m' rooms arranged as a grid. you are given a 2d
+array 'moveTime' of size 'n x m' where 'moveTime[i][j]' represents the
+minimum time in seconds when you can start moving to that room. you start
+from the room '(0, 0)' at time 't = 0' and can move to an adjacent room.
+moving between adjacent rooms takes one second for one move and two seconds
+for the next, alternating between the two. return the minimum time to reach
+the room '(n - 1, m - 1)'.
+"""
+
+
+class Solution(object):
+ def minTimeToReach(self, moveTime):
+ """
+ :type moveTime: List[List[int]]
+ :rtype: int
+ """
+ n, m = len(moveTime), len(moveTime[0])
+ dp = [["inf"] * m for i in range(n)]
+ heap = [[0, 0, 0]]
+ moveTime[0][0] = -1
+ while heap:
+ t, i, j = heapq.heappop(heap)
+ if t >= dp[i][j]:
+ continue
+ if i == n - 1 and j == m - 1:
+ return t
+ dp[i][j] = t
+ for di, dj in [[1, 0], [0, 1], [-1, 0], [0, -1]]:
+ x, y = i + di, j + dj
+ c = (i + j) % 2 + 1
+ if 0 <= x < n and 0 <= y < m and dp[x][y] == "inf":
+ heapq.heappush(heap, [max(moveTime[x][y], t) + c, x, y])
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.minTimeToReach(moveTime=[[0, 4], [4, 4]]))
+ print(obj.minTimeToReach(moveTime=[[0, 0, 0, 0], [0, 0, 0, 0]]))
+ print(obj.minTimeToReach(moveTime=[[0, 1], [1, 2]]))
diff --git a/find_num_even_digit.c b/find_num_even_digit.c
new file mode 100644
index 0000000..351896f
--- /dev/null
+++ b/find_num_even_digit.c
@@ -0,0 +1,27 @@
+// 1295. Find Numbers with Even Number of Digits
+#include "leetcode.h"
+
+/*
+ * given an array 'nums' of integers, return how many of them contain an even
+ * number of digits.
+ */
+
+int findNumbers(int *nums, int numsSize) {
+ int cnt = 0;
+ for (int i = 0; i < numsSize; i++) {
+ int curr = 0;
+ while (nums[i]) {
+ curr++;
+ nums[i] /= 10;
+ }
+ if (!(curr & 1))
+ cnt++;
+ }
+ return cnt;
+}
+
+int main() {
+ int n1[] = {12, 345, 2, 6, 7896}, n2[] = {555, 901, 482, 1771};
+ printf("%d\n", findNumbers(n1, ARRAY_SIZE(n1))); // expect: 2
+ printf("%d\n", findNumbers(n2, ARRAY_SIZE(n2))); // expect: 1
+}
diff --git a/find_num_even_digit.py b/find_num_even_digit.py
new file mode 100644
index 0000000..5cdb9e3
--- /dev/null
+++ b/find_num_even_digit.py
@@ -0,0 +1,21 @@
+# 1295. Find Numbers with Even Number of Digits
+
+"""
+given an array 'nums' of integers, return how many of them contain an even
+number of digits.
+"""
+
+
+class Solution(object):
+ def findNumbers(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ return sum(1 for i in nums if (len(str(i)) & 1) == 0)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.findNumbers(nums=[12, 345, 2, 6, 7896]))
+ print(obj.findNumbers(nums=[555, 901, 482, 1771]))
diff --git a/find_original_typed_str1.c b/find_original_typed_str1.c
new file mode 100644
index 0000000..ce60027
--- /dev/null
+++ b/find_original_typed_str1.c
@@ -0,0 +1,26 @@
+// 3330. Find the Original Typed String I
+#include "leetcode.h"
+
+/*
+ * alice is attmpting to type a specific string on her computer. however, she
+ * tends to be clumsy and may press a key for too long, resulting a character
+ * being typed multiple times. although alice tried to focus on her typing, she
+ * is aware that she may still have done this at least once. you are given a
+ * string 'word', which represents the final output displayed on alices screen.
+ * return the total number of possible original strings that alice might have
+ * intended to type.
+ */
+
+int possibleStringCount(char *word) {
+ int n = strlen(word), ans = n;
+ for (int i = 1; i < n; ++i)
+ ans -= word[i] != word[i - 1];
+ return ans;
+}
+
+int main() {
+ char *w1 = "abbcccc", *w2 = "abcd", *w3 = "aaaa";
+ printf("%d\n", possibleStringCount(w1)); // expect: 5
+ printf("%d\n", possibleStringCount(w2)); // expect: 1
+ printf("%d\n", possibleStringCount(w3)); // expect: 4
+}
diff --git a/find_original_typed_str1.py b/find_original_typed_str1.py
new file mode 100644
index 0000000..d4d59b0
--- /dev/null
+++ b/find_original_typed_str1.py
@@ -0,0 +1,28 @@
+# 3330. Find the Original Typed String I
+from itertools import groupby
+
+"""
+alice is attmpting to type a specific string on her computer. however, she
+tends to be clumsy and may press a key for too long, resulting a character
+being typed multiple times. although alice tried to focus on her typing, she
+is aware that she may still have done this at least once. you are given a
+string 'word', which represents the final output displayed on alices screen.
+return the total number of possible original strings that alice might have
+intended to type.
+"""
+
+
+class Solution(object):
+ def possibleStringCount(self, word):
+ """
+ :type word: str
+ :rtype: int
+ """
+ return len(word) - len(list(groupby(word))) + 1
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.possibleStringCount(word="abbcccc"))
+ print(obj.possibleStringCount(word="abcd"))
+ print(obj.possibleStringCount(word="aaaa"))
diff --git a/find_subseq_len_k_large_sum.c b/find_subseq_len_k_large_sum.c
new file mode 100644
index 0000000..ad29aa5
--- /dev/null
+++ b/find_subseq_len_k_large_sum.c
@@ -0,0 +1,62 @@
+// 2099. Find Subsequence of Length K With the Largest Sum
+#include "leetcode.h"
+
+/*
+ * you are given an integer array 'nums' and an integer 'k'. you want to find a
+ * subsequence of 'nums' of length 'k' that has the largest sum. return any such
+ * subsequence as an integer array of length 'k'. a subsequence is an array that
+ * can be derived from another array by deleting some or no elements without
+ * changing the order of the remaining elements.
+ */
+
+struct pair {
+ int idx;
+ int val;
+};
+
+int cmp_idx(const void *a, const void *b) {
+ struct pair aa = *(const struct pair *)a;
+ struct pair bb = *(const struct pair *)b;
+ return aa.idx - bb.idx;
+}
+
+int cmp_val(const void *a, const void *b) {
+ struct pair aa = *(const struct pair *)a;
+ struct pair bb = *(const struct pair *)b;
+ return aa.val - bb.val;
+}
+
+int *maxSubsequence(int *nums, int numsSize, int k, int *returnSize) {
+ struct pair *pairs = (struct pair *)malloc(numsSize * sizeof(struct pair));
+ for (int i = 0; i < numsSize; i++) {
+ pairs[i].idx = i;
+ pairs[i].val = nums[i];
+ }
+ qsort(pairs, numsSize, sizeof(struct pair), cmp_val);
+ qsort(pairs, k, sizeof(struct pair), cmp_idx);
+ int *ans = (int *)malloc(k * sizeof(int));
+ *returnSize = k;
+ for (int i = 0; i < k; i++)
+ ans[i] = nums[pairs[i].idx];
+ free(pairs);
+ return ans;
+}
+
+int main() {
+ int n1[] = {2, 1, 3, 3}, n2[] = {-1, -2, 3, 4}, n3[] = {3, 4, 3, 3};
+ int rs1, *ms1 = maxSubsequence(n1, ARRAY_SIZE(n1), 2, &rs1);
+ int rs2, *ms2 = maxSubsequence(n2, ARRAY_SIZE(n2), 3, &rs2);
+ int rs3, *ms3 = maxSubsequence(n3, ARRAY_SIZE(n3), 2, &rs3);
+ for (int i = 0; i < rs1; i++)
+ printf("%d ", ms1[i]); // expect: 3 3
+ printf("\n");
+ for (int i = 0; i < rs2; i++)
+ printf("%d ", ms2[i]); // expect: -1 3 4
+ printf("\n");
+ for (int i = 0; i < rs3; i++)
+ printf("%d ", ms3[i]); // expect: 3 4
+ printf("\n");
+ free(ms1);
+ free(ms2);
+ free(ms3);
+}
diff --git a/find_subseq_len_k_large_sum.py b/find_subseq_len_k_large_sum.py
new file mode 100644
index 0000000..c7ce933
--- /dev/null
+++ b/find_subseq_len_k_large_sum.py
@@ -0,0 +1,32 @@
+# 2099. Find Subsequence of Length K With the Largest Sum
+import heapq
+
+"""
+you are given an integer array 'nums' and an integer 'k'. you want to find a
+subsequence of 'nums' of length 'k' that has the largest sum. return any such
+subsequence as an integer array of length 'k'. a subsequence is an array that
+can be derived from another array by deleting some or no elements without
+changing the order of the remaining elements.
+"""
+
+
+class Solution(object):
+ def maxSubsequence(self, nums, k):
+ """
+ :type nums: List[int]
+ :type k: int
+ :rtype: List[int]
+ """
+ heap = []
+ for i, j in enumerate(nums):
+ heapq.heappush(heap, (j, i))
+ if len(heap) > k:
+ heapq.heappop(heap)
+ return [i[0] for i in sorted(heap, key=lambda x: x[1])]
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.maxSubsequence(nums=[2, 1, 3, 3], k=2))
+ print(obj.maxSubsequence(nums=[-1, -2, 3, 4], k=3))
+ print(obj.maxSubsequence(nums=[3, 4, 3, 3], k=2))
diff --git a/find_words_contain_char.c b/find_words_contain_char.c
new file mode 100644
index 0000000..68f541d
--- /dev/null
+++ b/find_words_contain_char.c
@@ -0,0 +1,40 @@
+// 2942. Find Words Containing Character
+#include "leetcode.h"
+
+/*
+ * you are given a 0-indexed array of strings 'words' and a character 'x'.
+ * return an array of indices representing the words that contain the character
+ * 'x'. note that the returned array may be in any order.
+ */
+
+int *findWordsContaining(char **words, int wordsSize, char x, int *returnSize) {
+ int *ans = (int *)malloc(wordsSize * sizeof(int)), cnt = 0;
+ for (int i = 0; i < wordsSize; i++)
+ for (int j = 0; words[i][j]; j++)
+ if (words[i][j] == x) {
+ ans[cnt++] = i;
+ break;
+ }
+ *returnSize = cnt;
+ return ans;
+}
+
+int main() {
+ char *w1[] = {"leet", "code"}, *w2[] = {"abc", "bcd", "aaaa", "cbc"},
+ *w3[] = {"abc", "bcd", "aaaa", "cbc"};
+ int rs1, *fwc1 = findWordsContaining((char **)w1, ARRAY_SIZE(w1), 'e', &rs1);
+ int rs2, *fwc2 = findWordsContaining((char **)w2, ARRAY_SIZE(w2), 'a', &rs2);
+ int rs3, *fwc3 = findWordsContaining((char **)w3, ARRAY_SIZE(w3), 'z', &rs3);
+ for (int i = 0; i < rs1; i++)
+ printf("%d ", fwc1[i]); // expect: 0 1
+ printf("\n");
+ for (int i = 0; i < rs2; i++)
+ printf("%d ", fwc2[i]); // expect: 0 2
+ printf("\n");
+ for (int i = 0; i < rs3; i++)
+ printf("%d ", fwc3[i]); // expect: null
+ printf("\n");
+ free(fwc1);
+ free(fwc2);
+ free(fwc3);
+}
diff --git a/find_words_contain_char.py b/find_words_contain_char.py
new file mode 100644
index 0000000..5554b2f
--- /dev/null
+++ b/find_words_contain_char.py
@@ -0,0 +1,24 @@
+# 2942. Find Words Containing Character
+
+"""
+you are given a 0-indexed array of strings 'words' and a character 'x'.
+return an array of indices representing the words that contain the character
+'x'. note that the returned array may be in any order.
+"""
+
+
+class Solution(object):
+ def findWordsContaining(self, words, x):
+ """
+ :type words: List[str]
+ :type x: str
+ :rtype: List[int]
+ """
+ return [i for i in range(len(words)) if x in words[i]]
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.findWordsContaining(words=["leet", "code"], x="e"))
+ print(obj.findWordsContaining(words=["abc", "bcd", "aaaa", "cbc"], x="a"))
+ print(obj.findWordsContaining(words=["abc", "bcd", "aaaa", "cbc"], x="z"))
diff --git a/finding_3_digit_even_num.c b/finding_3_digit_even_num.c
new file mode 100644
index 0000000..be8c065
--- /dev/null
+++ b/finding_3_digit_even_num.c
@@ -0,0 +1,59 @@
+// 2094. Finding 3-Digit Even Numbers
+#include "leetcode.h"
+
+/*
+ * you are given an integer 'digits' where each element is a digit. the array
+ * may contain duplicates. you need to find all the unique integers that follow
+ * the given requirements: the integer consists of the concatenation of three
+ * elements from 'digits' in any arbitrary order, the integer does not have
+ * leading zeros, and the integer is even. for example, if the given 'digits'
+ * were '[1, 2, 3]' integers '132' and '312' follow the requirments. return a
+ * sorted array of the unique integers.
+ */
+
+int *findEvenNumbers(int *digits, int digitsSize, int *returnSize) {
+ int hash[10] = {0};
+ for (int i = 0; i < digitsSize; i++)
+ hash[digits[i]]++;
+ int *ans = (int *)malloc(sizeof(int));
+ *returnSize = 0;
+ int idx = 0;
+ for (int i = 100; i < 999; i += 2) {
+ int cnt[10] = {0}, tmp = i;
+ bool flag = true;
+ while (tmp) {
+ cnt[tmp % 10]++;
+ tmp /= 10;
+ }
+ for (int j = 0; j < 10; j++)
+ if (cnt[j] > hash[j]) {
+ flag = false;
+ break;
+ }
+ if (flag) {
+ (*returnSize)++;
+ ans = (int *)realloc(ans, (*returnSize) * sizeof(int));
+ ans[idx++] = i;
+ }
+ }
+ return ans;
+}
+
+int main() {
+ int d1[] = {2, 1, 3, 0}, d2[] = {2, 2, 8, 8, 2}, d3[] = {3, 7, 5};
+ int rs1, *fen1 = findEvenNumbers(d1, ARRAY_SIZE(d1), &rs1);
+ int rs2, *fen2 = findEvenNumbers(d2, ARRAY_SIZE(d2), &rs2);
+ int rs3, *fen3 = findEvenNumbers(d3, ARRAY_SIZE(d3), &rs3);
+ for (int i = 0; i < rs1; i++)
+ printf("%d ", fen1[i]); // expect: 102,120,130,132,210,230,302,310,312,320
+ printf("\n");
+ for (int i = 0; i < rs2; i++)
+ printf("%d ", fen2[i]); // expect: 222,228,282,288,822,828,882
+ printf("\n");
+ for (int i = 0; i < rs3; i++)
+ printf("%d ", fen3[i]); // expect: null
+ printf("\n");
+ free(fen1);
+ free(fen2);
+ free(fen3);
+}
diff --git a/finding_3_digit_even_num.py b/finding_3_digit_even_num.py
new file mode 100644
index 0000000..cf6ccc7
--- /dev/null
+++ b/finding_3_digit_even_num.py
@@ -0,0 +1,32 @@
+# 2094. Finding 3-Digit Even Numbers
+from itertools import permutations
+
+"""
+you are given an integer 'digits' where each element is a digit. the array
+may contain duplicates. you need to find all the unique integers that follow
+the given requirements: the integer consists of the concatenation of three
+elements from 'digits' in any arbitrary order, the integer does not have
+leading zeros, and the integer is even. for example, if the given 'digits'
+were '[1, 2, 3]' integers '132' and '312' follow the requirments. return a
+sorted array of the unique integers.
+"""
+
+
+class Solution(object):
+ def findEvenNumbers(self, digits):
+ """
+ :type digits: List[int]
+ :rtype: List[int]
+ """
+ return sorted(
+ 100 * v + 10 * u + w
+ for v, u, w in {*permutations(digits, 3)}
+ if v > 0 == w & 1
+ )
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.findEvenNumbers(digits=[2, 1, 3, 0]))
+ print(obj.findEvenNumbers(digits=[2, 2, 8, 8, 2]))
+ print(obj.findEvenNumbers(digits=[3, 7, 5]))
diff --git a/fizz_buzz_multithread.c b/fizz_buzz_multithread.c
new file mode 100644
index 0000000..67da100
--- /dev/null
+++ b/fizz_buzz_multithread.c
@@ -0,0 +1,145 @@
+// 1195. Fizz Buzz Multithreaded
+#include "leetcode.h"
+
+/*
+ * you have the following functions:
+ * 'printFizz' prints the word "fizz" to the console
+ * 'printBuzz' prints the word "buzz" to the console
+ * 'printFizzBuzz' prints the word "fizzbuzz" to the console
+ * 'printNumber' that prints a given integer to the console
+ * you are given an instance of the class 'fizzbuzz' that has four functions
+ * 'fizz', 'buzz', 'fizzbuzz', and 'number'. the same instance of 'fizzbuzz'
+ * will be passed to four different threads.
+ * thread a calls 'fizz()' that should output the word "fizz"
+ * thread b calls 'buzz()' that should output the word "buzz"
+ * thread c calls 'fizzbuzz()' that should output the word "fizzbuzz"
+ * thread d calls 'number()' that should output the given integer
+ * modify the given class to output the series '[1, 2, "fizz", 4, "buzz", ...]'
+ * where the i'th toek of the series is.
+ */
+
+typedef struct {
+ int n;
+ int curr;
+ int turn;
+} FizzBuzz;
+
+pthread_mutex_t mutex;
+pthread_cond_t cond;
+
+FizzBuzz *fizzBuzzCreate(int n) {
+ FizzBuzz *obj = (FizzBuzz *)malloc(sizeof(FizzBuzz));
+ obj->n = n;
+ obj->curr = 1;
+ obj->turn = 0;
+ return obj;
+}
+
+// Don't change the following declarations
+void printNumber(int a);
+void printFizz();
+void printBuzz();
+void printFizzBuzz();
+
+int helper(FizzBuzz *obj, int turn) {
+ pthread_mutex_lock(&mutex);
+ while (obj->turn != turn && obj->curr <= obj->n)
+ pthread_cond_wait(&cond, &mutex);
+ if (obj->curr > obj->n)
+ return -1;
+ switch (turn) {
+ case 0:
+ printNumber(obj->curr);
+ break;
+ case 1:
+ printFizz();
+ break;
+ case 2:
+ printBuzz();
+ break;
+ case 3:
+ printFizzBuzz();
+ break;
+ }
+ obj->curr++;
+ if ((obj->curr % 3 == 0) && (obj->curr % 5 == 0))
+ obj->turn = 3;
+ else if (obj->curr % 3 == 0)
+ obj->turn = 1;
+ else if (obj->curr % 5 == 0)
+ obj->turn = 2;
+ else
+ obj->turn = 0;
+ pthread_cond_broadcast(&cond);
+ pthread_mutex_unlock(&mutex);
+ return 0;
+}
+
+// printFizz() outputs "fizz".
+void fizz(FizzBuzz *obj) {
+ while (1)
+ if (helper(obj, 1) == -1)
+ break;
+ pthread_mutex_unlock(&mutex);
+}
+
+// printBuzz() outputs "buzz".
+void buzz(FizzBuzz *obj) {
+ while (1)
+ if (helper(obj, 2) == -1)
+ break;
+ pthread_mutex_unlock(&mutex);
+}
+
+// printFizzBuzz() outputs "fizzbuzz".
+void fizzbuzz(FizzBuzz *obj) {
+ while (1)
+ if (helper(obj, 3) == -1)
+ break;
+ pthread_mutex_unlock(&mutex);
+}
+
+// You may call global function `void printNumber(int x)`
+// to output "x", where x is an integer.
+void number(FizzBuzz *obj) {
+ while (1)
+ if (helper(obj, 0) == -1)
+ break;
+ pthread_mutex_unlock(&mutex);
+}
+
+void fizzBuzzFree(FizzBuzz *obj) {
+ if (obj)
+ free(obj);
+}
+
+void printNumber(int a) { printf("%d ", a); }
+
+void printFizz() { printf("fizz "); }
+
+void printBuzz() { printf("buzz "); }
+
+void printFizzBuzz() { printf("fizzbuzz "); }
+
+int main() {
+ FizzBuzz *obj1 = fizzBuzzCreate(15);
+ FizzBuzz *obj2 = fizzBuzzCreate(5);
+ pthread_t t1[4], t2[4];
+ pthread_create(&t1[0], NULL, (void *)fizz, obj1);
+ pthread_create(&t1[1], NULL, (void *)buzz, obj1);
+ pthread_create(&t1[2], NULL, (void *)fizzbuzz, obj1);
+ pthread_create(&t1[3], NULL, (void *)number, obj1);
+ for (int i = 0; i < 4; i++)
+ pthread_join(
+ t1[i],
+ NULL); // expect:
+ // [1,2,"fizz",4,"buzz","fizz",7,8,"fizz","buzz",11,"fizz",13,14,"fizzbuzz"]
+ pthread_create(&t2[0], NULL, (void *)fizz, obj2);
+ pthread_create(&t2[1], NULL, (void *)buzz, obj2);
+ pthread_create(&t2[2], NULL, (void *)fizzbuzz, obj2);
+ pthread_create(&t2[3], NULL, (void *)number, obj2);
+ for (int i = 0; i < 4; i++)
+ pthread_join(t1[i], NULL); // expect: [1,2,"fizz",4,"buzz"]
+ fizzBuzzFree(obj1);
+ fizzBuzzFree(obj2);
+}
diff --git a/fizz_buzz_multithread.py b/fizz_buzz_multithread.py
new file mode 100644
index 0000000..5292164
--- /dev/null
+++ b/fizz_buzz_multithread.py
@@ -0,0 +1,94 @@
+# 1195. Fizz Buzz Multithreaded
+import threading
+
+"""
+you have the following functions:
+'printFizz' prints the word "fizz" to the console
+'printBuzz' prints the word "buzz" to the console
+'printFizzBuzz' prints the word "fizzbuzz" to the console
+'printNumber' that prints a given integer to the console
+you are given an instance of the class 'fizzbuzz' that has four functions
+'fizz', 'buzz', 'fizzbuzz', and 'number'. the same instance of 'fizzbuzz'
+will be passed to four different threads.
+thread a calls 'fizz()' that should output the word "fizz"
+thread b calls 'buzz()' that should output the word "buzz"
+thread c calls 'fizzbuzz()' that should output the word "fizzbuzz"
+thread d calls 'number()' that should output the given integer
+modify the given class to output the series '[1, 2, "fizz", 4, "buzz", ...]'
+where the i'th toek of the series is.
+"""
+
+
+class FizzBuzz(object):
+ def __init__(self, n):
+ self.n = n
+ self.f = threading.Lock()
+ self.b = threading.Lock()
+ self.fb = threading.Lock()
+ self.f.acquire()
+ self.b.acquire()
+ self.fb.acquire()
+ self.main = threading.Lock()
+
+ # printFizz() outputs "fizz"
+ def fizz(self, printFizz):
+ """
+ :type printFizz: method
+ :rtype: void
+ """
+ while True:
+ self.f.acquire()
+ if self.n == 0:
+ return
+ printFizz()
+ self.main.release()
+
+ # printBuzz() outputs "buzz"
+ def buzz(self, printBuzz):
+ """
+ :type printBuzz: method
+ :rtype: void
+ """
+ while True:
+ self.b.acquire()
+ if self.n == 0:
+ return
+ printBuzz()
+ self.main.release()
+
+ # printFizzBuzz() outputs "fizzbuzz"
+ def fizzbuzz(self, printFizzBuzz):
+ """
+ :type printFizzBuzz: method
+ :rtype: void
+ """
+ while True:
+ self.fb.acquire()
+ if self.n == 0:
+ return
+ printFizzBuzz()
+ self.main.release()
+
+ # printNumber(x) outputs "x", where x is an integer.
+ def number(self, printNumber):
+ """
+ :type printNumber: method
+ :rtype: void
+ """
+ for i in range(1, self.n + 1):
+ self.main.acquire()
+ if i % 15 == 0:
+ self.fb.release()
+ elif i % 3 == 0:
+ self.f.release()
+ elif i % 5 == 0:
+ self.b.release()
+ else:
+ printNumber(i)
+ self.main.release()
+ self.main.acquire()
+ self.n = 0
+ self.f.release()
+ self.b.release()
+ self.fb.release()
+ return
diff --git a/generate_binary_string_without_adj_0.c b/generate_binary_string_without_adj_0.c
new file mode 100644
index 0000000..7ad3843
--- /dev/null
+++ b/generate_binary_string_without_adj_0.c
@@ -0,0 +1,55 @@
+// 3211. Generate Binary Strings Without Adjacent Zeros
+#include "leetcode.h"
+
+/*
+ * you are given a positive integer 'n'. a binary string 'x' is valid if all
+ * substrings of 'x' of length 2 contain at least one 1. return all valid
+ * strings with length 'n' in any order.
+ */
+
+void dfs(char **ans, int *returnSize, char *tmp, int *tmp_idx, int n,
+ bool prev) {
+ if ((*tmp_idx) == n) {
+ ans[(*returnSize)] = (char *)calloc(n + 1, sizeof(char));
+ memcpy(ans[(*returnSize)++], tmp, (*tmp_idx) * sizeof(char));
+ return;
+ }
+ if (prev) {
+ tmp[(*tmp_idx)++] = '1';
+ dfs(ans, returnSize, tmp, tmp_idx, n, !prev);
+ (*tmp_idx)--;
+ } else {
+ for (int i = 0; i < 2; i++) {
+ tmp[(*tmp_idx)++] = i + '0';
+ dfs(ans, returnSize, tmp, tmp_idx, n, !i);
+ (*tmp_idx)--;
+ }
+ }
+}
+
+char **validStrings(int n, int *returnSize) {
+ *returnSize = 0;
+ char **ans = (char **)malloc(pow(2, n) * sizeof(char *));
+ char *tmp = (char *)calloc(n + 1, sizeof(char));
+ for (int i = 0; i < 2; i++) {
+ int tmp_idx = 0;
+ tmp[tmp_idx++] = i + '0';
+ dfs(ans, returnSize, tmp, &tmp_idx, n, !i);
+ }
+ free(tmp);
+ return ans;
+}
+
+int main() {
+ int rs1, rs2;
+ char **vs1 = validStrings(3, &rs1);
+ char **vs2 = validStrings(1, &rs2);
+ for (int i = 0; i < rs1; i++)
+ printf("%s ", vs1[i]); // expect: ["010","011","101","110","111"]
+ printf("\n");
+ for (int i = 0; i < rs1; i++)
+ printf("%s ", vs2[i]); // expect: ["0","1"]
+ printf("\n");
+ free(vs1);
+ free(vs2);
+}
diff --git a/generate_binary_string_without_adj_0.py b/generate_binary_string_without_adj_0.py
new file mode 100644
index 0000000..5669156
--- /dev/null
+++ b/generate_binary_string_without_adj_0.py
@@ -0,0 +1,36 @@
+# 3211. Generate Binary Strings Without Adjacent Zeros
+
+"""
+you are given a positive integer 'n'. a binary string 'x' is valid if all
+substrings of 'x' of length 2 contain at least one 1. return all valid
+strings with length 'n' in any order.
+"""
+
+
+class Solution(object):
+ def __init__(self):
+ self.ans = []
+
+ def dfs(self, prev, str, n):
+ if len(str) == n:
+ self.ans.append(str)
+ return
+ self.dfs(1, str + "1", n)
+ if prev == 1:
+ self.dfs(0, str + "0", n)
+
+ def validStrings(self, n):
+ """
+ :type n: int
+ :rtype: List[str]
+ """
+ self.ans = []
+ self.dfs(0, "0", n)
+ self.dfs(1, "1", n)
+ return self.ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.validStrings(n=3))
+ print(obj.validStrings(n=1))
diff --git a/kth_smallest_product_sort_arr.c b/kth_smallest_product_sort_arr.c
new file mode 100644
index 0000000..8ab9c80
--- /dev/null
+++ b/kth_smallest_product_sort_arr.c
@@ -0,0 +1,95 @@
+// 2040. Kth Smallest Product of Two Sorted Arrays
+#include "leetcode.h"
+
+/*
+ * given two sorted 0-indexed integer arrays 'nums1' and 'nums2' as well as an
+ * integer 'k', return the k'th smallest product of 'nums1[i] * nums2[i]' where
+ * '0 <= i < nums1.length' and '0 <= j < nums2.length'
+ */
+
+long long kthSmallestProduct(int *nums1, int nums1Size, int *nums2,
+ int nums2Size, long long k) {
+ int n1 = 0, n2 = 0;
+ while (n1 < nums1Size && nums1[n1] < 0)
+ n1++;
+ while (n2 < nums2Size && nums2[n1] < 0)
+ n2++;
+ int z1 = 0, p1 = 0;
+ for (int i = n1; i < nums1Size; i++) {
+ if (!nums1[i])
+ z1++;
+ else
+ p1++;
+ }
+ int z2 = 0, p2 = 0;
+ for (int i = n2; i < nums2Size; i++) {
+ if (!nums2[i])
+ z2++;
+ else
+ p2++;
+ ;
+ }
+ int p1_beg = n1 + z1, p2_beg = n2 + z2;
+ long long start = -1e9, end = 1e9;
+ while (start <= end) {
+ long long mid = (start + end) / 2, total = 0;
+ if (mid >= 0) {
+ total += (long long)n1 * p2 + (long long)p1 * n2;
+ total += (long long)z1 * nums2Size + (long long)(nums1Size - z1) * z2;
+ int i = 0, j = n2 - 1;
+ while (i < n1 && j >= 0) {
+ if ((long long)nums1[i] * nums2[j] > mid)
+ i++;
+ else {
+ total += n1 - i;
+ j--;
+ }
+ }
+ i = p1_beg, j = nums2Size - 1;
+ while (i < nums1Size && j >= p2_beg) {
+ if ((long long)nums1[i] * nums2[j] > mid)
+ j--;
+ else {
+ total += j - p2_beg + 1;
+ i++;
+ }
+ }
+ } else {
+ int i = 0, j = p2_beg;
+ while (i < n1 && j < nums2Size) {
+ if ((long long)nums1[i] * nums2[j] > mid)
+ j++;
+ else {
+ total += nums2Size - j;
+ i++;
+ }
+ }
+ i = p1_beg, j = 0;
+ while (i < nums1Size && j < n2) {
+ if ((long long)nums1[i] * nums2[j] > mid)
+ i++;
+ else {
+ total += nums1Size - i;
+ j++;
+ }
+ }
+ }
+ if (total < k)
+ start = mid + 1;
+ else
+ end = mid - 1;
+ }
+ return start;
+}
+
+int main() {
+ int n11[] = {2, 5}, n21[] = {3, 4};
+ int n12[] = {-4, -2, 0, 3}, n22[] = {2, 4};
+ int n13[] = {-2, -1, 0, 1, 2}, n23[] = {-3, -1, 2, 4, 5};
+ printf("%lld\n", kthSmallestProduct(n11, ARRAY_SIZE(n11), n21,
+ ARRAY_SIZE(n21), 2)); // expect: 8
+ printf("%lld\n", kthSmallestProduct(n12, ARRAY_SIZE(n12), n22,
+ ARRAY_SIZE(n22), 6)); // expect: 0
+ printf("%lld\n", kthSmallestProduct(n13, ARRAY_SIZE(n13), n23,
+ ARRAY_SIZE(n23), 3)); // expect: -6
+}
diff --git a/kth_smallest_product_sort_arr.py b/kth_smallest_product_sort_arr.py
new file mode 100644
index 0000000..459a00c
--- /dev/null
+++ b/kth_smallest_product_sort_arr.py
@@ -0,0 +1,45 @@
+# 2040. Kth Smallest Product of Two Sorted Arrays
+import bisect
+from math import ceil
+
+"""
+given two sorted 0-indexed integer arrays 'nums1' and 'nums2' as well as an
+integer 'k', return the k'th smallest product of 'nums1[i] nums2[i]' where
+'0 <= i < nums1.length' and '0 <= j < nums2.length'
+"""
+
+
+class Solution(object):
+ def kthSmallestProduct(self, nums1, nums2, k):
+ """
+ :type nums1: List[int]
+ :type nums2: List[int]
+ :type k: int
+ :rtype: int
+ """
+
+ def check(n):
+ total = 0
+ for i in nums1:
+ if i > 0:
+ total += bisect.bisect(nums2, n // i)
+ if i < 0:
+ total += len(nums2) - bisect.bisect_left(nums2, ceil(n / i))
+ if i == 0 and n >= 0:
+ total += len(nums2)
+
+ start, end = -(10**10) - 1, 10**10 + 1
+ while start + 1 < end:
+ mid = (start + end) // 2
+ if check(mid) >= k:
+ end = mid
+ else:
+ start = mid
+ return start + 1
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.kthSmallestProduct(nums1=[2, 5], nums2=[3, 4], k=2))
+ print(obj.kthSmallestProduct(nums1=[-4, -2, 0, 3], nums2=[2, 4], k=6))
+ print(obj.kthSmallestProduct(nums1=[-2, -1, 0, 1, 2], nums2=[-3, -1, 2, 4, 5], k=3))
diff --git a/largest_colour_val_dir_graph.c b/largest_colour_val_dir_graph.c
new file mode 100644
index 0000000..79771bf
--- /dev/null
+++ b/largest_colour_val_dir_graph.c
@@ -0,0 +1,115 @@
+// 1857. Largest Color Value in a Directed Graph
+#include "leetcode.h"
+
+/*
+ * there is a directed graph of 'n' coloured nodes and 'm' edges. the nodes are
+ * numbered from 0 to 'n - 1'. you are given a tring 'colours' where
+ * 'colours[i]' is a lowercase english letter representing the colour of the
+ * i'th node in this graph (0-indexed). you are also given a 2d integer array
+ * 'edges' where 'edges[i] = [ai, bi]' indicates that there is a directed edge
+ * from node 'ai' to 'bi'. a valid path in the graph is a sequence of nodes such
+ * that there is a directed edge for every ' 1 <= i < k'. the collour value of
+ * the path is the number of nodes that coloured the most frequently occuring
+ * along the path. return the largest colour value of any valid path in the
+ * given graph, or -1 if the graph contains a cycle.
+ */
+
+struct node {
+ int val;
+ struct node *next;
+};
+
+struct graph {
+ struct node *next;
+ char colour;
+ int *cnt;
+};
+
+struct node *graph_create(struct node *prev, int val) {
+ struct node *obj = (struct node *)malloc(sizeof(struct node));
+ obj->next = prev;
+ obj->val = val;
+ return obj;
+}
+
+void graph_free(struct graph *s, int n) {
+ for (int i = 0; i < n; i++) {
+ while (s[i].next) {
+ struct node *tmp = s[i].next;
+ s[i].next = s[i].next->next;
+ free(tmp);
+ }
+ free(s[i].cnt);
+ }
+ free(s);
+}
+
+void search(int val, struct graph *plan, bool *vis, bool *cycle, int *res) {
+ vis[val] = true;
+ while (plan[val].next) {
+ int new = plan[val].next->val;
+ if (vis[new]) {
+ *cycle = true;
+ return;
+ }
+ if (plan[new].cnt) {
+ for (int i = 0; i < 26; i++)
+ if (plan[val].cnt[i] < plan[new].cnt[i])
+ plan[val].cnt[i] = plan[new].cnt[i];
+ plan[val].next = plan[val].next->next;
+ continue;
+ }
+ plan[new].cnt = (int *)calloc(26, sizeof(int));
+ search(new, plan, vis, cycle, res);
+ for (int i = 0; i < 26; i++)
+ if (plan[val].cnt[i] < plan[new].cnt[i])
+ plan[val].cnt[i] = plan[new].cnt[i];
+ plan[val].next = plan[val].next->next;
+ }
+ plan[val].cnt[plan[val].colour - 'a']++;
+ if (*res < plan[val].cnt[plan[val].colour - 'a'])
+ *res = plan[val].cnt[plan[val].colour - 'a'];
+ vis[val] = false;
+}
+
+int largestPathValue(char *colors, int **edges, int edgesSize,
+ int *edgesColSize) {
+ int n = strlen(colors);
+ struct graph *plan = (struct graph *)calloc(n, sizeof(struct graph));
+ bool *vis = (bool *)calloc(n, sizeof(bool));
+ for (int i = 0; i < n; i++)
+ plan[i].colour = colors[i];
+ for (int i = 0; i < edgesSize; i++) {
+ if (edges[i][0] == edges[i][1]) {
+ graph_free(plan, n);
+ return -1;
+ }
+ plan[edges[i][0]].next = graph_create(plan[edges[i][0]].next, edges[i][1]);
+ }
+ bool cycle = false;
+ int ans = 0;
+ for (int i = 0; i < n; i++) {
+ if (!plan[i].cnt) {
+ plan[i].cnt = (int *)calloc(26, sizeof(int));
+ search(i, plan, vis, &cycle, &ans);
+ if (cycle) {
+ graph_free(plan, n);
+ return -1;
+ }
+ }
+ }
+ graph_free(plan, n);
+ return ans;
+}
+
+int main() {
+ char *c1 = "abaca", *c2 = "a";
+ int e1i[4][2] = {{0, 1}, {0, 2}, {2, 3}, {3, 4}}, e2i[1][2] = {{0, 0}};
+ struct two_d_arr e1, e2;
+ two_d_arr_init(&e1, ARRAY_SIZE(e1i), ARRAY_SIZE(e1i[0]), e1i);
+ two_d_arr_init(&e2, ARRAY_SIZE(e2i), ARRAY_SIZE(e2i[0]), e2i);
+ printf("%d\n",
+ largestPathValue(c1, e1.arr, e1.row_size, e1.col_size)); // expect: 3
+ printf("%d\n",
+ largestPathValue(c2, e2.arr, e2.row_size, e2.col_size)); // expect: -1
+}
diff --git a/largest_colour_val_dir_graph.py b/largest_colour_val_dir_graph.py
new file mode 100644
index 0000000..170c1a5
--- /dev/null
+++ b/largest_colour_val_dir_graph.py
@@ -0,0 +1,57 @@
+# 1857. Largest Color Value in a Directed Graph
+from collections import deque
+
+"""
+there is a directed graph of 'n' coloured nodes and 'm' edges. the nodes are
+numbered from 0 to 'n - 1'. you are given a tring 'colours' where
+'colours[i]' is a lowercase english letter representing the colour of the
+i'th node in this graph (0-indexed). you are also given a 2d integer array
+'edges' where 'edges[i] = [ai, bi]' indicates that there is a directed edge
+from node 'ai' to 'bi'. a valid path in the graph is a sequence of nodes such
+that there is a directed edge for every ' 1 <= i < k'. the collour value of
+the path is the number of nodes that coloured the most frequently occuring
+along the path. return the largest colour value of any valid path in the
+given graph, or -1 if the graph contains a cycle.
+"""
+
+
+class Solution(object):
+ def largestPathValue(self, colors, edges):
+ """
+ :type colors: str
+ :type edges: List[List[int]]
+ :rtype: int
+ """
+ n = len(colors)
+ indeg = [0] * n
+ graph = [[] for _ in range(n)]
+ for i in edges:
+ graph[i[0]].append(i[1])
+ indeg[i[1]] += 1
+ zero_indeg = deque()
+ for i in range(n):
+ if indeg[i] == 0:
+ zero_indeg.append(i)
+ cnt = [[0] * 26 for _ in range(n)]
+ for i in range(n):
+ cnt[i][ord(colors[i]) - ord("a")] += 1
+ max_cnt, vis = 0, 0
+ while zero_indeg:
+ u = zero_indeg.popleft()
+ vis += 1
+ for v in graph[u]:
+ for i in range(26):
+ cnt[v][i] = max(
+ cnt[v][i], cnt[u][i] + (ord(colors[v]) - ord("a") == i)
+ )
+ indeg[v] -= 1
+ if indeg[v] == 0:
+ zero_indeg.append(v)
+ max_cnt = max(max_cnt, max(cnt[u]))
+ return max_cnt if vis == n else -1
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.largestPathValue(colors="abaca", edges=[[0, 1], [0, 2], [2, 3], [3, 4]]))
+ print(obj.largestPathValue(colors="a", edges=[[0, 0]]))
diff --git a/leetcode.h b/leetcode.h
index c68a56a..0f0ca7c 100644
--- a/leetcode.h
+++ b/leetcode.h
@@ -4,6 +4,7 @@
#include <ctype.h>
#include <limits.h>
#include <math.h>
+#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
diff --git a/lex_min_str_rem_star.c b/lex_min_str_rem_star.c
new file mode 100644
index 0000000..1a854ef
--- /dev/null
+++ b/lex_min_str_rem_star.c
@@ -0,0 +1,141 @@
+// 3170. Lexicographically Minimum String After Removing Stars
+#include "leetcode.h"
+
+/*
+ * you are given a string 's'. it may contain any number of '*' characters. your
+ * task to remove all '*' characters. while there is a '*' character, do the
+ * following: delete the leftmost '*' and the smallest non-'*' character to its
+ * left. if there are several smallest characters, you can delete any of them.
+ * return the lexicographically smallest resulting string after removing all '*'
+ * characters.
+ */
+
+struct node {
+ char c;
+ int idx;
+};
+
+struct pq {
+ int (*cmp)(const void *, const void *);
+ int size;
+ int capacity;
+ void **data;
+};
+
+struct node *node_init(char c, int idx) {
+ struct node *obj = (struct node *)malloc(sizeof(struct node));
+ obj->c = c;
+ obj->idx = idx;
+ return obj;
+}
+
+int cmp(const void *a, const void *b) {
+ char c1 = ((struct node *)a)->c;
+ char c2 = ((struct node *)b)->c;
+ int n1 = ((struct node *)a)->idx;
+ int n2 = ((struct node *)b)->idx;
+ if (c1 < c2)
+ return 1;
+ if (c1 > c2)
+ return -1;
+ if (n1 > n2)
+ return 1;
+ if (n1 < n2)
+ return -1;
+ return 0;
+}
+
+struct pq *pq_init(int capacity, int (*cmp)(const void *, const void *)) {
+ struct pq *obj = (struct pq *)malloc(sizeof(struct pq));
+ obj->cmp = cmp;
+ obj->size = 0;
+ obj->capacity = capacity;
+ obj->data = (void **)malloc(capacity * sizeof(void *));
+ for (int i = 0; i < capacity; i++)
+ obj->data[i] = NULL;
+ return obj;
+}
+
+void pq_swap(struct pq *obj, const int key1, const int key2) {
+ void *tmp = obj->data[key1];
+ obj->data[key1] = obj->data[key2];
+ obj->data[key2] = tmp;
+ return;
+}
+
+void pq_repair_bottom(struct pq *obj) {
+ int child = obj->size - 1, parent = (child - 1) / 2;
+ while (child > 0 && obj->cmp(obj->data[child], obj->data[parent]) == 1) {
+ pq_swap(obj, child, parent);
+ child = parent;
+ parent = (child - 1) / 2;
+ }
+ return;
+}
+
+void pq_push(struct pq *obj, void *item) {
+ assert(obj->size < obj->capacity);
+ obj->data[obj->size++] = item;
+ pq_repair_bottom(obj);
+ return;
+}
+
+void pq_repair_top(struct pq *obj) {
+ int parent = 0, child = parent * 2 + 1;
+ while (child < obj->size) {
+ if (child + 1 < obj->size &&
+ obj->cmp(obj->data[child + 1], obj->data[child]) == 1)
+ child++;
+ if (obj->cmp(obj->data[parent], obj->data[child]) == 1)
+ break;
+ pq_swap(obj, parent, child);
+ parent = child;
+ child = parent * 2 + 1;
+ }
+ return;
+}
+
+void *pq_pop(struct pq *obj) {
+ assert(obj->size > 0);
+ pq_swap(obj, 0, obj->size - 1);
+ obj->size--;
+ pq_repair_top(obj);
+ return obj->data[obj->size];
+}
+
+void pq_free(struct pq *obj) {
+ for (int i = 0; i < obj->size; i++)
+ free(obj->data[i]);
+ free(obj->data);
+ free(obj);
+ return;
+}
+
+char *clearStars(char *s) {
+ const int n = strlen(s);
+ char *ans = (char *)malloc((n + 1) * sizeof(char));
+ struct pq *pq = pq_init(n, cmp);
+ for (int i = 0; i < n; i++) {
+ if (s[i] != '*') {
+ struct node *n = node_init(*(s + i), i);
+ pq_push(pq, n);
+ } else if (pq->size > 0) {
+ struct node *curr = pq_pop(pq);
+ s[curr->idx] = '#';
+ }
+ }
+ pq_free(pq);
+ int idx = 0;
+ for (; *s; s++)
+ if (*s != '#' && *s != '*')
+ ans[idx++] = *s;
+ ans[idx] = '\0';
+ return ans;
+}
+
+int main() {
+ char *s1 = "aaba*", *cs1 = clearStars(s1);
+ char *s2 = "abc", *cs2 = clearStars(s2);
+ printf("%s\n", cs1); // expect: aab
+ printf("%s\n", cs2); // expect: abc
+}
diff --git a/lex_min_str_rem_star.py b/lex_min_str_rem_star.py
new file mode 100644
index 0000000..04e2cd0
--- /dev/null
+++ b/lex_min_str_rem_star.py
@@ -0,0 +1,46 @@
+# 3170. Lexicographically Minimum String After Removing Stars
+from queue import PriorityQueue
+
+"""
+you are given a string 's'. it may contain any number of '' characters. your
+task to remove all '' characters. while there is a '' character, do the
+following: delete the leftmost '' and the smallest non-'' character to its
+left. if there are several smallest characters, you can delete any of them.
+return the lexicographically smallest resulting string after removing all ''
+characters.
+"""
+
+
+class Solution(object):
+ def clearStars(self, s):
+ """
+ :type s: str
+ :rtype: str
+ """
+ pq = PriorityQueue()
+ idx = [[] for i in range(26)]
+ remove_set = set()
+ for i in range(len(s)):
+ if s[i] == "*":
+ remove_set.add(i)
+ c = pq.get()
+ pq.put(c)
+ remove_set.add(idx[ord(c) - ord("a")][-1])
+ del idx[ord(c) - ord("a")][-1]
+ if len(idx[ord(c) - ord("a")]) == 0:
+ pq.get()
+ continue
+ if len(idx[ord(s[i]) - ord("a")]) == 0:
+ pq.put(s[i])
+ idx[ord(s[i]) - ord("a")].append(i)
+ ans = ""
+ for i in range(len(s)):
+ if i not in remove_set:
+ ans += str(s[i])
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.clearStars(s="aaba*"))
+ print(obj.clearStars(s="abc"))
diff --git a/lex_smallest_beaut_str.c b/lex_smallest_beaut_str.c
new file mode 100644
index 0000000..8009a4a
--- /dev/null
+++ b/lex_smallest_beaut_str.c
@@ -0,0 +1,47 @@
+// 2663. Lexicographically Smallest Beautiful String
+#include "leetcode.h"
+
+/*
+ * a string is beautiful if it consists of the first 'k' letters of the english
+ * lowercase alphabet, it does not contain a palindrome of length 2 or more
+ * which is a palindrome. you are given a beautiful string 's' of length 'n',
+ * and a positive integer 'k'. return the lexicographically smallest string of
+ * length 'n' which is larger than 's', and is beautiful. if there is no such
+ * string, return an empty string.
+ */
+
+char *smallestBeautifulString(char *s, int k) {
+ int n = strlen(s);
+ char *ans = (char *)malloc((n + 1) * sizeof(char));
+ strcpy(ans, s);
+ for (int i = n - 1; i >= 0; i--) {
+ for (int j = ans[i] - 'a' + 1; j < k; j++) {
+ char curr = j + 'a';
+ if ((i < 1 || curr != ans[i - 1]) && (i < 2 || curr != ans[i - 2])) {
+ ans[i] = curr;
+ for (int l = i + 1; l < n; l++) {
+ for (int m = 0; m < k; m++) {
+ curr = m + 'a';
+ if ((l < 1 || curr != ans[l - 1]) &&
+ (l < 2 || curr != ans[l - 2])) {
+ ans[l] = curr;
+ break;
+ }
+ }
+ }
+ return ans;
+ }
+ }
+ }
+ return "";
+}
+
+int main() {
+ char *s1 = "abcz", *s2 = "dc";
+ char *sbs1 = smallestBeautifulString(s1, 26);
+ char *sbs2 = smallestBeautifulString(s2, 4);
+ printf("%s\n", sbs1); // expect: abda
+ printf("%s\n", sbs2); // expect: null
+ free(sbs1);
+ free(sbs2);
+}
diff --git a/lex_smallest_beaut_str.py b/lex_smallest_beaut_str.py
new file mode 100644
index 0000000..58e1381
--- /dev/null
+++ b/lex_smallest_beaut_str.py
@@ -0,0 +1,36 @@
+# 2663. Lexicographically Smallest Beautiful String
+
+"""
+a string is beautiful if it consists of the first 'k' letters of the english
+lowercase alphabet, it does not contain a palindrome of length 2 or more
+which is a palindrome. you are given a beautiful string 's' of length 'n',
+and a positive integer 'k'. return the lexicographically smallest string of
+length 'n' which is larger than 's', and is beautiful. if there is no such
+string, return an empty string.
+"""
+
+
+class Solution(object):
+ def smallestBeautifulString(self, s, k):
+ """
+ :type s: str
+ :type k: int
+ :rtype: str
+ """
+ ans = [ord(c) - ord("a") for c in s]
+ n = len(ans) - 1
+ while n >= 0:
+ ans[n] += 1
+ if ans[n] == k:
+ n -= 1
+ elif ans[n] not in ans[max(n - 2, 0) : n]:
+ for j in range(n + 1, len(ans)):
+ ans[j] = min({0, 1, 2} - set(ans[max(0, j - 2) : j]))
+ return "".join(chr(ord("a") + i) for i in ans)
+ return ""
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.smallestBeautifulString(s="abcz", k=26))
+ print(obj.smallestBeautifulString(s="dc", k=4))
diff --git a/lexicographical_numbers.c b/lexicographical_numbers.c
index 5823da1..2208599 100644
--- a/lexicographical_numbers.c
+++ b/lexicographical_numbers.c
@@ -7,27 +7,22 @@
* complexity and uses O(1) extra space.
*/
-void lex(int *res, int n, int i, int digit, int *k) {
- if (!digit)
- return;
- for (int j = i * 10; j < (i + 1) * 10 && j <= n; j++) {
- res[(*k)++] = j;
- lex(res, n, j, digit - 1, k);
- }
-}
-
int *lexicalOrder(int n, int *returnSize) {
- int *ans = (int *)malloc((n + 1) * sizeof(int));
- int tmp = n, max_digit = 0, k = 0;
- while (tmp) {
- tmp /= 10;
- max_digit++;
- }
- for (int i = 1; i < 10 && i <= n; i++) {
- ans[k++] = i;
- lex(ans, n, i, max_digit, &k);
+ int *ans = (int *)malloc(n * sizeof(int));
+ int curr = 1, k = 0;
+ for (int i = 0; i < n; i++) {
+ ans[i] = curr;
+ if (((curr << 3) + (curr << 1)) <= n)
+ curr = (curr << 3) + (curr << 1);
+ else {
+ if (curr >= n)
+ curr /= 10;
+ curr++;
+ while (!(curr % 10))
+ curr /= 10;
+ }
}
- *returnSize = k;
+ *returnSize = n;
return ans;
}
diff --git a/lexicographically_small_string.c b/lexicographically_small_string.c
deleted file mode 100644
index e635184..0000000
--- a/lexicographically_small_string.c
+++ /dev/null
@@ -1,44 +0,0 @@
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-int unionFind(int *u, int val) {
- if (u[val] == val)
- return val;
- return unionFind(u, u[val]);
-}
-
-bool unionSet(int *u, int a, int b) {
- int findA = unionFind(u, a), findB = unionFind(u, b);
- if (findA == findB)
- return false;
- if (findA < findB)
- u[findB] = u[findA];
- else
- u[findA] = u[findB];
- return true;
-}
-
-char *smallestEquivalentString(char *s1, char *s2, char *baseStr) {
- int *table = malloc(26 * sizeof(int));
- for (int i = 0; i < 26; i++)
- table[i] = i;
- for (int i = 0; i < strlen(s1); i++)
- unionSet(table, s1[i] - 'a', s2[i] - 'a');
- int ansLen = strlen(baseStr);
- char *ans = malloc((ansLen + 1) * sizeof(int));
- ans[ansLen] = '\0';
- for (int i = 0; i < ansLen; i++)
- ans[i] = unionFind(table, baseStr[i] - 'a') + 'a';
- return ans;
-}
-
-int main() {
- printf("%s\n", smallestEquivalentString("parker", "morris",
- "parser")); // expect: makkek
- printf("%s\n",
- smallestEquivalentString("hello", "world", "hold")); // expect: hdld
- printf("%s\n", smallestEquivalentString("leetcode", "programs",
- "sourcecode")); // expect: aauaaaaada
-}
diff --git a/lexicographically_smallest_equivalent_str.c b/lexicographically_smallest_equivalent_str.c
new file mode 100644
index 0000000..f1b4939
--- /dev/null
+++ b/lexicographically_smallest_equivalent_str.c
@@ -0,0 +1,46 @@
+// 1061. Lexicographically Smallest Equivalent String
+#include "leetcode.h"
+
+/*
+ * you are given two strings of the same length 's1' and 's2' and a string
+ * 'baseStr'. we say 's1[i]' and 's2[i]' are equivalent characters. equivalent
+ * characters follow the usual rules of any equivalence relation: reflexivity,
+ * symmetry, and transitivity. return the lexicographically smallest equivalent
+ * string of 'baseStr' by using the equivalency information from 's1' and 's2'.
+ */
+
+char *smallestEquivalentString(char *s1, char *s2, char *baseStr) {
+ char *ans = baseStr, table[26], to_rep, rep_with;
+ for (int i = 0; i < 26; i++)
+ table[i] = i + 'a';
+ while (*s1) {
+ if (table[*s2 - 'a'] < table[*s1 - 'a']) {
+ to_rep = table[*s1 - 'a'];
+ rep_with = table[*s2 - 'a'];
+ for (int i = 0; i < 26; i++)
+ if (table[i] == to_rep)
+ table[i] = rep_with;
+ } else if (table[*s1 - 'a'] < table[*s2 - 'a']) {
+ to_rep = table[*s2 - 'a'];
+ rep_with = table[*s1 - 'a'];
+ for (int i = 0; i < 26; i++)
+ if (table[i] == to_rep)
+ table[i] = rep_with;
+ }
+ s1++, s2++;
+ }
+ while (*baseStr) {
+ *baseStr = table[*baseStr - 'a'];
+ baseStr++;
+ }
+ return ans;
+}
+
+int main() {
+ char *s11 = "parker", *s21 = "morris", *b1 = "parser";
+ char *s12 = "hello", *s22 = "world", *b2 = "hold";
+ char *s13 = "leetcode", *s23 = "programs", *b3 = "sourcecode";
+ printf("%s\n", smallestEquivalentString(s11, s21, b1)); // expect: makkek
+ printf("%s\n", smallestEquivalentString(s12, s22, b2)); // expect: hdld
+ printf("%s\n", smallestEquivalentString(s13, s23, b3)); // expect: aauaaaaada
+}
diff --git a/lexicographically_smallest_equivalent_str.py b/lexicographically_smallest_equivalent_str.py
new file mode 100644
index 0000000..534d844
--- /dev/null
+++ b/lexicographically_smallest_equivalent_str.py
@@ -0,0 +1,49 @@
+# 1061. Lexicographically Smallest Equivalent String
+
+"""
+you are given two strings of the same length 's1' and 's2' and a string
+'baseStr'. we say 's1[i]' and 's2[i]' are equivalent characters. equivalent
+characters follow the usual rules of any equivalence relation: reflexivity,
+symmetry, and transitivity. return the lexicographically smallest equivalent
+string of 'baseStr' by using the equivalency information from 's1' and 's2'.
+"""
+
+
+class Solution(object):
+ def smallestEquivalentString(self, s1, s2, baseStr):
+ """
+ :type s1: str
+ :type s2: str
+ :type baseStr: str
+ :rtype: str
+ """
+ uf = {}
+
+ def find(x):
+ uf.setdefault(x, x)
+ if x != uf[x]:
+ uf[x] = find(uf[x])
+ return uf[x]
+
+ def union(x, y):
+ rx, ry = find(x), find(y)
+ if rx > ry:
+ uf[rx] = ry
+ else:
+ uf[ry] = rx
+
+ for i in range(len(s1)):
+ union(s1[i], s2[i])
+ ans = []
+ for i in baseStr:
+ ans.append(find(i))
+ return "".join(ans)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.smallestEquivalentString(s1="parker", s2="morris", baseStr="parser"))
+ print(obj.smallestEquivalentString(s1="hello", s2="world", baseStr="hold"))
+ print(
+ obj.smallestEquivalentString(s1="leetcode", s2="programs", baseStr="sourcecode")
+ )
diff --git a/longest_binary_subseq_leq_k.c b/longest_binary_subseq_leq_k.c
new file mode 100644
index 0000000..7920e7d
--- /dev/null
+++ b/longest_binary_subseq_leq_k.c
@@ -0,0 +1,30 @@
+// 2311. Longest Binary Subsequence Less Than or Equal to K
+#include "leetcode.h"
+
+/*
+ * you are given a binary string 's' and a positive integer 'k'. return the
+ * length of the longest subsequence of 's' that makes up a binary number less
+ * than or equal to 'k'. note the subsequence can contain leading zeros, the
+ * empty string is considered to be equal to 0, and a subsequence is a string
+ * that can be derived from another string by deleting some or no characters
+ * without changing the order of the remaining characters.
+ */
+
+int longestSubsequence(char *s, int k) {
+ int ans = 0, cost = 1, n = strlen(s);
+ for (int i = n - 1; i >= 0; --i) {
+ if (s[i] == '0' || cost <= k) {
+ k -= cost * (s[i] - '0');
+ ans++;
+ }
+ if (cost <= k)
+ cost *= 2;
+ }
+ return ans;
+}
+
+int main() {
+ char *s1 = "1001010", *s2 = "00101001";
+ printf("%d\n", longestSubsequence(s1, 5)); // expect: 5
+ printf("%d\n", longestSubsequence(s2, 1)); // expect: 6
+}
diff --git a/longest_binary_subseq_leq_k.py b/longest_binary_subseq_leq_k.py
new file mode 100644
index 0000000..e07204a
--- /dev/null
+++ b/longest_binary_subseq_leq_k.py
@@ -0,0 +1,29 @@
+# 2311. Longest Binary Subsequence Less Than or Equal to K
+
+"""
+you are given a binary string 's' and a positive integer 'k'. return the
+length of the longest subsequence of 's' that makes up a binary number less
+than or equal to 'k'. note the subsequence can contain leading zeros, the
+empty string is considered to be equal to 0, and a subsequence is a string
+that can be derived from another string by deleting some or no characters
+without changing the order of the remaining characters.
+"""
+
+
+class Solution(object):
+ def longestSubsequence(self, s, k):
+ """
+ :type s: str
+ :type k: int
+ :rtype: int
+ """
+ i = 0
+ while int(s[-i - 1 :], 2) <= k and i < 32 and i < len(s):
+ i += 1
+ return s[:-i].count("0") + i
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.longestSubsequence(s="1001010", k=5))
+ print(obj.longestSubsequence(s="00101001", k=1))
diff --git a/longest_harmonious_subseq.c b/longest_harmonious_subseq.c
new file mode 100644
index 0000000..1c1e5b4
--- /dev/null
+++ b/longest_harmonious_subseq.c
@@ -0,0 +1,62 @@
+// 594. Longest Harmonious Subsequence
+#include "leetcode.h"
+
+/*
+ * we define a harmonious array as an array where the difference between its
+ * maximum value and its minimum value is exactly 1. given an integer array
+ * 'nums', return the length of the its longest harmonious subsequnce among all
+ * its possible subsequnces.
+ */
+
+struct hash {
+ int num;
+ int cnt;
+ UT_hash_handle hh;
+};
+
+struct hash *mem;
+static int idx;
+
+int *entry(struct hash **set, int n) {
+ struct hash *tmp;
+ HASH_FIND_INT(*set, &n, tmp);
+ if (!tmp) {
+ tmp = &mem[idx++];
+ tmp->num = n;
+ tmp->cnt = 0;
+ HASH_ADD_INT(*set, num, tmp);
+ }
+ return &(tmp->cnt);
+}
+
+bool contains(struct hash **obj, int num) {
+ struct hash *tmp;
+ HASH_FIND_INT(*obj, &num, tmp);
+ return tmp;
+}
+
+int findLHS(int *nums, int numsSize) {
+ struct hash *set = NULL, *p, *tmp, *s;
+ int ans = 0;
+ idx = 0;
+ mem = (struct hash *)calloc(numsSize, sizeof(struct hash));
+ for (int i = 0; i < numsSize; i++)
+ (*entry(&set, nums[i]))++;
+ HASH_ITER(hh, set, s, tmp) {
+ int key = s->num;
+ if (contains(&set, key + 1)) {
+ int sum = *entry(&set, key) + *entry(&set, key + 1);
+ if (sum > ans)
+ ans = sum;
+ }
+ }
+ free(mem);
+ return ans;
+}
+
+int main() {
+ int n1[] = {1, 3, 2, 2, 5, 2, 3, 7}, n2[] = {1, 2, 3, 4}, n3[] = {1, 1, 1, 1};
+ printf("%d\n", findLHS(n1, ARRAY_SIZE(n1))); // expect: 5
+ printf("%d\n", findLHS(n2, ARRAY_SIZE(n2))); // expect: 2
+ printf("%d\n", findLHS(n3, ARRAY_SIZE(n3))); // expect: 0
+}
diff --git a/longest_harmonious_subseq.py b/longest_harmonious_subseq.py
new file mode 100644
index 0000000..1252090
--- /dev/null
+++ b/longest_harmonious_subseq.py
@@ -0,0 +1,26 @@
+# 594. Longest Harmonious Subsequence
+from collections import Counter
+
+"""
+we define a harmonious array as an array where the difference between its
+maximum value and its minimum value is exactly 1. given an integer array
+'nums', return the length of the its longest harmonious subsequnce among all
+its possible subsequnces.
+"""
+
+
+class Solution(object):
+ def findLHS(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ c = Counter(nums)
+ return max((c[i] + c[i + 1]) * (c[i + 1] != 0) for i in c)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.findLHS(nums=[1, 3, 2, 2, 5, 2, 3, 7]))
+ print(obj.findLHS(nums=[1, 2, 3, 4]))
+ print(obj.findLHS(nums=[1, 1, 1, 1]))
diff --git a/longest_palindrome_concat_two_word.c b/longest_palindrome_concat_two_word.c
new file mode 100644
index 0000000..f1b4533
--- /dev/null
+++ b/longest_palindrome_concat_two_word.c
@@ -0,0 +1,36 @@
+// 2131. Longest Palindrome by Concatenating Two Letter Words
+#include "leetcode.h"
+
+/*
+ * you are given an array of strings 'words'. each element of 'words' consists
+ * of two lowercase english letters. create the longest possible palindrome by
+ * selecting some elements from 'words' and concatenating them in any order.
+ * each element can be select at most once. return the length of the longest
+ * palindrome you can create. if it is impossible, return 0. a palindrome is a
+ * string that reads the same forward and backward.
+ */
+
+int longestPalindrome(char **words, int wordsSize) {
+ int freq[26][26] = {0}, ans = 0;
+ for (int i = 0; i < wordsSize; i++) {
+ if (freq[words[i][1] - 'a'][words[i][0] - 'a']) {
+ freq[words[i][1] - 'a'][words[i][0] - 'a']--;
+ ans += 4;
+ } else
+ freq[words[i][0] - 'a'][words[i][1] - 'a']++;
+ }
+ for (int i = 0; i < 26; i++)
+ if (freq[i][i]) {
+ ans += 2;
+ break;
+ }
+ return ans;
+}
+
+int main() {
+ char *w1[] = {"lc", "cl", "gg"}, *w2[] = {"ab", "ty", "yt", "lc", "cl", "ab"},
+ *w3[] = {"cc", "ll", "xx"};
+ printf("%d\n", longestPalindrome((char **)w1, ARRAY_SIZE(w1))); // expect: 6
+ printf("%d\n", longestPalindrome((char **)w2, ARRAY_SIZE(w2))); // expect: 8
+ printf("%d\n", longestPalindrome((char **)w3, ARRAY_SIZE(w3))); // expect: 2
+}
diff --git a/longest_palindrome_concat_two_word.py b/longest_palindrome_concat_two_word.py
new file mode 100644
index 0000000..5c66903
--- /dev/null
+++ b/longest_palindrome_concat_two_word.py
@@ -0,0 +1,46 @@
+# 2131. Longest Palindrome by Concatenating Two Letter Words
+from collections import defaultdict
+
+"""
+you are given an array of strings 'words'. each element of 'words' consists
+of two lowercase english letters. create the longest possible palindrome by
+selecting some elements from 'words' and concatenating them in any order.
+each element can be select at most once. return the length of the longest
+palindrome you can create. if it is impossible, return 0. a palindrome is a
+string that reads the same forward and backward.
+"""
+
+
+class Solution(object):
+ def longestPalindrome(self, words):
+ """
+ :type words: List[str]
+ :rtype: int
+ """
+ map = defaultdict(int)
+ unpaired, ans = 0, 0
+ for i in words:
+ if i[0] == i[1]:
+ if map[i] > 0:
+ unpaired -= 1
+ map[i] -= 1
+ ans += 4
+ else:
+ map[i] += 1
+ unpaired += 1
+ else:
+ if map[i[::-1]] > 0:
+ ans += 4
+ map[i[::-1]] -= 1
+ else:
+ map[i] += 1
+ if unpaired > 0:
+ ans += 2
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.longestPalindrome(words=["lc", "cl", "gg"]))
+ print(obj.longestPalindrome(words=["ab", "ty", "yt", "lc", "cl", "ab"]))
+ print(obj.longestPalindrome(words=["cc", "ll", "xx"]))
diff --git a/longest_subseq_repeat_k_time.c b/longest_subseq_repeat_k_time.c
new file mode 100644
index 0000000..a5ba84e
--- /dev/null
+++ b/longest_subseq_repeat_k_time.c
@@ -0,0 +1,100 @@
+// 2014. Longest Subsequence Repeated k Times
+#include "leetcode.h"
+
+/*
+ * you are given a string 's' of length 'n', and an integer 'k. you are tasked
+ * to find the longest subsequence repeated 'k' times in 's'. a subsequence is a
+ * string that can be derived from another string by deleting some or no
+ * characters without changing the order of the remaining characters. a
+ * subsequence 'seq' is repeated 'k' times in a sting 's' if 'seq * k' is a
+ * subsequence of 's' where 'seq * k' represents a string constructed by
+ * concatenating 'seq' 'k' times. return the longest subsequence repeated 'k'
+ * times in string 's'. if multiple subsequences are found, return the
+ * lexicographically largest one.
+ */
+
+#define QUEUE_SIZE 1000000
+
+struct node {
+ char str[8];
+ int size;
+};
+
+static char max[8];
+
+bool is_subseq(const char *s, const char *t) {
+ int i = 0, j = 0, ns = strlen(s), nt = strlen(t);
+ while (i < ns && j < nt) {
+ if (s[i] == t[j])
+ j++;
+ i++;
+ }
+ return j == nt;
+}
+
+bool is_repeated(const char *s, const char *seq, int k) {
+ int n = strlen(seq), total = n * k;
+ if (total > strlen(s))
+ return false;
+ char *repeated = (char *)malloc((total + 1) * sizeof(char));
+ for (int i = 0; i < k; i++)
+ strncpy(repeated + i * n, seq, n);
+ repeated[total] = '\0';
+ int res = is_subseq(s, repeated);
+ free(repeated);
+ return res;
+}
+
+char *longestSubsequenceRepeatedK(char *s, int k) {
+ int freq[26] = {0}, n = strlen(s);
+ for (int i = 0; i < n; i++)
+ freq[s[i] - 'a']++;
+ char appear[27];
+ int idx = 0;
+ for (int i = 25; i >= 0; --i)
+ if (freq[i] >= k)
+ appear[idx++] = i + 'a';
+ appear[idx] = '\0';
+ struct node queue[QUEUE_SIZE];
+ int front = 0, back = 0;
+ queue[back++] = (struct node){"", 0};
+ max[0] = '\0';
+ int mn = 0;
+ while (front < back) {
+ struct node curr_node = queue[front++];
+ char *curr_str = curr_node.str;
+ if (curr_node.size < mn)
+ continue;
+ if (is_repeated(s, curr_str, k)) {
+ if (curr_node.size > mn ||
+ (curr_node.size == mn && strcmp(curr_str, max) > 0)) {
+ strcpy(max, curr_str);
+ mn = curr_node.size;
+ }
+ } else
+ continue;
+ if (curr_node.size == 7 || curr_node.size >= n / k)
+ continue;
+ for (int i = 0; i < idx; ++i) {
+ if (back >= QUEUE_SIZE)
+ break;
+ struct node next;
+ strcpy(next.str, curr_str);
+ next.str[curr_node.size] = appear[i];
+ next.str[curr_node.size + 1] = '\0';
+ next.size = curr_node.size + 1;
+ queue[back++] = next;
+ }
+ }
+ return strdup(max);
+}
+
+int main() {
+ char *s1 = "letsleetcode", *s2 = "bb", *s3 = "ab";
+ char *lsrk1 = longestSubsequenceRepeatedK(s1, 2);
+ char *lsrk2 = longestSubsequenceRepeatedK(s2, 2);
+ char *lsrk3 = longestSubsequenceRepeatedK(s3, 2);
+ printf("%s\n", lsrk1); // expect: let
+ printf("%s\n", lsrk2); // expect: b
+ printf("%s\n", lsrk3); // expect: null
+}
diff --git a/longest_subseq_repeat_k_time.py b/longest_subseq_repeat_k_time.py
new file mode 100644
index 0000000..2f4b525
--- /dev/null
+++ b/longest_subseq_repeat_k_time.py
@@ -0,0 +1,45 @@
+# 2014. Longest Subsequence Repeated k Times
+from collections import Counter
+from itertools import combinations, permutations
+
+"""
+you are given a string 's' of length 'n', and an integer 'k. you are tasked
+to find the longest subsequence repeated 'k' times in 's'. a subsequence is a
+string that can be derived from another string by deleting some or no
+characters without changing the order of the remaining characters. a
+subsequence 'seq' is repeated 'k' times in a sting 's' if 'seq k' is a
+subsequence of 's' where 'seq k' represents a string constructed by
+concatenating 'seq' 'k' times. return the longest subsequence repeated 'k'
+times in string 's'. if multiple subsequences are found, return the
+lexicographically largest one.
+"""
+
+
+class Solution(object):
+ def is_subseq(self, s, t):
+ t = iter(t)
+ return all(i in t for i in s)
+
+ def longestSubsequenceRepeatedK(self, s, k):
+ """
+ :type s: str
+ :type k: int
+ :rtype: str
+ """
+ freq = "".join(i * (j // k) for i, j in Counter(s).items())
+ combs = set()
+ for i in range(len(freq) + 1):
+ for j in combinations(freq, i):
+ for l in permutations(j):
+ combs.add("".join(l))
+ combs = sorted(combs, key=lambda x: (len(x), x), reverse=True)
+ for i in combs:
+ if self.is_subseq(i * k, s):
+ return i
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.longestSubsequenceRepeatedK(s="letsleetcode", k=2))
+ print(obj.longestSubsequenceRepeatedK(s="bb", k=2))
+ print(obj.longestSubsequenceRepeatedK(s="ab", k=2))
diff --git a/longest_unequal_adjacent_group1.c b/longest_unequal_adjacent_group1.c
new file mode 100644
index 0000000..ab8018a
--- /dev/null
+++ b/longest_unequal_adjacent_group1.c
@@ -0,0 +1,39 @@
+// 2900. Longest Unequal Adjacent Groups Subsequence I
+#include "leetcode.h"
+
+/*
+ * you are given a string array 'words' and a binary array 'groups' both of
+ * length 'n' where 'words[i]' is associated with 'groups[i]'. your task is to
+ * select the longest alternating subsequence from 'words'. a subsequence of
+ * 'words' is alternating if for any two consecutive strings in the sequence,
+ * their corresponding elements in the binary array 'groups' differ.
+ * essentially, you are to choose strings such that adjacent elements have
+ * non-matching corresponding bits in the 'groups' array. return the selected
+ * subsequence. if there are multiple, return any of them. note: the elements in
+ * 'words' are distinct.
+ */
+
+char **getLongestSubsequence(char **words, int wordsSize, int *groups,
+ int groupsSize, int *returnSize) {
+ int j = 1;
+ for (int i = 1; i < groupsSize; i++)
+ if (groups[i] != groups[i - 1])
+ words[j++] = strdup(words[i]);
+ *returnSize = j;
+ return words;
+}
+
+int main() {
+ char *w1[] = {"e", "a", "b"}, *w2[] = {"a", "b", "c", "d"};
+ int g1[] = {0, 0, 1}, g2[] = {1, 0, 1, 1}, rs1, rs2;
+ char **gls1 = getLongestSubsequence((char **)w1, ARRAY_SIZE(w1), g1,
+ ARRAY_SIZE(g1), &rs1);
+ char **gls2 = getLongestSubsequence((char **)w2, ARRAY_SIZE(w2), g2,
+ ARRAY_SIZE(g2), &rs2);
+ for (int i = 0; i < rs1; i++)
+ printf("%s ", gls1[i]); // expect: e b
+ printf("\n");
+ for (int i = 0; i < rs2; i++)
+ printf("%s ", gls2[i]); // expect: a b c
+ printf("\n");
+}
diff --git a/longest_unequal_adjacent_group1.py b/longest_unequal_adjacent_group1.py
new file mode 100644
index 0000000..629e9f9
--- /dev/null
+++ b/longest_unequal_adjacent_group1.py
@@ -0,0 +1,33 @@
+# 2900. Longest Unequal Adjacent Groups Subsequence I
+
+"""
+you are given a string array 'words' and a binary array 'groups' both of
+length 'n' where 'words[i]' is associated with 'groups[i]'. your task is to
+select the longest alternating subsequence from 'words'. a subsequence of
+'words' is alternating if for any two consecutive strings in the sequence,
+their corresponding elements in the binary array 'groups' differ.
+essentially, you are to choose strings such that adjacent elements have
+non-matching corresponding bits in the 'groups' array. return the selected
+subsequence. if there are multiple, return any of them. note: the elements in
+'words' are distinct.
+"""
+
+
+class Solution(object):
+ def getLongestSubsequence(self, words, groups):
+ """
+ :type words: List[str]
+ :type groups: List[int]
+ :rtype: List[str]
+ """
+ k = [0]
+ for i, j in enumerate(groups):
+ if j != groups[k[-1]]:
+ k.append(i)
+ return [words[i] for i in k]
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.getLongestSubsequence(words=["e", "a", "b"], groups=[0, 0, 1]))
+ print(obj.getLongestSubsequence(words=["a", "b", "c", "d"], groups=[1, 0, 1, 1]))
diff --git a/longest_unequal_adjacent_group2.c b/longest_unequal_adjacent_group2.c
new file mode 100644
index 0000000..9ccfe43
--- /dev/null
+++ b/longest_unequal_adjacent_group2.c
@@ -0,0 +1,116 @@
+// 2901. Longest Unequal Adjacent Groups Subsequence II
+#include "leetcode.h"
+
+/*
+ * you are given a string array 'words' and an array 'groups', both arrays
+ * having length 'n'. the hamming distance between two strings of equal length
+ * is the number of positions at which the corresponding characters are
+ * different. you need to select the longest subsequence from an array of
+ * indices such that for the subsequence denoted as '[i0, i1, ..., ik-1]' having
+ * length 'k', the following holds true: for adjacent indices in the subsequence
+ * their corresponding groups are unequal. 'words[i]' and 'words[i + 1]' are
+ * equal in length and the haming distance between them is 1. return a string
+ * array containing the words corresponding to the indices in order in the
+ * selected subsequence. if there are multiple, return any of them.
+ */
+
+struct pattern {
+ uint64_t pat;
+ int idx;
+};
+
+char **getWordsInLongestSubsequence(char **words, int wordsSize, int *groups,
+ int groupsSize, int *returnSize) {
+ int n = wordsSize;
+ if (!n) {
+ *returnSize = 0;
+ return NULL;
+ }
+ uint64_t *codes = (uint64_t *)malloc(n * sizeof(uint64_t));
+ for (int i = 0; i < n; ++i) {
+ uint64_t curr = 0;
+ for (int j = 0; words[i][j]; ++j)
+ curr |= (uint64_t)(words[i][j - 1] - 'a') << (5 * j);
+ codes[i] = curr;
+ }
+ int *dp = (int *)malloc(n * sizeof(int)),
+ *prev = (int *)malloc(n * sizeof(int));
+ for (int i = 0; i < n; ++i) {
+ dp[i] = 1;
+ prev[i] = -1;
+ }
+ int max_len = 1, max_idx = 0;
+ struct pattern *p[11][11] = {{0}};
+ int sizes[11][11] = {0}, caps[11][11] = {0};
+ for (int i = 0; i < n; ++i) {
+ int m = strlen(words[i]), curr_group = groups[i];
+ uint64_t curr_code = codes[i];
+ for (int j = 0; j < m; ++j) {
+ if (!caps[m][j]) {
+ caps[m][j] = 16;
+ p[m][j] = (struct pattern *)malloc(caps[m][j] * sizeof(struct pattern));
+ sizes[m][j] = 0;
+ }
+ }
+ int best = 1, bp = -1;
+ for (int j = 0; j < m; ++j) {
+ uint64_t mask = ~((uint64_t)31 << (5 * j)),
+ curr_pattern = curr_code & mask;
+ struct pattern *arr = p[m][j];
+ int curr_size = sizes[m][j];
+ for (int k = 0; k < curr_size; ++k) {
+ if (arr[k].pat == curr_pattern) {
+ int idx = arr[k].idx;
+ if (groups[idx] != curr_group && dp[idx] + 1 > best) {
+ best = dp[idx] + 1;
+ bp = idx;
+ }
+ }
+ }
+ }
+ dp[i] = best;
+ prev[i] = bp;
+ if (best > max_len) {
+ max_len = best;
+ max_idx = i;
+ }
+ for (int j = 0; j < m; ++j) {
+ uint64_t mask = ~((uint64_t)31 << (5 * j)),
+ curr_pattern = curr_code & mask;
+ if (sizes[m][j] == caps[m][j]) {
+ caps[m][j] *= 2;
+ p[m][j] = (struct pattern *)realloc(
+ p[m][j], caps[m][j] * sizeof(struct pattern));
+ }
+ p[m][j][sizes[m][j]].pat = curr_pattern;
+ p[m][j][sizes[m][j]].idx = i;
+ sizes[m][j]++;
+ }
+ }
+ char **tmp = (char **)malloc(max_len * sizeof(char *));
+ int cnt = 0;
+ for (int i = max_idx; i != 1; i = prev[i])
+ tmp[cnt++] = strdup(words[i]);
+ char **ans = (char **)malloc(cnt * sizeof(char *));
+ for (int i = 0; i < cnt; i++)
+ ans[i] = tmp[cnt - 1 - i];
+ *returnSize = cnt;
+ return ans;
+}
+
+int main() {
+ char *w1[] = {"bab", "dab", "cab"}, *w2[] = {"a", "b", "c", "d"};
+ int g1[] = {1, 2, 2}, g2[] = {1, 2, 3, 4}, rs1, rs2;
+ char **gwils1 = getWordsInLongestSubsequence((char **)w1, ARRAY_SIZE(w1), g1,
+ ARRAY_SIZE(g1), &rs1);
+ char **gwils2 = getWordsInLongestSubsequence((char **)w2, ARRAY_SIZE(w2), g2,
+ ARRAY_SIZE(g2), &rs2);
+ for (int i = 0; i < rs1; i++)
+ printf("%s ", gwils1[i]); // expect: bab cab
+ printf("\n");
+ for (int i = 0; i < rs2; i++)
+ printf("%s ", gwils2[i]); // expect: a b c d
+ printf("\n");
+ free(gwils1);
+ free(gwils2);
+}
diff --git a/longest_unequal_adjacent_group2.py b/longest_unequal_adjacent_group2.py
new file mode 100644
index 0000000..44255d1
--- /dev/null
+++ b/longest_unequal_adjacent_group2.py
@@ -0,0 +1,50 @@
+# 2901. Longest Unequal Adjacent Groups Subsequence II
+
+"""
+you are given a string array 'words' and an array 'groups', both arrays
+having length 'n'. the hamming distance between two strings of equal length
+is the number of positions at which the corresponding characters are
+different. you need to select the longest subsequence from an array of
+indices such that for the subsequence denoted as '[i0, i1, ..., ik-1]' having
+length 'k', the following holds true: for adjacent indices in the subsequence
+their corresponding groups are unequal. 'words[i]' and 'words[i + 1]' are
+equal in length and the haming distance between them is 1. return a string
+array containing the words corresponding to the indices in order in the
+selected subsequence. if there are multiple, return any of them.
+"""
+
+
+class Solution(object):
+ def getWordsInLongestSubsequence(self, words, groups):
+ """
+ :type words: List[str]
+ :type groups: List[int]
+ :rtype: List[str]
+ """
+ dp = []
+ for i, j in zip(words, groups):
+ dp.append(
+ max(
+ (
+ k
+ for a, b, k in zip(words, groups, dp)
+ if j != b and len(i) == len(a) and sum(map(ne, i, a)) < 2
+ ),
+ key=len,
+ default=[],
+ )
+ + [i]
+ )
+ return max(dp, key=len)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(
+ obj.getWordsInLongestSubsequence(words=["bab", "dab", "cab"], groups=[1, 2, 2])
+ )
+ print(
+ obj.getWordsInLongestSubsequence(
+ words=["a", "b", "c", "d"], groups=[1, 2, 3, 4]
+ )
+ )
diff --git a/max_candies_from_boxes.c b/max_candies_from_boxes.c
new file mode 100644
index 0000000..03b4b5f
--- /dev/null
+++ b/max_candies_from_boxes.c
@@ -0,0 +1,84 @@
+// 1298. Maximum Candies You Can Get from Boxes
+#include "leetcode.h"
+
+/*
+ * you have 'n' boxes labeled from 0 to 'n - 1'. you are given four arrays:
+ * 'status', 'candies', 'keys', and 'containedBoxes' where 'status[i]' is 1 if
+ * the i'th box is open and 0 if the i'th box is closed. 'candies[i]' is the
+ * number of candies in the i'th box. 'keys[i]' is a list of the labels of the
+ * boxes that you can open after opening the i'th box. 'containedBoxes[i]' is a
+ * list of the boxes you found inside the i'th box. you are given an integer
+ * array 'initialBoxes' that contains the labels of the boxes you initially
+ * have. you can take all the candies in any open box and you can use the keys
+ * in it to open new boxes and you can also use the boxes you find in it. return
+ * the maximum number of candies you can get following the rules.
+ */
+
+int dfs(int box_idx, int *status, int statusSize, int *candies, int candiesSize,
+ int **keys, int keysSize, int *keysColSize, int **containedBoxes,
+ int containedBoxesSize, int *containedBoxesColSize, bool *accessible,
+ bool *vis, bool *have_key) {
+ int cnt = 0;
+ if (vis[box_idx] == 1 || !accessible[box_idx] ||
+ (!status[box_idx] && !have_key[box_idx]))
+ return 0;
+ cnt = candies[box_idx];
+ vis[box_idx] = 1;
+ for (int i = 0; i < keysColSize[box_idx]; i++) {
+ have_key[keys[box_idx][i]] = 1;
+ cnt += dfs(keys[box_idx][i], status, statusSize, candies, candiesSize, keys,
+ keysSize, keysColSize, containedBoxes, containedBoxesSize,
+ containedBoxesColSize, accessible, vis, have_key);
+ }
+ for (int i = 0; i < containedBoxesColSize[box_idx]; i++) {
+ accessible[containedBoxes[box_idx][i]] = 1;
+ cnt += dfs(containedBoxes[box_idx][i], status, statusSize, candies,
+ candiesSize, keys, keysSize, keysColSize, containedBoxes,
+ containedBoxesSize, containedBoxesColSize, accessible, vis,
+ have_key);
+ }
+ return cnt;
+}
+
+int maxCandies(int *status, int statusSize, int *candies, int candiesSize,
+ int **keys, int keysSize, int *keysColSize, int **containedBoxes,
+ int containedBoxesSize, int *containedBoxesColSize,
+ int *initialBoxes, int initialBoxesSize) {
+ bool *accessible = (bool *)calloc(statusSize, sizeof(bool));
+ bool *vis = (bool *)calloc(statusSize, sizeof(bool));
+ bool *have_key = (bool *)calloc(statusSize, sizeof(bool));
+ int ans = 0;
+ for (int i = 0; i < initialBoxesSize; i++) {
+ accessible[initialBoxes[i]] = true;
+ ans += dfs(initialBoxes[i], status, statusSize, candies, candiesSize, keys,
+ keysSize, keysColSize, containedBoxes, containedBoxesSize,
+ containedBoxesColSize, accessible, vis, have_key);
+ }
+ free(accessible);
+ free(vis);
+ free(have_key);
+ return ans;
+}
+
+int main() {
+ int s1[] = {1, 0, 1, 0}, c1[] = {7, 5, 4, 100}, k1i[4][1] = {{}, {}, {1}, {}},
+ cb1i[4][2] = {{1, 2}, {3}, {}, {}}, ib1[] = {0};
+ int s2[] = {1, 0, 0, 0, 0, 0}, c2[] = {1, 1, 1, 1, 1, 1},
+ k2i[6][5] = {{1, 2, 3, 4, 5}, {}, {}, {}, {}, {}},
+ cb2i[6][5] = {{1, 2, 3, 4, 5}, {}, {}, {}, {}, {}}, ib2[] = {0};
+ struct two_d_arr k1, k2, cb1, cb2;
+ two_d_arr_init(&k1, ARRAY_SIZE(k1i), ARRAY_SIZE(k1i[0]), k1i);
+ two_d_arr_init(&k2, ARRAY_SIZE(k2i), ARRAY_SIZE(k2i[0]), k2i);
+ two_d_arr_init(&cb1, ARRAY_SIZE(cb1i), ARRAY_SIZE(cb1i[0]), cb1i);
+ two_d_arr_init(&cb2, ARRAY_SIZE(cb2i), ARRAY_SIZE(cb2i[0]), cb2i);
+ printf("%d\n", maxCandies(s1, ARRAY_SIZE(s1), c1, ARRAY_SIZE(c1), k1.arr,
+ k1.row_size, k1.col_size, cb1.arr, cb1.row_size,
+ cb1.col_size, ib1, ARRAY_SIZE(ib1))); // expect: 16
+ printf("%d\n", maxCandies(s2, ARRAY_SIZE(s2), c2, ARRAY_SIZE(c2), k2.arr,
+ k2.row_size, k2.col_size, cb2.arr, cb2.row_size,
+ cb2.col_size, ib2, ARRAY_SIZE(ib2))); // expect: 6
+ two_d_arr_free(&k1);
+ two_d_arr_free(&k2);
+ two_d_arr_free(&cb1);
+ two_d_arr_free(&cb2);
+}
diff --git a/max_candies_from_boxes.py b/max_candies_from_boxes.py
new file mode 100644
index 0000000..2b1d1b3
--- /dev/null
+++ b/max_candies_from_boxes.py
@@ -0,0 +1,60 @@
+# 1298. Maximum Candies You Can Get from Boxes
+
+"""
+you have 'n' boxes labeled from 0 to 'n - 1'. you are given four arrays:
+'status', 'candies', 'keys', and 'containedBoxes' where 'status[i]' is 1 if
+the i'th box is open and 0 if the i'th box is closed. 'candies[i]' is the
+number of candies in the i'th box. 'keys[i]' is a list of the labels of the
+boxes that you can open after opening the i'th box. 'containedBoxes[i]' is a
+list of the boxes you found inside the i'th box. you are given an integer
+array 'initialBoxes' that contains the labels of the boxes you initially
+have. you can take all the candies in any open box and you can use the keys
+in it to open new boxes and you can also use the boxes you find in it. return
+the maximum number of candies you can get following the rules.
+"""
+
+
+class Solution(object):
+ def maxCandies(self, status, candies, keys, containedBoxes, initialBoxes):
+ """
+ :type status: List[int]
+ :type candies: List[int]
+ :type keys: List[List[int]]
+ :type containedBoxes: List[List[int]]
+ :type initialBoxes: List[int]
+ :rtype: int
+ """
+ boxes = set(initialBoxes)
+ dfs = [i for i in boxes if status[i]]
+ for i in dfs:
+ for j in containedBoxes[i]:
+ boxes.add(j)
+ if status[j]:
+ dfs.append(j)
+ for j in keys[i]:
+ if status[j] == 0 and j in boxes:
+ dfs.append(j)
+ status[j] = 1
+ return sum(candies[i] for i in dfs)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(
+ obj.maxCandies(
+ status=[1, 0, 1, 0],
+ candies=[7, 5, 4, 100],
+ keys=[[], [], [1], []],
+ containedBoxes=[[1, 2], [3], [], []],
+ initialBoxes=[0],
+ )
+ )
+ print(
+ obj.maxCandies(
+ status=[1, 0, 0, 0, 0, 0],
+ candies=[1, 1, 1, 1, 1, 1],
+ keys=[[1, 2, 3, 4, 5], [], [], [], [], []],
+ containedBoxes=[[1, 2, 3, 4, 5], [], [], [], [], []],
+ initialBoxes=[0],
+ )
+ )
diff --git a/max_diff_between_adj_elem.c b/max_diff_between_adj_elem.c
new file mode 100644
index 0000000..a96f02c
--- /dev/null
+++ b/max_diff_between_adj_elem.c
@@ -0,0 +1,23 @@
+// 3423. Maximum Difference Between Adjacent Elements in a Circular Array
+#include "leetcode.h"
+
+/*
+ * given a circular array 'nums', find the maximum absolute difference between
+ * adjacent elements. note, in a circular array, the first and last elements are
+ * adjacent.
+ */
+
+int maxAdjacentDistance(int *nums, int numsSize) {
+ int ans = abs(nums[0] - nums[numsSize - 1]);
+ for (int i = 1; i < numsSize; i++) {
+ int curr = abs(nums[i - 1] - nums[i]);
+ ans = fmax(ans, curr);
+ }
+ return ans;
+}
+
+int main() {
+ int n1[] = {1, 2, 4}, n2[] = {-5, -10, -5};
+ printf("%d\n", maxAdjacentDistance(n1, ARRAY_SIZE(n2))); // expect: 3
+ printf("%d\n", maxAdjacentDistance(n1, ARRAY_SIZE(n2))); // expect: 5
+}
diff --git a/max_diff_between_adj_elem.py b/max_diff_between_adj_elem.py
new file mode 100644
index 0000000..4334537
--- /dev/null
+++ b/max_diff_between_adj_elem.py
@@ -0,0 +1,27 @@
+# 3423. Maximum Difference Between Adjacent Elements in a Circular Array
+
+"""
+given a circular array 'nums', find the maximum absolute difference between
+adjacent elements. note, in a circular array, the first and last elements are
+adjacent.
+"""
+
+
+class Solution(object):
+ def maxAdjacentDistance(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ n = len(nums)
+ ans = abs(nums[0] - nums[n - 1])
+ for i in range(1, n):
+ curr = abs(nums[i - 1] - nums[i])
+ ans = max(ans, curr)
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.maxAdjacentDistance(nums=[1, 2, 4]))
+ print(obj.maxAdjacentDistance(nums=[-5, -10, -5]))
diff --git a/max_diff_between_incr_elem.c b/max_diff_between_incr_elem.c
new file mode 100644
index 0000000..bf35ab0
--- /dev/null
+++ b/max_diff_between_incr_elem.c
@@ -0,0 +1,25 @@
+// 2016. Maximum Difference Between Increasing Elements
+#include "leetcode.h"
+
+/*
+ * given a 0-indexed integer array 'nums' of size 'n', find the maximum
+ * difference between 'nums[i]' and 'nums[j]' (ie. 'nums[j] - nums[i]') such
+ * that '0 <= i < j < n' and 'nums[i] < nums[j]'. return the maximum difference.
+ * if no such 'i' and 'j' exist, return -1
+ */
+
+int maximumDifference(int *nums, int numsSize) {
+ int min = nums[0], ans = -1;
+ for (int i = 1; i < numsSize; ++i) {
+ ans = fmax(ans, nums[i] - min);
+ min = fmin(min, nums[i]);
+ }
+ return ans;
+}
+
+int main() {
+ int n1[] = {7, 1, 5, 4}, n2[] = {9, 4, 3, 2}, n3[] = {1, 5, 2, 10};
+ printf("%d\n", maximumDifference(n1, ARRAY_SIZE(n1))); // expect: 4
+ printf("%d\n", maximumDifference(n2, ARRAY_SIZE(n2))); // expect: -1
+ printf("%d\n", maximumDifference(n3, ARRAY_SIZE(n3))); // expect: 9
+}
diff --git a/max_diff_between_incr_elem.py b/max_diff_between_incr_elem.py
new file mode 100644
index 0000000..d277298
--- /dev/null
+++ b/max_diff_between_incr_elem.py
@@ -0,0 +1,28 @@
+# 2016. Maximum Difference Between Increasing Elements
+
+"""
+given a 0-indexed integer array 'nums' of size 'n', find the maximum
+difference between 'nums[i]' and 'nums[j]' (ie. 'nums[j] - nums[i]') such
+that '0 <= i < j < n' and 'nums[i] < nums[j]'. return the maximum difference.
+if no such 'i' and 'j' exist, return -1
+"""
+
+
+class Solution(object):
+ def maximumDifference(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ minn, ans = nums[0], -1
+ for i in range(len(nums)):
+ ans = max(ans, nums[i] - minn)
+ minn = min(minn, nums[i])
+ return ans if ans != 0 else -1
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.maximumDifference(nums=[7, 1, 5, 4]))
+ print(obj.maximumDifference(nums=[9, 4, 3, 2]))
+ print(obj.maximumDifference(nums=[1, 5, 2, 10]))
diff --git a/max_diff_even_odd_freq1.c b/max_diff_even_odd_freq1.c
new file mode 100644
index 0000000..d51e73b
--- /dev/null
+++ b/max_diff_even_odd_freq1.c
@@ -0,0 +1,31 @@
+// 3442. Maximum Difference Between Even and Odd Frequency I
+#include "leetcode.h"
+
+/*
+ * you are given a string 's' consisting of lowercase english letters. your task
+ * is to find the minimum difference 'diff = a1 - a2' between the frequency of
+ * characters 'a1' and 'a2' in the string such that 'a1' has an odd frequency in
+ * the string, and 'a2' has an even frequency in the string. return this maximum
+ * difference.
+ */
+
+int maxDifference(char *s) {
+ int *freq = (int *)calloc(26, sizeof(int)), n = strlen(s);
+ for (int i = 0; i < n; i++)
+ freq[s[i] - 'a']++;
+ int max = INT_MIN, min = INT_MAX;
+ for (int i = 0; i < 26; i++) {
+ if (max < freq[i] && freq[i] % 2)
+ max = freq[i];
+ if (min > freq[i] && !(freq[i] % 2) && freq[i])
+ min = freq[i];
+ }
+ free(freq);
+ return max - min;
+}
+
+int main() {
+ char *s1 = "aaaaabbc", *s2 = "abcabcab";
+ printf("%d\n", maxDifference(s1)); // expect: 3
+ printf("%d\n", maxDifference(s2)); // expect: 1
+}
diff --git a/max_diff_even_odd_freq1.py b/max_diff_even_odd_freq1.py
new file mode 100644
index 0000000..b1d6ad3
--- /dev/null
+++ b/max_diff_even_odd_freq1.py
@@ -0,0 +1,33 @@
+# 3442. Maximum Difference Between Even and Odd Frequency I
+
+"""
+you are given a string 's' consisting of lowercase english letters. your task
+is to find the minimum difference 'diff = a1 - a2' between the frequency of
+characters 'a1' and 'a2' in the string such that 'a1' has an odd frequency in
+the string, and 'a2' has an even frequency in the string. return this maximum
+difference.
+"""
+
+
+class Solution(object):
+ def maxDifference(self, s):
+ """
+ :type s: str
+ :rtype: int
+ """
+ freq = [0] * 26
+ for i in s:
+ freq[ord(i) - ord("a")] += 1
+ maxi, mini = 0, len(s)
+ for i in range(26):
+ if freq[i] % 2 != 0:
+ maxi = max(maxi, freq[i])
+ if freq[i] % 2 == 0 and freq[i] > 0:
+ mini = min(mini, freq[i])
+ return maxi - mini
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.maxDifference(s="aaaaabbc"))
+ print(obj.maxDifference(s="abcabcab"))
diff --git a/max_diff_even_odd_freq2.c b/max_diff_even_odd_freq2.c
new file mode 100644
index 0000000..8d32226
--- /dev/null
+++ b/max_diff_even_odd_freq2.c
@@ -0,0 +1,120 @@
+// 3445. Maximum Difference Between Even and Odd Frequency II
+#include "leetcode.h"
+
+/*
+ * you are given a string 's' and an integer 'k'. your task is to find the
+ * maximum difference between the frequency of two characters 'freq[a], -
+ * freq[b]', in a substring 'subs' of 's' such that 'subs' has a size of at
+ * least 'k', character 'a' has an odd frequency in 'subs', character 'b' has an
+ * even frequency in 'subs'. return the maximum difference. note that 'subs' can
+ * contain more than 2 distinct characters.
+ */
+
+static int upper_bound(const int *arr, int n, int key) {
+ int low = 0, high = n;
+ while (low < high) {
+ int mid = low + ((high - low) >> 1);
+ if (arr[mid] <= key)
+ low = mid + 1;
+ else
+ high = mid;
+ }
+ return low;
+}
+
+int maxDifference(char *s, int k) {
+ int n = strlen(s);
+ if (!n || k > n)
+ return -1;
+ int (*freq)[5] = malloc(sizeof(int[5]) * n), present[5] = {0};
+ if (!freq)
+ return -1;
+ for (int i = 0; i < n; i++) {
+ int c = s[i] - '0';
+ if (!i)
+ memset(freq[i], 0, sizeof(int) * 5);
+ else
+ memcpy(freq[i], freq[i - 1], sizeof(int) * 5);
+ freq[i][c]++;
+ present[c] = 1;
+ }
+ int ans = INT_MIN;
+ for (int a = 0; a < 5; a++) {
+ if (!present[a])
+ continue;
+ for (int b = 0; b < 5; b++) {
+ if (!present[b] || a == b)
+ continue;
+ int *idx_list[4], *val_list[4], size[4];
+ for (int i = 0; i < 4; i++) {
+ idx_list[i] = (int *)malloc(sizeof(int) * n);
+ val_list[i] = (int *)malloc(sizeof(int) * n);
+ size[i] = 0;
+ }
+ int odd = 0, even = 0;
+ for (int i = 0; i < n; i++) {
+ int c = s[i] - '0';
+ if (c == a)
+ odd++;
+ else if (c == b)
+ even++;
+ if ((odd & 1) && (even & 1) == 0 && (i + 1) >= k && even > 0) {
+ int diff = odd - even;
+ if (diff > ans)
+ ans = diff;
+ }
+ int key1 = ((odd % 2 == 0) ? 1 : 0) << 1 | ((even % 2 == 0) ? 0 : 1);
+ if (size[key1] > 0) {
+ int limit = i - k;
+ if (limit >= 0) {
+ int pos = upper_bound(idx_list[key1], size[key1], limit);
+ if (pos > 0) {
+ int prev = pos - 1, l = 0, r = prev, curr_min = INT_MAX;
+ while (l <= r) {
+ int mid = (l + r) >> 1, j = idx_list[key1][mid];
+ if (freq[i][b] != freq[j][b]) {
+ int v = val_list[key1][mid];
+ if (v < curr_min)
+ curr_min = v;
+ l = mid + 1;
+ } else
+ r = mid - 1;
+ }
+ if (curr_min != INT_MAX) {
+ int cur = odd - even - curr_min;
+ if (cur > ans)
+ ans = cur;
+ }
+ }
+ }
+ }
+ int key2 = (odd % 2) << 1 | (even % 2), curr_diff = odd - even;
+ if (!size[key2]) {
+ idx_list[key2][0] = i;
+ val_list[key2][0] = curr_diff;
+ size[key2] = 1;
+ } else {
+ int prev_min = val_list[key2][size[key2] - 1];
+ int new_min = (prev_min < curr_diff) ? prev_min : curr_diff;
+ idx_list[key2][size[key2]] = i;
+ val_list[key2][size[key2]] = new_min;
+ size[key2]++;
+ }
+ }
+ for (int i = 0; i < 4; i++) {
+ free(idx_list[i]);
+ free(val_list[i]);
+ }
+ }
+ }
+
+ free(freq);
+ return (ans == INT_MIN ? -1 : ans);
+}
+
+int main() {
+ char *s1 = "12233", *s2 = "1122211", *s3 = "110";
+ printf("%d\n", maxDifference(s1, 4)); // expect: -1
+ printf("%d\n", maxDifference(s2, 3)); // expect: 1
+ printf("%d\n", maxDifference(s3, 3)); // expect: -1
+}
diff --git a/max_diff_even_odd_freq2.py b/max_diff_even_odd_freq2.py
new file mode 100644
index 0000000..a24d3d0
--- /dev/null
+++ b/max_diff_even_odd_freq2.py
@@ -0,0 +1,78 @@
+# 3445. Maximum Difference Between Even and Odd Frequency II
+
+"""
+you are given a string 's' and an integer 'k'. your task is to find the
+maximum difference between the frequency of two characters 'freq[a], -
+freq[b]', in a substring 'subs' of 's' such that 'subs' has a size of at
+least 'k', character 'a' has an odd frequency in 'subs', character 'b' has an
+even frequency in 'subs'. return the maximum difference. note that 'subs' can
+contain more than 2 distinct characters.
+"""
+
+
+class fenwick_tree:
+ inf = float("inf")
+
+ def __init__(self, n):
+ self.n = n
+ self.tree = [self.inf] * (n + 1)
+
+ def update(self, i, val):
+ pos = i + 1
+ while pos <= self.n:
+ self.tree[pos] = min(self.tree[pos], val)
+ pos += pos & -pos
+
+ def query(self, i):
+ res, pos = self.inf, i + 1
+ while pos > 0:
+ res = min(res, self.tree[pos])
+ pos -= pos & -pos
+ return res
+
+
+class Solution(object):
+ def maxDifference(self, s, k):
+ """
+ :type s: str
+ :type k: int
+ :rtype: int
+ """
+ n, ans = len(s), float("-inf")
+ for a in range(5):
+ for b in range(5):
+ if a == b:
+ continue
+ d = [0] * (n + 1)
+ pa, pb = [0] * (n + 1), [0] * (n + 1)
+ cnt_b = [0] * (n + 1)
+ for i in range(1, n + 1):
+ digit = int(s[i - 1])
+ d[i] = (
+ d[i - 1] + (1 if digit == a else 0) - (1 if digit == b else 0)
+ )
+ pa[i] = (pa[i - 1] + (1 if digit == a else 0)) & 1
+ pb[i] = (pb[i - 1] + (1 if digit == b else 0)) & 1
+ cnt_b[i] = cnt_b[i - 1] + (1 if digit == b else 0)
+ trees = [[fenwick_tree(n + 1) for _ in range(2)] for _ in range(2)]
+ for j in range(n + 1):
+ if j >= k:
+ idx = j - k
+ trees[pa[idx]][pb[idx]].update(cnt_b[idx], d[idx])
+ if j > 0:
+ need_p, need_q = (
+ 1 - pa[j],
+ pb[j],
+ )
+ if cnt_b[j] > 0:
+ best = trees[need_p][need_q].query(cnt_b[j] - 1)
+ if best != fenwick_tree.inf:
+ ans = max(ans, d[j] - best)
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.maxDifference(s="12233", k=4))
+ print(obj.maxDifference(s="1122211", k=3))
+ print(obj.maxDifference(s="110", k=3))
diff --git a/max_diff_remap_digit.c b/max_diff_remap_digit.c
new file mode 100644
index 0000000..3eff54a
--- /dev/null
+++ b/max_diff_remap_digit.c
@@ -0,0 +1,30 @@
+// 2566. Maximum Difference by Remapping a Digit
+#include "leetcode.h"
+
+/*
+ * you are given an integer 'num'. you know that bob will sneakily remap one of
+ * the 10 possible digits to another digit. return the difference between the
+ * maximum and minimum values bob can make by remapping exactly one digit in
+ * nums.
+ */
+
+int minMaxDifference(int num) {
+ int min = num, max = num;
+ for (int i = 0; i < 10; ++i) {
+ int low = 0, high = 0, mult = 1;
+ for (int j = num; j; j /= 10) {
+ bool replace = j % 10 == i;
+ low += (replace ? 0 : j % 10) * mult;
+ high += (replace ? 9 : j % 10) * mult;
+ mult *= 10;
+ }
+ min = fmin(min, low);
+ max = fmax(max, high);
+ }
+ return max - min;
+}
+
+int main() {
+ printf("%d\n", minMaxDifference(11891)); // expect: 99009
+ printf("%d\n", minMaxDifference(90)); // expect: 99
+}
diff --git a/max_diff_remap_digit.py b/max_diff_remap_digit.py
new file mode 100644
index 0000000..5d802ed
--- /dev/null
+++ b/max_diff_remap_digit.py
@@ -0,0 +1,26 @@
+# 2566. Maximum Difference by Remapping a Digit
+
+"""
+you are given an integer 'num'. you know that bob will sneakily remap one of
+the 10 possible digits to another digit. return the difference between the
+maximum and minimum values bob can make by remapping exactly one digit in
+nums.
+"""
+
+
+class Solution(object):
+ def minMaxDifference(self, num):
+ """
+ :type num: int
+ :rtype: int
+ """
+ num, i = str(num), 0
+ while num[i] == "9" and i < len(num) - 1:
+ i += 1
+ return int(num.replace(num[i], "9")) - int(num.replace(num[0], "0"))
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.minMaxDifference(num=11891))
+ print(obj.minMaxDifference(num=90))
diff --git a/max_manhattan_dist_k_change.c b/max_manhattan_dist_k_change.c
new file mode 100644
index 0000000..70e735a
--- /dev/null
+++ b/max_manhattan_dist_k_change.c
@@ -0,0 +1,39 @@
+// 3443. Maximum Manhattan Distance After K Changes
+#include "leetcode.h"
+
+/*
+ * you are given a sing 's' consisting of the characters 'N', 'S', 'E', and
+ * 'W', where 's[i]' indicates movements in an infinite grid, where each letter
+ * is a move of 1 unit in that cardinal direction. initially, you are at the
+ * origin '(0, 0)'. you can change at most 'k' characters to any of the four
+ * directions. find the maximum manhattan distance from the origin that can be
+ * achieved at any time while performing the movements in order.
+ */
+
+int maxDistance(char *s, int k) {
+ const char dir[4][2] = {{'N', 'E'}, {'N', 'W'}, {'S', 'E'}, {'S', 'W'}};
+ int ans = 0;
+ for (int i = 0; i < 4; i++) {
+ bool set[1 << (CHAR_BIT - 1)] = {0};
+ set[dir[i][0]] = set[dir[i][1]] = true;
+ int curr_dist = 0, curr_k = k;
+ for (int j = 0; s[j] != '\0'; j++) {
+ if (!set[s[j]] && !(curr_k >= 1)) {
+ curr_dist--;
+ continue;
+ }
+ if (!set[s[j]])
+ curr_k--;
+ curr_dist++;
+ if (curr_dist > ans)
+ ans = curr_dist;
+ }
+ }
+ return ans;
+}
+
+int main() {
+ char *s1 = "NWSE", *s2 = "NSWWEW";
+ printf("%d\n", maxDistance(s1, 1)); // expect: 3
+ printf("%d\n", maxDistance(s2, 3)); // expect: 6
+}
diff --git a/max_manhattan_dist_k_change.py b/max_manhattan_dist_k_change.py
new file mode 100644
index 0000000..5bb0ee2
--- /dev/null
+++ b/max_manhattan_dist_k_change.py
@@ -0,0 +1,35 @@
+# 3443. Maximum Manhattan Distance After K Changes
+
+"""
+you are given a sing 's' consisting of the characters 'N', 'S', 'E', and
+'W', where 's[i]' indicates movements in an infinite grid, where each letter
+is a move of 1 unit in that cardinal direction. initially, you are at the
+origin '(0, 0)'. you can change at most 'k' characters to any of the four
+directions. find the maximum manhattan distance from the origin that can be
+achieved at any time while performing the movements in order.
+"""
+
+
+class Solution(object):
+ def maxDistance(self, s, k):
+ """
+ :type s: str
+ :type k: int
+ :rtype: int
+ """
+ ans = 0
+ for i in [{"N", "E"}, {"N", "W"}, {"S", "E"}, {"S", "W"}]:
+ curr_dist, curr_k = 0, k
+ for j in s:
+ curr_dist += 1
+ curr_k -= j not in i
+ else:
+ curr_dist -= 1
+ ans = max(ans, curr_dist)
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.maxDistance(s="NWSE", k=1))
+ print(obj.maxDistance(s="NSWWEW", k=3))
diff --git a/max_num_tasks_assign.py b/max_num_tasks_assign.py
new file mode 100644
index 0000000..4c2fbf5
--- /dev/null
+++ b/max_num_tasks_assign.py
@@ -0,0 +1,64 @@
+# 2071. Maximum Number of Tasks You Can Assign
+from bisect import bisect_left
+
+"""
+you have 'n' tasks and 'm' workers. each task has a strength requirement
+stored in a 0-indexed integer array 'tasks', with the i'th task requiring
+'tasks[i]' strength to complete. the strength of each worker is stored in a
+0-indexed array 'workers' with the j'th worker having 'workers[j]' strength.
+each worker can only be assigned to a single task and must have a strength
+greather than or equal to the task's strength requirement. additionally, you
+have 'pills' magic pills that will increase a workers strength by 'strength'.
+you can decide which workers receive the pills, however, you may only give
+each worker at most one magical pill. given the 0-indexed integer arrays
+'tasks' and 'workers' and the integers 'pills' and 'strength', return the
+maximum number of tasks that can be completed.
+"""
+
+
+class Solution(object):
+ def maxTaskAssign(self, tasks, workers, pills, strength):
+ """
+ :type tasks: List[int]
+ :type workers: List[int]
+ :type pills: int
+ :type strength: int
+ :rtype: int
+ """
+
+ def check(k):
+ w, tries = workers[-k:], pills
+ for i in tasks[:k][::-1]:
+ idx = bisect_left(w, i)
+ if idx < len(w):
+ w.pop(idx)
+ elif tries > 0:
+ idx = bisect_left(w, i - strength)
+ if idx < len(w):
+ w.pop(idx)
+ tries -= 1
+ else:
+ return False
+ return len(w) == 0
+
+ tasks = sorted(tasks)
+ workers = sorted(workers)
+ l, r = 0, min(len(workers), len(tasks)) + 1
+ while l + 1 < r:
+ m = l + (r - l) // 2
+ if check(m):
+ l = m
+ else:
+ r = m
+ return l
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.maxTaskAssign(tasks=[3, 2, 1], workers=[0, 3, 3], pills=1, strength=1))
+ print(obj.maxTaskAssign(tasks=[5, 4], workers=[0, 0, 0], pills=1, strength=5))
+ print(
+ obj.maxTaskAssign(
+ tasks=[10, 15, 30], workers=[0, 10, 10, 10, 10], pills=3, strength=10
+ )
+ )
diff --git a/max_path_quality_graph.c b/max_path_quality_graph.c
new file mode 100644
index 0000000..9d3fc52
--- /dev/null
+++ b/max_path_quality_graph.c
@@ -0,0 +1,91 @@
+// 2065. Maximum Path Quality of a Graph
+#include "leetcode.h"
+
+/*
+ * there is an undirected graph with 'n' nodes numbered from 0 to 'n - 1'. you
+ * are given a 0-indexed integer array 'values' where 'values[i]' is the value
+ * of the i'th node. you are also given a 0-indexed 2d integer array 'edges',
+ * where each 'edges[j] = [uj, vj, timej]' indicates that there is an undirected
+ * edge between the nodes 'uj' and 'vj', and it takes 'timej' seconds to travel
+ * between the two nodes. finally, you are given an integer 'maxTime'. a valid
+ * path in the graph is any path that starts at node 0, ends at node 0, and
+ * takes at most 'maxTime' seconds to complete. you may visit the same node
+ * multiple times. the quality of a valid path is the sum of the value of the
+ * unique nodes visited in the path (each node's value is added at most once to
+ * the sum). return the maximum quality of a valid path.
+ */
+
+struct map {
+ struct map *next;
+ int adj;
+ int time;
+};
+
+void find_path(struct map **times, int *values, int size, int *vis, int *res,
+ int max, int i, int time, int max_time) {
+ if (time > max_time)
+ return;
+ if (!vis[i])
+ max += values[i];
+ if (!i)
+ *res = fmax(*res, max);
+ vis[i]++;
+ if (times[i]) {
+ struct map *curr = times[i];
+ while (curr) {
+ int j = curr->adj, new_time = time + curr->time;
+ find_path(times, values, size, vis, res, max, j, new_time, max_time);
+ curr = curr->next;
+ }
+ }
+ vis[i]--;
+}
+
+int maximalPathQuality(int *values, int valuesSize, int **edges, int edgesSize,
+ int *edgesColSize, int maxTime) {
+ if (valuesSize == 1)
+ return values[0];
+ int *ans = (int *)malloc(sizeof(int));
+ *ans = 0;
+ struct map **times = (struct map **)malloc(valuesSize * sizeof(struct map *));
+ int *vis = (int *)malloc(valuesSize * sizeof(int));
+ for (int i = 0; i < valuesSize; i++) {
+ times[i] = NULL;
+ vis[i] = 0;
+ }
+ for (int i = 0; i < edgesSize; i++) {
+ int src = edges[i][0], dst = edges[i][1], time = edges[i][2];
+ struct map *ins1 = (struct map *)malloc(sizeof(struct map));
+ ins1->adj = dst;
+ ins1->time = time;
+ ins1->next = times[src];
+ times[src] = ins1;
+ struct map *ins2 = (struct map *)malloc(sizeof(struct map));
+ ins2->adj = src;
+ ins2->time = time;
+ ins2->next = times[dst];
+ times[dst] = ins2;
+ }
+ find_path(times, values, valuesSize, vis, ans, 0, 0, 0, maxTime);
+ return *ans;
+}
+
+int main() {
+ int v1[] = {0, 32, 10, 43}, e1i[3][3] = {{0, 1, 10}, {1, 2, 15}, {0, 3, 10}};
+ int v2[] = {5, 10, 15, 20}, e2i[3][3] = {{0, 1, 10}, {1, 2, 10}, {0, 3, 10}};
+ int v3[] = {1, 2, 3, 4},
+ e3i[4][3] = {{0, 1, 10}, {1, 2, 11}, {2, 3, 12}, {1, 3, 13}};
+ struct two_d_arr e1, e2, e3;
+ two_d_arr_init(&e1, ARRAY_SIZE(e1i), ARRAY_SIZE(e1i[0]), e1i);
+ two_d_arr_init(&e2, ARRAY_SIZE(e2i), ARRAY_SIZE(e2i[0]), e2i);
+ two_d_arr_init(&e3, ARRAY_SIZE(e3i), ARRAY_SIZE(e3i[0]), e3i);
+ printf("%d\n", maximalPathQuality(v1, ARRAY_SIZE(v1), e1.arr, e1.row_size,
+ e1.col_size, 49)); // expect: 75
+ printf("%d\n", maximalPathQuality(v1, ARRAY_SIZE(v1), e1.arr, e1.row_size,
+ e1.col_size, 30)); // expect: 25
+ printf("%d\n", maximalPathQuality(v1, ARRAY_SIZE(v1), e1.arr, e1.row_size,
+ e1.col_size, 50)); // expect: 50
+ two_d_arr_free(&e1);
+ two_d_arr_free(&e2);
+ two_d_arr_free(&e3);
+}
diff --git a/max_path_quality_graph.py b/max_path_quality_graph.py
new file mode 100644
index 0000000..fcf4ee9
--- /dev/null
+++ b/max_path_quality_graph.py
@@ -0,0 +1,66 @@
+# 2065. Maximum Path Quality of a Graph
+from collections import defaultdict
+
+"""
+there is an undirected graph with 'n' nodes numbered from 0 to 'n - 1'. you
+are given a 0-indexed integer array 'values' where 'values[i]' is the value
+of the i'th node. you are also given a 0-indexed 2d integer array 'edges',
+where each 'edges[j] = [uj, vj, timej]' indicates that there is an undirected
+edge between the nodes 'uj' and 'vj', and it takes 'timej' seconds to travel
+between the two nodes. finally, you are given an integer 'maxTime'. a valid
+path in the graph is any path that starts at node 0, ends at node 0, and
+takes at most 'maxTime' seconds to complete. you may visit the same node
+multiple times. the quality of a valid path is the sum of the value of the
+unique nodes visited in the path (each node's value is added at most once to
+the sum). return the maximum quality of a valid path.
+"""
+
+
+class Solution(object):
+ def maximalPathQuality(self, values, edges, maxTime):
+ """
+ :type values: List[int]
+ :type edges: List[List[int]]
+ :type maxTime: int
+ :rtype: int
+ """
+ graph = defaultdict(list)
+ for u, v, t in edges:
+ graph[u].append((v, t))
+ graph[v].append((u, t))
+
+ def dfs(node, vis, gain, cost):
+ if node == 0:
+ self.ans = max(self.ans, gain)
+ for i, t in graph[node]:
+ if t <= cost:
+ dfs(i, vis | set([i]), gain + (i not in vis) * values[i], cost - t)
+
+ self.ans = 0
+ dfs(0, set([0]), values[0], maxTime)
+ return self.ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(
+ obj.maximalPathQuality(
+ values=[0, 32, 10, 43],
+ edges=[[0, 1, 10], [1, 2, 15], [0, 3, 10]],
+ maxTime=49,
+ )
+ )
+ print(
+ obj.maximalPathQuality(
+ values=[5, 10, 15, 20],
+ edges=[[0, 1, 10], [1, 2, 10], [0, 3, 10]],
+ maxTime=30,
+ )
+ )
+ print(
+ obj.maximalPathQuality(
+ values=[1, 2, 3, 4],
+ edges=[[0, 1, 10], [1, 2, 11], [2, 3, 12], [1, 3, 13]],
+ maxTime=50,
+ )
+ )
diff --git a/maximise_num_target_node_tree1.py b/maximise_num_target_node_tree1.py
new file mode 100644
index 0000000..d811536
--- /dev/null
+++ b/maximise_num_target_node_tree1.py
@@ -0,0 +1,64 @@
+# 3372. Maximize the Number of Target Nodes After Connecting Trees I
+
+"""
+there exists two undirected trees with 'n' and 'm' nodes with distinct labels
+in ranges '[0, n - 1]' respectively. you are given two 2d integer arrays
+'edges1' and 'edges2' of length 'n - 1' and 'm - 1' where 'edges[i] = [ai,
+bi]' indicates that there is an edge between nodes 'ai' and 'bi' in the first
+tree and 'edges2[i] = [ui, vi]' indicates that there is an edge between nodes
+'ui' and 'vi' in the second tree. you are also given an integer 'k'. return
+an array of 'n' integers 'answer' where 'answer[i]' is the maximum possible
+number of nodes target to node 'i' of the first tree if you have to connect
+one node from the first tree to another node in the second tree.
+"""
+
+
+class Solution(object):
+ def maxTargetNodes(self, edges1, edges2, k):
+ """
+ :type edges1: List[List[int]]
+ :type edges2: List[List[int]]
+ :type k: int
+ :rtype: List[int]
+ """
+ n, m, x = len(edges1) + 1, len(edges2) + 1, 0
+ if k == 0:
+ return [1] * n
+
+ def dfs(node, level, parent, cnt=1):
+ if level < k:
+ for i in graph[node]:
+ if i == parent:
+ continue
+ cnt += dfs(i, level + 1, node)
+ return cnt
+
+ graph = [[] for _ in range(m)]
+ for u, v in edges2:
+ graph[u].append(v)
+ graph[v].append(u)
+ for i in range(m):
+ x = max(x, dfs(i, 1, -1))
+ graph = [[] for _ in range(n)]
+ for u, v in edges1:
+ graph[u].append(v)
+ graph[v].append(u)
+ return [dfs(i, 0, -1) + x for i in range(n)]
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(
+ obj.maxTargetNodes(
+ edges1=[[0, 1], [0, 2], [2, 3], [2, 4]],
+ edges2=[[0, 1], [0, 2], [0, 3], [2, 7], [1, 4], [4, 5], [4, 6]],
+ k=2,
+ )
+ )
+ print(
+ obj.maxTargetNodes(
+ edges1=[[0, 1], [0, 2], [0, 3], [0, 4]],
+ edges2=[[0, 1], [1, 2], [2, 3]],
+ k=1,
+ )
+ )
diff --git a/maximise_num_target_node_tree2.c b/maximise_num_target_node_tree2.c
new file mode 100644
index 0000000..f00d00e
--- /dev/null
+++ b/maximise_num_target_node_tree2.c
@@ -0,0 +1,139 @@
+// 3373. Maximize the Number of Target Nodes After Connecting Trees II
+#include "leetcode.h"
+
+/*
+ * there exists two undirect trees with 'n' and 'm' nodes, labeled from '[0, n -
+ * 1]' andc '[0, m - 1]' respectively. you are given two 2d integer arrays
+ * 'edges1' and 'edges2' of lengths 'n - 1' and 'm - 1' respectively. node 'u'
+ * is target to node 'v' if the number of edges on the path from 'u' to 'v' is
+ * even. note that a node is always target to itself. return an array of
+ * integers where 'ans[i]' is the maximum possible number of nodes that are
+ * target to node 'i' of the first tree if you had to connect one node from the
+ * first tree to another node in the second tree. note that queries are
+ * independent from each other. that is, for every query, you will remove the
+ * added edge before proceeding to the next query.
+ */
+
+int *maxTargetNodes(int **edges1, int edges1Size, int *edges1ColSize,
+ int **edges2, int edges2Size, int *edges2ColSize,
+ int *returnSize) {
+ int n = edges1Size + 1, m = edges2Size + 1;
+ *returnSize = n;
+ int *ans = (int *)malloc(n * sizeof(int));
+ int *g1deg = (int *)calloc(n, sizeof(int));
+ for (int i = 0; i < edges1Size; i++) {
+ int u = edges1[i][0], v = edges1[i][1];
+ g1deg[u]++;
+ g1deg[v]++;
+ }
+ int **g1adj = (int **)malloc(n * sizeof(int *));
+ for (int i = 0; i < n; i++)
+ g1adj[i] = (int *)malloc(g1deg[i] * sizeof(int));
+ int *tmpd1 = (int *)calloc(n, sizeof(int));
+ for (int i = 0; i < edges1Size; i++) {
+ int u = edges1[i][0], v = edges1[i][1];
+ g1adj[u][tmpd1[u]++] = v;
+ g1adj[v][tmpd1[v]++] = u;
+ }
+ free(tmpd1);
+ int *c1 = (int *)malloc(n * sizeof(int));
+ for (int i = 0; i < n; i++)
+ c1[i] = -1;
+ int *q1 = (int *)malloc(n * sizeof(int));
+ int front1 = 0, rear1 = 0, cnt10 = 0, cnt11 = 0;
+ c1[0] = 0;
+ cnt10++;
+ q1[rear1++] = 0;
+ while (front1 < rear1) {
+ int u = q1[front1++];
+ for (int i = 0; i < g1deg[u]; i++) {
+ int v = g1adj[u][i];
+ if (c1[v] == -1) {
+ c1[v] = c1[u] ^ 1;
+ if (!c1[v])
+ cnt10++;
+ else
+ cnt11++;
+ q1[rear1++] = v;
+ }
+ }
+ }
+ for (int i = 0; i < n; i++)
+ free(g1adj[i]);
+ free(g1adj);
+ free(g1deg);
+ free(q1);
+
+ int *g2deg = (int *)calloc(m, sizeof(int));
+ for (int i = 0; i < edges2Size; i++) {
+ int u = edges2[i][0], v = edges2[i][1];
+ g2deg[u]++;
+ g2deg[v]++;
+ }
+ int **g2adj = (int **)malloc(m * sizeof(int *));
+ for (int i = 0; i < m; i++)
+ g2adj[i] = (int *)malloc(g2deg[i] * sizeof(int));
+ int *tmpd2 = (int *)calloc(m, sizeof(int));
+ for (int i = 0; i < edges2Size; i++) {
+ int u = edges2[i][0], v = edges2[i][1];
+ g2adj[u][tmpd2[u]++] = v;
+ g2adj[v][tmpd2[v]++] = u;
+ }
+ free(tmpd2);
+ int *v2 = (int *)malloc(m * sizeof(int));
+ for (int i = 0; i < m; i++)
+ v2[i] = -1;
+ int *q2 = (int *)malloc(m * sizeof(int));
+ int front2 = 0, rear2 = 0, cnt20 = 0, cnt21 = 0;
+ v2[0] = 0;
+ cnt20++;
+ q2[rear2++] = 0;
+ while (front2 < rear2) {
+ int u = q2[front2++];
+ for (int i = 0; i < g2deg[u]; i++) {
+ int v = g2adj[u][i];
+ if (v2[v] == -1) {
+ v2[v] = v2[u] ^ 1;
+ if (!v2[v])
+ cnt20++;
+ else
+ cnt21++;
+ q2[rear2++] = v;
+ }
+ }
+ }
+ int m2 = cnt20 > cnt21 ? cnt20 : cnt21;
+ for (int i = 0; i < n; i++)
+ ans[i] = (!c1[i] ? cnt10 : cnt11) + m2;
+ free(c1);
+ return ans;
+}
+
+int main() {
+ int e11i[4][2] = {{0, 1}, {0, 2}, {2, 3}, {2, 4}},
+ e21i[7][2] = {{0, 1}, {0, 2}, {0, 3}, {2, 7}, {1, 4}, {4, 5}, {4, 6}},
+ rs1;
+ int e12i[4][2] = {{0, 1}, {0, 2}, {0, 3}, {0, 4}},
+ e22i[3][2] = {{0, 1}, {1, 2}, {2, 3}}, rs2;
+ struct two_d_arr e11, e21, e12, e22;
+ two_d_arr_init(&e11, ARRAY_SIZE(e11i), ARRAY_SIZE(e11i[0]), e11i);
+ two_d_arr_init(&e21, ARRAY_SIZE(e21i), ARRAY_SIZE(e21i[0]), e21i);
+ two_d_arr_init(&e12, ARRAY_SIZE(e12i), ARRAY_SIZE(e12i[0]), e12i);
+ two_d_arr_init(&e22, ARRAY_SIZE(e22i), ARRAY_SIZE(e22i[0]), e22i);
+ int *mtn1 = maxTargetNodes(e11.arr, e11.row_size, e11.col_size, e21.arr,
+ e21.row_size, e21.col_size, &rs1);
+ int *mtn2 = maxTargetNodes(e12.arr, e12.row_size, e12.col_size, e22.arr,
+ e22.row_size, e22.col_size, &rs2);
+ for (int i = 0; i < rs1; i++)
+ printf("%d ", mtn1[i]); // expect: 8 7 7 8 8
+ printf("\n");
+ for (int i = 0; i < rs2; i++)
+ printf("%d ", mtn2[i]); // expect: 3 6 6 6 6
+ printf("\n");
+ free(mtn1);
+ free(mtn2);
+ two_d_arr_free(&e11);
+ two_d_arr_free(&e21);
+ two_d_arr_free(&e12);
+ two_d_arr_free(&e22);
+}
diff --git a/maximise_num_target_node_tree2.py b/maximise_num_target_node_tree2.py
new file mode 100644
index 0000000..264c1ea
--- /dev/null
+++ b/maximise_num_target_node_tree2.py
@@ -0,0 +1,63 @@
+# 3373. Maximize the Number of Target Nodes After Connecting Trees II
+from collections import deque
+
+"""
+there exists two undirect trees with 'n' and 'm' nodes, labeled from '[0, n -
+1]' andc '[0, m - 1]' respectively. you are given two 2d integer arrays
+'edges1' and 'edges2' of lengths 'n - 1' and 'm - 1' respectively. node 'u'
+is target to node 'v' if the number of edges on the path from 'u' to 'v' is
+even. note that a node is always target to itself. return an array of
+integers where 'ans[i]' is the maximum possible number of nodes that are
+target to node 'i' of the first tree if you had to connect one node from the
+first tree to another node in the second tree. note that queries are
+independent from each other. that is, for every query, you will remove the
+added edge before proceeding to the next query.
+"""
+
+
+class Solution(object):
+ def maxTargetNodes(self, edges1, edges2):
+ """
+ :type edges1: List[List[int]]
+ :type edges2: List[List[int]]
+ :rtype: List[int]
+ """
+
+ def find_even(edges, n):
+ graph = [[] for _ in range(n)]
+ queue = deque([(0, -1, True)])
+ evens = [False] * n
+
+ for u, v in edges:
+ graph[u].append(v)
+ graph[v].append(u)
+
+ while queue:
+ node, parent, curr = queue.popleft()
+ evens[node] = curr
+ for child in graph[node]:
+ if child == parent:
+ continue
+ queue.append((child, node, not curr))
+ return evens
+
+ n, m = len(edges1) + 1, len(edges2) + 1
+ e1, e2 = find_even(edges1, n), find_even(edges2, m)
+ s1, s2 = sum(e1), sum(e2)
+ x = max(s2, m - s2)
+ return [x + (s1 if even else n - s1) for even in e1]
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(
+ obj.maxTargetNodes(
+ edges1=[[0, 1], [0, 2], [2, 3], [2, 4]],
+ edges2=[[0, 1], [0, 2], [0, 3], [2, 7], [1, 4], [4, 5], [4, 6]],
+ )
+ )
+ print(
+ obj.maxTargetNodes(
+ edges1=[[0, 1], [0, 2], [0, 3], [0, 4]], edges2=[[0, 1], [1, 2], [2, 3]]
+ )
+ )
diff --git a/min_del_make_str_special.c b/min_del_make_str_special.c
new file mode 100644
index 0000000..cdac8f0
--- /dev/null
+++ b/min_del_make_str_special.c
@@ -0,0 +1,30 @@
+// 3085. Minimum Deletions to Make String K-Special
+#include "leetcode.h"
+
+/*
+ * you are given a string 'word' and an integer 'k'. we consider 'word' to be
+ * k-special if '|freq(word[i]) - freq(word[j])| <= k' for all indices 'i' and
+ * 'j' in the string. here, 'freq(x)' denotes the frequency of the character 'x'
+ * in the 'word'. and '|y|' denotes the absolute value of 'y'. return the
+ * minimum number of characters you need to delete to make 'word' k-special.
+ */
+
+int minimumDeletions(char *word, int k) {
+ int freq[26] = {0}, n = strlen(word), ans = INT_MAX;
+ for (int i = 0; i < n; i++)
+ freq[word[i] - 'a']++;
+ for (int i = 0; i < 26; i++) {
+ int curr = 0;
+ for (int j = 0; j < 26; j++)
+ curr += (freq[j] < freq[i]) ? freq[j] : fmax(0, freq[j] - (freq[i] + k));
+ ans = fmin(ans, curr);
+ }
+ return ans;
+}
+
+int main() {
+ char *w1 = "aabcaba", *w2 = "dabdcbdcdcd", *w3 = "aaabaaa";
+ printf("%d\n", minimumDeletions(w1, 0)); // expect: 3
+ printf("%d\n", minimumDeletions(w2, 2)); // expect: 2
+ printf("%d\n", minimumDeletions(w3, 2)); // expect: 1
+}
diff --git a/min_del_make_str_special.py b/min_del_make_str_special.py
new file mode 100644
index 0000000..32c66e0
--- /dev/null
+++ b/min_del_make_str_special.py
@@ -0,0 +1,33 @@
+# 3085. Minimum Deletions to Make String K-Special
+from collections import Counter
+
+"""
+you are given a string 'word' and an integer 'k'. we consider 'word' to be
+k-special if '|freq(word[i]) - freq(word[j])| <= k' for all indices 'i' and
+'j' in the string. here, 'freq(x)' denotes the frequency of the character 'x'
+in the 'word'. and '|y|' denotes the absolute value of 'y'. return the
+minimum number of characters you need to delete to make 'word' k-special.
+"""
+
+
+class Solution(object):
+ def minimumDeletions(self, word, k):
+ """
+ :type word: str
+ :type k: int
+ :rtype: int
+ """
+ freq, ans = Counter(word).values(), float("inf")
+ for i in freq:
+ curr = 0
+ for j in freq:
+ curr += j if j < i else max(0, j - (i + k))
+ ans = min(ans, curr)
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.minimumDeletions(word="aabcaba", k=0))
+ print(obj.minimumDeletions(word="dabdcbdcdcd", k=2))
+ print(obj.minimumDeletions(word="aaabaaa", k=2))
diff --git a/min_domino_rotation_eq_row.c b/min_domino_rotation_eq_row.c
new file mode 100644
index 0000000..9a214cb
--- /dev/null
+++ b/min_domino_rotation_eq_row.c
@@ -0,0 +1,40 @@
+// 1007. Minimum Domino Rotations For Equal Row
+#include "leetcode.h"
+
+/*
+ * in a row of dominoes, 'tops[i]' and 'bottoms[i]' represents the top and
+ * bottom halves of the i'th domino. we may rotate the i'th domino so that
+ * 'tops[i]' and 'bottoms[i]' swap values. return the minimum number of
+ * rotations so that all values in 'tops' are the same, or all values in
+ * 'bottoms' are the same. if it cannot be done, return -1.
+ */
+
+int minDominoRotations(int *tops, int topsSize, int *bottoms, int bottomsSize) {
+ int mask = 0x7E, num = -1, a = 0, b = 0;
+ for (int i = 0; i < topsSize; i++) {
+ mask &= ((1 << tops[i]) | (1 << bottoms[i]));
+ if (!mask)
+ return -1;
+ }
+ while (mask) {
+ num++;
+ mask >>= 1;
+ }
+ for (int i = 0; i < topsSize; i++) {
+ if (tops[i] == num)
+ a++;
+ if (bottoms[i] == num)
+ b++;
+ }
+ int max = a > b ? a : b;
+ return topsSize - max;
+}
+
+int main() {
+ int t1[] = {2, 1, 2, 4, 2, 2}, b1[] = {5, 2, 6, 2, 3, 2};
+ int t2[] = {3, 5, 1, 2, 3}, b2[] = {3, 6, 3, 3, 4};
+ printf("%d\n", minDominoRotations(t1, ARRAY_SIZE(t1), b1,
+ ARRAY_SIZE(b1))); // expect: 2
+ printf("%d\n", minDominoRotations(t2, ARRAY_SIZE(t2), b2,
+ ARRAY_SIZE(b2))); // expect: -1
+}
diff --git a/min_domino_rotation_eq_row.py b/min_domino_rotation_eq_row.py
new file mode 100644
index 0000000..03766f4
--- /dev/null
+++ b/min_domino_rotation_eq_row.py
@@ -0,0 +1,30 @@
+# 1007. Minimum Domino Rotations For Equal Row
+from functools import reduce
+
+"""
+in a row of dominoes, 'tops[i]' and 'bottoms[i]' represents the top and
+bottom halves of the i'th domino. we may rotate the i'th domino so that
+'tops[i]' and 'bottoms[i]' swap values. return the minimum number of
+rotations so that all values in 'tops' are the same, or all values in
+'bottoms' are the same. if it cannot be done, return -1.
+"""
+
+
+class Solution(object):
+ def minDominoRotations(self, tops, bottoms):
+ """
+ :type tops: List[int]
+ :type bottoms: List[int]
+ :rtype: int
+ """
+ s = reduce(set.__and__, (set(i) for i in zip(tops, bottoms)))
+ if not s:
+ return -1
+ x = s.pop()
+ return min(len(tops) - tops.count(x), len(bottoms) - bottoms.count(x))
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.minDominoRotations(tops=[2, 1, 2, 4, 2, 2], bottoms=[5, 2, 6, 2, 3, 2]))
+ print(obj.minDominoRotations(tops=[3, 5, 1, 2, 3], bottoms=[3, 6, 3, 3, 4]))
diff --git a/min_equal_sum_two_arr.c b/min_equal_sum_two_arr.c
new file mode 100644
index 0000000..0814682
--- /dev/null
+++ b/min_equal_sum_two_arr.c
@@ -0,0 +1,35 @@
+// 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros
+#include "leetcode.h"
+
+/*
+ * you are given two arrays 'nums1' and 'nums2' consisting of positive integers.
+ * you have to replace all the 0's in both arrays with strictly positive
+ * integers such that the sum of elements of both arrays becomes equal. return
+ * the minimum equal sum you can obtain, or -1 if it is impossible.
+ */
+
+long long minSum(int *nums1, int nums1Size, int *nums2, int nums2Size) {
+ long long sum1 = 0, sum2 = 0, zero1 = 0, zero2 = 0;
+ for (int i = 0; i < nums1Size; i++) {
+ zero1 += !nums1[i];
+ sum1 += fmax(nums1[i], 1);
+ }
+ for (int i = 0; i < nums2Size; i++) {
+ zero2 += !nums2[i];
+ sum2 += fmax(nums2[i], 1);
+ }
+ if (sum1 < sum2 && !zero1)
+ return -1;
+ if (sum1 > sum2 && !zero2)
+ return -1;
+ return fmax(sum1, sum2);
+}
+
+int main() {
+ int n11[] = {3, 2, 0, 1, 0}, n21[] = {6, 5, 0};
+ int n12[] = {2, 0, 2, 0}, n22[] = {1, 4};
+ printf("%lld\n",
+ minSum(n11, ARRAY_SIZE(n11), n21, ARRAY_SIZE(n21))); // expect: 12
+ printf("%lld\n",
+ minSum(n12, ARRAY_SIZE(n12), n22, ARRAY_SIZE(n22))); // expect: -1
+}
diff --git a/min_equal_sum_two_arr.py b/min_equal_sum_two_arr.py
new file mode 100644
index 0000000..a552b0e
--- /dev/null
+++ b/min_equal_sum_two_arr.py
@@ -0,0 +1,30 @@
+# 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros
+
+"""
+you are given two arrays 'nums1' and 'nums2' consisting of positive integers.
+you have to replace all the 0's in both arrays with strictly positive
+integers such that the sum of elements of both arrays becomes equal. return
+the minimum equal sum you can obtain, or -1 if it is impossible.
+"""
+
+
+class Solution(object):
+ def minSum(self, nums1, nums2):
+ """
+ :type nums1: List[int]
+ :type nums2: List[int]
+ :rtype: int
+ """
+ sum1 = sum(max(i, 1) for i in nums1)
+ sum2 = sum(max(i, 1) for i in nums2)
+ if sum1 < sum2 and nums1.count(0) == 0:
+ return -1
+ if sum1 > sum2 and nums2.count(0) == 0:
+ return -1
+ return max(sum1, sum2)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.minSum(nums1=[3, 2, 0, 1, 0], nums2=[6, 5, 0]))
+ print(obj.minSum(nums1=[2, 0, 2, 0], nums2=[1, 4]))
diff --git a/min_max_diff_pair.c b/min_max_diff_pair.c
index 6172bc7..7577e3b 100644
--- a/min_max_diff_pair.c
+++ b/min_max_diff_pair.c
@@ -1,6 +1,5 @@
// 2616. Minimize the Maximum Difference of Pairs
-#include <stdio.h>
-#include <stdlib.h>
+#include "leetcode.h"
/*
* given a 0-indexed integer array 'nums' and an integer 'p'. find 'p' pairs of
@@ -14,13 +13,12 @@
int cmp(const void *a, const void *b) { return *(int *)a - *(int *)b; }
-int minimizeMax(int *nums, int nums_size, int p) {
- qsort(nums, nums_size, sizeof(int), cmp);
- int i, j, left = 0, right = nums[nums_size - 1] - nums[0];
+int minimizeMax(int *nums, int numsSize, int p) {
+ qsort(nums, numsSize, sizeof(int), cmp);
+ int i, j, left = 0, right = nums[numsSize - 1] - nums[0];
while (left < right) {
- int mid = (left + right) / 2;
- int cnt = 0;
- for (int i = 0; i + 1 < nums_size; ++i)
+ int mid = (left + right) / 2, cnt = 0;
+ for (int i = 0; i + 1 < numsSize; ++i)
if (mid >= nums[i + 1] - nums[i])
++cnt, ++i;
if (cnt >= p)
@@ -33,6 +31,6 @@ int minimizeMax(int *nums, int nums_size, int p) {
int main() {
int n1[] = {10, 1, 2, 7, 1, 3}, n2[] = {4, 2, 1, 2};
- printf("%d\n", minimizeMax(n1, 6, 2)); // expect: 1
- printf("%d\n", minimizeMax(n2, 4, 1)); // expect: 0
+ printf("%d\n", minimizeMax(n1, ARRAY_SIZE(n1), 2)); // expect: 1
+ printf("%d\n", minimizeMax(n2, ARRAY_SIZE(n2), 1)); // expect: 0
}
diff --git a/min_max_diff_pair.py b/min_max_diff_pair.py
new file mode 100644
index 0000000..8c5478d
--- /dev/null
+++ b/min_max_diff_pair.py
@@ -0,0 +1,42 @@
+# 2616. Minimize the Maximum Difference of Pairs
+
+"""
+given a 0-indexed integer array 'nums' and an integer 'p'. find 'p' pairs of
+indices of 'nums' such that the maximum difference amongst all the pairs is
+minimised. also, ensure no index appears more than once amongst that 'p'
+pairs. note that for a pair of elements at the index 'i' and 'j'. the
+difference of this pair is '|nums[i] - nums[j]|', where '|x|' represents the
+absolute value of 'x'. return the minimum maximum difference among all 'p'
+pairs. we define the maximum of an empty set to be zero.
+"""
+
+
+class Solution(object):
+ def minimizeMax(self, nums, p):
+ """
+ :type nums: List[int]
+ :type p: int
+ :rtype: int
+ """
+ nums.sort()
+ n = len(nums)
+ left, right = 0, nums[-1] - nums[0]
+ while left < right:
+ mid = (left + right) // 2
+ i, j = 1, 0
+ while i < n:
+ if nums[i] - nums[i - 1] <= mid:
+ i += 1
+ j += 1
+ i += 1
+ if j >= p:
+ right = mid
+ else:
+ left = mid + 1
+ return left
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.minimizeMax(nums=[10, 1, 2, 7, 1, 3], p=2))
+ print(obj.minimizeMax(nums=[4, 2, 1, 2], p=1))
diff --git a/min_ops_make_int_zero.c b/min_ops_make_int_zero.c
new file mode 100644
index 0000000..95d7255
--- /dev/null
+++ b/min_ops_make_int_zero.c
@@ -0,0 +1,36 @@
+// 2749. Minimum Operations to Make the Integer Zero
+#include "leetcode.h"
+
+/*
+ * you are given two integers 'nums1' and 'nums2'. in one operation you can
+ * choose integer 'i' in the range '[0, 60]' and subtract '2^i + num2' from
+ * 'num1'. return the integer denoting the minimum number of operations needed
+ * to make 'nums1' equal to 0. if it is impossible to make 'nums1' equal to 0,
+ * return -1.
+ */
+
+int bit_cnt(long long num) {
+ int cnt = 0;
+ while (num > 0) {
+ cnt += num & 1;
+ num >>= 1;
+ }
+ return cnt;
+}
+
+int makeTheIntegerZero(int num1, int num2) {
+ if (num1 < num2)
+ return -1;
+ for (int i = 0; i <= 100; i++) {
+ long long diff = num1 - 1LL * num2 * i;
+ int bits = bit_cnt(diff);
+ if (bits <= i && i <= diff)
+ return i;
+ }
+ return -1;
+}
+
+int main() {
+ printf("%d\n", makeTheIntegerZero(3, -2)); // expect: 3
+ printf("%d\n", makeTheIntegerZero(5, 7)); // expect: -1
+}
diff --git a/min_ops_make_int_zero.py b/min_ops_make_int_zero.py
new file mode 100644
index 0000000..096921a
--- /dev/null
+++ b/min_ops_make_int_zero.py
@@ -0,0 +1,39 @@
+# 2749. Minimum Operations to Make the Integer Zero
+
+"""
+you are given two integers 'nums1' and 'nums2'. in one operation you can
+choose integer 'i' in the range '[0, 60]' and subtract '2^i + num2' from
+'num1'. return the integer denoting the minimum number of operations needed
+to make 'nums1' equal to 0. if it is impossible to make 'nums1' equal to 0,
+return -1.
+"""
+
+
+class Solution(object):
+ def bit_cnt(self, num):
+ cnt = 0
+ while num > 0:
+ cnt += num & 1
+ num >>= 1
+ return cnt
+
+ def makeTheIntegerZero(self, num1, num2):
+ """
+ :type num1: int
+ :type num2: int
+ :rtype: int
+ """
+ if num1 < num2:
+ return -1
+ for i in range(101):
+ diff = num1 - 1 * num2 * i
+ bits = self.bit_cnt(diff)
+ if bits <= i and i <= diff:
+ return i
+ return -1
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.makeTheIntegerZero(num1=3, num2=-2))
+ print(obj.makeTheIntegerZero(num1=5, num2=7))
diff --git a/num_equivalent_domino_pair.c b/num_equivalent_domino_pair.c
new file mode 100644
index 0000000..eb9e3d6
--- /dev/null
+++ b/num_equivalent_domino_pair.c
@@ -0,0 +1,35 @@
+// 1128. Number of Equivalent Domino Pairs
+#include "leetcode.h"
+
+/*
+ * given a list of 'dominoes', 'dominoes[i] = [a, b]' is equivalent to
+ * 'dominoes[j] = [c, d]' if and only if either 'a == c' and 'b == d' or 'a ==
+ * d' and 'b == c'. return the number of pairs '(i, j)' for which '0 <= i < j <
+ * dominoes.length' and 'dominoes[i]' is equivalent to 'dominoes[j]'.
+ */
+
+int numEquivDominoPairs(int **dominoes, int dominoesSize,
+ int *dominoesColSize) {
+ int map[100] = {0}, cnt = 0;
+ for (int i = 0; i < dominoesSize; ++i) {
+ int u = dominoes[i][0], v = dominoes[i][1];
+ int num = u > v ? v * 10 + u : u * 10 + v;
+ cnt += map[num];
+ map[num]++;
+ }
+ return cnt;
+}
+
+int main() {
+ int d1i[4][2] = {{1, 2}, {2, 1}, {3, 4}, {5, 6}};
+ int d2i[5][2] = {{1, 2}, {1, 2}, {1, 1}, {1, 2}, {2, 2}};
+ struct two_d_arr d1, d2;
+ two_d_arr_init(&d1, ARRAY_SIZE(d1i), ARRAY_SIZE(d1i[0]), d1i);
+ two_d_arr_init(&d2, ARRAY_SIZE(d2i), ARRAY_SIZE(d2i[0]), d2i);
+ printf("%d\n",
+ numEquivDominoPairs(d1.arr, d1.row_size, d1.col_size)); // expect: 1
+ printf("%d\n",
+ numEquivDominoPairs(d2.arr, d2.row_size, d2.col_size)); // expect: 3
+ two_d_arr_free(&d1);
+ two_d_arr_free(&d2);
+}
diff --git a/num_equivalent_domino_pair.py b/num_equivalent_domino_pair.py
new file mode 100644
index 0000000..6514349
--- /dev/null
+++ b/num_equivalent_domino_pair.py
@@ -0,0 +1,27 @@
+# 1128. Number of Equivalent Domino Pairs
+from collections import Counter
+
+"""
+given a list of 'dominoes', 'dominoes[i] = [a, b]' is equivalent to
+'dominoes[j] = [c, d]' if and only if either 'a == c' and 'b == d' or 'a ==
+d' and 'b == c'. return the number of pairs '(i, j)' for which '0 <= i < j <
+dominoes.length' and 'dominoes[i]' is equivalent to 'dominoes[j]'.
+"""
+
+
+class Solution(object):
+ def numEquivDominoPairs(self, dominoes):
+ """
+ :type dominoes: List[List[int]]
+ :rtype: int
+ """
+ return sum(
+ v * (v - 1) / 2
+ for v in Counter(tuple(sorted(u)) for u in dominoes).values()
+ )
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.numEquivDominoPairs(dominoes=[[1, 2], [2, 1], [3, 4], [5, 6]]))
+ print(obj.numEquivDominoPairs(dominoes=[[1, 2], [1, 2], [1, 1], [1, 2], [2, 2]]))
diff --git a/num_subseq_satisfy.c b/num_subseq_satisfy.c
index d7570d0..a007b28 100644
--- a/num_subseq_satisfy.c
+++ b/num_subseq_satisfy.c
@@ -1,6 +1,5 @@
// 1498. Number of Subsequences That Satisfy the Given Sum Condition
-#include <stdio.h>
-#include <stdlib.h>
+#include "leetcode.h"
/*
* given an array of integers 'nums' and an integer 'target'
@@ -9,47 +8,32 @@
* less or equal to 'target'. return modulo 10^9+7
*/
-#define MOD 1000000007
-
int cmp(const void *a, const void *b) { return *(int *)a - *(int *)b; }
-long long _pow(long long a, int b) {
- a %= MOD;
- if (!b)
- return 1;
- if (b)
- return a;
- if (b % 2)
- return a * _pow(a, b - 1) % MOD;
- return _pow(a * a, b / 2) % MOD;
-}
-
-int numSubseq(int *nums, int nums_size, int target) {
- int n = nums_size;
- qsort(nums, n, sizeof(int), cmp);
- long long ans;
- int j = n - 1;
- for (int i = 0; i < n; i++) {
- if (nums[i] * 2 > target)
- break;
- int rem = target - nums[i];
- while (i < j) {
- if (nums[j] > rem)
- j--;
- else
- break;
+int numSubseq(int *nums, int numsSize, int target) {
+ qsort(nums, numsSize, sizeof(int), cmp);
+ int ans = 0, l = 0, r = numsSize - 1, mod = 1e9 + 7;
+ int *pows = (int *)malloc(numsSize * sizeof(int));
+ pows[0] = 1;
+ for (int i = 1; i < numsSize; ++i)
+ pows[i] = (pows[i - 1] << 1) % mod;
+ while (l <= r) {
+ if (nums[l] + nums[r] > target) {
+ --r;
+ continue;
}
- ans += _pow(2, j - i);
- ans %= MOD;
+ ans = (ans + pows[r - l]) % mod;
+ ++l;
}
+ free(pows);
return ans;
}
int main() {
- int n1[] = {3, 5, 6, 7}, ns1 = 4, t1 = 9;
- int n2[] = {3, 3, 6, 8}, ns2 = 4, t2 = 10;
- int n3[] = {2, 3, 3, 4, 6, 7}, ns3 = 6, t3 = 12;
- printf("%d\n", numSubseq(n1, ns1, t1)); // expect: 4
- printf("%d\n", numSubseq(n2, ns2, t2)); // expect: 6
- printf("%d\n", numSubseq(n3, ns3, t3)); // expect: 61
+ int n1[] = {3, 5, 6, 7};
+ int n2[] = {3, 3, 6, 8};
+ int n3[] = {2, 3, 3, 4, 6, 7};
+ printf("%d\n", numSubseq(n1, ARRAY_SIZE(n1), 9)); // expect: 4
+ printf("%d\n", numSubseq(n2, ARRAY_SIZE(n2), 10)); // expect: 6
+ printf("%d\n", numSubseq(n3, ARRAY_SIZE(n3), 12)); // expect: 61
}
diff --git a/num_subseq_satisfy.py b/num_subseq_satisfy.py
new file mode 100644
index 0000000..2f3889c
--- /dev/null
+++ b/num_subseq_satisfy.py
@@ -0,0 +1,36 @@
+# 1498. Number of Subsequences That Satisfy the Given Sum Condition
+
+"""
+given an array of integers 'nums' and an integer 'target'
+return the numbe of non-empty subsequences of 'nums' such
+that the sum of the minimum and maximum element on it is
+less or equal to 'target'. return modulo 10^9+7
+"""
+
+
+class Solution(object):
+ def numSubseq(self, nums, target):
+ """
+ :type nums: List[int]
+ :type target: int
+ :rtype: int
+ """
+ pows, mod = [1], 10**9 + 7
+ nums.sort()
+ for i in range(1, len(nums)):
+ pows.append((pows[-1] << 1) % mod)
+ ans, l, r = 0, 0, len(nums) - 1
+ while l <= r:
+ if nums[l] + nums[r] > target:
+ r -= 1
+ continue
+ ans = (ans + pows[r - l]) % mod
+ l += 1
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.numSubseq(nums=[3, 5, 6, 7], target=9))
+ print(obj.numSubseq(nums=[3, 3, 6, 8], target=10))
+ print(obj.numSubseq(nums=[2, 3, 3, 4, 6, 7], target=12))
diff --git a/other/01_matrix.cpp b/other/01_matrix.cpp
deleted file mode 100644
index f6d9c2d..0000000
--- a/other/01_matrix.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<vector<int>> updateMatrix(vector<vector<int>> &mat) {
- int m = mat.size(), n = mat[0].size();
- vector<vector<int>> ans(m, vector<int>(n, INT_MAX));
- queue<pair<int, int>> qp;
- for (int i = 0; i < m; i++) {
- for (int j = 0; j < n; j++) {
- if (mat[i][j] == 0) {
- ans[i][j] = 0;
- qp.push({i, j});
- }
- }
- }
- vector<pair<int, int>> vp{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
- while (!qp.empty()) {
- auto curr = qp.front();
- qp.pop();
- int currX = curr.first, currY = curr.second;
- for (auto dirr : vp) {
- int x = currX + dirr.first, y = currY + dirr.second;
- if (x >= 0 && x < m && y >= 0 && y < n) {
- if (ans[x][y] > ans[currX][currY] + 1) {
- ans[x][y] = ans[currX][currY] + 1;
- qp.push({x, y});
- }
- }
- }
- }
- return ans;
- }
-};
diff --git a/other/132_pattern.cpp b/other/132_pattern.cpp
deleted file mode 100644
index a9f0c43..0000000
--- a/other/132_pattern.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool find132pattern(vector<int> &nums) {
- int n = nums.size(), minI[n];
- stack<int> s;
- minI[0] = nums[0];
- for (int i = 1; i < nums.size(); i++)
- minI[i] = min(minI[i - 1], nums[i]);
- for (int i = nums.size() - 1; i >= 0; i--) {
- while (!s.empty() && s.top() <= minI[i])
- s.pop();
- if (!s.empty() && s.top() < nums[i])
- return true;
- s.push(nums[i]);
- }
- return false;
- }
-};
-
-int main() {
- vector<int> nums = {1, 3, 2, 4};
- Solution obj;
- for (int i = 0; i < nums.size(); i++)
- cout << nums[i] << ' ';
- cout << endl << "searching for '132'...\n";
- if (obj.find132pattern(nums))
- cout << "found";
- else
- cout << "not found";
-}
diff --git a/other/3sum_closest.cpp b/other/3sum_closest.cpp
deleted file mode 100644
index 3050ee0..0000000
--- a/other/3sum_closest.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int threeSumClosest(vector<int> &nums, int target) {
- sort(nums.begin(), nums.end());
- int n = nums.size(), ans = nums[0] + nums[1] + nums[2];
- for (int i = 0; i < n - 2; ++i) {
- int left = i + 1, right = n - 1;
- while (left < right) {
- int sum3 = nums[i] + nums[left] + nums[right];
- if (abs(ans - target) > abs(sum3 - target))
- ans = sum3;
- if (sum3 == target)
- break;
- if (sum3 > target)
- --right;
- else
- ++left;
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {-1, 2, 1, -4};
- int target = 1;
- cout << obj.threeSumClosest(nums, target);
-}
diff --git a/other/add_arr_form_int.cpp b/other/add_arr_form_int.cpp
deleted file mode 100644
index 1cb8f7a..0000000
--- a/other/add_arr_form_int.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-// 989. Add to Array-Form of Integer
-#include "leetcode.h"
-
-/*
- * the array-form of an integer 'num' is an array representing its digits in
- * left to right order. eg 'num = 1231', the array form is 1,3,2,1. given 'num',
- * the array form of an integer, and an integer 'k', return the array-form of
- * 'num + k'
- */
-
-class Solution {
-public:
- vector<int> addToArrayForm(vector<int> &num, int k) {
- int carry = 0, j = num.size() - 1;
- while (j >= 0) {
- int sum = num[j] + (k % 10) + carry;
- k /= 10;
- num[j--] = sum % 10;
- carry = sum / 10;
- }
- while (k > 0) {
- int sum = (k % 10) + carry;
- k /= 10;
- num.insert(num.begin(), sum % 10);
- carry = sum / 10;
- }
- if (carry > 0)
- num.insert(num.begin(), carry);
- return num;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> num1 = {1, 2, 0, 0}, num2 = {2, 7, 4}, num3 = {2, 1, 5};
- for (auto i : obj.addToArrayForm(num1, 34))
- cout << i << ','; // expect: 1,2,3,4
- cout << endl;
- for (auto i : obj.addToArrayForm(num2, 181))
- cout << i << ','; // expect: 4,5,5
- cout << endl;
- for (auto i : obj.addToArrayForm(num3, 806))
- cout << i << ','; // expect: 1,0,2,1
-}
diff --git a/other/add_binary.cpp b/other/add_binary.cpp
deleted file mode 100644
index 9afc1dc..0000000
--- a/other/add_binary.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-// 67. Add Binary
-#include "leetcode.h"
-
-class Solution {
-public:
- string addBinary(string a, string b) {
- int i = a.size() - 1, j = b.size() - 1, carry = 0;
- string ans;
- while (i >= 0 || j >= 0 || carry) {
- if (i >= 0) {
- carry += a[i] - '0';
- i--;
- }
- if (j >= 0) {
- carry += b[j] - '0';
- j--;
- }
- ans += (carry % 2 + '0');
- carry /= 2;
- }
- reverse(ans.begin(), ans.end());
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.addBinary("11", "1") << endl; // expect: 100
- cout << obj.addBinary("1010", "1011") << endl; // expect: 10101
-}
diff --git a/other/add_digits.cpp b/other/add_digits.cpp
deleted file mode 100644
index ec8abfa..0000000
--- a/other/add_digits.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-// 258. Add Digits
-#include "leetcode.h"
-
-// given an integer 'num', repeatedly add all its digits until
-// the result has onlye one digit and return it
-
-class Solution {
-public:
- int addDigits(int num) {
- int sum = 0;
- while (num) {
- sum += num % 10;
- num /= 10;
- }
- if (sum < 10)
- return sum;
- else
- return addDigits(sum);
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.addDigits(38)); // expect: 2
- printf("%d\n", obj.addDigits(0)); // expect: 0
-}
diff --git a/other/add_row_tree.cpp b/other/add_row_tree.cpp
deleted file mode 100644
index 54ebfb4..0000000
--- a/other/add_row_tree.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- TreeNode *addOneRow(TreeNode *root, int val, int depth) {
- if (depth-- == 1)
- return new TreeNode(val, root, nullptr);
- queue<TreeNode *> q;
- q.push(root);
- while (!q.empty()) {
- bool addLevel = depth-- == 1;
- size_t sz = q.size();
- for (size_t _ = 0; _ < sz; _++) {
- TreeNode *curr = q.front();
- q.pop();
- if (addLevel) {
- curr->left = new TreeNode(val, curr->left, nullptr);
- curr->right = new TreeNode(val, nullptr, curr->right);
- continue;
- }
- if (curr->left)
- q.push(curr->left);
- if (curr->right)
- q.push(curr->right);
- }
- }
- return root;
- }
-};
diff --git a/other/add_search_words_data.cpp b/other/add_search_words_data.cpp
deleted file mode 100644
index 5c5e0f4..0000000
--- a/other/add_search_words_data.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-#include "leetcode.h"
-
-class WordDictionary {
-public:
- WordDictionary() {}
- void addWord(string word) { words[word.size()].push_back(word); }
- bool search(string word) {
- for (auto s : words[word.size()])
- if (isEqual(s, word))
- return true;
- return false;
- }
-
-private:
- unordered_map<int, vector<string>> words;
- bool isEqual(string a, string b) {
- for (int i = 0; i < a.size(); i++) {
- if (b[i] == '.')
- continue;
- if (a[i] != b[i])
- return false;
- }
- return true;
- }
-};
-
-int main() {
- WordDictionary *obj = new WordDictionary();
- obj->addWord("WordDictionary");
- bool param_2 = obj->search("WordDictionary");
- if (param_2)
- cout << "found";
- else
- cout << "not found";
-}
diff --git a/other/add_space_string.cpp b/other/add_space_string.cpp
deleted file mode 100644
index 9a9b7ea..0000000
--- a/other/add_space_string.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-// 2109. Adding Spaces to a String
-#include "leetcode.h"
-
-/*
- * given a 0-indexed string 's' and a 0-indexed integer array 'spaces' that
- * describes the indices in the original string where spaces will be added. each
- * space should be inserted before the character at the given index. return the
- * modified string after the spaces have been added
- */
-
-class Solution {
-public:
- string addSpaces(string s, vector<int> &spaces) {
- int n = spaces.size(), m = s.size(), i = 0, j = 0;
- string ans = "";
- while (i < m) {
- if (j < n && i == spaces[j]) {
- ans += ' ';
- j++;
- }
- ans += s[i];
- i++;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> s1 = {8, 13, 15}, s2 = {1, 5, 7, 9}, s3 = {0, 1, 2, 3, 4, 5, 6};
- cout << obj.addSpaces("LeetcodeHelpsMeLearn", s1)
- << endl; // expect: Leetcode Helps Me Learn
- cout << obj.addSpaces("icodeinpython", s2)
- << endl; // expect: i code in py thon
- cout << obj.addSpaces("spacing", s3) << endl; // expect: s p a c i n g
-}
diff --git a/other/add_two_num2.cpp b/other/add_two_num2.cpp
deleted file mode 100644
index 8cc7121..0000000
--- a/other/add_two_num2.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-// 445. Add Two Numbers II
-#include "leetcode.h"
-
-/*
- * given two non-empty linked lists representing two non-negative integers. the
- * most significant digit comes first and each of their nodes contains a single
- * digit. add the two numbers and return the same as a linked list. you may
- * assume the two numbers do not contain any leading zero, except the number 0
- * itself.
- */
-
-class Solution {
- ListNode *append(int val, ListNode *head) {
- ListNode *tmp = new ListNode(val);
- tmp->next = head;
- return tmp;
- }
-
-public:
- ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
- int n1 = 0, n2 = 0, carry = 0;
- ListNode *curr1 = l1, *curr2 = l2, *ans = NULL;
- while (curr1)
- curr1 = curr1->next, n1++;
- while (curr2)
- curr2 = curr2->next, n2++;
- curr1 = l1, curr2 = l2;
- while (n1 && n2) {
- int sum = 0;
- if (n1 >= n2) {
- sum += curr1->val;
- curr1 = curr1->next;
- n1--;
- }
- if (n2 > n1) {
- sum += curr2->val;
- curr2 = curr2->next;
- n2--;
- }
- ans = append(sum, ans);
- }
- curr1 = ans;
- ans = NULL;
- while (curr1) {
- curr1->val += carry;
- carry = curr1->val / 10;
- ans = append(curr1->val % 10, ans);
- curr2 = curr1;
- curr1 = curr1->next;
- delete curr2;
- }
- if (carry)
- ans = append(1, ans);
- return ans;
- }
-};
diff --git a/other/additive_number.cpp b/other/additive_number.cpp
deleted file mode 100644
index d62c2e5..0000000
--- a/other/additive_number.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-// 306. Additive Number
-#include "leetcode.h"
-
-/*
- * an additive number is a string whose digits can form an additive sequence. a
- * valid additive seuqnece should contain at least three numbers. except for the
- * firs ttwo numbers each subsequent number in the sequence must be the sum of
- * the preceding two. given a string containing only digits, return 'true' if it
- * is an additive number, or 'false' otherwise. note, numbers in the additive
- * sequence cannot have leading zeros, so sequence, 1,2,03, or 1,02,3 is invalid
- */
-
-class Solution {
- string add(string n, string m) {
- string res;
- int i = n.size() - 1, j = m.size() - 1, carry = 0;
- while (i >= 0 || j >= 0) {
- int sum =
- carry + (i >= 0 ? (n[i--] - '0') : 0) + (j >= 0 ? (m[j--] - '0') : 0);
- res.push_back(sum % 10 + '0');
- carry = sum / 10;
- }
- if (carry)
- res.push_back(carry + '0');
- reverse(res.begin(), res.end());
- return res;
- }
- bool check(string n1, string n2, string n) {
- if (n1.size() > 1 && n1[0] == '0' || n2.size() > 1 && n2[0] == '0')
- return false;
- string sum = add(n1, n2);
- if (n == sum)
- return true;
- if (n.size() <= sum.size() || !sum.compare(n.substr(0, sum.size())))
- return false;
- else
- return check(n1, sum, n.substr(sum.size()));
- }
-
-public:
- bool isAdditiveNumber(string num) {
- for (int i = 1; i <= num.size() / 2; i++)
- for (int j = 1; j <= (num.size() - i) / 2; j++)
- if (check(num.substr(0, i), num.substr(i, j), num.substr(i + j)))
- return true;
- return false;
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.isAdditiveNumber("112358")); // expect: 1
- printf("%d\n", obj.isAdditiveNumber("199100199")); // expect: 1
-};
diff --git a/other/all_nodes_binary_tree.cpp b/other/all_nodes_binary_tree.cpp
deleted file mode 100644
index 909352b..0000000
--- a/other/all_nodes_binary_tree.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-// 863. All Nodes Distance K in Binary Tree
-#include "leetcode.h"
-
-/*
- * given the 'root' of a binary tree, the value of a target node 'target', and
- * an integer 'k', return an array of the values of all nodes that have a
- * distance 'k' from the target node. you can return the answer in any order.
- */
-
-class Solution {
- void dfs(TreeNode *root, unordered_map<TreeNode *, TreeNode *> &back_edge,
- TreeNode *target) {
- if (!root || root == target)
- return;
- if (root->left) {
- back_edge[root->left] = root;
- dfs(root->left, back_edge, target);
- }
- if (root->right) {
- back_edge[root->right] = root;
- dfs(root->right, back_edge, target);
- }
- }
-
-public:
- vector<int> distanceK(TreeNode *root, TreeNode *target, int k) {
- unordered_map<TreeNode *, TreeNode *> back_edge;
- unordered_set<TreeNode *> visited;
- vector<int> ans;
- dfs(root, back_edge, target);
- queue<TreeNode *> q;
- q.push(target);
- while (!q.empty() && k >= 0) {
- int s = q.size();
- while (s--) {
- TreeNode *curr = q.front();
- int val = curr->val;
- q.pop();
- visited.insert(curr);
- if (!k)
- ans.push_back(val);
- if (!visited.count(back_edge[curr]) && back_edge[curr])
- q.push(back_edge[curr]);
- if (!visited.count(curr->left) && curr->left)
- q.push(curr->left);
- if (!visited.count(curr->right) && curr->right)
- q.push(curr->right);
- }
- k--;
- }
- return ans;
- }
-};
diff --git a/other/all_path_src_target.cpp b/other/all_path_src_target.cpp
deleted file mode 100644
index 4ad02ef..0000000
--- a/other/all_path_src_target.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vvd allPathsSourceTarget(vvd & graph) {
- vvd ans;
- vector<int> path;
- dfs(graph, ans, path, 0);
- return ans;
- }
-
-private:
- void dfs(vvd & graph, vvd & ans, vector<int> &path, int curr) {
- path.push_back(curr);
- if (curr == graph.size() - 1)
- ans.push_back(path);
- else
- for (auto it : graph[curr])
- dfs(graph, ans, path, it);
- path.pop_back();
- }
-};
-
-int main() {
- Solution obj;
- vvd graph = {{1, 2}, {3}, {3}, {}};
- for (auto i : obj.allPathsSourceTarget(graph))
- for (auto j : i)
- cout << j << ' ';
-}
diff --git a/other/all_path_src_target.rs b/other/all_path_src_target.rs
deleted file mode 100644
index c406cd8..0000000
--- a/other/all_path_src_target.rs
+++ /dev/null
@@ -1,54 +0,0 @@
-use std::collections::VecDeque;
-struct Solution;
-
-impl Solution {
- pub fn all_paths_source_target(graph: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
- let (src, dst, mut rev) = (0, (graph.len() - 1) as i32, vec![0; graph.len()]);
- for (u, adj) in graph.iter().enumerate() {
- for &v in adj {
- rev[v as usize] += 1;
- }
- }
- let mut top_sort_q = VecDeque::new();
- for v in 0..graph.len() {
- if rev[v] == 0 {
- top_sort_q.push_back(v as i32);
- }
- }
- let mut ans = vec![vec![]; graph.len()];
- while let Some(v) = top_sort_q.pop_front() {
- if v == src {
- ans[src as usize].push(vec![src])
- }
- if v == dst {
- break;
- }
- for &next in graph[v as usize].iter() {
- let (ans_v, ans_next) = {
- if v < next {
- let (ans_left, ans_right) = ans.split_at_mut(v as usize + 1);
- (&ans_left[v as usize], &mut ans_right[(next - v - 1) as usize])
- } else {
- let (ans_left, ans_right) = ans.split_at_mut(next as usize + 1);
- (&ans_right[(v - next - 1) as usize], &mut ans_left[next as usize])
- }
- };
- for path in ans_v {
- let mut new_path = path.clone();
- new_path.push(next);
- ans_next.push(new_path);
- }
- rev[next as usize] -= 1;
- if rev[next as usize] == 0 {
- top_sort_q.push_back(next);
- }
- }
- }
- std::mem::take(&mut ans[dst as usize])
- }
-}
-
-fn main() {
- let graph = vec![vec![1,2],vec![3],vec![3],vec![]];
- print!("{:?}", Solution::all_paths_source_target(graph));
-}
diff --git a/other/all_possible_full_tree.cpp b/other/all_possible_full_tree.cpp
deleted file mode 100644
index ca54570..0000000
--- a/other/all_possible_full_tree.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 894. All Possible Full Binary Trees
-#include "leetcode.h"
-
-/*
- * given an integer 'n', return a list of all possible full binary trees with
- * 'n' nodes. each node of each tree in the answer must have 'node.val == 0'.
- * each element of the answer is the root node of one possible tree. you may
- * return the final list of trees in any order. a full binary tree is a binary
- * tree where each node has exactly zero or two children
- */
-
-class Solution {
-public:
- vector<TreeNode *> allPossibleFBT(int n) {
- unordered_map<int, vector<TreeNode *>> memo;
- vector<TreeNode *> ans;
- if (n < 1 || !n % 2)
- return ans;
- if (memo.find(n) != memo.end())
- return memo[n];
- if (n == 1) {
- ans.push_back(new TreeNode(0));
- memo[1] = ans;
- return ans;
- }
- for (int i = 1; i < n; i += 2) {
- vector<TreeNode *> left = allPossibleFBT(i);
- vector<TreeNode *> right = allPossibleFBT(n - 1 - i);
- for (int j = 0; j < left.size(); j++)
- for (int k = 0; k < right.size(); k++) {
- TreeNode *root = new TreeNode(0);
- root->left = left[j];
- root->right = right[k];
- ans.push_back(root);
- }
- }
- memo[n] = ans;
- return ans;
- }
-};
diff --git a/other/alphabet_board_path.cpp b/other/alphabet_board_path.cpp
deleted file mode 100644
index 874e201..0000000
--- a/other/alphabet_board_path.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-// 1138. Alphabet Board Path
-#include "leetcode.h"
-
-/*
- * on an alphabet board, we start position [0,0], corresponding to character
- * 'board[0][0]'. here, 'board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy",
- * "z"]' as show in the diagram (see page). return a sequence of moves that
- * makes our answer equal to 'target' in the minimum numbe of moves. (in any
- * order/path)
- */
-
-class Solution {
-public:
- string alphabetBoardPath(string target) {
- unordered_map<char, pair<int, int>> mp;
- for (int i = 0; i < 26; ++i)
- mp[i + 'a'] = {i / 5, i % 5};
- target = 'a' + target;
- string path;
- int dx = 0, dy = 0;
- for (int i = 1; i < target.size(); ++i) {
- auto curr = mp[target[i]];
- auto prev = mp[target[i - 1]];
- dx = curr.first - prev.first;
- dy = curr.second - prev.second;
- if (dy < 0)
- path += string(-dy, 'L');
- if (dx < 0)
- path += string(-dx, 'U');
- if (dy > 0)
- path += string(dy, 'R');
- if (dx > 0)
- path += string(dx, 'D');
- path += '!';
- }
- return path;
- }
-};
-
-int main() {
- Solution boj;
- cout << boj.alphabetBoardPath("leet") << endl; // expect: DDR!UURRR!!DDD!
- cout << boj.alphabetBoardPath("code") << endl; // expect: RR!DDRR!UUL!R!
-}
diff --git a/other/ancestors_node_acyclic_graph.cpp b/other/ancestors_node_acyclic_graph.cpp
deleted file mode 100644
index 71b6fb7..0000000
--- a/other/ancestors_node_acyclic_graph.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-// 2192. All Ancestors of a Node in a Directed Acyclic Graph
-#include "leetcode.h"
-
-/*
- * given a positive integer 'n' representing the number of nodes of a directed
- * acyclic graph (dag). the nodes are numbered from 0 to 'n - 1' inclusively.
- * you are also given a 2d integer array 'edges' where 'edges[i] = [fromi, toi]'
- * denotes that there is a unidirectional edge from 'fromi' to 'toi' in the
- * graph. return a list 'answer' where 'answer[i]' is the list of ancestors of
- * the i'th node, sorted in ascending order. a node 'u' is an ancestor of
- * another node 'v' if 'u' can reach 'v' via a set of edges.
- */
-
-class Solution {
-private:
- void dfs(int x, int curr, vector<vector<int>> &res,
- vector<vector<int>> &direct_child) {
- for (auto &i : direct_child[curr])
- if (!res[i].size() || res[i].back() != x) {
- res[i].push_back(x);
- dfs(x, i, res, direct_child);
- }
- }
-
-public:
- vector<vector<int>> getAncestors(int n, vector<vector<int>> &edges) {
- vector<vector<int>> ans(n), direct_child(n);
- for (auto &i : edges)
- direct_child[i[0]].push_back(i[1]);
- for (int i = 0; i < n; i++)
- dfs(i, i, ans, direct_child);
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd e1 = {{0, 3}, {0, 4}, {1, 3}, {2, 4}, {2, 7},
- {3, 5}, {3, 6}, {3, 7}, {4, 6}};
- vvd e2 = {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {1, 2},
- {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}};
- vvd ga1 = obj.getAncestors(8, e1), ga2 = obj.getAncestors(5, e2);
- for (int i = 0; i < ga1.size(); i++) {
- for (int j = 0; j < ga1[0].size(); j++)
- printf("%d ",
- ga1[i][j]); // expect:
- // [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]
- printf("\n");
- }
- printf("\n");
- for (int i = 0; i < ga2.size(); i++) {
- for (int j = 0; j < ga2[0].size(); j++)
- printf("%d ",
- ga2[i][j]); // expect: [[],[0],[0,1],[0,1,2],[0,1,2,3]]
- printf("\n");
- }
- printf("\n");
-}
diff --git a/other/arithmetic_progression.cpp b/other/arithmetic_progression.cpp
deleted file mode 100644
index 4c1c996..0000000
--- a/other/arithmetic_progression.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-// 1502. Can Make Arithmetic Progression From Sequence
-#include "leetcode.h"
-
-/*
- * a sequence of numbers is called an arithmetic progression if the difference
- * between any two consecutive elements is the same. gien an array of numbers
- * 'arr', return true if the array can rearranged to form an arithmetic
- * progression. otherwise, return false.
- */
-
-class Solution {
-public:
- bool canMakeArithmeticProgression(vector<int> &arr) {
- if (arr.size() <= 2)
- return true;
- auto min = *min_element(begin(arr), end(arr));
- auto max = *max_element(begin(arr), end(arr));
- if ((max - min) % (arr.size() - 1))
- return false;
- int d = (max - min) / (arr.size() - 1);
- for (int i = 0; i < arr.size();) {
- if (arr[i] == min + i * d)
- i++;
- else if ((arr[i] - min) % d)
- return false;
- else {
- int pos = (arr[i] - min) / d;
- if (pos < i)
- return false;
- if (arr[pos] == arr[i])
- return false;
- swap(arr[i], arr[pos]);
- }
- }
- return true;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> a1 = {3, 5, 1}, a2 = {1, 2, 4};
- printf("%d\n", obj.canMakeArithmeticProgression(a1)); // expect: 1
- printf("%d\n", obj.canMakeArithmeticProgression(a2)); // expect: 0
-}
diff --git a/other/arithmetic_slices2.cpp b/other/arithmetic_slices2.cpp
deleted file mode 100644
index 38668b7..0000000
--- a/other/arithmetic_slices2.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int numberOfArithmeticSlices(vector<int> &nums) {
- unordered_map<int, vector<int>> num_idx;
- vvd dp(nums.size(), vector<int>(nums.size()));
- int ans = 0;
- for (auto i = 0; i < nums.size(); ++i)
- num_idx[nums[i]].push_back(i);
- for (auto i = 0; i < nums.size(); ++i) {
- for (int j = 0; j < i; j++) {
- auto prev = 2l * nums[j] - nums[i];
- if (prev < INT_MIN || prev > INT_MAX)
- continue;
- auto it = num_idx.find(prev);
- if (it != end(num_idx)) {
- for (auto k : it->second) {
- if (k >= j)
- break;
- dp[i][j] += dp[j][k] + 1;
- }
- }
- ans += dp[i][j];
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {2, 4, 6, 8, 10};
- cout << obj.numberOfArithmeticSlices(nums);
-}
diff --git a/other/arithmetic_slices2.rs b/other/arithmetic_slices2.rs
deleted file mode 100644
index 41162f0..0000000
--- a/other/arithmetic_slices2.rs
+++ /dev/null
@@ -1,30 +0,0 @@
-use std::collections::HashMap;
-struct Solution;
-
-impl Solution {
- pub fn number_of_arithmetic_slices(nums: Vec<i32>) -> i32 {
- let (n, mut ans) = (nums.len(), 0);
- let mut map: Vec<HashMap<i64, i32>> = Vec::with_capacity(n);
- for i in 1..n {
- for j in 0..i {
- let diff: i64 = nums[i] as i64 - nums[j] as i64;
- let count = match map.len() {
- 0 => 0,
- _ => *map[j].get(&diff).unwrap_or(&0)
- };
- if map.len() < i + 1 {
- let n = i - map.len() + 1;
- map.extend(vec![HashMap::new(); n]);
- }
- map[i].entry(diff).and_modify(|x| *x += count + 1).or_insert(count + 1);
- ans += count;
- }
- }
- ans
- }
-}
-
-fn main() {
- let nums = vec![2,4,6,8,10];
- print!("{}", Solution::number_of_arithmetic_slices(nums));
-}
diff --git a/other/asteroid_collision.cpp b/other/asteroid_collision.cpp
deleted file mode 100644
index e27f138..0000000
--- a/other/asteroid_collision.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-// 735. Asteroid Collision
-#include "leetcode.h"
-
-/*
- * given an array 'asteroids' o intergers representing asteroids in a row. for
- * each asteroid, the absolute value represents its size, and the sign
- * represents its direction (positive meaning right, negative meaning left).
- * each asteroid moves at the same speed. find out the state of the asteroids
- * after all collisions. if two asteroids meet the smaller one will explode. if
- * both are the same size, both will explode. two asteroids moving in the same
- * direction will never meet.
- */
-
-class Solution {
-public:
- vector<int> asteroidCollision(vector<int> &asteroids) {
- int n = asteroids.size();
- stack<int> s;
- for (int i = 0; i < n; i++) {
- if (asteroids[i] || s.empty())
- s.push(asteroids[i]);
- else {
- while (!s.empty() && s.top() && s.top() < abs(asteroids[i]))
- s.pop();
- if (!s.empty() && s.top() == abs(asteroids[i]))
- s.pop();
- else if (s.empty() || s.top() < 0)
- s.push(asteroids[i]);
- }
- }
- vector<int> ans(s.size());
- for (int i = s.size() - 1; i >= 0; i--) {
- ans[i] = s.top();
- s.pop();
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> a1 = {5, 10, -5}, a2 = {8, -8}, a3 = {10, 2, -5};
- for (auto i : obj.asteroidCollision(a1))
- printf("%d ", i); // expect: 5 10
- printf("\n");
- for (auto i : obj.asteroidCollision(a2))
- printf("%d ", i); // expect: nil
- printf("\n");
- for (auto i : obj.asteroidCollision(a3))
- printf("%d ", i); // expect: 10
- printf("\n");
-}
diff --git a/other/avg_levels_bst.cpp b/other/avg_levels_bst.cpp
deleted file mode 100644
index a18d38d..0000000
--- a/other/avg_levels_bst.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<double> averageOfLevels(TreeNode *root) {
- vector<double> ans;
- queue<TreeNode *> q;
- q.push(root);
- while (!q.empty()) {
- double tmp = q.size(), sum = 0;
- for (int i = 0; i < tmp; i++) {
- auto tt = q.front();
- q.pop();
- sum += (tt->val);
- if (tt->left)
- q.push(tt->left);
- if (tt->right)
- q.push(tt->right);
- }
- ans.push_back(sum / tmp);
- }
- return ans;
- }
-};
diff --git a/other/avg_salary.cpp b/other/avg_salary.cpp
deleted file mode 100644
index 12d49ce..0000000
--- a/other/avg_salary.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-// 1491. Average Salary Excluding the Minimum and Maximum Salary
-#include "leetcode.h"
-
-/*
- * given an array of unique integers 'salary' where 'salary[i]' is the salaray
- * of the i'th employee. return the average salary of employees excluding the
- * minimum and maximum salary. answer within 10^-5 of actual answer
- */
-
-class Solution {
-public:
- double average(vector<int> &salary) {
- double max = DBL_MIN, min = DBL_MAX, sum = 0;
- for (int i = 0; i < salary.size(); i++) {
- sum += salary[i];
- if (salary[i] < min)
- min = salary[i];
- if (salary[i] > max)
- max = salary[i];
- }
- sum = sum - min - max;
- return sum / (salary.size() - 2);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> s1 = {4000, 3000, 1000, 2000};
- vector<int> s2 = {1000, 2000, 3000};
- printf("%f\n", obj.average(s1)); // expect: 2500.00000
- printf("%f\n", obj.average(s2)); // expect: 2000.00000
-}
diff --git a/other/bag_of_tokens.cpp b/other/bag_of_tokens.cpp
deleted file mode 100644
index d645d2b..0000000
--- a/other/bag_of_tokens.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int bagOfTokensScore(vector<int> &tokens, int power) {
- sort(tokens.begin(), tokens.end());
- int i, j, n;
- i = 0;
- j = n = tokens.size();
- while (i < j) {
- if (power >= tokens[i])
- power -= tokens[i++];
- else if (i - (n - j) && j > i + 1)
- power += tokens[--j];
- else
- break;
- }
- return i - (n - j);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> tokens = {100};
- int power = 50;
- cout << obj.bagOfTokensScore(tokens, power);
-}
diff --git a/other/balanced_num.cpp b/other/balanced_num.cpp
deleted file mode 100644
index 779cb06..0000000
--- a/other/balanced_num.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-// 2048. Next Greater Numerically Balanced Number
-#include "leetcode.h"
-
-/*
- * an integer 'x' is numerically balanced if for every digit 'd' in the number
- * 'x', there are exactly 'd' occurences of that digit in 'x'. given an integer
- * 'n', return the smallest numerically balanced number strictly greater than
- * 'n'
- */
-
-class Solution {
-public:
- int nextBeautifulNumber(int n) {
- /*
- vector<int> all;
- for (int i = 0; i <= 1224444; ++i) {
- int v = i;
- unordered_map<int, int> m;
- while (v > 0) {
- ++m[v % 10];
- v /= 10;
- }
- for (auto &p : m) {
- if (p.first != p.second)
- goto L;
- }
- all.push_back(i);
- L:;
- }
- */
- static vector<int> all{
- 0, 1, 22, 122, 212, 221, 333, 1333, 3133,
- 3313, 3331, 4444, 14444, 22333, 23233, 23323, 23332, 32233,
- 32323, 32332, 33223, 33232, 33322, 41444, 44144, 44414, 44441,
- 55555, 122333, 123233, 123323, 123332, 132233, 132323, 132332, 133223,
- 133232, 133322, 155555, 212333, 213233, 213323, 213332, 221333, 223133,
- 223313, 223331, 224444, 231233, 231323, 231332, 232133, 232313, 232331,
- 233123, 233132, 233213, 233231, 233312, 233321, 242444, 244244, 244424,
- 244442, 312233, 312323, 312332, 313223, 313232, 313322, 321233, 321323,
- 321332, 322133, 322313, 322331, 323123, 323132, 323213, 323231, 323312,
- 323321, 331223, 331232, 331322, 332123, 332132, 332213, 332231, 332312,
- 332321, 333122, 333212, 333221, 422444, 424244, 424424, 424442, 442244,
- 442424, 442442, 444224, 444242, 444422, 515555, 551555, 555155, 555515,
- 555551, 666666, 1224444,
- };
- return *upper_bound(all.begin(), all.end(), n);
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.nextBeautifulNumber(1));
- printf("%d\n", obj.nextBeautifulNumber(1000));
- printf("%d\n", obj.nextBeautifulNumber(3000));
-}
diff --git a/other/basic_calculator.cpp b/other/basic_calculator.cpp
deleted file mode 100644
index 80e0ffe..0000000
--- a/other/basic_calculator.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int calculate(string s) {
- stack<pair<int, int>> sp;
- long long int ans = 0;
- int sign = +1;
- for (int i = 0; i < s.size(); ++i) {
- char ch = s[i];
- if (isdigit(ch)) {
- long long int num = 0;
- while (i < s.size() && isdigit(s[i])) {
- num = (num * 10) + s[i] - '0';
- i++;
- }
- i--;
- ans += (num * sign);
- sign = +1;
- } else if (ch == '(') {
- sp.push(make_pair(ans, sign));
- ans = 0;
- sign = +1;
- } else if (ch == ')') {
- ans = sp.top().first + (sp.top().second * ans);
- sp.pop();
- } else if (ch == '-')
- sign = (-1 * sign);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.calculate("1 + 1");
-}
diff --git a/other/basic_calculator.rs b/other/basic_calculator.rs
deleted file mode 100644
index d33a18c..0000000
--- a/other/basic_calculator.rs
+++ /dev/null
@@ -1,29 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn calculate(s: String) -> i32 {
- let mut sp: Vec<i32> = Vec::new();
- let (mut ans, mut num, mut sign) = (0, 0, 1);
- sp.push(sign);
- for ch in s.chars() {
- match ch {
- ' ' => {}
- '+' | '-' => {
- ans += num * sign;
- sign = sp.last().unwrap() * if ch == '+' {1} else {-1};
- num = 0;
- }
- '(' => {sp.push(sign);}
- ')' => {sp.pop();}
- _ => {num * 10 + (ch as i32 - '0' as i32)}
- };
- }
- ans += num * sign;
- ans
- }
-}
-
-fn main() {
- let s = String::from("1 + 1");
- print!("{}", Solution::calculate(s));
-}
diff --git a/other/best_buy_sell_stock.cpp b/other/best_buy_sell_stock.cpp
deleted file mode 100644
index 31b2a17..0000000
--- a/other/best_buy_sell_stock.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-// 121. Best Time to Buy and Sell Stock
-#include "leetcode.h"
-
-/*
- * given an array 'prices' where 'prices[i]' is the price of a given stock on
- * the ith day. maximise profit by choosing a single day to buy one stock and
- * choosing a diff day in future to sell stock. return maximum profit achievable
- * from transaction.
- */
-
-class Solution {
-public:
- int maxProfit(vector<int> &prices) {
- int lsf = INT_MAX, op = 0, pist = 0;
- for (int i = 0; i < prices.size(); i++) {
- if (prices[i] < lsf)
- lsf = prices[i];
- pist = prices[i] - lsf;
- if (op < pist)
- op = pist;
- }
- return op;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> p1 = {7, 1, 5, 3, 6, 4}, p2 = {7, 6, 4, 3, 1};
- cout << obj.maxProfit(p1) << endl; // expect: 5
- cout << obj.maxProfit(p2) << endl; // expect: 0
-}
diff --git a/other/best_team_no_conflict.cpp b/other/best_team_no_conflict.cpp
deleted file mode 100644
index 0773202..0000000
--- a/other/best_team_no_conflict.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int bestTeamScore(vector<int> &scores, vector<int> &ages) {
- int n = scores.size(), ans = 0;
- vector<int> dp(n, 0);
- vector<pair<int, int>> arr(n, {0, 0});
- for (int i = 0; i < n; ++i) {
- arr[i].first = ages[i];
- arr[i].second = scores[i];
- }
- for (int i = 0; i < n; ++i) {
- dp[i] = arr[i].second;
- for (int j = i - 1; j >= 0; --j)
- if (arr[i].second >= arr[j].second)
- dp[i] = max(dp[i], dp[j] + arr[i].second);
- ans = max(ans, dp[i]);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> scores = {1, 3, 5, 10, 15}, ages = {1, 2, 3, 4, 5};
- cout << obj.bestTeamScore(scores, ages);
-}
diff --git a/other/binary_search.cpp b/other/binary_search.cpp
deleted file mode 100644
index 478281e..0000000
--- a/other/binary_search.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-// 704. Binary Search
-#include "leetcode.h"
-
-class Solution {
-public:
- int search(vector<int> &nums, int target) {
- int n = nums.size() - 1;
- int low = 0, high = n;
- while (low <= high) {
- int mid = low + (high - low) / 2;
- if (nums[mid] == target)
- return mid;
- else if (nums[mid] > target)
- high = mid - 1;
- else
- low = mid + 1;
- }
- return -1;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {-1, 0, 3, 5, 9, 12};
- printf("%d\n", obj.search(nums, 9)); // expect: 4
- printf("%d\n", obj.search(nums, 2)); // expect: -1
-}
diff --git a/other/binary_tree_factors.cpp b/other/binary_tree_factors.cpp
deleted file mode 100644
index fef1b69..0000000
--- a/other/binary_tree_factors.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int numFactoredBinaryTrees(vector<int> &arr) {
- sort(arr.begin(), arr.end());
- int n = arr.size();
- long ans = 0;
- unordered_map<int, long> um;
- for (int num : arr) {
- long ways = 1;
- double lim = sqrt(num);
- for (int i = 0, fA = arr[0]; fA <= lim; fA = arr[++i]) {
- if (num % fA != 0)
- continue;
- int fB = num / fA;
- if (um.find(fB) != um.end())
- ways += um[fA] * um[fB] * (fA == fB ? 1 : 2);
- }
- um[num] = ways;
- ans = (ans + ways) % 1000000007;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> arr = {2, 4};
- cout << obj.numFactoredBinaryTrees(arr);
-}
diff --git a/other/binary_tree_inorder.cpp b/other/binary_tree_inorder.cpp
deleted file mode 100644
index a677d27..0000000
--- a/other/binary_tree_inorder.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> inorderTraversal(TreeNode *root) {
- vector<int> ans;
- stack<TreeNode *> s;
- TreeNode *curr = root;
- while (curr || !s.empty()) {
- while (curr) {
- s.push(curr);
- curr = curr->left;
- }
- curr = s.top();
- s.pop();
- ans.push_back(curr->val);
- curr = curr->right;
- }
- return ans;
- }
-};
-
-int main() { Solution obj; }
diff --git a/other/binary_tree_level_traverse.cpp b/other/binary_tree_level_traverse.cpp
deleted file mode 100644
index 47a69da..0000000
--- a/other/binary_tree_level_traverse.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<vector<int>> levelOrder(TreeNode *root) {
- vector<vector<int>> ans;
- if (!root)
- return ans;
- queue<TreeNode *> q;
- q.push(root);
- q.push(NULL);
- vector<int> curr;
- while (!q.empty()) {
- TreeNode *t = q.front();
- q.pop();
- if (t == NULL) {
- ans.push_back(curr);
- curr.resize(0);
- if (q.size() > 0)
- q.push(NULL);
- } else {
- curr.push_back(t->val);
- if (t->left)
- q.push(t->left);
- if (t->right)
- q.push(t->right);
- }
- }
- return ans;
- }
-};
diff --git a/other/binary_tree_preorder.cpp b/other/binary_tree_preorder.cpp
deleted file mode 100644
index 7bba435..0000000
--- a/other/binary_tree_preorder.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> preorderTraversal(TreeNode *root) {
- // morris traversal
- vector<int> nodes;
- while (root) {
- if (root->left) {
- TreeNode *pre = root->left;
- while (pre->right && pre->right != root)
- pre = pre->right;
- if (!pre->right) {
- pre->right = root;
- nodes.push_back(root->val);
- root = root->left;
- } else {
- pre->right = NULL;
- root = root->right;
- }
- } else {
- nodes.push_back(root->val);
- root = root->right;
- }
- }
- return nodes;
- }
-};
diff --git a/other/binary_tree_preorder.rs b/other/binary_tree_preorder.rs
deleted file mode 100644
index da6e0b8..0000000
--- a/other/binary_tree_preorder.rs
+++ /dev/null
@@ -1,35 +0,0 @@
-use std::rc::Rc;
-use std::cell::RefCell;
-#[derive(Debug, PartialEq, Eq)]
-pub struct TreeNode {
- pub val: i32,
- pub left: Option<Rc<RefCell<TreeNode>>>,
- pub right: Option<Rc<RefCell<TreeNode>>>,
-}
-
-impl TreeNode {
- #[inline]
- pub fn new(val: i32) -> Self {
- TreeNode {
- val, left: None,
- right: None
- }
- }
-}
-
-struct Solution;
-
-impl Solution {
- pub fn preorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
- let mut ans: Vec<i32> = Vec::new();
- let mut stack: Vec<Option<Rc<RefCell<TreeNode>>>> = vec![root];
- while let Some(last) = stack.pop() {
- if let Some(n) = last {
- ans.push(n.borrow().val);
- stack.push(n.borrow().right.clone());
- stack.push(n.borrow().left.clone());
- }
- }
- ans
- }
-}
diff --git a/other/binary_tree_pruning.cpp b/other/binary_tree_pruning.cpp
deleted file mode 100644
index 3bac07d..0000000
--- a/other/binary_tree_pruning.cpp
+++ /dev/null
@@ -1,15 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- TreeNode *pruneTree(TreeNode *root) {
- if (root) {
- root->left = pruneTree(root->left);
- root->right = pruneTree(root->right);
- if (root->left || root->right || root->val != 0)
- return root;
- }
- delete root;
- return nullptr;
- }
-};
diff --git a/other/binary_tree_right_view.cpp b/other/binary_tree_right_view.cpp
deleted file mode 100644
index e5a040c..0000000
--- a/other/binary_tree_right_view.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> rightSideView(TreeNode *root) {
- queue<TreeNode *> q;
- vector<int> ans;
- if (!root)
- return ans;
- q.push(root);
- while (!q.empty()) {
- ans.push_back(q.back()->val);
- for (int i = q.size(); i > 0; i--) {
- TreeNode *n = q.front();
- q.pop();
- if (n->left)
- q.push(n->left);
- if (n->right)
- q.push(n->right);
- }
- }
- return ans;
- }
-};
diff --git a/other/binary_tree_traversal.cpp b/other/binary_tree_traversal.cpp
deleted file mode 100644
index 601e21c..0000000
--- a/other/binary_tree_traversal.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
- unordered_map<int, int> m;
- for (int i = 0; i < inorder.size(); i++)
- m[inorder[i]] = i;
- return splitTree(preorder, m, 0, 0, inorder.size() - 1);
- }
-
-private:
- TreeNode *splitTree(vector<int> &preorder, unordered_map<int, int> &m,
- int pix, int iLeft, int iRight) {
- int rVal = preorder[pix], iMid = m[rVal];
- TreeNode *root = new TreeNode(rVal);
- if (iMid > iLeft)
- root->left = splitTree(preorder, m, pix + 1, iLeft, iMid - 1);
- if (iMid < iRight)
- root->right =
- splitTree(preorder, m, pix + iMid - iLeft + 1, iMid + 1, iRight);
- return root;
- }
-};
diff --git a/other/binary_tree_zigzag.cpp b/other/binary_tree_zigzag.cpp
deleted file mode 100644
index 186a99f..0000000
--- a/other/binary_tree_zigzag.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-// 103. Binary Tree Zigzag Level Order Traversal
-#include "leetcode.h"
-// given the 'root' of a binary tree, return the zigzag level order traversal of
-// its nodes' values (ie. from left to right, then right to left for the next
-// level)
-
-class Solution {
-public:
- vvd zigzagLevelOrder(TreeNode *root) {
- if (!root)
- return {};
- queue<TreeNode *> q;
- vvd ans;
- q.push(root);
- int level = 0;
- while (!q.empty()) {
- int sz = q.size();
- vector<int> curr(sz);
- for (int i = 0; i < sz; i++) {
- TreeNode *tmp = q.front();
- q.pop();
- if (level == 0)
- curr[i] = tmp->val;
- else
- curr[sz - i - 1] = tmp->val;
- if (tmp->left)
- q.push(tmp->left);
- if (tmp->right)
- q.push(tmp->right);
- }
- ans.push_back(curr);
- level = !level;
- }
- return ans;
- }
-};
diff --git a/other/boats_save_people.cpp b/other/boats_save_people.cpp
deleted file mode 100644
index 7221191..0000000
--- a/other/boats_save_people.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-// 881. Boats to Save People
-#include "leetcode.h"
-
-/*
- * given an array 'people' where 'people[i]' is the weight of the i'th person,
- * and an infinite number of boats where each boat can carry a maximum weight of
- * 'limit'. each boat carries at most two people at the same time, provided the
- * sum of the weight of those people is at most 'limit'. return minimum number
- * of boats to carry every person
- */
-
-class Solution {
-public:
- int numRescueBoats(vector<int> &people, int limit) {
- sort(people.begin(), people.end());
- int max_weight = people.size() - 1, min_weight = 0, ans = 0;
- while (min_weight <= max_weight) {
- if (people[min_weight] + people[max_weight] <= limit) {
- min_weight++;
- max_weight--;
- } else
- max_weight--;
- ans++;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> p1 = {1, 2}, p2 = {3, 2, 2, 1}, p3 = {3, 5, 3, 4};
- printf("%d\n", obj.numRescueBoats(p1, 3)); // expect: 1
- printf("%d\n", obj.numRescueBoats(p2, 3)); // expect: 3
- printf("%d\n", obj.numRescueBoats(p3, 5)); // expect: 4
-}
diff --git a/other/brainpower.cpp b/other/brainpower.cpp
deleted file mode 100644
index 6708336..0000000
--- a/other/brainpower.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// 2140. Solving Questions With Brainpower
-#include "leetcode.h"
-
-/*
- * given a 0-indexed 2d integer array 'questions' where 'questions[i] =
- * [pointsi, brainpoweri]'. the array describes the questions of an exam, where
- * you have to process the questions in order (ie starting from question 0) and
- * make a decision whether to solve or skip each question. solving question 'i'
- * will earn you 'pointsi' points, but you will be unable to solve each of the
- * next 'brainpoweri' questions. if you skip question 'i', yo get to make the
- * decision on the next question. return maximum points you can score.
- *
- */
-
-class Solution {
-public:
- long long mostPoints(vvd & questions) {
- int n = questions.size();
- vector<long long> dp(n + 1, 0);
- for (int i = n - 1; i >= 0; --i) {
- int points = questions[i][0];
- int jump = questions[i][1];
- int next_q = min(jump + i + 1, n);
- long long p = points + dp[next_q];
- dp[i] = max(p, dp[i + 1]);
- }
- return dp[0];
- }
-};
-
-int main() {
- Solution obj;
- vvd q1 = {{3, 2}, {4, 3}, {4, 4}, {2, 5}};
- vvd q2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
- printf("%lld\n", obj.mostPoints(q1)); // expect: 5
- printf("%lld\n", obj.mostPoints(q2)); // expect: 7
-}
diff --git a/other/break_palindrom.cpp b/other/break_palindrom.cpp
deleted file mode 100644
index d10c0e6..0000000
--- a/other/break_palindrom.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-// 1328. Break a Palindrome
-#include "leetcode.h"
-
-/*
- * given a palindrome string of lowercase english letters 'palindrome' replace
- * exactly one character with any lowercase english letter so that the resulting
- * string is not a palindrome and that it is the lexicographically smallest one
- * possible. return the resulting string. if there is no way to replace a
- * character to make it not a palindrome, return an empty string.
- */
-
-class Solution {
-public:
- string breakPalindrome(string palindrome) {
- int n = palindrome.size();
- if (n == 1)
- return "";
- for (int i = 0; i < n / 2; i++) {
- if (palindrome[i] != 'a') {
- palindrome[i] = 'a';
- return palindrome;
- }
- }
- palindrome[n - 1] = 'b';
- return palindrome;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.breakPalindrome("abccba") << endl; // expect: aaccba
- cout << obj.breakPalindrome("a") << endl; // expect: null
-}
diff --git a/other/browser_history.cpp b/other/browser_history.cpp
deleted file mode 100644
index df7d3cd..0000000
--- a/other/browser_history.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-// 1472. Design Browser History
-#include "leetcode.h"
-
-/*
- * you have a browser of one tab where you start on the homepage and can visit
- * another url, get back in the history number of steps or move forward in the
- * history number of steps. implement BrowserHistory class (they're self
- * explantory)
- */
-
-class BrowserHistory {
-public:
- BrowserHistory(string homepage) { curr = homepage; }
- void visit(string url) {
- h_forward = stack<string>();
- h_back.push(curr);
- curr = url;
- }
- string back(int steps) {
- while (--steps >= 0 && !h_back.empty()) {
- h_forward.push(curr);
- curr = h_back.top();
- h_back.pop();
- }
- return curr;
- }
- string forward(int steps) {
- while (--steps >= 0 && !h_forward.empty()) {
- h_back.push(curr);
- curr = h_forward.top();
- h_forward.pop();
- }
- return curr;
- }
-
-private:
- stack<string> h_back, h_forward;
- string curr;
-};
-
-int main() {
- BrowserHistory *obj = new BrowserHistory("https.xyz");
- string param_2 = obj->back(1);
- string param_3 = obj->forward(1);
-}
diff --git a/other/bt_max_path_sum.cpp b/other/bt_max_path_sum.cpp
deleted file mode 100644
index ff39808..0000000
--- a/other/bt_max_path_sum.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-// 124. Binary Tree Maximum Path Sum
-#include "leetcode.h"
-
-/*
- * a path in a binary tree is a sequence of nodes where each pair of adjacent
- * nodes in the sequence has an edge connecting them. a node can only appear in
- * the sequence at most once. note that the path does not need to pass through
- * the root. the path sum of a path is the sum of the node's value in the path.
- * given the 'root' of a binary tree, return the maximum path sum of any non
- * empty path
- */
-
-class Solution {
-public:
- int sum;
- int maxPathSum(TreeNode *root) {
- sum = INT_MIN;
- solve(root);
- return sum;
- }
-
-private:
- int solve(TreeNode *root) {
- if (!root)
- return 0;
- int left = max(0, solve(root->left));
- int right = max(0, solve(root->right));
- sum = max(sum, left + right + root->val);
- return max(left, right) + root->val;
- }
-};
diff --git a/other/bt_max_path_sum.rs b/other/bt_max_path_sum.rs
deleted file mode 100644
index b0cb984..0000000
--- a/other/bt_max_path_sum.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-#[derive(Debug, PartialEq, Eq)]
-pub struct TreeNode {
- pub val: i32,
- pub left: Option<Rc<RefCell<TreeNode>>>,
- pub right: Option<Rc<RefCell<TreeNode>>>
-}
-
-impl TreeNode {
- #[inline]
- pub fn new(val: i32) -> Self {
- TreeNode {
- val,
- left: None,
- right: None
- }
- }
-}
-
-use std::rc::Rc;
-use std::cell::RefCell;
-impl Solution {
- pub fn max_path_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
- let mut ans = std::i32::MIN;
- Solution::dfs(&root, &mut ans);
- ans
- }
- fn dfs(node: &Option<Rc<RefCell<TreeNode>>>, ans: &mut i32) -> i32 {
- if let Some(n) = node {
- let val = n.borrow().val;
- let l = std::cmp::max(0, Solution::dfs(&n.borrow().left, ans));
- let r = std::cmp::max(0, Solution::dfs(&n.borrow().right, ans));
- *ans = std::cmp::max(*ans, val + l + r);
- val + std::cmp::max(l, r)
- } else {
- 0
- }
- }
-}
diff --git a/other/buddy_strings.cpp b/other/buddy_strings.cpp
deleted file mode 100644
index 22ce6d8..0000000
--- a/other/buddy_strings.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-// 859. Buddy Strings
-#include "leetcode.h"
-
-/*
- * given two strings 's' and 'goal', return 'true' if you can swap two letters
- * in 's' so the result is equal to 'goal', otherwise, return 'false'. swapping
- * letters is defined as taking two indices 'i' and 'j' 0-indexed such that 'i
- * != j' and swapping the characters at 's[i]' and 's[j]'. for example, swapping
- * indices at '0' and '2' in "abcd" results in "cbad"
- */
-
-class Solution {
-public:
- bool buddyStrings(string s, string goal) {
- if (s.size() != goal.size())
- return false;
- if (s == goal) {
- unordered_map<char, int> cnt;
- for (auto i : s) {
- cnt[i]++;
- if (cnt[i] > 1)
- return true;
- }
- return false;
- }
- vector<int> diff;
- for (int i = 0; i < s.size(); i++)
- if (s[i] != goal[i]) {
- diff.push_back(i);
- if (diff.size() > 2)
- return false;
- }
- if (diff.size() != 2)
- return false;
- if ((s[diff[0]] == goal[diff[1]]) && (s[diff[1]] == goal[diff[0]]))
- return true;
- return false;
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.buddyStrings("ab", "ba")); // expect: 1
- printf("%d\n", obj.buddyStrings("ab", "ab")); // expect: 0
- printf("%d\n", obj.buddyStrings("aa", "aa")); // expect: 1
-}
diff --git a/other/build_matrix_conditions.cpp b/other/build_matrix_conditions.cpp
deleted file mode 100644
index e192dda..0000000
--- a/other/build_matrix_conditions.cpp
+++ /dev/null
@@ -1,98 +0,0 @@
-// 2392. Build a Matrix With Conditions
-#include "leetcode.h"
-
-/*
- * you are givne a positive integer 'k'. you are also given a 2d integer array
- * 'rowConditions' of size 'n' where 'rowConditions[i] = [above_i, below_i]' and
- * a 2d integer array 'colConditions' of size 'm' where 'colConditions[i] =
- * [left_i, right_i]'. the two arrays contain integers from 1 to 'k'. you have
- * to build a 'k * k' matrix that contains each of the numbers from 1 to 'k'
- * exactly once. the remaining cells should satisfy the following conditions.
- * the number 'above_i' should appear in a row that is strictly above the row at
- * which the number 'below_i' appears for all 'i'. the number 'left_i' should
- * appear in a column that is strictly left of the column at which the number
- * 'right_i' appears for all 'i'. return any matrix that satisfies these
- * conditions.
- */
-
-class Solution {
-private:
- vector<char> colour;
- vector<bool> visited;
- bool dfs(int v, vector<vector<int>> &graph) {
- colour[v] = 1;
- for (int i : graph[v]) {
- if (!colour[i]) {
- if (dfs(i, graph))
- return true;
- } else if (colour[i] == 1)
- return true;
- }
- colour[v] = 2;
- return false;
- }
- bool find_cycle(vector<vector<int>> &graph, int n) {
- colour.assign(n, 0);
- for (int i = 0; i < n; i++)
- if (!colour[i] && dfs(i, graph))
- return true;
- return false;
- }
- void dfs2(int v, vector<vector<int>> &graph, vector<int> &res) {
- visited[v] = true;
- for (int i : graph[v])
- if (!visited[i])
- dfs2(i, graph, res);
- res.push_back(v);
- }
- void topo_sort(vector<vector<int>> &graph, int n, vector<int> &res) {
- visited.assign(n, false);
- res.clear();
- for (int i = 0; i < n; ++i)
- if (!visited[i])
- dfs2(i, graph, res);
- reverse(res.begin(), res.end());
- }
-
-public:
- vector<vector<int>> buildMatrix(int k, vector<vector<int>> &rowConditions,
- vector<vector<int>> &colConditions) {
- vector<vector<int>> g1(k), g2(k);
- for (auto i : rowConditions)
- g1[i[0] - 1].push_back(i[1] - 1);
- for (auto i : colConditions)
- g2[i[0] - 1].push_back(i[1] - 1);
- if (find_cycle(g1, k) || find_cycle(g2, k))
- return vector<vector<int>>();
- vector<int> a1, a2;
- topo_sort(g1, k, a1);
- topo_sort(g1, k, a2);
- vector<vector<int>> ans(k, vector<int>(k));
- map<int, int> m;
- for (int i = 0; i < k; i++)
- m[a2[i]] = i;
- for (int i = 0; i < k; i++)
- ans[i][m[a1[i]]] = a1[i] + 1;
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd rc1 = {{1, 2}, {3, 2}}, cc1 = {{2, 1}, {3, 2}};
- vvd rc2 = {{1, 2}, {2, 3}, {3, 1}, {2, 3}}, cc2 = {{2, 1}};
- vvd bm1 = obj.buildMatrix(3, rc1, cc1),
- bm2 = obj.buildMatrix(3, rc2, cc2);
- for (int i = 0; i < bm1.size(); i++) {
- for (int j = 0; j < bm1[0].size(); j++)
- printf("%d ", bm1[i][j]);
- printf("\n");
- }
- printf("\n");
- for (int i = 0; i < bm2.size(); i++) {
- for (int j = 0; j < bm2[0].size(); j++)
- printf("%d ", bm2[i][j]);
- printf("\n");
- }
- printf("\n");
-}
diff --git a/other/bulb_switcher.cpp b/other/bulb_switcher.cpp
deleted file mode 100644
index 9fd9374..0000000
--- a/other/bulb_switcher.cpp
+++ /dev/null
@@ -1,19 +0,0 @@
-// 319. Bulb Switcher
-#include <math.h>
-#include <stdio.h>
-
-/*
- * there are 'n' light bulbs that are initially off. you first turn on all the
- * bulbs, then you turn off every second bulb. on the third round, you toggle
- * every third bulb (turning on if it is off or vice-versa). for the i'th round,
- * you toggle every 'i' bulb for the n'th round, you only toggle the last bulb.
- * return the number that on after 'n'
- */
-
-int bulbSwitch(int n) { return sqrt(n); }
-
-int main() {
- printf("%d\n", bulbSwitch(3)); // expect: 1
- printf("%d\n", bulbSwitch(0)); // expect: 0
- printf("%d\n", bulbSwitch(1)); // expect: 1
-}
diff --git a/other/buy_sell_stock.cpp b/other/buy_sell_stock.cpp
deleted file mode 100644
index 122ee2a..0000000
--- a/other/buy_sell_stock.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maxProfit(int k, vector<int> &prices) {
- if (k == 0)
- return 0;
- if (prices.size() == 0 || prices.size() == 1)
- return 0;
- vvd dp(k + 1, vector<int>(prices.size()));
- for (int i = 0; i < dp.size(); i++) {
- for (int j = 0; j < dp[i].size(); j++) {
- if (i == 0 || j == 0)
- dp[i][j] = 0;
- else {
- int x, mx = INT_MIN;
- for (int k = 0; k < j; k++) {
- x = prices[j] - prices[k] + dp[i - 1][k];
- mx = max(x, mx);
- }
- dp[i][j] = max(dp[i][j - 1], mx);
- }
- }
- }
- return dp[dp.size() - 1][prices.size() - 1];
- }
-};
-
-int main() {
- Solution obj;
- int k = 2;
- vector<int> prices = {2, 4, 1};
- cout << obj.maxProfit(k, prices);
-}
diff --git a/other/buy_sell_stock.rs b/other/buy_sell_stock.rs
deleted file mode 100644
index 268482f..0000000
--- a/other/buy_sell_stock.rs
+++ /dev/null
@@ -1,33 +0,0 @@
-use std::collections::HashMap;
-struct Solution;
-
-#[derive(PartialEq, Eq, Hash, Copy, Clone)]
-enum Invested {
- Yes, No, Cooldown
-}
-
-impl Solution {
- pub fn max_profit(prices: Vec<i32>) -> i32 {
- Self::dp(&prices, 0, Invested::No, &mut HashMap::new())
- }
- fn dp(prices: &[i32], day: usize, invested: Invested, memo: &mut HashMap<(usize, Invested), i32>) -> i32 {
- if day == prices.len() {
- 0
- } else if let Some(profit) = memo.get(&(day, invested)) {
- *profit
- } else {
- let ans = match invested {
- Invested::Yes => Self::dp(prices, day + 1, invested, memo).max(prices[day] + Self::dp(prices, day + 1, Invested::Cooldown, memo)),
- Invested::No => Self::dp(prices, day + 1, invested, memo).max(-prices[day] + Self::dp(prices, day + 1, Invested::Yes, memo)),
- Invested::Cooldown => Self::dp(prices, day + 1, Invested::No, memo)
- };
- memo.insert((day, invested), ans);
- ans
- }
- }
-}
-
-fn main() {
- let prices = vec![1,2,3,0,2];
- print!("{}", Solution::max_profit(prices));
-}
diff --git a/other/buy_sell_stock_fee.cpp b/other/buy_sell_stock_fee.cpp
deleted file mode 100644
index 0375c56..0000000
--- a/other/buy_sell_stock_fee.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-// 714. Best Time to Buy and Sell Stock with Transaction Fee
-#include "leetcode.h"
-
-/*
- * given an array 'prices' where 'prices[i]' is the price of a given stock on
- * the i'th day, and an integer 'fee' representing a transaction fee. find the
- * maximum profit you can achieve. you may complete as many transactions as youl
- * like, but you need to pay the transaction fee for each transaction. note: you
- * may not engage in multiple transactions simultaneously (ie. you must sell the
- * stock before you buy again)
- */
-
-class Solution {
-public:
- int maxProfit(vector<int> &prices, int fee) {
- int n = prices.size();
- if (n < 2)
- return 0;
- vector<int> hold(n, 0), sold(n, 0);
- hold[0] = -prices[0];
- for (int i = 1; i < n; i++) {
- hold[i] = max(hold[i - 1], sold[i - 1] - prices[i]);
- sold[i] = max(sold[i - 1], hold[i - 1] - fee + prices[i]);
- }
- return sold[n - 1];
- }
-};
-
-int main() {
- Solution obj;
- vector<int> p1 = {1, 3, 2, 8, 4, 9};
- vector<int> p2 = {1, 3, 7, 5, 10, 3};
- printf("%d\n", obj.maxProfit(p1, 2)); // expect: 8
- printf("%d\n", obj.maxProfit(p2, 3)); // expect: 6
-}
diff --git a/other/can_place_flower.cpp b/other/can_place_flower.cpp
deleted file mode 100644
index 72846ff..0000000
--- a/other/can_place_flower.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-// 605. Can Place Flowers
-#include "leetcode.h"
-
-/*
- * you have long flowerbed in which some of the plots are
- * planted, and some are not. however, flowers cannot be planted
- * in adjacent plots. given an integer array 'flowerbed'
- * containing 0's and 1's, where 0 means empty and 1 means not empty
- * and an integer 'n', return if 'n' new flowers can be planted
- * in the 'flowerbed' without violating the no-adjacent rule
- */
-
-class Solution {
-public:
- bool canPlaceFlowers(vector<int> &flowerbed, int n) {
- flowerbed.insert(flowerbed.begin(), 0);
- flowerbed.push_back(0);
- int count = 0, s = flowerbed.size() - 1;
- for (int i = 1; i < s; i++)
- if (flowerbed[i - 1] == 0 && flowerbed[i + 1] == 0 && flowerbed[i] == 0) {
- count++;
- flowerbed[i] = 1;
- }
- if (count >= n)
- return true;
- return false;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> flowerbed = {1, 0, 0, 0, 1};
- printf("%d\n", obj.canPlaceFlowers(flowerbed, 1)); // expect: 1
- printf("%d\n", obj.canPlaceFlowers(flowerbed, 2)); // expect: 0
-}
diff --git a/other/candy.cpp b/other/candy.cpp
deleted file mode 100644
index 83915b0..0000000
--- a/other/candy.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int candy(vector<int> &ratings) {
- if (ratings.size() <= 1)
- return ratings.size();
- int ans = 0, up = 0, down = 0, oldSign = 0;
- for (int i = 1; i < ratings.size(); i++) {
- int newSign = ratings[i] > ratings[i - 1] ? 1
- : ratings[i] < ratings[i - 1] ? -1
- : 0;
- if ((oldSign > 0 && newSign == 0) || (oldSign < 0 && newSign >= 0)) {
- ans += helper(up) + helper(down) + max(up, down);
- up = 0;
- down = 0;
- }
- if (newSign > 0)
- up++;
- if (newSign < 0)
- down++;
- if (newSign == 0)
- ans++;
- oldSign = newSign;
- }
- ans += ramp(up) + ramp(down) + max(up, down) + 1;
- }
-
-private:
- int helper(int n) { return (n * (n + 1)) / 2; }
-};
-
-int main() {
- Solution obj;
- vector<int> ratings = {};
- cout << obj.candy(ratings);
-}
diff --git a/other/capacity_ship_d_day.cpp b/other/capacity_ship_d_day.cpp
deleted file mode 100644
index 3612105..0000000
--- a/other/capacity_ship_d_day.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-// 1011. Capacity To Ship Packages Within D Days
-#include "leetcode.h"
-
-/*
- * a conveyor belt has packages that must be shipped from one port to another
- * within 'days' days. the i'th package on the conveyor belt has a weight of
- * 'weights[i]'. each day, the ship is loaded with packages on the conveyor belt
- * (in order given by 'weights'). we may not load more weight than the maximum
- * capacity of the ship. return the least weight capacity of the ship that will
- * result in all the packages on the conveyor belt being shipped within 'days'
- * days.
- */
-
-class Solution {
-public:
- int shipWithinDays(vector<int> &weights, int days) {
- auto r = accumulate(begin(weights), end(weights), 0);
- auto l = max(r / days, *max_element(begin(weights), end(weights)));
- while (l < r) {
- auto m = (l + r) / 2;
- if (countDays(weights, m) <= days)
- r = m;
- else
- l = m + 1;
- }
- return l;
- }
-
-private:
- int countDays(vector<int> &weights, int tot_cap, int cur_cap = 0,
- int res = 1) {
- for (auto w : weights) {
- cur_cap += w;
- if (cur_cap > tot_cap) {
- ++res;
- cur_cap = w;
- }
- }
- return res;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> weights1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
- weights2 = {3, 2, 2, 4, 1, 4}, weights3 = {1, 2, 3, 1, 1};
- cout << obj.shipWithinDays(weights1, 5) << endl; // expect: 15
- cout << obj.shipWithinDays(weights2, 3) << endl; // expect: 6
- cout << obj.shipWithinDays(weights3, 4) << endl; // expect: 3
-}
diff --git a/other/cheapest_flight_k_stop.cpp b/other/cheapest_flight_k_stop.cpp
deleted file mode 100644
index 84cb206..0000000
--- a/other/cheapest_flight_k_stop.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-// 787. Cheapest Flights Within K Stops
-#include "leetcode.h"
-
-/*
- * there are 'n' cities connected by some number of flights. you are given array
- * 'flights' where 'flight[i] = [fromi, toi, pricei]' indicates that there is a
- * flight from city 'fromi' to city 'toi' with cost 'pricei'.
- * you are also given three integers 'src, dst, & k'. return the cheapest price
- * from 'src' to 'dst' with at most 'k' stops. if there is no such route, -1
- */
-
-typedef tuple<int, int, int> tp;
-class Solution {
-public:
- int findCheapestPrice(int n, vvd & flights, int src, int dst, int k) {
- vector<vector<pair<int, int>>> vvp(n);
- for (const auto &f : flights)
- vvp[f[0]].emplace_back(f[1], f[2]);
- priority_queue<tp, vector<tp>, greater<tp>> pqvg;
- pqvg.emplace(0, src, k + 1);
- while (!pqvg.empty()) {
- auto [cost, u, stops] = pqvg.top();
- pqvg.pop();
- if (u == dst)
- return cost;
- if (!stops)
- continue;
- for (auto to : vvp[u]) {
- auto [v, w] = to;
- pqvg.emplace(cost + w, v, stops - 1);
- }
- }
- return -1;
- }
-};
-
-int main() {
- Solution obj;
- vvd flights1 = {
- {0, 1, 100}, {1, 2, 100}, {2, 0, 100}, {1, 3, 600}, {2, 3, 200}};
- vvd flights2 = {{0, 1, 100}, {1, 2, 100}, {0, 2, 500}};
- vvd flights3 = {{0, 1, 100}, {1, 2, 100}, {0, 2, 500}};
- cout << obj.findCheapestPrice(4, flights1, 0, 3, 1) << endl; // expect: 700
- cout << obj.findCheapestPrice(3, flights2, 0, 2, 1) << endl; // expect: 200
- cout << obj.findCheapestPrice(3, flights3, 0, 2, 0) << endl; // expect: 500
-}
diff --git a/other/check_complete_bt.cpp b/other/check_complete_bt.cpp
deleted file mode 100644
index 4054423..0000000
--- a/other/check_complete_bt.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-// 958. Check Completeness of a Binary Tree
-#include "leetcode.h"
-
-/*
- * given 'root' of binary tree, determine if it is a complete binary tree. in a
- * completely filled binary tree, every level, except possibly the last, is
- * completely filled, and all nodes in the last level are as far left as
- * possible. it can have between 1 and 2^h nodes inclusive at the last level h.
- */
-
-class Solution {
-public:
- bool isCompleteTree(TreeNode *root) {
- vector<TreeNode *> bfs;
- bfs.push_back(root);
- int i = 0;
- while (i < bfs.size() && bfs[i]) {
- bfs.push_back(bfs[i]->left);
- bfs.push_back(bfs[i]->right);
- i++;
- }
- while (i < bfs.size() && !bfs[i])
- i++;
- return i == bfs.size();
- }
-};
diff --git a/other/check_existence_edge.cpp b/other/check_existence_edge.cpp
deleted file mode 100644
index c2bd8e9..0000000
--- a/other/check_existence_edge.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-// 1697. Checking Existence of Edge Length Limited Paths
-#include "leetcode.h"
-
-/*
- * an undirected graph of 'n' nodes is defined by 'edge_list',
- * where 'edge_list[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]' whthere there is a path between 'pj' and
- * 'qj' such that each edge on the path has a distance strictly less
- * than 'limitj'. return boolean array where 'ans.length == queries.len'
- * and the j'th value of 'ans' is true if there is a path for
- * 'queries[j]' is true, and false otherwise
- */
-
-class UnionFind {
- vector<int> parent;
-
-public:
- UnionFind(int n) : parent(n) { iota(begin(parent), end(parent), 0); }
- void connect(int a, int b) {
- int x = find(a), y = find(b);
- if (x == y)
- return;
- parent[x] = y;
- }
- bool connected(int i, int j) { return find(i) == find(j); }
- int find(int a) { return parent[a] == a ? a : (parent[a] = find(parent[a])); }
-};
-
-class Solution {
-public:
- vector<bool> distanceLimitedPathsExist(int n, vvd & edge_list,
- vvd & queries) {
- vector<bool> ans(queries.size());
- for (int i = 0; i < queries.size(); ++i)
- queries[i].push_back(i);
- sort(begin(queries), end(queries),
- [&](auto &a, auto &b) { return a[2] < b[2]; });
- sort(begin(edge_list), end(edge_list),
- [&](auto &a, auto &b) { return a[2] < b[2]; });
- UnionFind uf(n);
- int i = 0;
- for (auto &q : queries) {
- int u = q[0], v = q[1], limit = q[2], qid = q[3];
- for (; i < edge_list.size() && edge_list[i][2] < limit; ++i)
- uf.connect(edge_list[i][0], edge_list[i][1]);
- ans[qid] = uf.connected(u, v);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd el1 = {{0, 1, 2}, {1, 2, 4}, {2, 0, 8}, {1, 0, 6}};
- vvd q1 = {{0, 1, 2}, {0, 2, 5}};
- vector<bool> dlpe1 = obj.distanceLimitedPathsExist(3, el1, q1);
- vvd el2 = {{0, 1, 10}, {1, 2, 5}, {2, 3, 9}, {3, 4, 13}};
- vvd q2 = {{0, 4, 14}, {1, 4, 13}};
- vector<bool> dlpe2 = obj.distanceLimitedPathsExist(5, el2, q2);
- for (int i = 0; i < 2; i++)
- cout << dlpe1[i] << ' '; // expect: 0 1
- printf("\n");
- for (int i = 0; i < 2; i++)
- cout << dlpe2[i] << ' '; // expect: 1 0
-}
diff --git a/other/check_knight_config.cpp b/other/check_knight_config.cpp
deleted file mode 100644
index 1d97495..0000000
--- a/other/check_knight_config.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-// 2596. Check Knight Tour Configuration
-#include "leetcode.h"
-
-/*
- * there is a knight on an 'n * n' chessboard. in a valid config
- * the knight starts at the topl-left cell of the board and visits
- * every cell on the board exactly once. you are given an 'n * n'
- * integer matrix 'grid' consisting of distinct integers from the
- * range '[0, n * n - 1]' where 'grid[row][col]' indicates that
- * the cell '(row, col)' is the 'grid[row][col]'th cell that the
- * knight visited. the moves are 0-indexed. return true if grid
- * represents a valid configuration of the knight's movements or
- * false otherwise. note that a valid knight move consists of
- * moving two squares vertically and one square horizontally,
- * or two squares horizontally and one square vertically. the
- * figure illustrates all possible 8 moves of a knight from cell
- */
-
-class Solution {
-public:
- bool checkValidGrid(vvd & grid) {
- int dir[8][2] = {{1, -2}, {2, -1}, {2, 1}, {1, 2},
- {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};
- int cnt = 0, max_cnt = grid.size() * grid.size() - 1;
- int x = 0, y = 0, i, j;
- if (grid[x][y] != cnt)
- return false;
- while (cnt < max_cnt) {
- cnt++;
- int flag = 1;
- for (auto d : dir) {
- i = x + d[0];
- j = y + d[1];
- if (i >= 0 && j >= 0 && i < grid.size() && j < grid.size() &&
- grid[i][j] == cnt) {
- x = i;
- y = j;
- flag = 0;
- break;
- }
- }
- if (flag)
- return false;
- }
- return true;
- }
-};
-
-int main() {
- Solution obj;
- vvd g1 = {{0, 11, 16, 5, 20},
- {17, 4, 19, 10, 15},
- {12, 1, 8, 21, 6},
- {3, 18, 23, 14, 9},
- {24, 13, 2, 7, 22}};
- vvd g2 = {{0, 3, 6}, {5, 8, 1}, {2, 7, 4}};
- printf("%d\n", obj.checkValidGrid(g1)); // expect: 1
- printf("%d\n", obj.checkValidGrid(g2)); // expect: 0
-}
diff --git a/other/check_pangram_sentence.cpp b/other/check_pangram_sentence.cpp
deleted file mode 100644
index 67f1af2..0000000
--- a/other/check_pangram_sentence.cpp
+++ /dev/null
@@ -1,19 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool checkIfPangram(string sentence) {
- set<int> s;
- for (auto &i : sentence)
- s.insert(i);
- return s.size() == 26;
- }
-};
-
-int main() {
- Solution obj;
- if (obj.checkIfPangram("thequickbrownfoxjumpsoverthelazydog"))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/check_pangram_sentence.rs b/other/check_pangram_sentence.rs
deleted file mode 100644
index 0f69c31..0000000
--- a/other/check_pangram_sentence.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn check_if_pangram(sentence: String) -> bool {
- let mut bit_mask: u32 = 0;
- let mut count = 0;
- for c in sentence.chars() {
- let idx = c as usize - 'a' as usize;
- if bit_mask & (1 << idx) == 0 {
- count += 1;
- }
- bit_mask |= 1 << idx;
- }
- count == 26
- }
-}
-
-fn main() {
- let sentence = String::from("thequickbrownfoxjumpsoverthelazydog");
- print!("{}", Solution::check_if_pangram(sentence));
-}
diff --git a/other/check_straight_line.cpp b/other/check_straight_line.cpp
deleted file mode 100644
index 745738b..0000000
--- a/other/check_straight_line.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-// 1232. Check If It Is a Straight Line
-#include "leetcode.h"
-
-/*
- * given an array 'coordinates, coordinates[i] = [x, y]' where '[x, y]'
- * represents the coordinate of a point. check if these points make a straight
- * line in the xy plane
- */
-
-class Solution {
-public:
- bool checkStraightLine(vvd & coordinates) {
- int n = coordinates.size();
- if (n == 1)
- return false;
- if (n == 2)
- return true;
- int x0 = coordinates[0][0], y0 = coordinates[0][1];
- int dx = coordinates[1][0] - x0, dy = coordinates[1][1] - y0;
- for (int i = 1; i < n; i++) {
- int x = coordinates[i][0], y = coordinates[i][1];
- if (dx * (y - y0) != dy * (x - x0))
- return false;
- }
- return true;
- }
-};
-
-int main() {
- Solution obj;
- vvd c1 = {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}};
- vvd c2 = {{1, 1}, {2, 2}, {3, 4}, {4, 5}, {5, 6}, {7, 7}};
- printf("%d\n", obj.checkStraightLine(c1)); // expect: 1
- printf("%d\n", obj.checkStraightLine(c2)); // expect: 0
-}
diff --git a/other/check_string_cont_k.cpp b/other/check_string_cont_k.cpp
deleted file mode 100644
index e041052..0000000
--- a/other/check_string_cont_k.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool hasAllCodes(string s, int k) {
- int bitLimit = 1 << k, n = 0;
- bool combos[bitLimit];
- for (int i = 0; i < bitLimit; i++)
- combos[i] = true;
- for (int i = 0, limit = k - 1; i < limit; i++)
- n = (n << 1) + (s[i] == '1');
- for (int i = k - 1, limit = s.size(), total = bitLimit; i < limit; i++) {
- n = (n << 1) + (s[i] == '1');
- if (n >= bitLimit)
- n -= bitLimit;
- if (combos[n])
- combos[n] = false, total--;
- if (!total)
- return true;
- }
- return false;
- }
-};
-
-int main() {
- Solution obj;
- string s = "00110110";
- int k = 2;
- cout << obj.hasAllCodes(s, k);
-}
diff --git a/other/check_two_str_arr.cpp b/other/check_two_str_arr.cpp
deleted file mode 100644
index 5e4d8a7..0000000
--- a/other/check_two_str_arr.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool arrayStringsAreEqual(vector<string> &word1, vector<string> &word2) {
- int i = 0, j = 0, m = 0, n = 0;
- while (i < word1.size() && j < word2.size()) {
- if (word1[i][m++] != word2[j][n++])
- return false;
- if (m >= word1[i].size())
- i++, m = 0;
- if (n >= word2[j].size())
- j++, n = 0;
- }
- return i == word1.size() && j == word2.size();
- }
-};
-
-int main() {
- Solution obj;
- vector<string> word1 = {"ab", "c"}, word2 = {"a", "bc"};
- if (obj.arrayStringsAreEqual(word1, word2))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/check_two_str_arr.rs b/other/check_two_str_arr.rs
deleted file mode 100644
index 7fd2a2d..0000000
--- a/other/check_two_str_arr.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn array_strings_are_equal(word1: Vec<String>, word2: Vec<String>) -> bool {
- let ans: bool;
- if word1.join("") == word2.join("") {
- ans = true;
- } else {
- ans = false;
- }
- return ans;
- }
-}
-
-fn main() {
- let word1 = vec!["ab".to_string(), "c".to_string()];
- let word2 = vec!["a".to_string(), "bc".to_string()];
- print!("{}", Solution::array_strings_are_equal(word1, word2));
-}
diff --git a/other/check_valid_partition.cpp b/other/check_valid_partition.cpp
deleted file mode 100644
index 3f4cd76..0000000
--- a/other/check_valid_partition.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-// 2369. Check if There is a Valid Partition For The Array
-#include "leetcode.h"
-
-/*
- * given a 0-indexed integer array 'nums', you have to partition the array into
- * one or more contiguous subarrays. we call a partition of the array valid if
- * each of the obtained subarrays satisfies one of the following conditions
- * - the subarray consists of exactly 2 equal elements. for example, the
- * subarray '[2,2]' is good.
- * - the subarray consists of exactly 3 equal elements. for example, the
- * subarray '[4,4,4]' is good.
- * - the subarray consists of exactly 3 consecutive increasing elements, that
- * is, the difference between adjacent elements is 1. for example, the subarray
- * '[3,4,5]' is good, but the subarray '[1,3,5]' is not. return true if the
- * array has at least one valid partition. otherwise, return false.
- */
-
-class Solution {
- bool solve(vector<int> &nums, int i, vector<int> &dp) {
- if (nums.size() == i)
- return true;
- if (dp[i] != -1)
- return dp[i];
- if (i + 1 < nums.size() && nums[i] == nums[i + 1]) {
- if (solve(nums, i + 2, dp))
- return true;
- if (i + 2 < nums.size() && nums[i] == nums[i + 2])
- if (solve(nums, i + 3, dp))
- return true;
- }
- if (i + 2 < nums.size() && nums[i] == nums[i + 1] - 1 &&
- nums[i] == nums[i + 2] - 2)
- if (solve(nums, i + 3, dp))
- return true;
- return !dp[i];
- }
-
-public:
- bool validPartition(vector<int> &nums) {
- vector<int> dp(nums.size(), -1);
- return solve(nums, 0, dp);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {4, 4, 4, 5, 6}, n2 = {1, 1, 1, 2};
- printf("%d\n", obj.validPartition(n1)); // expect: 1
- printf("%d\n", obj.validPartition(n2)); // expect: 0
-}
diff --git a/other/climbing_stairs.cpp b/other/climbing_stairs.cpp
deleted file mode 100644
index afc3d7e..0000000
--- a/other/climbing_stairs.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int climbStairs(int n) {
- /*
- * base case
- * because if 0 steps -> 0 ways,
- * 1 step -> 1 way, & 2 step -> 2 ways
- */
- if (n <= 2)
- return n;
- /*
- * last step was either:
- * 1 step (oneStep) or 2 steps (twoStep)
- * so simply add the two values (fibonacci sequence)
- */
- int oneStep = 1, twoStep = 2, ans;
- for (int i = 3; i <= n; i++) { // 0-2 steps already determined
- ans = oneStep + twoStep;
- oneStep = twoStep;
- twoStep = ans;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.climbStairs(4);
-}
diff --git a/other/climbing_stairs.rs b/other/climbing_stairs.rs
deleted file mode 100644
index e3bf42d..0000000
--- a/other/climbing_stairs.rs
+++ /dev/null
@@ -1,16 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn climb_stairs(n: i32) -> i32 {
- let (mut ans, mut i) = ([2, 1], 3);
- while i <= n as usize {
- ans[i & 0b01] = ans[0] + ans[1];
- i += 1;
- }
- ans[n as usize & 0b01]
- }
-}
-
-fn main() {
- print!("{}", Solution::climb_stairs(2));
-}
diff --git a/other/clone_graph.cpp b/other/clone_graph.cpp
deleted file mode 100644
index fc372a0..0000000
--- a/other/clone_graph.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-// 133. Clone Graph
-#include <cstddef>
-#include <unordered_map>
-#include <vector>
-using namespace std;
-
-// given reference of a node in a connected undirected graph. return a deep copy
-// (clone) of the graph. each node in the graph contains a value and a
-// list (list[node]).
-
-class Node {
-public:
- int val;
- vector<Node *> neighbors;
- Node() {
- val = 0;
- neighbors = vector<Node *>();
- }
- Node(int _val) {
- val = _val;
- neighbors = vector<Node *>();
- }
- Node(int _val, vector<Node *> _neighbors) {
- val = _val;
- neighbors = _neighbors;
- }
-};
-
-class Solution {
- Node *dfs(Node *curr, unordered_map<Node *, Node *> &um) {
- vector<Node *> neighbour;
- Node *clone = new Node(curr->val);
- um[curr] = clone;
- for (auto i : curr->neighbors) {
- if (um.find(i) != um.end())
- neighbour.push_back(um[i]);
- else
- neighbour.push_back(dfs(i, um));
- }
- clone->neighbors = neighbour;
- return clone;
- }
-
-public:
- Node *cloneGraph(Node *node) {
- unordered_map<Node *, Node *> um;
- if (node == NULL)
- return NULL;
- if (!node->neighbors.size()) {
- Node *clone = new Node(node->val);
- return clone;
- }
- return dfs(node, um);
- }
-};
diff --git a/other/closest_node_2_nodes.cpp b/other/closest_node_2_nodes.cpp
deleted file mode 100644
index 7b85f22..0000000
--- a/other/closest_node_2_nodes.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int closestMeetingNode(vector<int> &edges, int node1, int node2) {
- pair<int, int> p1 = dfs(edges, node1, node2);
- pair<int, int> p2 = dfs(edges, node2, node1);
- if (p1.second != -1 && p1.first < p2.first)
- return p1.second;
- else if (p2.second != -1 && p2.first < p1.first)
- return p2.second;
- else if (p1.first == p2.first) {
- if (p1.second < p2.second)
- return p1.second;
- else
- return p2.second;
- }
- return -1;
- }
-
-private:
- pair<int, int> dfs(vector<int> &edges, int node1, int node2) {
- unordered_map<int, int> um;
- int n = edges.size();
- vector<int> vis1(n + 2, 0), vis2(n + 2, 0);
- um[node1] = 1;
- int len = 0;
- while (edges[node1] != -1 && vis1[node1] != 1) {
- vis1[node1] = 1;
- node1 = edges[node1];
- um[node1] = len++;
- }
- pair<int, int> pp = make_pair(INT_MAX, -1);
- if (um.find(node2) != um.end()) {
- pp = make_pair(um[node2], node2);
- return pp;
- }
- while (edges[node2] != -1 && vis2[node2] != 1) {
- vis2[node2] = 1;
- node2 = edges[node2];
- if (um.find(node2) != um.end()) {
- pp = make_pair(um[node2], node2);
- return pp;
- }
- }
- return pp;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> edges1 = {2, 2, 3, -1}, edges2 = {1, 2, -1};
- cout << obj.closestMeetingNode(edges1, 0, 2) << endl; // expect: 2
- cout << obj.closestMeetingNode(edges2, 0, 2) << endl; // expect: 2
-}
diff --git a/other/closest_node_2_nodes.rs b/other/closest_node_2_nodes.rs
deleted file mode 100644
index ea3ee86..0000000
--- a/other/closest_node_2_nodes.rs
+++ /dev/null
@@ -1,45 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn closest_meeting_node(edges: Vec<i32>, node1: i32, node2: i32) -> i32 {
- let n = edges.len();
- let (mut d1, mut d2) = (vec![n; n], vec![n; n]);
- d1[node1 as usize] = 0;
- d2[node2 as usize] = 0;
- let mut u = node1 as usize;
- while edges[u] != -1 {
- let v = edges[u] as usize;
- if d1[v] < d1[u] {
- break;
- }
- d1[v] = d1[u] + 1;
- u = v;
- }
- u = node2 as usize;
- while edges[u] != -1 {
- let v = edges[u] as usize;
- if d2[v] < d2[u] {
- break;
- }
- d2[v] = d2[u] + 1;
- u = v;
- }
- let (mut ans, mut mx) = (-1i32, n);
- for i in 0..n {
- let tmp = d1[i].max(d2[i]);
- if tmp >= mx {
- continue;
- }
- ans = i as i32;
- mx = tmp;
- }
- ans
- }
-}
-
-fn main() {
- let edges1 = vec![2,2,3,-1];
- let edges2 = vec![1,2,-1];
- println!("{}", Solution::closest_meeting_node(edges1, 0, 1)); //expect: 2
- println!("{}", Solution::closest_meeting_node(edges2, 0, 2)); //expect: 2
-}
diff --git a/other/coin_change.cpp b/other/coin_change.cpp
deleted file mode 100644
index 5d31f7a..0000000
--- a/other/coin_change.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int coinChange(vector<int> &coins, int amount) {
- int m = amount + 1;
- vector<int> dp(amount + 1, m);
- dp[0] = 0;
- for (int i = 1; i <= amount; i++)
- for (int j = 0; j < coins.size(); j++)
- if (coins[j] <= i)
- dp[i] = min(dp[i], dp[i - coins[j]] + 1);
- return dp[amount] > amount ? -1 : dp[amount];
- }
-};
-
-int main() {
- vector<int> coins = {1, 2, 5};
- int amount = 11;
- Solution obj;
- cout << obj.coinChange(coins, amount);
-}
diff --git a/other/coin_change2.cpp b/other/coin_change2.cpp
deleted file mode 100644
index 4680c95..0000000
--- a/other/coin_change2.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-// 518. Coin Change II
-#include "leetcode.h"
-
-/*
- * given an integer array 'coins' representing cons of different denominations
- * and an integer 'amount' representing a total amount of money. return the
- * number of combinations that make up the amount. if that amount of money
- * cannot be made up by any combination the coins, return 0. you may assume that
- * you have an infinite number of each kind of coin. the answer is guaranteed to
- * fit into a signed 32-bit integer.
- */
-
-class Solution {
-public:
- int change(int amount, vector<int> &coins) {
- vector<int> dp(amount + 1, 0);
- dp[0] = 1;
- for (int i : coins)
- for (int j = i; j <= amount; j++)
- dp[j] += dp[j - i];
- return dp[amount];
- }
-};
-
-int main() {
- Solution obj;
- vector<int> c1 = {1, 2, 5}, c2 = {2}, c3 = {10};
- printf("%d\n", obj.change(5, c1)); // expect: 4
- printf("%d\n", obj.change(3, c2)); // expect: 0
- printf("%d\n", obj.change(10, c3)); // expect: 1
-}
diff --git a/other/combination_sum3.cpp b/other/combination_sum3.cpp
deleted file mode 100644
index bde03a3..0000000
--- a/other/combination_sum3.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<vector<int>> combinationSum3(int k, int n) {
- vector<vector<int>> ans;
- vector<int> sol;
- helper(ans, sol, k, n);
- return ans;
- }
- void print(vector<vector<int>> &ans) {
- for (int i = 0; i < ans.size(); i++)
- for (int j = 0; j < ans.size(); j++)
- cout << ans[i][j] << ' ';
- }
-
-private:
- void helper(vector<vector<int>> &ans, vector<int> sol, int k, int n) {
- if (sol.size() == k && n == 0) {
- ans.push_back(sol);
- return;
- }
- if (sol.size() < k)
- for (int i = sol.empty() ? 1 : sol.back() + 1; i <= 9; ++i) {
- if (n - i < 0)
- break;
- sol.push_back(i);
- helper(ans, sol, k, n - i);
- sol.pop_back();
- }
- }
-};
-
-int main() {
- Solution obj;
- vector<vector<int>> ans;
- obj.print(ans);
-}
diff --git a/other/combination_sum4.cpp b/other/combination_sum4.cpp
deleted file mode 100644
index b05bc96..0000000
--- a/other/combination_sum4.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int combinationSum4(vector<int> &nums, int target) {
- vector<unsigned int> dp(target + 1, 0);
- dp[0] = 1;
- for (int i = 0; i < target; i++) {
- if (!dp[i])
- continue;
- for (int num : nums)
- if (num + i <= target)
- dp[i + num] += dp[i];
- }
- return dp[target];
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {1, 2, 3};
- int target = 4;
- cout << obj.combinationSum4(nums, target);
-}
diff --git a/other/combinations.cpp b/other/combinations.cpp
deleted file mode 100644
index 94d4bfc..0000000
--- a/other/combinations.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-// 77. Combinations
-#include "leetcode.h"
-
-/*
- * given two integers 'n' and 'k', return all possible combinations of 'k'
- * numbers chosen from the range '[1, n]'. you may return the answer in any
- * order
- */
-
-class Solution {
-public:
- vvd combine(int n, int k) {
- vvd ans;
- int i = 0;
- vector<int> p(k, 0);
- while (i >= 0) {
- p[i]++;
- if (p[i] > n)
- --i;
- else if (i == k - 1)
- ans.push_back(p);
- else
- i++, p[i] = p[i - 1];
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- for (auto i : obj.combine(4, 2))
- for (auto j : i)
- printf("%d ", j); // expect: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
- printf("\n");
- for (auto i : obj.combine(1, 1))
- for (auto j : i)
- printf("%d ", j); // expect: [[1]]
- printf("\n");
-}
diff --git a/other/concatenated_words.cpp b/other/concatenated_words.cpp
deleted file mode 100644
index 9263d87..0000000
--- a/other/concatenated_words.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-// 472. Concatenated Words
-#include "leetcode.h"
-
-/*
- * given an array of strings 'words' (without duplicates), return all the
- * concatenated words in the given list of 'words'. a concatenated word is
- * defined as as string that is comprised entirely of at least two shorter
- * words in the given array.
- */
-
-class Solution {
-private:
- struct Trie {
- struct Trie *arr[26];
- bool end = false;
- Trie() {
- memset(arr, 0, sizeof(arr));
- end = false;
- }
- };
- Trie *root;
- void insert(string s) {
- Trie *node = root;
- for (int i = s.length() - 1; i >= 0; i--) {
- char c = s[i];
- if (!node->arr[c - 'a'])
- node->arr[c - 'a'] = new Trie();
- node = node->arr[c - 'a'];
- }
- node->end = true;
- }
-
-public:
- vector<string> findAllConcatenatedWordsInADict(vector<string> &words) {
- sort(words.begin(), words.end(),
- [](string &w1, string &w2) { return (w1.length() <= w2.length()); });
- vector<string> ans;
- root = new Trie();
- for (string w : words) {
- if (w.length() == 0)
- continue;
- vector<bool> dp(w.length() + 1, false);
- dp[0] = true;
- for (int i = 0; i < w.length(); i++) {
- Trie *node = root;
- for (int j = i; j >= 0; j--) {
- if (node->arr[w[j] - 'a'] == NULL)
- break;
- node = node->arr[w[j] - 'a'];
- if (dp[j] && node->end) {
- dp[i + 1] = true;
- break;
- }
- }
- }
- if (dp[w.length()])
- ans.push_back(w);
- insert(w);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<string> words1 = {"cat", "cats", "catsdogcats",
- "dog", "dogcatsdog", "hippopotamuses",
- "rat", "ratcatdogcat"};
- vector<string> words2 = {"cat", "dog", "catdog"};
- for (auto i : obj.findAllConcatenatedWordsInADict(words1))
- cout << i << ' ';
- cout << endl;
- for (auto i : obj.findAllConcatenatedWordsInADict(words2))
- cout << i << ' ';
-}
diff --git a/other/concatenation_binary_num.cpp b/other/concatenation_binary_num.cpp
deleted file mode 100644
index b212c09..0000000
--- a/other/concatenation_binary_num.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int concatenatedBinary(int n) {
- string s = decimalToBinary(n);
- return binaryToDecimal(s);
- }
-
-private:
- int mod = 1000000007;
- string decimalToBinary(int n) {
- string str = "";
- for (int i = n; i >= 1; --i) {
- int j = i;
- while (j) {
- str += (j % 2) + '0';
- j /= 2;
- }
- }
- return str;
- }
- int binaryToDecimal(string n) {
- long long ans = 0, p = 1;
- for (int i = 0; i < n.size(); ++i) {
- long long curr = (n[i] - '0') * p;
- p *= 2;
- p %= mod;
- ans += curr;
- }
- return ans % mod;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.concatenatedBinary(3);
-}
diff --git a/other/construct_array_multiple_sum.cpp b/other/construct_array_multiple_sum.cpp
deleted file mode 100644
index 5d2751d..0000000
--- a/other/construct_array_multiple_sum.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool isPossible(vector<int> &target) {
- long total = 0;
- int i;
- priority_queue<int> pq(target.begin(), target.end());
- for (int i : target)
- total += i;
- while (true) {
- i = pq.top();
- pq.pop();
- total -= i;
- if (i == 1 || total == 1)
- return true;
- if (i < total || total == 0 || i % total == 0)
- return false;
- i %= total;
- total += i;
- pq.push(i);
- }
- }
-};
-
-int main() {
- Solution obj;
- vector<int> target = {9, 3, 5};
- cout << obj.isPossible(target);
-}
diff --git a/other/construct_bt_io_po.cpp b/other/construct_bt_io_po.cpp
deleted file mode 100644
index 6fb9163..0000000
--- a/other/construct_bt_io_po.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-// 106. Construct Binary Tree from Inorder and Postorder Traversal
-#include "leetcode.h"
-
-/*
- * given two integer arrays 'inorder' and 'postorder', where 'inorder' is the
- * inorder traversal of a binary tree, and 'postorder' is the postorder
- * traversal of the same tree, construct and return the binary tree.
- */
-
-class Solution {
-public:
- TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
- int n = inorder.size(), po_idx = n - 1;
- for (int i = 0; i < n; i++)
- um[inorder[i]] = i;
- return construct(inorder, postorder, 0, n - 1, po_idx);
- }
-
-private:
- unordered_map<int, int> um;
- TreeNode *construct(vector<int> &inorder, vector<int> &postorder,
- int io_start, int io_end, int po_idx) {
- if (io_start > io_end)
- return nullptr;
- TreeNode *root = new TreeNode(postorder[po_idx--]);
- int io_idx = um[root->val];
- root->right = construct(inorder, postorder, io_idx + 1, io_end, po_idx);
- root->left = construct(inorder, postorder, io_start, io_idx - 1, po_idx);
- return root;
- }
-};
diff --git a/other/construct_quad_tree.cpp b/other/construct_quad_tree.cpp
deleted file mode 100644
index 845cefe..0000000
--- a/other/construct_quad_tree.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-// 427. Construct Quad Tree
-#include <bits/stdc++.h>
-using namespace std;
-#define vvd(data) vector<vector<data>>
-
-/*
- * wtf this is right pants for a medium
- */
-
-class Node {
-public:
- bool val;
- bool isLeaf;
- Node *topLeft;
- Node *topRight;
- Node *bottomLeft;
- Node *bottomRight;
- Node() {
- val = false;
- isLeaf = false;
- topLeft = NULL;
- topRight = NULL;
- bottomLeft = NULL;
- bottomRight = NULL;
- }
- Node(bool _val, bool _isLeaf) {
- val = _val;
- isLeaf = _isLeaf;
- topLeft = NULL;
- topRight = NULL;
- bottomLeft = NULL;
- bottomRight = NULL;
- }
- Node(bool _val, bool _isLeaf, Node *_topLeft, Node *_topRight,
- Node *_bottomLeft, Node *_bottomRight) {
- val = _val;
- isLeaf = _isLeaf;
- topLeft = _topLeft;
- topRight = _topRight;
- bottomLeft = _bottomLeft;
- bottomRight = _bottomRight;
- }
-};
-
-class Solution {
-public:
- Node *construct(vvd & grid) {
- grid_v = move(grid);
- leafNodes_a[0] = new Node(false, true, nullptr, nullptr, nullptr, nullptr);
- leafNodes_a[1] = new Node(true, true, nullptr, nullptr, nullptr, nullptr);
- return construct(0, 0, grid_v.size());
- }
-
-private:
- vvd grid_v;
- array<Node *, 2> leafNodes_a;
- Node *construct(int r, int c, int s) {
- if (s == 1)
- return leafNodes_a[grid_v[r][c]];
- s /= 2;
- Node *tl = construct(r, c, s);
- Node *tr = construct(r, c + s, s);
- Node *bl = construct(r + s, c, s);
- Node *br = construct(r + s, c + s, s);
- if (tl == tr && tl == bl && tl == br)
- return tl;
- return new Node(false, false, tl, tr, bl, br);
- }
-};
-
-int main() {
- Solution obj;
- vvd grid = {{0, 1}, {1, 0}};
- cout << obj.construct(grid); // expect: [[0,1],[1,0],[1,1],[1,1],[1,0]]
-}
diff --git a/other/construct_string_binary_tree.cpp b/other/construct_string_binary_tree.cpp
deleted file mode 100644
index a63e3c9..0000000
--- a/other/construct_string_binary_tree.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string tree2str(TreeNode *root) {
- if (!root)
- return "";
- string ans = to_string(root->val);
- if (root->left || root->right) {
- ans.push_back('(');
- ans += tree2str(root->left);
- ans.push_back(')');
- }
- if (root->right) {
- ans.push_back('(');
- ans += tree2str(root->right);
- ans.push_back(')');
- }
- return ans;
- }
-};
diff --git a/other/contains_duplicate2.cpp b/other/contains_duplicate2.cpp
deleted file mode 100644
index 9af7758..0000000
--- a/other/contains_duplicate2.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool containsNearbyDuplicate(vector<int> &nums, int k) {
- unordered_map<int, int> um;
- for (int i = 0; i < nums.size(); i++) {
- if (um.count(nums[i]))
- if (abs(i - um[nums[i]]) <= k)
- return true;
- um[nums[i]] = i;
- }
- return false;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {1, 2, 3, 1};
- if (obj.containsNearbyDuplicate(nums, 3))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/contains_duplicate2.rs b/other/contains_duplicate2.rs
deleted file mode 100644
index b016e21..0000000
--- a/other/contains_duplicate2.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-use std::collections::HashMap;
-struct Solution;
-
-impl Solution {
- pub fn contains_nearby_duplicate(nums: Vec<i32>, k: i32) -> bool {
- let mut hm = HashMap::new();
- for (i, n) in nums.iter().enumerate() {
- if let Some(j) = hm.insert(n, i) {
- if (i as i32) - (j as i32) <= k {
- return true;
- }
- }
- }
- false
- }
-}
-
-fn main() {
- let nums = vec![1,2,3,1];
- print!("{}", Solution::contains_nearby_duplicate(nums, 3));
-}
diff --git a/other/contains_duplicate3.cpp b/other/contains_duplicate3.cpp
deleted file mode 100644
index 6e1467c..0000000
--- a/other/contains_duplicate3.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-// 220. Contains Duplicate III
-#include "leetcode.h"
-
-/*
- * given an integer array 'nums' and two integers 'index_diff'
- * and 'value_diff'. find a pai of indices '(i, j)' such that:
- * i != j
- * abs(i - j) <= index_diff
- * abs(num[i] - num[j]) <= value_diff
- * return true if such pair exists or false otherwise
- */
-
-class Solution {
-public:
- bool containsNearbyAlmostDuplicate(vector<int> &nums, int index_diff,
- int value_diff) {
- int n = nums.size();
- if (n == 0 || index_diff < 0 || value_diff < 0)
- return false;
- unordered_map<int, int> buckets;
- for (int i = 0; i < n; i++) {
- int b = nums[i] / ((long)value_diff + 1);
- if (nums[i] < 0)
- --b;
- if (buckets.find(b) != buckets.end())
- return true;
- else {
- buckets[b] = nums[i];
- if (buckets.find(b - 1) != buckets.end() &&
- (long)nums[i] - buckets[b - 1] <= value_diff)
- return true;
- if (buckets.find(b + 1) != buckets.end() &&
- (long)buckets[b + 1] - nums[i] <= value_diff)
- return true;
- if (buckets.size() > index_diff) {
- int remove = nums[i - index_diff] / ((long)value_diff + 1);
- if (nums[i - index_diff] < 0)
- --remove;
- buckets.erase(remove);
- }
- }
- }
- return false;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 2, 3, 1}, n2 = {1, 5, 9, 1, 5, 9};
- printf("%d\n", obj.containsNearbyAlmostDuplicate(n1, 3, 0)); // expect: 1
- printf("%d\n", obj.containsNearbyAlmostDuplicate(n2, 2, 3)); // expect: 0
-}
diff --git a/other/contains_virus.cpp b/other/contains_virus.cpp
deleted file mode 100644
index d0040c5..0000000
--- a/other/contains_virus.cpp
+++ /dev/null
@@ -1,77 +0,0 @@
-// 749. Contain Virus
-#include "leetcode.h"
-
-class Cluster {
-public:
- set<pair<int, int>> c;
- set<pair<int, int>> uc;
- int w_cnt = 0;
-};
-
-class Solution {
-public:
- int containsVirus(vvd & isInfected) {
- int n = isInfected.size(), m = isInfected[0].size(), ans = 0;
- while (1) {
- vvd(bool) vis(n, vector<bool>(m));
- auto cmp = [](const Cluster &A, const Cluster &B) {
- return A.uc.size() < B.uc.size();
- };
- priority_queue<Cluster, vector<Cluster>, decltype(cmp)> pq(cmp);
- for (int i = 0; i < n; i++)
- for (int j = 0; j < m; j++)
- if (!vis[i][j] && isInfected[i][j] == 1) {
- Cluster c;
- dfs(isInfected, i, j, vis, c);
- pq.push(c);
- }
- if (pq.size() == 0)
- break;
- Cluster k = pq.top();
- pq.pop();
- for (auto x : k.c)
- isInfected[x.first][x.second] = -1;
- ans += k.w_cnt;
- while (!pq.empty()) {
- Cluster k1 = pq.top();
- pq.pop();
- for (auto x : k1.uc)
- isInfected[x.first][x.second] = 1;
- }
- }
- return ans;
- }
-
-private:
- void dfs(vvd & grid, int i, int j, vvd(bool) & vis, Cluster &cl) {
- if (i == grid.size() || i < 0 || j < 0 || j == grid[0].size() ||
- vis[i][j] || grid[i][j] == -1)
- return;
- if (grid[i][j] == 0) {
- cl.w_cnt++;
- cl.uc.insert({i, j});
- return;
- }
- cl.c.insert({i, j});
- vis[i][j] = true;
- dfs(grid, i + 1, j, vis, cl); // above
- dfs(grid, i - 1, j, vis, cl); // below
- dfs(grid, i, j + 1, vis, cl); // right
- dfs(grid, i, j - 1, vis, cl); // left
- }
-};
-
-int main() {
- Solution obj;
- vvd isInfected1 = {{0, 1, 0, 0, 0, 0, 0, 1},
- {0, 1, 0, 0, 0, 0, 0, 1},
- {0, 0, 0, 0, 0, 0, 0, 1},
- {0, 0, 0, 0, 0, 0, 0, 0}};
- vvd isInfected2 = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}};
- vvd isInfected3 = {{1, 1, 1, 0, 0, 0, 0, 0, 0},
- {1, 0, 1, 0, 1, 1, 1, 1, 1},
- {1, 1, 1, 0, 0, 0, 0, 0, 0}};
- cout << obj.containsVirus(isInfected1) << endl; // expect: 10
- cout << obj.containsVirus(isInfected2) << endl; // expect: 4
- cout << obj.containsVirus(isInfected3) << endl; // expect: 13
-}
diff --git a/other/continuous_subarr_sum.cpp b/other/continuous_subarr_sum.cpp
deleted file mode 100644
index ceaf3ce..0000000
--- a/other/continuous_subarr_sum.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool checkSubarraySum(vector<int> &nums, int k) {
- unordered_map<int, int> um;
- int s = 0;
- um[0] = -1;
- for (int i = 0; i < nums.size(); i++) {
- s += nums[i];
- if (k != 0)
- s %= k;
- if (um.find(s) != um.end()) {
- if (i - um[s] > 1)
- return true;
- } else
- um[s] = i;
- }
- return false;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {23, 2, 4, 6, 7};
- int k = 6;
- if (obj.checkSubarraySum(nums, k))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/continuous_subarr_sum.rs b/other/continuous_subarr_sum.rs
deleted file mode 100644
index 2e1567e..0000000
--- a/other/continuous_subarr_sum.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-use std::collections::HashSet;
-struct Solution;
-
-impl Solution {
- pub fn check_subarray_sum(nums: Vec<i32>, k: i32) -> bool {
- let mut mod_k_val = HashSet::<i32>::from([0]);
- let mut prefix_sum = nums[0] % k;
- for val in nums.into_iter().skip(1) {
- let tba = prefix_sum;
- prefix_sum = (prefix_sum + val) % k;
- if mod_k_val.contains(&prefix_sum) {
- return true;
- }
- mod_k_val.insert(tba);
- }
- false
- }
-}
-
-fn main() {
- let nums = vec![18,84,4,38,11,248];
- let k = 6;
- print!("{}", Solution::check_subarray_sum(nums, k));
-}
diff --git a/other/convert_sorted_bst.cpp b/other/convert_sorted_bst.cpp
deleted file mode 100644
index 8b5b656..0000000
--- a/other/convert_sorted_bst.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-// 109. Convert Sorted List to Binary Search Tree
-#include "leetcode.h"
-
-/*
- * given 'head' of a singly linked list where elements are sorted in ascending
- * order convert it to a height balanced binary search tree. meaning the depth
- * of two sub- trees of every node never differs by more than one.
- */
-
-class Solution {
-public:
- TreeNode *sortedListToBST(ListNode *head) {
- if (!head)
- return NULL;
- if (!head->next)
- return new TreeNode(head->val);
- auto slow = head, fast = head, pre = head;
- while (fast && fast->next) {
- pre = slow;
- slow = slow->next;
- fast = fast->next->next;
- }
- pre->next = 0;
- TreeNode *root = new TreeNode(slow->val);
- root->left = sortedListToBST(head);
- root->right = sortedListToBST(slow->next);
- return root;
- }
-};
diff --git a/other/cost_hire_k_worker.cpp b/other/cost_hire_k_worker.cpp
deleted file mode 100644
index 5bb0860..0000000
--- a/other/cost_hire_k_worker.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-// 2462. Total Cost to Hire K Workers
-#include "leetcode.h"
-
-/*
- * given a 0-indexed integer array 'costs' where 'costs[i]' is the cost of
- * hiring the i'th worker. you are also given two integers 'k, candidates'. we
- * want to hire exactly 'k' workders according to the following rules:
- * - you will run 'k' sessions and hire exactly one worker in each session
- * - in each hiring session, choose the worker with the lowest cost from either
- * the first 'candidates' workers or the last 'candidates' workers. break the
- * tie by the smallest index.
- * - if there are fewer than candidates workers remaining, choose the workder
- * with the lowest cost among them. break the tie by the smallest index.
- * - a worker can only be chosen once
- * return the total cost to hire eactly 'k' workers.
- */
-
-class Solution {
-public:
- long long totalCost(vector<int> &costs, int k, int candidates) {
- int i = 0, j = costs.size() - 1;
- priority_queue<int, vector<int>, greater<int>> pq1, pq2;
- long long ans;
- while (k--) {
- while (pq1.size() < candidates && i <= j)
- pq1.push(costs[i++]);
- while (pq2.size() < candidates && i <= j)
- pq2.push(costs[j--]);
- int t1 = pq1.size() > 0 ? pq1.top() : INT_MAX;
- int t2 = pq2.size() > 0 ? pq2.top() : INT_MAX;
- if (t1 <= t2) {
- ans += t1;
- pq1.pop();
- } else {
- ans += t2;
- pq2.pop();
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> c1 = {17, 12, 10, 2, 7, 2, 11, 20, 8}, c2 = {1, 2, 4, 1};
- printf("%lld\n", obj.totalCost(c1, 3, 4)); // expect: 11
- printf("%lld\n", obj.totalCost(c2, 3, 3)); // expect: 4
-}
diff --git a/other/count_all_pickup_delivery.cpp b/other/count_all_pickup_delivery.cpp
deleted file mode 100644
index 0d82d5a..0000000
--- a/other/count_all_pickup_delivery.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-#include "leetcode.h"
-#define lli long long int
-
-class Solution {
-public:
- int countOrders(int n) {
- lli mod = 1e9 + 7;
- vector<lli> dp(n + 2);
- dp[1] = 1;
- dp[2] = 6;
- for (lli i = 3; i <= n; i++) {
- lli x = 2 * i - 1;
- lli combs = x * (x + 1) / 2;
- dp[i] = (dp[i - 1] * combs) % mod;
- }
- return dp[n];
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.countOrders(2);
-}
diff --git a/other/count_and_say.cpp b/other/count_and_say.cpp
deleted file mode 100644
index a1086b4..0000000
--- a/other/count_and_say.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string countAndSay(int n) {
- if (n == 0)
- return "";
- string ans = "1";
- while (--n) {
- string curr = "";
- for (int i = 0; i < ans.size(); i++) {
- int count = 1;
- while ((i + 1 < ans.size()) && (ans[i] == ans[i + 1]))
- count++, i++;
- curr += to_string(count) + ans[i];
- }
- ans = curr;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.countAndSay(4);
-}
diff --git a/other/count_and_say.rs b/other/count_and_say.rs
deleted file mode 100644
index 55a1fec..0000000
--- a/other/count_and_say.rs
+++ /dev/null
@@ -1,32 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn count_and_say(n: i32) -> String {
- if n == 1 {
- return "1".to_string();
- }
- let mut output: Vec<char> = vec![];
- let mut last_char = ' ';
- let mut count: u8 = '0' as u8;
- for char in Solution::count_and_say(n - 1).chars().into_iter() {
- if last_char == ' ' {
- last_char = char;
- count = '1' as u8;
- } else if char == last_char {
- count += 1;
- } else {
- output.push(count as char);
- output.push(last_char);
- last_char = char;
- count = '1' as u8;
- }
- }
- output.push(count as char);
- output.push(last_char);
- output.into_iter().collect()
- }
-}
-
-fn main() {
- print!("{}", Solution::count_and_say(4));
-}
diff --git a/other/count_complete_tree_node.cpp b/other/count_complete_tree_node.cpp
deleted file mode 100644
index 5929110..0000000
--- a/other/count_complete_tree_node.cpp
+++ /dev/null
@@ -1,18 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int countNodes(TreeNode *root) {
- if (!root)
- return 0;
- int l = 1, r = 1;
- TreeNode *ptr_r = root, *ptr_l = root;
- while (ptr_l = ptr_l->left)
- l++;
- while (ptr_r = ptr_r->right)
- r++;
- if (l == r)
- return pow(2, l) - 1;
- return 1 + countNodes(root->left) + countNodes(root->right);
- }
-};
diff --git a/other/count_complete_tree_node.rs b/other/count_complete_tree_node.rs
deleted file mode 100644
index 4859862..0000000
--- a/other/count_complete_tree_node.rs
+++ /dev/null
@@ -1,51 +0,0 @@
-#[derive(Debug, PartialEq, Eq)]
-pub struct TreeNode {
- pub val: i32,
- pub left: Option<RC<RefCell<TreeNode>>>,
- pub right: Option<RC<RefCell<TreeNode>>>
-}
-
-impl TreeNode {
- #[inline]
- pub fn new(val: i32) -> Self {
- TreeNode {
- val,
- left: None,
- right: None
- }
- }
-}
-
-use std::rc::Rc;
-use std::cell::RefCell;
-impl Solution {
- pub fn count_nodes(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
- if let Some(r) = root {
- let ld = {
- let mut h = 1;
- let mut node = r.borrow().left.clone();
- while let Some(n) = node {
- h += 1;
- node = n.borrow().left.clone();
- }
- h
- };
- let rd = {
- let mut h = 1;
- let mut node = r.borrow().right.clone();
- while let Some(n) = node {
- h += 1;
- node = n.borrow().right.clone();
- }
- h
- };
- if ld == rd {
- 2i32.pow(ld) - 1
- } else {
- 1 + Solution::count_nodes(r.borrow().left.clone()) + Solution::count_nodes(r.borrow().right.clone())
- }
- } else {
- 0
- }
- }
-}
diff --git a/other/count_distinct_int.cpp b/other/count_distinct_int.cpp
deleted file mode 100644
index ff5c1d6..0000000
--- a/other/count_distinct_int.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 2442. Count Number of Distinct Integers After Reverse Operations
-#include "leetcode.h"
-
-/*
- * array nums contains positive integers
- * take each integer in array and reverse its digits (eg. 13 -> 31)
- * then *add* it to end of array. return number of distinct integers.
- * [1,13,10,12,31] becomes [1,13,10,12,31,1,31,1,21,13]
- * and total num of distinct ints = 6
- */
-
-class Solution {
-public:
- int countDistinctIntegers(vector<int> &nums) {
- // unordered set constructor to insert 'nums'
- // note: a set only maintains unique values in it
- unordered_set<int> us(nums.begin(), nums.end());
- // find reverse of every num
- for (auto i : nums) {
- int n = 0;
- while (i) {
- int rem = i % 10;
- n = n * 10 + rem;
- i /= 10;
- }
- // insert (to end) reverse
- us.insert(n);
- }
- // we can simply return the size since
- // every element in a set is unique
- return us.size();
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums1 = {1, 13, 10, 12, 31}, nums2 = {2, 2, 2};
- cout << obj.countDistinctIntegers(nums1) << endl; // expect: 6
- cout << obj.countDistinctIntegers(nums2) << endl; // expect: 1
-}
diff --git a/other/count_distinct_int.rs b/other/count_distinct_int.rs
deleted file mode 100644
index 32ce622..0000000
--- a/other/count_distinct_int.rs
+++ /dev/null
@@ -1,35 +0,0 @@
-//2442. Count Number of Distinct Integers After Reverse Operations
-use std::collections::HashSet;
-struct Solution;
-
-/*
- * array nums contains positive integers
- * take each integer in array and reverse its digits (eg. 13 -> 31)
- * then *add* it to end of array. return number of distinct integers.
- * [1,13,10,12,31] becomes [1,13,10,12,31,1,31,1,21,13]
- * and total num of distinct ints = 6
- */
-
-impl Solution {
- pub fn count_distinct_integers(nums: Vec<i32>) -> i32 {
- let mut hs: HashSet<i32> = nums.iter().map(|&n| Self::reverse(n)).collect();
- hs.extend(nums.iter());
- hs.len() as i32
- }
- fn reverse(mut n: i32) -> i32 {
- let mut rev: i32 = 0;
- while n > 0 {
- rev *= 10;
- rev += n % 10;
- n /= 10;
- }
- rev
- }
-}
-
-fn main() {
- let nums1 = vec![1,13,10,12,31];
- let nums2 = vec![2,2,2];
- println!("{}", Solution::count_distinct_integers(nums1)); //expect: 6
- println!("{}", Solution::count_distinct_integers(nums2)); //expect: 1
-}
diff --git a/other/count_good_nodes_bst.cpp b/other/count_good_nodes_bst.cpp
deleted file mode 100644
index b6b9b3e..0000000
--- a/other/count_good_nodes_bst.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int goodNodes(TreeNode *root) {
- dfs(root, root->val);
- return count;
- }
-
-private:
- int count = 0;
- void dfs(TreeNode *node, int currMax) {
- if (!node)
- return;
- if (node->val >= currMax) {
- count++;
- currMax = node->val;
- }
- dfs(node->left, currMax);
- dfs(node->right, currMax);
- }
-};
diff --git a/other/count_ints_even_sum.cpp b/other/count_ints_even_sum.cpp
deleted file mode 100644
index 83070c6..0000000
--- a/other/count_ints_even_sum.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-// 2180. Count Integers With Even Digit Sum
-#include "leetcode.h"
-
-/*
- * given a positive integer 'num', return the number of positive integersless
- * than or equal to 'num' whose digit sums are event. the digitsum of a positive
- * integer is the sum of all of its digits.
- */
-
-class Solution {
-public:
- int countEven(int num) {
- int tmp = num, sum = 0;
- while (num > 0) {
- sum += num % 10;
- num /= 10;
- }
- return sum % 2 == 0 ? tmp / 2 : (tmp - 1) / 2;
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.countEven(4)); // expect: 2
- printf("%d\n", obj.countEven(30)); // expect: 14
-}
diff --git a/other/count_negative_num_matrix.cpp b/other/count_negative_num_matrix.cpp
deleted file mode 100644
index f7c776d..0000000
--- a/other/count_negative_num_matrix.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// 1351. Count Negative Numbers in a Sorted Matrix
-#include "leetcode.h"
-
-// given an 'm x n' matrix 'grid' which is sorted in non-increasing order both
-// row-wise and column-wise, return the number of negative numbers in 'grid'
-
-class Solution {
-public:
- int countNegatives(vvd & grid) {
- int ans = 0;
- for (vector<int> row : grid)
- for (int i : row)
- if (i < 0)
- ans++;
- return ans;
- for (vector<int> row : grid)
- ans += upper_bound(row.rbegin(), row.rend(), -1) - row.rbegin();
- return ans;
- int m = grid.size(), n = grid[0].size(), r = 0, c = n - 1;
- while (r < m) {
- while (c >= 0 && grid[r][c] < 0)
- c--;
- ans += n - c - 1;
- r++;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd
- g1 = {{4, 3, 2, -1}, {3, 2, 1, -1}, {1, 1, -1, -2}, {-1, -1, -2, -3}};
- vvd g2 = {{3, 2}, {1, 0}};
- printf("%d\n", obj.countNegatives(g1)); // expect: 8
- printf("%d\n", obj.countNegatives(g2)); // expect: 0
-}
diff --git a/other/count_odd_num_interval_range.cpp b/other/count_odd_num_interval_range.cpp
deleted file mode 100644
index f690d01..0000000
--- a/other/count_odd_num_interval_range.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-// 1523. Count Odd Numbers in an Interval Range
-#include "leetcode.h"
-
-// given two non-negative integers 'low' and 'high' return the
-// count of odd numbers * between 'low' and 'high' (incusively)
-
-class Solution {
-public:
- int countOdds(int low, int high) {
- int ans = 0;
- if (low % 2) {
- ans += (high - low) / 2;
- ans++;
- } else
- ans += ceil(double(high - low) / 2.0);
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.countOdds(3, 7) << endl; // expect: 3
- cout << obj.countOdds(8, 10) << endl; // expect: 1
-}
diff --git a/other/count_possible_routes.cpp b/other/count_possible_routes.cpp
deleted file mode 100644
index 228fb2e..0000000
--- a/other/count_possible_routes.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-// 1575. Count All Possible Routes
-#include "leetcode.h"
-
-/*
- * given an array of disticnt positive integers locations where 'locations[i]'
- * represents the position of city 'i'. you are lso given integers 'start,
- * finish, fuel' representing the starting city, ending city, and the initial
- * amount of fuel you have, respectively. at each step if you are in city 'i',
- * you can pick any city 'j' such that 'j != i' and '0 <= j < locations.length'
- * and move to city 'j'. moving city 'i' to 'j' reduces the amount of fuel you
- * have by |locations[i] - locations[j]|. Please notice that |x| denotes the
- * absolute value of x. notice that fuel cannot become negative at any point in
- * time. and that are allowed to visit any city more than once (including
- * 'start' and 'finish'). return the count of all possible routes from 'start'
- * to 'finish'. since the answer may be large, return it modulo 10^9+7.
- */
-
-class Solution {
-public:
- int countRoutes(vector<int> &locations, int start, int finish, int fuel) {
- int n = locations.size(), mod = 1e9 + 7, ans = 0;
- vvd dp(n, vector<int>(fuel + 1));
- dp[start][fuel] = 1;
- for (int f = fuel; f >= 0; f--)
- for (int i = 0; i < n; i++)
- for (int j = 0; j < n; j++) {
- int diff = abs(locations[i] - locations[j]);
- if (i != j && f >= diff)
- dp[j][f - diff] = (dp[j][f - diff] % mod + dp[i][f] % mod) % mod;
- }
- for (int i = 0; i <= fuel; i++)
- ans = (ans % mod + dp[finish][i] % mod) % mod;
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> l1 = {2, 3, 6, 8, 4}, l2 = {4, 3, 1};
- printf("%d\n", obj.countRoutes(l1, 1, 3, 5)); // expect: 4
- printf("%d\n", obj.countRoutes(l2, 1, 0, 6)); // expect: 5
-}
diff --git a/other/count_sorted_vowel.cpp b/other/count_sorted_vowel.cpp
deleted file mode 100644
index e113311..0000000
--- a/other/count_sorted_vowel.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int countVowelStrings(int n) {
- int a = 1, e = 1, i = 1, o = 1, u = 1;
- while (--n) {
- o += u;
- i += o;
- e += i;
- a += e;
- }
- return a + e + i + o + u;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.countVowelStrings(1);
-}
diff --git a/other/count_unreach_node.cpp b/other/count_unreach_node.cpp
deleted file mode 100644
index bf7413b..0000000
--- a/other/count_unreach_node.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-// 2316. Count Unreachable Pairs of Nodes in an Undirected Graph
-#include "leetcode.h"
-
-/*
- * given integer 'n', there is undirected graph with 'n' nodes, numbered 0 to 'n
- * - 1' given 2d integer array 'edges' where 'edges[i] = [ai bi]' denotes that
- * there exists an undirected edge connecting nodes ai and bi. return number of
- * pairs of different nodes that are unreachable from each other
- */
-
-class Solution {
-public:
- long long countPairs(int n, vvd & edges) {
- unordered_map<int, vector<int>> m;
- for (int i = 0; i < edges.size(); i++) {
- m[edges[i][0]].push_back(edges[i][0]);
- m[edges[i][1]].push_back(edges[i][1]);
- }
- long long ans = ((long long)n * (n - 1)) / 2;
- vector<int> vis(n, 0);
- for (int i = 0; i < n; i++) {
- if (vis[i] == 0) {
- long long cnt = 0;
- dfs(i, m, cnt, vis);
- ans -= (cnt * (cnt - 1)) / 2;
- }
- }
- return ans;
- }
-
-private:
- void dfs(int n, unordered_map<int, vector<int>> m, long long cnt,
- vector<int> vis) {
- vis[n] = 1;
- cnt++;
- for (auto i : m[n])
- if (vis[i] == 0)
- dfs(i, m, cnt, vis);
- }
-};
-
-int main() {
- Solution obj;
- vvd e1 = {{0, 1}, {0, 2}, {1, 2}};
- vvd e2 = {{0, 2}, {0, 5}, {2, 4}};
- printf("%lld\n", obj.countPairs(3, e1)); // expect: 0
- printf("%lld\n", obj.countPairs(7, e2)); // expect: 14
-}
diff --git a/other/count_vowels_permutation.cpp b/other/count_vowels_permutation.cpp
deleted file mode 100644
index 807a1f4..0000000
--- a/other/count_vowels_permutation.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "leetcode.h"
-class Solution {
-public:
- int countVowelPermutation(int n) {
- int ans = 0;
- memo.resize(n + 1, vector<int>(5, -1));
- for (int i = 0; i < 5; i++)
- ans += dp(n, i), ans %= mod;
- return ans;
- }
-
-private:
- int mod = 1e9 + 7;
- vector<vector<int>> relation = {{1}, {0, 2}, {0, 1, 3, 4}, {2, 4}, {0}}, memo;
- int dp(int n, int v) {
- if (n == 1)
- return 1;
- if (memo[n][v] != -1)
- return memo[n][v];
- memo[n][v] = 0;
- for (int &i : relation[v])
- memo[n][v] += dp(n - 1, i), memo[n][v] %= mod;
- return memo[n][v];
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.countVowelPermutation(1);
-}
diff --git a/other/count_ways_build_strs.cpp b/other/count_ways_build_strs.cpp
deleted file mode 100644
index d388b2f..0000000
--- a/other/count_ways_build_strs.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-// 2466. Count Ways To Build Good Strings
-#include "leetcode.h"
-
-/*
- * given the integers 'zero, one, low, and high', we can construct a string by
- * starting with an empty string, and then at each step perform either of the
- * following opperations:
- * - append the character 0 'zero' times
- * - append the character 1 'one' times
- * this can be performed any number of times. a good string is a string
- * constructed by the above process having a length between 'low' and 'high'
- * (inclusive). return the number of different good strings that can be
- * constructed. return modulo 10^9+7.
- */
-
-class Solution {
-public:
- int countGoodStrings(int low, int high, int zero, int one) {
- int mod = 1e9 + 7, ans = 0;
- vector<int> dp(high + 1, 0);
- dp[0] = 1;
- for (int i = 1; i <= high; i++) {
- if (i >= one)
- dp[i] = (dp[i] + dp[i - one]) % mod;
- if (i >= zero)
- dp[i] = (dp[i] + dp[i - zero]) % mod;
- if (i >= low)
- ans = (ans + dp[i]) % mod;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.countGoodStrings(3, 3, 1, 1)); // expect: 8
- printf("%d\n", obj.countGoodStrings(2, 3, 1, 2)); // expect: 5
-}
diff --git a/other/couples_holding_hands.cpp b/other/couples_holding_hands.cpp
deleted file mode 100644
index 7c3069a..0000000
--- a/other/couples_holding_hands.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-// 765. Couples Holding Hands
-#include "leetcode.h"
-
-/*
- * there are 'n' couples sitting '2n' seats arranged in a row and want to hold
- * hands. the people and seats are represented by an integer array 'row' where
- * 'row[i]' is the id of the person sitting in the i'th seat. the couples are
- * numbered in order, the first couple being '(0, 1)', the second couple being
- * '(2, 3)', and so on with the last couple being '(2n -2, 2n -1)'. return the
- * minimum number of swaps so that every couple is sitting side by side. a swap
- * consists of choosing any two people then they stand up and switch seats.
- */
-
-class Solution {
-public:
- int minSwapsCouples(vector<int> &row) {
- int ans = 0, n = row.size();
- vector<int> ptn(n, 0), pos(n, 0);
- for (int i = 0; i < n; i++) {
- ptn[i] = (!(i % 2) ? i + 1 : i - 1);
- pos[row[i]] = i;
- }
- for (int i = 0; i < n; i++)
- for (int j = ptn[pos[ptn[row[i]]]]; i != j; j = ptn[pos[ptn[row[i]]]]) {
- swap(row[i], row[j]);
- swap(pos[row[i]], pos[row[j]]);
- ans++;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> r1 = {0, 2, 1, 3}, r2 = {3, 2, 0, 1};
- printf("%d\n", obj.minSwapsCouples(r1)); // expect: 1
- printf("%d\n", obj.minSwapsCouples(r2)); // expect: 0
-}
diff --git a/other/course_schedule.cpp b/other/course_schedule.cpp
deleted file mode 100644
index 4a249d2..0000000
--- a/other/course_schedule.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-// 207. Course Schedule
-#include "leetcode.h"
-
-/*
- * there are a total of 'num_courses' courses you have to take labeled from 0 to
- * 'num_courses - 1'. you are given an array 'prerequisites' where
- * 'prerequisites[i] = [ai, bi]' indicates that you must take course 'bi' first
- * if you want to take course 'ai'. return true if you can finish all courses,
- * otherwise, return false
- */
-
-class Solution {
- bool is_cycle(vector<int> adj[], vector<int> &vis, int id) {
- if (vis[id] == 1)
- return true;
- if (!vis[id]) {
- vis[id] = 1;
- for (auto edge : adj[id])
- if (is_cycle(adj, vis, edge))
- return true;
- }
- vis[id] = 2;
- return false;
- }
-
-public:
- bool canFinish(int num_courses, vvd & prerequisites) {
- vector<int> adj[num_courses];
- for (auto edge : prerequisites)
- adj[edge[1]].push_back(edge[0]);
- vector<int> vis(num_courses, 0);
- for (int i = 0; i < num_courses; i++)
- if (is_cycle(adj, vis, i))
- return false;
- return true;
- }
-};
-
-int main() {
- Solution obj;
- vvd p1 = {{1, 0}}, p2 = {{1, 0}, {0, 1}};
- printf("%d\n", obj.canFinish(2, p1)); // expect: 1
- printf("%d\n", obj.canFinish(2, p2)); // expect: 0
-}
diff --git a/other/course_schedule_3.cpp b/other/course_schedule_3.cpp
deleted file mode 100644
index e13d2ca..0000000
--- a/other/course_schedule_3.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int scheduleCourse(vector<vector<int>> &courses) {
- int time = 0;
- priority_queue<int> pq;
- sort(courses.begin(), courses.end(), compare);
- for (int i = 0; i < courses.size(); i++) {
- if (time + courses[i][0] <= courses[i][1]) {
- time += courses[i][0];
- pq.push(courses[i][0]);
- } else {
- if (!pq.empty() && pq.top() > courses[i][0]) {
- pq.pop();
- time -= pq.top();
- time += courses[i][0];
- pq.push(courses[i][0]);
- }
- }
- }
- return pq.size();
- }
-
-private:
- static bool compare(vector<int> a, vector<int> b) { return a[1] < b[1]; }
-};
diff --git a/other/create_bt_from_desc.cpp b/other/create_bt_from_desc.cpp
deleted file mode 100644
index 9ad6b4a..0000000
--- a/other/create_bt_from_desc.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 2196. Create Binary Tree From Descriptions
-#include "leetcode.h"
-
-/*
- * you are given a 2d integer array 'descriptions' where 'descriptions[i] =
- * [parent_i, child_i, isleft_i]' indicates that 'parent_i' is the parent of
- * 'child_i', in a binary tree of unique values. construct the binary tree
- * described by 'descriptions' and return its root. the test cases will be
- * generated such that the binary tree is valid.
- */
-
-class Solution {
-public:
- TreeNode *createBinaryTree(vector<vector<int>> &descriptions) {
- unordered_map<int, TreeNode *> get_node;
- unordered_map<int, bool> is_child;
- for (auto &i : descriptions) {
- if (!get_node.count(i[0])) {
- TreeNode *par = new TreeNode(i[0]);
- get_node[i[0]] = par;
- }
- if (!get_node.count(i[1])) {
- TreeNode *child = new TreeNode(i[1]);
- get_node[i[1]] = child;
- }
- if (i[2] == 1)
- get_node[i[0]]->left = get_node[i[1]];
- else
- get_node[i[0]]->right = get_node[i[1]];
- is_child[i[1]] = true;
- }
- TreeNode *ans = NULL;
- for (auto &i : descriptions)
- if (!is_child[i[0]]) {
- ans = get_node[i[0]];
- break;
- }
- return ans;
- }
-};
diff --git a/other/daily_temps.cpp b/other/daily_temps.cpp
deleted file mode 100644
index e244252..0000000
--- a/other/daily_temps.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> dailyTemperatures(vector<int> &temperatures) {
- int n = temperatures.size();
- vector<int> nge(n, 0);
- stack<int> stk{};
- for (int i = n - 1; i >= 0; --i) {
- while (!stk.empty() && temperatures[stk.top()] <= temperatures[i])
- stk.pop();
- if (!stk.empty())
- nge[i] = stk.top() - i;
- stk.push(i);
- }
- return nge;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> t1 = {73, 74, 75, 71, 69, 72, 76, 73};
- vector<int> t2 = {30, 40, 50, 60};
- vector<int> t3 = {30, 60, 90};
- obj.dailyTemperatures(t1); // expect 1,1,4,2,1,1,0,0
- obj.dailyTemperatures(t2); // expect 1,1,1,0
- obj.dailyTemperatures(t3); // expect 1,1,0
-}
diff --git a/other/daily_temps.rs b/other/daily_temps.rs
deleted file mode 100644
index 63b1f2b..0000000
--- a/other/daily_temps.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn daily_temperatures(temperatures: Vec<i32>) -> Vec<i32> {
- let n = temperatures.len();
- let mut ans: Vec<i32> = vec![0; n];
- let mut stk: Vec<usize> = Vec::new();
- for i in 0..n {
- while stk.last().map_or(false, |&v| { temperatures[v] < temperatures[i]}) {
- match stk.pop() {
- None => break,
- Some(idx) => ans[idx] = (i - idx) as i32
- }
- }
- stk.push(i);
- }
- ans
- }
-}
-
-fn main() {
- let t1 = vec![73,74,75,71,69,72,76,73];
- let t2 = vec![30,40,50,60];
- let t3 = vec![30,60,90];
- println!("{:?}", Solution::daily_temperatures(t1));
- println!("{:?}", Solution::daily_temperatures(t2));
- println!("{:?}", Solution::daily_temperatures(t3));
-}
diff --git a/other/data_stream_disjoint_interval.cpp b/other/data_stream_disjoint_interval.cpp
deleted file mode 100644
index 3682ee2..0000000
--- a/other/data_stream_disjoint_interval.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-// 352. Data Stream as Disjoint Intervals
-#include "leetcode.h"
-
-/*
- * given a data stream input of non-negative integers 'a1, a2, ..., an',
- * summarize the numbers seen so far as a list of disjoint intervals. implement
- * 'SummaryRanges': SummaryRanges() initialises the object with an empty stream
- * void addNum(int value) adds the integer 'value' to the stream
- * int[][] getIntervals() returns a summary of the integers in the stream
- * currently as a list of disjoint intervals '[starti, endi]'. sort answer by
- * 'starti'
- */
-
-class SummaryRanges {
-public:
- map<int, int> m;
- void addNum(int value) {
- if (m.count(value))
- return;
- m[value] = value;
- int mn = value, mx = value;
- if (m.count(value - 1))
- mn = m[value - 1];
- if (m.count(value + 1))
- mx = m[value + 1];
- m[mn] = mx;
- m[mx] = mn;
- }
- vvd getIntervals() {
- vvd ans;
- auto it = m.begin();
- while (it != m.end()) {
- ans.push_back({it->first, it->second});
- it = m.upper_bound(it->second);
- }
- return ans;
- }
-};
-
-int main() {
- SummaryRanges *obj = new SummaryRanges();
- int value;
- obj->addNum(value);
- vvd param_2 = obj->getIntervals();
-}
diff --git a/other/decode_ways.cpp b/other/decode_ways.cpp
deleted file mode 100644
index c03bd67..0000000
--- a/other/decode_ways.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int numDecodings(string s) {
- int n = s.size();
- vector<int> dp(n + 1, 0);
- dp[0] = 1;
- for (int i = 0; i < n; ++i) {
- if (s[i] != '0')
- dp[i + 1] += dp[i];
- if (i >= 1 &&
- (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] >= '0' && s[i] <= '6')))
- dp[i + 1] += dp[i - 1];
- }
- return dp[n];
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.numDecodings("226");
-}
diff --git a/other/decode_xor_array.cpp b/other/decode_xor_array.cpp
deleted file mode 100644
index 7ee4139..0000000
--- a/other/decode_xor_array.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-// 720. Decode XORed Array
-#include "leetcode.h"
-
-/*
- * 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] ^ 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'. ie. of
- * 'arr[0]'. return the original array 'arr'. it can be proved that the answer
- * exists and is unique.
- */
-
-class Solution {
-public:
- vector<int> decode(vector<int> encoded, int first) {
- for (int &i : encoded) {
- swap(i, first);
- first ^= i;
- }
- encoded.push_back(first);
- return encoded;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> e1 = {1, 2, 3}, e2 = {6, 2, 7, 3};
- for (auto i : obj.decode(e1, 1))
- printf("%d ", i); // expect: 1 0 2 1
- printf("\n");
- for (auto i : obj.decode(e2, 4))
- printf("%d ", i); // expect: 4 2 0 7 4
- printf("\n");
-}
diff --git a/other/delete_col_sorted.cpp b/other/delete_col_sorted.cpp
deleted file mode 100644
index 4954032..0000000
--- a/other/delete_col_sorted.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minDeletionSize(vector<string> &strs) {
- int ans = 0;
- if (strs.empty())
- return ans;
- for (auto i = 0; i < strs[0].size(); ++i)
- for (auto j = 1; j < strs.size(); ++j)
- if (strs[j - 1][i] > strs[j][i]) {
- ++ans;
- break;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<string> strs1 = {"cba", "daf", "ghi"}, strs2 = {"a", "b"},
- strs3 = {"zyx", "wvu", "tsr"};
- cout << obj.minDeletionSize(strs1) << endl;
- cout << obj.minDeletionSize(strs2) << endl;
- cout << obj.minDeletionSize(strs3) << endl;
-}
diff --git a/other/delete_col_sorted.rs b/other/delete_col_sorted.rs
deleted file mode 100644
index 1b7d24a..0000000
--- a/other/delete_col_sorted.rs
+++ /dev/null
@@ -1,25 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn min_deletion_size(strs: Vec<String>) -> i32 {
- let mut ans = 0;
- let mut new_strs: Vec<Vec<char>> = Vec::new();
- for i in 0..strs.len() {
- new_strs.push(strs[i].chars().collect::<Vec<char>>());
- }
- for i in 0..new_strs[0].len() {
- for j in 1..new_strs.len() {
- if new_strs[j - 1][i] > new_strs[j][i] {
- ans += 1;
- break
- }
- }
- }
- ans
- }
-}
-
-fn main() {
- let strs = vec![String::from("cba"), String::from("daf"), String::from("ghi")];
- print!("{}", Solution::min_deletion_size(strs));
-}
diff --git a/other/delete_middle_node.cpp b/other/delete_middle_node.cpp
deleted file mode 100644
index 1493046..0000000
--- a/other/delete_middle_node.cpp
+++ /dev/null
@@ -1,16 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- ListNode *deleteMiddle(ListNode *head) {
- if (head->next == nullptr)
- return nullptr;
- auto slow = head, fast = head->next->next;
- while (fast != nullptr && fast->next != nullptr) {
- fast = fast->next->next;
- slow = slow->next;
- }
- slow->next = slow->next->next;
- return head;
- }
-};
diff --git a/other/delete_middle_node.rs b/other/delete_middle_node.rs
deleted file mode 100644
index 289d8dd..0000000
--- a/other/delete_middle_node.rs
+++ /dev/null
@@ -1,52 +0,0 @@
-pub struct Solution;
-pub struct ListNode {
- pub val: i32,
- pub next: Option<Box<ListNode>>
-}
-
-impl ListNode {
- #[inline]
- fn new(val: i32) -> self {
- ListNode {
- next: None,
- val
- }
- }
-}
-
-impl Solution {
- pub fn delete_middle(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
- let mut slowPtr = &head;
- let mut fastPtr = &head;
- let mut fakeHead = Box::new(ListNode::new(-1));
- let mut fakeTmp = &mut *fakeHead as *mut ListNode;
- let mut slowPrevPtr = &mut *fakeHead as *mut ListNode;
- while fastPtr.is_some() && (fastPtr).as_ref().unwrap().next.is_some() {
- unsafe {
- let mut next = Box::new(ListNode::new((slowPtr).as_ref().unwrap().val));
- let nextPtr = &mut *next as *mut ListNode;
- (*fakeTmp).next = Some(next);
- slowPrevPtr = fakeTmp;
- fakeTmp = nextPtr;
- slowPtr = &(slowPtr).as_ref().unwrap().next;
- fastPtr = &(fastPtr).as_ref().unwrap().next;
- if fastPtr.is_some() {
- fastPtr = &(fastPtr).as_ref().unwrap().next;
- }
- }
- }
- slowPtr = &(slowPtr).as_ref().unwrap().next;
- while slowPtr.is_some() {
- unsafe {
- let mut next = Box::new(ListNode::new((slowPtr).as_ref().unwrap().val));
- let nextPtr = &mut *next as *mut ListNode;
- (*fakeTmp).next = Some(next);
- fakeTmp = nextPtr;
- slowPtr = &(slowPtr).as_ref().unwrap().next;
- }
- }
- fakeHead.next
- }
-}
-
-fn main() {}
diff --git a/other/delete_node_link_list.cpp b/other/delete_node_link_list.cpp
deleted file mode 100644
index cefe915..0000000
--- a/other/delete_node_link_list.cpp
+++ /dev/null
@@ -1,10 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- void deleteNode(ListNode *node) {
- auto next = node->next;
- *node = *next;
- delete next;
- }
-};
diff --git a/other/delete_operation_2string.cpp b/other/delete_operation_2string.cpp
deleted file mode 100644
index b6e38e4..0000000
--- a/other/delete_operation_2string.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minDistance(string word1, string word2) {
- int m = word1.size(), n = word2.size();
- if (m < n) {
- swap(word1, word2);
- swap(n, m);
- }
- vector<int> last(n + 1, 0), curr(n + 1, 0);
- for (char char1 : word1) {
- for (int i = 0; i < n; i++)
- curr[i + 1] =
- char1 == word2[i] ? last[i] + 1 : max(curr[i], last[i + 1]);
- swap(last, curr);
- }
- return m + n - 2 * last[n];
- }
-};
-
-int main() {
- Solution obj;
- string word1 = "sea", word2 = "eat";
- cout << obj.minDistance(word1, word2);
-}
diff --git a/other/design_circular_queue.cpp b/other/design_circular_queue.cpp
deleted file mode 100644
index 697e17b..0000000
--- a/other/design_circular_queue.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-struct Node {
-public:
- int value;
- Node *next;
- Node(int v, Node *n = nullptr) {
- value = v;
- next = n;
- }
-};
-
-class MyCircularQueue {
-public:
- MyCircularQueue(int k) { maxSize = k; }
- bool enQueue(int value) {
- if (isFull())
- return false;
- Node *newNode = new Node(value);
- if (isEmpty())
- head = newNode, tail = newNode;
- else
- tail->next = newNode, tail = tail->next;
- size++;
- return true;
- }
- bool deQueue() {
- if (isEmpty())
- return false;
- Node *rem = head;
- head = head->next;
- delete rem;
- size--;
- return true;
- }
- int Front() { return isEmpty() ? -1 : head->value; }
- int Rear() { return isEmpty() ? -1 : tail->value; }
- bool isEmpty() { return size == 0; }
- bool isFull() { return size == maxSize; }
-
-private:
- int maxSize, size = 0;
- Node *head = new Node(0), *tail = new Node(0);
-};
-
-int main() {
- int k, value;
- MyCircularQueue *obj = new MyCircularQueue(k);
- bool param_1 = obj->enQueue(value);
- bool param_2 = obj->deQueue();
- int param_3 = obj->Front();
- int param_4 = obj->Rear();
- bool param_5 = obj->isEmpty();
- bool param_6 = obj->isFull();
-}
diff --git a/other/design_food_rating_sys.cpp b/other/design_food_rating_sys.cpp
deleted file mode 100644
index bdfef0c..0000000
--- a/other/design_food_rating_sys.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 2353. Design a Food Rating System
-#include "leetcode.h"
-
-/*
- * design a food rating system that can do the following:
- * - modify the rating of a food item listed in the system
- * - return the highest rated food item for a type of cuisine in the system
- * implement the 'FoodRatings' class. 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 beofre y[i] in
- * alpabetic order
- */
-
-class FoodRatings {
-private:
- unordered_map<string_view, string_view> f2c;
- unordered_map<string_view, int> f2r;
- unordered_map<string_view, set<pair<int, string>>> c2r;
-
-public:
- FoodRatings(vector<string> &foods, vector<string> &cuisines,
- vector<int> &ratings) {
- for (int i = 0; i < foods.size(); i++) {
- f2c[foods[i]] = cuisines[i];
- f2r[foods[i]] = ratings[i];
- c2r[cuisines[i]].emplace(-ratings[i], foods[i]);
- }
- }
-
- void changeRating(string food, int newRating) {
- int r = exchange(f2r[food], newRating);
- auto &c = f2c[food];
- auto it = c2r.find(c);
- it->second.erase({-r, food});
- it->second.emplace(-newRating, food);
- }
-
- string highestRated(string cuisine) { return begin(c2r[cuisine])->second; }
-};
diff --git a/other/design_number_container.cpp b/other/design_number_container.cpp
deleted file mode 100644
index bc37a6a..0000000
--- a/other/design_number_container.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-// 2349. Design a Number Container System
-#include "leetcode.h"
-
-/*
- * design a number container system that can do the following: insert or replace
- * a number at the given index in the system or return the smallest index for
- * the given number in the system. implement the 'NumberContainers' class.
- */
-
-class NumberContainers {
-private:
- unordered_map<int, int> idxs;
- unordered_map<int, set<int>> nums;
-
-public:
- void change(int index, int number) {
- auto i = idxs.find(index);
- if (i != end(idxs))
- nums[i->second].erase(index);
- idxs[index] = number;
- nums[number].insert(index);
- }
- int find(int number) {
- auto i = nums.find(number);
- return i == end(nums) || i->second.empty() ? -1 : *begin(i->second);
- }
-};
-
-int main() {
- NumberContainers *obj = new NumberContainers();
- printf("%d\n", obj->find(10)); // expect: -1
- obj->change(2, 10);
- obj->change(1, 10);
- obj->change(3, 10);
- obj->change(5, 10);
- printf("%d\n", obj->find(10)); // expect: 1
- obj->change(1, 20);
- printf("%d\n", obj->find(10)); // expect: 2
-}
diff --git a/other/design_parking_system.cpp b/other/design_parking_system.cpp
deleted file mode 100644
index 5cfaf74..0000000
--- a/other/design_parking_system.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 1603. Design Parking System
-#include "leetcode.h"
-
-/*
- * design a parking system for a parking lot. the parking lot has three kinds of
- * parking spaces: big, medium, and small. with a fixed number of slots for each
- * size. implement the 'ParkingSystem' class:
- * - 'ParkingSystem(big, medium, small)' initialises object of the
- * 'ParkingSystem' class the number of slots for each parking space are given as
- * part of the constructor
- * - 'bool addCar(car_type)' checks whether there is a parking space of
- * 'car_type' for the car that wants to get into the parking lot. 'car_type' can
- * be of three kinds: big, medium, or small, which are represented by 1, 2, or
- * 3, respectively. a car can only park in a parking space of its 'car_type'. if
- * there is no space available, return false, else park the car in that size
- * space and return true
- */
-
-class ParkingSystem {
-public:
- vector<int> vehicle;
- ParkingSystem(int big, int medium, int small) {
- vehicle = {big, medium, small};
- }
- bool addCar(int car_type) {
- if (vehicle[car_type - 1]) {
- vehicle[car_type - 1] -= 1;
- return true;
- }
- return false;
- }
-};
-
-int main() {
- ParkingSystem *obj = new ParkingSystem(1, 1, 0);
- printf("%d\n", obj->addCar(1)); // expect: 1
- printf("%d\n", obj->addCar(2)); // expect: 1
- printf("%d\n", obj->addCar(3)); // expect: 0
- printf("%d\n", obj->addCar(1)); // expect: 0
-}
diff --git a/other/design_underground_system.cpp b/other/design_underground_system.cpp
deleted file mode 100644
index f0904d2..0000000
--- a/other/design_underground_system.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-class UndergroundSystem {
-public:
- unordered_map<int, pair<string, int>> checkIns;
- unordered_map<string, pair<int, int>> routes;
- UndergroundSystem() {}
- void checkIn(int id, string stationName, int t) {
- checkIns[id] = {stationName, t};
- }
- void checkOut(int id, string stationName, int t) {
- auto [stn, start] = checkIns[id];
- checkIns.erase(id);
- string route = stn + "," + stationName;
- routes[route].first++;
- routes[route].second += t - start;
- }
- double getAverageTime(string startStation, string endStation) {
- auto &[count, sum] = routes[startStation + "," + endStation];
- return (double)sum / count;
- }
-};
diff --git a/other/detect_capital.cpp b/other/detect_capital.cpp
deleted file mode 100644
index 27aa46b..0000000
--- a/other/detect_capital.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool detectCapitalUse(string word) {
- bool firstCaps = isupper(word[0]), allCaps = true, allLower = true;
- for (int i = 1; i < word.size(); i++) {
- if (isupper(word[i]))
- allLower = false;
- else
- allCaps = false;
- }
- return (firstCaps && allCaps) || allLower;
- }
-};
-
-int main() {
- Solution obj;
- testBool(obj.detectCapitalUse("USA")); // true
- testBool(obj.detectCapitalUse("FlaG")); // false
-}
diff --git a/other/detect_capital.rs b/other/detect_capital.rs
deleted file mode 100644
index 454381d..0000000
--- a/other/detect_capital.rs
+++ /dev/null
@@ -1,20 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn detect_capital_use(word: String) -> bool {
- let v: Vec<char> = word.chars().collect();
- if v[0].is_lowercase() {
- return v.iter().all(|&c| c.is_lowercase());
- }
- if v.len() > 1 {
- let b = v[1].is_lowercase();
- return v.iter().skip(1).all(|&c| c.is_lowercase() == b);
- }
- true
- }
-}
-
-fn main() {
- let word = String::from("USA");
- print!("{}", Solution::detect_capital_use(word)); //true
-}
diff --git a/other/determine_string_halves.cpp b/other/determine_string_halves.cpp
deleted file mode 100644
index fd249e1..0000000
--- a/other/determine_string_halves.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
- string vowels = "aeiouAEIOU";
-
-public:
- bool halvesAreAlike(string s) {
- int mid = s.size() / 2, ans = 0;
- for (int i = 0, j = mid; i < mid; i++, j++) {
- if (~vowels.find(s[i]))
- ans++;
- if (~vowels.find(s[j]))
- ans--;
- }
- return ans == 0;
- }
-};
-
-int main() {
- Solution obj;
- if (obj.halvesAreAlike("book"))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/determine_string_halves.rs b/other/determine_string_halves.rs
deleted file mode 100644
index f7f4303..0000000
--- a/other/determine_string_halves.rs
+++ /dev/null
@@ -1,18 +0,0 @@
-use std::collections::HashSet;
-struct Solution;
-
-impl Solution {
- pub fn halves_are_alike(s: String) -> bool {
- let vowels: HashSet<char> = HashSet::from(['a','e','i','o','u','A','E','I','O','U']);
- s.chars()
- .enumerate()
- .filter(|(_, c)| vowels.contains(c))
- .map(|(i, _)| (s.len() as i32 - 2 * (i as i32) - 1).signum())
- .sum::<i32>() == 0
- }
-}
-
-fn main() {
- let s = String::from("book");
- print!("{}", Solution::halves_are_alike(s));
-}
diff --git a/other/determine_strings_close.cpp b/other/determine_strings_close.cpp
deleted file mode 100644
index 89e2322..0000000
--- a/other/determine_strings_close.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool closeStrings(string word1, string word2) {
- if (word1.size() != word2.size())
- return false;
- vector<int> c1(26), c2(26);
- for (auto i = 0; i < word1.size(); ++i) {
- ++c1[word1[i] - 'a'];
- ++c2[word2[i] - 'a'];
- }
- if (!equal(begin(c1), end(c1), begin(c2), end(c2),
- [](int a, int b) { return (bool)a == bool(b); }))
- return false;
- sort(begin(c1), end(c1));
- sort(begin(c2), end(c2));
- return c1 == c2;
- }
-};
-
-int main() {
- Solution obj;
- if (obj.closeStrings("abc", "bca"))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/determine_strings_close.rs b/other/determine_strings_close.rs
deleted file mode 100644
index f293b6d..0000000
--- a/other/determine_strings_close.rs
+++ /dev/null
@@ -1,25 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn close_strings(word1: String, word2: String) -> bool {
- let (mut c1, mut c2) = ([0; 26], [0; 26]);
- for &b in word1.as_bytes() {
- c1[(b - b'a') as usize] += 1;
- }
- for &b in word2.as_bytes() {
- c2[(b - b'a') as usize] += 1;
- }
- if (0..26).any(|i| (c1[i] > 0) != (c2[i] > 0)) {
- return false;
- }
- c1.sort_unstable();
- c2.sort_unstable();
- c1 == c2
- }
-}
-
-fn main() {
- let word1 = String::from("abc");
- let word2 = String::from("bca");
- print!("{}", Solution::close_strings(word1, word2));
-}
diff --git a/other/detonate_max_bombs.cpp b/other/detonate_max_bombs.cpp
deleted file mode 100644
index 4d92b98..0000000
--- a/other/detonate_max_bombs.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-// 2101. Detonate the Maximum Bombs
-#include "leetcode.h"
-
-/*
- * given a list of bombs. the range of a bomb is defined as the area where its
- * effect can be felt. this area is in the shape of a circle with the center as
- * the location of the bomb. the bombs are represented by a 0-indexed 2d integer
- * array 'bombs' where 'bombs[i] = [xi, yi, ri]'. 'xi' and 'yi' denote the x and
- * y coordinates of the location of the i'th bomb, whereas 'ri' denotes the
- * radius of its range. you may choose to detonate a single bomb. when a bomb is
- * detonated, it will detonate all the bombs that lie in its range. these bombs
- * will further detonate the bombs that lie in their ranges. given the list of
- * 'bombs', return the max number of bombs that can be detonated
- */
-
-class Solution {
- void dfs(vvd & graph, vector<bool> &visited, int c, int i) {
- visited[i] = true;
- c++;
- for (int j = 0; j < graph[i].size(); j++)
- if (!visited[graph[i][j]])
- dfs(graph, visited, c, graph[i][j]);
- }
-
-public:
- int maximumDetonation(vvd & bombs) {
- int n = bombs.size(), ans = INT_MIN;
- vvd graph(n);
- for (int i = 0; i < n; i++) {
- long long int x1, y1, r1;
- x1 = bombs[i][0];
- y1 = bombs[i][1];
- r1 = bombs[i][2];
- for (int j = 0; j < n; j++)
- if (i != j) {
- long long int x2, y2, r2;
- x2 = abs(x1 - bombs[j][0]);
- y2 = abs(y1 - bombs[j][1]);
- if (x2 * x2 + y2 * y2 <= r1 * r1)
- graph[i].push_back(j);
- }
- }
- for (int i = 0; i < n; i++) {
- int c = 0;
- vector<bool> visited(n, false);
- dfs(graph, visited, c, i);
- ans = max(ans, c);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd b1 = {{2, 1, 3}, {6, 1, 4}};
- vvd b2 = {{1, 1, 5}, {10, 10, 5}};
- vvd b3 = {{1, 2, 3}, {2, 3, 1}, {3, 4, 2}, {4, 5, 3}, {5, 6, 4}};
- printf("%d\n", obj.maximumDetonation(b1)); // expect: 2
- printf("%d\n", obj.maximumDetonation(b2)); // expect: 1
- printf("%d\n", obj.maximumDetonation(b3)); // expect: 5
-}
diff --git a/other/diff_two_array.cpp b/other/diff_two_array.cpp
deleted file mode 100644
index 6695ae7..0000000
--- a/other/diff_two_array.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-// 2215. Find the Difference of Two Arrays
-#include "leetcode.h"
-
-/*
- * given two zero-indexed arrays 'n1' and 'n2', return a list
- * 'ans' of size 2 where:
- * 'ans[0]' is a list of all distinct integers in 'n1' which
- * are not present in 'n2'
- * 'ans[1]' is a list of all distinct integers in 'n2' which
- * are not present in 'n1'
- * note that the integers in the lists may be returned in any order
- */
-
-class Solution {
-public:
- vvd findDifference(vector<int> &n1, vector<int> &n2) {
- unordered_set<int> us1(begin(n1), end(n1)), us2(begin(n2), end(n2));
- vvd ans(2);
- for (int i : us1)
- if (!us2.count(i))
- ans[0].push_back(i);
- for (int i : us2)
- if (!us1.count(i))
- ans[1].push_back(i);
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n11 = {1, 2, 3}, n21 = {2, 4, 6};
- vector<int> n12 = {1, 2, 3, 3}, n22 = {1, 1, 2, 2};
- vvd fd1 = obj.findDifference(n11, n21);
- vvd fd2 = obj.findDifference(n12, n22);
-}
diff --git a/other/discount_n_orders.cpp b/other/discount_n_orders.cpp
deleted file mode 100644
index a76d21e..0000000
--- a/other/discount_n_orders.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-#include "leetcode.h"
-
-class Cashier {
-public:
- Cashier(int n, int discount, vector<int> &products, vector<int> &prices) {
- count = 0, mod = n, pct = (100.0 - discount) / 100.0;
- for (int i = 0; i < products.size(); ++i)
- tags[products[i]] = prices[i];
- }
- double getBill(vector<int> product, vector<int> amount) {
- count++;
- double ans(0.0);
- for (int i = 0; i < product.size(); ++i)
- ans += tags[product[i]] * amount[i];
- return count % mod ? ans : ans * pct;
- }
-
-private:
- unordered_map<int, int> tags;
- int count, mod;
- double pct;
-};
-
-int main() {
- Cashier *obj = new Cashier(n, discount, products, prices);
- double param_1 = obj->getBill(product, amount);
-}
diff --git a/other/divide_nodes_max_groups.cpp b/other/divide_nodes_max_groups.cpp
deleted file mode 100644
index ea07a34..0000000
--- a/other/divide_nodes_max_groups.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-// 2493. Divide Nodes Into the Maximum Number of Groups
-#include "leetcode.h"
-
-/*
- * you are given a positive integer 'n' representing the number of nodes in an
- * undirected graph. the nodes are labeled from 1 to 'n'. you are also given a
- * 2d integer array 'edges', where 'edges[i] = [a_i, b_i]' indicates that there
- * is a bidirectional edge between nodes 'a_i' and 'b_i'. divide the nodes of
- * the graph into 'm' groups such that each node in the graph belongs to exactly
- * one group, and for every pair of nodes in the graph that are connected by an
- * edge '[a_i, b_i]', then '|y - x| = 1'. return the maximum number of groups
- * into which you can divide the nodes. return -1 if it is impossible.
- */
-
-class Solution {
-public:
- int magnificentSets(int n, vector<vector<int>> &edges) {
- vector<int> vis(n);
- vector<vector<int>> graph(n), group;
- for (auto e : edges) {
- graph[e[0] - 1].push_back(e[1] - 1);
- graph[e[1] - 1].push_back(e[0] - 1);
- }
- for (int i = 0; i < n; ++i)
- if (!vis[i]) {
- vis[i] = true;
- stack<int> stk;
- stk.push(i);
- group.push_back({i});
- while (stk.size()) {
- auto u = stk.top();
- stk.pop();
- for (auto &v : graph[u])
- if (!vis[v]) {
- vis[v] = vis[u] + 1;
- stk.push(v);
- group.back().push_back(v);
- } else if ((vis[u] & 1) == (vis[v] & 1))
- return -1;
- }
- }
- auto bfs = [&](int x) {
- int res = 0;
- vector<bool> vis(n);
- vis[x] = true;
- queue<int> q;
- q.push(x);
- for (; q.size(); ++res)
- for (int size = q.size(); size; --size) {
- auto u = q.front();
- q.pop();
- for (auto &v : graph[u])
- if (!vis[v]) {
- vis[v] = true;
- q.push(v);
- }
- }
- return res;
- };
- int ans = 0;
- for (auto &g : group) {
- transform(g.begin(), g.end(), g.begin(), bfs);
- ans += *max_element(g.begin(), g.end());
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd e1 = {{1, 2}, {1, 4}, {1, 5}, {2, 6}, {2, 3}, {4, 6}};
- vvd e2 = {{1, 2}, {2, 3}, {3, 1}};
- printf("%d\n", obj.magnificentSets(6, e1)); // expect: 4
- printf("%d\n", obj.magnificentSets(3, e2)); // expect: -1
-}
diff --git a/other/domino_tromino_tiling.cpp b/other/domino_tromino_tiling.cpp
deleted file mode 100644
index 80a97d0..0000000
--- a/other/domino_tromino_tiling.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include "leetcode.h"
-#include <vector>
-
-class Solution {
-public:
- int numTilings(int n) {
- int mod = 1e9;
- mod += 7;
- vector<long long> ans(1001, 0);
- ans[1] = 1;
- ans[2] = 2;
- ans[3] = 5;
- if (n <= 3)
- return ans[n];
- for (int i = 4; i <= n; ++i) {
- ans[i] = 2 * ans[i - 1] + ans[i - 3];
- ans[i] %= mod;
- }
- return ans[n];
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.numTilings(3); // 5
- cout << endl;
- cout << obj.numTilings(1); // 1
-}
diff --git a/other/domino_tromino_tiling.rs b/other/domino_tromino_tiling.rs
deleted file mode 100644
index 554f147..0000000
--- a/other/domino_tromino_tiling.rs
+++ /dev/null
@@ -1,20 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn num_tilings(n: i32) -> i32 {
- const MOD: i32 = 1_000_000_007;
- let (mut x, mut y, mut z) = (-1, 0, 1);
- for _ in 1..=n {
- let curr = (2 * z % MOD + x) % MOD;
- x = y;
- y = z;
- z = curr;
- }
- z
- }
-}
-
-fn main() {
- println!("{}", Solution::num_tilings(3)); // 5
- println!("{}", Solution::num_tilings(1)); // 1
-}
diff --git a/other/earliest_possible_full_bloom.cpp b/other/earliest_possible_full_bloom.cpp
deleted file mode 100644
index f990e62..0000000
--- a/other/earliest_possible_full_bloom.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int earliestFullBloom(vector<int> &plantTime, vector<int> &growTime) {
- int n = plantTime.size();
- vector<pair<int, int>> times(n);
- for (int i = 0; i < n; i++) {
- times[i].first = -growTime[i];
- times[i].second = plantTime[i];
- }
- sort(times.begin(), times.end());
- int total = 0, curr = 0;
- for (int i = 0; i < n; i++) {
- total = max(total, curr + times[i].second - times[i].first);
- curr += times[i].second;
- }
- return total;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> plantTime = {1, 4, 3}, growTime = {2, 3, 1};
- cout << obj.earliestFullBloom(plantTime, growTime);
-}
diff --git a/other/earliest_possible_full_bloom.rs b/other/earliest_possible_full_bloom.rs
deleted file mode 100644
index b8e6444..0000000
--- a/other/earliest_possible_full_bloom.rs
+++ /dev/null
@@ -1,20 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn earliest_full_bloom(plant_time: Vec<i32>, grow_time: Vec<i32>) -> i32 {
- let n = plant_time.len();
- let mut plant_data: Vec<(i32, i32)> = plant_time.into_iter().zip(grow_time.into_iter()).collect();
- plant_data.sort_by(|a,b| b.1.cmp(&a.1));
- let (mut free_time, mut max_bloom_time) = (0,0);
- for i in 0..n {
- free_time += plant_data[i].0;
- max_bloom_time = max_bloom_time.max(free_time + plant_data[i].1);
- }
- max_bloom_time
- }
-}
-
-fn main() {
- let (plant_time, grow_time) = (vec![1,4,3], vec![2,3,1]);
- print!("{}", Solution::earliest_full_bloom(plant_time, grow_time));
-}
diff --git a/other/edit_distance.cpp b/other/edit_distance.cpp
deleted file mode 100644
index 4103e83..0000000
--- a/other/edit_distance.cpp
+++ /dev/null
@@ -1,41 +0,0 @@
-// 72. Edit Distance
-#include "leetcode.h"
-
-/*
- * given two strings 'word1' and 'word2', return minimum number of operations
- * required to convert 'word1' to 'word2'. the following operations are
- * permitted: insert character, delete character, replace character
- */
-
-class Solution {
-public:
- int minDistance(string word1, string word2) {
- int m = word1.size(), n = word2.size();
- vvd memo(m + 1, vector<int>(n + 1, -1));
- return editDistance(word1, word2, m, n, memo);
- }
-
-private:
- int editDistance(string word1, string word2, int m, int n, vvd memo) {
- if (m == 0)
- return memo[m][n] = n;
- if (n == 0)
- return memo[m][n] = m;
- if (memo[m][n] != -1)
- return memo[m][n];
- if (word1[m - 1] == word2[n - 1])
- return memo[m][n] = editDistance(word1, word2, m - 1, n - 1, memo);
- else {
- int insertChar = editDistance(word1, word2, m, n - 1, memo);
- int deleteChar = editDistance(word1, word2, m - 1, n, memo);
- int replacChar = editDistance(word1, word2, m - 1, n - 1, memo);
- return memo[m][n] = 1 + min({insertChar, deleteChar, replacChar});
- }
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.minDistance("horse", "ros") << endl; // expect: 3
- cout << obj.minDistance("intention", "execution"); // expect: 5
-}
diff --git a/other/eliminate_monsters.cpp b/other/eliminate_monsters.cpp
deleted file mode 100644
index b0a1711..0000000
--- a/other/eliminate_monsters.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- typedef pair<double, int> p;
- int eliminateMaxium(vector<int> &dist, vector<int> &speed) {
- priority_queue<p, vector<p>, greater<p>> pq;
- for (int i = 0; i < speed.size(); i++) {
- double time = (double)dist[i] / (double)speed[i];
- pq.push({time, i});
- }
- int ans = 0, t = 0;
- while (pq.empty()) {
- auto node = pq.top();
- pq.pop();
- int idx = node.second, d = dist[idx] - (t * speed[idx]);
- if (d <= 0)
- break;
- else
- ans++;
- t++;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> dist = {1, 3, 4}, speed = {1, 1, 1};
- cout << obj.eliminateMaxium(dist, speed);
-}
diff --git a/other/encode_decode_tinyurl.cpp b/other/encode_decode_tinyurl.cpp
deleted file mode 100644
index d7b9d98..0000000
--- a/other/encode_decode_tinyurl.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-// 535. Encode and Decode TinyURL
-#include "leetcode.h"
-
-/*
- * tinyurl is a url shortening service where you enter a url such as
- * https://looooooongurl.com and it returns a short url such as
- * http://tinyurl.com/4e9iAk. design a class to encode a url and decode a tiny
- * url. there is no restriction on how your encode/decode algorithm should work.
- * you just need to ensure that a url can be encoded to a tiny url and the tiny
- * url can be decoded to the original url.
- */
-
-class Solution {
-private:
- const string charset =
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
- map<string, string> url_code, code_url;
- random_device rd;
-
-public:
- string encode(string longUrl) {
- string code;
- if (!url_code.count(longUrl)) {
- for (int i = 0; i < 6; i++)
- code.push_back(charset[rd() % charset.size()]);
- url_code.insert(pair<string, string>(longUrl, code));
- code_url.insert(pair<string, string>(code, longUrl));
- } else
- code = url_code[longUrl];
- return "http://tinyurl.com/" + code;
- }
- string decode(string shortUrl) {
- if (shortUrl.size() != 25 || !code_url.count(shortUrl.substr(19, 6)))
- return "";
- return code_url[shortUrl.substr(19, 6)];
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.decode(obj.encode("https://leetcode.com/problems/design-tinyurl"))
- << endl; // expect: https://leetcode.com/problems/design-tinyurl
-}
diff --git a/other/equal_row_col_pair.cpp b/other/equal_row_col_pair.cpp
deleted file mode 100644
index 426291c..0000000
--- a/other/equal_row_col_pair.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-// 2352. Equal Row and Column Pairs
-#include "leetcode.h"
-
-/*
- * given a 0-indexed n x n integer matrix 'grid', return the number of pairs
- * (ri, cj) such that row 'ri' and column 'ci' are equal. a row and column pair
- * is considered equal if they contain the same elements in the same order (ie.
- * an equal array)
- */
-
-class Solution {
-public:
- int equalPairs(vvd & grid) {
- int ans = 0;
- map<vector<int>, int> mv;
- for (int i = 0; i < grid.size(); i++)
- mv[grid[i]]++;
- for (int i = 0; i < grid[0].size(); i++) {
- vector<int> v;
- for (int j = 0; j < grid.size(); j++)
- v.push_back(grid[j][i]);
- ans += mv[v];
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd g1 = {{3, 2, 1}, {1, 7, 6}, {2, 7, 7}};
- vvd g2 = {{3, 1, 2, 2}, {1, 4, 4, 5}, {2, 4, 2, 2}, {2, 4, 2, 2}};
- printf("%d\n", obj.equalPairs(g1)); // expect: 1
- printf("%d\n", obj.equalPairs(g2)); // expect: 3
-}
diff --git a/other/erect_fence.cpp b/other/erect_fence.cpp
deleted file mode 100644
index 9d26fb9..0000000
--- a/other/erect_fence.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- using tree = vector<int>;
- vector<tree> outerTrees(vector<tree> &trees) {
- auto cross = [](tree &a, tree &b, tree &c) -> int {
- return (c[1] - a[1]) * (a[0] - b[0]) - (a[1] - b[1]) * (c[0] - a[0]);
- };
- sort(trees.begin(), trees.end());
- deque<tree> dv;
- for (tree t : trees) {
- while (dv.size() >= 2 &&
- cross(dv[dv.size() - 1], dv[dv.size() - 2], t) < 0)
- dv.pop_back();
- dv.push_back(t);
- while (dv.size() >= 2 && cross(dv[0], dv[1], t) > 0)
- dv.pop_front();
- dv.push_front(t);
- }
- set<tree> unique(dv.begin(), dv.end());
- return vector<tree>(unique.begin(), unique.end());
- }
-};
-
-int main() {
- Solution obj;
- vvd trees = {{1, 1}, {2, 2}, {2, 0}, {2, 4}, {3, 3}, {4, 2}};
-}
diff --git a/other/erect_fence.rs b/other/erect_fence.rs
deleted file mode 100644
index 6dee425..0000000
--- a/other/erect_fence.rs
+++ /dev/null
@@ -1,27 +0,0 @@
-use std::collections::VecDeque;
-type Tree = Vec<i32>;
-struct Solution;
-
-impl Solution {
- pub fn outer_trees(mut trees: Vec<Tree>) -> Vec<Tree> {
- fn cross(a: &Tree, b: &Tree, c: &Tree) -> i32 {
- return (c[1] - a[1]) * (a[0] - b[0]) - (a[1] - b[1]) * (c[0] - a[0])
- }
- trees.sort();
- let mut dv: VecDeque<Tree> = VecDeque::new();
- for t in trees {
- while dv.len() >= 2 && cross(&dv[dv.len() - 1], &dv[dv.len() - 2], &t) < 0 {
- dv.pop_back();
- }
- dv.push_back(t.clone());
- while dv.len() >= 2 && cross(&dv[0], &dv[1], &t) > 0 {
- dv.pop_front();
- }
- dv.push_front(t.clone());
- }
- let mut fence = Vec::from(dv);
- fence.sort_unstable();
- fence.dedup();
- fence
- }
-}
diff --git a/other/eval_reverse_polish_notation.cpp b/other/eval_reverse_polish_notation.cpp
deleted file mode 100644
index 4cd39b8..0000000
--- a/other/eval_reverse_polish_notation.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int evalRPN(vector<string> &tokens) {
- unordered_map<string, function<int(int, int)>> umf = {
- {"+", [](long a, long b) { return a + b; }},
- {"-", [](long a, long b) { return a - b; }},
- {"*", [](long a, long b) { return a * b; }},
- {"/", [](long a, long b) { return a / b; }}};
- stack<long> stk;
- for (string &s : tokens) {
- if (!umf.count(s))
- stk.push(stoi(s));
- else {
- long op1 = stk.top();
- stk.pop();
- long op2 = stk.top();
- stk.pop();
- stk.push(umf[s](op2, op1));
- }
- }
- return static_cast<int>(stk.top());
- }
-};
-
-int main() {
- Solution obj;
- vector<string> tokens1 = {"2", "1", "+", "3", "*"};
- // output: 9
- // ((2 + 1) * 3)
- cout << obj.evalRPN(tokens1);
- vector<string> tokens2 = {"4", "13", "5", "/", "+"};
- // output: 6
- // (4 + (13 / 5))
- cout << obj.evalRPN(tokens2);
- vector<string> tokens3 = {"10", "6", "9", "3", "+", "-11", "*",
- "/", "*", "17", "+", "5", "+"};
- // output: 22
- // ((10 * (6 / (12 * -11))) + 17) + 5
- // ((10 * (6 / -132)) + 17) + 5
- // ((10 * 0) + 17) + 5
- // (0 + 17) + 5
- // 17 + 5
- cout << obj.evalRPN(tokens3);
-}
diff --git a/other/eval_reverse_polish_notation.rs b/other/eval_reverse_polish_notation.rs
deleted file mode 100644
index 11a36e3..0000000
--- a/other/eval_reverse_polish_notation.rs
+++ /dev/null
@@ -1,29 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn eval_rpn(tokens: Vec<String>) -> i32 {
- tokens.iter().fold(Vec::new(), |mut stack, x| {
- if let Ok(x) = x.parse() {
- stack.push(x);
- } else if let (Some(rhs), Some(lhs)) = (stack.pop(), stack.pop()) {
- stack.push(match x.as_str() {
- "+" => lhs + rhs,
- "-" => lhs - rhs,
- "*" => lhs * rhs,
- "/" => lhs / rhs,
- _ => unreachable!()
- })
- }
- stack
- }) [0]
- }
-}
-
-fn main() {
- let tokens1 = ["2","1","+","3","*"];
- let tokens2 = ["4","13","5","/","+"];
- let tokens3 = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"];
- println!("{}", Solution::eval_rpn(tokens1));
- println!("{}", Solution::eval_rpn(tokens2));
- println!("{}", Solution::eval_rpn(tokens3));
-}
diff --git a/other/eventual_safe_states.cpp b/other/eventual_safe_states.cpp
deleted file mode 100644
index 6e41e3e..0000000
--- a/other/eventual_safe_states.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-// 802. Find Eventual Safe States
-#include "leetcode.h"
-
-/*
- * there is a directed graph of 'n' nodes with each node labeled from 0 to n
- * - 1. the graph is represented by a 0-indexed 2d integer array 'graph' where
- * 'graph[i]' is an integer array of nodes adjacent to node 'i', meaning there
- * is an edge from node 'i' to each node in 'graph[i]'. a node is a terminal
- * node if there are no outgoing edges. a node is a safe node if every possible
- * path starting from that node leads to a terminal node ( or another safe
- * node). return an array containing all the safe nodes of the graph. the answer
- * should be sorted in ascending order.
- */
-
-class Solution {
-public:
- vector<int> eventualSafeNodes(vector<vector<int>> &graph) {
- int n = graph.size();
- vector<vector<int>> g(n);
- vector<int> dp(n, 0);
- for (int i = 0; i < n; i++)
- for (int j = 0; j < graph[i].size(); j++) {
- g[graph[i][j]].push_back(i);
- dp[i]++;
- }
- queue<int> q;
- for (int i = 0; i < n; i++)
- if (!dp[i])
- q.push(i);
- vector<int> ans;
- while (!q.empty()) {
- int u = q.front();
- q.pop();
- ans.push_back(u);
- for (int v : g[u])
- if (!--dp[v])
- q.push(v);
- }
- sort(ans.begin(), ans.end());
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd g1 = {{1, 2}, {2, 3}, {5}, {0}, {5}, {}, {}};
- vvd g2 = {{1, 2, 3, 4}, {1, 2}, {3, 4}, {0, 4}, {}};
- for (auto i : obj.eventualSafeNodes(g1))
- printf("%d ", i); // expect: 2 4 5 6
- printf("\n");
- for (auto i : obj.eventualSafeNodes(g2))
- printf("%d ", i); // expect: 4
- printf("\n");
-}
diff --git a/other/excel_sheet_column_title.cpp b/other/excel_sheet_column_title.cpp
deleted file mode 100644
index 3de395f..0000000
--- a/other/excel_sheet_column_title.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-// 168. Excel Sheet Column Title
-#include "leetcode.h"
-
-/*
- * given an integer 'column_number', return its corresponding column title as it
- * appears in an excel sheet. for example: A -> 1 B -> 2 C -> 3
- * ...
- * Z -> 26
- * AA -> 27
- * AB -> 28
- * ...
- */
-
-class Solution {
-public:
- string convertToTitle(int n) {
- if (n < 27)
- return string(1, 'A' + (n - 1) % 26);
- string ans = "";
- while (n > 0) {
- if (!(n % 26)) {
- ans += 'A' + 25;
- n--;
- } else {
- ans += 'A' + n % 26 - 1;
- }
- n /= 26;
- }
- reverse(ans.begin(), ans.end());
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.convertToTitle(1) << endl; // expect: A
- cout << obj.convertToTitle(28) << endl; // expect: AB
- cout << obj.convertToTitle(701) << endl; // expect: ZY
-}
diff --git a/other/extra_char_string.cpp b/other/extra_char_string.cpp
deleted file mode 100644
index b26cb93..0000000
--- a/other/extra_char_string.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-// 2707. Extra Characters in a String
-#include "leetcode.h"
-
-/*
- * you are given a 0-indexed string 's' and a dictionary of words 'dictionary'.
- * you have to break 's' into one or more non-overlapping substrings that each
- * substring is present in 'dictionary'. there may be some extra characters in
- * 's' which are not present in any of the substrings. return the minimum number
- * of extra characters left over if you break up 's' optimally
- */
-
-class Solution {
- int mod = 1e7 + 7;
- int hash_func(string s) {
- int res = 0;
- for (auto i : s)
- res = (res * 27 + i - 'a' + 1) % mod;
- return res;
- }
- int min_cost(int l, vector<int> &dp, string s, unordered_set<int> &d) {
- if (l == s.size())
- return 0;
- if (dp[l] != -1)
- return dp[l];
- int res = 1 + min_cost(l + 1, dp, s, d), curr = 0;
- for (int i = l; i < s.size(); i++) {
- curr = (curr * 27 + s[i] - 'a' + 1) % mod;
- if (d.find(curr) != d.end())
- res = min(res, min_cost(i + 1, dp, s, d));
- }
- return dp[l] = res;
- }
-
-public:
- int minExtraChar(string s, vector<string> &dictionary) {
- unordered_set<int> d;
- for (auto i : dictionary)
- d.insert(hash_func(i));
- vector<int> dp(s.size(), -1);
- return min_cost(0, dp, s, d);
- }
-};
-
-int main() {
- Solution obj;
- string s1 = "leetscode", s2 = "sayhelloworld";
- vector<string> d1 = {"leet", "code", "leetcode"}, d2 = {"hello", "world"};
- printf("%d\n", obj.minExtraChar(s1, d1)); // expepct: 1
- printf("%d\n", obj.minExtraChar(s2, d2)); // expepct: 3
-}
diff --git a/other/fair_distribution_cookie.cpp b/other/fair_distribution_cookie.cpp
deleted file mode 100644
index 69e0ab4..0000000
--- a/other/fair_distribution_cookie.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-// 2305. Fair Distribution of Cookies
-#include "leetcode.h"
-
-/*
- * given an integer array 'cookies', where 'cookies[i]' denotes the number of
- * cookies in the i'th bag. you are also given an integer 'k' that denotes the
- * number of children to distribute all the bags of cookies to. all the cookies
- * in the same bag must go to the same child and cannot be split up. the
- * unfairness of a distribution is defined as the maximum total cookies obtained
- * by a single child in the distribution. return the minimum unfairness of all
- * distributions
- */
-
-class Solution {
- int ans = INT_MAX;
- void solve(int start, vector<int> &cookies, vector<int> &v, int k) {
- if (start == cookies.size()) {
- int max_m = INT_MIN;
- for (int i = 0; i < k; k++)
- max_m = max(max_m, v[i]);
- ans = min(ans, max_m);
- return;
- }
- for (int i = 0; i < k; i++) {
- v[i] += cookies[start];
- solve(start + 1, cookies, v, k);
- v[i] -= cookies[start];
- }
- }
-
-public:
- int distributeCookies(vector<int> &cookies, int k) {
- int n = cookies.size();
- vector<int> v(k, 0);
- solve(0, cookies, v, k);
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> c1 = {8, 15, 10, 20, 8}, c2 = {6, 1, 3, 2, 2, 4, 1, 2};
- printf("%d\n", obj.distributeCookies(c1, 2)); // expect: 31
- printf("%d\n", obj.distributeCookies(c2, 3)); // expect: 7
-}
diff --git a/other/far_from_land.cpp b/other/far_from_land.cpp
deleted file mode 100644
index 651b8a7..0000000
--- a/other/far_from_land.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maxDistance(vector<vector<int>> &grid) {
- int ans = -1;
- if (grid.empty() || grid[0].empty())
- return ans;
-
- vector<vector<int>> gridValues(grid.size(),
- vector<int>(grid[0].size(), INT_MAX));
- queue<pair<int, int>> q;
-
- for (int i = 0; i < grid.size(); ++i) {
- for (int j = 0; j < grid[0].size(); ++j) {
- if (grid[i][j] == 1) {
- q.push(make_pair(i, j));
- gridValues[i][j] = 0;
- }
- }
- }
- if (q.empty())
- return -1;
- vector<int> dx({0, 1, 0, -1}), dy({1, 0, -1, 0});
- while (!q.empty()) {
- auto pos = q.front();
- q.pop();
- for (int i = 0; i < 4; ++i) {
- int x = pos.first + dx[i], y = pos.second + dy[i];
- if (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size()) {
- if (gridValues[x][y] == INT_MAX)
- q.push(make_pair(x, y));
- gridValues[x][y] =
- min(gridValues[x][y], gridValues[pos.first][pos.second] + 1);
- }
- }
- }
- for (int i = 0; i < grid.size(); ++i)
- for (int j = 0; j < grid[0].size(); ++j)
- if (grid[i][j] == 0)
- ans = max(ans, gridValues[i][j]);
- return ans;
- }
-};
diff --git a/other/fibonacci_number.cpp b/other/fibonacci_number.cpp
deleted file mode 100644
index 69e46ee..0000000
--- a/other/fibonacci_number.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int fib(int n) {
- if (n < 2)
- return n;
- int ans[n + 1];
- ans[0] = 0;
- ans[1] = 1;
- for (int i = 2; i <= n; i++)
- ans[i] = ans[i - 1] + ans[i - 2];
- return ans[n];
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.fib(2);
-}
diff --git a/other/find_all_anagrams.cpp b/other/find_all_anagrams.cpp
deleted file mode 100644
index 39fe153..0000000
--- a/other/find_all_anagrams.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 438. Find All Anagrams in a String
-#include "leetcode.h"
-
-/*
- * given two strings 's & p', return an array of all the start indices of 'p's
- * anagrams in 's' (any order). an anagram is a word or phrase formed by
- * rearranging the letters of a different word or phrase, typically using all
- * original letters exactly one
- */
-
-class Solution {
-public:
- vector<int> findAnagrams(string s, string p) {
- int ssz = s.size(), psz = p.size();
- if (ssz < psz)
- return {};
- vector<int> freq(26, 0), window(26, 0), ans;
- for (int i = 0; i < psz; i++) {
- freq[p[i] - 'a']++;
- window[s[i] - 'a']++;
- }
- if (freq == window)
- ans.push_back(0);
- for (int i = psz; i < ssz; i++) {
- window[s[i - psz] - 'a']--;
- window[s[i] - 'a']++;
- if (freq == window)
- ans.push_back(i - psz + 1);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- for (auto i : obj.findAnagrams("cbaebabacd", "abc"))
- cout << i << ' '; // expect 0 6
- for (auto i : obj.findAnagrams("abab", "ab"))
- cout << i << ' '; // expect 0 1 2
-}
diff --git a/other/find_building_alice_bob_meet.cpp b/other/find_building_alice_bob_meet.cpp
deleted file mode 100644
index 2288095..0000000
--- a/other/find_building_alice_bob_meet.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-// 2940. Find Building Where Alice and Bob Can Meet
-#include "leetcode.h"
-
-/*
- * you are given a 0-indexed array 'heights' of positive integers where
- * 'heights[i]' represents the height of the i'th building. if a person is in
- * building 'i', they can move to any other building 'j' if and only if 'i < j'
- * and 'heights[i] < heights[j]'. you are also given an array 'queries' where
- * 'queries[i] = [a_i, b_i]'. on the i'th query, alice is in building 'a_i', and
- * bob is in building 'b_i'. return array 'ans' where 'ans[i]' is the index of
- * the leftmost building where alice and bob can meet on i'th query. if alice
- * and bob cannot move to a common building on query 'i', set 'ans[i]' to -1
- */
-
-class Solution {
-public:
- vector<int> leftmostBuildingQueries(vector<int> &heights,
- vector<vector<int>> &queries) {
- int hn = heights.size(), qn = queries.size();
- vector<vector<vector<int>>> q(hn);
- priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;
- vector<int> ans(qn, -1);
- for (int qi = 0; qi < qn; qi++) {
- int i = queries[qi][0], j = queries[qi][1];
- if (i < j && heights[i] < heights[j])
- ans[qi] = j;
- else if (i > j && heights[i] > heights[j])
- ans[qi] = i;
- else if (i == j)
- ans[qi] = i;
- else
- q[max(i, j)].push_back({max(heights[i], heights[j]), qi});
- }
- for (int i = 0; i < hn; i++) {
- while (!pq.empty() && pq.top()[0] < heights[i]) {
- ans[pq.top()[1]] = i;
- pq.pop();
- }
- for (auto &j : q[i])
- pq.push(j);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> h1 = {6, 4, 8, 5, 2, 7}, h2 = {5, 3, 8, 2, 6, 1, 4, 6};
- vvd q1 = {{0, 1}, {0, 3}, {2, 4}, {3, 4}, {2, 2}},
- q2 = {{0, 7}, {3, 5}, {5, 2}, {3, 0}, {1, 6}};
- vector<int> lmbq1 = obj.leftmostBuildingQueries(h1, q1);
- vector<int> lmbq2 = obj.leftmostBuildingQueries(h2, q2);
- for (auto i : lmbq1)
- printf("%d ", i); // expect: 2 5 -1 5 2
- printf("\n");
- for (auto i : lmbq2)
- printf("%d ", i); // expect: 7 6 -1 4 6
- printf("\n");
-}
diff --git a/other/find_critical_edge_tree.cpp b/other/find_critical_edge_tree.cpp
deleted file mode 100644
index 898fd81..0000000
--- a/other/find_critical_edge_tree.cpp
+++ /dev/null
@@ -1,101 +0,0 @@
-// 1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
-#include "leetcode.h"
-
-/*
- * given a weighted undirected connected graph with 'n' vertices numbered from 0
- * to 'n - 1' and an array 'edges' where 'edges[i] = [ai, bi, weighti]'
- * represents a bidrectional and weighted edge between nodes 'ai' and 'bi'. a
- * minimum spanning tree (MST) is a subset of the graph's edges that connects
- * all vertices withoutcycles and with the minimum possible total edge weight.
- * find all critical and pseudo-critical edges in the given graph's MST. an MST
- * edge whose deletion from the graph would casue the MST weight to increase is
- * called a critical edge. on the other hand, a pseudo-critical edge is that
- * which can appear in some MSTs butnot all. note that you can return the
- * indices of the edges in any order.
- */
-
-class UnionFind {
- vector<int> f, rank;
-
-public:
- UnionFind(int n) {
- rank = vector<int>(n, 1);
- f.resize(n);
- for (int i = 0; i < n; ++i)
- f[i] = i;
- }
- int find(int x) {
- if (f[x] == x)
- return x;
- else
- return f[x] = find(f[x]);
- }
- void uinion(int x, int y) {
- int fx = find(x), fy = find(y);
- if (fx == fy)
- return;
- if (rank[fx] > rank[fy])
- swap(fx, fy);
- f[fx] = fy;
- if (rank[fx] == rank[fy])
- rank[fy]++;
- }
-};
-
-class Solution {
- int get_mst(const int n, const vvd & edges, int block_edge,
- int pre_edge = -1) {
- UnionFind uf(n);
- int weight = 0;
- if (pre_edge != -1) {
- weight += edges[pre_edge][2];
- uf.uinion(edges[pre_edge][0], edges[pre_edge][1]);
- }
- for (int i = 0; i < edges.size(); ++i) {
- if (block_edge == i)
- continue;
- const auto &e = edges[i];
- if (uf.find(e[0]) == uf.find(e[1]))
- continue;
- uf.uinion(e[0], e[1]);
- weight += e[2];
- }
- for (int i = 0; i < n; ++i)
- if (uf.find(i) != uf.find(0))
- return 1e9 + 7;
- return weight;
- }
-
-public:
- vvd findCriticalAndPseudoCriticalEdges(int n, vvd & edges) {
- for (int i = 0; i < edges.size(); ++i)
- edges[i].push_back(i);
- sort(
- edges.begin(), edges.end(),
- [](const vector<int> &a, const vector<int> &b) { return a[2] < b[2]; });
- int origin_mst = get_mst(n, edges, -1);
- vector<int> critical, non_critical;
- for (int i = 0; i < edges.size(); ++i) {
- if (origin_mst < get_mst(n, edges, i))
- critical.push_back(edges[i][3]);
- else if (origin_mst == get_mst(n, edges, -1, i))
- non_critical.push_back(edges[i][3]);
- }
- return {critical, non_critical};
- }
-};
-
-int main() {
- Solution obj;
- vvd e1 = {{0, 1, 1}, {1, 2, 1}, {2, 3, 2}, {0, 3, 2},
- {0, 4, 3}, {3, 4, 3}, {1, 4, 6}},
- e2 = {{0, 1, 1}, {1, 2, 1}, {2, 3, 1}, {0, 3, 1}};
- for (auto i : obj.findCriticalAndPseudoCriticalEdges(5, e1))
- for (auto j : i)
- printf("%d ", j);
- printf("\n");
- for (auto i : obj.findCriticalAndPseudoCriticalEdges(4, e2))
- for (auto j : i)
- printf("%d ", j);
- printf("\n");
-}
diff --git a/other/find_duplicate_file.cpp b/other/find_duplicate_file.cpp
deleted file mode 100644
index 17ff6f0..0000000
--- a/other/find_duplicate_file.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vvd(string) findDuplicate(vector<string> &paths) {
- unordered_map<string, vector<string>> files;
- vvd(string) ans;
- for (auto &path : paths) {
- int i = 0, j;
- while (path[i] != ' ')
- i++;
- string dir = path.substr(0, i), file, content;
- while (i++ < path.size()) {
- j = i;
- while (path[i] != '(')
- i++;
- file = path.substr(j, i - j);
- j = i;
- while (path[i++] != ')')
- ;
- content = path.substr(j, i - j);
- files[content].emplace_back(dir + '/' + file);
- }
- }
- for (auto &content : files)
- if (content.second.size() > 1)
- ans.push_back(move(content.second));
- return ans;
- }
-};
diff --git a/other/find_duplicate_subtree.cpp b/other/find_duplicate_subtree.cpp
deleted file mode 100644
index 5880fc8..0000000
--- a/other/find_duplicate_subtree.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-// 652. Find Duplicate Subtrees
-#include "leetcode.h"
-
-/*
- * given 'root' of a binary tree, return all duplicate subtrees. for each kind
- * of duplicate, only return the root node of any one of them. two trees are
- * duplicate if they have the same structure with the same node values.
- */
-
-class Solution {
-public:
- vector<TreeNode *> findDuplicateSubtrees(TreeNode *root) {
- unordered_map<string, vector<TreeNode *>> map;
- vector<TreeNode *> dups;
- serialise(root, map);
- for (auto it = map.begin(); it != map.end(); it++)
- if (it->second.size() > 1)
- dups.push_back(it->second[0]);
- return dups;
- }
-
-private:
- string serialise(TreeNode *node,
- unordered_map<string, vector<TreeNode *>> &map) {
- string s = "(" + serialise(node->left, map) + to_string(node->val) +
- serialise(node->right, map) + ")";
- map[s].push_back(node);
- return s;
- }
-};
diff --git a/other/find_first_last_array.cpp b/other/find_first_last_array.cpp
deleted file mode 100644
index 7f5f989..0000000
--- a/other/find_first_last_array.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> searchRange(vector<int> &nums, int target) {
- int tLeft = find(target, nums);
- if (tLeft == nums.size() || nums[tLeft] != target)
- return {-1, -1};
- return {tLeft, find(target + 1, nums, tLeft) - 1};
- }
- int find(int target, vector<int> arr, int left = 0) {
- int right = arr.size() - 1;
- while (left <= right) {
- int mid = left + right >> 1;
- if (arr[mid] < target)
- left = mid + 1;
- else
- right = mid - 1;
- }
- return left;
- }
-};
diff --git a/other/find_groups_farmland.cpp b/other/find_groups_farmland.cpp
deleted file mode 100644
index d496633..0000000
--- a/other/find_groups_farmland.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vvd findFarmland(vvd & land) {
- int n = land.size(), m = land[0].size();
- vvd ans;
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < m; j++) {
- if (land[i][j] == 1) {
- if ((!i || !land[i - 1][j]) && (!j || !land[i][j - 1])) {
- int right = j, down = i;
- while (down + 1 < n && land[down + 1][j] == 1)
- down++;
- while (right + 1 < m && land[i][right + 1] == 1)
- right++;
- ans.push_back({i, j, down, right});
- }
- }
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd l1 = {{1, 0, 0},
- {
- 0,
- 1,
- 1,
- },
- {0, 1, 1}};
- vvd l2 = {{1, 1}, {1, 1}};
- for (auto i : obj.findFarmland(l1))
- for (auto j : i)
- printf("%d ", j); // expect: [[0,0,0,0],[1,1,2,2]]
- printf("\n");
- for (auto i : obj.findFarmland(l2))
- for (auto j : i)
- printf("%d ", j); // expect: [[0,0,1,1]]
-}
diff --git a/other/find_highest_altitude.cpp b/other/find_highest_altitude.cpp
deleted file mode 100644
index c67dbac..0000000
--- a/other/find_highest_altitude.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-// 1732. Find the Highest Altitude
-#include "leetcode.h"
-
-/*
- * 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 0. given an integer array 'ain' of length 'n' where 'gain[i]' is the
- * net gain in altidude between points 'i' and 'i + 1' for all '0 <= i < n'.
- * return the highest altitude of a point
- */
-
-class Solution {
-public:
- int largestAltitude(vector<int> &gain) {
- int ans = INT_MIN, pre_sum = 0;
- for (int i = 0; i < gain.size(); i++) {
- ans = max(pre_sum, ans);
- pre_sum += gain[i];
- }
- if (pre_sum > ans)
- ans = pre_sum;
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> g1 = {-5, 1, 5, 0, -7}, g2 = {-4, -3, -2, -1, 4, 3, 2};
- printf("%d\n", obj.largestAltitude(g1)); // expect: 1
- printf("%d\n", obj.largestAltitude(g2)); // expect: 0
-}
diff --git a/other/find_k_beauty_num.cpp b/other/find_k_beauty_num.cpp
deleted file mode 100644
index a8a224e..0000000
--- a/other/find_k_beauty_num.cpp
+++ /dev/null
@@ -1,16 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int divisorSubStrings(int num, int k) {}
-};
-
-int main() {
- Solution obj;
- cout << obj.divisorSubStrings(240, 2);
-
- int num = 240, k = 2;
- string s = to_string(num);
- int i = 0, j = 0, n = s.size();
- cout << s.size();
-}
diff --git a/other/find_k_closest_elements.cpp b/other/find_k_closest_elements.cpp
deleted file mode 100644
index e15810c..0000000
--- a/other/find_k_closest_elements.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// 658. Find K Closest Elements
-#include "leetcode.h"
-
-/*
- * given a sorted integer array 'arr', two integers 'k' and 'x', return the 'k'
- * closest integers to 'x' in the array. the result should also be sorted in
- * ascending order. an integer 'a' is closer to 'x' than an integer 'b' if '|a -
- * x| < |b - x|' or '|a - x| == |b - x|' and 'a < b'.
- */
-
-class Solution {
-public:
- vector<int> findClosestElements(vector<int> &arr, int k, int x) {
- int l = 0, r = arr.size() - k;
- while (l < r) {
- int m = (l + r) / 2;
- if (x - arr[m] > arr[m + k] - x)
- l = m + 1;
- else
- r = m;
- }
- return vector<int>(arr.begin() + l, arr.begin() + l + k);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> a1 = {1, 2, 3, 4, 5}, a2 = {1, 2, 3, 4, 5};
- vector<int> fce1 = obj.findClosestElements(a1, 4, 3);
- vector<int> fce2 = obj.findClosestElements(a2, 4, -1);
- for (int i = 0; i < fce1.size(); i++)
- printf("%d ", fce1[i]); // expect: 1 2 3 4
- printf("\n");
- for (int i = 0; i < fce2.size(); i++)
- printf("%d ", fce2[i]); // expect: 1 2 3 4
- printf("\n");
-}
diff --git a/other/find_k_pair_sum.cpp b/other/find_k_pair_sum.cpp
deleted file mode 100644
index 94b779a..0000000
--- a/other/find_k_pair_sum.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-// 373. Find K Pairs with Smallest Sums
-#include "leetcode.h"
-
-/*
- * given two integer arrays 'nums1 nums2' sorted in ascending order and an
- * integer k. define a pair '(u, v)' which consists of one element from the
- * first array and one element from the second array. return the 'k' pairs '(u1,
- * v1), (u2, v2), ..., (uk, vk)' with the smallest sums
- */
-
-class Solution {
-public:
- vvd kSmallestPairs(vector<int> &nums1, vector<int> &nums2, int k) {
- priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>,
- greater<pair<int, pair<int, int>>>>
- pq;
- int n = nums1.size(), m = nums2.size();
- vvd ans;
- for (int i = 0; i < n; i++)
- pq.push({nums1[i] + nums2[0], {i, 0}});
- while (!pq.empty() && k--) {
- pair<int, pair<int, int>> tp = pq.top();
- int x = tp.second.first, y = tp.second.second;
- pq.pop();
- ans.push_back({nums1[x], nums2[y]});
- if (y != m - 1)
- pq.push({nums1[x] + nums2[y + 1], {x, y + 1}});
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n11 = {1, 7, 11}, n21 = {2, 4, 6};
- vector<int> n12 = {1, 1, 2}, n22 = {1, 2, 3};
- vector<int> n13 = {1, 2}, n23 = {3};
- for (auto i : obj.kSmallestPairs(n11, n21, 3))
- for (auto j : i)
- printf("%d ", j);
- printf("\n");
- for (auto i : obj.kSmallestPairs(n12, n22, 2))
- for (auto j : i)
- printf("%d ", j);
- printf("\n");
- for (auto i : obj.kSmallestPairs(n13, n23, 3))
- for (auto j : i)
- printf("%d ", j);
- printf("\n");
-}
diff --git a/other/find_max_sum_node_val.cpp b/other/find_max_sum_node_val.cpp
deleted file mode 100644
index 60c43b8..0000000
--- a/other/find_max_sum_node_val.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-// 3068. Find the Maximum Sum of Node Values
-#include "leetcode.h"
-
-/*
- * there exists an undirected tree with 'n' nodes numbered 0 to 'n - 1'. you are
- * given a 0-indexed 2d integer array 'edges' of length 'n - 1', where 'edges[i]
- * = [ui,vi]' indicates that there is an edge between nodes 'ui' and 'vi' in the
- * tree. you are also given a positive integer 'k' and a 0 indexed array of non
- * negative integers 'nums' of length 'n' where 'nums[i]' represents the value
- * of the node numbered 'i'. return the maximum possible sum of the values alice
- * can achieve by performing the operation any number of times.
- */
-
-class Solution {
-public:
- long long maximumValueSum(vector<int> &nums, int k,
- vector<vector<int>> &edges) {
- int change = 0;
- long long sum = 0LL, ans = 0LL;
- for (auto &n : nums) {
- if ((n ^ k) > n) {
- change++;
- sum += (n ^ k);
- } else
- sum += n;
- }
- if (!(change & 1))
- return sum;
- for (int i = 0; i < nums.size(); i++)
- ans = max(ans, sum - abs(nums[i] - (nums[i] ^ k)));
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 2, 1}, n2 = {2, 3}, n3 = {7, 7, 7, 7, 7, 7};
- vvd e1 = {{0, 1}, {0, 2}}, e2 = {{0, 1}},
- e3 = {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}};
- printf("%lld\n", obj.maximumValueSum(n1, 3, e1)); // expect: 6
- printf("%lld\n", obj.maximumValueSum(n2, 7, e2)); // expect: 9
- printf("%lld\n", obj.maximumValueSum(n3, 3, e3)); // expect: 42
-}
diff --git a/other/find_median_data_stream.cpp b/other/find_median_data_stream.cpp
deleted file mode 100644
index 14fbcc3..0000000
--- a/other/find_median_data_stream.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-#include "leetcode.h"
-
-class MedianFinder {
-public:
- void addNum(int num) {
- small.push(num);
- large.push(-small.top());
- small.pop();
- if (small.size() < large.size()) {
- small.push(-large.top());
- large.pop();
- }
- }
- double findMedian() {
- if (small.size() > large.size())
- return small.top();
- else
- return (small.top() - large.top()) / 2.0;
- }
-
-private:
- priority_queue<long> small, large;
-};
-
-int main() {
- MedianFinder *obj = new MedianFinder();
- obj->addNum(69);
- double param_2 = obj->findMedian();
-}
diff --git a/other/find_median_data_stream.rs b/other/find_median_data_stream.rs
deleted file mode 100644
index 1ef5252..0000000
--- a/other/find_median_data_stream.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-use std::cmp::Reverse;
-use std::collections::BinaryHeap;
-#[derive(Default)]
-struct MedianFinder {
- small: BinaryHeap<i32>,
- large: BinaryHeap<Reverse<i32>>,
- odd: bool
-}
-
-impl MedianFinder {
- fn new() -> Self {
- Default::default()
- }
- fn add_num(&mut self, num: i32) {
- if self.odd {
- self.small.push(num);
- if let Some(max) = self.small.pop() {
- self.large.push(Reverse(max));
- }
- } else {
- self.large.push(Reverse(num));
- if let Some(Reverse(min)) = self.large.pop() {
- self.small.push(min);;
- }
- }
- self.odd = !self.odd;
- }
- fn find_median(&self) -> f64 {
- if self.odd {
- *self.small.peek().unwrap() as f64
- } else {
- (self.small.peek().unwrap() + self.large.peek().unwrap().0) as f64 / 2.0
- }
- }
-}
-
-fn main() {
- let obj = MedianFinder::new();
- obj.add_num(num);
- let ret_2: f64 = obj.find_median();
-}
diff --git a/other/find_orig_array_double.cpp b/other/find_orig_array_double.cpp
deleted file mode 100644
index a434616..0000000
--- a/other/find_orig_array_double.cpp
+++ /dev/null
@@ -1,19 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> findOriginalArray(vector<int> &changed) {
- int count[100001] = {}, i = 0;
- vector<int> ans;
- for (auto n : changed)
- ++count[n];
- for (int i = 0; i <= 50000; ++i)
- if (count[i]) {
- if (--count[i * 2] < 0 || --count[i] < 0)
- return {};
- ans.push_back(i--);
- }
- return accumulate(begin(count) + 50000, end(count), 0ll) ? vector<int>()
- : ans;
- }
-};
diff --git a/other/find_path_graph.cpp b/other/find_path_graph.cpp
deleted file mode 100644
index 9f6c8ae..0000000
--- a/other/find_path_graph.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool validPath(int n, vvd & edges, int source, int destination) {
- vector<int> ds(n, -1);
- for (auto &e : edges) {
- int p1 = find(ds, e[0]), p2 = find(ds, e[1]);
- if (p1 != p2)
- ds[p2] = p1;
- }
- return find(ds, source) == find(ds, destination);
- }
-
-private:
- int find(vector<int> &ds, int i) {
- return ds[i] < 0 ? i : ds[i] = find(ds, ds[i]);
- }
-};
-
-int main() {
- Solution obj;
- vvd edges = {{0, 1}, {1, 2}, {2, 0}};
- if (obj.validPath(3, edges, 0, 2))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/find_path_graph.rs b/other/find_path_graph.rs
deleted file mode 100644
index a74a654..0000000
--- a/other/find_path_graph.rs
+++ /dev/null
@@ -1,48 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn valid_path(n: i32, edges: Vec<Vec<i32>>, source: i32, destination: i32) -> bool {
- let n: usize = n as usize;
- let mut roots: Vec<usize> = {
- let mut ans: Vec<usize> = vec![0; n];
- for i in 0..n {
- ans[i] = i;
- }
- ans
- };
- let mut ranks: Vec<usize> = vec![1; n];
- for e in edges {
- let u = e[0] as usize;
- let v = e[1] as usize;
- Self::union(u, v, &mut roots, &mut ranks);
- }
- Self::find(source as usize, &mut roots) == Self::find(destination as usize, &mut roots)
- }
- fn union(x: usize, y: usize, roots: &mut Vec<usize>, ranks: &mut Vec<usize>) {
- let (root_x, root_y) = (Self::find(x, roots), Self::find(y, roots));
- if root_x == root_y {
- return;
- }
- if ranks[x] > ranks[y] {
- roots[root_y] = root_x;
- ranks[root_x] += 1;
- } else {
- roots[root_x] = root_y;
- ranks[root_y] += 1;
- }
- }
- fn find(x: usize, roots: &mut Vec<usize>) -> usize {
- let mut x = x;
- while x != roots[x] {
- roots[x] = roots[roots[x]];
- x = roots[x];
- }
- x
- }
-}
-
-fn main() {
- let (n, source, destination) = (3, 0, 2);
- let edges = vec![vec![0,1], vec![1,2], vec![2,0]];
- print!("{}", Solution::valid_path(n, edges, source, destination));
-}
diff --git a/other/find_player_zero_one_loss.cpp b/other/find_player_zero_one_loss.cpp
deleted file mode 100644
index 5aba77e..0000000
--- a/other/find_player_zero_one_loss.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vvd findWinners(vvd & matches) {
- map<int, int> lost;
- for (auto m : matches) {
- if (!lost.count(m[0]))
- lost[m[0]] = 0;
- lost[m[1]]++;
- }
- vector<int> zero, ones;
- for (auto [k, l] : lost) {
- if (l == 0)
- zero.push_back(k);
- if (l == 1)
- ones.push_back(k);
- }
- return {zero, ones};
- }
-};
diff --git a/other/find_player_zero_one_loss.rs b/other/find_player_zero_one_loss.rs
deleted file mode 100644
index a0ae44e..0000000
--- a/other/find_player_zero_one_loss.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-use std::collections::BTreeMap;
-struct Solution;
-
-impl Solution {
- pub fn find_winners(matches: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
- let mut lost: BTreeMap<i32, i32> = matches.into_iter().fold(BTreeMap::new(), |mut hm, m| {
- hm.entry(m[0]).or_insert(0);
- *hm.entry(m[1]).or_insert(0) += 1;
- hm
- });
- return vec![lost.iter().filter(|(_, l)| **l == 0).map(|(&i, _)| i).collect(),
- lost.iter().filter(|(_, l)| **l == 1).map(|(&i, _)| i).collect()];
- }
-}
diff --git a/other/find_replace_pattern.cpp b/other/find_replace_pattern.cpp
deleted file mode 100644
index a00bfcb..0000000
--- a/other/find_replace_pattern.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<string> findAndReplacePattern(vector<string> &words, string pattern) {
- ans.resize(0);
- codex.clear();
- cipher = pattern;
- for (int i = 0; i < pattern.size(); i++)
- cipher[i] = translate(cipher[i]);
- for (auto &word : words)
- compare(word);
- return ans;
- }
-
-private:
- vector<string> ans;
- unordered_map<char, char> codex;
- string cipher;
- char translate(char &c) {
- if (codex.find(c) == codex.end())
- codex[c] = (char)(97 + codex.size());
- return codex[c];
- }
- void compare(string &word) {
- codex.clear();
- for (int i = 0; i < word.size(); i++)
- if (translate(word[i]) != cipher[i])
- return;
- ans.push_back(word);
- }
-};
diff --git a/other/find_safest_path_grid.cpp b/other/find_safest_path_grid.cpp
deleted file mode 100644
index e6dcc3b..0000000
--- a/other/find_safest_path_grid.cpp
+++ /dev/null
@@ -1,89 +0,0 @@
-// 2812. Find the Safest Path in a Grid
-#include "leetcode.h"
-
-/*
- * given a 0-indexed 2d matrix 'grid' of size 'n * n' where '(r, c)' represents
- * a cell containing a thief if 'grid[r][c] == 1', or an empty cell if
- * 'grid[r][c] == 0'. you are initially positioned at cell '(0, 0)'. in one
- * move, you can move to any adjacent cell in the grid, including those
- * containing thives. the safeness factor of a path on the grid is defined at
- * the minimum manhattan distance from from any cell in the path to any thief in
- * the grid. return the maximum safeness factor of all paths leading to cell '(n
- * - 1, n - 1)'.
- */
-
-class Solution {
-private:
- int n, dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
- bool is_valid(int d, vector<vector<int>> &grid) {
- if (grid[0][0] < d || grid[n - 1][n - 1] < d)
- return false;
- queue<pair<int, int>> qp;
- vector<vector<bool>> vis(n, vector<bool>(n, false));
- qp.push({0, 0});
- vis[0][0] = true;
- while (qp.empty()) {
- auto [x, y] = qp.front();
- qp.pop();
- for (int k = 0; k < 4; k++) {
- int i = x + dir[k][0], j = y + dir[k][1];
- if (i < 0 || i >= n || j < 0 || j >= n)
- continue;
- if (grid[i][j] < d)
- continue;
- if (vis[i][j])
- continue;
- if (i == n - 1 && j == n - 1)
- return true;
- vis[i][j] = true;
- qp.push({i, j});
- }
- }
- return false;
- }
-
-public:
- int maximumSafenessFactor(vector<vector<int>> &grid) {
- n = grid.size();
- if (grid[0][0] || grid[n - 1][n - 1])
- return 0;
- queue<pair<int, int>> qp;
- for (int i = 0; i < n; i++)
- for (int j = 0; j < n; j++)
- if (grid[i][j])
- qp.push({i, j});
- while (!qp.empty()) {
- int len = qp.size();
- for (int l = 0; l < len; l++) {
- auto [x, y] = qp.front();
- qp.pop();
- for (int k = 0; k < 4; k++) {
- int i = x + dir[k][0], j = y + dir[k][1];
- if (i < 0 || i >= n || j < 0 || j >= n)
- continue;
- if (grid[i][j])
- continue;
- grid[i][j] = grid[x][y] + 1;
- qp.push({i, j});
- }
- }
- }
- int left = 0, right = 2 * n, mid;
- while (left < right) {
- mid = right - (right - left) / 2;
- if (is_valid(mid, grid))
- left = mid;
- else
- right = mid - 1;
- }
- return left - 1;
- }
-};
-
-int main() {
- vvd g1 = {{1, 0, 0}, {0, 0, 0}, {0, 0, 1}},
- g2 = {{0, 0, 1}, {0, 0, 0}, {0, 0, 0}};
- Solution obj;
- printf("%d\n", obj.maximumSafenessFactor(g1)); // expect: 0
- printf("%d\n", obj.maximumSafenessFactor(g2)); // expect: 2
-}
diff --git a/other/find_score_arr_mark.cpp b/other/find_score_arr_mark.cpp
deleted file mode 100644
index 42f2e6a..0000000
--- a/other/find_score_arr_mark.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 2593. Find Score of an Array After Marking All Elements
-#include "leetcode.h"
-
-/*
- * given an array 'nums' consisting of positive integers. starting with 'score =
- * 0', apply the following algorithm
- * - choose the smallest integer of the array that is not marked. if there is a
- * tie, choose the one with the smallest index
- * - add the value of the chosen integer to 'score'
- * - mark the chosen element and its two adjacent elements if they exist
- * - repeat until all the array elements are marked
- * return the score you get after applying the above algorithm
- */
-
-class Solution {
-public:
- long long findScore(vector<int> &nums) {
- long long ans = 0;
- set<pair<int, int>> s;
- for (int i = 0; i < nums.size(); ++i)
- s.insert({nums[i], i});
- for (auto i : s)
- if (nums[i.second]) {
- nums[i.second] = 0;
- if (i.second - 1 >= 0)
- nums[i.second - 1] = 0;
- if (i.second + 1 < nums.size())
- nums[i.second + 1] = 0;
- ans += i.first;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {2, 1, 3, 4, 5, 2}, n2 = {2, 3, 5, 1, 3, 2};
- printf("%lld\n", obj.findScore(n1)); // expect: 7
- printf("%lld\n", obj.findScore(n2)); // expect: 5
-}
diff --git a/other/find_smallest_letter.cpp b/other/find_smallest_letter.cpp
deleted file mode 100644
index 01a5562..0000000
--- a/other/find_smallest_letter.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-// 744. Find Smallest Letter Greater Than Target
-#include "leetcode.h"
-
-/*
- * given an array of characters 'letters' that is sorted in non-decreasing
- * order, and a character 'target'. there are at least two different characters
- * in 'letters'. return the smallest character in 'letters' that is
- * lexicographically greater than 'target'. if such a character does not exist,
- * return the first character in 'letters'.
- */
-
-class Solution {
-public:
- char nextGreatestLetter(vector<char> &letters, char target) {
- int low = 0, high = letters.size() - 1;
- while (low < high) {
- int mid = low + (high - low) / 2;
- if (letters[mid] <= target)
- low = mid + 1;
- else
- high = mid;
- }
- return letters[low] > target ? letters[low] : letters[0];
- }
-};
-
-int main() {
- Solution obj;
- vector<char> l1_2 = {'c', 'f', 'j'};
- vector<char> l3 = {'x', 'x', 'y', 'y'};
- printf("%c", obj.nextGreatestLetter(l1_2, 'a')); // expect: c
- printf("%c", obj.nextGreatestLetter(l1_2, 'c')); // expect: f
- printf("%c", obj.nextGreatestLetter(l3, 'z')); // expect: x
-}
diff --git a/other/find_town_judge.cpp b/other/find_town_judge.cpp
deleted file mode 100644
index 5607688..0000000
--- a/other/find_town_judge.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-// 997. Find the Town Judge
-#include "leetcode.h"
-
-/*
- * in a town, there are 'n' people labeled from 1 to 'n'. there is a rumor that
- * one of these people is secretly the town judge. if the town judge exists,
- * then: the town judge trusts nobody. everybody (except the judge) trusts the
- * judge. given: array 'trust' where 'trust[i]' = [ai, bi] representing the the
- * person labeled ai trusts the person labeled bi. return label of judge, if
- * they exist.
- */
-
-class Solution {
-public:
- int findJudge(int n, vvd trust) {
- vector<unordered_set<int>> graph(n + 1, unordered_set<int>());
- for (auto &edge : trust) {
- int a = edge[0], b = edge[1];
- graph[a].insert(b); // a trusts b
- }
- int townJudge = -1;
- for (int i = 1; i <= n; ++i)
- if (graph[i].size() == 0) {
- townJudge = i;
- break;
- }
- if (townJudge == -1)
- return -1;
- for (int i = 1; i <= n; ++i) {
- if (i == townJudge)
- continue;
- if (!graph[i].count(townJudge))
- return -1;
- }
- return townJudge;
- }
-};
-
-int main() {
- Solution obj;
- vvd trust1 = {{1, 2}}, trust2 = {{1, 3}, {2, 3}},
- trust3 = {{1, 3}, {2, 3}, {3, 1}};
- cout << obj.findJudge(2, trust1) << endl; // expect: 2
- cout << obj.findJudge(3, trust2) << endl; // expect: 3
- cout << obj.findJudge(3, trust3) << endl; // expect: -1
-}
diff --git a/other/first_missing_positive.cpp b/other/first_missing_positive.cpp
deleted file mode 100644
index 48fc05d..0000000
--- a/other/first_missing_positive.cpp
+++ /dev/null
@@ -1,12 +0,0 @@
-#include "leetcode.h"
-#include <vector>
-
-class Solution {
-public:
- vector<int> firstMissingPositive(vector<int> &nums) {}
-};
-
-int main() {
- Solution obj;
- vector<int> nums1 = {1, 2, 0}, nums2 = {}
-}
diff --git a/other/first_unique_char_string.cpp b/other/first_unique_char_string.cpp
deleted file mode 100644
index 5f55821..0000000
--- a/other/first_unique_char_string.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int firstUniqChar(string s) {
- unordered_map<char, pair<int, int>> ump;
- int idx = s.size();
- for (int i = 0; i < s.size(); i++) {
- ump[s[i]].first++;
- ump[s[i]].second = i;
- }
- for (const auto &[c, p] : ump)
- if (p.first == 1)
- idx = min(idx, p.second);
- return idx == s.size() ? -1 : idx;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.firstUniqueChar("loveleetcode");
-}
diff --git a/other/flatten_binary_to_linked.cpp b/other/flatten_binary_to_linked.cpp
deleted file mode 100644
index 82751c7..0000000
--- a/other/flatten_binary_to_linked.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- void flatten(TreeNode *root) {
- if (root)
- helper(root);
- }
-
-private:
- TreeNode *head = nullptr;
- void helper(TreeNode *node) {
- if (node->right)
- helper(node->right);
- if (node->left)
- helper(node->left);
- node->left = nullptr;
- node->right = head;
- head = node;
- }
-};
diff --git a/other/flip_string_monotone_increase.cpp b/other/flip_string_monotone_increase.cpp
deleted file mode 100644
index 35e0e0c..0000000
--- a/other/flip_string_monotone_increase.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-#include "leetcode.h"
-
-/*
- * a binary string is monotone increasing if it consists of some number
- * of 0's (none is valid), followed by some number of 1's (none is valid)
- * given: binary string 's'. you can flip 's[i]' changing for 0 to 1 or vice
- * versa. return the minimum number of flips to make 's' monotone increasing.
- */
-
-class Solution {
-public:
- int minFlipsMonoIncr(string s) {
- int flips = 0, cnt = 0;
- for (auto i : s) {
- if (i == '1')
- cnt++;
- else
- flips++;
- flips = min(flips, cnt);
- }
- return flips;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.minFlipsMonoIncr("00110") << endl;
- // expect: 1
- // flip last digit to get 00111
- cout << obj.minFlipsMonoIncr("010110") << endl;
- // expect: 2
- // flip s[1] s[5] to get 000111
- cout << obj.minFlipsMonoIncr("00011000") << endl;
- // expect: 2
- // flip s[3] s[4] to get 00000000
-}
diff --git a/other/freedom_trail.cpp b/other/freedom_trail.cpp
deleted file mode 100644
index 2763f8c..0000000
--- a/other/freedom_trail.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-// 514. Freedom Trail
-#include "leetcode.h"
-
-/*
- * in the video game fallout 4, the quest "road to freeom" requires players to
- * reach a metal dial call the "freedom trail ring" and use the dial to spell a
- * specific keyword to open the door. given a string 'rint' that represents the
- * code engraved on the outer ring and another string 'key' that represents the
- * keyword that needs to be spelled, return the minimum number of steps to spell
- * all of the characters in the keyword. initially, the first character of the
- * ring is aligned at "12:00" diretion. you should spell all the characters in
- * 'key' one by rotating 'ring' clockwise or anticlockwise to make each
- * character of the string aligned at the "12:00" direction and then by pressing
- * the center button. at the stage of rotating the ring to spell the key
- * character 'key[i]' you can rotate the ring clockwise or anticlockwise by one
- * place, which counts as one step. the final purpose of the rotation is to
- * align one of 'ring's characters at "12:00" direction, where this character
- * must equal 'key[i]'
- */
-
-class Solution {
-public:
- int findRotateSteps(string ring, string key) {
- int n = ring.size();
- unordered_map<char, vector<int>> idx_map;
- for (int i = 0; i < n; ++i)
- idx_map[ring[i]].push_back(i);
- vector<vector<pair<int, int>>> dp(key.size());
- for (int i : idx_map[key[0]]) {
- int dist = min(i, n - i);
- dp[0].push_back({i, dist});
- }
- int min_sum = INT_MAX;
- for (int i = 1; i < key.size(); ++i) {
- for (int idx : idx_map[key[i]]) {
- int min_dist = INT_MAX;
- for (auto &pair : dp[i - 1]) {
- int abs_dist = abs(pair.first - idx);
- int dist = min(abs_dist, n - abs_dist);
- min_dist = min(min_dist, dist + pair.second);
- }
- dp[i].push_back({idx, min_dist});
- if (i == key.size() - 1)
- min_sum = min(min_dist, min_sum);
- }
- }
- return min_sum + key.size();
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.findRotateSteps("godding", "gd")); // expect: 4
- printf("%d\n", obj.findRotateSteps("godding", "godding")); // expect: 13
-}
diff --git a/other/frog_jump.cpp b/other/frog_jump.cpp
deleted file mode 100644
index d9a21fc..0000000
--- a/other/frog_jump.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-// 403. Frog Jump
-#include "leetcode.h"
-
-/*
- * a frog is crossing a river. the river is divided into some number of units
- * and at each unit, there may or may not exist a stone. the frog can jump on a
- * stone, but it must not jump into the water. given a list of 'stones'
- * positions in (units) in sorted ascending order, determine if the frog can
- * cross the river by landing on the last stone. initially, the frog is on the
- * first stone and assumes the frist just must be 1 unit. if the frog's last
- * jump was k units, its next jujp must be either 'k - 1' or 'k + 1' units. the
- * frog can only jump in the forward direction.
- */
-
-class Solution {
- bool process(vector<int> &stones, map<int, int> &mp, int i, int k,
- vvd & dp) {
- if (i == stones.size() - 1)
- return dp[i][k] = 1;
- if (dp[i][k] != -1)
- return dp[i][k];
- for (int t = k - 1; t <= k + 1; t++)
- if (t && mp.find(stones[i] + t) != mp.end()) {
- int idx = mp[stones[i] + t];
- if (process(stones, mp, idx, t, dp))
- return dp[i][k] = 1;
- }
- return dp[i][k] = 0;
- }
-
-public:
- bool canCross(vector<int> &stones) {
- int n = stones.size();
- map<int, int> mp;
- for (int i = 0; i < n; i++)
- mp[stones[i]] = i;
- vvd dp(n + 1, vector<int>(n + 1, -1));
- return process(stones, mp, 0, 0, dp);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> s1 = {0, 1, 3, 5, 6, 8, 12, 17}, s2 = {0, 1, 2, 3, 4, 8, 9, 11};
- printf("%d\n", obj.canCross(s1)); // expect: 1
- printf("%d\n", obj.canCross(s2)); // expect: 0
-}
diff --git a/other/fruit_into_baskets.cpp b/other/fruit_into_baskets.cpp
deleted file mode 100644
index e613659..0000000
--- a/other/fruit_into_baskets.cpp
+++ /dev/null
@@ -1,41 +0,0 @@
-// 904. Fruit Into Baskets
-#include "leetcode.h"
-
-/*
- * you are visiting a farm that has a single row of fruit trees arranged from
- * left t oright. the trees are represented by an integer array 'fruits' where
- * 'fruits[i]' is the type of fruit the i'th tree produces. you want to collect
- * as much fruit as possible. however, the owner has some strict rules that you
- * must follow: you can only have two baskets and each can only hoold a single
- * type of fruit (unlimited quantity). starting from any tree, you must pick
- * exacty one fruit from every tree while moving to the right. once you reach a
- * tree with fruit that cannot fit in your baskets, you must stop. given the int
- * array 'fruits', return the maximum number of fruits you can pick
- */
-
-class Solution {
-public:
- int totalFruit(vector<int> &fruits) {
- int n = fruits.size(), ans = 0;
- unordered_map<int, int> cnt;
- for (int l = 0, r = 0; r < n; ++r) {
- cnt[fruits[r]]++;
- while (cnt.size() > 2) {
- if (--cnt[fruits[l]] == 0)
- cnt.erase(fruits[l]);
- ++l;
- }
- ans = max(ans, r - l + 1);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> fruits1 = {1, 2, 1}, fruits2 = {0, 1, 2, 2},
- fruits3 = {1, 2, 3, 2, 2};
- cout << obj.totalFruit(fruits1) << endl; // expect: 3
- cout << obj.totalFruit(fruits2) << endl; // expect: 3
- cout << obj.totalFruit(fruits3) << endl; // expect: 4
-}
diff --git a/other/furthest_building_reach.cpp b/other/furthest_building_reach.cpp
deleted file mode 100644
index 6baff33..0000000
--- a/other/furthest_building_reach.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int furthestBuilding(vector<int> &heights, int bricks, int ladders) {
- int n = heights.size() - 1;
- priority_queue<int> pq;
- for (int i = 0; i < n; i++) {
- int diff = heights[i + 1] - heights[i];
- if (diff > 0) {
- if (ladders)
- pq.push(-diff), ladders--;
- else if (!pq.empty() && diff > -pq.top()) {
- pq.push(-diff);
- bricks += pq.top();
- pq.pop();
- } else
- bricks -= diff;
- if (bricks < 0)
- return i;
- }
- }
- return n;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> heights = {4, 2, 7, 6, 9, 14, 12};
- int bricks = 5, ladders = 1;
- cout << obj.furthestBuilding(heights, bricks, ladders);
-}
diff --git a/other/gas_station.cpp b/other/gas_station.cpp
deleted file mode 100644
index 2fdc7fb..0000000
--- a/other/gas_station.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
- int n = gas.size(), totalSurplus = 0, surplus = 0, start = 0;
- for (int i = 0; i < n; i++) {
- totalSurplus += gas[i] - cost[i];
- surplus += gas[i] - cost[i];
- if (surplus < 0) {
- surplus = 0;
- start = i + 1;
- }
- }
- return (totalSurplus < 0) ? -1 : start;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> gas1 = {1, 2, 3, 4, 5}, gas2 = {2, 3, 4}, cost1 = {3, 4, 5, 1, 2},
- cost2 = {3, 4, 3};
- cout << obj.canCompleteCircuit(gas1, cost1) << endl; // expect: 3
- cout << obj.canCompleteCircuit(gas2, cost1) << endl; // expect: -1
-}
diff --git a/other/gas_station.rs b/other/gas_station.rs
deleted file mode 100644
index 0554f5b..0000000
--- a/other/gas_station.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn can_complete_circuit(gas: Vec<i32>, cost: Vec<i32>) -> i32 {
- let (mut sum, mut idx, mut min) = (0, 0, 0);
- for i in 0..gas.len() {
- sum += gas[i] - cost[i];
- if sum < min {
- min = sum;
- idx = i + 1;
- }
- }
- if sum < 0 {
- -1
- } else {
- idx as i32
- }
- }
-}
-
-fn main() {
- let (gas1, gas2) = (vec![1,2,3,4,5], vec![2,3,4]);
- let (cost1, cost2) = (vec![3,4,5,1,2], vec![3,4,3]);
- println!("{}", Solution::can_complete_circuit(gas1, cost1)); //expect: 3
- println!("{}", Solution::can_complete_circuit(gas2, cost2)); //expect: -1
-}
diff --git a/other/greatest_common_div_string.cpp b/other/greatest_common_div_string.cpp
deleted file mode 100644
index 420eb10..0000000
--- a/other/greatest_common_div_string.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-// 1071. Greatest Common Divisor of Strings
-#include "leetcode.h"
-
-/*
- * for two strings 's' & 't', we say 't' divides 's' if and only if s = t + ...
- * + t ie. 't' is concatenated with itself one or more times given two strings
- * 'str1' & 'str2', return largest string 'x' such that 'x' divides both 'str1'
- * & 'str2'
- */
-
-class Solution {
-public:
- string gcdOfStrings(string str1, string str2) {
- /* first check if finding gcd is even possible
- * eg. ABAB + AB == AB + ABAB
- * LEET + CODE != CODE + LEET
- */
- if (str1 + str2 == str2 + str1) {
- // get gcd of string sizes
- // eg. ABAB (4) and AB (2), gcd = 2
- int gcd = __gcd(str1.size(), str2.size());
- // return substring of (either) string
- // beginning at element 0 and a length of gcd
- return str1.substr(0, gcd);
- // if gcd isn't possible, return empty string
- } else
- return "";
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.gcdOfStrings("ABCABC", "ABC") << endl; // expect: ABC
- cout << obj.gcdOfStrings("ABABAB", "ABAB") << endl; // expect: AB
- cout << obj.gcdOfStrings("LEET", "CODE") << endl; // expect: n/a
-}
diff --git a/other/greatest_sum_div_three.cpp b/other/greatest_sum_div_three.cpp
deleted file mode 100644
index c828e58..0000000
--- a/other/greatest_sum_div_three.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-// 1262. Greatest Sum Divisible by Three
-#include "leetcode.h"
-
-/*
- * given an integer array 'nums', return the maximum possible sum of elements of
- * the array such that it is divisible by three
- */
-
-class Solution {
-public:
- int maxSumDivThree(vector<int> &nums) {
- int f1 = 10001, s1 = 10001, f2 = 10001, s2 = 10001, sum = 0;
- for (int i = 0; i < nums.size(); i++) {
- sum += nums[i];
- if (nums[i] % 3 == 1) {
- if (nums[i] < f1) {
- s1 = f1;
- f1 = nums[i];
- } else if (nums[i] < s1)
- s1 = nums[i];
- } else if (nums[i] % 3 == 2) {
- if (nums[i] < f2) {
- s2 = f2;
- f2 = nums[i];
- } else if (nums[i] < s2)
- s2 = nums[i];
- }
- }
- if (!(sum % 3))
- return sum;
- if (sum % 3 == 1)
- return sum - min(f1, f2 + s2);
- return sum - min(f2, f1 + s1);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {3, 6, 5, 1, 8}, n2 = {4}, n3 = {1, 2, 3, 4, 4};
- printf("%d\n", obj.maxSumDivThree(n1)); // expect: 18
- printf("%d\n", obj.maxSumDivThree(n2)); // expect: 0
- printf("%d\n", obj.maxSumDivThree(n3)); // expect: 12
-}
diff --git a/other/group_anagrams.cpp b/other/group_anagrams.cpp
deleted file mode 100644
index a2a7c8a..0000000
--- a/other/group_anagrams.cpp
+++ /dev/null
@@ -1,18 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vvd(string) groupAnagrams(vector<string> &strs) {
- map<array<int, 26>, vector<string>> groups;
- for (string s : strs) {
- array<int, 26> hash = {0};
- for (char c : s)
- ++hash[c - 'a'];
- groups[hash].push_back(s);
- }
- vvd(string) ans;
- for (auto [hash, group] : groups)
- ans.push_back(group);
- return ans;
- }
-};
diff --git a/other/group_anagrams.rs b/other/group_anagrams.rs
deleted file mode 100644
index 212fc15..0000000
--- a/other/group_anagrams.rs
+++ /dev/null
@@ -1,15 +0,0 @@
-use std::collections::HashMap;
-struct Solution;
-
-impl Solution {
- pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
- let mut groups = HashMap::new();
- for s in strs {
- let hash = s.bytes().fold([0;26], |mut h, b| {
- h[(b - b'a') as usize] += 1; h
- });
- groups.entry(hash).or_insert_with(Vec::new).push(s);
- }
- groups.into_values().collect()
- }
-}
diff --git a/other/guess_number_high_low.cpp b/other/guess_number_high_low.cpp
deleted file mode 100644
index d31ca99..0000000
--- a/other/guess_number_high_low.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int guessNumber(int n) {
- int left = 1, right = n, mid = n / 2;
- while (left <= right) {
- int ans = guess(mid); // guess is api call
- if (!ans)
- return mid;
- left = ans < 0 ? left : mid + 1;
- right = ans < 0 ? mid - 1 : right;
- mid = left + (right - left) / 2;
- }
- return -1;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.guessNumber(10);
-}
diff --git a/other/guess_number_high_low.rs b/other/guess_number_high_low.rs
deleted file mode 100644
index 4cd717b..0000000
--- a/other/guess_number_high_low.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-struct Solution;
-
-impl Solution {
- unsafe fn guessNumber(n: i32) -> i32 {
- let (mut s, mut n) = (1, n as i64);
- while s <= n {
- let x = (n + s) / 2;
- let g = guess(x as i32);
- match g {
- 0 => return x as i32,
- 1 => s = x + 1,
- -1 => n = x - 1,
- _ => unreachable!()
- }
- }
- unreachable!()
- }
-}
-
-fn main() {
- print!("{}", Solution::guessNumber(10));
-}
diff --git a/other/hand_of_straights.cpp b/other/hand_of_straights.cpp
deleted file mode 100644
index b08c7fa..0000000
--- a/other/hand_of_straights.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool isNStraightHand(vector<int> &hand, int groupSize) {
- if (hand.size() % groupSize != 0)
- return false;
- map<int, int> m;
- for (auto &card : hand)
- m[card]++;
- for (int i = 0; i < groupSize; i++) {
- int curr = m.begin()->first;
- if (m[curr + i] == 0)
- return false;
- else if (--m[curr + i] < 1)
- m.erase(curr + i);
- }
- return true;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> hand = {1, 2, 3, 6, 2, 3, 4, 7, 8};
- int groupSize = 3;
- if (obj.isNStraightHand(hand, groupSize))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/happy_number.cpp b/other/happy_number.cpp
deleted file mode 100644
index e946b96..0000000
--- a/other/happy_number.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool isHappy(int n) {
- int slow, fast;
- slow = fast = n;
- do {
- slow = square(slow);
- for (int i = 0; i < 2; i++)
- fast = square(fast);
- } while (slow != fast);
- if (slow == 1)
- return 1;
- else
- return 0;
- }
-
-private:
- int square(int n) {
- int num = 0, tmp;
- while (n) {
- tmp = n % 10;
- num += tmp * tmp;
- n /= 10;
- }
- return num;
- }
-};
-
-int main() {
- Solution obj;
- if (obj.isHappy(19))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/house_robber.cpp b/other/house_robber.cpp
deleted file mode 100644
index a08aa54..0000000
--- a/other/house_robber.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int rob(vector<int> &nums) {
- // space-optimized dynamic programming approach
- int prev = 0, prev2 = 0, curr = 0;
- for (auto i : nums) {
- curr = max(prev, i + prev2);
- prev2 = prev;
- prev = curr;
- }
- return curr;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {1, 2, 3, 1};
- cout << obj.rob(nums); // expect 4
-}
diff --git a/other/house_robber.rs b/other/house_robber.rs
deleted file mode 100644
index ce4afd9..0000000
--- a/other/house_robber.rs
+++ /dev/null
@@ -1,18 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn rob(nums: Vec<i32>) -> i32 {
- let (mut prev, mut prev2) = (0,0);
- for n in nums {
- let curr = std::cmp::max(n + prev2, prev);
- prev2 = prev;
- prev = curr;
- }
- prev
- }
-}
-
-fn main() {
- let nums = vec![1,2,3,1];
- print!("{}", Solution::rob(nums)); //expect 4
-}
diff --git a/other/idx_first_occur_str.cpp b/other/idx_first_occur_str.cpp
deleted file mode 100644
index 0f24457..0000000
--- a/other/idx_first_occur_str.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-// 28. Find the Index of the First Occurrence in a String
-#include "leetcode.h"
-#include <vector>
-
-/*
- * given two strings 'needle' and 'haystack', return index of the first
- * occurrence of 'needle' in 'haystack', or -1 if 'needle' is not part of
- * 'haystack'
- */
-
-class Solution {
-public:
- int strStr(string haystack, string needle) {
- int m = haystack.size(), n = needle.size();
- if (!n)
- return 0;
- vector<int> lps = kmp(needle);
- for (int i = 0, j = 0; i < m;) {
- if (haystack[i] == needle[j])
- i++, j++;
- if (j == n)
- return i - j;
- if (i < m && haystack[i] != needle[j])
- j ? j = lps[j - 1] : i++;
- }
- return -1;
- }
-
-private:
- // kmp algorithm:
- // http://jakeboxer.com/blog/2009/12/13/the-knuth-morris-pratt-algorithm-in-my-own-words/
- vector<int> kmp(string needle) {
- int n = needle.size();
- vector<int> lps(n, 0);
- for (int i = 1, len = 0; i < n;) {
- if (needle[i] == needle[len])
- lps[i++] = ++len;
- else if (len)
- len = lps[len - 1];
- else
- lps[i++] = 0;
- }
- return lps;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.strStr("sadbutsad", "sad") << endl; // expect: 0
- cout << obj.strStr("leetcode", "leeto") << endl; // expect: -1
-}
diff --git a/other/image_overlap.cpp b/other/image_overlap.cpp
deleted file mode 100644
index bc6eeba..0000000
--- a/other/image_overlap.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int largestOverlap(vvd & img1, vvd & img2) {
- vector<int> la, lb;
- int n = img1.size();
- unordered_map<int, int> count;
- for (int i = 0; i < n * n; ++i)
- if (img1[i / n][i % n] == 1)
- la.push_back(i / n * 100 + i % n);
- for (int i = 0; i < n * n; ++i)
- if (img2[i / n][i % n] == 1)
- lb.push_back(i / n * 100 + i % n);
- for (int i : la)
- for (int j : lb)
- count[i - j]++;
- int ans = 0;
- for (auto it : count)
- ans = max(ans, it.second);
- return ans;
- }
-};
diff --git a/other/image_overlap.rs b/other/image_overlap.rs
deleted file mode 100644
index fa6fbd6..0000000
--- a/other/image_overlap.rs
+++ /dev/null
@@ -1,35 +0,0 @@
-impl Solution {
- pub fn largest_overlap(img1: Vec<Vec<i32>>, img2: Vec<Vec<i32>>) -> i32 {
- let mut ans = 0;
- for i in 0..img1[0].len() {
- for j in 00..img1.len() {
- ans = ans.max(Solution::shift_and_compare(&img1, &img2, j, i));
- }
- }
- ans
- }
-
- fn shift_and_compare(img1: &[Vec<i32>],img2: &[Vec<i32>], x_shift: usize, y_shift: usize) -> i32 {
- let (mut counter, cols, rows) = ((0,0), img1.len(), img1[0].len());
- for i in 0..cols {
- for j in 0..rows {
- if img1[i][j] == 1 {
- let ii = i + y_shift;
- let jj = j + x_shift;
- if ii < rows && jj < cols && img2[ii][jj] == 1 {
- counter.0 += 1;
- }
- }
- if img2[i][j] == 1 {
- let ii = i + y_shift;
- let jj = j + x_shift;
- if ii < rows && jj < cols && img2[ii][jj] == 1 {
- counter.1 += 1;
- }
- }
- }
- }
- counter.0.max(counter.1)
- }
-}
-
diff --git a/other/implement_queue_stacks.cpp b/other/implement_queue_stacks.cpp
deleted file mode 100644
index 551ce9f..0000000
--- a/other/implement_queue_stacks.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-#include "leetcode.h"
-
-class MyQueue {
-public:
- stack<int> input, output;
- void push(int x) { input.push(x); }
- int pop() {
- int x = output.top();
- peek();
- return x;
- }
- int peek() {
- if (output.empty())
- while (input.size())
- output.push(input.top()), input.pop();
- return output.top();
- }
- bool empty() { return input.empty() && output.empty(); }
-};
-
-int main() {
- MyQueue *obj = new MyQueue();
- obj->push(2);
- int param_2 = obj->pop();
- int param_3 = obj->peek();
- bool param_4 = obj->empty();
- cout << param_2 << endl << param_3 << endl;
- if (param_4)
- cout << "true";
- else
- cout << "endl";
-}
diff --git a/other/increasing_triplet_subsequence.cpp b/other/increasing_triplet_subsequence.cpp
deleted file mode 100644
index 41a9f0e..0000000
--- a/other/increasing_triplet_subsequence.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool increasingTriplet(vector<int> &nums) {
- int one = INT_MAX, two = INT_MAX;
- for (auto n : nums) {
- if (n <= one)
- one = n;
- else if (n <= two)
- two = n;
- else
- return true;
- }
- return false;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {1, 2, 3, 4, 5};
- if (obj.increasingTriplet(nums))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/inform_employees.cpp b/other/inform_employees.cpp
deleted file mode 100644
index 700ccc3..0000000
--- a/other/inform_employees.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-// 1376. Time Needed to Inform All Employees
-#include "leetcode.h"
-
-/*
- * a company has 'n' employees with a unique id for each employee from 0 to 'n -
- * 1'. the head of the company is the one with the 'head_id'. each employee has
- * one direct manager given the 'manager' array where 'manager[i]' is the direct
- * manager of the i'th employee, 'manager[head_id] = -1'. also it is guaranteed
- * that the subordination relations have a tree structure. the head of the
- * company wants to inform all the company employees of an urgent piece of new.
- * he will inform his direct subordinates, and they will inform their
- * subordinates and so on until all the employees know about the urgent news.
- * the i'th employee needs 'inform_time[i]' minutes to inform all of his direct
- * subordinates (ie. after 'inform_time[i]' minutes, all his direct subordinates
- * can start spreading the news) return the number of minutes needed to inform
- * all the employees about the urget news.
- */
-
-class Solution {
- int dfs(int i, vector<int> &manager, vector<int> &inform_time) {
- if (manager[i] != -1) {
- inform_time[i] += dfs(manager[i], manager, inform_time);
- manager[i] = -1;
- }
- return inform_time[i];
- }
-
-public:
- int numOfMinutes(int n, int head_id, vector<int> &manager,
- vector<int> &inform_time) {
- int ans = 0;
- for (int i = 0; i < n; ++i)
- ans = max(ans, dfs(i, manager, inform_time));
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> m1 = {-1}, m2 = {2, 2, -1, 2, 2, 2};
- vector<int> it1 = {0}, it2 = {0, 0, 1, 0, 0, 0};
- printf("%d\n", obj.numOfMinutes(1, 0, m1, it1)); // expect: 0
- printf("%d\n", obj.numOfMinutes(6, 2, m2, it2)); // expect: 1
-}
diff --git a/other/insert_delete_getrandom.cpp b/other/insert_delete_getrandom.cpp
deleted file mode 100644
index 5bb76da..0000000
--- a/other/insert_delete_getrandom.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-#include "leetcode.h"
-
-class RandomizedSet {
-public:
- bool insert(int val) {
- if (data.count(val))
- return false;
- data[val] = idxs.size();
- idxs.push_back(val);
- return true;
- }
- bool remove(int val) {
- if (!data.count(val))
- return false;
- int lst = idxs.back(), pos = data[val];
- data[lst] = pos;
- idxs[pos] = lst;
- data.erase(val);
- idxs.pop_back();
- return true;
- }
- int getRandom() { return idxs[rand() % idxs.size()]; }
-
-private:
- unordered_map<int, int> data;
- vector<int> idxs;
-};
-
-int main() {
- RandomizedSet *obj = new RandomizedSet();
- bool param_1 = obj->insert(2);
- bool param_2 = obj->remove(1);
- int param_3 = obj->getRandom();
- cout << "param_1 (insert 2): ";
- if (param_1)
- cout << "true\n";
- else
- cout << "false\n";
- cout << "param_2 (remove 1): ";
- if (param_2)
- cout << "true\n";
- else
- cout << "false\n";
- cout << "param_3 (getRandom): " << param_3;
-}
diff --git a/other/insert_delete_getrandom.rs b/other/insert_delete_getrandom.rs
deleted file mode 100644
index 12a772f..0000000
--- a/other/insert_delete_getrandom.rs
+++ /dev/null
@@ -1,55 +0,0 @@
-extern crate rand;
-use rand::{Rng, thread_rng, rngs::ThreadRng};
-use std::collections::HashMap;
-
-struct RandomizedSet {
- rng: ThreadRng,
- data: Vec<i32>,
- idx_map: HashMap<i32, usize>
-}
-
-impl RandomizedSet {
- fn new() -> Self {
- Self {
- rng: thread_rng(),
- data: vec![],
- idx_map: HashMap::new()
- }
- }
- fn insert(&mut self, val: i32) -> bool {
- if self.idx_map.contains_key(&val) {
- return false;
- }
- self.idx_map.insert(val, self.data.len());
- self.data.push(val);
- true
- }
- fn remove(&mut self, val: i32) -> bool {
- if self.idx_map.contains_key(&val) == false {
- return false;
- }
- let i = self.idx_map.remove(&val).unwrap();
- if i != self.data.len() - 1 {
- self.data[i] = self.data[self.data.len() - 1];
- (*self.idx_map.get_mut(&self.data[i]).unwrap()) = i;
- }
- self.data.pop();
- true
- }
- fn get_random(&mut self) -> i32 {
- if self.data.len() == 0 {
- panic!(":P")
- }
- self.data[self.rng.gen_range(0, self.data.len())]
- }
-}
-
-fn main() {
- let obj = RandomizedSet::new();
- let ret_1: bool = obj.insert(2);
- let ret_2: bool = obj.remove(1);
- let ret_3: i32 = obj.get_random();
- println!("param_1 (insert 2): {}", ret_1);
- println!("param_2 (remove 1): {}", ret_2);
- print!("param_3 (get_random): {}", ret_3);
-}
diff --git a/other/insert_interval.cpp b/other/insert_interval.cpp
deleted file mode 100644
index 50e16f8..0000000
--- a/other/insert_interval.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vvd insert(vvd & intervals, vector<int> &newInterval) {
- const int START = 0, END = 1;
- int s = newInterval[START], e = newInterval[END];
- vvd left, right;
- for (auto &curr : intervals) {
- if (curr[END] < s)
- left.push_back(curr);
- else if (curr[START] > e)
- right.push_back(curr);
- else {
- s = min(s, curr[START]);
- e = max(e, curr[END]);
- }
- }
- vvd ans;
- ans.insert(ans.end(), left.begin(), left.end());
- ans.push_back({s, e});
- ans.insert(ans.end(), right.begin(), right.end());
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd intervals1 = {{1, 3}, {6, 9}},
- intervals2 = {{1, 2}, {3, 5}, {6, 7}, {8, 10}, {12, 16}};
- vector<int> newInterval1 = {2, 5}, newInterval2 = {4, 8};
- for (auto i : obj.insert(intervals1, newInterval1))
- for (auto j : i)
- cout << j << ' '; // expect: [[1,5],[6,9]]
- cout << endl;
- for (auto i : obj.insert(intervals2, newInterval2))
- for (auto j : i)
- cout << j << ' '; // expect: [[1,2],[3,10],[12,16]]
-}
diff --git a/other/int_roman.cpp b/other/int_roman.cpp
deleted file mode 100644
index e3a8a22..0000000
--- a/other/int_roman.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string intToRoman(int num) {
- string ans;
- int val[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
- string sym[] = {"M", "CM", "D", "CD", "C", "XC", "L",
- "XL", "X", "IX", "V", "IV", "I"};
- for (int i = 0; num != 0; i++)
- while (num >= val[i]) {
- ans += sym[i];
- num -= val[i];
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.intToRoman(1994);
-}
diff --git a/other/int_roman.rs b/other/int_roman.rs
deleted file mode 100644
index 9e8aa9e..0000000
--- a/other/int_roman.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn int_to_roman(num: i32) -> String {
- let (mut ans, mut curr) = ("".to_owned(), num);
- let val_sym: Vec<(i32, &str)> = vec![
- (1000, "M"), (900, "CM"), (500, "D"),
- (400, "CD"), (100, "C"), (90, "XC"),
- (50, "L"), (40, "XL"), (10, "X"),
- (9, "IX"), (5, "V"), (4, "IV"), (1, "I")
- ];
- for &(v, s) in val_sym.iter() {
- let count = curr / v;
- if count > 0 {
- let mult_str = s.repeat(count as usize);
- ans.push_str(&mult_str);
- curr %= v;
- }
- }
- ans
- }
-}
-
-fn main() {
- print!("{}", Solution::int_to_roman(1994));
-}
diff --git a/other/integer_break.cpp b/other/integer_break.cpp
deleted file mode 100644
index c015be2..0000000
--- a/other/integer_break.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int integerBreak(int n) {
- if (n <= 2)
- return true;
- vector<int> arrMax(n + 1, 0);
- arrMax[1] = 0, arrMax[2] = 1;
- for (int i = 3; i <= n; i++)
- for (int j = 1; j < i; j++)
- arrMax[i] = max(arrMax[i], max(j * (i - j), j * arrMax[i - j]));
- return arrMax[n];
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.integerBreak(2);
-}
diff --git a/other/interleaving_string.cpp b/other/interleaving_string.cpp
deleted file mode 100644
index ed2a5b9..0000000
--- a/other/interleaving_string.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool isInterleave(string s1, string s2, string s3) {
- memset(t, -1, sizeof(t));
- m = s1.size();
- n = s2.size();
- N = s3.size();
- if (m + n != N)
- return false;
- return helper(s1, s2, s3, 0, 0);
- }
-
-private:
- int m, n, N;
- int t[101][101];
- bool helper(string s1, string s2, string s3, int i, int j) {
- if (i >= m && j >= n && i + j >= N)
- return true;
- if (i + j >= N)
- return false;
- if (t[i][j] != -1)
- return t[i][j];
- return t[i][j] = ((s1[i] == s3[i + j] && helper(s1, s2, s3, i + 1, j)) ||
- (s2[j] == s3[i + j] && helper(s1, s2, s3, i, j + 1)));
- }
-};
-
-int main() {
- Solution obj;
- string s1 = "aabcc";
- string s2 = "dbbca";
- string s3 = "aadbbcbcac";
- if (obj.isInterleave(s1, s2, s3))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/invert_binary_tree.cpp b/other/invert_binary_tree.cpp
deleted file mode 100644
index e8f0585..0000000
--- a/other/invert_binary_tree.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-// 226. Invert Binary Tree
-#include "leetcode.h"
-
-// given 'root' of binary tree, invert the tree and return its root
-
-class Solution {
-public:
- TreeNode *invertTree(TreeNode *root) {
- if (root == nullptr)
- return root;
- queue<TreeNode *> q;
- q.push(root);
- while (!q.empty()) {
- TreeNode *node = q.front();
- q.pop();
- if (node->left != nullptr)
- q.push(node->left);
- if (node->right != nullptr)
- q.push(node->right);
- TreeNode *tmp = node->left;
- node->left = node->right;
- node->right = tmp;
- }
- return root;
- }
-};
diff --git a/other/ipo.cpp b/other/ipo.cpp
deleted file mode 100644
index 61d5baa..0000000
--- a/other/ipo.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-// 502. IPO
-#include "leetcode.h"
-
-/*
- * suppose leetcode will start its ipo soon. in order to sell a good price of
- * its shares to venture capital, leetcode woule like to work on some projects
- * to increase its capital before the ipo. since it has limited resources, it
- * can only finish at most k distinct projects before the ipo. maximise capital
- * after finishing at most 'k' distinct projects. given 'n' projects where the
- * i'th project has a pure profit 'profits[i]' and min capital of 'capital[i]'
- * is needed to start it.
- */
-
-class Solution {
-public:
- int findMaximizedCapital(int k, int w, vector<int> &profits,
- vector<int> &capital) {
- priority_queue<int> pq;
- int x = 0;
- vector<pair<int, int>> vp;
- for (int i = 0; i < profits.size(); i++)
- vp.push_back({capital[i], profits[i]});
- sort(vp.begin(), vp.end());
- while (x < vp.size() && k) {
- if (w >= vp[x].first) {
- pq.push(vp[x].second);
- x++;
- } else {
- if (pq.empty())
- return w;
- else {
- w += pq.top();
- pq.pop();
- k--;
- }
- }
- }
- while (k-- && !pq.empty()) {
- w += pq.top();
- pq.pop();
- }
- return w;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> profits = {1, 2, 3};
- vector<int> c1 = {0, 1, 1}, c2 = {0, 1, 2};
- cout << obj.findMaximizedCapital(2, 0, profits, c1) << endl; // expect: 4
- cout << obj.findMaximizedCapital(3, 0, profits, c2) << endl; // expect: 6
-}
diff --git a/other/is_graph_biparite.cpp b/other/is_graph_biparite.cpp
deleted file mode 100644
index 4a6b4fc..0000000
--- a/other/is_graph_biparite.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-// 785. Is Graph Bipartite?
-#include "leetcode.h"
-
-/*
- * there is an undirected graph with 'n' nodes, where each node is numbered
- * between 0 and 'n - 1'. you are given a 2d array 'graph' where 'graph[u]' is
- * an array of nodes that node 'u' is adjacent to. more formally, for each 'v'
- * in 'graph[u]', there is an undirected edge between node 'u' and node 'v'. the
- * graph has the following properties:
- * - there are no self-edges ('graph[u]' does not contain 'u')
- * - there are no parallel edges ('graph[u]' does not contain duplicate values)
- * - if 'v' is in 'graph[u]', then 'u' is in 'graph[v]' (the graph is
- * undirected)
- * - the graph may not be connected, meaning there may be two nodes 'u' and 'v'
- * such that there is no path between them a graph is bipartite if the nodes can
- * be partitioned into two independent sets 'A' and 'B' such that every edge in
- * the graph connects a node in set 'A' and a node in set 'B'. return true if
- * and only if the graph is bipartite.
- */
-
-class Solution {
-public:
- bool isBipartite(vvd & graph) {
- int n = graph.size();
- vector<int> colour(n);
- queue<int> q;
- for (int i = 0; i < n; i++) {
- if (colour[i])
- continue;
- colour[i] = 1;
- for (q.push(i); !q.empty(); q.pop()) {
- int curr = q.front();
- for (int neighbour : graph[curr]) {
- if (!colour[neighbour]) {
- colour[neighbour] = -colour[curr];
- q.push(neighbour);
- } else if (colour[neighbour] == colour[curr])
- return false;
- }
- }
- }
- return true;
- }
-};
-
-int main() {
- Solution obj;
- vvd g1 = {{1, 2, 3}, {0, 2}, {0, 1, 3}, {0, 2}};
- vvd g2 = {{1, 3}, {0, 2}, {1, 3}, {0, 2}};
- printf("%d\n", obj.isBipartite(g1)); // expect: 0
- printf("%d\n", obj.isBipartite(g2)); // expect: 1
-}
diff --git a/other/jump_game.cpp b/other/jump_game.cpp
deleted file mode 100644
index 153d9aa..0000000
--- a/other/jump_game.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool canJump(vector<int> &nums) {
- int minJump = 0;
- for (int i = nums.size() - 2; i >= 0; i--) {
- minJump++;
- if (nums[i] >= minJump)
- minJump = 0;
- }
- if (minJump == 0)
- return true;
- else
- return false;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums1 = {2, 3, 1, 1, 4}, nums2 = {3, 2, 1, 0, 4};
- testBool(obj.canJump(nums1)); // true
- testBool(obj.canJump(nums2)); // false
-}
diff --git a/other/jump_game.rs b/other/jump_game.rs
deleted file mode 100644
index e7f36b0..0000000
--- a/other/jump_game.rs
+++ /dev/null
@@ -1,18 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn can_jump(nums: Vec<i32>) -> bool {
- let mut n = 1;
- for i in (0..nums.len() - 1).rev() {
- n = if nums[i] < n { n + 1 } else { 1 };
- }
- n == 1
- }
-}
-
-fn main() {
- let nums1 = vec![2,3,1,1,4];
- let nums2 = vec![3,2,1,0,4];
- println!("{}", Solution::can_jump(nums1));
- println!("{}", Solution::can_jump(nums2));
-}
diff --git a/other/jump_game3.cpp b/other/jump_game3.cpp
deleted file mode 100644
index 03f7d37..0000000
--- a/other/jump_game3.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool canReach(vector<int> &arr, int start) {
- vector<bool> visited(arr.size(), false);
- return dfs(arr, start, visited);
- }
-
-private:
- bool dfs(vector<int> &arr, int curr, vector<bool> &k) {
- if ((curr < 0) || (curr >= arr.size()) || k[curr])
- return false;
- if (arr[curr] == 0)
- return true;
- k[curr] = true;
- return dfs(arr, curr + arr[curr], k) || dfs(arr, curr - arr[curr], k);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> arr1 = {4, 2, 3, 0, 3, 1, 2}, arr2 = {3, 0, 2, 1, 2};
- testBool(obj.canReach(arr1, 5)); // true
- testBool(obj.canReach(arr1, 0)); // true
- testBool(obj.canReach(arr2, 2)); // false
-}
diff --git a/other/jump_game3.rs b/other/jump_game3.rs
deleted file mode 100644
index a973fad..0000000
--- a/other/jump_game3.rs
+++ /dev/null
@@ -1,35 +0,0 @@
-use std::collections::VecDeque;
-struct Solution;
-
-impl Solution {
- pub fn can_reach(arr: Vec<i32>, start: i32) -> bool {
- let mut arr = arr;
- let mut vd: VecDeque<i32> = VecDeque::with_capacity(arr.len());
- vd.push_back(start);
- while let Some(front) = vd.pop_front() {
- match arr[front as usize].cmp(&0) {
- std::cmp::Ordering::Less => continue,
- std::cmp::Ordering::Equal => return true,
- std::cmp::Ordering::Greater => {
- if front - arr[front as usize] >= 0 {
- vd.push_back(front - arr[front as usize]);
- }
- if front + arr[front as usize] < arr.len() as i32 {
- vd.push_back(front + arr[front as usize]);
- }
- arr[front as usize] = -1;
- }
- }
- }
- false
- }
-}
-
-fn main() {
- let arr1 = vec![4,2,3,0,3,1,2];
- let arr2 = vec![4,2,3,0,3,1,2];
- let arr3 = vec![3,0,2,1,2];
- println!("{}", Solution::can_reach(arr1, 5)); //true
- println!("{}", Solution::can_reach(arr2, 0)); //true
- println!("{}", Solution::can_reach(arr3, 2)); //false
-}
diff --git a/other/jump_game4.cpp b/other/jump_game4.cpp
deleted file mode 100644
index 8496d94..0000000
--- a/other/jump_game4.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-// 1345. Jump Game IV
-#include "leetcode.h"
-
-/*
- * given array of integers 'arr', you are initially positioned at first index of
- * array. in one step, you can jump from index 'i' to index 'j'. return minimum
- * number of steps to reach lat index of array. notice, you cannot jump outside
- * of array at any time.
- */
-
-class Solution {
-public:
- int minJumps(vector<int> &arr) {
- int n = arr.size(), step = 0;
- unordered_map<int, vector<int>> idx_val;
- for (int i = 0; i < n; i++)
- idx_val[arr[i]].push_back(i);
- vector<bool> visited(n);
- visited[0] = true;
- queue<int> q;
- q.push(0);
- while (!q.empty()) {
- for (int size = q.size(); size > 0; --size) {
- int i = q.front();
- q.pop();
- if (i == n - 1)
- return step; // end of arr
- vector<int> next = idx_val[arr[i]];
- next.push_back(i - 1);
- next.push_back(i + 1);
- for (int j : next) {
- if (j >= 0 && j < n && !visited[j]) {
- visited[j] = true;
- q.push(j);
- }
- }
- next.clear();
- }
- step++;
- }
- return 0;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> a1 = {100, -23, -23, 404, 100, 23, 23, 23, 3, 404};
- vector<int> a2 = {7}, a3 = {7, 6, 9, 6, 9, 6, 9, 7};
- cout << obj.minJumps(a1) << endl; // expect: 3
- cout << obj.minJumps(a2) << endl; // expect: 0
- cout << obj.minJumps(a3) << endl; // expect: 1
-}
diff --git a/other/jump_game6.cpp b/other/jump_game6.cpp
deleted file mode 100644
index 81bbf05..0000000
--- a/other/jump_game6.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maxResult(vector<int> &nums, int k) {
- int ans = 0;
- deque<int> dq;
- for (int i = nums.size() - 1; i >= 0; i--) {
- ans = nums[i] + (dq.empty() ? 0 : nums[dq.front()]);
- while (!dq.empty() && ans > nums[dq.back()])
- dq.pop_back();
- dq.push_back(i);
- if (dq.front() >= i + k)
- dq.pop_front();
- nums[i] = ans;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {1, -1, -2, 4, -7, 3};
- int k = 2;
- cout << obj.maxResult(nums, k);
-}
diff --git a/other/k_inverse_pairs.cpp b/other/k_inverse_pairs.cpp
deleted file mode 100644
index 5601d19..0000000
--- a/other/k_inverse_pairs.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int kInversePairs(int n, int k) {
- vector<int> dp(k + 1, 0);
- int mod = 1e9 + 7;
- for (int i = 1; i <= n; i++) {
- vector<int> tmp(k + 1, 0);
- tmp[0] = 1;
- for (int j = 1; j <= k; j++) {
- long long val = (dp[j] + mod - ((j - i) >= 0 ? dp[j - i] : 0)) % mod;
- tmp[j] = (tmp[j - 1] + val) % mod;
- }
- dp = tmp;
- }
- return (dp[k] + mod - (k > 0 ? dp[k - 1] : 0)) % mod;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.kInversePairs(3, 0);
-}
diff --git a/other/k_radius_subarr.cpp b/other/k_radius_subarr.cpp
deleted file mode 100644
index 91184bb..0000000
--- a/other/k_radius_subarr.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-// 2090. K Radius Subarray Averages
-#include "leetcode.h"
-
-/*
- * given a 0-indexed array 'nums' of 'n' integers, and an integer 'k'. the
- * k-radius average for a subarray of 'nums' centered at some index 'i' with the
- * radius 'k' is the average of all elements in 'nums' between the indices 'i -
- * k' and 'i + k' (inclusive). if there are less than 'k' elements before or
- * after the index 'i', then the k-radius average is -1. build and return 'avgs'
- * of length 'n' where 'avgs[i]' is the k-radius average for the subarray
- * centered at index 'i'. the average of 'x' elements is the sum of the 'x'
- * elements divided by 'x', using integer division. the integer division
- * truncates toward zero, which means losing its fractional part.
- */
-
-class Solution {
-public:
- vector<int> getAverages(vector<int> &nums, int k) {
- vector<int> ans(nums.size(), -1);
- long long sum = 0, d = k * 2 + 1;
- for (int i = 0; i < nums.size(); ++i) {
- sum += nums[i];
- if (i + 1 >= d) {
- if (i >= d)
- sum -= nums[i - d];
- ans[i - d / 2] = sum / d;
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {7, 4, 3, 9, 1, 8, 5, 2, 6}, n2 = {100000}, n3 = {8};
- for (auto i : obj.getAverages(n1, 3))
- printf("%d ", i); // expect: -1,-1,-1,5,4,4,-1,-1,-1
- printf("\n");
- for (auto i : obj.getAverages(n2, 0))
- printf("%d ", i); // expect: 100000
- printf("\n");
- for (auto i : obj.getAverages(n3, 100000))
- printf("%d ", i); // expect: -1
- printf("\n");
-}
diff --git a/other/keys_and_rooms.cpp b/other/keys_and_rooms.cpp
deleted file mode 100644
index 59308ef..0000000
--- a/other/keys_and_rooms.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool canVisitAllRooms(vvd & rooms) {
- stack<int> dfs;
- dfs.push(0);
- unordered_set<int> seen = {0};
- while (!dfs.empty()) {
- int i = dfs.top();
- dfs.pop();
- for (int j : rooms[i]) {
- if (seen.count(j) == 0) {
- dfs.push(j);
- seen.insert(j);
- if (rooms.size() == seen.size())
- return true;
- }
- }
- }
- return rooms.size() == seen.size();
- }
-};
-
-int main() {
- Solution obj;
- vvd rooms = {{1}, {2}, {3}, {}};
- if (obj.canVisitAllRooms(rooms))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/keys_and_rooms.rs b/other/keys_and_rooms.rs
deleted file mode 100644
index 678c732..0000000
--- a/other/keys_and_rooms.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn can_visit_all_rooms(rooms: Vec<Vec<i32>>) -> bool {
- let mut unlocked = vec![false; rooms.len()];
- unlocked[0] = true;
- let mut stack = vec![0];
- while let Some(next) = stack.pop() {
- for &i in &rooms[next as usize] {
- if !unlocked[i as usize] {
- unlocked[i as usize] = true;
- stack.push(i);
- }
- }
- }
- unlocked.iter().all(|&b| b)
- }
-}
-
-fn main() {
- let rooms = vec![vec![1], vec![2], vec![3], vec![]];
- print!("{}", Solution::can_visit_all_rooms(rooms));
-}
diff --git a/other/kids_max_num_candy.cpp b/other/kids_max_num_candy.cpp
deleted file mode 100644
index 8be7b4c..0000000
--- a/other/kids_max_num_candy.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-// 1431. Kids With the Greatest Number of Candies
-#include "leetcode.h"
-
-/*
- * there are 'n' kids with candies. you are given an integer array 'candies',
- * where each 'candies[i]' represents the number of candies the i'th kid has,
- * and an integer 'extra' denoting the number of extra candies that you have.
- * return a boolean array 'result' of length 'n' where 'result[i]' is 1 if,
- * after giving the i'th kid all the 'extra', they will have the greatest number
- * of candies among all the kids, or 0 otherwise.
- */
-
-class Solution {
-public:
- vector<bool> kidsWithCandies(vector<int> &candies, int extra) {
- int m = 0;
- vector<bool> ans;
- for (int c : candies)
- m = max(m, c);
- for (int c : candies) {
- if (c + extra >= m)
- ans.push_back(1);
- else
- ans.push_back(0);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> c1 = {2, 3, 5, 1, 3}, c2 = {4, 2, 1, 1, 2}, c3 = {12, 1, 12};
- for (auto i : obj.kidsWithCandies(c1, 3))
- cout << i << ' '; // expect: 1 1 1 0 1
- cout << endl;
- for (auto i : obj.kidsWithCandies(c2, 1))
- cout << i << ' '; // expect: 1 0 0 0 0
- cout << endl;
- for (auto i : obj.kidsWithCandies(c3, 10))
- cout << i << ' '; // expect: 1 0 1
- cout << endl;
-}
diff --git a/other/knight_probability_chessboard.cpp b/other/knight_probability_chessboard.cpp
deleted file mode 100644
index 0c5094d..0000000
--- a/other/knight_probability_chessboard.cpp
+++ /dev/null
@@ -1,41 +0,0 @@
-// 688. Knight Probability in Chessboard
-#include "leetcode.h"
-
-/*
- * on an 'n x n' chessboard, a knight starts at the cell '(row, column)' and
- * attempts to make exactly 'k' moves. the rows and columns are 0-indexed, so
- * the top-left cell is '(0, 0)', and the bottom-right cell is '(n - 1, n - 1)'.
- * a chess knight has eight possible moves it can make, as illustrated below
- * [see image]. each move is two cells in a cardinal direction, then one cell in
- * an orthogonal direction.
- */
-
-class Solution {
-public:
- double knightProbability(int n, int k, int row, int col) {
- unordered_map<int, unordered_map<int, unordered_map<int, double>>> dp;
- if (dp.count(row) && dp[row].count(col) && dp[row][row].count(k))
- return dp[row][col][k];
- if (row < 0 || row >= n || col < 0 || col >= n)
- return 0;
- if (!k)
- return 1;
- double total = knightProbability(n, k - 1, row - 1, col - 2) +
- knightProbability(n, k - 1, row - 2, col - 1) +
- knightProbability(n, k - 1, row - 1, col + 2) +
- knightProbability(n, k - 1, row - 2, col + 1) +
- knightProbability(n, k - 1, row + 1, col + 2) +
- knightProbability(n, k - 1, row + 2, col + 1) +
- knightProbability(n, k - 1, row + 1, col - 2) +
- knightProbability(n, k - 1, row + 2, col - 1);
- double ans = total / 8;
- dp[row][col][k] = ans;
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- printf("%f\n", obj.knightProbability(3, 2, 0, 0)); // expect: 0.06250
- printf("%f\n", obj.knightProbability(1, 0, 0, 0)); // expect: 1.00000
-}
diff --git a/other/koko_eating_bananas.cpp b/other/koko_eating_bananas.cpp
deleted file mode 100644
index 3076169..0000000
--- a/other/koko_eating_bananas.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-// 875. Koko Eating Bananas
-#include "leetcode.h"
-
-// return minimum integer 'k' such that koko can eat all bananas within 'h'
-// hours
-
-class Solution {
-public:
- int minEatingSpeed(vector<int> &piles, int h) {
- int l = 1, r = 1000000000;
- while (l < r) {
- int m = (l + r) / 2, total = 0;
- for (int p : piles)
- total += (p + m - 1) / m;
- if (total > h)
- l = m + 1;
- else
- r = m;
- }
- return l;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> p1 = {3, 6, 7, 11}, p2_3 = {30, 11, 23, 4, 20};
- printf("%d\n", obj.minEatingSpeed(p1, 8)); // expect: 4
- printf("%d\n", obj.minEatingSpeed(p2_3, 5)); // expect: 30
- printf("%d\n", obj.minEatingSpeed(p2_3, 6)); // expect: 23
-}
diff --git a/other/kth_element_in_stream.cpp b/other/kth_element_in_stream.cpp
deleted file mode 100644
index 75e5234..0000000
--- a/other/kth_element_in_stream.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-#include "leetcode.h"
-
-class KthLargest {
-private:
- int k;
- priority_queue<int, vector<int>, greater<int>> pq;
-
-public:
- KthLargest(int k, vector<int> &nums) {
- this->k = k;
- auto endPointer = nums.begin() + min(k, nums.size());
- pq = priority_queue<int, vector<int>, greater<int>>(nums.begin(),
- endPointer);
- for (int i = k; i < nums.size(); ++i) {
- pq.push(nums[i]);
- pq.pop();
- }
- }
- int add(int val) {
- pq.push(val);
- if (pq.size() > k)
- pq.pop();
- return pq.top();
- }
-};
-
-int main() {
- vector<int> nums({4, 5, 8, 2}), stream({3, 5, 10, 9, 4});
- KthLargest *obj = new KthLargest(3, nums);
- for (auto num : stream)
- cout << obj->add(num) << ' ';
-}
diff --git a/other/kth_largest_element.cpp b/other/kth_largest_element.cpp
deleted file mode 100644
index c9a60c2..0000000
--- a/other/kth_largest_element.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-// 215. Kth Largest Element in an Array
-#include "leetcode.h"
-
-/*
- * given an integer array 'nums' and an integer 'k', return the k'th largest
- * element in the array. note that it is the k'th largest elemented in sorted
- * order, not the k'th distinct element. can you solve without sorting?
- */
-
-class Solution {
-public:
- int findKthLargest(vector<int> &nums, int k) {
- priority_queue<int> pq(nums.begin(), nums.end());
- for (int i = 1; i < k; i++)
- pq.pop();
- return pq.top();
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {3, 2, 1, 5, 6, 4};
- int k = 2;
- cout << obj.findKthLargest(nums, k);
-}
diff --git a/other/kth_largest_element_stream.cpp b/other/kth_largest_element_stream.cpp
deleted file mode 100644
index 3ef8b3c..0000000
--- a/other/kth_largest_element_stream.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-// 703. Kth Largest Element in a Stream
-#include "leetcode.h"
-
-/*
- * design a class to find the k'th largest element in a stream. note that it is
- * the k'th largest element in the sorted order, not the k'th distinct element.
- * implement 'KthLargest' class:
- * - KthLargest(int k, int[] nums) initialises the objct with the integer 'k'
- * and the stream of integers 'nums' int add(int val) appends the integer 'val'
- * to the stream and returns the element representing the k'th largest stream
- * element
- */
-
-class KthLargest {
- priority_queue<int, vector<int>, greater<int>> pq;
- int size;
-
-public:
- KthLargest(int k, vector<int> &nums) {
- size = k;
- for (int i = 0; i < nums.size(); i++) {
- pq.push(nums[i]);
- if (pq.size() > k)
- pq.pop();
- }
- }
- int add(int val) {
- pq.push(val);
- if (pq.size() > size)
- pq.pop();
- return pq.top();
- }
-};
-
-int main() {
- vector<int> nums = {4, 5, 8, 2};
- KthLargest *obj = new KthLargest(3, nums);
- printf("%d\n", obj->add(3)); // expect: 4
- printf("%d\n", obj->add(5)); // expect: 5
- printf("%d\n", obj->add(10)); // expect: 5
- printf("%d\n", obj->add(9)); // expect: 8
- printf("%d\n", obj->add(4)); // expect: 8
-}
diff --git a/other/kth_missing_pos_num.cpp b/other/kth_missing_pos_num.cpp
deleted file mode 100644
index a7f81f7..0000000
--- a/other/kth_missing_pos_num.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-// 1539. Kth Missing Positive Number
-#include "leetcode.h"
-
-/*
- * given array 'arr' of positive integers sorted in a strictly increasing order,
- * and an integer 'k', return 'kth' positive integer missing from array -- o(log
- * n)
- */
-
-class Solution {
-public:
- int findKthPositive(vector<int> &arr, int k) {
- int l = 0, r = arr.size(), m;
- while (l < r) {
- m = (l + r) / 2;
- if (arr[m] - 1 - m < k)
- l = m + 1;
- else
- r = m;
- }
- return l + k;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> a1 = {2, 3, 4, 7, 11}, a2 = {1, 2, 3, 4};
- cout << obj.findKthPositive(a1, 5) << endl; // expect: 9
- cout << obj.findKthPositive(a2, 2) << endl; // expect: 6
-}
diff --git a/other/kth_smallest_lexicographical.cpp b/other/kth_smallest_lexicographical.cpp
deleted file mode 100644
index 71478e9..0000000
--- a/other/kth_smallest_lexicographical.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-// 440. K-th Smallest in Lexicographical Order
-#include "leetcode.h"
-// given two integers 'n' and 'k', return the k'th lexicographically smallest
-// integer
-
-class Soltuion {
-public:
- int findKthNumber(int n, int k) {
- int curr = 1;
- for (--k; k > 0;) {
- int cnt = 0;
- for (long long first = static_cast<long long>(curr), last = first + 1;
- first <= n; first *= 10, last *= 10)
- cnt += static_cast<int>((min(n + 1LL, last) - first));
- if (k >= cnt) {
- ++curr;
- k -= cnt;
- } else {
- curr *= 10;
- --k;
- }
- }
- return curr;
- }
-};
-
-int main() {
- Soltuion obj;
- printf("%d\n", obj.findKthNumber(13, 2)); // expect: 10
- printf("%d\n", obj.findKthNumber(1, 1)); // expect: 1
-}
diff --git a/other/kth_smallest_sorted_matrix.cpp b/other/kth_smallest_sorted_matrix.cpp
deleted file mode 100644
index aad9458..0000000
--- a/other/kth_smallest_sorted_matrix.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int kthSmallest(vector<vector<int>> &matrix, int k) {
- int n = matrix.size(), left = matrix[0][0], right = matrix[n - 1][n - 1],
- mid = 0;
- while (left < right) {
- mid = left + (right - left) / 2;
- int num = 0;
- for (int i = 0; i < n; i++) {
- int pos = upper_bound(matrix[i].begin(), matrix[i].end(), mid) -
- matrix[i].begin();
- num += pos;
- }
- if (num < k)
- left = mid + 1;
- else
- right = mid;
- }
- return left;
- }
-};
-
-int main() {
- Solution obj;
- vector<vector<int>> matrix;
- int k;
- obj.kthSmallest(matrix, k);
-}
diff --git a/other/largest_colour_value_graph.cpp b/other/largest_colour_value_graph.cpp
deleted file mode 100644
index 5307742..0000000
--- a/other/largest_colour_value_graph.cpp
+++ /dev/null
@@ -1,87 +0,0 @@
-// 1857. Largest Color Value in a Directed Graph
-#include "leetcode.h"
-
-/*
- * there is a directed graph of n coloured nodes and m edges. the nodes are
- * numbered from 0 to n - 1. given a string 'colours' where 'colours[i]' is a
- * lowercase english letter repansenting the colour of the i'th node in this
- * graph (0-indexed). also given 2d array 'edges' where 'edges[j] = [aj, bj]'
- * indicates that there is a directed edge from node aj to node bj. a valid path
- * in the graph is a sequence of nodes 'x1 -> x2 -> ... -> xk' such that there
- * is a directed edge from xi to xi + 1 for every 1 <= i < k. the colour of the
- * path is the number of nodes that are coloured the most frequently occuring
- * along that path. return largest colour value of any valid path in the given
- * graph or -1.
- */
-
-class Solution {
- bool dfs(vvd & al, vector<int> &gb, int i) {
- if (!gb[i]) {
- gb[i] = 1;
- for (auto j : al[i])
- if (!dfs(al, gb, j))
- return false;
- gb[i] = 2;
- }
- return gb[i] == 2;
- }
-
-public:
- int largestPathValue(string colours, vvd & edges) {
- int cnt[128] = {}, colours_size = colours_size;
- for (auto c : colours)
- ++cnt[c];
- char s[26] = {};
- iota(begin(s), end(s), 'a');
- sort(begin(s), end(s), [&](char a, char b) { return cnt[a] > cnt[b]; });
- vvd al(colours_size);
- vector<bool> target(colours_size);
- for (auto &e : edges) {
- al[e[0]].push_back(e[1]);
- target[e[1]] = true;
- }
- vector<pair<int, int>> vp;
- for (int i = 0; i < colours_size; ++i)
- if (!target[i])
- vp.push_back({i, -1});
- int ans = 0;
- vector<int> gb(colours_size);
- for (auto [i, tmp] : vp)
- if (!dfs(al, gb, i))
- return -1;
- if (count(begin(gb), end(gb), 2) != colours_size)
- return -1;
- for (char c : s) {
- if (ans >= cnt[c])
- continue;
- vector<int> cnt(colours_size, -1);
- auto q = vp;
- while (!q.empty()) {
- vector<pair<int, int>> vp1;
- for (auto [i, from] : vp) {
- int count = (from == -1 ? 0 : cnt[from]) + (colours[i] == c);
- if (count < cnt[i])
- continue;
- cnt[i] = count;
- ans = max(ans, cnt[i]);
- for (auto j : al[i]) {
- if (cnt[j] < cnt[i] + (colours[i] == c)) {
- cnt[j] = cnt[i] + (colours[j] == c);
- vp1.push_back({j, i});
- }
- }
- }
- swap(vp, vp1);
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd e1 = {{0, 1}, {0, 2}, {2, 3}, {3, 4}};
- vvd e2 = {{0, 0}};
- printf("%d\n", obj.largestPathValue("abaca", e1)); // expect: 3
- printf("%d\n", obj.largestPathValue("a", e2)); // expect: -1
-}
diff --git a/other/largest_int_add_target.cpp b/other/largest_int_add_target.cpp
deleted file mode 100644
index 91015d0..0000000
--- a/other/largest_int_add_target.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string largestNumber(vector<int> &cost, int target) {
- vector<int> dp(target + 1, -10000);
- dp[0] = 0;
- for (int i = 1; i <= target; ++i)
- for (int j = 0; j < 9; ++j)
- dp[i] = max(dp[i], i >= cost[j] ? 1 + dp[i - cost[j]] : -10000);
- if (dp[target] < 0)
- return "0";
- string ans = "";
- for (int i = 8; i >= 0; --i) {
- while (target >= cost[i] && dp[target] == dp[target - cost[i]] + 1) {
- ans.push_back('1' + i);
- target -= cost[i];
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> cost = {4, 3, 2, 5, 6, 7, 2, 5, 5};
- int target = 9;
- cout << obj.largestNumber(cost, target);
-}
diff --git a/other/largest_multiple_three.cpp b/other/largest_multiple_three.cpp
deleted file mode 100644
index 1c9e3e1..0000000
--- a/other/largest_multiple_three.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string largestMultipleOfThree(vector<int> &digits) {
- int n = digits.size(), d[10] = {}, sum = 0;
- int r1[] = {1, 4, 7, 2, 5, 8}, r2[] = {2, 5, 8, 1, 4, 7};
- string ans = "";
- for (int i = 0; i < n; i++) {
- ++d[digits[i]];
- sum += digits[i];
- }
- while (sum % 3 != 0) {
- for (int i = 0; i < 6; i++) {
- if (sum % 3 == 1 && d[r1[i]]) {
- sum -= r1[i];
- d[r1[i]]--;
- break;
- } else if (sum % 3 == 2 && d[r2[i]]) {
- sum -= r2[i];
- d[r2[i]]--;
- break;
- }
- }
- }
- for (int i = 9; i >= 0; i--)
- for (int j = 1; j <= d[i]; j++)
- ans += to_string(i);
- return ans[0] == '0' ? "0" : ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> digits = {8, 1, 9};
- cout << obj.largestMultipleOfThree(digits);
-}
diff --git a/other/largest_odd_num_string.cpp b/other/largest_odd_num_string.cpp
deleted file mode 100644
index 019d609..0000000
--- a/other/largest_odd_num_string.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string largestOddNumber(string num) {
- if (num.back() == '0')
- num.pop_back();
- int back = stoi(num) % 10;
- if (back % 2 == 0) {
- for (int i = 0; i < num.size(); i++)
- if (num[i] % 2 == 0)
- num.erase(i, 1), i--;
- if (num.size() < 2)
- return num;
- else
- for (int i = 0; i < num.size(); i++)
- if (num[i] < num[i + 1])
- return num.substr(i + 2, 1);
- } else
- return num;
- return string();
- }
-};
-
-int main() {
- Solution obj;
- cout << endl << obj.largestOddNumber("10133890");
-}
diff --git a/other/largest_perimeter_triangle.cpp b/other/largest_perimeter_triangle.cpp
deleted file mode 100644
index 64b3682..0000000
--- a/other/largest_perimeter_triangle.cpp
+++ /dev/null
@@ -1,18 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int largestPerimeter(vector<int> &nums) {
- sort(nums.begin(), nums.end());
- for (int i = nums.size() - 1; i > 1; --i)
- if (nums[i] < nums[i - 1] + nums[i - 2])
- return nums[i] + nums[i - 1] + nums[i - 2];
- return 0;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {2, 1, 2};
- cout << obj.largestPerimeter(nums);
-}
diff --git a/other/last_day_cross.cpp b/other/last_day_cross.cpp
deleted file mode 100644
index 4bf2e6b..0000000
--- a/other/last_day_cross.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-// 1970. Last Day Where You Can Still Cross
-#include "leetcode.h"
-
-/*
- * there is a 1-based binary matrix where 0 represents land and 1 represents
- * water. you are given integers 'row' and 'col' representing the number of rows
- * and columns in the matrix, respectively. initially on day 0, the entire
- * matrix is land. however each day a new cell becomes flooded with water. you
- * are given a 1-based 2d array 'cells', where 'cells[i] = [ri, ci]' represnts
- * that on the i'th day, the cell on the r[i'th] row and c[i'th] column (1-based
- * coordinates) will be covered with water (ie. changed to 1). you want to find
- * the last day that it is possible to walk from the top to the bottom by only
- * walking on land cells. you can start from any cell in the top row and end in
- * any cell in the bottom row. you can only travel in the four cardinal
- * directions (left, right, up, down) return the last day where it is possible
- * to walk from the top to the bottom by only walking on land cells
- */
-
-class Solution {
-public:
- int latestDayToCross(int row, int col, vvd & cells) {
- vvd grid(row, vector<int>(col, 1));
- p = vector<int>(row * col + 3, -1);
- int start_g = row * col + 1, end_g = row * col + 2;
- for (int i = 0; i < col; i++) {
- uni(i, start_g);
- uni((row - 1) * col + i, end_g);
- }
- for (int i = row * col - 1; i >= 0; i--) {
- int r = cells[i][0] - 1, c = cells[i][1] - 1;
- grid[r][c] = 0;
- int key = r * col + c;
- for (int k = 0; k < 4; ++k) {
- int n_r = r + dir[k][0], n_c = c + dir[k][1];
- if (n_r >= 0 && n_r < row && n_c >= 0 && n_c < col && !grid[n_r][n_c]) {
- int n_key = n_r * col + n_c;
- uni(key, n_key);
- }
- }
- }
- return row * col - 1;
- }
-
-private:
- vector<int> p;
- const int dir[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
- int find(int x) { return p[x] < 0 ? x : p[x] = find(p[x]); }
- void uni(int x, int y) {
- x = find(x), y = find(y);
- if (x == y)
- return;
- p[y] = x;
- }
-};
-
-int main() {
- Solution obj;
- vvd c1 = {{1, 1}, {2, 1}, {1, 2}, {2, 2}},
- c2 = {{1, 1}, {1, 2}, {2, 1}, {2, 2}};
- printf("%d\n", obj.latestDayToCross(2, 2, c1)); // expect: 2
- printf("%d\n", obj.latestDayToCross(2, 2, c2)); // expect: 1
-}
diff --git a/other/leaf_similar_trees.cpp b/other/leaf_similar_trees.cpp
deleted file mode 100644
index 319fbbf..0000000
--- a/other/leaf_similar_trees.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool leafSimilar(TreeNode *root1, TreeNode *root2) {
- stack<TreeNode *> s1, s2;
- s1.push(root1);
- s2.push(root2);
- while (!s1.empty() && !s2.empty())
- if (dfs(s1) != dfs(s2))
- return false;
- return s1.empty() && s2.empty();
- }
-
-private:
- int dfs(stack<TreeNode *> &s) {
- while (true) {
- TreeNode *node = s.top();
- s.pop();
- if (node->right)
- s.push(node->right);
- if (node->left)
- s.push(node->left);
- if (!node->left && !node->right)
- return node->val;
- }
- }
-};
diff --git a/other/leaf_similar_trees.rs b/other/leaf_similar_trees.rs
deleted file mode 100644
index 6dcaae1..0000000
--- a/other/leaf_similar_trees.rs
+++ /dev/null
@@ -1,44 +0,0 @@
-#[derive(Debug, PartialEq, Eq)]
-pub struct TreeNode {
- pub val: i32,
- pub left: Option<Rc<RefCell<TreeNode>>>,
- pub right: Option<Rc<RefCell<TreeNode>>>
-}
-
-impl TreeNode {
- #[inline]
- pub fn new(val: i32) -> Self {
- TreeNode {
- val,
- left: None,
- right: None
- }
- }
-}
-
-use std::rc::Rc;
-use std::cell::RefCell;
-impl Solution {
- pub fn leaf_similar(root1: Option<Rc<RefCell<TreeNode>>>, root2: Option<Rc<RefCell<TreeNode>>>) -> bool {
- let mut leaves1 = Vec::<i32>::new();
- Solution::get_leaves(root1, &mut leaves1);
- let mut leaves2 = Vec::<i32>::new();
- Solution::get_leaves(root2, &mut leaves2);
- leaves1 == leaves2
- }
- fn get_leaves(node: Option<Rc<RefCell<TreeNode>>>, leaves: &mut Vec<i32>) {
- if let Some(node) = node {
- let node = node.borrow();
- if node.left == None && node.right == None {
- leaves.push(node.val);
- } else {
- if let Some(ref left_node) = node.left {
- Solution::get_leaves(Some(Rc::clone(left_node)), leaves);
- }
- if let Some(ref right_node) = node.right {
- Solution::get_leaves(Some(Rc::clone(right_node)), leaves);
- }
- }
- }
- }
-}
diff --git a/other/letter_combo_number.cpp b/other/letter_combo_number.cpp
deleted file mode 100644
index c15a628..0000000
--- a/other/letter_combo_number.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<string> letterCombinations(string digits) {
- if (digits.empty())
- return {};
- vector<string> ans;
- ans.push_back("");
- for (auto digit : digits) {
- vector<string> tmp;
- for (auto candidate : nums[digit - '0'])
- for (auto s : ans)
- tmp.push_back(s + candidate);
- ans.swap(tmp);
- }
- for (int i = 0; i < digits.size(); i++)
- cout << ans[i];
- return ans;
- }
-
-private:
- const vector<string> nums = {"", "", "abc", "def", "ghi",
- "jkl", "mno", "pqrs", "tuv", "wxyz"};
-};
-
-int main() {
- string digits = "23";
- cout << digits << endl;
- Solution obj;
- obj.letterCombinations(digits);
-}
diff --git a/other/lexicographical_numbers.cpp b/other/lexicographical_numbers.cpp
deleted file mode 100644
index ab48ce5..0000000
--- a/other/lexicographical_numbers.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-// 386. Lexicographical Numbers
-#include "leetcode.h"
-
-/*
- * given an integer 'n', return all the numbers in the range '[1, n]' sorted in
- * lexicographical order. you must write an algorithm that runs in O(n) time
- * complexity and uses O(1) extra space.
- */
-
-class Solution {
-public:
- vector<int> ans;
- vector<int> lexicalOrder(int n) {
- ans.resize(n);
- int pos = 0;
- for (int i = 1; i <= 9 && i <= n; i++)
- helper(i, n, pos);
- return ans;
- }
-
-private:
- void helper(int i, int n, int pos) {
- ans[pos++] = i;
- int tmp;
- for (int j = 0; j <= 9; j++) {
- tmp = i * 10 + j;
- if (tmp > n)
- break;
- helper(tmp, n, pos);
- }
- }
-};
-
-int main() {
- Solution obj;
- vector<int> lo1 = obj.lexicalOrder(13), lo2 = obj.lexicalOrder(2);
- for (int i = 0; i < lo1.size(); i++)
- printf("%d ", lo1[i]); // expect: [1,10,11,12,13,2,3,4,5,6,7,8,9]
- printf("\n");
- for (int i = 0; i < lo2.size(); i++)
- printf("%d ", lo2[i]); // expect: [1,2]
- printf("\n");
-}
diff --git a/other/lexicographically_small_string.cpp b/other/lexicographically_small_string.cpp
deleted file mode 100644
index 3a58189..0000000
--- a/other/lexicographically_small_string.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-#include "leetcode.h"
-
-/*
- * given: 2 strings of same length ('s1', 's2'), & a string 'baseStr'
- * s1[i] and s2[i] are equivalent characters
- * eg. s1 = "abc", s2 = "cde", 'a' == 'c', 'b' == 'd', etc.
- * return lexicographically smallest equivalent string of 'baseStr' by using
- * equivalency information from 's1' & 's2'
- */
-
-class Solution {
-public:
- // union find
- string smallestEquivalentString(string s1, string s2, string baseStr) {
- vector<int> ds(26, -1);
- for (auto i = 0; i < s1.size(); ++i)
- dsMerge(ds, s1[i] - 'a', s2[i] - 'a');
- for (auto i = 0; i < baseStr.size(); ++i)
- baseStr[i] = dsFind(ds, baseStr[i] - 'a') + 'a';
- return baseStr;
- }
-
-private:
- int dsFind(vector<int> &ds, int p) {
- return ds[p] == -1 ? p : ds[p] = dsFind(ds, ds[p]);
- }
- void dsMerge(vector<int> &ds, int p1, int p2) {
- p1 = dsFind(ds, p1), p2 = dsFind(ds, p2);
- if (p1 != p2)
- ds[max(p1, p2)] = min(p1, p2);
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.smallestEquivalentString("parker", "morris",
- "parser"); // expect: makkek
- cout << obj.smallestEquivalentString("hello", "world", "hold"); // expect:
- // hdld
- cout << obj.smallestEquivalentString("leetcode", "programs",
- "sourcecode"); // expect: aauaaaaada
-}
diff --git a/other/lfu_cache.cpp b/other/lfu_cache.cpp
deleted file mode 100644
index c0c857a..0000000
--- a/other/lfu_cache.cpp
+++ /dev/null
@@ -1,69 +0,0 @@
-// 460. LFU Cache
-#include <bits/stdc++.h>
-#include <unordered_map>
-using namespace std;
-
-// https://en.wikipedia.org/wiki/Least_frequently_used
-// http://dhruvbird.com/lfu.pdf
-
-struct Node {
- int value;
- list<int>::iterator itr;
-};
-
-class LFUCache {
-private:
- unordered_map<int, Node> umVal;
- unordered_map<int, int> umCount;
- unordered_map<int, list<int>> umlCountKey;
- int lowFreq, maxCap;
-
-public:
- LFUCache(int capacity) {
- maxCap = capacity;
- lowFreq = 0;
- }
- int get(int key) {
- if (umVal.find(key) == umVal.end() || maxCap <= 0)
- return -1;
- put(key, umVal[key].value);
- return umVal[key].value;
- }
- void put(int key, int value) {
- if (maxCap <= 0)
- return;
- if (umVal.find(key) == umVal.end()) {
- if (umVal.size() == maxCap) {
- int del = umlCountKey[lowFreq].back();
- umlCountKey[lowFreq].pop_back();
- if (umlCountKey[lowFreq].empty())
- umlCountKey.erase(lowFreq);
- umVal.erase(del);
- umCount.erase(del);
- }
- umVal[key].value = value;
- umCount[key] = 0;
- lowFreq = 0;
- umlCountKey[umCount[key]].push_front(key);
- umVal[key].itr = umlCountKey[0].begin();
- } else {
- umlCountKey[umCount[key]].erase(umVal[key].itr);
- if (umlCountKey[umCount[key]].empty()) {
- if (lowFreq == umCount[key])
- lowFreq++;
- umlCountKey.erase(umCount[key]);
- }
- umVal[key].value = value;
- umCount[key]++;
- umlCountKey[umCount[key]].push_front(key);
- umVal[key].itr = umlCountKey[umCount[key]].begin();
- }
- }
-};
-
-int main() {
- int capacity, key, value;
- LFUCache *obj = new LFUCache(capacity);
- int param_1 = obj->get(key);
- obj->put(key, value);
-}
diff --git a/other/linked_list_cycle2.cpp b/other/linked_list_cycle2.cpp
deleted file mode 100644
index 43dccea..0000000
--- a/other/linked_list_cycle2.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-// 142. Linked List Cycle II
-#include "leetcode.h"
-
-/*
- * given 'head' of linked list, return node where the cycle begins. if there is
- * no cycle return null. there is a cycle in linked list of there is some node
- * in the list that can be reached again by continuously following the 'next'
- * pointer. internally, 'pos' is used to denote the index of the node that
- * tail's 'next' pointer is connected to. it is -1 if there is no cycle. note
- * 'pos' is not passed as parameter.
- */
-
-class Solution {
-public:
- ListNode *detectCycle(ListNode *head) {
- ListNode *slow = head, *fast = head;
- while (fast && fast->next) {
- slow = slow->next;
- fast = fast->next->next;
- if (slow == fast)
- break;
- }
- if (!(fast && fast->next))
- return NULL;
- while (head != slow) {
- head = head->next;
- slow = slow->next;
- }
- return head;
- }
-};
diff --git a/other/linked_list_random.cpp b/other/linked_list_random.cpp
deleted file mode 100644
index ae147c5..0000000
--- a/other/linked_list_random.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 382. Linked List Random Node
-#include "leetcode.h"
-
-/*
- * given singly linked list, return a random node's value from the linked list.
- * each node must have the same probability of being chosen. implement
- * 'Solution' class: f1: initialises object with head of signly linked list
- * 'head' f2: chooses node randomly from list and returns its value. all nodes
- * should be equally likely to be chosen
- */
-
-class Solution {
-public:
- Solution(ListNode *head) {
- this->head = head;
- while (head != NULL) {
- this->n++;
- head = head->next;
- }
- }
- int getRandom() {
- int i = rand() % this->n;
- ListNode *p = this->head;
- while (i) {
- p = p->next;
- i -= 1;
- }
- return p->val;
- }
-
-private:
- int n = 0;
- ListNode *head = NULL;
-};
-
-int main() {
- ListNode *head;
- Solution *obj = new Solution(head);
- int param_1 = obj->getRandom();
-}
diff --git a/other/longest_arithmetic_subseq.cpp b/other/longest_arithmetic_subseq.cpp
deleted file mode 100644
index 5cc91a7..0000000
--- a/other/longest_arithmetic_subseq.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// 1027. Longest Arithmetic Subsequence
-#include "leetcode.h"
-
-/*
- * given an array 'nums' of integers, return the length of the longest
- * arithmetic subsequence in 'nums'. note that
- * - a subsequence is an array that can be derived from another array by
- * deleting some or no elements without changing the order of the remaining
- * elements.
- * - a sequence 'seq' is arithmetic if 'seq[i + 1] - seq[i]' are all the same
- * value (for '0 <= i < seq.len() - 1')
- */
-
-class Solution {
-public:
- int longestArithmeticSeqLength(vector<int> &nums) {
- int n = nums.size(), ans = 0;
- vvd dp(n, vector<int>(n, 1));
- for (int i = 1; i < n - 1; ++i)
- for (int j = i + 1; j < n; ++j) {
- for (int k = i - 1; k >= 0; k--)
- if (nums[i] - nums[k] == nums[j] - nums[i])
- dp[i][j] = max(dp[i][j], dp[k][i] + 1);
- ans = max(ans, dp[i][j]);
- }
- return ans + 1;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {3, 6, 9, 12}, n2 = {9, 4, 7, 2, 10},
- n3 = {20, 1, 15, 3, 10, 5, 8};
- printf("%d\n", obj.longestArithmeticSeqLength(n1)); // expect: 4
- printf("%d\n", obj.longestArithmeticSeqLength(n2)); // expect: 3
- printf("%d\n", obj.longestArithmeticSeqLength(n3)); // expect: 4
-}
diff --git a/other/longest_arithmetic_subseq_diff.cpp b/other/longest_arithmetic_subseq_diff.cpp
deleted file mode 100644
index dc6e9ff..0000000
--- a/other/longest_arithmetic_subseq_diff.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-// 1218. Longest Arithmetic Subsequence of Given Difference
-#include "leetcode.h"
-
-/*
- * given an integer array 'arr' and an integer 'difference', return the length
- * of the longest subsequence in 'arr' which is an arithmetic sequence such that
- * the difference between adjacent elements in the subsequence equals
- * 'difference'. a subsequence is a sequence that can be derived from 'arr' by
- * deleting some or no elements without changing the order of the remaining
- * elements.
- */
-
-class Solution {
-public:
- int longestSubsequence(vector<int> &arr, int difference) {
- int ans = 1;
- unordered_map<int, int> max;
- for (int i = 0; i < arr.size(); i++)
- max[arr[i]] = max[arr[i] - difference] + 1;
- for (auto i : max)
- ans = std::max(ans, i.second);
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> a1 = {1, 2, 3, 4}, a2 = {1, 3, 5, 7},
- a3 = {1, 5, 7, 8, 5, 3, 4, 2, 1};
- printf("%d\n", obj.longestSubsequence(a1, 1)); // expect: 4
- printf("%d\n", obj.longestSubsequence(a2, 1)); // expect: 1
- printf("%d\n", obj.longestSubsequence(a3, -2)); // expect: 4
-}
diff --git a/other/longest_common_subseq.cpp b/other/longest_common_subseq.cpp
deleted file mode 100644
index 56cbaf9..0000000
--- a/other/longest_common_subseq.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int longestCommonSubsequence(string text1, string text2) {
- short ans[2][1000] = {};
- for (int i = 0; i < text1.size(); ++i)
- for (int j = 0; j < text2.size(); ++j)
- ans[!(i % 2)][j + 1] = text1[i] == text2[j]
- ? ans[i % 2][j] + 1
- : max(ans[i % 2][j + 1], ans[!(i % 2)][j]);
- return ans[text1.size() % 2][text2.size()];
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.longestCommonSubsequcne("abcde", "ace"); // 3
- cout << endl << obj.longestCommonSubsequcne("abc", "abc"); // 3
-}
diff --git a/other/longest_common_subseq.rs b/other/longest_common_subseq.rs
deleted file mode 100644
index 212070a..0000000
--- a/other/longest_common_subseq.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn longest_common_subsequence(text1: String, text2: String) -> i32 {
- let mut dp: Vec<Vec<usize>> = vec![vec![0; text2.len() + 1]; text1.len() + 1];
- for (i, c1) in text1.chars().enumerate() {
- for (j, c2) in text2.chars().enumerate() {
- dp[i + 1][j + 1] = if c1 == c2 {
- dp[i][j] + 1
- } else {
- std::cmp::max(dp[i][j + 1], dp[i + 1][j])
- }
- }
- }
- dp[text1.len()][text2.len()] as i32
- }
-}
-
-fn main() {
- let text1 = String::from("abcde");
- let text2 = String::from("ace");
- print!("{}", Solution::longest_common_subsequence(text1, text2)); //3
-}
diff --git a/other/longest_consecutive_sequence.cpp b/other/longest_consecutive_sequence.cpp
deleted file mode 100644
index 2fda5e6..0000000
--- a/other/longest_consecutive_sequence.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int longestConsecutive(vector<int> &nums) {
- unordered_set<int> us;
- int ans = 0;
- for (int i = 0; i < nums.size(); i++)
- us.insert(nums[i]);
- while (us.size() > 0) {
- int num = *us.begin();
- int count = 1;
- us.erase(num);
- int smaller = num - 1;
- int bigger = num + 1;
- while (us.count(smaller) > 0) {
- us.erase(smaller);
- smaller--;
- count++;
- }
- while (us.count(bigger) > 0) {
- us.erase(bigger);
- bigger++;
- count++;
- }
- ans = max(ans, count);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {100, 4, 200, 1, 3, 2};
- cout << obj.longestConsecutive(nums);
-}
diff --git a/other/longest_cycle_graph.cpp b/other/longest_cycle_graph.cpp
deleted file mode 100644
index b0cdf49..0000000
--- a/other/longest_cycle_graph.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-// 2360. Longest Cycle in a Graph
-#include "leetcode.h"
-
-/*
- * given a directed graph of 'n' nodes numbered from 0 to n - 1, where each node
- * has at most one outgoing edge. the graph is represented with a given
- * 0-indexed array 'edges' of size n, indicating that there is a directed edge
- * from node i to node edges[i]. if there is no outgoing edge from node i, then
- * edges[i] == -1. return length of longest cycle in the graph. if no cycle
- * exists, return -1. a cycle path starts at same node.
- */
-
-class Solution {
-public:
- int longestCycle(vector<int> &edges) {
- vector<bool> vis(edges.size(), 0);
- for (int i = 0; i < edges.size(); i++) {
- if (vis[i])
- continue;
- vector<int> store;
- dfs(edges, i, vis, store);
- }
- return max_len;
- }
-
-private:
- int max_len = -1;
- void dfs(vector<int> &edges, int si, vector<bool> &vis, vector<int> &store) {
- if (si == -1)
- return;
- if (vis[si]) {
- int cnt = -1;
- for (int i = 0; i < store.size(); i++) {
- if (store[i] == si) {
- cnt = i;
- break;
- }
- }
- if (cnt == -1)
- return;
- int size = store.size() - cnt;
- max_len = max(max_len, size);
- return;
- }
- vis[si] = true;
- store.push_back(si);
- dfs(edges, edges[si], vis, store);
- return;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> e1 = {3, 3, 4, 2, 3};
- vector<int> e2 = {2, -1, 3, 1};
- printf("%d\n", obj.longestCycle(e1));
- printf("%d\n", obj.longestCycle(e2));
-}
diff --git a/other/longest_happy_string.cpp b/other/longest_happy_string.cpp
deleted file mode 100644
index ea3ad78..0000000
--- a/other/longest_happy_string.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-// 1405. Longest Happy String
-#include "leetcode.h"
-
-/*
- * a string 's' is called happy if it satisfies the following conditions: 's'
- * only contains the letters 'a', 'b', 'c', does not contain any of 'aaa',
- * 'bbb', or 'ccc' as a substring, contains at most 'n' occurences of the
- * letters 'a', 'b', 'c'. given three integers, return the longest possible
- * happy string. if there are multiple longest happy strings, return any of
- * them. if there is no such string, return the empty string
- */
-
-class Solution {
-public:
- string longestDiverseString(int a, int b, int c, char aa = 'a', char bb = 'b',
- char cc = 'c') {
- if (a < b)
- return longestDiverseString(b, a, c, bb, aa, cc);
- if (b < c)
- return longestDiverseString(a, c, b, aa, cc, bb);
- if (!b)
- return string(min(2, a), aa);
- auto use_a = min(2, a), use_b = a - use_a >= b ? 1 : 0;
- return string(use_a, aa) + string(use_b, bb) +
- longestDiverseString(a - use_a, b - use_b, c, aa, bb, cc);
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.longestDiverseString(1, 1, 7) << endl; // expect: ccaccbcc
- cout << obj.longestDiverseString(7, 1, 0) << endl; // expect: aabaa
-}
diff --git a/other/longest_increasing_subseq.cpp b/other/longest_increasing_subseq.cpp
deleted file mode 100644
index 127a984..0000000
--- a/other/longest_increasing_subseq.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-#include "leetcode.h"
-
-class maxBit {
-public:
- vector<int> bit;
- maxBit(int size) { bit.resize(size + 1); }
- int get(int idx) {
- int ans = 0;
- for (; idx > 0; idx -= idx & -idx)
- ans = max(ans, bit[idx]);
- return ans;
- }
- void update(int idx, int val) {
- for (; idx < bit.size(); idx += idx & -idx)
- bit[idx] = max(bit[idx], val);
- }
-};
-
-class Solution {
-public:
- int lengthOisLIS(vector<int> &nums) {
- int uniqueNum = compress(nums);
- maxBit bit(uniqueNum);
- for (int x : nums) {
- int subLongest = bit.get(x - 1);
- bit.update(x, subLongest + 1);
- }
- return bit.get(uniqueNum);
- }
-
-private:
- int compress(vector<int> &arr) {
- vector<int> uniqueSorted(arr);
- sort(uniqueSorted.begin(), uniqueSorted.end());
- uniqueSorted.erase(unique(uniqueSorted.begin(), uniqueSorted.end()),
- uniqueSorted.end());
- for (int &x : arr)
- x = lower_bound(uniqueSorted.begin(), uniqueSorted.end(), x) -
- uniqueSorted.begin() + 1;
- return uniqueSorted.size();
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {10, 9, 2, 5, 3, 7, 101, 18};
- cout << obj.lengthOisLIS(nums);
-}
diff --git a/other/longest_palindrome_concat.cpp b/other/longest_palindrome_concat.cpp
deleted file mode 100644
index 3a42e0a..0000000
--- a/other/longest_palindrome_concat.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int longestPalindrome(vector<string> &words) {
- unordered_map<string, int> um;
- for (auto w : words)
- ++um[w];
- int ans = 0, center = 0, sz = 2;
- for (auto [w, cnt] : um) {
- auto reversed = string(rbegin(w), rend(w));
- if (w == reversed) {
- ans += 2 * (cnt / 2);
- center |= cnt % 2;
- } else {
- auto it = um.find(reversed);
- if (it != end(um))
- ans += min(cnt, it->second);
- }
- }
- return sz * ans + (center ? sz : 0);
- }
-};
-
-int main() {
- Solution obj;
- vector<string> words = {"lc", "cl", "gg"};
- cout << obj.longestPalindrome(words);
-}
diff --git a/other/longest_palindrome_concat.rs b/other/longest_palindrome_concat.rs
deleted file mode 100644
index 2a97ed4..0000000
--- a/other/longest_palindrome_concat.rs
+++ /dev/null
@@ -1,39 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn longest_palindrome(words: Vec<String>) -> i32 {
- let (mut hist, mut ans, a_code) = (vec![vec![0; 26];26], 0, 'a' as usize);
- for w in words.iter() {
- if let Some(i) = w.chars().nth(0) {
- if let Some(j) = w.chars().nth(1) {
- let i = i as usize - a_code;
- let j = j as usize - a_code;
- match hist[j][i] {
- cnt if cnt > 0 => {
- ans += 4;
- hist[j][i] -= 1;
- },
- _ => {
- hist[i][j] += 1;
- }
- }
- }
- }
- }
- for i in 0..26 {
- match hist[i][i] {
- cnt if cnt > 0 => {
- ans += 2;
- break;
- },
- _ => (),
- }
- }
- ans
- }
-}
-
-fn main() {
- let words = vec!["lc".to_string(), "cl".to_string(), "gg".to_string()];
- print!("{}", Solution::longest_palindrome(words));
-}
diff --git a/other/longest_palindromic_subseq.cpp b/other/longest_palindromic_subseq.cpp
deleted file mode 100644
index f2a074f..0000000
--- a/other/longest_palindromic_subseq.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-// 516. Longest Palindromic Subsequence
-#include "leetcode.h"
-
-/*
- * given string 's', find the longest palindromic susbsequences
- * of length in 's'. a subsequcnes is a sequence that can be derived
- * from another sequence by deleting some or no elements without
- * changing the order of the remaining elements
- */
-
-class Solution {
-public:
- int longestPalindromeSubseq(string s) {
- int n = s.size();
- vector<int> dp(n, 0);
- for (int i = n - 1; i >= 0; i--) {
- vector<int> new_dp(n, 0);
- new_dp[i] = 1;
- for (int j = i + 1; j < n; j++) {
- if (s[i] == s[j])
- new_dp[j] = 2 + dp[j - 1];
- else
- new_dp[j] = max(dp[j], new_dp[j - 1]);
- }
- dp = new_dp;
- }
- return dp[n - 1];
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.longestPalindromeSubseq("bbbab")); // expect: 4
- printf("%d\n", obj.longestPalindromeSubseq("cbbd")); // expect: 2
-}
diff --git a/other/longest_palindromic_substr.cpp b/other/longest_palindromic_substr.cpp
deleted file mode 100644
index 4ecba25..0000000
--- a/other/longest_palindromic_substr.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string longestPalindrome(string s) {
- if (s.size() == 0)
- return "";
- int i = 0, j = 0, n = s.size();
- bool p[n][n] = {false};
- for (int x = 0; x < n; x++) {
- p[x][x] = true;
- if (x == n - 1)
- break;
- p[x][x + 1] = (s[x] == s[x + 1]);
- }
- for (int i = n - 3; i >= 0; --i)
- for (int j = i + 2; j < n; ++j)
- p[i][j] = (p[i + 1][j - 1] && s[i] == s[j]);
- int max = 0;
- string ans = "";
- for (int i = 0; i < n; i++)
- for (int j = i; j < n; j++)
- if (p[i][j] == true && j - i + 1 > max) {
- max = j - i + 1;
- ans = s.substr(i, j - i + 1);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- string s = "babad";
- cout << obj.longestPalindrome(s);
-}
diff --git a/other/longest_path_diff_adjacent_char.cpp b/other/longest_path_diff_adjacent_char.cpp
deleted file mode 100644
index 0f60da9..0000000
--- a/other/longest_path_diff_adjacent_char.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-// 2246. Longest Path With Different Adjacent Characters
-#include "leetcode.h"
-
-/*
- * you are given a tree (ie. a connected undirected graph that has no cycles)
- * rooted at node '0' consisting of 'n' nodes numbered from '0' to 'n - 1'. the
- * tree is represented by a 0-indexed array 'parent' of size 'n' where
- * 'parent[i]' is the parent of node 'i'. since node 0 is the root, 'parent[0] =
- * -1'. you are also given a string 's' of length 'n', where 's[i]' is the
- * character assigned to node 'i'. return the legnth of the longest path in the
- * tree such that no pair of adjacnet nodes on the path have the same character
- * assigned to them.
- */
-
-class Solution {
-public:
- int longestPath(vector<int> &parent, string s) {
- int n = parent.size(), ans = 1;
- queue<int> q;
- vector<int> cnt(n), top1(n, 1), top2(n, 1);
- for (int i = 1; i < n; ++i)
- ++cnt[parent[i]];
- for (int i = 1; i < n; ++i)
- if (!cnt[i])
- q.push(i);
- while (!q.empty() && q.front()) {
- int i = q.front(), p = parent[i];
- q.pop();
- if (int len = 1 + (s[i] != s[p] ? top1[i] : 0); top1[p] <= len) {
- top2[p] = top1[p];
- top1[p] = len;
- } else
- top2[p] = max(top2[p], len);
- if (--cnt[p] == 0) {
- q.push(p);
- ans = max(ans, top1[p] + top2[p] - 1);
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> p1 = {-1, 0, 0, 1, 1, 2}, p2 = {-1, 0, 0, 0};
- printf("%d\n", obj.longestPath(p1, "abacbe")); // expect: 3
- printf("%d\n", obj.longestPath(p2, "aabc")); // expect: 3
-}
diff --git a/other/longest_path_diff_adjacent_char.rs b/other/longest_path_diff_adjacent_char.rs
deleted file mode 100644
index b35568c..0000000
--- a/other/longest_path_diff_adjacent_char.rs
+++ /dev/null
@@ -1,77 +0,0 @@
-// 2246. Longest Path With Different Adjacent Characters
-
-/*
- * you are given a tree (ie. a connected undirected graph that has no cycles)
- * rooted at node '0' consisting of 'n' nodes numbered from '0' to 'n - 1'. the
- * tree is represented by a 0-indexed array 'parent' of size 'n' where
- * 'parent[i]' is the parent of node 'i'. since node 0 is the root, 'parent[0] =
- * -1'. you are also given a string 's' of length 'n', where 's[i]' is the
- * character assigned to node 'i'. return the legnth of the longest path in the
- * tree such that no pair of adjacnet nodes on the path have the same character
- * assigned to them.
- */
-
-use std::cmp::max;
-use std::collections::HashMap;
-struct Solution;
-
-static mut res: i32 = 0;
-impl Solution {
- pub fn longest_path(parent: Vec<i32>, s: String) -> i32 {
- unsafe { res = 0 }
- let mut graph = HashMap::new();
- for (i, &u) in parent.iter().enumerate() {
- if u == -1 {
- continue;
- }
- let u = u as usize;
- if !graph.contains_key(&u) {
- graph.insert(u, vec![]);
- }
- graph.entry(u).or_insert(vec![]).push(i);
- }
- let sa: Vec<char> = s.chars().collect();
- Self::dfs(0, &graph, &sa);
- let mut ans: i32 = 0;
- unsafe {
- ans = res;
- }
- ans
- }
- fn dfs(root: usize, graph: &HashMap<usize, Vec<usize>>, s: &Vec<char>) -> i32 {
- if !graph.contains_key(&root) {
- unsafe {
- res = max(res, 1);
- }
- return 1;
- }
- let (mut a1, mut a2) = (0, 0);
- for &v in graph[&root].iter() {
- if s[root] == s[v] {
- Self::dfs(v, graph, s);
- continue;
- }
- let curr = Self::dfs(v, graph, s);
- if curr >= a1 {
- a2 = a1;
- a1 = curr;
- } else if curr > a2 {
- a2 = curr
- }
- }
- unsafe {
- res = max(res, a1 + a2 + 1);
- }
- a1 + 1
- }
-}
-
-fn main() {
- let parent1 = vec![-1, 0, 0, 1, 1, 2];
- let parent2 = vec![-1, 0, 0, 0];
- println!(
- "{}",
- Solution::longest_path(parent1, String::from("abacbe"))
- ); //expect: 3
- println!("{}", Solution::longest_path(parent2, String::from("aabc"))); //expect: 3
-}
diff --git a/other/longest_string_chain.cpp b/other/longest_string_chain.cpp
deleted file mode 100644
index afa805c..0000000
--- a/other/longest_string_chain.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int longestStrChain(vector<string> &words) {
- vector<unordered_set<string>> vus(17);
- for (auto i : words)
- vus[i.size()].insert(i);
- unordered_map<string, int> um;
- int ans = 1;
- for (int i = 16; i; i--) {
- if (vus[i - 1].empty())
- continue;
- for (auto j : vus[i]) {
- int wVal = um[j] ? um[j] : 1;
- for (int k = 0; k < j.size(); k++) {
- string prev = j.substr(0, k) + j.substr(k + 1);
- int pVal = um[prev] ? um[prev] : 1;
- if (vus[i - 1].find(prev) != vus[i - 1].end() && wVal >= pVal) {
- um[prev] = wVal + 1;
- ans = max(ans, wVal + 1);
- }
- }
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<string> words = {"a", "b", "ba", "bca", "bda", "bdca"};
- cout << obj.longestStrChain(words);
-}
diff --git a/other/longest_subarr_ones.cpp b/other/longest_subarr_ones.cpp
deleted file mode 100644
index 35f2353..0000000
--- a/other/longest_subarr_ones.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-// 1493. Longest Subarray of 1's After Deleting One Element
-#include "leetcode.h"
-
-/*
- * given a binary array 'nums', you should delete one element from it. return
- * the size of the longest non-empty subarray containing only 1's in the
- * resulting array. return 0 if there is no such subarray.
- */
-
-class Solution {
-public:
- int longestSubarray(vector<int> &nums) {
- int ans = 0;
- for (int i = 0, j = 0, skip = 0; i < nums.size(); ++i) {
- skip += !nums[i];
- if (skip > 1)
- skip -= !nums[j++];
- ans = max(ans, i - j);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 1, 0, 1}, n2 = {0, 1, 1, 1, 0, 1, 1, 0, 1},
- n3 = {1, 1, 1};
- printf("%d\n", obj.longestSubarray(n1)); // expect: 3
- printf("%d\n", obj.longestSubarray(n2)); // expect: 5
- printf("%d\n", obj.longestSubarray(n3)); // expect: 2
-}
diff --git a/other/longest_subseq_lim_sum.cpp b/other/longest_subseq_lim_sum.cpp
deleted file mode 100644
index 9613667..0000000
--- a/other/longest_subseq_lim_sum.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> answerQueries(vector<int> &nums, vector<int> &queries) {
- int n = nums.size(), m = queries.size();
- sort(nums.begin(), nums.end());
- vector<int> ans, pre(n + 1, 0);
- for (int i = 1; i < n; i++)
- pre[i] = pre[i - 1] + nums[i - 1];
- for (int i = 0; i < m; i++) {
- int sum = queries[i];
- auto z = lower_bound(pre.begin(), pre.end(), sum) - pre.begin();
- if (z < n + 1) {
- if (pre[z] == sum)
- ans.push_back(z);
- else
- ans.push_back(z - 1);
- } else if (z == n + 1)
- ans.push_back(n);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {4, 5, 2, 1}, queries = {3, 10, 21};
- for (auto i : obj.answerQueries(nums, queries))
- cout << i << ' ';
-}
diff --git a/other/longest_subseq_lim_sum.rs b/other/longest_subseq_lim_sum.rs
deleted file mode 100644
index 037b606..0000000
--- a/other/longest_subseq_lim_sum.rs
+++ /dev/null
@@ -1,17 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn answer_queries(mut nums: Vec<i32>, queries: Vec<i32>) -> Vec<i32> {
- nums.sort_unstable();
- nums.iter_mut().fold(0, |acc, x| { *x += acc; *x});
- queries.iter().map(|x|
- nums.binary_search(x).unwrap_or_else(|i| i - 1) as i32 + 1
- ).collect()
- }
-}
-
-fn main() {
- let nums = vec![4,5,2,1];
- let queries = vec![3,10,21];
- print!("{:?}", Solution::answer_queries(nums, queries));
-}
diff --git a/other/longest_substring_no_repeat.cpp b/other/longest_substring_no_repeat.cpp
deleted file mode 100644
index 0735fc7..0000000
--- a/other/longest_substring_no_repeat.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int lengthOfLongestSubstring(string s) {
- if (s.size() == 0)
- return 0;
- map<char, int> charsInSub;
- int ans = 0, j = 0;
- for (int i = 0; i < s.size(); ++i) {
- if (charsInSub.find(s[i]) != charsInSub.end())
- charsInSub.find(s[i])->second++;
- else
- charsInSub.insert(pair<char, int>(s[i], 1));
- while (charsInSub.find(s[i])->second > 1) {
- charsInSub.find(s[j])->second--;
- ++j;
- }
- ans = ans >= i - j + 1 ? ans : i - j + 1;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- string s = "abcabcbb";
- cout << obj.lengthOfLongestSubstring(s);
-}
diff --git a/other/longest_valid_course.cpp b/other/longest_valid_course.cpp
deleted file mode 100644
index 87f07a6..0000000
--- a/other/longest_valid_course.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-// 1964. Find the Longest Valid Obstacle Course at Each Position
-#include "leetcode.h"
-
-/*
- * you want to build obstacle courses. you are given a 0-indexed integer array
- * 'obstacles' of length 'n' where 'obstacles[i]' describes the height of the
- * i'th obstacle. for every index 'i' between 0 and 'n - 1' (inclusive), find
- * the length of the longest obstacle course in 'obstacles' such that:
- * - you choose any number of obstacles between 0 and 'i' inclusive
- * - you must include the i'th obstacle in the course
- * - you must put the chosen obstacles in the same order as they appear in
- * 'obstacles'
- * - every obstacle (except the first) is taller than or the same height as the
- * obstacle immediately before it return an array 'ans' of length 'n', where
- * 'ans[i]' is the length of the longest obstacle course for index 'i' as
- * described aboveeeeeeeee
- */
-
-class Solution {
-public:
- vector<int> longestObstacleCourseAtEachEachPosition(vector<int> &obstacles) {
- vector<int> n;
- for (int i = 0; i < obstacles.size(); ++i) {
- auto it = upper_bound(n.begin(), n.end(), obstacles[i]);
- if (it == n.end()) {
- n.push_back(obstacles[i]);
- it = prev(n.end());
- } else {
- *it = obstacles[i];
- }
- obstacles[i] = it - n.begin() + 1;
- }
- return obstacles;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> o1 = {1, 2, 3, 2}, o2 = {2, 2, 1}, o3 = {3, 1, 5, 6, 4, 2};
- for (auto i : obj.longestObstacleCourseAtEachEachPosition(o1))
- printf("%d ", i); // expect: 1 2 3 3
- printf("\n");
- for (auto i : obj.longestObstacleCourseAtEachEachPosition(o2))
- printf("%d ", i); // expect: 1 2 1
- printf("\n");
- for (auto i : obj.longestObstacleCourseAtEachEachPosition(o3))
- printf("%d ", i); // expect: 1 1 2 3 2 2
- printf("\n");
-}
diff --git a/other/longest_valid_parentheses.cpp b/other/longest_valid_parentheses.cpp
deleted file mode 100644
index 953e8be..0000000
--- a/other/longest_valid_parentheses.cpp
+++ /dev/null
@@ -1,41 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int longestValidParentheses(string s) {
- int n = s.size(), ans = 0;
- stack<int> stk;
- for (int i = 0; i < n; i++) {
- if (s[i] == '(')
- stk.push(i);
- else {
- if (!stk.empty()) {
- if (s[stk.top()] == '(')
- stk.pop();
- else
- stk.push(i);
- } else
- stk.push(i);
- }
- }
- if (stk.empty())
- ans = n;
- else {
- int a = n, b = 0;
- while (!stk.empty()) {
- b = stk.top();
- stk.pop();
- ans = max(ans, a - b - 1);
- a = b;
- }
- ans = max(ans, a);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- string s = ")()())";
- cout << obj.longestValidParentheses(s);
-}
diff --git a/other/longest_word_dict.cpp b/other/longest_word_dict.cpp
deleted file mode 100644
index 3be4538..0000000
--- a/other/longest_word_dict.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string findLongestWord(string s, vector<string> &dictionary) {
- string ans;
- for (auto d : dictionary)
- if (canForm(d, s))
- if (d.size() > ans.size() || (d.size() == ans.size() && d < ans))
- ans = d;
- return ans;
- }
-
-private:
- bool canForm(string w, string s) {
- int w1 = 0, s1 = 0;
- while (w1 < w.size() && s1 < s.size()) {
- if (w[w1] == s[s1])
- w1++;
- s1++;
- }
- return w1 == w.size();
- }
-};
-
-int main() {
- Solution obj;
- string s = "abpcplea";
- vector<string> dictionary = {"ale", "apple", "monkey", "plea"};
- cout << obj.findLongestWord(s, dictionary);
-}
diff --git a/other/longest_zigzag_bt.cpp b/other/longest_zigzag_bt.cpp
deleted file mode 100644
index b0ebe7f..0000000
--- a/other/longest_zigzag_bt.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-// 1372. Longest ZigZag Path in a Binary Tree
-#include "leetcode.h"
-
-/*
- * given the 'root' of a binary tree. a zigzag path for a binary tree is defined
- * as follows
- * - choose any node in the binary tree and a direction (left or right)
- * - if the current direction is right, move to the right child of the current
- * node
- * - change the direction from right to left or from left to right
- * - repeat the second nd third steps until you cannot move in the tree
- * zigzag length is defined as the number of nodes visited - 1. return longest
- * zigzag
- */
-
-class Solution {
- int ans = 0;
- map<pair<TreeNode *, bool>, int> mp;
- int find(TreeNode *root, bool check) {
- if (mp.find({root, check}) != mp.end())
- return mp[{root, check}];
- if (check) {
- if (root->right)
- return mp[{root, check}] = 1 + find(root->right, !check);
- else if (root->left)
- return mp[{root, check}] = 1 + find(root->left, !check);
- }
- return mp[{root, check}] = 1;
- }
- void preorder(TreeNode *root) {
- if (root) {
- if (root->left)
- ans = max(ans, find(root->left, true));
- if (root->right)
- ans = max(ans, find(root->right, false));
- preorder(root->left);
- preorder(root->right);
- }
- }
-
-public:
- int longestZigZag(TreeNode *root) {
- preorder(root);
- return ans;
- }
-};
diff --git a/other/lowest_common_ancestor.cpp b/other/lowest_common_ancestor.cpp
deleted file mode 100644
index ec99f32..0000000
--- a/other/lowest_common_ancestor.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
- frame ans;
- stack<frame> st;
- st.push({root, &ans});
- while (st.size()) {
- frame *top = &st.top(), *parent = top->parent;
- TreeNode *node = top->node;
- if (!node || node == p || node == q) {
- parent->subs.push_back(node);
- st.pop();
- } else if (top->subs.empty()) {
- st.push({node->right, top});
- st.push({node->left, top});
- } else {
- TreeNode *left = top->subs[0], *right = top->subs[1];
- parent->subs.push_back(!left ? right : !right ? left : node);
- st.pop();
- }
- }
- return ans.subs[0];
- }
-
-private:
- struct frame {
- TreeNode *node;
- frame *parent;
- vector<TreeNode *> subs;
- };
-};
diff --git a/other/lowest_common_ancestor_bst.cpp b/other/lowest_common_ancestor_bst.cpp
deleted file mode 100644
index d496c2c..0000000
--- a/other/lowest_common_ancestor_bst.cpp
+++ /dev/null
@@ -1,17 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
- int small = min(p->val, q->val), large = max(p->val, q->val);
- while (root != nullptr) {
- if (root->val > large)
- root = root->left;
- else if (root->val < small)
- root = root->right;
- else
- return root;
- }
- return nullptr;
- }
-};
diff --git a/other/lru_cache.cpp b/other/lru_cache.cpp
deleted file mode 100644
index f8d1656..0000000
--- a/other/lru_cache.cpp
+++ /dev/null
@@ -1,60 +0,0 @@
-// 146. LRU Cache
-#include "leetcode.h"
-
-/*
- * design a data structure that follows the constraints of a least recently used
- * cache (LRU). implete the 'LRUCache' class. the functions 'get' and 'put' must
- * each run in O(1) average time complexity
- */
-
-class LRUCache {
-private:
- typedef list<int> li;
- typedef pair<int, li::iterator> pii;
- typedef unordered_map<int, pii> hipii;
- hipii cache;
- li used;
- int _capacity;
- void touch(hipii::iterator i) {
- int key = i->first;
- used.erase(i->second.second);
- used.push_front(key);
- i->second.second = used.begin();
- }
-
-public:
- LRUCache(int capacity) { _capacity = capacity; }
- int get(int key) {
- auto i = cache.find(key);
- if (i == cache.end())
- return -1;
- touch(i);
- return i->second.first;
- }
- void put(int key, int value) {
- auto i = cache.find(key);
- if (i != cache.end())
- touch(i);
- else {
- if (cache.size() == _capacity) {
- cache.erase(used.back());
- used.pop_back();
- }
- used.push_front(key);
- }
- cache[key] = {value, used.begin()};
- }
-};
-
-int main() {
- LRUCache *obj = new LRUCache(2);
- obj->put(1, 1);
- obj->put(2, 2);
- printf("%d\n", obj->get(1)); // expect: 1
- obj->put(3, 3);
- printf("%d\n", obj->get(2)); // expect: -1
- obj->put(4, 4);
- printf("%d\n", obj->get(1)); // expect: -1
- printf("%d\n", obj->get(3)); // expect: 3
- printf("%d\n", obj->get(4)); // expect: 4
-}
diff --git a/other/magnetic_force_2_balls.cpp b/other/magnetic_force_2_balls.cpp
deleted file mode 100644
index 8416deb..0000000
--- a/other/magnetic_force_2_balls.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-// 1552. Magnetic Force Between Two Balls
-#include "leetcode.h"
-
-/*
- * in the universe earth c-137 rick discovered a special form of magnetic force
- * between two balls if they are put in his new invented basket. rick has 'n'
- * empty baskets the i'th basket is at 'position[i]', more has 'm' ball and
- * needs to distribute the balls into the baskets such that the minimum magnetic
- * force between any two balls is maximum. rick stated that magnetic force
- * betweeen two different balls at positions 'x' and 'y' is '|x - y|'. given the
- * integer array 'position' and the integer 'm', return the required force.
- */
-
-class Solution {
-public:
- int maxDistance(vector<int> &position, int m) {
- sort(position.begin(), position.end());
- int ans = 1, i = 999999999;
- while (ans < i) {
- int mid = (ans + i) / 2 + 1;
- if (check(position, m, mid))
- ans = mid;
- else
- i = mid - 1;
- }
- return ans;
- }
-
-private:
- int check(vector<int> &position, int m, int force) {
- int pos = position[0];
- for (auto i = 1; i < position.size() && m > 1; ++i)
- if (position[i] - pos >= force) {
- --m;
- pos = position[i];
- }
- return m < 2;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> p1 = {1, 2, 3, 4, 7}, p2 = {5, 4, 3, 2, 1, 1000000000};
- printf("%d\n", obj.maxDistance(p1, 3)); // expect: 3
- printf("%d\n", obj.maxDistance(p2, 2)); // expect: 999999999
-}
diff --git a/other/make_array_increasing.cpp b/other/make_array_increasing.cpp
deleted file mode 100644
index 482c0da..0000000
--- a/other/make_array_increasing.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-// 1187. Make Array Strictly Increasing
-#include <algorithm>
-#include <limits.h>
-#include <stdio.h>
-#include <unordered_map>
-#include <vector>
-using namespace std;
-
-/*
- * given two integer arrays 'arr1' and 'arr2', return the minimum number of
- * operations (possibly zero) needed to make 'arr1' strictly Increasing in one
- * opration, you can choose two indices '0 <= i <= arr1.len' and '0 <= j <
- * arr2.len' and do the assignment 'arr1[i] = arr2[j]' if there is no way to
- * make 'arr1' strictly increasing, return -1
- */
-
-class Solution {
- int check(int curr, int left, vector<int> &arr1, vector<int> &arr2,
- vector<unordered_map<int, int>> &dp) {
- if (curr == arr1.size())
- return 0;
- if (dp[curr].find(left) != dp[curr].end())
- return dp[curr][left];
- int exclude, include;
- if (arr1[curr] > left)
- exclude = check(curr + 1, arr1[curr], arr1, arr2, dp);
- else
- exclude = INT_MAX;
- int rep = upper_bound(arr2.begin(), arr2.end(), left) - arr2.begin();
- if (rep == arr2.size())
- include = INT_MAX;
- else
- include = check(curr + 1, arr2[rep], arr1, arr2, dp);
- if (include == INT_MAX)
- dp[curr][left] = exclude;
- else
- dp[curr][left] = min(exclude, include + 1);
- return dp[curr][left];
- }
-
-public:
- int makeArrayIncreasing(vector<int> &arr1, vector<int> &arr2) {
- sort(arr2.begin(), arr2.end());
- vector<unordered_map<int, int>> dp(2001);
- int val = check(0, INT_MIN, arr1, arr2, dp);
- if (val == INT_MAX)
- return -1;
- return val;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> a1123 = {1, 5, 3, 6, 7};
- vector<int> a21 = {1, 3, 2, 4}, a22 = {4, 3, 1}, a23 = {1, 6, 3, 3};
- printf("%d\n", obj.makeArrayIncreasing(a1123, a21)); // expect: 1
- printf("%d\n", obj.makeArrayIncreasing(a1123, a22)); // expect: 1
- printf("%d\n", obj.makeArrayIncreasing(a1123, a23)); // expect: 1
-}
diff --git a/other/make_string_great.cpp b/other/make_string_great.cpp
deleted file mode 100644
index 190bbed..0000000
--- a/other/make_string_great.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string makeGood(string s) {
- int n = s.size();
- if (n < 2)
- return s;
- while (n > 1) {
- bool pair = false;
- for (int i = 0; i < n; i++) {
- char curr = s[i], next = s[i + 1];
- if (abs(curr - next) == 32) {
- s = s.substr(0, i) + s.substr(i + 2);
- pair = true;
- break;
- }
- }
- if (!pair)
- break;
- }
- return s;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.makeGood("HhvmLxpqQPXlMVQWwq");
-}
diff --git a/other/make_string_great.rs b/other/make_string_great.rs
deleted file mode 100644
index 76a28a2..0000000
--- a/other/make_string_great.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn make_good(s: String) -> String {
- let diff_cases = |c1: char, c2: char| c1.to_ascii_lowercase() == c2.to_ascii_lowercase() && c1 != c2;
- s.chars().into_iter().fold(Vec::with_capacity(s.len()), |mut v: Vec<char>, c| {
- match v.last() {
- Some(prev_c) if diff_cases(c, *prev_c) => {
- v.pop();
- }
- _ => v.push(c)
- }
- v
- }).iter().collect()
- }
-}
-
-fn main() {
- let s = "leEeetcode".to_string();
- print!("{}", Solution::make_good(s));
-}
diff --git a/other/make_sum_divisible_p.cpp b/other/make_sum_divisible_p.cpp
deleted file mode 100644
index 993c955..0000000
--- a/other/make_sum_divisible_p.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-// 1590. Make Sum Divisible by P
-#include "leetcode.h"
-
-/*
- * given an array of positive integers 'nums', remove the smallest subarray
- * (possibly empty) such that the sum of the remaining elements is divisible by
- * 'p'. it is not allowed to remove the whole array. return the length of the
- * smallest subarray that you need to remove, or -1 if it is impossible. a
- * subarray is defined as a contiguous block of elements in the array.
- */
-
-class Solution {
-public:
- int minSubarray(vector<int> &nums, int p) {
- int n = nums.size(), ans = n, req = 0, curr = 0;
- for (auto i : nums)
- req = (req + i) % p;
- unordered_map<int, int> dp = {{0, -1}};
- for (int i = 0; i < n; i++) {
- curr = (curr + nums[i]) % p;
- dp[curr] = i;
- int need = (curr - req + p) % p;
- if (dp.count(need))
- ans = min(ans, i - dp[need]);
- }
- return ans < n ? ans : -1;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {3, 1, 4, 2}, n2 = {6, 3, 5, 2}, n3 = {1, 2, 3};
- printf("%d\n", obj.minSubarray(n1, 6)); // expect: 1
- printf("%d\n", obj.minSubarray(n2, 9)); // expect: 2
- printf("%d\n", obj.minSubarray(n3, 3)); // expect: 0
-}
diff --git a/other/marbles_in_bags.cpp b/other/marbles_in_bags.cpp
deleted file mode 100644
index 4640eb9..0000000
--- a/other/marbles_in_bags.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-// 2551. Put Marbles in Bags
-#include "leetcode.h"
-
-/*
- * you have 'k' bags. you are given a 0-indexed integer array 'weights' where
- * 'weights[i]' is the weight of the i'th marble. you are also given the integer
- * 'k'. divide the marbles into the 'k' bags according to the following rules
- * - no bag is empty
- * - if the i'th marble and the j'th marble are in a bag, then all the marbles
- * with an index between the i'th and j'th indices should also be in that same
- * bag.
- * - if a bag onsists of all the marbles with an index from 'i' to 'j'
- * inclusively, then the cost of the bag is 'weights[i] + weights[j]' the score
- * after distributing the marbles is the sum of the costs of all the 'k' bags.
- * return the difference between the maximum and minimum scores among marble
- * distributions
- */
-
-class Solution {
-public:
- long long putMarbles(vector<int> &weights, int k) {
- priority_queue<int> pq1;
- priority_queue<int, vector<int>, greater<int>> pq2;
- for (int i = 0; i < weights.size() - 1; i++) {
- pq1.push(weights[i] + weights[i + 1]);
- pq2.push(weights[i] + weights[i + 1]);
- if (pq1.size() > k - 1) {
- pq1.pop();
- pq2.pop();
- }
- }
- long long ans1 = 0, ans2 = 0;
- while (!pq1.empty()) {
- ans1 += pq1.top();
- ans2 += pq2.top();
- pq1.pop();
- pq2.pop();
- }
- return ans2 - ans1;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> w1 = {1, 3, 5, 1}, w2 = {1, 3};
- printf("%lld\n", obj.putMarbles(w1, 2)); // expect: 4
- printf("%lld\n", obj.putMarbles(w2, 2)); // expect: 0
-}
diff --git a/other/matchsticks_square.cpp b/other/matchsticks_square.cpp
deleted file mode 100644
index f2422b8..0000000
--- a/other/matchsticks_square.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool makesquare(vector<int> &matchsticks) {
- sort(matchsticks.begin(), matchsticks.end(), greater<int>());
- int total = accumulate(matchsticks.begin(), matchsticks.end(), 0);
- side = total;
- if ((float)total / 4 > side || matchsticks[0] > side)
- return false;
- return helper(0, side, 0, matchsticks);
- }
-
-private:
- int side;
- bool helper(int i, int space, int done, vector<int> &matchsticks) {
- if (done == 3)
- return true;
- for (; i < matchsticks.size(); i++) {
- int num = matchsticks[i];
- bool ans;
- if (num > space)
- continue;
- matchsticks[i] = side + 1;
- if (num == space)
- ans = helper(1, side, done + 1, matchsticks);
- else
- ans = helper(i + 1, space - num, done, matchsticks);
- if (ans)
- return true;
- matchsticks[i] = num;
- while (i < matchsticks.size() && matchsticks[i + 1] == num)
- i++;
- }
- return false;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> matchsticks = {1, 1, 2, 2, 2};
- if (obj.makesquare(matchsticks))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/matrix_diagonal_sum.cpp b/other/matrix_diagonal_sum.cpp
deleted file mode 100644
index 90e7fd5..0000000
--- a/other/matrix_diagonal_sum.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-// 1572. Matrix Diagonal Sum
-#include "leetcode.h"
-
-/*
- * given a square matrix 'mat', return the sum of the matrix
- * diagonals. only include the sum of all the elements on the
- * primary diagonal and all the elements on the secondary
- * diagonal that are not part of the primary
- */
-
-class Solution {
-public:
- int diagonalSum(vvd & mat) {
- int n = mat.size(), ans = 0;
- for (int i = 0; i < n; i++) {
- if (i != n - i - 1)
- ans += mat[i][i] + mat[i][n - i - 1];
- else
- ans += mat[i][i];
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd m1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
- vvd m2 = {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}};
- vvd m3 = {{5}};
- printf("%d\n", obj.diagonalSum(m1)); // expect: 25
- printf("%d\n", obj.diagonalSum(m2)); // expect: 8
- printf("%d\n", obj.diagonalSum(m3)); // expect: 5
-}
diff --git a/other/max_69.cpp b/other/max_69.cpp
deleted file mode 100644
index bc8abeb..0000000
--- a/other/max_69.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maximum69Number(int num) {
- if (num == 9999)
- return num;
- string n = to_string(num);
- for (auto &i : n)
- if (i == '6') {
- i = '9';
- break;
- }
- return stoi(n);
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.maximum69Number(9669);
-}
diff --git a/other/max_69.rs b/other/max_69.rs
deleted file mode 100644
index 0bead97..0000000
--- a/other/max_69.rs
+++ /dev/null
@@ -1,11 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn maximum69_number(num: i32) -> i32 {
- num.to_string().replacen("6", "9", 1).parse().unwrap()
- }
-}
-
-fn main() {
- print!("{}", Solution::maximum69_number(9669));
-}
diff --git a/other/max_area_cake.cpp b/other/max_area_cake.cpp
deleted file mode 100644
index da1f745..0000000
--- a/other/max_area_cake.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maxArea(int h, int w, vector<int> &horizontalCuts,
- vector<int> &verticalCuts) {
- sort(horizontalCuts.begin(), horizontalCuts.end());
- sort(verticalCuts.begin(), verticalCuts.end());
- int maxH = max(horizontalCuts[0], h - horizontalCuts.back());
- int maxV = max(verticalCuts[0], w - verticalCuts.back());
- for (int i = 1; i < horizontalCuts.size(); i++)
- maxH = max(maxH, horizontalCuts[i] - horizontalCuts[i - 1]);
- for (int i = 1; i < verticalCuts.size(); i++)
- maxV = max(maxV, verticalCuts[i] - verticalCuts[i - 1]);
- return ((long)maxH * maxV % 1000000007);
- }
-};
-
-int main() {
- Solution obj;
- int h = 5, w = 4;
- vector<int> horizontalCuts = {1, 2, 4};
- vector<int> verticalCuts = {1, 3};
- cout << obj.maxArea(h, w, horizontalCuts, verticalCuts);
-}
diff --git a/other/max_area_island.cpp b/other/max_area_island.cpp
deleted file mode 100644
index aad8b2d..0000000
--- a/other/max_area_island.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maxAreaOfIsland(vector<vector<int>> &grid) {
- int ans = 0;
- n = grid.size(), m = grid[0].size();
- for (int i = 0; i < n; i++)
- for (int j = 0; j < m; j++)
- if (grid[i][j])
- ans = max(ans, helper(i, j, grid));
- return ans;
- }
-
-private:
- int n = 0, m = 0;
- int helper(int i, int j, vector<vector<int>> &grid) {
- if (i < 0 || j < 0 || i >= n || j >= m || !grid[i][j])
- return 0;
- grid[i][j] = 0;
- return 1 + helper(i - 1, j, grid) + helper(i, j - 1, grid) +
- helper(i + 1, j, grid) + helper(i, j + 1, grid);
- }
-};
diff --git a/other/max_average_pass_ration.cpp b/other/max_average_pass_ration.cpp
deleted file mode 100644
index e9ebb25..0000000
--- a/other/max_average_pass_ration.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-// 1792. Maximum Average Pass Ratio
-#include "leetcode.h"
-
-/*
- * there is a school that has classes of student and each class will be having a
- * final exam. you are given a 2d integer array 'classes', where 'classes[i] =
- * [pass_i, total_i]'. you know beforehand that in the i'th class, there are
- * 'total_i' total students, but only 'pass_i' 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' to a class in a way that maximises the average pass ration
- * across all classes. return the maximum possible average pass ratio after
- * assigning the 'extraStudents'. answers within '10^-5' of the actual answer
- * will be accepted.
- */
-
-struct cmp {
- bool operator()(pair<int, int> a, pair<int, int> b) {
- double aa =
- (a.first + 1) / (double)(a.second + 1) - (a.first) / (double)a.second;
- double bb =
- (b.first + 1) / (double)(b.second + 1) - (b.first) / (double)b.second;
- return aa < bb;
- }
-};
-
-class Solution {
-public:
- double maxAverageRatio(vector<vector<int>> &classes, int extraStudents) {
- double acc = 0;
- priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> pq;
- for (vector<int> i : classes)
- pq.push(make_pair(i[0], i[1]));
- while (extraStudents--) {
- pair<int, int> curr = pq.top();
- pq.pop();
- curr.first++;
- curr.second++;
- pq.push(curr);
- }
- while (!pq.empty()) {
- pair<int, int> curr = pq.top();
- pq.pop();
- acc += curr.first / (double)curr.second;
- }
- return acc / (double)classes.size();
- }
-};
-
-int main() {
- Solution obj;
- vvd c1 = {{1, 2}, {3, 5}, {2, 2}},
- c2 = {{2, 4}, {3, 9}, {4, 5}, {2, 10}};
- printf("%f\n", obj.maxAverageRatio(c1, 2)); // expect: 0.78333
- printf("%f\n", obj.maxAverageRatio(c2, 4)); // expect: 0.53485
-}
diff --git a/other/max_bags_rocks.cpp b/other/max_bags_rocks.cpp
deleted file mode 100644
index 35c66bc..0000000
--- a/other/max_bags_rocks.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maximumBags(vector<int> &capacity, vector<int> &rocks,
- int additionalRocks) {
- vector<int> count;
- int n = rocks.size(), ans;
- for (int i = 0; i < n; ++i)
- count.push_back(capacity[i] - rocks[i]);
- sort(count.begin(), count.end());
- for (ans = 0; ans < n && additionalRocks >= count[ans]; ++ans)
- additionalRocks -= count[ans];
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> capacity = {2, 3, 4, 5}, rocks = {1, 2, 4, 4};
- cout << obj.maximumBags(capacity, rocks, 2);
-}
diff --git a/other/max_bags_rocks.rs b/other/max_bags_rocks.rs
deleted file mode 100644
index 808c393..0000000
--- a/other/max_bags_rocks.rs
+++ /dev/null
@@ -1,20 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn maximum_bags(capacity: Vec<i32>, rocks: Vec<i32>, mut additional_rocks: i32) -> i32 {
- let mut bag_space = (0..rocks.len()).map(|i| capacity[i] - rocks[i])
- .filter(|&d| d > 0)
- .collect::<Vec<_>>();
- let bag_full = rocks.len() - bag_space.len();
- bag_space.sort_unstable();
- bag_space.into_iter()
- .take_while(|&n| { additional_rocks -= n; additional_rocks >= 0 })
- .count() as i32 + bag_full as i32
- }
-}
-
-fn main() {
- let capacity = vec![2,3,4,5];
- let rocks = vec![1,2,4,4];
- print!("{}", Solution::maximum_bags(capacity, rocks, 2)); //expect: 3
-}
diff --git a/other/max_consecutive_ones3.cpp b/other/max_consecutive_ones3.cpp
deleted file mode 100644
index cff044f..0000000
--- a/other/max_consecutive_ones3.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int longestOnes(vector<int> &nums, int k) {
- int start = 0, end, count = 0, ans = 0;
- for (int end = 0; end < nums.size(); end++) {
- if (!nums[end])
- count++;
- if (count == k + 1) {
- while (nums[start])
- start++;
- start++;
- count--;
- }
- ans = max(ans, end - start + 1);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0};
- int k = 2;
- cout << obj.longestOnes(nums, k);
-}
diff --git a/other/max_depth_binary_tree.cpp b/other/max_depth_binary_tree.cpp
deleted file mode 100644
index e5ecc10..0000000
--- a/other/max_depth_binary_tree.cpp
+++ /dev/null
@@ -1,19 +0,0 @@
-// 104. Maximum Depth of Binary Tree
-#include "leetcode.h"
-
-/*
- * given the 'root' of a binary tree, return its maximum depth. a binary tree's
- * max depth is the number of nodes along the longest path from the root node
- * down to the farthest leaf node.
- */
-
-class Solution {
-public:
- int maxDepth(TreeNode *root) {
- if (!root)
- return 0;
- int max_left = maxDepth(root->left);
- int max_rght = maxDepth(root->right);
- return max(max_left, max_rght) + 1;
- }
-};
diff --git a/other/max_diff_node_ancestor.cpp b/other/max_diff_node_ancestor.cpp
deleted file mode 100644
index ab96947..0000000
--- a/other/max_diff_node_ancestor.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int diff = INT_MIN;
- int maxAncestorDiff(TreeNode *root) {
- if (!root)
- return 0;
- int mx = INT_MIN, mn = INT_MAX;
- getMax(root, mx, mn);
- return diff;
- }
-
-private:
- int getMax(TreeNode *root, int mx, int mn) {
- mx = max(mx, root->val);
- mn = min(mn, root->val);
- diff = max(diff, mx - mn);
- getMax(root->left, mx, mn);
- getMax(root->right, mx, mn);
- }
-};
diff --git a/other/max_diff_node_ancestor.rs b/other/max_diff_node_ancestor.rs
deleted file mode 100644
index 671bd27..0000000
--- a/other/max_diff_node_ancestor.rs
+++ /dev/null
@@ -1,61 +0,0 @@
-use std::cmp;
-use std::rc::Rc;
-use std::cell::RefCell;
-
-#[derive(Debug, PartialEq, Eq)]
-pub struct TreeNode {
- pub val: i32,
- pub left: Option<Rc<RefCell<TreeNode>>>,
- pub right: Option<Rc<RefCell<TreeNode>>>
-}
-
-struct MinMax {
- min: i32,
- max: i32,
- ans: i32
-}
-
-impl TreeNode {
- #[inline]
- pub fn new(val: i32) -> Self {
- TreeNode {
- val,
- left: None,
- right: None
- }
- }
-}
-
-impl Solution {
- fn minMax(node_ref: Rc<RefCell<TreeNode>>) -> MinMax {
- let node = node_ref.borrow();
- let mut a = MinMax {
- min: node.val,
- max: node.val,
- ans: 0
- };
- if node.left.is_none() && node.right.is_none() {
- a
- } else {
- let children = vec![&node.left, &node.right];
- for child_option in children.iter() {
- if let Some(child) = child_option {
- let c = Self::minMax(Rc::clone(&child));
- a.ans = cmp::max(a.ans, c.ans);
- a.ans = cmp::max(a.ans, (node.val - c.min).abs());
- a.ans = cmp::max(a.ans, (node.val - c.max).abs());
- a.min = cmp::min(a.min, c.min);
- a.max = cmp::max(a.max, c.max);
- }
- }
- a
- }
- }
- pub fn max_ancestor_diff(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
- if let Some(node_ref) = root {
- Self::minMax(Rc::clone(&node_ref)).ans
- } else {
- panic!("bad input");
- }
- }
-}
diff --git a/other/max_distance_closest_person.cpp b/other/max_distance_closest_person.cpp
deleted file mode 100644
index a9203fe..0000000
--- a/other/max_distance_closest_person.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-// 849. Maximize Distance to Closest Person
-#include "leetcode.h"
-
-/*
- * given an array representing a row of 'seats' where 'seats[i] = 1' represents
- * a person sitting in the i'th seat, and 'seats[i] = 0' represents that the
- * i'th seat is empty (0-indexed). there is at least one empty seat, and at
- * least one person sitting. alex wants to sit in the seat such that the
- * distance between him and the closest person to him is maximised. return that
- * maximum distance to the closest person.
- */
-
-class Solution {
-public:
- int maxDistToClosest(vector<int> &seats) {
- int n = seats.size(), empty = 0, ans = 0, idx1 = -1, idx2 = -1;
- for (int i = 0; i < n; i++) {
- if (seats[i] == 1) {
- empty = 0;
- if (idx1 == -1)
- idx1 = i;
- idx2 = i;
- } else {
- empty++;
- ans = max(ans, (empty + 1) / 2);
- }
- }
- ans = max({ans, idx1, n - 1 - idx2});
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> s1 = {1, 0, 0, 0, 1, 0, 1}, s2 = {1, 0, 0, 0}, s3 = {0, 1};
- printf("%d\n", obj.maxDistToClosest(s1)); // expect: 2
- printf("%d\n", obj.maxDistToClosest(s2)); // expect: 3
- printf("%d\n", obj.maxDistToClosest(s3)); // expect: 1
-}
diff --git a/other/max_erasure_value.cpp b/other/max_erasure_value.cpp
deleted file mode 100644
index dd72746..0000000
--- a/other/max_erasure_value.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maximumUniqueSubarray(vector<int> &nums) {
- int ans = 0;
- unordered_set<int> us;
- for (int i = 0, j = 0, win = 0; j < nums.size(); j++) {
- while (us.find(nums[j]) != us.end()) {
- us.erase(nums[i]);
- win -= nums[i];
- i++;
- }
- us.insert(nums[j]);
- win += nums[j];
- ans = max(ans, win);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {5, 2, 1, 2, 5, 2, 1, 2, 5};
- cout << obj.maximumUniqueSubarray(nums);
-}
diff --git a/other/max_ice_cream_bars.cpp b/other/max_ice_cream_bars.cpp
deleted file mode 100644
index e391f87..0000000
--- a/other/max_ice_cream_bars.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maxIceCream(vector<int> &costs, int coins) {
- int k = costs.size();
- vector<int> dp(k + 1, -1);
- sort(costs.begin(), costs.end());
- return dfs(dp, costs, coins, 0, k);
- }
-
-private:
- int dfs(vector<int> &dp, vector<int> &nums, int coins, int i, int k) {
- if (coins <= 0)
- return 0;
- if (i == k - 1) {
- if (nums[i] <= coins)
- return 1;
- else
- return 0;
- }
- if (dp[i] != -1)
- return dp[i];
- int y = 0, n = 0;
- if (nums[i] <= coins)
- y = 1 + dfs(dp, nums, coins - nums[i], i + 1, k);
- n = dfs(dp, nums, coins, i + 1, k);
- return dp[i] = max(y, n);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> costs1 = {1, 3, 2, 4, 1}, costs2 = {10, 6, 8, 7, 7, 8},
- costs3 = {1, 6, 3, 1, 2, 5};
- cout << obj.maxIceCream(costs1, 7) << endl; // expect: 4
- cout << obj.maxIceCream(costs2, 5) << endl; // expect: 0
- cout << obj.maxIceCream(costs3, 20) << endl; // expect: 6
-}
diff --git a/other/max_ice_cream_bars.rs b/other/max_ice_cream_bars.rs
deleted file mode 100644
index 6691a3b..0000000
--- a/other/max_ice_cream_bars.rs
+++ /dev/null
@@ -1,27 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn max_ice_cream(costs: Vec<i32>, coins: i32) -> i32 {
- let (mut bars, mut coins, mut price, mut count) =
- ([0_u32; 100_001], coins, 1, 0);
- costs.into_iter().for_each(|c| bars[c as usize] += 1);
- while coins >= price && price <= 100_000 {
- while bars[price as usize] > 0 && coins >= price {
- bars[price as usize] -= 1;
- coins -= price;
- count += 1;
- }
- price += 1;
- }
- count
- }
-}
-
-fn main() {
- let costs1 = vec![1,3,2,4,1];
- let costs2 = vec![10,6,8,7,7,8];
- let costs3 = vec![1,6,3,1,2,5];
- println!("{}", Solution::max_ice_cream(costs1, 7)); //expect: 4
- println!("{}", Solution::max_ice_cream(costs2, 5)); //expect: 0
- println!("{}", Solution::max_ice_cream(costs3, 20)); //expect: 6
-}
diff --git a/other/max_len_concat_str.cpp b/other/max_len_concat_str.cpp
deleted file mode 100644
index b364d26..0000000
--- a/other/max_len_concat_str.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maxLength(vector<string> &arr) {
- int ans = 0;
- vector<bitset<26>> unique;
- for (auto s : arr) {
- bitset<26> b;
- for (char ch : s)
- b.set(ch - 'a');
- if (b.count() == s.size())
- unique.push_back(b);
- }
- vector<bitset<26>> concat = {bitset<26>()};
- for (auto &u : unique)
- for (int i = concat.size() - 1; i >= 0; i--)
- if ((concat[i] & u).none()) {
- concat.push_back(concat[i] | u);
- ans = max(ans, (concat[i].count() + u.count()));
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<string> arr = {"un", "iq", "ue"};
- cout << obj.maxLength(arr);
-}
diff --git a/other/max_len_concat_str.rs b/other/max_len_concat_str.rs
deleted file mode 100644
index 8ce0c2b..0000000
--- a/other/max_len_concat_str.rs
+++ /dev/null
@@ -1,29 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn max_length(arr: Vec<String>) -> i32 {
- let mut ans: u32 = 0;
- let mut unique: Vec<u32> = Vec::new();
- for s in arr {
- let bin: u32 = s.bytes().map(|c| 1 << (c - b'a')).sum();
- if bin.count_ones() == s.len() as u32 {
- unique.push(bin);
- }
- }
- let mut concat: Vec<u32> = vec![0];
- for u in unique {
- for i in 0..concat.len() {
- if (concat[i] & u).count_ones() == 0 {
- concat.push(concat[i] | u);
- ans = ans.max(concat[i].count_ones() + u.count_ones());
- }
- }
- }
- ans as i32
- }
-}
-
-fn main() {
- let arr = vec!["un".to_string(),"iq".to_string(),"ue".to_string()];
- print!("{}", Solution::max_length(arr));
-}
diff --git a/other/max_length_pair_chain.cpp b/other/max_length_pair_chain.cpp
deleted file mode 100644
index c8ef536..0000000
--- a/other/max_length_pair_chain.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-// 646. Maximum Length of Pair Chain
-#include "leetcode.h"
-
-/*
- * given a n array of 'n' pairs, where 'pairs[i]= [lefti, righti]' and 'left[i]
- * < right[i]'. a pair 'p2 = [c, d]' follows a pair 'p1 = [a, b]' if 'b < c'. a
- * chain of pairs can be formed in this fashion. return the length of the
- * longest chain which can be formed. you do not need to use up all the given
- * intervals. you can select pairs in any order.
- */
-
-class Solution {
- static bool cmp(vector<int> &a, vector<int> &b) { return a[1] < b[1]; }
-
-public:
- int findLongestChain(vvd & pairs) {
- sort(pairs.begin(), pairs.end(), cmp);
- int cnt = 0;
- for (int i = 0, j = 0; j < pairs.size(); j++)
- if (!j || pairs[i][1] < pairs[j][0]) {
- cnt++;
- i = j;
- }
- return cnt;
- }
-};
-
-int main() {
- Solution obj;
- vvd p1 = {{1, 2}, {2, 3}, {3, 4}}, p2 = {{1, 2}, {7, 8}, {4, 5}};
- printf("%d\n", obj.findLongestChain(p1)); // expect: 2
- printf("%d\n", obj.findLongestChain(p2)); // expect: 3
-}
diff --git a/other/max_length_repeated_subarr.cpp b/other/max_length_repeated_subarr.cpp
deleted file mode 100644
index 6e8ef68..0000000
--- a/other/max_length_repeated_subarr.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int findLength(vector<int> &nums1, vector<int> &nums2) {
- int m = nums1.size(), n = nums2.size();
- vvd dp(m + 1, vector<int>(n + 1));
- int ans = 0;
- for (int i = 1; i <= m; ++i) {
- for (int j = 1; j <= n; ++j) {
- if (nums1[i - 1] == nums2[j - 1])
- dp[i][j] = dp[i - 1][j - 1] + 1;
- else
- dp[i][j] = 0;
- ans = max(ans, dp[i][j]);
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums1 = {1, 2, 3, 2, 1}, nums2 = {3, 2, 1, 4, 7};
- cout << obj.findLength(nums1, nums2);
-}
diff --git a/other/max_network_rank.cpp b/other/max_network_rank.cpp
deleted file mode 100644
index 86b0e4c..0000000
--- a/other/max_network_rank.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-// 1615. Maximal Network Rank
-#include "leetcode.h"
-
-/*
- * 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 conncected 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.
- */
-
-class Solution {
-public:
- int maximalNetworkRank(int n, vvd & roads) {
- vector<unordered_set<int>> graph(n);
- for (auto r : roads) {
- graph[r[0]].insert(r[1]);
- graph[r[1]].insert(r[0]);
- }
- int maximal = 0;
- for (int i = 0; i < n; i++) {
- for (int j = i + 1; j < n; j++) {
- int network_rank = graph[i].size();
- if (graph[j].count(i))
- --network_rank;
- maximal = max(maximal, network_rank);
- }
- }
- return maximal;
- }
-};
-
-int main() {
- Solution obj;
- vvd r1 = {{0, 1}, {0, 3}, {1, 2}, {1, 3}},
- r2 = {{0, 1}, {0, 3}, {1, 2}, {1, 3}, {2, 3}, {2, 4}},
- r3 = {{0, 1}, {1, 2}, {2, 3}, {2, 4}, {5, 6}, {5, 7}};
- printf("%d\n", obj.maximalNetworkRank(4, r1)); // expect: 4
- printf("%d\n", obj.maximalNetworkRank(5, r2)); // expect: 5
- printf("%d\n", obj.maximalNetworkRank(8, r3)); // expect: 5
-}
diff --git a/other/max_num_events_attended2.cpp b/other/max_num_events_attended2.cpp
deleted file mode 100644
index 95c1563..0000000
--- a/other/max_num_events_attended2.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-// 1751. Maximum Number of Events That Can Be Attended II
-#include "leetcode.h"
-
-/*
- * given an array of 'events' where 'events[i] = [startdayi, enddayi, valuei]'.
- * the i'th event starts at 'startdayi' and ends at 'enddayi', and if you attent
- * 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
- */
-
-class Solution {
- vvd dp;
- int dfs(vvd & events, int k, int i) {
- if (!k || i >= events.size())
- return 0;
- if (dp[i][k] != -1)
- return dp[i][k];
- auto j = upper_bound(begin(events) + i, end(events), events[i][1],
- [](int t, const vector<int> &v) { return v[0] > t; }) -
- begin(events);
- return dp[i][k] ==
- max(events[i][2] + dfs(events, k - 1, j), dfs(events, k, i + 1));
- }
-
-public:
- int maxValue(vvd & events, int k) {
- dp = vvd(events.size(), vector<int>(k + 1, -1));
- sort(begin(events), end(events));
- return dfs(events, k, 0);
- }
-};
-
-int main() {
- Solution obj;
- vvd e1 = {{1, 2, 4}, {3, 4, 3}, {2, 3, 1}},
- e2 = {{1, 2, 4}, {3, 4, 3}, {2, 3, 10}},
- e3 = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}, {4, 4, 4}};
- printf("%d\n", obj.maxValue(e1, 2)); // expect: 7
- printf("%d\n", obj.maxValue(e2, 2)); // expect: 10
- printf("%d\n", obj.maxValue(e3, 3)); // expect: 9
-}
diff --git a/other/max_num_ksum_pair.cpp b/other/max_num_ksum_pair.cpp
deleted file mode 100644
index 13c6980..0000000
--- a/other/max_num_ksum_pair.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maxOperations(vector<int> &nums, int k) {
- unordered_map<int, int> freq;
- int ans = 0;
- for (int i = 0; i < nums.size(); i++)
- if (freq[k - nums[i]] > 0) {
- ans++;
- freq[k - nums[i]]--;
- } else
- freq[nums[i]]++;
- return ans;
- }
-};
-
-int main() {
- vector<int> nums = {1, 2, 3, 4};
- Solution obj;
- cout << obj.maxOperations(nums, 5);
-}
diff --git a/other/max_num_tasks_assign.cpp b/other/max_num_tasks_assign.cpp
deleted file mode 100644
index 370fdda..0000000
--- a/other/max_num_tasks_assign.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-// 2071. Maximum Number of Tasks You Can Assign
-#include "leetcode.h"
-
-/*
- * you have 'n' tasks and 'm' workers. each task has a strength requirement
- * stored in a 0-indexed integer array 'tasks', with the i'th task requiring
- * 'tasks[i]' strength to complete. the strength of each worker is stored in a
- * 0-indexed array 'workers' with the j'th worker having 'workers[j]' strength.
- * each worker can only be assigned to a single task and must have a strength
- * greather than or equal to the task's strength requirement. additionally, you
- * have 'pills' magic pills that will increase a workers strength by 'strength'.
- * you can decide which workers receive the pills, however, you may only give
- * each worker at most one magical pill. given the 0-indexed integer arrays
- * 'tasks' and 'workers' and the integers 'pills' and 'strength', return the
- * maximum number of tasks that can be completed.
- */
-
-class Solution {
-public:
- int maxTaskAssign(vector<int> &tasks, vector<int> &workers, int pills,
- int strength) {
- int n = tasks.size(), m = workers.size();
- sort(tasks.begin(), tasks.end());
- sort(workers.begin(), workers.end());
- int lo = 0, hi = min(m, n), ans;
- while (lo <= hi) {
- int mid = lo + (hi - lo) / 2;
- int cnt = 0;
- bool flag = true;
- multiset<int> st(workers.begin(), workers.end());
- for (int i = mid - 1; i >= 0; i--) {
- auto it = prev(st.end());
- if (tasks[i] <= *it)
- st.erase(it);
- else {
- auto it = st.lower_bound(tasks[i] - strength);
- if (it != st.end()) {
- cnt++;
- st.erase(it);
- } else {
- flag = false;
- break;
- }
- }
- if (cnt > pills) {
- flag = false;
- break;
- }
- }
- if (flag) {
- ans = mid;
- lo = mid + 1;
- } else {
- hi = mid - 1;
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> t1 = {3, 2, 1}, t2 = {5, 4}, t3 = {10, 15, 30};
- vector<int> w1 = {0, 3, 3}, w2 = {0, 0, 0}, w3 = {0, 10, 10, 10, 10};
- printf("%d\n", obj.maxTaskAssign(t1, w1, 1, 1)); // expect: 3
- printf("%d\n", obj.maxTaskAssign(t2, w2, 1, 5)); // expect: 1
- printf("%d\n", obj.maxTaskAssign(t3, w3, 3, 10)); // expect: 2
-}
diff --git a/other/max_num_vowel_substr.cpp b/other/max_num_vowel_substr.cpp
deleted file mode 100644
index fe24499..0000000
--- a/other/max_num_vowel_substr.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-// 1456. Maximum Number of Vowels in a Substring of Given Length
-#include "leetcode.h"
-
-/*
- * given a string 's' and an integer 'k', return the maximum
- * number of vowel letters in any substring of 's' with length
- * 'k'. vowel letters in english are 'a e i o u'
- */
-
-class Solution {
-public:
- int maxVowels(string s, int k) {
- int count = 0, counting = 0;
- unordered_set<char> bag = {'a', 'e', 'i', 'o', 'u'};
- for (int i = 0, local = 0; i < s.size(); i++) {
- local += bag.count(s[i]);
- if (i - k >= 0)
- local -= bag.count(s[i - k]);
- count = max(count, local);
- }
- return count;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.maxVowels("abciiidef", 3); // expect: 3
- cout << obj.maxVowels("aeiou", 2); // expect: 2
- cout << obj.maxVowels("leetcode", 3); // expect: 2
-}
diff --git a/other/max_performance_team.cpp b/other/max_performance_team.cpp
deleted file mode 100644
index a7e4be8..0000000
--- a/other/max_performance_team.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- const int mod = 1e9 + 7;
- int maxPerformance(int n, vector<int> &speed, vector<int> &efficiency,
- int k) {
- priority_queue<int, vector<int>, greater<int>> pqvg;
- vector<pair<int, int>> vp;
- for (int i = 0; i < n; i++)
- vp.push_back({efficiency[i], speed[i]});
- sort(vp.rbegin(), vp.rend());
- long totSpeed = 0, ans = 0;
- for (int i = 0; i < n; i++) {
- int currEff = vp[i].first, currSpeed = vp[i].second;
- if (pqvg.size() == k) {
- totSpeed -= pqvg.top();
- pqvg.pop();
- }
- pqvg.push(currSpeed);
- totSpeed += currSpeed;
- ans = max(ans, totSpeed * currEff);
- }
- return ans % mod;
- }
-};
-
-int main() {
- Solution obj;
- int n = 6, k = 2;
- vector<int> speed = {2, 10, 3, 1, 5, 8}, efficiency = {5, 4, 3, 9, 7, 2};
- cout << obj.maxPerformance(n, speed, efficiency, k);
-}
diff --git a/other/max_points_from_cards.cpp b/other/max_points_from_cards.cpp
deleted file mode 100644
index 23fc78e..0000000
--- a/other/max_points_from_cards.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maxScore(vector<int> &cardPoints, int k) {
- int ans = 0, n = cardPoints.size();
- for (int i = n - k; i < n; i++)
- ans += cardPoints[i];
- for (int i = 0, s = ans; i < k; i++) {
- s -= cardPoints[n - k + i];
- s += cardPoints[i];
- ans = max(ans, s);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> cardPoints = {1, 2, 3, 4, 5, 6, 1};
- int k = 3;
- cout << obj.maxScore(cardPoints, k);
-}
diff --git a/other/max_points_line.cpp b/other/max_points_line.cpp
deleted file mode 100644
index 3e34be4..0000000
--- a/other/max_points_line.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-#include "leetcode.h"
-
-class Point { // basic coordinate geometry
-public:
- double x, y;
- Point(double x, double y) {
- this->x = x;
- this->y = y;
- }
-};
-
-class Solution {
-public:
- int maxPoints(vvd & points) {
- int n = points.size(), ans = 0;
- if (n <= 2) // 2 or less means points are always collinear
- return n;
- vector<Point> coordinates;
- for (auto &i : points) {
- Point k = Point((double)i[0], (double)i[1]);
- coordinates.push_back(k);
- }
- for (int i = 0; i < n; i++)
- for (int j = 0; j < n; j++) {
- int cnt = 0;
- for (int k = 0; k < n; k++)
- if (i != j && j != k && i != k)
- if (isCollinear(coordinates[i], coordinates[j], coordinates[k]))
- cnt++;
- ans = max(cnt + 2, ans);
- }
- return ans;
- }
-
-private:
- bool isCollinear(Point a, Point b,
- Point c) { // checks if 3 given points lie on same line
- double i = (b.y - a.y) / (b.x - a.x);
- double j = (c.y - b.y) / (c.x - b.x);
- return i == j;
- }
-};
-
-int main() {
- Solution obj;
- vvd points1 = {{1, 1}, {2, 2}, {3, 3}},
- points2 = {{1, 1}, {3, 2}, {5, 3}, {4, 1}, {2, 3}, {1, 4}};
- cout << obj.maxPoints(points1) << endl; // expect: 3
- cout << obj.maxPoints(points2) << endl; // expect: 4
-}
diff --git a/other/max_points_line.rs b/other/max_points_line.rs
deleted file mode 100644
index ee9c03d..0000000
--- a/other/max_points_line.rs
+++ /dev/null
@@ -1,91 +0,0 @@
-use std::collections::HashMap;
-struct Solution;
-
-/*
-* 'Line' is represented as y = m * x + c
-* m & c are rational numbers because of integer coordinates,
-* but in general floating point numbers can be insufficient to
-* guarantee uniqueness as they are still finite precision.
-* so for most real irl cases we use numerator and denominator
-* to represent m & c. decimal precision!!!
-* if m -> +- infinity then use x-int to identify line
-* if m == 0 then use y-int to identify line
-*/
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-enum Line {
- Inf(i32), //x-int
- MC((i32, i32), (i32, i32)), //numerator, denominator tuples for m & c
- Zero(i32) //y-int
-}
-
-impl Solution {
- pub fn max_points(points: Vec<Vec<i32>>) -> i32 {
- if points.len() == 1 {
- return 1;
- }
- //y - y0 = (y1 - y0) / (x1 - x0) * (x - x0)
- //y = dy / dx x + (dx * y0 - dy * x0) / dx
- let mut fm: HashMap<Line, i32> = HashMap::new();
- points.iter().enumerate().flat_map(|(i, pt1)| {
- points.iter().skip(i + 1).map(move |pt2| {
- //swap points arounto make sure dy >= 0 since we are storing
- //fraction numerator & denominator separately.
- let (x0, y0, x1, y1) = if pt2[1] > pt1[1] || (pt2[1] == pt1[1] && pt2[0] > pt2[1]) {
- (pt1[0], pt1[1], pt2[0], pt2[1])
- } else {
- (pt2[0], pt2[1], pt1[0], pt1[1])
- };
- let mut dy = y1 - y0;
- let mut dx = x1 - x0;
- let g = Self::gcd(dy.abs(), dx.abs());
- if g != 0 {
- dy /= g;
- dx /= g;
- }
- if dx != 0 && dy != 0 {
- /*
- * slope is non-zero and finite so consistent line representation
- * can be achieved using numerator & denominator representation
- * because we have already preprocessed dy & dx for sign consistency
- * and removed gcd from dy & dx
- */
- Line::MC((dy, dx), (dx * y0 - dy * x0, dx))
- } else if dx == 0 {
- //x-int is enough to identify common lines
- Line::Inf(x0)
- } else {
- //y-int is enough to identify common lines
- Line::Zero(y0)
- }
- })
- }).for_each(|k| {
- *fm.entry(k).or_insert(0) += 1;
- });
- let n = fm.values().max().cloned().unwrap();
- /*
- * if 'm' points lie on a line & all points have been processed pairwise
- * then n = m * (m - 1) / 2 pairs of points would have matched to same
- * line m^2 - m - 2 * n = 0 => m = (1 + sqrt(8 * n + 1)) / 2
- */
- (1 + (8f64 * n as f64 + 1f64).sqrt() as i32) / 2
- }
- fn gcd(a: i32, b: i32) -> i32 {
- if a == 0 || b == 0 {
- return 0;
- }
- let (mut a, mut b) = (a, b);
- while b > 0 {
- let tmp = a % b;
- a = b;
- b = tmp;
- }
- a
- }
-}
-
-fn main() {
- let points1 = vec![vec![1,1],vec![2,2],vec![3,3]];
- let points2 = vec![vec![1,1],vec![3,2],vec![5,3],vec![4,1],vec![2,3],vec![1,4]];
- println!("{}", Solution::max_points(points1)); //expect: 3
- println!("{}", Solution::max_points(points2)); //expect: 3
-}
diff --git a/other/max_product_3num.cpp b/other/max_product_3num.cpp
deleted file mode 100644
index 1886bdb..0000000
--- a/other/max_product_3num.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 628. Maximum Product of Three Numbers
-#include "leetcode.h"
-
-/*
- * given an integer array 'nums', find three numbers whose product is maximum
- * and return the maximum product
- */
-
-class Solution {
-public:
- int maximumProduct(vector<int> &nums) {
- int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN;
- int min1 = INT_MAX, min2 = INT_MAX, min3 = INT_MAX;
- for (int i = 0; i < nums.size(); i++) {
- if (nums[i] <= min1) {
- min2 = min1;
- min1 = nums[i];
- } else if (nums[i] <= min2)
- min2 = nums[i];
- if (nums[i] >= max1) {
- max3 = max2;
- max2 = max1;
- max1 = nums[i];
- } else if (nums[i] >= max2) {
- max3 = max2;
- max2 = nums[i];
- } else if (nums[i] >= max3)
- max3 = nums[i];
- }
- return max(min1 * min2 * max1, max1 * max2 * max3);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 2, 3}, n2 = {1, 2, 3, 4}, n3 = {-1, -2, -3};
- printf("%d\n", obj.maximumProduct(n1)); // expect: 6
- printf("%d\n", obj.maximumProduct(n2)); // expect: 24
- printf("%d\n", obj.maximumProduct(n3)); // expect: -6
-}
diff --git a/other/max_product_split_bt.cpp b/other/max_product_split_bt.cpp
deleted file mode 100644
index 71fc9a4..0000000
--- a/other/max_product_split_bt.cpp
+++ /dev/null
@@ -1,19 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maxProduct(TreeNode *root) {
- tot = solve(root), solve(root);
- return ans % (1e9 + 7);
- }
-
-private:
- long ans = 0, tot = 0, sub;
- int solve(TreeNode *root) {
- if (!root)
- return 0;
- sub = root->val + solve(root->left) + solve(root->right);
- ans = max(ans, sub * (tot - sub));
- return sub;
- }
-};
diff --git a/other/max_product_split_bt.rs b/other/max_product_split_bt.rs
deleted file mode 100644
index 6aec321..0000000
--- a/other/max_product_split_bt.rs
+++ /dev/null
@@ -1,43 +0,0 @@
-#[derive(Debug, PartialEq, Eq)]
-pub struct TreeNode {
- pub val: i32,
- pub left: Option<Rc<RefCell<TreeNode>>>,
- pub right: Option<Rc<RefCell<TreeNode>>>,
-}
-
-impl TreeNode {
- #[inline]
- pub fn new(val: i32) -> Self {
- TreeNode {
- val,
- left: None,
- right: None,
- }
- }
-}
-
-use std::cell::RefCell;
-use std::rc::Rc;
-const MOD: i64 = 1_000_000_007;
-impl Solution {
- pub fn max_product(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
- let mut sums = Vec::new();
- Self::dfs(&root, &mut sums);
- ((0..sums.len() - 1)
- .map(|i| sums[i] * (sums[sums.len() - 1] - sums[i]))
- .max()
- .unwrap()
- % MOD) as i32
- }
- fn dfs(node: &Option<Rc<RefCell<TreeNode>>>, sums: &mut Vec<i64>) -> i64 {
- if let Some(n) = node {
- let sum = n.borrow().val as i64
- + Self::dfs(&n.borrow().left, sums)
- + Self::dfs(&n.borrow().right, sums);
- sums.push(sum);
- sum
- } else {
- 0
- }
- }
-}
diff --git a/other/max_product_word_len.cpp b/other/max_product_word_len.cpp
deleted file mode 100644
index e119ea1..0000000
--- a/other/max_product_word_len.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maxProduct(vector<string> &words) {
- int n = words.size(), ans = 0;
- vector<bitset<26>> chars(n);
- for (int i = 0; i < n; i++) {
- for (auto &ch : words[i])
- chars[i][ch - 'a'] = 1;
- for (int j = 0; j < i; j++)
- if (!helper(chars[i], chars[j]))
- ans = max(ans, words[i].size() * words[j].size());
- }
- return ans;
- }
-
-private:
- bool helper(bitset<26> &a, bitset<26> &b) {
- for (int i = 0; i < 26; i++)
- if (a[i] && b[i])
- return true;
- return false;
- }
-};
-
-int main() {
- Solution obj;
- vector<string> words = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef"};
- cout << obj.maxProduct(words);
-}
diff --git a/other/max_profit_job.cpp b/other/max_profit_job.cpp
deleted file mode 100644
index 811874b..0000000
--- a/other/max_profit_job.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int jobScheduling(vector<int> &startTime, vector<int> &endTime,
- vector<int> &profit) {
- int n = startTime.size();
- vvd jobs;
- for (int i = 0; i < n; ++i)
- jobs.push_back({endTime[i], startTime[i], profit[i]});
- sort(jobs.begin(), jobs.end());
- map<int, int> dp = {{0, 0}};
- for (auto &j : jobs) {
- int curr = prev(dp.upper_bound(j[1]))->second + j[2];
- if (curr > dp.rbegin()->second)
- dp[j[0]] = curr;
- }
- return dp.rbegin()->second;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> startTime = {1, 2, 3, 3};
- vector<int> endTime = {3, 4, 5, 6};
- vector<int> profit = {50, 10, 40, 70};
- cout << obj.jobScheduling(startTime, endTime, profit); // 120
-}
diff --git a/other/max_profit_job.rs b/other/max_profit_job.rs
deleted file mode 100644
index fe1fafe..0000000
--- a/other/max_profit_job.rs
+++ /dev/null
@@ -1,30 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn job_scheduling(start_time: Vec<i32>, end_time: Vec<i32>, profit: Vec<i32>) -> i32 {
- let mut jobs: Vec<usize> = (0..profit.len()).collect();
- jobs.sort_unstable_by_key(|&i| end_time[i]);
- let mut dp: Vec<(i32, i32)> = vec![(0, i32::MIN)];
- for &i in jobs.iter() {
- let left = match dp.binary_search_by_key(&start_time[i], |&(_, t)| t) {
- Ok(j) => j,
- Err(j) => j - 1
- };
- if dp[left].0 + profit[i] > dp.last().unwrap().0 {
- if end_time[i] == dp.last().unwrap().1 {
- dp.last_mut().unwrap().0 = dp[left].0 + profit[i];
- } else {
- dp.push((dp[left].0 + profit[i], end_time[i]));
- }
- }
- }
- dp.last().unwrap().0
- }
-}
-
-fn main() {
- let start_time = vec![1,2,3,3];
- let end_time = vec![3,4,5,6];
- let profit = vec![50,10,40,70];
- print!("{}", Solution::job_scheduling(start_time, end_time, profit)); //120
-}
diff --git a/other/max_running_time_n_computer.cpp b/other/max_running_time_n_computer.cpp
deleted file mode 100644
index e5a10b5..0000000
--- a/other/max_running_time_n_computer.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-// 2141. Maximum Running Time of N Computers
-#include "leetcode.h"
-
-/*
- * you have 'n' computers. you are given the integer 'n' and a 0-indexed integer
- * array 'batteries' where the i'th battery can run a computer for
- * 'batteries[i]' minutes. you are interested in running all 'n' computers
- * simultaneously using the given batteries. initially, you can insert at most
- * one battery into each computer. after that and at any integer time moment,
- * you can remove a battery from a computer and insert another battery any
- * number of times. the inserted battery can be a totally new battery or a
- * battery forom another computer. you may assume that the removing and
- * inserting process takes no time. note that the batteries canot be recharged.
- * return the maximum number of minutes you can run all the 'n' computers
- * simultaneously.
- */
-
-class Solution {
-public:
- long long maxRunTime(int n, vector<int> &batteries) {
- sort(batteries.begin(), batteries.end());
- long long sum = accumulate(batteries.begin(), batteries.end(), 0L);
- int k = 0, i = batteries.size();
- while (batteries[i - 1 - k] > sum / (n - k))
- sum -= batteries[i - 1 - k++];
- return sum / (n - k);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> b1 = {3, 3, 3}, b2 = {1, 1, 1, 1};
- printf("%lld\n", obj.maxRunTime(2, b1)); // expect: 4
- printf("%lld\n", obj.maxRunTime(2, b2)); // expect: 2
-}
diff --git a/other/max_score_good_subarr.cpp b/other/max_score_good_subarr.cpp
deleted file mode 100644
index 3c7bc89..0000000
--- a/other/max_score_good_subarr.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-// 1793. Maximum Score of a Good Subarray
-#include "leetcode.h"
-
-/*
- * 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.
- */
-
-class Solution {
-public:
- int maximumScore(vector<int> &nums, int k) {
- nums.push_back(0);
- stack<int> st;
- int n = nums.size(), ans = 0;
- for (int i = 0; i < n; i++) {
- while (!st.empty() && nums[st.top()] >= nums[i]) {
- int height = nums[st.top()];
- st.pop();
- int left = st.empty() ? -1 : st.top();
- if (k < i && k > left)
- ans = max(ans, height * (i - left - 1));
- }
- st.push(i);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 4, 3, 7, 4, 5}, n2 = {5, 5, 4, 5, 4, 1, 1, 1};
- printf("%d\n", obj.maximumScore(n1, 3)); // expect: 15
- printf("%d\n", obj.maximumScore(n2, 0)); // expect: 20
-}
diff --git a/other/max_score_mult_opp.cpp b/other/max_score_mult_opp.cpp
deleted file mode 100644
index 7758a29..0000000
--- a/other/max_score_mult_opp.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maximumScore(vector<int> &nums, vector<int> &multipliers) {
- n = nums.size();
- m = multipliers.size();
- memset(memo, -1, sizeof(memo));
- return dp(0, 0, nums, multipliers);
- }
-
-private:
- int m, n, memo[1000][1000];
- int dp(int l, int i, vector<int> &nums, vector<int> &multipliers) {
- if (i == m)
- return 0;
- if (memo[l][i] != -1)
- return memo[l][i];
- int pickLeft =
- dp(l + 1, i + 1, nums, multipliers) + nums[l] * multipliers[i];
- int pickRight = dp(l, i + 1, nums, multipliers) +
- nums[n - (i - l) - 1] * multipliers[i];
- return memo[l][i] = max(pickLeft, pickRight);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {1, 2, 3}, multipliers = {3, 2, 1};
- cout << obj.maximumScore(nums, multipliers);
-}
diff --git a/other/max_score_n_operations.cpp b/other/max_score_n_operations.cpp
deleted file mode 100644
index a2dc2b9..0000000
--- a/other/max_score_n_operations.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-// 1799. Maximize Score After N Operations
-#include "leetcode.h"
-
-/*
- * given 'nums', an array of positive integers of size '2 * n'. you must perform
- * 'n' operations on this array. in the i'th operation (1-index), 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.
- */
-
-class Solution {
-public:
- int maxScore(vector<int> nums) {
- m = nums.size();
- n = m / 2;
- return dp(nums, 1, 0);
- }
-
-private:
- int gcd_memo[14][14] = {};
- int memo[1 << 4] = {};
- int m, n;
- int dp(vector<int> &nums, int op, int mask) {
- if (op > n)
- return 0;
- if (memo[mask])
- return memo[mask];
- for (int i = 0; i < m; ++i) {
- if ((mask >> i) & 0x1)
- continue;
- for (int j = i + 1; j < m; ++j) {
- if ((mask >> j) & 0x1)
- continue;
- int new_mask = (0x1 << i) | (0x1 << j) | mask;
- int score = op * gcd(nums, i, j) + dp(nums, op + 1, new_mask);
- memo[mask] = max(memo[mask], score);
- }
- }
- return memo[mask];
- }
- int gcd(vector<int> &nums, int i, int j) {
- if (gcd_memo[i][j])
- return gcd_memo[i][j];
- return gcd_memo[i][j] = __gcd(nums[i], nums[j]);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 2};
- vector<int> n2 = {3, 4, 6, 8};
- vector<int> n3 = {1, 2, 3, 4, 5, 6};
- printf("%d\n", obj.maxScore(n1)); // expect: 1
- printf("%d\n", obj.maxScore(n2)); // expect: 11
- printf("%d\n", obj.maxScore(n3)); // expect: 14
-}
diff --git a/other/max_score_node_sequence.cpp b/other/max_score_node_sequence.cpp
deleted file mode 100644
index b4df5d5..0000000
--- a/other/max_score_node_sequence.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maximumScore(vector<int> &scores, vector<vector<int>> &edges) {
- const int n = scores.size();
- vector<vector<int>> adj(n);
- for (const vector<int> &edge : edges) {
- adj[edge[0]].push_back(edge[1]);
- adj[edge[1]].push_back(edge[0]);
- }
- for (vector<int> &a : adj) {
- priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pqpvg;
- for (int v : a) {
- int score = scores[v];
- if (pqpvg.size() < 3 || pqpvg.top().first < score) {
- pqpvg.push({score, v});
- if (pqpvg.size() > 3)
- pqpvg.pop();
- }
- }
- a.resize(pqpvg.size());
- for (int i = a.size() - 1; i >= 0; --i) {
- a[i] = pqpvg.top().second;
- pqpvg.pop();
- }
- }
- int ans = -1;
- for (const vector<int> &edge : edges) {
- int u = edge[0], v = edge[1], base = scores[u] + scores[v];
- for (int x : adj[u]) {
- if (x == v)
- continue;
- for (int y : adj[v]) {
- if (y == u || x == y)
- continue;
- ans = max(ans, base + scores[x] + scores[y]);
- }
- }
- }
- return ans;
- }
-};
diff --git a/other/max_subarray.cpp b/other/max_subarray.cpp
deleted file mode 100644
index 7356925..0000000
--- a/other/max_subarray.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maxSubArray(vector<int> &nums) {
- return helper(nums, 0, nums.size() - 1);
- }
-
-private:
- int helper(vector<int> &nums, int l, int r) {
- if (l > r)
- return INT_MIN;
- int m = l + (r - l) / 2, mL = 0, mR = 0;
- int lMax = helper(nums, l, m - 1);
- int rMax = helper(nums, m + 1, r);
- for (int i = m - 1, sum = 0; i >= l; i--) {
- sum += nums[i];
- mL = max(sum, mL);
- }
- for (int i = m + 1, sum = 0; i <= r; i++) {
- sum += nums[i];
- mR = max(sum, mR);
- }
- return max(max(lMax, rMax), mL + mR + nums[m]);
- }
-};
-
-int main() {
- vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
- Solution obj;
- cout << obj.maxSubArray(nums);
-}
diff --git a/other/max_subseq_score.cpp b/other/max_subseq_score.cpp
deleted file mode 100644
index a739d77..0000000
--- a/other/max_subseq_score.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-// 2542. Maximum Subsequence Score
-#include "leetcode.h"
-
-/*
- * given two 0-indexed integer arrays 'num1' and 'nums2' of equal length 'n' and
- * a positive integer 'k'. you must choose a subsequence of indices from 'nums1'
- * of length 'k'. for chosen indices 'i0, i1, ..., ik-1', your score is defined
- * as
- * - the sum of the selected elements from 'nums1' multiplied with the minimum
- * of the selected elements from 'nums2'
- * - it can defined simply as '(num1[i0] + nums1[i1] + ... + nums1[ik - 1]) *
- * min(nums2[i0], nums2[i1], ..., nums2[ik - 1])' return the maximum possible
- * score. a subseqnce of indices of an array is a set that can be derived from
- * the set '{0, 1, ..., n - 1}' by deleting no elements
- */
-
-class Solution {
-public:
- long long maxScore(vector<int> &nums1, vector<int> &nums2, int k) {
- int n = nums1.size();
- vector<pair<int, int>> ess(n);
- for (int i = 0; i < n; ++i)
- ess[i] = {nums2[i], nums1[i]};
- sort(rbegin(ess), rend(ess));
- long long sum_s = 0, ans = 0;
- priority_queue<int, vector<int>, greater<int>> pq;
- for (auto &[e, s] : ess) {
- pq.emplace(s);
- sum_s += s;
- if (pq.size() > k) {
- sum_s -= pq.top();
- pq.pop();
- }
- if (pq.size() == k)
- ans = max(ans, sum_s * e);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n11 = {1, 3, 3, 2}, n21 = {2, 1, 3, 4};
- vector<int> n12 = {4, 2, 3, 1, 1}, n22 = {7, 5, 10, 9, 6};
- printf("%lld\n", obj.maxScore(n11, n21, 3)); // expect: 12
- printf("%lld\n", obj.maxScore(n12, n22, 1)); // expect: 30
-}
diff --git a/other/max_sum_3_noverlap_subarr.cpp b/other/max_sum_3_noverlap_subarr.cpp
deleted file mode 100644
index c326ad3..0000000
--- a/other/max_sum_3_noverlap_subarr.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-// 689. Maximum Sum of 3 Non-Overlapping Subarrays
-#include "leetcode.h"
-
-/*
- * given an integer array 'nums' and an integer 'k', find three non-overlapping
- * subarrays of length 'k' with maximum sum and return them. return the result
- * as a list of indices representing the starting position of each interval
- * (0-indexed). if there are multiple answers, return the lexicographcially
- * smallest one
- */
-
-class Solution {
-public:
- vector<int> maxSumOfThreeSubarrays(vector<int> &nums, int k) {
- int n = nums.size(), max_sum = 0;
- vector<int> sum = {0}, left(n, 0), right(n, n - k), ans(3, 0);
- for (int i : nums)
- sum.push_back(sum.back() + i);
- for (int i = k, tot = sum[k] - sum[0]; i < n; i++) {
- if (sum[i + 1] - sum[i + 1 - k] > tot) {
- left[i] = i + 1 - k;
- tot = sum[i + 1] - sum[i + 1 - k];
- } else
- left[i] = left[i - 1];
- }
- for (int i = n - k - 1, tot = sum[n] - sum[n - k]; i >= 0; i--) {
- if (sum[i + k] - sum[i] >= tot) {
- right[i] = i;
- tot = sum[i + k] - sum[i];
- } else
- right[i] = right[i + 1];
- }
- for (int i = k; i <= n - 2 * k; i++) {
- int l = left[i - 1], r = right[i + k];
- int tot =
- (sum[i + k] - sum[i]) + (sum[l + k] - sum[l]) + (sum[r + k] - sum[r]);
- if (tot > max_sum) {
- max_sum = tot;
- ans = {l, i, r};
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 2, 1, 2, 6, 7, 5, 1}, n2 = {1, 2, 1, 2, 1, 2, 1, 2, 1};
- vector<int> msots1 = obj.maxSumOfThreeSubarrays(n1, 2);
- vector<int> msots2 = obj.maxSumOfThreeSubarrays(n2, 2);
- for (auto i : msots1)
- printf("%d ", i); // expect: 0 3 5
- printf("\n");
- for (auto i : msots2)
- printf("%d ", i); // expect: 0 2 4
- printf("\n");
-}
diff --git a/other/max_sum_binary_tree.cpp b/other/max_sum_binary_tree.cpp
deleted file mode 100644
index 64d1d20..0000000
--- a/other/max_sum_binary_tree.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-// 1161. Maximum Level Sum of a Binary Tree
-#include "leetcode.h"
-
-/*
- * given the 'root' of a binary tree, the level of its root is 1, the level of
- * its children is 2, and so on. return the smallest level 'x' such that the sum
- * of all the values of nodes at level 'x' is maximal.
- */
-
-class Solution {
- vector<int> sums;
- void dfs(TreeNode *root, size_t level) {
- if (root) {
- sums.resize(max(sums.size(), level));
- sums[level - 1] += root->val;
- dfs(root->left, level + 1);
- dfs(root->right, level + 1);
- }
- }
-
-public:
- int maxLevelSum(TreeNode *root) {
- dfs(root, 1);
- return distance(begin(sums), max_element(begin(sums), end(sums))) + 1;
- }
-};
diff --git a/other/max_sum_circular_subarr.cpp b/other/max_sum_circular_subarr.cpp
deleted file mode 100644
index a86eafa..0000000
--- a/other/max_sum_circular_subarr.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-// 918. Maximum Sum Circular Subarray
-#include "leetcode.h"
-
-/*
- * given: circular int array 'nums' of length 'n', return the max possible
- * sum of non-empty subarray of 'nums'
- *
- * a circular array means the end of the array connects to the beginning.
- * formally, the previous element of 'nums[i]' is 'nums[(i -/+ 1) % n]'
- *
- * a subarray may only include each element of the fixed buffer 'nums' at
- * most once. formally, for a subarray 'nums[i], nums[i + 1], ..., nums[j]'
- * there does not exist i <= k1, k2 <= j with k1 % n == k2 % n
- */
-
-class Solution {
-public:
- int maxSubarraySumCircular(vector<int> &nums) {
- int sum = 0;
- for (int i : nums)
- sum += i;
- int s1 = helper(nums.begin(), nums.end());
- for (int &i : nums)
- i *= -1;
- int s2 = sum + helper(nums.begin(), nums.end() - 1);
- int s3 = sum + helper(nums.begin() + 1, nums.end());
- return max(s1, max(s2, s3));
- }
-
-private:
- int helper(vector<int>::iterator p, vector<int>::iterator q) {
- int res = INT_MIN, n = 0;
- for (auto i = p; i != q; i++) {
- n += *i;
- res = max(res, n);
- if (n < 0)
- n = 0;
- }
- return res;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums1 = {-2}, nums2 = {5, -3, 5}, nums3 = {-3, -2, -3};
- cout << obj.maxSubarraySumCircular(nums1) << endl; // expect: 3
- cout << obj.maxSubarraySumCircular(nums2) << endl; // expect: 10
- cout << obj.maxSubarraySumCircular(nums3) << endl; // expect: -2
-}
diff --git a/other/max_sum_rectangle.cpp b/other/max_sum_rectangle.cpp
deleted file mode 100644
index 9b252e1..0000000
--- a/other/max_sum_rectangle.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maxSumSubmatrix(vector<vector<int>> &matrix, int k) {
- int ans = INT_MIN, rows = matrix.size(), cols = matrix[0].size();
- for (int l = 0; l < cols; ++l) {
- vector<int> sums(rows);
- for (int r = l; r < cols; ++r) {
- int pMin = 0, pMax = INT_MIN;
- for (int i = 0; i < rows; ++i) {
- sums[i] += matrix[i][r];
- pMin = max(pMin + sums[i], sums[i]);
- pMax = max(pMax, pMin);
- }
- if (pMax <= k) {
- ans = max(ans, pMax);
- continue;
- }
- set<int> s = {0};
- int runSum = 0;
- for (int sum : sums) {
- runSum += sum;
- auto it = s.lower_bound(runSum - k);
- if (it != end(s))
- ans = max(ans, runSum - *it);
- s.insert(runSum);
- }
- }
- }
- return ans;
- }
-};
diff --git a/other/max_total_importance_road.cpp b/other/max_total_importance_road.cpp
deleted file mode 100644
index 82380ab..0000000
--- a/other/max_total_importance_road.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-// 2285. Maximum Total Importance of Roads
-#include "leetcode.h"
-
-/*
- * given an integer 'n' denoting the number of cities in a country. the cities
- * are numbered from 0 to 'n - 1'. you are also given a 2d integer array 'roads'
- * where 'roads{i} = {ai, bi}', where each value can only be used once. the
- * importance of a road is then defined as the sum of the values of the two
- * cities it connects. return the maximum total importance of all roads possible
- * after assigning the values optimally.
- */
-
-class Solution {
-public:
- long long maximumImportance(int n, vector<vector<int>> &roads) {
- long long cnt[50001] = {}, ans = 0;
- for (auto &i : roads) {
- ++cnt[i[0]];
- ++cnt[i[1]];
- }
- sort(begin(cnt), begin(cnt) + n);
- for (int i = 0; i < n; i++)
- ans += cnt[i] * (i + 1);
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd r1 = {{0, 1}, {1, 2}, {2, 3}, {0, 2}, {1, 3}, {2, 4}};
- vvd r2 = {{0, 3}, {2, 4}, {1, 3}};
- printf("%lld\n", obj.maximumImportance(5, r1)); // expect: 43
- printf("%lld\n", obj.maximumImportance(5, r2)); // expect: 20
-}
diff --git a/other/max_tranfer_requests.cpp b/other/max_tranfer_requests.cpp
deleted file mode 100644
index 2f0e499..0000000
--- a/other/max_tranfer_requests.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-// 1601. Maximum Number of Achievable Transfer Requests
-#include "leetcode.h"
-
-/*
- * we have 'n' buildings numbered from 0 to 'n - 1'. each building has a number
- * of employees. it's transfer season and some employees want to change the
- * building they reside in. you are an an array 'requests' where 'requests[i] =
- * [fromi, toi]' represents an employee's request to transfer from building
- * 'fromi' to building 'toi'. all buildings are full. so a list of requests is
- * achievable only if for each building, the net change in emplyee transfers is
- * zero. this means the number of emplyees leaving is equal to the number of
- * employees moving in. return the maximum number of achievable requests
- */
-
-class Solution {
-public:
- int maximumRequests(int n, vvd & requests) {
- int ans = 0, k = requests.size(), r = 1 << k, x;
- for (int i = 1; i < r; i++) {
- int *a = (int *)calloc(n, sizeof);
- int curr = 0;
- for (int j = 0; j < k; j++) {
- if (int(i >> j) & 1) {
- a[requests[j][0]]++;
- a[requests[j][1]]--;
- curr++;
- }
- }
- for (x = 0; x < n; x++)
- if (a[x])
- break;
- if (x == n)
- ans = max(ans, curr);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd r1 = {{0, 1}, {1, 0}, {0, 1}, {1, 2}, {2, 0}, {3, 4}};
- vvd r2 = {{0, 0}, {1, 2}, {2, 1}}, r3 = {{0, 3}, {3, 1}, {1, 2}, {2, 0}};
- printf("%d\n", obj.maximumRequests(5, r1)); // expect: 5
- printf("%d\n", obj.maximumRequests(3, r2)); // expect: 3
- printf("%d\n", obj.maximumRequests(4, r3)); // expect: 4
-}
diff --git a/other/max_twin_sum_list.cpp b/other/max_twin_sum_list.cpp
deleted file mode 100644
index dd635e1..0000000
--- a/other/max_twin_sum_list.cpp
+++ /dev/null
@@ -1,41 +0,0 @@
-// 2130. Maximum Twin Sum of a Linked List
-#include "leetcode.h"
-
-/*
- * in a linked-list of size 'n', where 'n' is even, the i'th node (0-indexed) of
- * the linked list is known as the twin of the 'n - 1 - i' node, if 0 <= i <= (n
- * / 2) - 1. for example, if 'n = 4', then node 0 is the twin of node 3, and
- * node 1 is the twin node of node 2. these are the only nodes with twins for 'n
- * = 4'. the twin sum is defined as the sum of a node and its twin. given the
- * 'head' of a linked list with even length, return the maximum twin sum of the
- * linked list.
- *
- */
-
-class Solution {
-public:
- int pairSum(ListNode *head) {
- int ans = 0;
- auto slow = head, fast = head;
- while (fast != nullptr && fast->next != nullptr) {
- fast = fast->next->next;
- slow = slow->next;
- }
- slow = reverseList(slow);
- while (slow != nullptr) {
- ans = max(ans, slow->val + head->val);
- slow = slow->next;
- head = head->next;
- }
- return ans;
- }
-
-private:
- ListNode *reverseList(ListNode *curr, ListNode *prev = nullptr) {
- while (curr != nullptr) {
- swap(curr->next, prev);
- swap(prev != nullptr ? prev->next : prev, curr);
- }
- return prev;
- }
-};
diff --git a/other/max_units_truck.cpp b/other/max_units_truck.cpp
deleted file mode 100644
index f95e777..0000000
--- a/other/max_units_truck.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maximumUnits(vector<vector<int>> &boxTypes, int truckSize) {
- sort(boxTypes.begin(), boxTypes.end(), cmp);
- int ans = 0;
- for (auto box : boxTypes) {
- int n = min(box[0], truckSize);
- ans += (n * box[1]);
- truckSize -= n;
- if (!truckSize)
- break;
- }
- return ans;
- }
-
-private:
- static bool cmp(vector<int> &a, vector<int> &b) { return a[1] > b[1]; }
-};
diff --git a/other/max_val_k_coin_pile.cpp b/other/max_val_k_coin_pile.cpp
deleted file mode 100644
index 6452a7b..0000000
--- a/other/max_val_k_coin_pile.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-// 2218. Maximum Value of K Coins From Piles
-#include "leetcode.h"
-
-/*
- * there are 'n' piles of coins on a table. each pile consists of a positive
- * number of coins of assorted denominations. in one move you can choose any
- * coin on top of a pile remove it and add it to your wallet. given a list of
- * 'piles' where 'piles[i]' is a list of integers denoting the composition of
- * the i'th pile from top to bottom, and a positive integer 'k', return the
- * maximum total values of coins you can have in your wallet if you choose
- * exactly 'k' coins optimally.
- */
-
-class Solution {
-public:
- int maxValueOfCoins(vvd & piles, int k) {
- int n = piles.size(), m[1001][2001] = {};
- memset(m, -1, sizeof(m));
- function<int(int, int)> dp = [&](int i, int j) {
- if (m[i][j] != -1)
- return m[i][j];
- if (i == n)
- return 0;
- int ans = dp(i + 1, j), sum = 0;
- for (int k = 1; k <= j && k <= piles[i].size(); ++k) {
- sum += piles[i][k - 1];
- ans = max(ans, dp(i + 1, j - k) + sum);
- }
- return m[i][j] = ans;
- };
- return dp(0, k);
- }
-};
-
-int main() {
- Solution obj;
- vvd
- p1 = {{1, 100, 3}, {7, 8, 9}},
- p2 = {{100}, {100}, {100}, {100}, {100}, {100}, {1, 1, 1, 1, 1, 1, 700}};
- printf("%d\n", obj.maxValueOfCoins(p1, 2)); // expect: 101
- printf("%d\n", obj.maxValueOfCoins(p2, 7)); // expect: 706
-}
diff --git a/other/max_value_give_idx.cpp b/other/max_value_give_idx.cpp
deleted file mode 100644
index ee6c25f..0000000
--- a/other/max_value_give_idx.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-// 1802. Maximum Value at a Given Index in a Bounded Array
-#include "leetcode.h"
-
-/*
- * given three positive integers: 'n, index, and max_sum'. you want to construct
- * an array 'nums' (0-indexed) that satisfies the following conditions:
- * - nums.length == n
- * - nums[i] is a positive integer where 0 <= i < n
- * - abs(nums[i] - nums[i + 1]) <= 1 where 0 <= i < n - 1
- * - the sum of all the elements of 'nums' does not exceed 'max_sum'
- * - nums[index] is maximised
- * return 'nums[index]' of the constructed array. note that 'abs(x)' equals 'x'
- * if 'x >= 0' and '-x' otherwise
- */
-
-class Solution {
- bool check(int n, int i, int max_sum, int m) {
- for (int d = 1; max_sum >= 0 && d < m && i + d < n; ++d)
- max_sum -= m - d;
- for (int d = 1; max_sum >= 0 && d < m && i - d >= 0; ++d)
- max_sum -= m - d;
- return max_sum >= 0;
- }
-
-public:
- int maxValue(int n, int index, int max_sum) {
- int left = 0, right = max_sum;
- while (left < right) {
- int mid = (left + right + 1) / 2;
- if (check(n, index, max_sum - n - mid, mid))
- left = mid;
- else
- right = mid - 1;
- }
- return left + 1;
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.maxValue(4, 2, 6)); // expect: 2
- printf("%d\n", obj.maxValue(6, 1, 10)); // expect: 3
-}
diff --git a/other/max_width_binary_tree.cpp b/other/max_width_binary_tree.cpp
deleted file mode 100644
index 3f69177..0000000
--- a/other/max_width_binary_tree.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 662. Maximum Width of Binary Tree
-#include "leetcode.h"
-
-/*
- * given 'root' of binary tree, return the maximum width of the
- * given tree. the maximum width of a tree is the maximum width
- * among all levels. the width of one level is defined as the
- * length between the end-nodes (the leftmost and rightmost non
- * null nodes), where the null nodes between the end-nodes that
- * would be present in a complete binary tree extending down to
- * that level are also counted into the length calculation.
- */
-
-class Solution {
-public:
- int widthOfBinaryTree(TreeNode *root) {
- if (root == NULL)
- return 0;
- int max_width = 1;
- queue<pair<TreeNode *, int>> qp;
- qp.push({root, 0});
- while (!qp.empty()) {
- int level_size = qp.size();
- int start_idx = qp.front().second;
- int end_idx = qp.back().second;
- max_width = max(max_width, end_idx - start_idx + 1);
- for (int i = 0; i < level_size; ++i) {
- auto node_idx_pair = qp.front();
- TreeNode *node = node_idx_pair.first;
- int node_idx = node_idx_pair.second - start_idx;
- qp.pop();
- if (node->left != nullptr)
- qp.push({node->left, 2LL * node_idx + 1});
- if (node->right != nullptr)
- qp.push({node->right, 2LL * node_idx + 2});
- }
- }
- return max_width;
- }
-};
diff --git a/other/maximise_confusion_exam.cpp b/other/maximise_confusion_exam.cpp
deleted file mode 100644
index 0de5eaf..0000000
--- a/other/maximise_confusion_exam.cpp
+++ /dev/null
@@ -1,41 +0,0 @@
-// 2024. Maximize the Confusion of an Exam
-#include "leetcode.h"
-
-/*
- * a teacher is writing a test with 'n' true/false questions. with 'T' denoting
- * true, and 'F' denoting false. he wants to confuse the students by maximising
- * the number of consecutive questions with the same answer (multiple trues or
- * multiple falses in a row) you are given a string 'answer_key', where
- * 'answer_key[i]' is the original answer to the i'th question. in addition, you
- * are given an integer 'k', the following operation:
- * - change the answer key for any question to 'T' or 'F'
- * return the maximum number of consecutive 'T's or 'F's in the answer key after
- * performing the operation at most 'k' times
- */
-
-class Solution {
-public:
- int maxConsecutiveAnswers(string answer_key, int k) {
- int n = answer_key.size(), start = 0, end = 0, t = 0, f = 0, ans = 0;
- while (end < n) {
- t += (answer_key[end] == 'T');
- f += (answer_key[end] == 'F');
- while (t > k && f > k) {
- if (answer_key[start] == 'T')
- t--;
- else
- f--;
- }
- ans = max(ans, end - start + 1);
- end++;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.maxConsecutiveAnswers("TTFF", 2)); // expect: 4
- printf("%d\n", obj.maxConsecutiveAnswers("TFFT", 1)); // expect: 3
- printf("%d\n", obj.maxConsecutiveAnswers("TTFTTFTT", 1)); // expect: 5
-}
diff --git a/other/maximise_grid_happiness.cpp b/other/maximise_grid_happiness.cpp
deleted file mode 100644
index 612c111..0000000
--- a/other/maximise_grid_happiness.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-// 1659. Maximize Grid Happiness
-#include "leetcode.h"
-
-/*
- * you are given four integers 'm', 'n', 'introvertsCount', and
- * 'extrovertsCount'. you have an 'm * 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 ou 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. neighbours live 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
- */
-
-class Solution {
-private:
- int dp[25][7][7][64][64] = {};
- int n_cost(int m, int n, int i, int j, int introvert_mask, int extrovert_mask,
- int d) {
- int diff = 0, up = (1 << (n - 1));
- if (j && (introvert_mask & 1))
- diff += d - 30;
- if (i && (introvert_mask & up))
- diff += d - 30;
- if (j && (extrovert_mask & 1))
- diff += d + 20;
- if (i && (extrovert_mask & up))
- diff += d + 20;
- return diff;
- }
- int dfs(int m, int n, int p, int in, int out, int introvert_mask,
- int extrovert_mask) {
- int i = p / n, j = p % n;
- if (i >= m)
- return 0;
- if (dp[p][in][out][introvert_mask][extrovert_mask])
- return dp[p][in][out][introvert_mask][extrovert_mask] - 1;
- int n_introvert_mask = (introvert_mask << 1) & 63,
- n_extrovert_mask = (extrovert_mask << 1) & 63;
- int res = dfs(m, n, p + 1, in, out, n_introvert_mask, n_extrovert_mask);
- if (in) {
- int diff = n_cost(m, n, i, j, introvert_mask, extrovert_mask, -30) + 120;
- res = max(res, diff + dfs(m, n, p + 1, in - 1, out, n_introvert_mask + 1,
- n_extrovert_mask));
- }
- if (out) {
- int diff = n_cost(m, n, i, j, introvert_mask, extrovert_mask, 20) + 40;
- res = max(res, diff + dfs(m, n, p + 1, in, out - 1, n_introvert_mask,
- n_extrovert_mask + 1));
- }
- return res;
- }
-
-public:
- int getMaxGridHappiness(int m, int n, int introvertsCount,
- int extrovertsCount) {
- return dfs(m, n, 0, introvertsCount, extrovertsCount, 0, 0);
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.getMaxGridHappiness(2, 3, 1, 2)); // expect: 240
- printf("%d\n", obj.getMaxGridHappiness(3, 1, 2, 1)); // expect: 260
-}
diff --git a/other/merge_sorted_array.cpp b/other/merge_sorted_array.cpp
deleted file mode 100644
index 6a98a38..0000000
--- a/other/merge_sorted_array.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- void merge(vector<int> &nums1, int m, vector<int> &nums2, int n) {
- int i = m - 1, j = n - 1, k = m + n - 1;
- while (i >= 0 && j >= 0) {
- if (nums1[i] > nums2[j])
- nums1[k--] = nums1[i--];
- else
- nums1[k--] = nums2[j--];
- }
- while (j >= 0)
- nums1[k--] = nums2[j--];
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums1 = {1, 2, 3, 0, 0, 0};
- vector<int> nums2 = {2, 5, 6};
- int m = 3, n = 3;
- cout << "nums1:\n";
- for (auto i : nums1)
- cout << i;
- cout << "\nnums2:\n";
- for (auto i : nums2)
- cout << i;
- obj.merge(nums1, m, nums2, n);
- cout << "\nnums1 & nums2 merged:\n";
- for (auto i : nums1)
- cout << i;
-}
diff --git a/other/merge_sorted_array.rs b/other/merge_sorted_array.rs
deleted file mode 100644
index 1e2704d..0000000
--- a/other/merge_sorted_array.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn merge(nums1: &mut Vec<i32>, m: i32, nums2: &mut Vec<i32>, n: i32) {
- let (mut m )
- }
-}
-
-fn main() {
- let mut nums1 = vec![1,2,3,0,0,0];
- let mut nums2 = vec![2,5,6];
- let (m, n) = (3, 3);
- Solution::merge(&mut nums1, m, &mut nums2, n);
-}
diff --git a/other/merge_string_alt.cpp b/other/merge_string_alt.cpp
deleted file mode 100644
index d69c5fc..0000000
--- a/other/merge_string_alt.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-// 1768. Merge Strings Alternately
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-/*
- * 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!!
- */
-
-char *mergeAlternately(char *word1, char *word2) {
- char *ans = (char *)calloc(strlen(word1) + strlen(word2) + 1, sizeof(char));
- int i = 0, j = 0, k = 0;
- while (i < strlen(word1) || j < strlen(word2)) {
- if (i < strlen(word1))
- ans[k++] = word1[i++];
- if (j < strlen(word2))
- ans[k++] = word2[j++];
- }
- return ans;
-}
-
-int main() {
- char w1[] = {"abc"}, w2[] = {"pqr"}, *ma1 = mergeAlternately(w1, w2);
- char w3[] = {"ab"}, w4[] = {"pqrs"}, *ma2 = mergeAlternately(w3, w4);
- char w5[] = {"abcd"}, w6[] = {"pq"}, *ma3 = mergeAlternately(w5, w6);
- printf("%s\n", ma1); // expect: apbqcr
- printf("%s\n", ma2); // expect: apbqrs
- printf("%s\n", ma3); // expect: apbqcd
-}
diff --git a/other/middle_linked_list.cpp b/other/middle_linked_list.cpp
deleted file mode 100644
index ba3a2a0..0000000
--- a/other/middle_linked_list.cpp
+++ /dev/null
@@ -1,18 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- ListNode *middleNode(ListNode *head) {
- ListNode *tmp = head;
- int len = 0;
- while (tmp) {
- len++;
- tmp = tmp->next;
- }
- int mid = len / 2;
- tmp = head;
- while (tmp && mid--)
- tmp = tmp->next;
- return tmp;
- }
-};
diff --git a/other/middle_linked_list.rs b/other/middle_linked_list.rs
deleted file mode 100644
index ed84409..0000000
--- a/other/middle_linked_list.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-#[derive(PartialEq, Eq, Clone, Debug)]
-struct Solution;
-pub struct ListNode {
- pub val: i32,
- pub next: Option<Box<ListNode>>
-}
-
-impl ListNode {
- #[inline]
- fn new(val: i32) -> Self {
- ListNode {
- next: None,
- val
- }
- }
-}
-
-impl Solution {
- pub fn middle_node(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
- let mut curr = &head;
- let mut node_vec: Vec<Option<Box<ListNode>>> = vec![];
- while let Some(node) = curr.as_ref() {
- node_vec.push(Some(node.clone()));
- curr = &curr.as_ref().unwrap().next;
- }
- node_vec[node_vec.len() / 2].clone()
- }
-}
diff --git a/other/min_abs_diff_bst.cpp b/other/min_abs_diff_bst.cpp
deleted file mode 100644
index 0c0ef82..0000000
--- a/other/min_abs_diff_bst.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-// 530. Minimum Absolute Difference in BST
-#include "leetcode.h"
-
-/*
- * given the 'root' of a binary search tree (bst), return the minimum absolute
- * difference between the values of any two different nodes in the tree
- */
-
-class Solution {
- int diff = INT_MAX;
- TreeNode *prev = NULL;
- void dfs(TreeNode *root) {
- if (root->left)
- dfs(root->left);
- if (prev)
- diff = min(diff, abs(prev->val - root->val));
- prev = root;
- if (root->right)
- dfs(root->right);
- }
-
-public:
- int getMinimumDifference(TreeNode *root) {
- dfs(root);
- return diff;
- }
-};
diff --git a/other/min_ascii_strs.cpp b/other/min_ascii_strs.cpp
deleted file mode 100644
index 07433d6..0000000
--- a/other/min_ascii_strs.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-// 712. Minimum ASCII Delete Sum for Two Strings
-#include "leetcode.h"
-
-/*
- * given two strings 's1' and 's2', return the lowest ascii sum of the deleted
- * characters to make two strings equal
- */
-
-class Solution {
-public:
- int minimumDeleteSum(string s1, string s2) {
- int n = s1.size(), m = s2.size(), sum1 = 0, sum2 = 0;
- int dp[n + 1][m + 1];
- for (int i = 0; i < n; i++)
- sum1 += s1[i];
- for (int i = 0; i < m; i++)
- sum2 += s2[i];
- for (int i = 0; i <= n; i++)
- for (int j = 0; j <= m; j++)
- if (!i || !j)
- dp[i][j] = 0;
- for (int i = 1; i <= n; i++)
- for (int j = 1; j <= m; j++) {
- if (s1[i - 1] == s2[j - 1])
- dp[i][j] = s1[i - 1] + dp[i - 1][j - 1];
- else
- dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
- }
- int ans = dp[n][m];
- return sum1 + sum2 - 2 * ans;
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.minimumDeleteSum("sea", "eat")); // expect: 231
- printf("%d\n", obj.minimumDeleteSum("delete", "leet")); // expect: 403
-}
diff --git a/other/min_avg_diff.cpp b/other/min_avg_diff.cpp
deleted file mode 100644
index 4bbc2b1..0000000
--- a/other/min_avg_diff.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minimumAverageDifference(vector<int> &nums) {
- long i = 0, j = 0, m = LONG_MAX, k, d;
- long pfx = 0, sfx = accumulate(nums.begin(), nums.end(), 0L);
- for (int n : nums) {
- pfx += n;
- sfx -= n;
- j += 1;
- k = nums.size() - j;
- d = abs(pfx / j - sfx / (k ? k : 1));
- if (d < m) {
- m = d;
- i = j - 1;
- }
- }
- return i;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {2, 5, 3, 9, 5, 3};
- cout << obj.minimumAverageDifference(nums);
-}
diff --git a/other/min_avg_diff.rs b/other/min_avg_diff.rs
deleted file mode 100644
index 71c18aa..0000000
--- a/other/min_avg_diff.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn minimum_average_difference(nums: Vec<i32>) -> i32 {
- let (mut left, mut ans, mut min) = (0, 0, i64::MAX);
- let mut right = nums.iter().map(|&x| x as i64).sum::<i64>();
- for i in 0..nums.len() {
- left += nums[i] as i64;
- right -= nums[i] as i64;
- let diff = (left / (i + 1) as i64 - right / 1i64.max((nums.len() - i - 1) as i64)).abs();
- if diff < min {
- ans = i as i32;
- min = diff;
- }
- }
- ans
- }
-}
-
-fn main() {
- let nums = vec![2,5,3,9,5,3];
- print!("{}", Solution::minimum_average_difference(nums));
-}
diff --git a/other/min_cost_arr_equal.cpp b/other/min_cost_arr_equal.cpp
deleted file mode 100644
index 3d2b95c..0000000
--- a/other/min_cost_arr_equal.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-// 2448. Minimum Cost to Make Array Equal
-#include "leetcode.h"
-
-/*
- * given two 0-indexed arrays 'nums' and 'cost' consisting each of 'n' positive
- * integers. you can do the following operation any number of times:
- * - increase or decrease any element of the array 'nums' by 1
- * the cost of doing one operation on the i'th element is 'cost[i]'. return the
- * minimum total cost such that all the elements of the array 'nums' become
- * equal
- */
-
-class Solution {
- long long helper(vector<int> &nums, vector<int> &cost, int x) {
- long long res = 0;
- for (int i = 0; i < nums.size(); ++i)
- res += 1L * abs(nums[i] - x) * cost[i];
- return res;
- }
-
-public:
- long long minCost(vector<int> &nums, vector<int> &cost) {
- long long left = 1, right = 1000000, ans = helper(nums, cost, 1), mid;
- while (left < right) {
- mid = (left + right) / 2;
- long long y1 = helper(nums, cost, mid);
- long long y2 = helper(nums, cost, mid + 1);
- ans = min(y1, y2);
- if (y1 < y2)
- right = mid;
- else
- left = mid + 1;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 3, 5, 2}, c1 = {2, 3, 1, 14};
- vector<int> n2 = {2, 2, 2, 2, 2}, c2 = {4, 2, 8, 1, 3};
- printf("%lld\n", obj.minCost(n1, c1)); // expect: 8
- printf("%lld\n", obj.minCost(n2, c2)); // expect: 0
-}
diff --git a/other/min_cost_change_expr.cpp b/other/min_cost_change_expr.cpp
deleted file mode 100644
index c75d10c..0000000
--- a/other/min_cost_change_expr.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minOperationsToFlip(string expression) {
- vector<vector<array<char, 2>>> vva(1);
- for (auto ch : expression) {
- if (ch == '(')
- vva.push_back(vector<array<char, 2>>());
- else if (ch == ')') {
- auto val = eval(vva.back(), vva.back().size() - 1);
- vva.pop_back();
- vva.back().push_back(val);
- } else
- vva.back().push_back({ch, 1});
- }
- return eval(vva.back(), vva.back().size() - 1)[1];
- }
-
-private:
- array<char, 2> eval(vector<array<char, 2>> &exp, int i) {
- if (i == 0)
- return exp[0];
- auto left = eval(exp, i - 2), right = exp[i];
- int v1 = left[0] - '0', v2 = right[0] - '0', cost = 1;
- if (exp[i - 1][0] == '|') {
- if (v1 == v2)
- cost = min(left[1], right[1]) + (v1 == 1);
- return {v1 | v2 ? '1' : '0', (char)cost};
- }
- if (v1 == v2)
- cost = min(left[1], right[1]) + (v1 == 0);
- return {v1 & v2 ? '1' : '0', (char)cost};
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.minOperationsToFlip("(0|(1|0&1))");
-}
diff --git a/other/min_cost_climbing_stairs.cpp b/other/min_cost_climbing_stairs.cpp
deleted file mode 100644
index 3df886a..0000000
--- a/other/min_cost_climbing_stairs.cpp
+++ /dev/null
@@ -1,16 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minCostClimbingStairs(vector<int> &cost) {
- for (int i = cost.size() - 3; ~i; i--)
- cost[i] += min(cost[i + 1], cost[i + 2]);
- return min(cost[0], cost[1]);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> cost = {10, 15, 20};
- cout << obj.minCostClimbingStairs(cost);
-}
diff --git a/other/min_cost_convert_string1.cpp b/other/min_cost_convert_string1.cpp
deleted file mode 100644
index 914eff9..0000000
--- a/other/min_cost_convert_string1.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-// 2976. Minimum Cost to Convert String I
-#include "leetcode.h"
-
-/*
- * you are given two 0 indexed strings 'source' and 'target', both of length 'n'
- * and consisting of lowercase english letters. you are also given two 0 indexed
- * character arrays 'original' and 'changed', and an integer array 'cost' where
- * 'cost[i]' represents the cost of changing the character 'original[i]' to the
- * character 'changed[i]' you start with the string 'source'. in one operation,
- * you can pick a character 'x' from te string and change it to the character
- * 'y' at a cost of 'z' if there exists any index 'j' such that 'cost[j] == z,
- * original[j] == x, changed[j] == y'. return the minimum cost to conver the
- * string 'source' to the string 'target'.
- */
-
-class Solution {
-public:
- long long minimumCost(string source, string target, vector<char> &original,
- vector<char> &changed, vector<int> &cost) {
- long long ans = 0;
- vector<vector<long long>> n(26, vector<long long>(26, INT_MAX));
- for (int i = 0; i < original.size(); ++i) {
- int s = original[i] = 'a', t = changed[i] - 'a';
- n[s][t] = min(n[s][t], (long long)cost[i]);
- }
- for (int k = 0; k < 26; ++k)
- for (int i = 0; i < 26; i++)
- for (int j = 0; j < 26; j++)
- n[i][j] = min(n[i][j], n[i][k] + n[k][j]);
- for (int i = 0; i < source.size(); ++i) {
- if (source[i] == target[i])
- continue;
- int s = source[i] - 'a', t = target[i] - 'a';
- if (n[s][t] >= INT_MAX)
- return -1;
- ans += n[s][t];
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<char> o1 = {'a', 'b', 'c', 'c', 'e', 'd'},
- ch1 = {'b', 'c', 'b', 'e', 'b', 'e'}, o2 = {'a', 'b'},
- ch2 = {'c', 'b'}, o3 = {'a'}, ch3 = {'e'};
- vector<int> co1 = {2, 5, 5, 1, 2, 20}, co2 = {1, 2}, co3 = {10000};
- printf("%lld\n", obj.minimumCost("abcd", "acbe", o1, ch1, co1)); // expect: 28
- printf("%lld\n", obj.minimumCost("aaaa", "bbbb", o2, ch2, co2)); // expect: 12
- printf("%lld\n", obj.minimumCost("abcd", "acbe", o3, ch3, co3)); // expect: -1
-}
diff --git a/other/min_cost_cut_stick.cpp b/other/min_cost_cut_stick.cpp
deleted file mode 100644
index 5622868..0000000
--- a/other/min_cost_cut_stick.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-// 1547. Minimum Cost to Cut a Stick
-#include "leetcode.h"
-
-/*
- * given a wooden stick of length 'n' units. the stick is labelled from 0 to
- * 'n'. for example, a stick of length 6 is labelled as follows (see image).
- * given an integer array 'cuts' where 'cuts[i]' denotes a position you should
- * perform a cut at. you should perform the cuts in order, you can change the
- * order of the cuts as you wish. the cost of one cut is the length of the stick
- * to be cut, the total cost is the sum of costs of all cuts. when you cut a
- * stick, it will be split into two smaller sticks ie. the sum of their lengths
- * is the length of the stick before the cut. refer to first example for better
- * explanation (see image). return minimum cost of the cuts
- */
-
-class Solution {
- int dp[102][102] = {};
- int dfs(vector<int> &cuts, int i, int j) {
- if (j - i <= 1)
- return 0;
- if (!dp[i][j]) {
- dp[i][j] = INT_MAX;
- for (auto k = i + 1; k < j; ++k)
- dp[i][j] = min(dp[i][j],
- cuts[j] - cuts[i] + dfs(cuts, i, k) + dfs(cuts, k, j));
- }
- return dp[i][j];
- }
-
-public:
- int minCost(int n, vector<int> &cuts) {
- cuts.push_back(0);
- cuts.push_back(n);
- sort(begin(cuts), end(cuts));
- return dfs(cuts, 0, cuts.size() - 1);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> c1 = {1, 3, 4, 5};
- vector<int> c2 = {5, 6, 1, 4, 2};
- printf("%d\n", obj.minCost(7, c1)); // expect: 16
- printf("%d\n", obj.minCost(9, c2)); // expect: 22
-}
diff --git a/other/min_cost_ticket.cpp b/other/min_cost_ticket.cpp
deleted file mode 100644
index 1d00853..0000000
--- a/other/min_cost_ticket.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-// 983. Minimum Cost For Tickets
-#include "leetcode.h"
-
-/*
- * you have planned some train traveling one year in advance. the days of the
- * year in which you will travel are given as an integer array 'days'. each day
- * is an integer 1 - 365. train tickets are sold in three different ways: 1 day
- * pass sold for 'costs[0]' dollars 7 day pass sold for 'costs[1]' dollars 30
- * day pass sold for 'costs[2]' dollars the passes allow that many days of
- * consecutive travel. return mininum number of dollars you need to travel every
- * day in the given list of days.
- */
-
-class Solution {
-public:
- int mincostTickets(vector<int> &days, vector<int> &costs) {
- unordered_map<int, int> tickets;
- tickets[1] = costs[0];
- tickets[7] = costs[1];
- tickets[30] = costs[2];
- vector<int> dp(366, INT_MAX);
- dp[0] = 0;
- for (int i = 1; i < 366; i++) {
- if (find(days.begin(), days.end(), i) == days.end()) {
- dp[i] = dp[i - 1];
- continue;
- }
- for (auto t : tickets)
- dp[i] = min(dp[i], dp[max(0, i - t.first)] + t.second);
- }
- return dp[365];
- }
-};
-
-int main() {
- Solution obj;
- vector<int> d1 = {1, 4, 6, 7, 8, 20},
- d2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31};
- vector<int> c1 = {2, 7, 15};
- printf("%d\n", obj.mincostTickets(d1, c1)); // expect: 11
- printf("%d\n", obj.mincostTickets(d2, c1)); // expect: 17
-}
diff --git a/other/min_cost_walk_weight_graph.cpp b/other/min_cost_walk_weight_graph.cpp
deleted file mode 100644
index 79f3a8b..0000000
--- a/other/min_cost_walk_weight_graph.cpp
+++ /dev/null
@@ -1,72 +0,0 @@
-// 3108. Minimum Cost Walk in Weighted Graph
-#include "leetcode.h"
-
-/*
- * there is an undirected weighted graph with 'n' vertices labeled from 0 to 'n
- * - 1'. you are given the integer 'n' and an array 'edges', where 'edges[i] =
- * [u_i, v_i, w_i]' indicates that there is an edge between vertices 'u_i' and
- * 'v_i' with a weight of 'w_i'. a walk on the graph is a sequence of vertices
- * and edges. the walk starts and ends with a vertex, and each edge connects the
- * vertex that comes before it and the vertex that comes after it. it's
- * important to note that a walk may visit the same edge or vertex more than
- * once. return the array 'answer' where 'answer[i]' denotes the minimum cost of
- * a walk for query 'i'.
- */
-
-class Solution {
-public:
- vector<int> minimumCost(int n, vector<vector<int>> &edges,
- vector<vector<int>> &query) {
- vector<vector<int>> adj(n);
- vector<int> cnt(n, (1 << 30) - 1);
- for (vector<int> e : edges) {
- int u = e[0], v = e[1], k = e[2];
- adj[u].push_back(v);
- adj[v].push_back(u);
- cnt[u] &= k;
- cnt[v] &= k;
- }
- queue<int> q;
- vector<int> group(n, -1);
- for (int i = 0; i < n; i++) {
- if (group[i] == -1) {
- group[i] = i;
- q.push(i);
- while (!q.empty()) {
- int u = q.front();
- q.pop();
- cnt[i] &= cnt[u];
- for (int v : adj[u]) {
- if (group[v] == -1) {
- group[v] = i;
- q.push(v);
- }
- }
- }
- }
- }
- vector<int> ans;
- for (vector<int> qs : query) {
- int s = qs[0], t = qs[1];
- if (s == t)
- ans.push_back(0);
- else
- ans.push_back(group[s] == group[t] ? cnt[group[s]] : -1);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd e1 = {{0, 1, 7}, {1, 3, 7}, {1, 2, 1}}, q1 = {{0, 3}, {3, 4}};
- vvd e2 = {{0, 2, 7}, {0, 1, 15}, {1, 2, 6}, {1, 2, 1}}, q2 = {{1, 2}};
- vector<int> mc1 = obj.minimumCost(5, e1, q1);
- vector<int> mc2 = obj.minimumCost(3, e2, q2);
- for (auto i : mc1)
- printf("%d ", i); // expect: 1 -1
- printf("\n");
- for (auto i : mc2)
- printf("%d ", i); // expect: 0
- printf("\n");
-}
diff --git a/other/min_deletions_unique_char.cpp b/other/min_deletions_unique_char.cpp
deleted file mode 100644
index c971b21..0000000
--- a/other/min_deletions_unique_char.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minDeletions(string s) {
- vector<int> freq(26, 0);
- int ans = 0;
- for (char c : s)
- freq[c - 'a']++;
- sort(freq.begin(), freq.end());
- for (int i = 24; i >= 0; i--) {
- if (freq[i] == 0)
- break;
- if (freq[i] >= freq[i + 1]) {
- int prev = freq[i];
- freq[i] = max(0, freq[i + 1] - 1);
- ans += prev - freq[i];
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- string s = "aab";
- cout << obj.minDeletions(s);
-}
diff --git a/other/min_depth_binary_tree.cpp b/other/min_depth_binary_tree.cpp
deleted file mode 100644
index 7661fb2..0000000
--- a/other/min_depth_binary_tree.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-// 111. Minimum Depth of Binary Tree
-#include "leetcode.h"
-
-/*
- * given a binary tree, find its minimum depth. the minimum depth is the number
- * of nodes along the shortest path from the root node down to the nearest leaf
- * node. note: a leaf is a node with no children.
- */
-
-class Solution {
-public:
- int minDepth(TreeNode *root) {
- if (!root)
- return 0;
- queue<TreeNode *> q;
- q.push(root);
- int i = 0;
- while (!q.empty()) {
- i++;
- int k = q.size();
- for (int j = 0; j < k; j++) {
- TreeNode *rt = q.front();
- if (rt->left)
- q.push(rt->left);
- if (rt->right)
- q.push(rt->right);
- q.pop();
- if (!rt->left && !rt->right)
- return i;
- }
- }
- return -1;
- }
-};
diff --git a/other/min_deviation_arr.cpp b/other/min_deviation_arr.cpp
deleted file mode 100644
index 47099a6..0000000
--- a/other/min_deviation_arr.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-// 1675. Minimize Deviation in Array
-#include "leetcode.h"
-
-/*
- * the deviation of the array is the maximum difference between any two elements
- * in the array. return minimum deviation the array can have after performing
- * 'nums' ops.
- */
-
-class Solution {
-public:
- int minimumDeviation(vector<int> nums) {
- int ans = INT_MAX, min_nums = INT_MAX;
- for (int i = 0; i < nums.size(); ++i) {
- nums[i] = nums[i] % 2 ? nums[i] * 2 : nums[i];
- min_nums = min(min_nums, nums[i]);
- }
- make_heap(begin(nums), end(nums));
- while (nums[0] % 2 == 0) {
- ans = min(ans, nums[0] - min_nums);
- min_nums = min(min_nums, nums[0] / 2);
- pop_heap(begin(nums), end(nums));
- nums.back() /= 2;
- push_heap(begin(nums), end(nums));
- }
- return min(ans, nums[0] - min_nums);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 2, 3, 4}, n2 = {4, 1, 5, 20, 3}, n3 = {2, 10, 8};
- cout << obj.minimumDeviation(n1) << endl; // expect: 1
- cout << obj.minimumDeviation(n2) << endl; // expect: 3
- cout << obj.minimumDeviation(n3) << endl; // expect: 3
-}
diff --git a/other/min_difficulty_schedule.cpp b/other/min_difficulty_schedule.cpp
deleted file mode 100644
index 40fab6e..0000000
--- a/other/min_difficulty_schedule.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-#include "leetcode.h"
-#include <algorithm>
-#include <vector>
-
-class Solution {
-public:
- int minDifficulty(vector<int> &jobDifficulty, int d) {
- int n = jobDifficulty.size();
- if (n < d)
- return -1;
- vector<int> dp(n, 1000), dp2(n), stack;
- for (int i = 0; i < d; ++i) {
- stack.clear();
- for (int j = i; j < n; j++) {
- dp2[j] = j ? dp[j - 1] + jobDifficulty[j] : jobDifficulty[j];
- while (stack.size() &&
- jobDifficulty[stack.back()] <= jobDifficulty[j]) {
- int k = stack.back();
- stack.pop_back();
- dp[j] = min(dp2[j], dp2[k] - jobDifficulty[k] + jobDifficulty[j]);
- }
- if (stack.size())
- dp2[j] = min(dp2[j], dp2[stack.back()]);
- stack.push_back(j);
- }
- swap(dp, dp2);
- }
- return dp[n - 1];
- }
-};
-
-int main() {
- Solution obj;
- vector<int> jobDifficulty = {6, 5, 4, 3, 2, 1};
- cout << obj.minDifficulty(jobDifficulty, 2);
-}
diff --git a/other/min_dist_bst_node.cpp b/other/min_dist_bst_node.cpp
deleted file mode 100644
index 5222628..0000000
--- a/other/min_dist_bst_node.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-// 783. Minimum Distance Between BST Nodes
-#include "leetcode.h"
-
-// given the 'root' of BST, return the minimum difference between the values
-// of any two different nodes in the tree!
-
-class Solution {
-public:
- int ans = INT_MAX, pre = -1;
- int minDiffInBST(TreeNode *root) {
- if (root->left != NULL)
- minDiffInBST(root->left);
- if (pre >= 0)
- ans = min(ans, root->val - pre);
- pre = root->val;
- if (root->right != NULL)
- minDiffInBST(root->right);
- return ans;
- }
-};
diff --git a/other/min_dist_target_element.cpp b/other/min_dist_target_element.cpp
deleted file mode 100644
index 662c5ec..0000000
--- a/other/min_dist_target_element.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int getMinDistance(vector<int> &nums, int target, int start) {
- int ans = INT_MAX;
- for (int i = 0; i < nums.size(); i++)
- if (nums[i] == target)
- ans = min(ans, abs(i - start));
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {1, 2, 3, 4, 5};
- int target = 5, start = 3;
- // expect 1
- cout << obj.getMinDistance(nums, target, start);
-}
diff --git a/other/min_falling_path_sum.cpp b/other/min_falling_path_sum.cpp
deleted file mode 100644
index 3bc2940..0000000
--- a/other/min_falling_path_sum.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-#include "leetcode.h"
-
-/*
- * given NxN array of integers 'matrix' return the minimum
- * sum of any falling path through 'matrix'
- *
- * a falling path starts at any element in row 0 and chooses
- * the element in the next row that is either directly below
- * or diagonally left/right that obviously makes for the lowest sum
- */
-
-class Solution {
-public:
- int minFallingPathSum(vvd & matrix) {
- vvd dp(matrix.size(), vector<int>(matrix.size(), INT_MAX));
- for (int i = 0; i < matrix.size(); i++)
- dp[0][i] = matrix[0][i];
- for (int i = 1; i < matrix.size(); i++) {
- for (int j = 0; j < matrix.size(); j++) {
- if (j > 0 && j < matrix.size() - 1) {
- dp[i][j] =
- min(dp[i - 1][j - 1] + matrix[i][j], dp[i - 1][j] + matrix[i][j]);
- dp[i][j] = min(dp[i - 1][i + 1] + matrix[i][j], dp[i][j]);
- } else if (j == 0)
- dp[i][j] =
- min(dp[i - 1][j + 1] + matrix[i][j], dp[i - 1][j] + matrix[i][j]);
- else if (j == matrix.size() - 1)
- dp[i][j] =
- min(dp[i - 1][j - 1] + matrix[i][j], dp[i - 1][j] + matrix[i][j]);
- }
- }
- int ans = INT_MAX;
- for (auto &x : dp[dp.size() - 1])
- ans = min(ans, x);
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd matrix = {{2, 1, 3}, // 1
- {6, 5, 4}, //-> 4
- {7, 8, 9}}; // 8 <-
- cout << obj.minFallingPathSum(matrix); // expect 13
-}
diff --git a/other/min_falling_path_sum.rs b/other/min_falling_path_sum.rs
deleted file mode 100644
index 4b704c1..0000000
--- a/other/min_falling_path_sum.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn min_falling_path_sum(matrix: Vec<Vec<i32>>) -> i32 {
- matrix.into_iter().reduce(|prev, mut curr| {
- prev.into_iter().chain(std::iter::once(i32::MAX)).scan((i32::MAX, i32::MAX, i32::MAX), |(w1, w2, w3), c| {
- *w1 = *w2;
- *w2 = *w3;
- *w3 = c;
- Some(c.min(*w1).min(*w2))
- }).skip(1).zip(curr.iter_mut()).for_each(|(p, c)| *c += p);
- curr
- }).unwrap().into_iter().min().unwrap()
- }
-}
-
-fn main() {
- let matrix = vec![
- vec![2,1,3],
- vec![6,5,4],
- vec![7,8,9]];
- print!("{}", Solution::min_falling_path_sum(matrix));
-}
diff --git a/other/min_flips_abc.cpp b/other/min_flips_abc.cpp
deleted file mode 100644
index b51b261..0000000
--- a/other/min_flips_abc.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-// 1318. Minimum Flips to Make a OR b Equal to c
-#include "leetcode.h"
-
-/*
- * given three positive numbers 'a, b, c'. return the minimum flips required in
- * some bits of 'a | b == c'. flip operation consists of changing any single bit
- * 1 to 0 or changing the bit 0 to 1 in their binary representation
- */
-
-class Solution {
-public:
- int minFlips(int a, int b, int c) {
- return __builtin_popcount(c ^= a | b) + __builtin_popcount(a & b & c);
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.minFlips(2, 6, 5)); // expect: 3
- printf("%d\n", obj.minFlips(4, 2, 7)); // expect: 1
- printf("%d\n", obj.minFlips(1, 2, 3)); // expect: 0
-}
diff --git a/other/min_fuel_report_captial.cpp b/other/min_fuel_report_captial.cpp
deleted file mode 100644
index 4e3e2d6..0000000
--- a/other/min_fuel_report_captial.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-// 2477. Minimum Fuel Cost to Report to the Capital
-#include "leetcode.h"
-
-/*
- * there is a tree (ie. a connected, undirected graph with no cycles) structure
- * country network consisting of 'n' cities numbered from 0 to 'n - 1' and
- * exactly 'n - 1' roads the capital city is city 0. given a 2d integer array
- * 'roads' where 'roads[i] = [ai, bi]' denotes that there exists a bidirectional
- * road connecting cities ai & bi. there is a meeting for the representitive of
- * each city. the meeting is in the capital city. there is a car in each city.
- * given integer seats that indicates the number of seats in each car. a
- * representitive can use the car in their city to travel or change the car and
- * ride with another representitive. the cost of traveling between two cities is
- * 1 liter of fuel. return minimum number of liters of fuel needed to reach
- * capital city.
- */
-
-class Solution {
-public:
- long long minimumFuelCost(vvd & roads, int seats) {
- vvd al(roads.size() + 1);
- for (auto &r : roads) {
- al[r[0]].push_back(r[1]);
- al[r[1]].push_back(r[0]);
- }
- long long ans = 0;
- return dfs(0, -1, 0, seats, al, ans);
- }
-
-private:
- long long dfs(int i, int prev, int depth, int seats, vvd & al,
- long long &ans) {
- long long riders = 1;
- for (int j : al[i])
- if (j != prev)
- riders += dfs(j, i, depth + 1, seats, al, ans);
- if (depth == 0)
- return ans;
- ans += (riders / seats) * depth + (riders % seats ? 1 : 0);
- return riders % seats;
- }
-};
-
-int main() {
- Solution obj;
- vvd roads1 = {{0, 1}, {0, 2}, {0, 3}};
- vvd roads2 = {{3, 1}, {3, 2}, {1, 0}, {0, 4}, {0, 5}, {4, 6}};
- cout << obj.minimumFuelCost(roads1, 5) << endl; // expect: 3
- cout << obj.minimumFuelCost(roads2, 2) << endl; // expect: 7
-}
diff --git a/other/min_genetic_mutation.cpp b/other/min_genetic_mutation.cpp
deleted file mode 100644
index 8bbf503..0000000
--- a/other/min_genetic_mutation.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minMutation(string start, string end, vector<string> &bank) {
- deque<pair<string, int>> dqp({{start, 0}});
- set<string> s(bank.begin(), bank.end());
- vector<char> nucleotides = {'A', 'T', 'G', 'C'};
- while (!dqp.empty()) {
- auto [g, m] = dqp.front();
- dqp.pop_front();
- if (g == end)
- return m;
- for (int i = 0; i < g.size(); ++i)
- for (char n : nucleotides) {
- string gm = g;
- gm[i] = n;
- if (s.count(gm)) {
- s.erase(gm);
- dqp.emplace_back(gm, m + 1);
- }
- }
- }
- return -1;
- }
-};
-
-int main() {
- Solution obj;
- string start = "AACCGGTT", end = "AACCGGTA";
- vector<string> bank = {"AACCGGTA"};
- cout << obj.minMutation(start, end, bank);
-}
diff --git a/other/min_genetic_mutation.rs b/other/min_genetic_mutation.rs
deleted file mode 100644
index 1362636..0000000
--- a/other/min_genetic_mutation.rs
+++ /dev/null
@@ -1,53 +0,0 @@
-use std::collections::HashSet;
-struct Solution;
-
-impl Solution {
- pub fn min_mutation(start: String, end: String, mut bank: Vec<String>) -> i32 {
- match bank.iter().position(|w| end.eq(w)) {
- None => return -1,
- Some(idx) => bank.swap_remove(idx)
- };
- let (mut left, mut right, mut next) = (HashSet::new(), HashSet::new(), HashSet::new());
- left.insert(start);
- right.insert(end);
- let mut len = 0;
- while !left.is_empty() && !right.is_empty() {
- if left.len() > right.len() {
- std::mem::swap(&mut left, &mut right);
- }
- for w in left.drain() {
- let mut idx = 0;
- for word in right.iter() {
- if Self::is_adjacent(&w, word.as_str()) {
- return len + 1;
- }
- }
- while idx < bank.len() {
- if !is_adjacent(&w, &bank[idx]) {
- idx += 1;
- continue;
- }
- let neighbor = bank.swap_remove(idx);
- next.insert(neighbor);
- }
- }
- std::mem::swap(&mut left, &mut next);
- len += 1;
- }
- -1
- }
- fn is_adjacent(a: &str, b: &str) -> bool {
- let (a, b) = (a.as_bytes(), b.as_bytes());
- assert_eq!(a.len(), b.len());
- let mut diff = 0;
- for idx in 0..a.len() {
- if a[idx] != b[idx] {
- diff += 1;
- }
- if diff > 1 {
- break;
- }
- }
- diff == 1
- }
-}
diff --git a/other/min_incr_arr_unique.cpp b/other/min_incr_arr_unique.cpp
deleted file mode 100644
index 9121d48..0000000
--- a/other/min_incr_arr_unique.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-// 945. Minimum Increment to Make Array Unique
-#include "leetcode.h"
-
-/*
- * given an integer array 'nums'. in one move, you can pick an index 'i' where
- * '0 <= i < nums.length' and increment 'nums[i]' by 1. return the minimum
- * number of moves to make every value in 'nums' unique. the test cases are
- * generated so that the answer fits in a 32-bit integer.
- */
-
-class Solution {
-public:
- int minIncrementForUnique(vector<int> &nums) {
- int n = nums.size(), ans = 0;
- if (n < 2)
- return 0;
- sort(nums.begin(), nums.end());
- for (int i = 1; i < n; ++i)
- if (nums[i] <= nums[i - 1]) {
- ans += nums[i - 1] + 1 - nums[i];
- nums[i] = nums[i - 1] + 1;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 2, 2}, n2 = {3, 2, 1, 2, 1, 7};
- printf("%d\n", obj.minIncrementForUnique(n1)); // expect: 1
- printf("%d\n", obj.minIncrementForUnique(n2)); // expect: 6
-}
diff --git a/other/min_insertion_make_palindrome.cpp b/other/min_insertion_make_palindrome.cpp
deleted file mode 100644
index 7af74da..0000000
--- a/other/min_insertion_make_palindrome.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-// 1312. Minimum Insertion Steps to Make a String Palindrome
-#include "leetcode.h"
-
-/*
- * given string 's'. in one step you can insert any character at any index of
- * the string. return the minimum number of steps to make 's' palindrome. a
- * palindrome string is one that reads the same backward as well as forward.
- */
-
-class Solution {
-public:
- int minInsertions(string s) {
- vector<int> memo(s.size(), 0);
- int prv, tmp;
- for (int i = s.size() - 2; i >= 0; i--) {
- prv = 0;
- for (int j = i; j < s.size(); j++) {
- tmp = memo[j];
- memo[j] = s[i] == s[j] ? prv : 1 + min(memo[j], memo[j - 1]);
- prv = tmp;
- }
- }
- return memo[s.size() - 1];
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.minInsertions("zzazz")); // expect: 0
- printf("%d\n", obj.minInsertions("mbadm")); // expect: 2
- printf("%d\n", obj.minInsertions("leetcode")); // expect: 5
-}
diff --git a/other/min_jump_reach_home.cpp b/other/min_jump_reach_home.cpp
deleted file mode 100644
index 7510c8c..0000000
--- a/other/min_jump_reach_home.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minimumJumps(vector<int> &forbidden, int a, int b, int x) {
- unordered_set<int> f(forbidden.begin(), forbidden.end());
- vvd visited(2, vector<int>(5000));
- queue<pair<int, bool>> qp;
- qp.push({0, false});
- visited[0][0] = 1;
- visited[1][0] = 1;
- int ans = 0;
- while (!qp.empty()) {
- int len = qp.size();
- while (len > 0) {
- len--;
- int curr = qp.front().first;
- bool flag = qp.front().second;
- if (curr == x)
- return ans;
- qp.pop();
- int forward = curr + a, backward = curr - b;
- if (forward < 5000 && visited[0][forward] == 0 && !f.count(forward)) {
- qp.push({forward, false});
- visited[0][forward] = 1;
- }
- if (backward >= 0 && visited[1][backward] == 0 && !f.count(backward) &&
- !flag) {
- qp.push({backward, true});
- visited[1][backward] = 1;
- }
- }
- ans++;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> forbidden = {14, 4, 18, 1, 15};
- int a = 3, b = 15, x = 9;
- cout << obj.minimumJumps(forbidden, a, b, x);
-}
diff --git a/other/min_max_array.cpp b/other/min_max_array.cpp
deleted file mode 100644
index 6da3f2b..0000000
--- a/other/min_max_array.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-// 2439. Minimize Maximum of Array
-#include "leetcode.h"
-
-/*
- * given a 0-indexed array 'nums' comprising of n unsigned integers. ine one
- * operation you must choose an integer 'i' such that '1 <= i < n' and 'nums[i]
- * > 0'. decrease 'nums[i]' by 1 or increase 'nums[i]' by 1. return minimum
- * possible value of the max integer 'nums' after performing any number of
- * operations.
- */
-
-class Solution {
- bool valid(vector<int> &nums, int mid) {
- long sum = 0;
- for (int i = 0; i < nums.size(); i++) {
- sum += nums[i];
- if (sum > (long)mid * (i + 1))
- return false;
- }
- return true;
- }
-
-public:
- int minimizeArrayValue(vector<int> &nums) {
- int left = 0, right = *max_element(nums.begin(), nums.end()), ans = 0;
- while (left <= right) {
- int mid = (left + right) >> 1;
- if (valid(nums, mid)) {
- ans = mid;
- right = mid - 1;
- } else
- left = mid + 1;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {3, 7, 1, 6}, n2 = {10, 1};
- printf("%d\n", obj.minimizeArrayValue(n1)); // expect: 5
- printf("%d\n", obj.minimizeArrayValue(n2)); // expect: 10
-}
diff --git a/other/min_max_diff_pair.cpp b/other/min_max_diff_pair.cpp
deleted file mode 100644
index ac6dc3b..0000000
--- a/other/min_max_diff_pair.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-// 2616. Minimize the Maximum Difference of Pairs
-#include "leetcode.h"
-
-/*
- * given a 0-indexed integer array 'nums' and an integer 'p'. find 'p' pairs of
- * indices of 'nums' such that the maximum difference amongst all the pairs is
- * minimised. also, ensure no index appears more than once amongst that 'p'
- * pairs. note that for a pair of elements at the index 'i' and 'j'. the
- * difference of this pair is '|nums[i] - nums[j]|', where '|x|' represents the
- * absolute value of 'x'. return the minimum maximum difference among all 'p'
- * pairs. we define the maximum of an empty set to be zero.
- */
-
-class Solution {
- bool can_form_pair(vector<int> &nums, int p, int mid) {
- int cnt = 0;
- for (int i = 0; i < nums.size() - 1 && cnt < p;) {
- if (nums[i + 1] - nums[i] <= mid) {
- cnt++;
- i += 2;
- } else
- i++;
- }
- return cnt >= p;
- }
-
-public:
- int minimizeMax(vector<int> &nums, int p) {
- sort(nums.begin(), nums.end());
- int left = 0, right = nums.end() - nums.begin();
- while (left < right) {
- int mid = (left + right) / 2;
- if (can_form_pair(nums, p, mid))
- right = mid;
- else
- left = mid + 1;
- }
- return left;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {10, 1, 2, 7, 1, 3}, n2 = {4, 2, 1, 2};
- printf("%d\n", obj.minimizeMax(n1, 2)); // expect: 1
- printf("%d\n", obj.minimizeMax(n2, 1)); // expect: 0
-}
diff --git a/other/min_move_palindrome.cpp b/other/min_move_palindrome.cpp
deleted file mode 100644
index 6455889..0000000
--- a/other/min_move_palindrome.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-// 2193. Minimum Number of Moves to Make Palindrome
-#include "leetcode.h"
-
-/*
- * given a string 's' consisting of only lowercase ascii characters.
- * in one move you can select any two adjacent characters of 's'
- * and swap them. return the minimum number of moves needed to
- * make 's' a palindrome. note that the input will be generated
- * such that 's' can always be converted to a palindrome
- */
-
-class Solution {
-public:
- int minMovesToMakePalindrome(string s) {
- int ans = 0;
- while (s.size()) {
- int i = s.find(s.back());
- if (8 == s.size() - 1)
- ans += i / 2;
- else {
- ans += i;
- s.erase(i, 1);
- }
- s.pop_back();
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.minMovesToMakePalindrome("aabb"); // expect: 2
- cout << obj.minMovesToMakePalindrome("letelt"); // expect: 2
-}
diff --git a/other/min_moves_equal_array2.cpp b/other/min_moves_equal_array2.cpp
deleted file mode 100644
index e5fcfd0..0000000
--- a/other/min_moves_equal_array2.cpp
+++ /dev/null
@@ -1,18 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minMoves2(vector<int> &nums) {
- sort(nums.begin(), nums.end());
- int mid = nums.size() / 2, steps = 0;
- for (int i = 0; i < nums.size(); i++)
- steps += abs(nums[i] - nums[mid]);
- return steps;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {1, 2, 3};
- cout << obj.minMoves2(nums);
-}
diff --git a/other/min_num_arrow_balloon.cpp b/other/min_num_arrow_balloon.cpp
deleted file mode 100644
index 8c79da0..0000000
--- a/other/min_num_arrow_balloon.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int findMinArrowShots(vvd & points) {
- if (points.size() == 0)
- return 0;
- sort(points.begin(), points.end(), cmp);
- int arrows = 1, end = points[0][1];
- for (int i = 1; i < points.size(); i++)
- if (points[i][0] > end) {
- arrows++;
- end = points[i][1];
- }
- return arrows;
- }
-
-private:
- static bool cmp(vector<int> &x, vector<int> &y) { return x[1] < y[1]; }
-};
-
-int main() {
- Solution obj;
- vvd points1 = {{10, 16}, {2, 8}, {1, 6}, {7, 12}},
- points2 = {{1, 2}, {3, 4}, {5, 6}, {7, 8}},
- points3 = {{1, 2}, {2, 3}, {3, 4}, {4, 5}};
- cout << obj.findMinArrowShots(points1) << endl; // expect: 2
- cout << obj.findMinArrowShots(points2) << endl; // expect: 4
- cout << obj.findMinArrowShots(points3) << endl; // expect: 2
-}
diff --git a/other/min_num_arrow_balloon.rs b/other/min_num_arrow_balloon.rs
deleted file mode 100644
index 6204bfe..0000000
--- a/other/min_num_arrow_balloon.rs
+++ /dev/null
@@ -1,20 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn find_min_arrow_shots(mut points: Vec<Vec<i32>>) -> i32 {
- points.sort_unstable_by(|a, b| a[1].cmp(&b[1]));
- let (mut arrows, mut target) = (0, points[0][1]);
- for p in points {
- if p[0] > target && p[1] > target {
- arrows += 1;
- target = p[1];
- }
- }
- arrows + 1
- }
-}
-
-fn main() {
- let points = vec![vec![10,16],vec![2,8],vec![1,6],vec![7,12]];
- println!("{}", Solution::find_min_arrow_shots(points)); //expect: 2
-}
diff --git a/other/min_num_days_disconnect_island.cpp b/other/min_num_days_disconnect_island.cpp
deleted file mode 100644
index ff54c44..0000000
--- a/other/min_num_days_disconnect_island.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-// 1568. Minimum Number of Days to Disconnect Island
-#include "leetcode.h"
-
-/*
- * you are given an 'm * n' binary grid where 1 represents land and 0 represents
- * water. an island is a maximal 4 directionally horizontal or vertical
- * connected group of 1's. the grid is said to be connected if we have exactly
- * one island otherwise it is disconnected. in one day, we are allowed to change
- * any single land cell 1 into a water cell 0. return the minimum number of days
- * to disconnect the grid.
- */
-
-class Solution {
-public:
- int minDays(vector<vector<int>> &grid) {
- int islands = cnt_islands(grid), n = grid.size(), m = grid[0].size();
- if (islands > 1 || !islands)
- return 0;
- else
- for (int i = 0; i < n; i++)
- for (int j = 0; j < m; j++)
- if (grid[i][j]) {
- grid[i][j] = 0;
- islands = cnt_islands(grid);
- grid[i][j] = 1;
- if (islands > 1 || !islands)
- return 1;
- }
- return 2;
- }
-
-private:
- vector<int> dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1};
- void dfs(int x, int y, vector<vector<int>> &grid, vector<vector<int>> &vis) {
- int n = grid.size(), m = grid[0].size();
- vis[x][y] = 1;
- for (int i = 0; i < 4; i++) {
- int nx = x + dx[i], ny = y + dy[i];
- if (nx >= 0 and ny >= 0 and nx < n and ny < m and !vis[nx][ny] and
- grid[nx][ny])
- dfs(nx, ny, grid, vis);
- }
- }
- int cnt_islands(vector<vector<int>> &grid) {
- int res = 0, n = grid.size(), m = grid[0].size();
- vector<vector<int>> vis(n, vector<int>(m, 0));
- for (int i = 0; i < n; i++)
- for (int j = 0; j < m; j++)
- if (!vis[i][j] && grid[i][j]) {
- dfs(i, j, grid, vis);
- res++;
- }
- return res;
- }
-};
-
-int main() {
- Solution obj;
- vvd g1 = {{0, 1, 1, 0}, {0, 1, 1, 0}, {0, 0, 0, 0}}, g2 = {{1, 1}};
- printf("%d\n", obj.minDays(g1)); // expect: 2
- printf("%d\n", obj.minDays(g2)); // expect: 2
-}
diff --git a/other/min_num_opp_arr_cont.cpp b/other/min_num_opp_arr_cont.cpp
deleted file mode 100644
index 5dcb40f..0000000
--- a/other/min_num_opp_arr_cont.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minOperations(vector<int> &nums) {
- int n = nums.size(), ans = n, j = 0;
- sort(nums.begin(), nums.end());
- nums.erase(unique(nums.begin(), nums.end()), nums.end());
- for (int i = 0; i < nums.size(); ++i) {
- while (j < nums.size() && nums[j] < nums[i] + n)
- ++j;
- ans = min(ans, n - j + i);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {4, 2, 5, 3};
- cout << obj.minOperations(nums);
-}
diff --git a/other/min_num_refueling_stops.cpp b/other/min_num_refueling_stops.cpp
deleted file mode 100644
index 34d929b..0000000
--- a/other/min_num_refueling_stops.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minRefuelStops(int target, int startFuel, vector<vector<int>> &stations) {
- int n = stations.size(), ans = 0;
- priority_queue<int> pq;
- for (int i = 0; i <= n; i++) {
- int dist = i == n ? target : stations[i][0];
- while (startFuel < dist) {
- if (!pq.size())
- return -1;
- startFuel += pq.top();
- ans++;
- pq.pop();
- }
- if (i < n)
- pq.push(stations[i][1]);
- }
- return ans;
- }
-};
diff --git a/other/min_num_remove_mountain_arr.cpp b/other/min_num_remove_mountain_arr.cpp
deleted file mode 100644
index 007c8c6..0000000
--- a/other/min_num_remove_mountain_arr.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-// 1671. Minimum Number of Removals to Make Mountain Array
-#include "leetcode.h"
-
-/*
- * you may recall that an array 'arr' is a mountain array if and only if
- * 'arr.length >= 3', there exists soome index 'i' with '0 < i < arr.length - 1'
- * such that 'arr[0] < arr[1] <... < arr[i - 1]' and 'arr[i] > arr[i + 1] > ...
- * > arr[length - 1]'. given an integer array 'nums', return the minimum number
- * of elements to remove to make 'nums' a mountain array
- */
-
-class Solution {
-public:
- int minimumMountainRemovals(vector<int> &nums) {
- int n = nums.size();
- vector<int> left(n), right(n), stk;
- for (int i = 0; i < n; i++) {
- if (stk.empty() || stk.back() < nums[i]) {
- stk.push_back(nums[i]);
- left[i] = stk.size();
- } else {
- auto iter = lower_bound(stk.begin(), stk.end(), nums[i]);
- *iter = nums[i];
- left[i] = iter - stk.begin() + 1;
- }
- }
- stk.clear();
- for (int i = n - 1; i >= 0; i--) {
- if (stk.empty() || stk.back() < nums[i]) {
- stk.push_back(nums[i]);
- right[i] = stk.size();
- } else {
- auto iter = lower_bound(stk.begin(), stk.end(), nums[i]);
- *iter = nums[i];
- right[i] = iter - stk.begin() + 1;
- }
- }
- int max_item = 0;
- for (int i = 0; i < n; i++)
- if (left[i] >= 2 && right[i] >= 2)
- max_item = max(max_item, left[i] + right[i] - 1);
- return n - max_item;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 3, 1}, n2 = {2, 1, 1, 5, 6, 2, 3, 1};
- printf("%d\n", obj.minimumMountainRemovals(n1)); // expect: 0
- printf("%d\n", obj.minimumMountainRemovals(n2)); // expect: 3
-}
diff --git a/other/min_num_vertices_node.cpp b/other/min_num_vertices_node.cpp
deleted file mode 100644
index 2d53fed..0000000
--- a/other/min_num_vertices_node.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-// 1557. Minimum Number of Vertices to Reach All Nodes
-#include "leetcode.h"
-
-/*
- * given a directed acyclic graph, with 'n' vertices numbered from 0 to 'n - 1',
- * and an array 'edges', where 'edges[i] = [fromi, toi]' representes a directed
- * edge from node 'fromi' to node 'toi'. find the smallest set of vertices from
- * which all nodes in the graph are reachale. it's guaranteed that a unique
- * solution exists. notice you cano return the vertices in any order.
- */
-
-class Solution {
-public:
- vector<int> findSmallestSetOfVertices(int n, vvd & edges) {
- vector<int> ans, seen(n);
- for (auto e : edges)
- seen[e[1]] = 1;
- for (int i = 0; i < n; ++i)
- if (!seen[i])
- ans.push_back(i);
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd e1 = {{0, 1}, {0, 2}, {2, 5}, {3, 4}, {4, 2}};
- vvd e2 = {{0, 1}, {2, 1}, {3, 1}, {1, 4}, {2, 4}};
- for (auto i : obj.findSmallestSetOfVertices(6, e1))
- printf("%d ", i); // expect: 0 3
- printf("\n");
- for (auto i : obj.findSmallestSetOfVertices(5, e2))
- printf("%d ", i); // expect: 0 2 3
-}
diff --git a/other/min_one_bit_0.cpp b/other/min_one_bit_0.cpp
deleted file mode 100644
index 9820ace..0000000
--- a/other/min_one_bit_0.cpp
+++ /dev/null
@@ -1,18 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- unordered_map<int, int> um{{0, 0}};
- inline int bto0(int b) { return (1 << (b + 1)) - 1; }
- int minimumOneBitOperations(int n) {
- if (um.count(n))
- return um[n];
- int b = 31 - __builtin_clz(n);
- return um[n] = bto0(b) - minimumOneBitOperations(n - (1 << b));
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.minimumOneBitOperations(39769175); // expect 4
-}
diff --git a/other/min_one_bit_0.rs b/other/min_one_bit_0.rs
deleted file mode 100644
index 1b52362..0000000
--- a/other/min_one_bit_0.rs
+++ /dev/null
@@ -1,29 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn minimum_one_bit_operations(n: i32) -> i32 {
- if n <= 1 {
- return n;
- }
- let mut max = 1usize;
- while max < n as usize {
- max += max;
- }
- let mut dp = vec![0; max as usize + 1];
- dp[1] = 1;
- let (mut start, mut _i) = (2usize, 1);
- while start < max as usize {
- for i in 0..start / 2 {
- dp[start + i] = dp[start / 2 + i] + start;
- dp[start * 3 / 2 + i] = dp[i] + start;
- }
- start *= 2;
- }
- dp[max] = max * 2 - 1;
- dp[n as usize] as i32
- }
-}
-
-fn main() {
- print!("{}", Solution::minimum_one_bit_operations(39769175));
-}
diff --git a/other/min_operations_x_zero.cpp b/other/min_operations_x_zero.cpp
deleted file mode 100644
index 011839e..0000000
--- a/other/min_operations_x_zero.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minOperations(vector<int> &nums, int x) {
- unordered_map<int, int> left;
- int ans = INT_MAX;
- for (auto i = 0, sum = 0; i < nums.size() && sum <= x; ++i) {
- left[sum] = i;
- sum += nums[i];
- }
- for (int i = nums.size() - 1, sum = 0; i >= 0 && sum <= x; --i) {
- auto it = left.find(x - sum);
- if (it != end(left) && i + 1 >= it->second)
- ans = min(ans, nums.size() - i - 1 + it->second);
- sum += nums[i];
- }
- return ans = INT_MAX ? -1 : ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {1, 1, 4, 2, 3};
- int x = 5;
- cout << obj.minOperations(nums, x);
-}
diff --git a/other/min_path_sum.cpp b/other/min_path_sum.cpp
deleted file mode 100644
index 46c2ff1..0000000
--- a/other/min_path_sum.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-// 64. Minimum Path Sum
-#include "leetcode.h"
-
-// given 'm x n grid' filled with non-negative numbers, find a path from top
-// left to bottom right, which minimises the sum of all numbers along its path
-
-class Solution {
-public:
- int minPathSum(vvd & grid) {
- int m = grid.size(), n = grid[0].size();
- vvd sum(m, vector<int>(n, grid[0][0]));
- for (int i = 1; i < m; i++)
- sum[i][0] = sum[i - 1][0] + grid[i][0];
- for (int j = 1; j < n; j++)
- sum[0][j] = sum[0][j - 1] + grid[0][j];
- for (int i = 1; i < m; i++)
- for (int j = 1; j < n; j++)
- sum[i][j] = min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j];
- return sum[m - 1][n - 1];
- }
-};
-
-int main() {
- Solution obj;
- vvd g1 = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}};
- vvd g2 = {{1, 2, 3}, {4, 5, 6}};
- printf("%d\n", obj.minPathSum(g1)); // expect: 7
- printf("%d\n", obj.minPathSum(g2)); // expect: 12
-}
diff --git a/other/min_rounds_complete_all_tasks.cpp b/other/min_rounds_complete_all_tasks.cpp
deleted file mode 100644
index 0d78073..0000000
--- a/other/min_rounds_complete_all_tasks.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minimumRounds(vector<int> &tasks) {
- unordered_map<int, int> um;
- for (auto i : tasks)
- um[i]++;
- int count = 0;
- for (auto i : um) {
- int t = i.second;
- if (t == 1)
- return -1;
- count += t / 3;
- if (t % 3 != 0)
- count++;
- }
- return count;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> tasks1 = {2, 2, 3, 3, 2, 4, 4, 4, 4, 4}, tasks2 = {2, 3, 3};
- cout << obj.minimumRounds(tasks1) << endl;
- cout << obj.minimumRounds(tasks2) << endl;
-}
diff --git a/other/min_rounds_complete_all_tasks.rs b/other/min_rounds_complete_all_tasks.rs
deleted file mode 100644
index 1c9b7dd..0000000
--- a/other/min_rounds_complete_all_tasks.rs
+++ /dev/null
@@ -1,30 +0,0 @@
-use std::collections::HashMap;
-struct Solution;
-
-impl Solution {
- pub fn minimum_rounds(tasks: Vec<i32>) -> i32 {
- let (mut map, mut ans) = (HashMap::new(), 0);
- for t in tasks {
- let val = map.get_mut(&t);
- if let Some(v) = val {
- *v += 1;
- } else {
- map.insert(t, 1);
- }
- }
- for c in map.into_values() {
- if c == 1 {
- return -1;
- }
- ans += (c + 2) / 3;
- }
- ans
- }
-}
-
-fn main() {
- let tasks1 = vec![2,2,3,3,2,4,4,4,4,4];
- let tasks2 = vec![2,3,3];
- println!("{}", Solution::minimum_rounds(tasks1));
- println!("{}", Solution::minimum_rounds(tasks2));
-}
diff --git a/other/min_score_path_city.cpp b/other/min_score_path_city.cpp
deleted file mode 100644
index 16f4c87..0000000
--- a/other/min_score_path_city.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-// 2492. Minimum Score of a Path Between Two Cities
-#include "leetcode.h"
-
-class Solution {
-public:
- int minScore(int n, vvd & roads) {
- unordered_map<int, unordered_map<int, int>> graph;
- for (auto r : roads)
- graph[r[0]][r[1]] = graph[r[1]][r[0]] = r[2];
- unordered_set<int> vis;
- function<int> dfs;
- dfs = [&](int n) -> int {
- int res = INT_MAX;
- vis.insert(n);
- for (auto [adj, scr] : graph[n]) {
- if (!vis.count(adj))
- res = min(res, dfs(adj));
- res = min(res, scr);
- }
- return res;
- };
- return dfs(1);
- }
-};
-
-int main() {
- Solution obj;
- vvd r1 = {{1, 2, 9}, {2, 3, 6}, {2, 4, 5}, {1, 4, 7}};
- vvd r2 = {{1, 2, 2}, {1, 3, 4}, {3, 4, 7}};
- printf("%d\n", obj.minScore(4, r1)); // expect: 5
- printf("%d\n", obj.minScore(4, r2)); // expect: 2
-}
diff --git a/other/min_size_subarr_sum.cpp b/other/min_size_subarr_sum.cpp
deleted file mode 100644
index 3e54b2b..0000000
--- a/other/min_size_subarr_sum.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-// 209. Minimum Size Subarray Sum
-#include "leetcode.h"
-
-/*
- * given an array of positive integer 'nums' and a positive integer 'target',
- * return the minimal length of a subarray whose sum is greater than or equal to
- * 'target'. if there is no such subarray, return 0 instead.
- */
-
-class Solution {
-public:
- int minSubArrayLen(int target, vector<int> &nums) {
- int i = 0, n = nums.size(), ans = n + 1;
- for (int j = 0; j < n; ++j) {
- target -= nums[j];
- while (target <= 0) {
- ans = min(ans, j - i + 1);
- target += nums[i++];
- }
- }
- return ans % (n + 1);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {2, 3, 1, 2, 4, 3}, n2 = {1, 4, 4},
- n3 = {1, 1, 1, 1, 1, 1, 1, 1};
- printf("%d\n", obj.minSubArrayLen(7, n1)); // expect: 2
- printf("%d\n", obj.minSubArrayLen(4, n2)); // expect: 1
- printf("%d\n", obj.minSubArrayLen(11, n3)); // expect: 0
-}
diff --git a/other/min_speed_arrive_time.cpp b/other/min_speed_arrive_time.cpp
deleted file mode 100644
index 55cfa98..0000000
--- a/other/min_speed_arrive_time.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-// 1870. Minimum Speed to Arrive on Time
-#include "leetcode.h"
-
-/*
- * given a floating point number 'hour', representing the amount of time you
- * have to reach the office. to commute to the office, you must take 'n' trains
- * in sequential order. you are also given an integer array 'dist' of length 'n'
- * where 'dist[i]' describes the distance in kilometres of the i'th train ride.
- * each train can only depart at an integer hour, so you may need to wait in
- * between each ride. return the minimum number speed in km/h that all the
- * trains must travel at for you to reach the office on time, or '-1' if it is
- * possible to be on time.
- */
-
-class Solution {
- bool can_reach_on_time(vector<int> &dist, double hour, int speed) {
- double time = 0;
- for (int i = 0; i < dist.size() - 1; ++i)
- time += ((dist[i] + speed - 1) / speed);
- time += ((double)dist.back()) / speed;
- return time <= hour;
- }
-
-public:
- int minSpeedOnTime(vector<int> dist, double hour) {
- int n = dist.size();
- if (hour <= n - 1)
- return -1;
- int low = 1, high = 1e7, mid;
- while (low < high) {
- mid = (low + high) / 2;
- if (can_reach_on_time(dist, hour, mid))
- high = mid;
- else
- low = mid + 1;
- }
- return high;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> dist = {1, 3, 2};
- printf("%d\n", obj.minSpeedOnTime(dist, 6)); // expect: 1
- printf("%d\n", obj.minSpeedOnTime(dist, 2.7)); // expect: 3
- printf("%d\n", obj.minSpeedOnTime(dist, 1.9)); // expect: -1
-}
diff --git a/other/min_stack.cpp b/other/min_stack.cpp
deleted file mode 100644
index 745c537..0000000
--- a/other/min_stack.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-#include "leetcode.h"
-
-class MinStack {
-public:
- stack<int> st;
- int min = INT_MAX;
- void push(int val) {
- if (min >= val) {
- st.push(min);
- min = val;
- }
- st.push(val);
- }
- void pop() {
- if (min == st.top()) {
- st.pop();
- min = st.top();
- }
- st.pop();
- }
- int top() { return st.top(); }
- int getMin() { return min; }
-};
diff --git a/other/min_swap_group_1.cpp b/other/min_swap_group_1.cpp
deleted file mode 100644
index 89ab5dd..0000000
--- a/other/min_swap_group_1.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 2134. Minimum Swaps to Group All 1's Together II
-#include "leetcode.h"
-
-/*
- * a swap is defined as taking two distinct position in an array and swapping
- * the values in them. a circular array is defined as an array where we consider
- * the first element and the last element to adjacent. given a binary circular
- * array 'nums', return the minimum number of swaps required to group all 1's
- * preent in the array together at any location.
- */
-
-class Solution {
-public:
- int minSwaps(vector<int> &nums) {
- int n = nums.size(), k = 0;
- for (int i = 0; i < n; i++)
- k += (nums[i] == 1);
- nums.insert(nums.end(), nums.begin(), nums.end());
- int ans = n, i = 0, j = 0, l = 0;
- while (j < 2 * n) {
- l += (nums[j] == 1);
- if (j - i + 1 == k) {
- ans = min(ans, k - l);
- l -= (nums[i] == 1);
- i++;
- }
- j++;
- }
- return ans == n ? 0 : ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {0, 1, 0, 1, 1, 0, 0}, n2 = {0, 1, 1, 1, 0, 0, 1, 1, 0},
- n3 = {1, 1, 0, 0, 1};
- printf("%d\n", obj.minSwaps(n1)); // expect: 1
- printf("%d\n", obj.minSwaps(n2)); // expect: 2
- printf("%d\n", obj.minSwaps(n3)); // expect: 0
-}
diff --git a/other/min_time_apples_tree.cpp b/other/min_time_apples_tree.cpp
deleted file mode 100644
index 81d97d7..0000000
--- a/other/min_time_apples_tree.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minTime(int n, vvd & edges, vector<bool> &hasApple) {
- unordered_map<int, int> um;
- int ans = 0;
- sort(edges.begin(), edges.end());
- for (auto const &e : edges) {
- if (um.count(e[1]) > 0)
- um[e[0]] = e[1];
- else
- um[e[1]] = e[0];
- }
- for (int i = 0; i < hasApple.size(); ++i) {
- if (!hasApple[i])
- continue;
- int parent = i;
- while (parent != 0 && um[parent] >= 0) {
- auto tmp = um[parent];
- um[parent] = -1;
- parent = tmp;
- ans += 2;
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd edges = {{0, 1}, {0, 2}, {1, 4}, {1, 5}, {2, 3}, {2, 6}};
- vector<bool> hasApple1 = {false, false, true, false, true, true, false},
- hasApple2 = {false, false, true, false, false, true, false},
- hasApple3 = {false, false, false, false, false, false, false};
- cout << obj.minTime(7, edges, hasApple1) << endl; // expect: 8
- cout << obj.minTime(7, edges, hasApple2) << endl; // expect: 6
- cout << obj.minTime(7, edges, hasApple3) << endl; // expect: 0
-}
diff --git a/other/min_time_apples_tree.rs b/other/min_time_apples_tree.rs
deleted file mode 100644
index 537e5cc..0000000
--- a/other/min_time_apples_tree.rs
+++ /dev/null
@@ -1,47 +0,0 @@
-use std::collections::HashSet;
-struct Solution;
-
-impl Solution {
- pub fn min_time(n: i32, edges: Vec<Vec<i32>>, has_apple: Vec<bool>) -> i32 {
- let mut adj_list: Vec<Vec<i32>> = vec![vec![]; n as usize];
- for e in edges {
- adj_list[e[0] as usize].push(e[1]);
- adj_list[e[1] as usize].push(e[0]);
- }
- let mut total = 0i32;
- let mut vis: HashSet<i32> = HashSet::new();
- Self::dfs(0, adj_list, &mut vis, has_apple, &mut total);
- total
- }
- fn dfs(node: i32, adj_list: Vec<Vec<i32>>, vis: &mut HashSet<i32>,
- has_apple: Vec<bool>, total: &mut i32) -> bool {
- let mut res = false;
- if has_apple[node as usize] {
- res = true;
- }
- vis.insert(node);
- for i in &adj_list[node as usize] {
- if !vis.contains(&i) {
- if Self::dfs(*i, adj_list, vis, has_apple, total) {
- *total += 2;
- res = true;
- }
- }
- }
- res
- }
-}
-
-fn main() {
- let edges = vec![
- vec![0,1], vec![0,2],
- vec![1,4], vec![1,5],
- vec![2,3], vec![2,6]
- ];
- let has_apple1 = vec![false,false,true,false,true,true,false];
- let has_apple2 = vec![false,false,true,false,false,true,false];
- let has_apple3 = vec![false,false,false,false,false,false,false];
- println!("{}", Solution::min_time(7, edges, has_apple1)); //expect: 8
- println!("{}", Solution::min_time(7, edges, has_apple2)); //expect: 6
- println!("{}", Solution::min_time(7, edges, has_apple3)); //expect: 0
-}
diff --git a/other/min_time_complete_trip.cpp b/other/min_time_complete_trip.cpp
deleted file mode 100644
index 2e325a2..0000000
--- a/other/min_time_complete_trip.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-// 2187. Minimum Time to Complete Trips
-#include "leetcode.h"
-
-/*
- * given array 'time' where 'time[i]' denotes the time taken by the 'i'th bus to
- * complete one trip. each bus can make multiple trips successively; that is,
- * the next trip can start immediately after completing the current trip. also,
- * each bus operates independently; that is, the trips of one bus do not
- * influence the trips of any other bus. also given an integer 'totalTrips',
- * which denotes the number of trips all buses should make in total. return the
- * minimum time required to complete all trips.
- */
-
-class Solution {
-public:
- long long minimumTime(vector<int> &time, int totalTrips) {
- long long l = 0, r = LLONG_MAX / time.size();
- while (l < r) {
- long long m = (l + r) / 2, trips = 0;
- for (int t : time)
- trips += m / t;
- if (trips < totalTrips)
- l = m + 1;
- else
- r = m;
- }
- return l;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> t1 = {1, 2, 3}, t2 = {2};
- printf("%lld\n", obj.minimumTime(t1, 5)); // expect: 3
- printf("%lld\n", obj.minimumTime(t2, 1)); // expect: 2
-}
diff --git a/other/min_time_rope_colorful.cpp b/other/min_time_rope_colorful.cpp
deleted file mode 100644
index 9e34c1c..0000000
--- a/other/min_time_rope_colorful.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minCost(string colors, vector<int> &neededTime) {
- int ans = 0, maxCost = 0, sumCost = 0, n = colors.size();
- for (int i = 0; i < n; ++i) {
- if (i > 0 && colors[i] != colors[i - 1]) {
- ans += sumCost - maxCost;
- sumCost = maxCost = 0;
- }
- sumCost += neededTime[i];
- maxCost = max(maxCost, neededTime[i]);
- }
- ans += sumCost - maxCost;
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- string colors = "abaac";
- vector<int> neededTime = {1, 2, 3, 4, 5};
- cout << obj.minCost(colors, neededTime);
-}
diff --git a/other/min_time_visit_cell_grid.cpp b/other/min_time_visit_cell_grid.cpp
deleted file mode 100644
index 58a0099..0000000
--- a/other/min_time_visit_cell_grid.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-// 2577. Minimum Time to Visit a Cell In a Grid
-#include "leetcode.h"
-
-/*
- * you are given an 'm x n' matrix 'grid' consisting of non-negative integers
- * where 'grid[row][col]' represents the minimum time required to be able to
- * visit the cell '(row, col)', which means you can visit the cell '(row, col)'
- * only when the time you visit it is greater than or equal to the value. you
- * are standing in the top left cell of the matrix in the 0th second and you
- * must move to any adjacent cell in the four directions: up, down, left, and
- * right. each move you make takes 1 second. return the minimum time required in
- * which you can visit the bottom right cell of the matrix. if you cannot visit
- * the bottomright cell, then return -1.
- */
-
-class Solution {
-public:
- int minimumTime(vector<vector<int>> &grid) {
- if (grid[0][1] > 1 && grid[1][0] > 1)
- return -1;
- int m = grid.size(), n = grid[0].size();
- vector<vector<int>> dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
- vector<vector<bool>> vis(m, vector<bool>(n, false));
- priority_queue<vector<int>, vector<vector<int>>, greater<>> pq;
- pq.push({grid[0][0], 0, 0});
- while (!pq.empty()) {
- int time = pq.top()[0], row = pq.top()[1], col = pq.top()[2];
- pq.pop();
- if (row == m - 1 && col == n - 1)
- return time;
- if (vis[row][col])
- continue;
- vis[row][col] = true;
- for (auto i : dir) {
- int r = row + i[0], c = col + i[1];
- if (r < 0 || r >= m || c < 0 || c >= n || vis[r][c])
- continue;
- int wait = !((grid[r][c] - time) % 2);
- pq.push({max(grid[r][c] + wait, time + 1), r, c});
- }
- }
- return -1;
- }
-};
-
-int main() {
- Solution obj;
- vvd g1 = {{0, 1, 3, 2}, {5, 1, 2, 5}, {4, 3, 8, 6}},
- g2 = {{0, 2, 4}, {3, 2, 1}, {1, 0, 4}};
- printf("%d\n", obj.minimumTime(g1)); // expect: 7
- printf("%d\n", obj.minimumTime(g2)); // expect: -1
-}
diff --git a/other/min_window_substring.cpp b/other/min_window_substring.cpp
deleted file mode 100644
index c529687..0000000
--- a/other/min_window_substring.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string minWindow(string s, string t) {
- unordered_map<char, int> m1, m2;
- int check = INT_MAX;
- string ans;
- for (char &ch : t)
- m1[ch]++;
- int slow = 0, fast = 0, count = 0;
- for (; fast < s.size(); fast++) {
- char c = s[fast];
- if (m1.find(c) != m1.end()) {
- m2[c]++;
- if (m2[c] <= m1[c])
- count++;
- }
- if (count >= t.size()) {
- while (m1.find(s[slow]) == m1.end() || m2[s[slow]] > m1[s[slow]]) {
- m2[s[slow]]--;
- slow++;
- }
- if (fast - slow + 1 < check) {
- check = fast - slow + 1;
- ans = s.substr(slow, check);
- }
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.minWindow("ADOBECODEBANC", "ABC");
-}
diff --git a/other/min_window_substring.rs b/other/min_window_substring.rs
deleted file mode 100644
index f23402b..0000000
--- a/other/min_window_substring.rs
+++ /dev/null
@@ -1,43 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn min_window(s: String, t: String) -> String {
- let mut state = [0 as isize; (b'z' - b'A' + 1) as usize];
- let mut target = [0 as isize; (b'z' - b'A' + 1) as usize];
- for b in t.bytes() {
- target[(b - b'A') as usize] += 1;
- }
- let (target, string, mut best_from, mut best_to, mut from, mut to, mut chars_found, chars_expected) =
- (target, s.as_bytes(), 0, 0, 0, 0, 0, target.iter().filter(|&&ch| ch > 0).count());
- while to < string.len() {
- let ch = (string[to] - b'A') as usize;
- if target[ch] > 0 {
- if state[ch] + 1 == target[ch] {
- chars_found += 1;
- }
- state[ch] += 1;
- }
- if chars_found == chars_expected {
- let mut fch = (string[from] - b'A') as usize;
- while target[fch] == 0 || state[fch] > target[fch] {
- if state[fch] > 0 {
- state[fch] -= 1;
- }
- from += 1;
- fch = (string[from] - b'A') as usize;
- }
- if to - from < best_to - best_from || best_to == 0 {
- best_from = from;
- best_to = to + 1;
- }
- }
- to += 1;
- }
- s[best_from..best_to].to_string()
- }
-}
-
-fn main() {
- let (s, t) = (String::from("ADOBECODEBANC"), String::from("ABC"));
- print!("{}", Solution::min_window(s, t));
-}
diff --git a/other/mirror_reflection.cpp b/other/mirror_reflection.cpp
deleted file mode 100644
index 447ce5e..0000000
--- a/other/mirror_reflection.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int mirrorReflection(int p, int q) {
- while ((p % 2 == 0) && (q % 2 == 0)) {
- p /= 2;
- q /= 2;
- }
- if ((p % 2) == 0 && (q % 2) != 0)
- return 2;
- if ((p % 2) != 0 && (q % 2) != 0)
- return 1;
- return 0;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.mirrorReflection(2, 1);
-}
diff --git a/other/missing_number.cpp b/other/missing_number.cpp
deleted file mode 100644
index 03dd331..0000000
--- a/other/missing_number.cpp
+++ /dev/null
@@ -1,18 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int missingNumber(vector<int> &nums) {
- int sum = 0, n = nums.size();
- int total = n * (n + 1) / 2;
- for (auto number : nums)
- sum += number;
- return total - sum;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {9, 6, 4, 2, 3, 5, 7, 0, 1};
- cout << obj.missingNumber(nums);
-}
diff --git a/other/modify_graph_edge_weight.cpp b/other/modify_graph_edge_weight.cpp
deleted file mode 100644
index 289098f..0000000
--- a/other/modify_graph_edge_weight.cpp
+++ /dev/null
@@ -1,91 +0,0 @@
-// 2699. Modify Graph Edge Weights
-#include "leetcode.h"
-
-/*
- * you are given an undirected weighted connected graph containing 'n' nodes
- * labeled from '0' to 'n - 1' and an integer array 'edges' where 'edges[i] =
- * [ai, bi, wi]' indicates that there is an edge between nodes 'ai' and 'bi'
- * with weight 'wi'. some edges have a weight of -1 ('wi = -1'), while other
- * have a positive weight ('wi > 0'). your task is to modify all edges with a
- * weight of -1 by assigning them positive integer values in the range '[1, 2 *
- * 10^9]' so that the shortest distance between the nodes 'source' and
- * 'destination' becomes equal to an integer 'target'. if there are multiple
- * modifications that make the shortest distance equal to 'target', any of them
- * are considered correct. return an array containing all edges in any order if
- * it is possible to make the shortest to equal 'target', or an empty array if
- * it is not possible
- */
-
-class Solution {
- array<int, 2> bfs(vector<vector<array<int, 2>>> &adj,
- vector<vector<int>> &edges, int source, int destination,
- int target, bool modify) {
- priority_queue<array<int, 2>, vector<array<int, 2>>, greater<>> pq;
- vector<int> dist(adj.size(), INT_MAX), mod_id(adj.size(), INT_MAX);
- pq.push({0, source});
- dist[source] = 0;
- while (!pq.empty() && pq.top()[1] != destination) {
- auto [d, i] = pq.top();
- pq.pop();
- if (d != dist[i])
- continue;
- for (auto [j, edge_id] : adj[i]) {
- int w = edges[edge_id][2];
- if (modify || w != -1)
- if (dist[j] > d + max(1, w)) {
- mod_id[j] = w == -1 ? edge_id : mod_id[i];
- dist[j] = d + max(1, w);
- pq.push({d + max(1, w), j});
- }
- }
- }
- return {dist[destination], mod_id[destination]};
- }
-
-public:
- vector<vector<int>> modifiedGraphEdges(int n, vector<vector<int>> &edges,
- int source, int destination,
- int target) {
- vector<vector<array<int, 2>>> adj(n);
- for (int i = 0; i < edges.size(); ++i) {
- adj[edges[i][0]].push_back({edges[i][1], i});
- adj[edges[i][1]].push_back({edges[i][0], i});
- }
- auto [dist, _] = bfs(adj, edges, source, destination, target, false);
- if (dist < target)
- return {};
- while (true) {
- auto [dist, mod_id] = bfs(adj, edges, source, destination, target, true);
- if (dist > target)
- return {};
- if (dist == target)
- break;
- edges[mod_id][2] = 1 + target - dist;
- }
- for (auto &e : edges)
- e[2] = e[2] == -1 ? 1 : e[2];
- return edges;
- }
-};
-
-int main() {
- Solution obj;
- vvd e1 = {{4, 1, -1}, {2, 0, -1}, {0, 3, -1}, {4, 3, -1}},
- e2 = {{0, 1, -1}, {0, 2, 5}},
- e3 = {{1, 0, 4}, {1, 2, 3}, {2, 3, 5}, {0, 3, -1}};
- vvd mge1 = obj.modifiedGraphEdges(5, e1, 0, 1, 5),
- mge2 = obj.modifiedGraphEdges(3, e2, 0, 2, 6),
- mge3 = obj.modifiedGraphEdges(4, e3, 0, 2, 6);
- for (int i = 0; i < mge1.size(); i++)
- for (int j = 0; j < mge1[0].size(); j++)
- printf("%d ", mge1[i][j]); // expect: [[4,1,1],[2,0,1],[0,3,3],[4,3,1]]
- printf("\n");
- for (int i = 0; i < mge2.size(); i++)
- for (int j = 0; j < mge2[0].size(); j++)
- printf("%d ", mge2[i][j]); // expect: []
- printf("\n");
- for (int i = 0; i < mge3.size(); i++)
- for (int j = 0; j < mge3[0].size(); j++)
- printf("%d ", mge3[i][j]); // expect: [[1,0,4],[1,2,3],[2,3,5],[0,3,1]]
- printf("\n");
-}
diff --git a/other/most_stones_remove.cpp b/other/most_stones_remove.cpp
deleted file mode 100644
index 97499f8..0000000
--- a/other/most_stones_remove.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-// 947. Most Stones Removed with Same Row or Column
-#include "leetcode.h"
-
-/*
- * on a 2d plane, we place 'n' stones at some integer coordinate points. each
- * coordinate point may have at most one stone. a stone can be removed if it
- * shares either the same row or the same column as another stone that has not
- * been removed. given an array 'stones' of length 'n' where 'stones[i] = [x_i,
- * y_i]' represents the location of the i'th stone, return the largest possible
- * number of stones that can be removed
- */
-
-class Solution {
-public:
- int removeStones(vector<vector<int>> &stones) {
- int n = stones.size(), c = 0;
- unordered_map<int, vector<int>> rows, cols;
- for (int i = 0; i < n; ++i) {
- rows[stones[i][0]].push_back(i);
- cols[stones[i][1]].push_back(i);
- }
- unordered_set<int> seen;
- function<int> dfs;
- dfs = [&](int i) -> int {
- if (seen.count(i))
- return 0;
- seen.insert(i);
- int j = stones[i][0], k = stones[i][1];
- for (auto r : rows[j])
- dfs(r);
- for (auto c : cols[k])
- dfs(c);
- return 1;
- };
- for (int i = 0; i < n; ++i)
- c += dfs(i);
- return n - c;
- }
-};
-
-int main() {
- Solution obj;
- vvd s1 = {{0, 0}, {0, 1}, {1, 0}, {1, 2}, {2, 1}, {2, 2}},
- s2 = {{0, 1}, {0, 2}, {1, 1}, {2, 0}, {2, 2}};
- printf("%d\n", obj.removeStones(s1)); // expect: 5
- printf("%d\n", obj.removeStones(s2)); // expect: 3
-}
diff --git a/other/most_stones_remove.rs b/other/most_stones_remove.rs
deleted file mode 100644
index d32137f..0000000
--- a/other/most_stones_remove.rs
+++ /dev/null
@@ -1,69 +0,0 @@
-// 947. Most Stones Removed with Same Row or Column
-
-/*
- * on a 2d plane, we place 'n' stones at some integer coordinate points. each
- * coordinate point may have at most one stone. a stone can be removed if it
- * shares either the same row or the same column as another stone that has not
- * been removed. given an array 'stones' of length 'n' where 'stones[i] = [x_i,
- * y_i]' represents the location of the i'th stone, return the largest possible
- * number of stones that can be removed
- */
-
-use std::collections::HashMap;
-struct Solution;
-
-impl Solution {
- pub fn remove_stones(stones: Vec<Vec<i32>>) -> i32 {
- let mut ans = 0;
- let mut parent: Vec<usize> = (0..stones.len()).collect();
- let mut rows: HashMap<i32, usize> = HashMap::new();
- let mut cols: HashMap<i32, usize> = HashMap::new();
- for (i, v) in stones.iter().enumerate() {
- match rows.get(&v[0]) {
- Some(&j) => {
- if Self::union_stone(i, j, &mut parent) {
- ans += 1;
- }
- }
- None => {
- rows.insert(v[0], i);
- }
- }
- match cols.get(&v[1]) {
- Some(&j) => {
- if Self::union_stone(i, j, &mut parent) {
- ans += 1;
- }
- }
- None => {
- cols.insert(v[1], i);
- }
- }
- }
- ans
- }
- fn union_stone(i: usize, j: usize, parent: &mut Vec<usize>) -> bool {
- let i_root = Self::find_set(i, parent);
- let j_root = Self::find_set(j, parent);
- parent[i_root] = j_root;
- i_root != j_root
- }
- fn find_set(x: usize, parent: &mut Vec<usize>) -> usize {
- if x != parent[x] {
- parent[x] = Self::find_set(parent[x], parent);
- }
- parent[x]
- }
-}
-
-fn main() {
- let stones = vec![
- vec![0, 0],
- vec![0, 1],
- vec![1, 0],
- vec![1, 2],
- vec![2, 1],
- vec![2, 2],
- ];
- print!("{}", Solution::remove_stones(stones));
-}
diff --git a/other/most_water.cpp b/other/most_water.cpp
deleted file mode 100644
index 89d4e19..0000000
--- a/other/most_water.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#include <bits/stdc++.h>
-using namespace std;
-
-class Solution {
-public:
- int maxArea(vector<int> &height) {
- int start = 0, max = 0, end = height.size() - 1;
- while (start < end) {
- int x = end - start;
- int y = height[start] > height[end] ? height[end] : height[start];
- max = (x * y) > max ? (x * y) : max;
- if (height[start] > height[end])
- end--;
- else
- start++;
- }
- return max;
- }
-};
-
-int main() {}
diff --git a/other/my_calendar.cpp b/other/my_calendar.cpp
deleted file mode 100644
index 472884e..0000000
--- a/other/my_calendar.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-// 729. My Calendar I
-#include "leetcode.h"
-
-/*
- * you are implementing a program to use as your calendar. we can add a new
- * event if adding the event will not cause a double booking. a double booking
- * happens when two events have some non empty intersection (ie. some moment is
- * common to both events.). the event can be represented as a pair of integers
- * 'start' and 'end' that represent a booking on the half open interval '[start,
- * end)', the range of real numbers 'x' such that 'start <= x < end'.
- */
-
-class MyCalendar {
- vector<pair<int, int>> books;
-
-public:
- bool book(int start, int end) {
- for (pair<int, int> p : books)
- if (max(p.first, start) < min(end, p.second))
- return false;
- books.push_back({start, end});
- return true;
- }
-};
-
-int main() {
- MyCalendar *obj = new MyCalendar();
- printf("%d\n", obj->book(10, 20)); // expect: 1
- printf("%d\n", obj->book(15, 25)); // expect: 0
- printf("%d\n", obj->book(20, 30)); // expect: 1
-}
diff --git a/other/my_calendar2.cpp b/other/my_calendar2.cpp
deleted file mode 100644
index 2012a35..0000000
--- a/other/my_calendar2.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-// 731. My Calendar II
-#include "leetcode.h"
-
-/*
- * you are implementing a program to use as your calendar. we can add a new
- * event if adding the event will not cause a triple booking. a triple booking
- * happens when three events have the same non empty intersection (ie. some
- * moment is common to all the three event). the event can be represented as a
- * pair of integers 'start' and 'end' that represents a booking on the half open
- * interval '[start, end]', the range of real numbers 'x' such that 'start <= x
- * < end'.
- */
-
-class MyCalendar {
- vector<pair<int, int>> books;
-
-public:
- bool book(int start, int end) {
- for (pair<int, int> p : books)
- if (max(p.first, start) < min(end, p.second))
- return false;
- books.push_back({start, end});
- return true;
- }
-};
-
-class MyCalendarTwo {
- vector<pair<int, int>> books;
-
-public:
- bool book(int start, int end) {
- MyCalendar overlaps;
- for (pair<int, int> p : books)
- if (max(p.first, start) < min(end, p.second)) {
- pair<int, int> overlapped = getOverlap(p.first, p.second, start, end);
- if (!overlaps.book(overlapped.first, overlapped.second))
- return false;
- }
- books.push_back({start, end});
- return true;
- }
- pair<int, int> getOverlap(int s0, int e0, int s1, int e1) {
- return {max(s0, s1), min(e0, e1)};
- }
-};
-
-int main() {
- MyCalendarTwo *obj = new MyCalendarTwo();
- printf("%d\n", obj->book(10, 20)); // expect: 1
- printf("%d\n", obj->book(50, 60)); // expect: 1
- printf("%d\n", obj->book(10, 40)); // expect: 1
- printf("%d\n", obj->book(5, 15)); // expect: 0
- printf("%d\n", obj->book(5, 10)); // expect: 1
- printf("%d\n", obj->book(25, 55)); // expect: 1
- delete obj;
-}
diff --git a/other/my_calendar3.cpp b/other/my_calendar3.cpp
deleted file mode 100644
index 25de075..0000000
--- a/other/my_calendar3.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#include "leetcode.h"
-
-class MyCalendarThree {
-public:
- map<int, int> count = {{-1, 0}};
- int ans = 0;
- MyCalendarThree() {}
- int book(int start, int end) {
- auto s = count.emplace(start, (--count.upper_bound(start))->second);
- auto e = count.emplace(end, (--count.upper_bound(end))->second);
- for (auto i = s.first; i != e.first; ++i)
- ans = max(ans, ++(i->second));
- return ans;
- }
-};
-
-int main() {
- int start, end;
- MyCalendarThree *obj = new MyCalendarThree();
- int param_1 = obj->book(start, end);
-}
diff --git a/other/n_ary_tree_traverse.cpp b/other/n_ary_tree_traverse.cpp
deleted file mode 100644
index 9c89682..0000000
--- a/other/n_ary_tree_traverse.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vvd levelOrder(Node *root) {
- vvd ans;
- if (!root)
- return ans;
- queue<Node *> q;
- q.push(root);
- while (!q.empty()) {
- int n = q.size();
- vector<int> v;
- while (n--) {
- auto curr = q.front();
- q.pop();
- v.push_back(curr->val);
- for (auto it : curr->children)
- q.push(it);
- }
- ans.push_back(v);
- }
- return ans;
- }
-};
diff --git a/other/n_queens2.cpp b/other/n_queens2.cpp
deleted file mode 100644
index 2af1bcd..0000000
--- a/other/n_queens2.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int totalNQueens(int n) {
- vector<bool> col(n, true);
- vector<bool> anti(2 * n - 1, true);
- vector<bool> main(2 * n - 1, true);
- vector<int> row(n, 0);
- int count = 0;
- helper(0, row, col, main, anti, count);
- return count;
- }
-
-private:
- void helper(int i, vector<int> &row, vector<bool> &col, vector<bool> &main,
- vector<bool> &anti, int &count) {
- if (i == row.size()) {
- count++;
- return;
- }
- for (int j = 0; j < col.size(); j++)
- if (col[j] && main[i + j] && anti[i + col.size() - 1 - j]) {
- row[i] = j;
- col[j] = main[i + j] = anti[i + col.size() - 1 - j] = false;
- helper(i + 1, row, col, main, anti, count);
- col[j] = main[i + j] = anti[i + col.size() - 1 - j] = true;
- }
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.totalNQueens(4);
-}
diff --git a/other/naming_company.cpp b/other/naming_company.cpp
deleted file mode 100644
index 24de89f..0000000
--- a/other/naming_company.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// 2306. Naming a Company
-#include "leetcode.h"
-
-/*
- * you are given an array of strings 'ideas' that represents a list of names to
- * be used in the process o naming a company. the process of naming a company is
- * as follows: chose 2 distinct names from 'ideas', call them 'ideaa, ideab'.
- * swap the first letters of 'ideaa & ideab' with each other.
- * if both the new names are not found in the original 'ideas', then the name
- * 'ideaa ideab' (concatenated, separated by space) is a valid company name.
- */
-
-class Solution {
-public:
- long long distinctNames(vector<string> &ideas) {
- long long ans = 0, cnt[26][26] = {};
- unordered_set<string> us[26];
- for (auto &i : ideas)
- us[i[0] - 'a'].insert(i.substr(1));
- for (int i = 0; i < 26; ++i)
- for (auto &suffix : us[i])
- for (int j = 0; j < 26; ++j)
- cnt[i][j] += us[j].count(suffix) == 0;
- for (int i = 0; i < 26; ++i)
- for (int j = 0; j < 26; ++j)
- ans += cnt[i][j] * cnt[j][i];
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<string> ideas1 = {"coffee", "donuts", "time", "toffee"},
- ideas2 = {"lack", "back"};
- cout << obj.distinctNames(ideas1) << endl; // expect: 6
- cout << obj.distinctNames(ideas2) << endl; // expect: 0
-}
diff --git a/other/nearest_exit_maze.cpp b/other/nearest_exit_maze.cpp
deleted file mode 100644
index 2e0a4cf..0000000
--- a/other/nearest_exit_maze.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int nearestExit(vvd(char) & maze, vector<int> &entrance) {
- int m = maze.size(), n = maze[0].size();
- int dirs[5] = {0, -1, 0, 1, 0};
- auto isExit = [&](int i, int j) -> int {
- return (i != entrance[0] || j != entrance[1]) &&
- (i * j == 0 || i == m - 1 || j == n - 1);
- };
- deque<array<int, 3>> dqa = {{entrance[0], entrance[1], 0}};
- while (!dqa.empty()) {
- auto [i, j, s] = dqa.front();
- dqa.pop_front();
- for (int d = 0; d < 4; ++d) {
- int i2 = i + dirs[d];
- int j2 = j + dirs[d + 1];
- if (i2 < 0 || i2 >= m || j2 < 0 || j2 >= n || maze[i2][j2] == '+')
- continue;
- maze[i2][j2] = '+';
- if (isExit(i2, j2))
- return s + 1;
- dqa.push_back({i2, j2, s + 1});
- }
- }
- return -1;
- }
-};
-
-int main() {
- Solution obj;
- vvd(char)
- maze = {{'+', '+', '.', '+'}, {'.', '.', '.', '+'}, {'+', '+', '+', '.'}};
- vector<int> entrance = {1, 2};
- cout << obj.nearestExit(maze, entrance);
-}
diff --git a/other/nearest_exit_maze.rs b/other/nearest_exit_maze.rs
deleted file mode 100644
index 3f314f2..0000000
--- a/other/nearest_exit_maze.rs
+++ /dev/null
@@ -1,37 +0,0 @@
-use std::collections::VecDeque;
-use std::collections::HashSet;
-struct Solution;
-
-impl Solution {
- pub fn nearest_exit(maze: Vec<Vec<char>>, entrance: Vec<i32>) -> i32 {
- let (mut dq, mut visited) = (VecDeque::new(), HashSet::new());
- dq.push_back((entrance[0] as usize, entrance[1] as usize, 0));
- while !dq.is_empty() {
- while let Some((i, j, c)) = dq.pop_front() {
- if !visited.insert((i, j)) {
- continue;
- }
- if i == 0 || i == maze.len() - 1 || j == 0 || j == maze[0].len() - 1 {
- if i != entrance[0] as usize || j != entrance[1] as usize {
- return c;
- }
- }
- if maze[i][j] == '.' {
- if i > 0 && maze[i - 1][j] == '.' {
- dq.push_back((i - 1, j, c + 1));
- }
- if i < maze.len() - 1 && maze[i + 1][j] == '.' {
- dq.push_back((i + 1, j, c + 1));
- }
- if j > 0 && maze[i][j - 1] == '.' {
- dq.push_back((i, j - 1, c + 1));
- }
- if j < maze[0].len() - 1 && maze[i][j + 1] == '.' {
- dq.push_back((i, j + 1, c + 1));
- }
- }
- }
- }
- -1
- }
-}
diff --git a/other/new_21_game.cpp b/other/new_21_game.cpp
deleted file mode 100644
index dc21609..0000000
--- a/other/new_21_game.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 837. New 21 Game
-#include "leetcode.h"
-
-/*
- * alice plays the following game, loosely based on the card game "21". alice
- * starts with 0 points and draws numbers while she has less than 'k' points.
- * during each draw, she gains an integer number of points randomly from range
- * '[1, max_pts]', where 'max_pts' is an integer. each draw is independent and
- * the outcomes have equal posibilities. alice stops drawing numbers when she
- * gets 'k' or more points. return the probability that alice has 'n' or fewer
- * points. answers within 10^-5 of the actual answer are considered accepted
- */
-
-class Solution {
-public:
- double new21Game(int n, int k, int max_pts) {
- if (!k || n >= k + max_pts)
- return 1.0;
- vector<double> dp(n + 1);
- dp[0] = 1.0;
- double sum = 1.0, ans = 0.0;
- for (int i = 1; i <= n; ++i) {
- dp[i] = sum / max_pts;
- if (i < k)
- sum += dp[i];
- else
- ans += dp[i];
- if (i - max_pts >= 0)
- sum -= dp[i - max_pts];
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- printf("%f\n", obj.new21Game(10, 1, 10)); // expect: 1.00000
- printf("%f\n", obj.new21Game(6, 1, 10)); // expect: 0.60000
- printf("%f\n", obj.new21Game(21, 17, 10)); // expect: 0.73278
-}
diff --git a/other/next_greater_element2.cpp b/other/next_greater_element2.cpp
deleted file mode 100644
index c6a8412..0000000
--- a/other/next_greater_element2.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-// 503. Next Greater Element II
-#include "leetcode.h"
-
-/*
- * given a circular integer array 'nums' (ie. the next element 'nums[nums.length
- * - 1]' is 'nums[0]') return the next greater number for every element in
- * 'nums'. the next greater number of a number 'x' is the first greater number
- * to its traversing-order next in the array, which means you could search
- * circularly to find its next greater number. if it doesn't exist, return -1
- */
-
-class Solution {
-public:
- vector<int> nextGreatestElements(vector<int> &nums) {
- int n = nums.size();
- nums.resize(n * 2);
- for (int i = n; i < n * 2; i++)
- nums[i] = nums[i - n];
- vector<int> ans(n, -1);
- stack<int> s;
- for (int i = 0; i < n * 2; i++) {
- int elem = nums[i];
- while (!s.empty() && elem > nums[s.top()]) {
- if (s.top() >= n)
- s.top() = s.top() - n;
- ans[s.top()] = elem;
- s.pop();
- }
- s.push(i);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 2, 1}, n2 = {1, 2, 3, 4, 3};
- for (auto i : obj.nextGreatestElements(n1))
- printf("%d ", i); // expect: 2 -1 2
- printf("\n");
- for (auto i : obj.nextGreatestElements(n2))
- printf("%d ", i); // expect: 2 3 4 -1 4
-}
diff --git a/other/next_permutation.cpp b/other/next_permutation.cpp
deleted file mode 100644
index 95e70f4..0000000
--- a/other/next_permutation.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-#include <bits/stdc++.h>
-#include <vector>
-using namespace std;
-
-class Solution {
-public:
- void nextPermutation(vector<int> &nums) {
- int i = nums.size() - 2;
- while (i >= 0 && nums[i + 1] <= nums[i])
- i--;
- if (i >= 0) {
- int j = nums.size() - 1;
- while (nums[j] <= nums[i])
- j--;
- swap(nums, i, j);
- }
- reverse(nums, i + 1);
- }
-
-private:
- void reverse(vector<int> &nums, int start) {
- int i = start, j = nums.size() - 1;
- while (i < j) {
- swap(nums, i, j);
- i++;
- j--;
- }
- }
-
- void swap(vector<int> &nums, int i, int j) {
- int temp = nums[i];
- nums[i] = nums[j];
- nums[j] = temp;
- }
-};
-
-int main() {}
diff --git a/other/non_decreasing_array.cpp b/other/non_decreasing_array.cpp
deleted file mode 100644
index 6ea4280..0000000
--- a/other/non_decreasing_array.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool checkPossibility(vector<int> &nums) {
- for (int i = 0; i < nums.size() - 1; i++) {
- if (nums[i] > nums[i + 1]) {
- if (i - 1 >= 0 && nums[i - 1] > nums[i + 1])
- nums[i + 1] = nums[i];
- else
- nums[i] = nums[i + 1];
- break;
- }
- }
- for (int i = 0; i < nums.size() - 1; i++) {
- if (nums[i] > nums[i + 1])
- return false;
- }
- return true;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {4, 2, 3};
- cout << obj.checkPossibility(nums);
-}
diff --git a/other/non_decreasing_subseq.cpp b/other/non_decreasing_subseq.cpp
deleted file mode 100644
index b94510f..0000000
--- a/other/non_decreasing_subseq.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-// 491. Non-decreasing Subsequences
-#include "leetcode.h"
-
-/*
- * given: integer array 'nums'
- * return: all possible different non-decreasing subsequences
- * of given array with at least two elements. return value
- * can be in any order
- */
-
-class Solution {
-public:
- vector<vector<int>> findSubsequences(vector<int> &nums) {
- set<vector<int>> seqs = {vector<int>(0)};
- for (int i = 0; i < nums.size(); i++) {
- vector<vector<int>> built(seqs.size());
- copy(seqs.begin(), seqs.end(), built.begin());
- for (auto s : built)
- if (s.empty() || nums[i] >= s.back()) {
- s.push_back(nums[i]);
- seqs.insert(s);
- }
- }
- vector<vector<int>> ans;
- for (auto s : seqs)
- if (s.size() > 1)
- ans.push_back(s);
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {4, 6, 7, 7}, n2 = {4, 4, 3, 2, 1};
- for (auto i : obj.findSubsequences(n1)) {
- for (auto j : i)
- printf("%d ", j);
- printf("\n");
- }
- printf("\n");
- for (auto i : obj.findSubsequences(n2)) {
- for (auto j : i)
- printf("%d ", j);
- printf("\n");
- }
-}
diff --git a/other/non_overlapping_interval.cpp b/other/non_overlapping_interval.cpp
deleted file mode 100644
index 228f691..0000000
--- a/other/non_overlapping_interval.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-// 435. Non-overlapping Intervals
-#include "leetcode.h"
-
-/*
- * given an array of intervals 'intervals' where 'intervals[i] = [start[i],
- * end[i]]', return the minimum number of intervals you need to remove to make
- * the rest of the intervals non-overlapping
- */
-
-class Solution {
- static bool cmp(vector<int> &a, vector<int> &b) { return a[1] < b[1]; }
-
-public:
- int eraseOverlapIntervals(vvd & intervals) {
- int ans = -1;
- if (!intervals.size())
- return 0;
- sort(intervals.begin(), intervals.end(), cmp);
- vector<int> prev = intervals[0];
- for (vector<int> i : intervals) {
- if (prev[1] > i[0])
- ans++;
- else
- prev = i;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd i1 = {{1, 2}, {2, 3}, {3, 4}, {1, 3}};
- vvd i2 = {{1, 2}, {1, 2}, {1, 2}};
- vvd i3 = {{1, 2}, {2, 3}};
- printf("%d\n", obj.eraseOverlapIntervals(i1)); // expect: 1
- printf("%d\n", obj.eraseOverlapIntervals(i2)); // expect: 2
- printf("%d\n", obj.eraseOverlapIntervals(i3)); // expect: 0
-}
diff --git a/other/nth_tribonacci_number.cpp b/other/nth_tribonacci_number.cpp
deleted file mode 100644
index cabdb39..0000000
--- a/other/nth_tribonacci_number.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-// 1137. N-th Tribonacci Number
-#include "leetcode.h"
-
-/*
- * the tribonacci sequence t^n is defined as follows
- * t0 = 0, t1 = 1, t2 = 1, & tn+3 = tn + tn+1 + tn+2 for n >= 0
- * given n, return value of tn
- * eg.
- * n = 4, output: 4
- * t3 = 0 + 1 + 1 = 2
- * t4 = 1 + 1 + 2 = 4
- */
-
-typedef long long ll;
-struct Matrix {
- vvd(ll) a;
- int rows, cols;
- Matrix(int rows = 0, int cols = 0) : rows(rows), cols(cols) {
- a.resize(rows);
- for (int i = 0; i < rows; ++i)
- a[i].assign(cols, 0);
- }
- Matrix(const vvd(ll) & matrix)
- : a(matrix), rows(matrix.size()), cols(matrix[0].size()) {}
-};
-
-Matrix operator*(const Matrix &a, const Matrix &b) {
- Matrix res(a.rows, b.cols);
- for (int i = 0; i < a.rows; ++i)
- for (int j = 0; j < b.cols; ++j)
- for (int k = 0; k < a.cols; ++k)
- res.a[i][j] += a.a[i][k] * b.a[k][j];
- return res;
-}
-
-Matrix fastPow(const Matrix &matrix, int pow) {
- if (pow == 1)
- return matrix;
- Matrix half = fastPow(matrix, pow / 2);
- if (pow & 1)
- return half * half * matrix;
- return half * half;
-}
-
-class Solution {
-public:
- int tribonacci(int n) {
- if (n == 0)
- return 0;
- Matrix m({{0, 1, 0}, {0, 0, 1}, {1, 1, 1}});
- Matrix m0({{0}, {1}, {1}});
- Matrix mn = fastPow(m, n) * m0;
- return mn.a[0][0];
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.tribonacci(4) << endl; // expect: 4
- cout << obj.tribonacci(25) << endl; // expect: 1389537
-}
diff --git a/other/num_bad_pairs.cpp b/other/num_bad_pairs.cpp
deleted file mode 100644
index 144e6ef..0000000
--- a/other/num_bad_pairs.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-// 2364. Count Number of Bad Pairs
-#include "leetcode.h"
-
-/*
- * you are given a 0-indexed integer array 'nums'. a pair of indices '(i, j)' is
- * a bad pair if 'i < j' and 'j - i != nums[j] - nums[i]'. return the total
- * number of bad pairs in 'nums'.
- */
-
-class Solution {
-public:
- long long countBadPairs(vector<int> &nums) {
- long long ans = 0;
- unordered_map<int, int> mp;
- for (int i = 0; i < nums.size(); ++i) {
- ans += i - mp[nums[i] - i];
- mp[nums[i] - i]++;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {4, 1, 3, 3}, n2 = {1, 2, 3, 4, 5};
- printf("%lld\n", obj.countBadPairs(n1)); // expect: 5
- printf("%lld\n", obj.countBadPairs(n2)); // expect: 0
-}
diff --git a/other/num_bad_pairs.rs b/other/num_bad_pairs.rs
deleted file mode 100644
index 88119d8..0000000
--- a/other/num_bad_pairs.rs
+++ /dev/null
@@ -1,30 +0,0 @@
-// 2364. Count Number of Bad Pairs
-use std::collections::HashMap;
-struct Solution;
-
-/*
- * you are given a 0-indexed integer array 'nums'. a pair of indices '(i, j)' is
- * a bad pair if 'i < j' and 'j - i != nums[j] - nums[i]'. return the total
- * number of bad pairs in 'nums'.
- */
-
-impl Solution {
- pub fn count_bad_pairs(nums: Vec<i32>) -> i64 {
- let mut hm: HashMap<i32, i32> = HashMap::with_capacity(nums.len());
- let mut ans = 0;
- nums.iter().zip(0..).for_each(|(&x, i)| {
- let delta = x - i;
- let e = hm.entry(delta).or_default();
- ans += (i - *e) as i64;
- *e += 1;
- });
- ans
- }
-}
-
-fn main() {
- let n1 = vec![4, 1, 3, 3];
- let n2 = vec![1, 2, 3, 4, 5];
- println!("{}", Solution::count_bad_pairs(n1)); //expect: 5
- println!("{}", Solution::count_bad_pairs(n2)); //expect: 0
-}
diff --git a/other/num_closed_islands.cpp b/other/num_closed_islands.cpp
deleted file mode 100644
index ba0635c..0000000
--- a/other/num_closed_islands.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-// 1254. Number of Closed Islands
-#include "leetcode.h"
-
-/*
- * given 2d 'grid' consists of 0's (land) and 1's (water). an island is a
- * maximal four directionally connected group of 0's and a closed island is an
- * island totally (all left, top, right, bottom) surrouned by 1's. return the
- * number of closed islands.
- */
-
-class Solution {
- int dx[4] = {0, 0, -1, 1}, dy[4] = {1, -1, 0, 0};
- bool is_valid(vvd & grid, int i, int j, int r, int c) {
- if (i >= 0 && i < r && j >= 0 && j < c && grid[i][j] == 0)
- return true;
- else
- return false;
- }
- void dfs(vvd & grid, int i, int j, int r, int c) {
- grid[i][j] = 1;
- for (int x = 0; x < 4; ++x) {
- int new_x = i + dx[x];
- int new_y = i + dy[x];
- if (is_valid(grid, new_x, new_y, r, c))
- dfs(grid, new_x, new_y, r, c);
- }
- }
-
-public:
- int closedIsland(vvd & grid) {
- int r = grid.size(), c = grid[0].size(), ans = 0;
- for (int i = 0; i < r; ++i)
- for (int j = 0; j < c; ++j)
- if (i * j == 0 || i == r - 1 || j == c - 1)
- if (grid[i][j] == 0)
- dfs(grid, i, j, r, c);
- for (int i = 0; i < r; ++i)
- for (int j = 0; j < c; ++j)
- if (grid[i][j] == 0) {
- ans++;
- dfs(grid, i, j, r, c);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd g1 = {{1, 1, 1, 1, 1, 1, 1, 0},
- {1, 0, 0, 0, 0, 1, 1, 0},
- {1, 0, 0, 0, 0, 1, 0, 1},
- {1, 1, 1, 1, 1, 1, 1, 0}};
- vvd g2 = {{0, 0, 1, 0, 0}, {0, 1, 0, 1, 0}};
- vvd
- g3 = {{1, 1, 1, 1, 1, 1, 1}, {1, 0, 0, 0, 0, 0, 1}, {1, 0, 1, 1, 1, 0, 1},
- {1, 0, 1, 0, 1, 0, 1}, {1, 0, 1, 1, 1, 0, 1}, {1, 0, 0, 0, 0, 0, 1},
- {1, 1, 1, 1, 1, 1, 1}};
- printf("%d\n", obj.closedIsland(g1)); // expect: 2
- printf("%d\n", obj.closedIsland(g2)); // expect: 1
- printf("%d\n", obj.closedIsland(g3)); // expect: 2
-}
diff --git a/other/num_cut_pizza.cpp b/other/num_cut_pizza.cpp
deleted file mode 100644
index 526e21d..0000000
--- a/other/num_cut_pizza.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-// 1444. Number of Ways of Cutting a Pizza
-#include "leetcode.h"
-
-/*
- * given rectangular pizza represented as a rows x cols matrix containing the
- * following characters 'A' an apple and '.' empty cell, and given integer 'k'.
- * you have to cut the pizza into 'k' pieces using 'k - 1' cuts.
- */
-
-class Solution {
- void add(long &a, long &b) { a = (a + b) % (1e9 + 7); }
-
-public:
- int ways(vector<string> &pizza, int k) {
- int m = pizza.size(), n = pizza[0].size();
- vvd cnt(m + 1, vector<int>(n + 1));
- for (int i = m - 1; i >= 0; --i) {
- int s = 0;
- for (int j = n - 1; j >= 0; --j) {
- s += pizza[i][j] == 'A';
- cnt[i][j] = cnt[i + 1][j] + s;
- }
- }
- vvd(vector<long>) dp(m + 1, vvd(long)(n + 1, vector<long>(k + 1)));
- for (int i = m - 1; i >= 0; --i) {
- for (int j = n - 1; j >= 0; --j) {
- dp[i][j][1] = cnt[i][j] > 0;
- for (int p = 2; p <= k; ++p) {
- for (int q = i + 1; q < m; ++q) {
- if (cnt[i][j] == cnt[q][j])
- continue;
- if (cnt[q][j] == 0)
- break;
- add(dp[i][j][p], dp[q][j][p - 1]);
- }
- for (int q = j + 1; q < n; ++q) {
- if (cnt[i][j] == cnt[i][q])
- continue;
- if (cnt[i][q] == 0)
- break;
- add(dp[i][j][p], dp[i][q][p - 1]);
- }
- }
- }
- }
- return dp[0][0][k];
- }
-};
-
-int main() {
- Solution obj;
- vector<string> p1 = {"A..", "AAA", "..."};
- vector<string> p2 = {"A..", "AA.", "..."};
- vector<string> p3 = {"A..", "A..", "..."};
- printf("%d\n", obj.ways(p1, 3)); // expect: 3
- printf("%d\n", obj.ways(p2, 3)); // expect: 1
- printf("%d\n", obj.ways(p3, 1)); // expect: 1
-}
diff --git a/other/num_dice_roll_target_sum.cpp b/other/num_dice_roll_target_sum.cpp
deleted file mode 100644
index abb7596..0000000
--- a/other/num_dice_roll_target_sum.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int numRollsToTarget(int n, int k, int target) {
- int mod = 1000000007;
- vvd dp(n + 1, vector<int>(target + 1, 0));
- dp[0][0] = 1;
- for (int i = 1; i <= n; i++)
- for (int j = 1; j <= target; j++)
- for (int x = 1; x <= k; x++)
- if (x <= j)
- dp[i][j] = ((dp[i][j] % mod) + (dp[i - 1][j - x] % mod)) % mod;
- return dp[n][target];
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.numRollsToTarget(1, 6, 3);
-}
diff --git a/other/num_enclaves.cpp b/other/num_enclaves.cpp
deleted file mode 100644
index 2629d65..0000000
--- a/other/num_enclaves.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-// 1020. Number of Enclaves
-#include "leetcode.h"
-
-/*
- * given an 'm * n' binary matrix grid, where 0 represents a sea
- * cell and 1 represents a land cell. a move consists of walking
- * from one land cell to another adjacent (4-directionally) land
- * cell o walking off the boundary of the 'grid'. return number
- * of land cells in 'grid' for which we cannot walk off the
- * boundary of the grid in any number of moves.
- */
-
-class Solution {
- int dfs(vvd & grid, int i, int j) {
- if (i < 0 || j < 0 || i >= grid.size() || j >= grid[0].size() ||
- grid[i][j] == 0)
- return 0;
- grid[i][j] = 0;
- return 1 + dfs(grid, i - 1, j) + dfs(grid, i + 1, j) + dfs(grid, i, j - 1) +
- dfs(grid, i, j + 1);
- }
-
-public:
- int numEnclaves(vvd & grid) {
- int ones = 0, zeros = 0;
- for (int i = 0; i < grid.size(); i++)
- for (int j = 0; j < grid[0].size(); j++)
- ones += grid[i][j];
- for (int i = 0; i < grid.size(); i++)
- for (int j = 0; j < grid[0].size(); j++)
- if ((i == 0 || j == 0 || i == grid.size() - 1 ||
- j == grid[0].size() - 1) &&
- grid[i][j] == 1)
- zeros += dfs(grid, i, j);
- return ones - zeros;
- }
-};
-
-int main() {
- Solution obj;
- vvd g1 = {{0, 0, 0, 0}, {1, 0, 1, 0}, {0, 1, 1, 0}, {0, 0, 0, 0}};
- vvd g2 = {{0, 1, 1, 0}, {0, 0, 1, 0}, {0, 0, 1, 0}, {0, 0, 0, 0}};
- printf("%d\n", obj.numEnclaves(g1)); // expect: 3
- printf("%d\n", obj.numEnclaves(g2)); // expect: 0
-}
diff --git a/other/num_even_nums.cpp b/other/num_even_nums.cpp
deleted file mode 100644
index 1513c72..0000000
--- a/other/num_even_nums.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-#include "leetcode.h"
-
-/*
- * given array 'nums' of integers, return how
- * many of them contain an even number of digits.
- */
-
-class Solution {
-public:
- int findNumbers(vector<int> &nums) {
- int ans = 0;
- // use auto to identify data type & iterate through array
- for (auto i : nums)
- /*
- * log10 returns a decimal so convert it to int
- * it also returns n - 1. eg. log10(100) = 2
- * use bitwise and to check if it's odd
- */
- ans += log10(i) & 1;
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums1 = {12, 345, 2, 6, 7896}, nums2 = {555, 901, 482, 1771};
- cout << obj.findNumbers(nums1) << endl; // expect: 2
- cout << obj.findNumbers(nums2) << endl; // expect: 1
-}
diff --git a/other/num_good_path.cpp b/other/num_good_path.cpp
deleted file mode 100644
index 79fae31..0000000
--- a/other/num_good_path.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-#include "leetcode.h"
-
-class UnionFind {
-private:
- vector<int> id, rank;
- int cnt;
-
-public:
- UnionFind(int cnt) : cnt(cnt) {
- id = vector<int>(cnt);
- rank = vector<int>(cnt, 0);
- for (int i = 0; i < cnt; ++i)
- id[i] = i;
- }
- int find(int p) {
- if (id[p] == p)
- return p;
- return id[p] = find(id[p]);
- }
- bool connected(int p, int q) { return find(p) == find(q); }
- void connect(int p, int q) {
- int i = find(p), j = find(q);
- if (i == j)
- return;
- if (rank[i] < rank[j])
- id[i] = j;
- else {
- id[j] = i;
- if (rank[i] == rank[j])
- rank[j]++;
- }
- --cnt;
- }
-};
-
-class Solution {
-public:
- int numberOfGoodPaths(vector<int> &vals, vvd & edges) {
- int n = vals.size(), goodPaths = 0;
- vvd adj(n);
- map<int, vector<int>> sameVal;
- for (int i = 0; i < n; i++)
- sameVal[vals[i]].push_back(i);
- for (auto &e : edges) {
- int u = e[0], v = e[1];
- if (vals[u] >= vals[v])
- adj[u].push_back(v);
- else if (vals[v] >= vals[u])
- adj[v].push_back(u);
- }
- UnionFind uf(n);
- for (auto &[value, allNodes] : sameVal) {
- for (int u : allNodes)
- for (int v : adj[u])
- uf.connect(u, v);
- unordered_map<int, int> group;
- for (int u : allNodes)
- group[uf.find(u)]++;
- goodPaths += allNodes.size();
- for (auto &[_, size] : group)
- goodPaths += (size * (size - 1) / 2);
- }
- return goodPaths;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> vals1 = {1, 3, 2, 1, 3}, vals2 = {1, 1, 2, 2, 3}, vals3 = {1};
- vvd edges1 = {{0, 1}, {0, 2}, {2, 3}, {2, 4}},
- edges2 = {{0, 1}, {1, 2}, {2, 3}, {2, 4}}, edges3 = {};
- cout << obj.numberOfGoodPaths(vals1, edges1) << endl; // expect: 6
- cout << obj.numberOfGoodPaths(vals2, edges2) << endl; // expect: 7
- cout << obj.numberOfGoodPaths(vals3, edges3) << endl; // expect: 1
-}
diff --git a/other/num_increasing_path.cpp b/other/num_increasing_path.cpp
deleted file mode 100644
index 4f60d46..0000000
--- a/other/num_increasing_path.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-// 2328. Number of Increasing Paths in a Grid
-#include <stdio.h>
-#include <vector>
-using namespace std;
-
-/*
- * given an 'm x n' integer matrix 'grid' where you can move from a cell to any
- * adjacent cell in all 4 directions. return th number of strictly increasing
- * paths in the grid such that you can start from any cell and end at any cell.
- * since the answer may be very large, return it modulo 10^9+7. two paths are
- * considered different if they do not have exactly the same sequence of visited
- * cells.
- */
-
-class Solution {
- int mod = 1e9 + 7;
- int dfs(vector<vector<int>> &grid, int i, int j, vector<vector<int>> &dp,
- int prev) {
- if (i < 0 || j < 0 || i >= grid.size() || j >= grid[0].size() ||
- prev >= grid[i][j])
- return 0;
- if (dp[i][j] != -1)
- return dp[i][j];
- int top = dfs(grid, i - 1, j, dp, grid[i][j]);
- int bottom = dfs(grid, i + 1, j, dp, grid[i][j]);
- int right = dfs(grid, i, j + 1, dp, grid[i][j]);
- int left = dfs(grid, i, j - 1, dp, grid[i][j]);
- dp[i][j] = (1 + top + bottom + right + left) % mod;
- return dp[i][j];
- }
-
-public:
- int countPaths(vector<vector<int>> &grid) {
- int m = grid.size(), n = grid[0].size(), ans = 0;
- if (m == 1 && n == 1)
- return 1;
- vector<vector<int>> dp(m, vector<int>(n, -1));
- for (int i = 0; i < m; i++)
- for (int j = 0; j < n; j++) {
- if (dp[i][j] == -1)
- ans = (ans + dfs(grid, i, j, dp, -1)) % mod;
- else
- ans = (ans + dp[i][j]) % mod;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<vector<int>> g1 = {{1, 1}, {3, 4}}, g2 = {{1}, {2}};
- printf("%d\n", obj.countPaths(g1)); // expect: 8
- printf("%d\n", obj.countPaths(g2)); // expect: 3
-}
diff --git a/other/num_longest_incr_subseq.cpp b/other/num_longest_incr_subseq.cpp
deleted file mode 100644
index bf6529b..0000000
--- a/other/num_longest_incr_subseq.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-// 673. Number of Longest Increasing Subsequence
-#include "leetcode.h"
-
-/*
- * given an integer array 'nums', return the number of longest increasing
- * subsequences. notice that the sequence has to strictly increasing.
- */
-
-class Solution {
-public:
- int findNumberOfLIS(vector<int> &nums) {
- if (nums.empty())
- return 0;
- vector<vector<pair<int, int>>> dyn(nums.size() + 1);
- int curr_max = 0;
- for (int i = 0; i < nums.size(); ++i) {
- int l = 0, r = curr_max;
- while (l < r) {
- int mid = l + (r - l) / 2;
- if (dyn[mid].back().first < nums[i])
- l = mid + 1;
- else
- r = mid;
- }
- int options = 1, row = l - 1;
- if (row >= 0) {
- int l1 = 0, r1 = dyn[row].size();
- while (l1 < r1) {
- int mid = l1 + (r1 - l1) / 2;
- if (dyn[row][mid].first < nums[i])
- r1 = mid;
- else
- l1 = mid + 1;
- }
- options = dyn[row].back().second;
- options -= !l1 ? 0 : dyn[row][l1 - 1].second;
- }
- dyn[l].push_back(
- {nums[i],
- (dyn[l].empty() ? options : dyn[l].back().second + options)});
- if (l == curr_max)
- curr_max++;
- }
- return dyn[curr_max - 1].back().second;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 3, 5, 4, 7}, n2 = {2, 2, 2, 2, 2};
- printf("%d\n", obj.findNumberOfLIS(n1)); // expect: 2
- printf("%d\n", obj.findNumberOfLIS(n2)); // expect: 5
-}
diff --git a/other/num_matching_subsequence.cpp b/other/num_matching_subsequence.cpp
deleted file mode 100644
index a97d464..0000000
--- a/other/num_matching_subsequence.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int numMatchingSubseq(string s, vector<string> &words) {
- int ans = 0;
- unordered_map<string, int> up;
- for (int i = 0; i < words.size(); i++)
- up[words[i]]++;
- for (auto it = up.begin(); it != up.end(); it++)
- if (helper(s, it->first))
- ans += it->second;
- return ans;
- }
-
-private:
- int helper(string a, string b) {
- int i = 0, j = 0, m = a.size(), n = b.size();
- while (i < m && j < n) {
- if (a[i] == b[j])
- i++, j++;
- else
- i++;
- }
- return (j == n);
- }
-};
-
-int main() {
- Solution obj;
- string s = "abcde";
- vector<string> words = {"a", "bb", "acd", "ace"};
- cout << obj.numMatchingSubseq(s, words);
-}
diff --git a/other/num_music_playlists.cpp b/other/num_music_playlists.cpp
deleted file mode 100644
index 78cad3c..0000000
--- a/other/num_music_playlists.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 920. Number of Music Playlists
-#include "leetcode.h"
-
-/*
- * your music player contains 'n' different songs. you want to listen to 'goal'
- * songs (not necessarily different) during your trip. to avoid boredom, you
- * will create a playlist so that:
- * - every song is played at least once
- * - a song can only be played again only if 'k' other songs have been played
- * given 'n, goal, k', return the number of possible playlists that you can
- * create. since the answer can be very large, return it modulo 10^9+7
- */
-
-class Solution {
- const int mod = 1e9 + 7;
- long long solve(int n, int goal, int k, vvd & dp) {
- if (!n && !goal)
- return 1;
- if (!n || !goal)
- return 0;
- if (dp[n][goal] != -1)
- return dp[n][goal];
- long long pick = solve(n - 1, goal - 1, k, dp) * n;
- long long skip = solve(n, goal - 1, k, dp) * max(n - k, 0);
- return dp[n][goal] = (pick + skip) % mod;
- }
-
-public:
- int numMusicPlaylists(int n, int goal, int k) {
- vvd dp(n + 1, vector<int>(goal + 1, -1));
- return solve(n, goal, k, dp);
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.numMusicPlaylists(3, 3, 1)); // expect: 6
- printf("%d\n", obj.numMusicPlaylists(2, 3, 0)); // expect: 6
- printf("%d\n", obj.numMusicPlaylists(2, 3, 1)); // expect: 2
-}
diff --git a/other/num_nodes_sub_tree.cpp b/other/num_nodes_sub_tree.cpp
deleted file mode 100644
index 4edb9ad..0000000
--- a/other/num_nodes_sub_tree.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> countSubTrees(int n, vvd & edges, string labels) {
- vector<int> ans(n);
- int cnt[26] = {};
- vvd i(n);
- for (auto e : edges) {
- i[e[0]].push_back(e[1]);
- i[e[1]].push_back(e[0]);
- }
- dfs(0, labels, i, cnt, ans);
- return ans;
- }
-
-private:
- void dfs(int i, string labels, vvd & edges, int cnt[],
- vector<int> &ans) {
- if (ans[i] == 0) {
- ans[i] = 1;
- for (auto j : edges[i]) {
- int cnt1[26] = {};
- dfs(j, labels, edges, cnt1, ans);
- for (auto k = 0; k < 26; ++k)
- cnt[k] += cnt1[k];
- }
- ans[i] = ++cnt[labels[i] - 'a'];
- }
- }
-};
-
-int main() {
- Solution obj;
- vvd edges1 = {{0, 1}, {0, 2}, {1, 4}, {1, 5}, {2, 3}, {2, 6}},
- edges2 = {{0, 1}, {1, 2}, {0, 3}},
- edges3 = {{0, 1}, {0, 2}, {1, 3}, {0, 4}};
- for (auto i : obj.countSubTrees(7, edges1, "abaedcd"))
- cout << i << ' '; // expect: 2,1,1,1,1,1,1
- cout << endl;
- for (auto i : obj.countSubTrees(4, edges2, "bbbb"))
- cout << i << ' '; // expect: 4,2,1,1
- cout << endl;
- for (auto i : obj.countSubTrees(5, edges3, "aabab"))
- cout << i << ' '; // expect: 3,2,1,1,1
- cout << endl;
-}
diff --git a/other/num_nodes_sub_tree.rs b/other/num_nodes_sub_tree.rs
deleted file mode 100644
index ca52f7b..0000000
--- a/other/num_nodes_sub_tree.rs
+++ /dev/null
@@ -1,39 +0,0 @@
-use std::collections::{HashMap, HashSet};
-struct Solution;
-
-impl Solution {
- pub fn count_sub_trees(n: i32, edges: Vec<Vec<i32>>, labels: String) -> Vec<i32> {
- let mut map = HashMap::<usize, Vec<usize>>::new();
- for e in &edges {
- map.entry(e[0] as usize).or_default().push(e[1] as usize);
- map.entry(e[1] as usize).or_default().push(e[0] as usize);
- }
- let mut visited = HashSet::<usize>::new();
- let mut ans = vec![0; n as usize];
- Self::dfs(n, &mut map, &labels, 0, &mut visited, &mut ans);
- ans
- }
- fn dfs(n: i32, map: &mut HashMap<usize, Vec<usize>>, labels: &str,
- x: usize, visited: &mut HashSet<usize>, ans: &mut Vec<i32>) -> [i32; 26] {
- let mut vec = [0;26];
- if visited.insert(x) {
- for e in map.entry(x).or_default().clone() {
- let v = Self::dfs(n, map, labels, e, visited, ans);
- for i in 0..26 {
- vec[i] += v[i]
- }
- }
- let ch = labels.as_bytes()[x];
- vec[(ch - b'a') as usize] += 1;
- ans[x] = vec[(ch - b'a') as usize];
- }
- vec
- }
-}
-
-fn main() {
- let edges = vec![vec![0,1],vec![0,2],vec![1,4],
- vec![1,5],vec![2,3],vec![2,6]];
- print!("{:?}", Solution::count_sub_trees(7, edges, String::from("abaedcd")));
- //expect: [2,1,1,1,1,1,1]
-}
diff --git a/other/num_op_connect_network.cpp b/other/num_op_connect_network.cpp
deleted file mode 100644
index 2a9e2e4..0000000
--- a/other/num_op_connect_network.cpp
+++ /dev/null
@@ -1,41 +0,0 @@
-// 1319. Number of Operations to Make Network Connected
-#include "leetcode.h"
-
-class Solution {
-public:
- int makeConnected(int n, vvd & connections) {
- if (connections.size() < n - 1)
- return -1;
- vvd adj(n);
- for (auto v : connections) {
- adj[v[0]].push_back(v[1]);
- adj[v[1]].push_back(v[0]);
- }
- vector<bool> visited(n, false);
- int comp = 0;
- for (int i = 0; i < n; i++)
- if (!visited[i]) {
- dfs(adj, visited, i);
- comp++;
- }
- return comp - 1;
- }
-
-private:
- void dfs(vvd & adj, vector<bool> &visited, int src) {
- visited[src] = true;
- for (int i : adj[src])
- if (!visited[i])
- dfs(adj, visited, i);
- }
-};
-
-int main() {
- Solution obj;
- vvd c1 = {{0, 1}, {0, 2}, {1, 2}};
- vvd c2 = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}};
- vvd c3 = {{0, 1}, {0, 2}, {0, 3}, {1, 2}};
- printf("%d\n", obj.makeConnected(4, c1));
- printf("%d\n", obj.makeConnected(6, c2));
- printf("%d\n", obj.makeConnected(6, c3));
-}
diff --git a/other/num_people_aware_secret.cpp b/other/num_people_aware_secret.cpp
deleted file mode 100644
index 80a4b91..0000000
--- a/other/num_people_aware_secret.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int peopleAwareOfSecret(int n, int delay, int forget) {
- long long sharing = 0, mod = 1000000007;
- deque<int> d{1}, f{1};
- while (--n > 0) {
- if (d.size() >= delay) {
- sharing = (sharing + d.front()) % mod;
- d.pop_front();
- }
- if (f.size() >= forget) {
- sharing = (mod + sharing - f.front()) % mod;
- f.pop_front();
- }
- d.push_back(sharing);
- f.push_back(sharing);
- }
- return accumulate(begin(f), end(f), 0LL) % mod;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.peopleAwareOfSecret(6, 2, 4);
-}
diff --git a/other/num_same_consecutive_diff.cpp b/other/num_same_consecutive_diff.cpp
deleted file mode 100644
index 0602ce1..0000000
--- a/other/num_same_consecutive_diff.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> numsSameConsecDiff(int n, int k) {
- vector<int> ans;
- for (int i = 1; i < 10; i++)
- findNum(i, n, k, ans);
- return ans;
- }
-
-private:
- int digits(int x) {
- int count = 0;
- while (x) {
- count++;
- x /= 10;
- }
- return count;
- }
- void findNum(int curr, int n, int k, vector<int> &ans) {
- if (digits(curr) == n) {
- ans.push_back(curr);
- return;
- }
- for (int i = 0; i < 10; i++) {
- int last = curr % 10;
- if (abs(last - i) == k)
- findNum((curr * 10 + i), n, k, ans);
- }
- }
-};
diff --git a/other/num_smaller_num_self.cpp b/other/num_smaller_num_self.cpp
deleted file mode 100644
index 49b3ed3..0000000
--- a/other/num_smaller_num_self.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> countSmaller(vector<int> &nums) {
- int n = nums.size();
- vector<pair<int, int>> vp(n);
- vector<int> count(n, 0);
- for (int i = 0; i < n; i++)
- vp[i] = make_pair(nums[i], i);
- sort(count, vp, 0, n - 1);
- return count;
- }
-
-private:
- void merge(vector<int> &count, vector<pair<int, int>> &vp, int left, int mid,
- int right) {
- vector<pair<int, int>> tmp(right - left + 1);
- int i = left, j = mid + 1, k = 0;
- while (i <= mid && j <= right) {
- if (vp[i].first <= vp[j].first)
- tmp[k++] = vp[j++];
- else {
- count[vp[i].second] += right - j + 1;
- tmp[k++] = vp[i++];
- }
- }
- while (i <= mid)
- tmp[k++] = vp[i++];
- while (j <= right)
- tmp[k++] = vp[j++];
- for (int i = left; i <= right; i++)
- vp[i] = tmp[i - left];
- }
- void sort(vector<int> &count, vector<pair<int, int>> &vp, int left,
- int right) {
- if (left >= right)
- return;
- int mid = left + (right - left) / 2;
- sort(count, vp, left, mid);
- sort(count, vp, mid + 1, right);
- merge(count, vp, left, mid, right);
- }
-};
diff --git a/other/num_squareful_arrays.cpp b/other/num_squareful_arrays.cpp
deleted file mode 100644
index a7fc481..0000000
--- a/other/num_squareful_arrays.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-// 996. Number of Squareful Arrays
-#include "leetcode.h"
-
-/*
- * an array is squareful if the sum of every pair of adjacent elements is a
- * perfect square. given an intger array nums, return the number of permutations
- * of 'nums' that are squareful. two permutations 'perm1' and 'perm2' are
- * different if there is some index 'i' such that 'perm1[i] != perm2[i]'.
- */
-
-class Solution {
- bool is_square(int x) {
- int t = sqrt(x);
- return t * t == x;
- }
- int fact(int x) {
- int t = 1;
- for (int i = 2; i <= x; i++)
- t *= i;
- return t;
- }
-
-public:
- int numSquarefulPerms(vector<int> &nums) {
- int n = nums.size(), cnt = 1;
- sort(nums.begin(), nums.end());
- vector<int> s;
- for (int i = 1; i < n; i++) {
- if (nums[i] != nums[i - 1]) {
- s.push_back(cnt);
- cnt = 0;
- }
- cnt++;
- }
- s.push_back(cnt);
- vvd f(1 << n, vector<int>(n, 0));
- for (int i = 0; i < n; i++)
- f[1 << i][i] = 1;
- for (int S = 1; S < 1 << n; S++)
- for (int i = 0; i < n; i++)
- if (S & (1 << i))
- for (int j = 0; j < n; j++)
- if (!(S & (1 << j)) && is_square(nums[i] + nums[j]))
- f[S | (1 << j)][j] += f[S][i];
- int ans = 0;
- for (int i = 0; i < n; i++)
- ans += f[(1 << n) - 1][i];
- for (int i = 0; i < s.size(); i++)
- ans /= fact(s[i]);
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 17, 8}, n2 = {2, 2, 2};
- printf("%d\n", obj.numSquarefulPerms(n1)); // expect: 2
- printf("%d\n", obj.numSquarefulPerms(n2)); // expect: 1
-}
diff --git a/other/num_subseq_satisfy.cpp b/other/num_subseq_satisfy.cpp
deleted file mode 100644
index 6eb1a12..0000000
--- a/other/num_subseq_satisfy.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-// 1498. Number of Subsequences That Satisfy the Given Sum Condition
-#include "leetcode.h"
-
-/*
- * given an array of integers 'nums' and an integer 'target'
- * return the numbe of non-empty subsequences of 'nums' such
- * that the sum of the minimum and maximum element on it is
- * less or equal to 'target'. return modulo 10^9+7
- */
-
-class Solution {
-public:
- int numSubSeq(vector<int> &nums, int target) {
- int ans = 0, mod = 1000000007;
- vector<int> pre = {0, 1};
- for (auto i = pre.size(); i <= nums.size(); ++i)
- pre.push_back((pre.back() << 1) % mod);
- sort(nums.begin(), nums.end());
- for (int i = 0, j = nums.size() - 1; i <= j; ++i) {
- while (i <= j && nums[i] + nums[j] > target)
- --j;
- ans = (ans + pre[j - i + 1]) % mod;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {3, 5, 6, 7}, n2 = {3, 3, 6, 8}, n3 = {2, 3, 3, 4, 6, 7};
- printf("%d\n", obj.numSubSeq(n1, 9)); // expect: 4
- printf("%d\n", obj.numSubSeq(n2, 10)); // expect: 6
- printf("%d\n", obj.numSubSeq(n3, 12)); // expect: 61
-}
diff --git a/other/num_to_hex_binary.cpp b/other/num_to_hex_binary.cpp
deleted file mode 100644
index 81470fd..0000000
--- a/other/num_to_hex_binary.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-#include "leetcode.h"
-#include <string>
-
-/*
- * given integer 'num', return string representing hexidecimal value.
- * for negative numbers, use two's complement method
- */
-
-class Solution {
-public:
- string toHex(int num) {
- string ans;
- while (num) {
- int rem = num % 16;
- if (rem > 9)
- switch (rem) {
- case 10:
- ans = 'a' + ans;
- break;
- case 11:
- ans = 'b' + ans;
- break;
- case 12:
- ans = 'c' + ans;
- break;
- case 13:
- ans = 'd' + ans;
- break;
- case 14:
- ans = 'e' + ans;
- break;
- case 15:
- ans = 'f' + ans;
- break;
- }
- else
- ans = char(rem + 48) + ans;
- num /= 16;
- }
- return ans;
- }
- int toBinary(int num) {
- int ans = 0;
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- // obj.toHex(26);
- cout << obj.toHex(26) << endl; // expect: "1a"
- cout << obj.toHex(-1) << endl; // expect: "fffffff"
- cout << obj.toBinary(26) << endl; // expect: 11010
- cout << obj.toBinary(-1) << endl; // expect:
-}
diff --git a/other/num_valid_words_puzzle.cpp b/other/num_valid_words_puzzle.cpp
deleted file mode 100644
index 9286280..0000000
--- a/other/num_valid_words_puzzle.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> findNumOfValidWords(vector<string> &words,
- vector<string> &puzzles) {
- unordered_map<int, int> um;
- for (auto w : words)
- um[(mask(w))]++;
- vector<int> ans;
- for (auto p : puzzles) {
- int m = mask(p), s = m, first = (1 << p[0] - 'a'), curr = 0;
- while (s) {
- if (s & first)
- curr += um[s];
- s = (s - 1) & m;
- }
- ans.push_back(curr);
- }
- return ans;
- }
-
-private:
- int mask(string word) {
- int m = 0;
- for (auto w : word)
- m |= (1 << w - 'a');
- return m;
- }
-};
-
-int main() {
- Solution obj;
- vector<string> words = {"aaaa", "asas", "able", "ability",
- "actt", "actor", "access"};
- vector<string> puzzles = {"aboveyz", "abrodyz", "abslute",
- "absoryz", "actresz", "gaswxyz"};
- for (const auto &i : obj.findNumOfValidWords(words, puzzles))
- cout << i << endl;
-}
diff --git a/other/num_ways_arrive_dest.cpp b/other/num_ways_arrive_dest.cpp
deleted file mode 100644
index 416d811..0000000
--- a/other/num_ways_arrive_dest.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-// 1976. Number of Ways to Arrive at Destination
-#include "leetcode.h"
-
-/*
- * you are in a city that consists of 'n' intersections numbered from 0 to 'n -
- * 1' with bi directional roads between some intersections. the inputs are
- * generated such that you can reach any intersection from any other
- * intersection and that there is at most one road between any two
- * intersections. you are given an integer 'n' and a 2d integer array 'roads'
- * where 'roads[i] = [u_i, v_i, t_i]' means that there is a road between
- * intersections 'u' and 'v' that takes 't' minutes to travel. you want to know
- * in how many ways you can travel from interseciton 0 to intersection 'n - 1'.
- */
-
-class Solution {
-public:
- int countPaths(int n, vector<vector<int>> &roads) {
- vector<vector<pair<long long, long long>>> graph(n);
- for (auto &r : roads) {
- long long u = r[0], v = r[1], t = r[2];
- graph[u].push_back({v, t});
- graph[v].push_back({u, t});
- }
- return dijkstra(graph, n, 0);
- }
-
-private:
- int mod = 1e9 + 7;
- int dijkstra(const vector<vector<pair<long long, long long>>> &graph, int n,
- int src) {
- vector<long long> dist(n, LONG_MAX), ways(n);
- ways[src] = 1;
- dist[src] = 0;
- priority_queue<pair<long long, long long>,
- vector<pair<long long, long long>>, greater<>>
- pq;
- pq.push({0, 0});
- while (!pq.empty()) {
- auto [d, u] = pq.top();
- pq.pop();
- if (d > dist[u])
- continue;
- for (auto [v, t] : graph[u]) {
- if (dist[v] > d + t) {
- dist[v] = d + t;
- ways[v] = ways[u];
- } else if (dist[v] == d + t)
- ways[v] = (ways[v] + ways[u]) % mod;
- }
- }
- return ways[n - 1];
- }
-};
-
-int main() {
- Solution obj;
- vvd r1 = {{0, 6, 7}, {0, 1, 2}, {1, 2, 3}, {1, 3, 3}, {6, 3, 3},
- {3, 5, 1}, {6, 5, 1}, {2, 5, 1}, {0, 4, 5}, {4, 6, 2}};
- vvd r2 = {{1, 0, 10}};
- printf("%d\n", obj.countPaths(7, r1)); // expect: 4
- printf("%d\n", obj.countPaths(2, r2)); // expect: 1
-}
diff --git a/other/num_ways_dict.cpp b/other/num_ways_dict.cpp
deleted file mode 100644
index 582c2f9..0000000
--- a/other/num_ways_dict.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-// 1639. Number of Ways to Form a Target String Given a Dictionary
-#include "leetcode.h"
-
-/*
- * 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'. 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 from 'target' from
- * 'words'. since the answer may be too large, return it modulo 10^9+7
- */
-
-class Solution {
-public:
- int numWays(vector<string> &words, string target) {
- int n = target.length(), mod = 1e9 + 7;
- vector<long> ans(n + 1);
- ans[0] = 1;
- for (int i = 0; i < words[0].length(); ++i) {
- vector<int> cnt(26);
- for (auto &w : words)
- cnt[w[i] - 'a']++;
- for (int j = n - 1; j >= 0; --j)
- ans[j + 1] += ans[j] * cnt[target[j] - 'a'] % mod;
- }
- return ans[n] % mod;
- }
-};
-
-int main() {
- Solution obj;
- vector<string> s1 = {"acca", "bbbb", "caca"}, s2 = {"abba", "baab"};
- string t1 = "aba", t2 = "bab";
- printf("%d\n", obj.numWays(s1, t1)); // expect: 6
- printf("%d\n", obj.numWays(s2, t2)); // expect: 4
-}
diff --git a/other/num_ways_remain_place.cpp b/other/num_ways_remain_place.cpp
deleted file mode 100644
index eee14e5..0000000
--- a/other/num_ways_remain_place.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-// 1269. Number of Ways to Stay in the Same Place After Some Steps
-#include "leetcode.h"
-
-/*
- * you have a pointer at index 0 in an array of size 'arr_len'. at each step,
- * you can move 1 position to the left, 1 position to the right in the array, or
- * stay in the same plae. given two integers 'steps' and 'arr_len' return the
- * number of ways such that your pointer is still at index 0 after exactly
- * 'steps' steps. since the answer may be too large, return it modulo 10e9+7
- */
-
-class Solution {
-public:
- int numWays(int steps, int arr_len) {
- int n = min(steps / 2 + 1, arr_len);
- vector<int> v1(n + 2), v2(n + 2);
- v1[1] = 1;
- while (steps--) {
- for (auto i = 1; i <= n; ++i)
- v2[i] = ((long)v1[i] + v1[i - 1] + v1[i + 1]) % 1000000007;
- swap(v1, v2);
- }
- return v1[1];
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.numWays(3, 2)); // expect: 4
- printf("%d\n", obj.numWays(2, 4)); // expect: 2
- printf("%d\n", obj.numWays(4, 2)); // expect: 8
-}
diff --git a/other/num_ways_reorder_array.cpp b/other/num_ways_reorder_array.cpp
deleted file mode 100644
index 9adcb55..0000000
--- a/other/num_ways_reorder_array.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-// 1569. Number of Ways to Reorder Array to Get Same BST
-#include "leetcode.h"
-
-/*
- * given an array 'nums' that represents a permutation of integers from '1 to
- * n'. we are going to construct a binary search tree (BST) by inserting the
- * elements of 'nums' in order into an initially empty BST. find the number of
- * different ways to reorder 'nums' so that the constructed BST is identical to
- * that formed from the original array 'nums'. for example given 'nums =
- * [2,1,3]', we will have 2 as the root, 1 as a left child, and three as a right
- * child. the array [2,3,1] also yields the same BST, but '[3,2,1]' yields a
- * different BST. return the number of ways to reorder 'nums' such that the BST
- * formed is identical to the original BST formed from 'nums'. since the answer
- * may be large, return it modulo 10^9+7
- */
-
-class Solution {
- int mod = 1e+9 + 7;
- long l[10001][10001] = {0};
- bool init = false;
- long combination(int n, int r) {
- if (init)
- return l[n][r];
- l[0][0] = 1;
- for (int i = 1; i < 1001; i++) {
- l[i][0] = 1;
- for (int j = 1; j < i + 1; j++)
- l[i][j] = (l[i - 1][j - 1] + l[i - 1][j]) % mod;
- }
- init = true;
- return l[n][r];
- }
- long dfs(vector<int> &nums) {
- if (nums.size() < 3)
- return 1;
- vector<int> l, r;
- for (auto n : nums) {
- if (n > nums[0])
- l.push_back(n);
- if (n < nums[0])
- r.push_back(n);
- }
- long c = combination(l.size() + r.size(), l.size());
- return c * dfs(l) % mod * dfs(r) % mod;
- }
-
-public:
- int numOfWays(vector<int> &nums) { return dfs(nums) - 1; }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {2, 1, 3}, n2 = {3, 4, 5, 1, 2}, n3 = {1, 2, 3};
- printf("%d\n", obj.numOfWays(n1)); // expect: 1
- printf("%d\n", obj.numOfWays(n2)); // expect: 5
- printf("%d\n", obj.numOfWays(n3)); // expect: 0
-}
diff --git a/other/num_weak_char_game.cpp b/other/num_weak_char_game.cpp
deleted file mode 100644
index 06fa2db..0000000
--- a/other/num_weak_char_game.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int numberOfWeakCharacters(vvd & properties) {
- sort(properties.begin(), properties.end(), compare);
- int currMax = INT_MIN, ans = 0;
- for (auto p : properties) {
- if (currMax > p[1])
- ans++;
- else
- currMax = p[1];
- }
- return ans;
- }
-
-private:
- static bool compare(vector<int> &a, vector<int> &b) {
- if (a[0] != b[0])
- return a[0] > b[0];
- return a[1] < b[1];
- }
-};
diff --git a/other/num_zero_filled_subarr.cpp b/other/num_zero_filled_subarr.cpp
deleted file mode 100644
index 8ba45f3..0000000
--- a/other/num_zero_filled_subarr.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-// 2348. Number of Zero-Filled Subarrays
-#include "leetcode.h"
-
-// given integer array 'nums', return number of subarrays filled with zero. a
-// subarray is a contiguous non-empty sequence of elements from within an array
-
-class Solution {
-public:
- long long zeroFilledSubarray(vector<int> &nums) {
- long long ans = 0;
- short n = nums.size();
- for (int i = 0, j = 0; i < n; ++i) {
- if (nums[i] != 0)
- j = i + 1;
- ans += i - j + 1;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 3, 0, 0, 2, 0, 0, 4};
- vector<int> n2 = {0, 0, 0, 2, 0, 0};
- vector<int> n3 = {2, 10, 2019};
- printf("%lld\n", obj.zeroFilledSubarray(n1)); // expect: 6
- printf("%lld\n", obj.zeroFilledSubarray(n2)); // expect: 9
- printf("%lld\n", obj.zeroFilledSubarray(n3)); // expect: 0
-}
diff --git a/other/number_1bits.cpp b/other/number_1bits.cpp
deleted file mode 100644
index c8e0ac3..0000000
--- a/other/number_1bits.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int hammingWeight(uint32_t n) {
- int count = 0;
- while (n > 0) {
- if ((n & 1) > 0)
- ++count;
- n = n >> 1;
- }
- return count;
- }
-};
-
-int main() {
- uint32_t n = 00000000000000000000000000001011;
- Solution obj;
- cout << obj.hammingWeight(n);
-}
diff --git a/other/number_atoms.cpp b/other/number_atoms.cpp
deleted file mode 100644
index 2f05d3f..0000000
--- a/other/number_atoms.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-// 726. Number of Atoms
-#include "leetcode.h"
-
-/*
- * given a string 'formula' representing a chemical formula, return the count of
- * each atom. the atomic element always stats with an uppercase character, then
- * zer or more lowercase letters, representing the name. one or more digits
- * representing that element's count may follow if the count is greater than 1.
- * if the count is 1, no digits will follow. return the count of all elements as
- * a string in the following form: the first name, followed by its count,
- * followed by the second name, followed by its count, and so on.
- */
-
-class Solution {
-public:
- string countOfAtoms(string formula) {
- string ans;
- const int n = formula.size();
- int i = 0;
- map<string, int> cnts = parse_formula(formula, i);
- for (pair<string, int> p : cnts) {
- ans += p.first;
- if (p.second > 1)
- ans += to_string(p.second);
- }
- return ans;
- }
-
-private:
- map<string, int> parse_formula(string &s, int &i) {
- map<string, int> cnts;
- const int n = s.size();
- while (i < n && s[i] != ')') {
- map<string, int> cnt = parse_unit(s, i);
- merge(cnts, cnt, 1);
- }
- return cnts;
- }
- map<string, int> parse_unit(string &s, int &i) {
- map<string, int> cnts;
- const int n = s.size();
- if (s[i] == '(') {
- map<string, int> cnt = parse_formula(s, ++i);
- int digits = parse_digits(s, ++i);
- merge(cnts, cnt, digits);
- } else {
- int i0 = i++;
- while (i < n && islower(s[i]))
- i++;
- string atom = s.substr(i0, i - i0);
- int digits = parse_digits(s, i);
- cnts[atom] += digits;
- }
- return cnts;
- }
- int parse_digits(string &s, int &i) {
- int i0 = i;
- while (i < s.size() && isdigit(s[i]))
- i++;
- int digits = i == i0 ? 1 : stoi(s.substr(i0, i - i0));
- return digits;
- }
- void merge(map<string, int> &cnts, map<string, int> &cnt, int times) {
- for (pair<string, int> p : cnt)
- cnts[p.first] += p.second * times;
- }
-};
-
-int main() {
- Solution obj;
- char f1[] = "H2O", f2[] = "Mg(OH)2", f3[] = "K4(ON(SO3)2)2";
- cout << obj.countOfAtoms(f1) << endl; // expect: H2O
- cout << obj.countOfAtoms(f2) << endl; // expect: H2MgO2
- cout << obj.countOfAtoms(f3) << endl; // expect: K4N2O14S4
-}
diff --git a/other/number_islands.cpp b/other/number_islands.cpp
deleted file mode 100644
index 96b8e0b..0000000
--- a/other/number_islands.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int numIslands(vector<vector<char>> &grid) {
- int islands = 0;
- for (int i = 0; i < grid.size(); i++) {
- for (int j = 0; j < grid[0].size(); j++) {
- if (grid[i][j] == '1') {
- dfs(grid, i, j);
- ++islands;
- }
- }
- }
- return islands;
- }
-
-private:
- void dfs(vector<vector<char>> &grid, int i, int j) {
- if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size())
- return;
- if (grid[i][j] == '2' || grid[i][j] == '0')
- return;
- grid[i][j] = '2';
- dfs(grid, i + 1, j);
- dfs(grid, i, j + 1);
- dfs(grid, i - 1, j);
- dfs(grid, i, j + 1);
- }
-};
diff --git a/other/number_provinces.cpp b/other/number_provinces.cpp
deleted file mode 100644
index 2f733f9..0000000
--- a/other/number_provinces.cpp
+++ /dev/null
@@ -1,41 +0,0 @@
-// 547. Number of Provinces
-#include "leetcode.h"
-
-/*
- * dthere are 'n' cities. some of them are connected, while some are not. if
- * city 'a' is connected directly with city 'b', and city 'b' is connected
- * directly with city 'c', then city 'a' is connected indirectly with city 'c'.
- * a province is a group of directly or indirectly connected cities and no other
- * cities outside of the group. given an 'n x n' matrix 'is_connected' where
- * 'is_connected[i][j] = 1' if the i'th city and the j'th city are directly
- * connected, and 'is_connected[i][j] = 0' otherwise. return the total number of
- * provinces
- */
-
-class Solution {
- void dfs(int i, vvd & is_connected, vector<bool> &vis) {
- vis[i] = true;
- for (int j = 0; j < vis.size(); j++)
- if (i != j && is_connected[i][j] && !vis[j])
- dfs(j, is_connected, vis);
- }
-
-public:
- int findCircleNum(vvd & is_connected) {
- if (is_connected.empty())
- return 0;
- int n = is_connected.size(), groups = 0;
- vector<bool> vis(n, false);
- for (int i = 0; i < vis.size(); i++)
- groups += !vis[i] ? dfs(i, is_connected, vis), 1 : 0;
- return groups;
- }
-};
-
-int main() {
- Solution obj;
- vvd ic1 = {{1, 1, 0}, {1, 1, 0}, {0, 0, 1}};
- vvd ic2 = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
- printf("%d\n", obj.findCircleNum(ic1)); // expect: 2
- printf("%d\n", obj.findCircleNum(ic2)); // expect: 3
-}
diff --git a/other/number_steps_to_0.cpp b/other/number_steps_to_0.cpp
deleted file mode 100644
index 2683dca..0000000
--- a/other/number_steps_to_0.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int numberOfSteps(int num) {
- int steps = 0;
- while (num) {
- if (num % 2 == 0)
- num /= 2, steps++;
- else
- num--, steps++;
- }
- return steps;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.numberOfSteps(1043);
-}
diff --git a/other/number_submatrices_sum_target.cpp b/other/number_submatrices_sum_target.cpp
deleted file mode 100644
index db5a84f..0000000
--- a/other/number_submatrices_sum_target.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int numSubmatrixSumTarget(vector<vector<int>> &matrix, int target) {
- int xLen = matrix[0].size(), yLen = matrix.size(), ans = 0;
- unordered_map<int, int> res;
- for (int i = 0; i < yLen; i++)
- for (int j = 1; j < xLen; j++)
- matrix[i][j] += matrix[i][j - 1];
- for (int j = 0; j < xLen; j++)
- for (int k = j; k < xLen; k++) {
- res.clear();
- res[0] = 1;
- int cSum = 0;
- for (int i = 0; i < yLen; i++) {
- cSum += matrix[i][k] - (j ? matrix[i][j - 1] : 0);
- ans += res.find(cSum - target) != res.end() ? res[cSum - target] : 0;
- res[cSum]++;
- }
- }
- return ans;
- }
-};
diff --git a/other/odd_even_linke_list.cpp b/other/odd_even_linke_list.cpp
deleted file mode 100644
index 4ee4bac..0000000
--- a/other/odd_even_linke_list.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- ListNode *oddEvenList(ListNode *head) {
- ListNode *odd = NULL, *headOdd = NULL, *even = NULL, *headEven = NULL;
- if (!head || !head->next || !head->next->next)
- return head;
- odd = head;
- headOdd = odd;
- even = head->next;
- headEven = even;
- while (even && even->next) {
- odd->next = odd->next->next;
- even->next = even->next->next;
- odd = odd->next;
- even = even->next;
- }
- odd->next = headEven;
- return headOdd;
- }
-};
diff --git a/other/odd_even_linke_list.rs b/other/odd_even_linke_list.rs
deleted file mode 100644
index 89e96c1..0000000
--- a/other/odd_even_linke_list.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-#[derive(PartialEq, Eq, Clone, Debug)]
-pub struct ListNode {
- pub val: i32,
- pub next: Option<Box<ListNode>>
-}
-
-impl ListNode {
- #[inline]
- fn new(val: i32) -> Self {
- ListNode {
- next: None,
- val
- }
- }
-}
-
-impl Solution {
- pub fn odd_even_list(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
- let mut odd_dummy_head = ListNode::new(-1);
- let mut even_dummy_head = ListNode::new(-1);
- let mut odd_curr = &mut odd_dummy_head;
- let mut even_curr = &mut even_dummy_head;
- let mut is_even = false;
- while let Some(mut node) = head {
- head = std::mem::replace(&mut node.next, None);
- if is_even {
- even_curr.next = Some(node);
- even_curr = even_curr.next.as_mut().unwrap();
- } else {
- odd_curr.next = Some(node);
- odd_curr = odd_curr.next.as_mut().unwrap();
- }
- is_even = !is_even;
- }
- odd_curr.next = even_dummy_head.next;
- odd_dummy_head.next
- }
-}
diff --git a/other/ones_and_zeroes.cpp b/other/ones_and_zeroes.cpp
deleted file mode 100644
index 851f1e8..0000000
--- a/other/ones_and_zeroes.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-#include "leetcode.h"
-#include <vector>
-
-class Solution {
-public:
- int findMaxForm(vector<string> &strs, int m, int n) {
- vector<pair<int, int>> vp;
- for (auto i : strs) {
- int one = 0, zero = 0;
- for (auto j : i)
- (j == '1') ? one++ : zero++;
- vp.push_back({one, zero});
- }
- return helper(vp, 0, m, n);
- }
-
-private:
- int helper(vector<pair<int, int>> &vp, int idx, int m, int n) {
- int j = vp.size();
- if (idx == j || (m == 0 && n == 0))
- return 0;
- if (vp[idx].first > n || vp[idx].second > m)
- return helper(vp, idx + 1, m, n);
- int include =
- 1 + helper(vp, idx + 1, n - vp[idx].first, m - vp[idx].second);
- int exclude = helper(vp, idx + 1, m, n);
- return max(include, exclude);
- }
-};
-
-int main() {
- Solution obj;
- vector<string> strs = {"10", "0001", "111001", "1", "0"};
- int m = 5, n = 3;
- cout << obj.findMaxForm(strs, m, n);
-}
diff --git a/other/online_stock_span.cpp b/other/online_stock_span.cpp
deleted file mode 100644
index 340f32e..0000000
--- a/other/online_stock_span.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-// 901. Online Stock Span
-#include "leetcode.h"
-
-/*
- * design an algorithm that collects daily price quotes for some stock and
- * returns the span of that stock's price for the current day. the span of the
- * stock's price in one day is the maximum number of consecutive days (starting
- * from that day and going backward) for which the stock price was less than or
- * equal to the price of that day. if the prices of the stock in the last four
- * days is '[7,34,1,2]' and the price of the stock today is 8, then the span of
- * today is 3 because starting from today, the price of the stock was less than
- * or equal 8 for 3 consecutive days.
- */
-
-class StockSpanner {
-public:
- stack<pair<int, int>> storage;
- int idx = 0;
- int next(int price) {
- if (storage.empty()) {
- storage.push({price, idx++});
- return 1;
- } else {
- while (!storage.empty() && price >= storage.top().first)
- storage.pop();
- int ans = 0;
- ans = storage.empty() ? idx + 1 : idx - storage.top().second;
- storage.push({price, idx++});
- return ans;
- }
- }
-};
-
-int main() {
- StockSpanner *obj = new StockSpanner();
- printf("%d\n", obj->next(100)); // expect: 1
- printf("%d\n", obj->next(80)); // expect: 1
- printf("%d\n", obj->next(60)); // expect: 1
- printf("%d\n", obj->next(70)); // expect: 2
- printf("%d\n", obj->next(60)); // expect: 1
- printf("%d\n", obj->next(75)); // expect: 4
- printf("%d\n", obj->next(85)); // expect: 6
-}
diff --git a/other/online_stock_span.rs b/other/online_stock_span.rs
deleted file mode 100644
index a967028..0000000
--- a/other/online_stock_span.rs
+++ /dev/null
@@ -1,51 +0,0 @@
-// 901. Online Stock Span
-
-/*
- * design an algorithm that collects daily price quotes for some stock and
- * returns the span of that stock's price for the current day. the span of the
- * stock's price in one day is the maximum number of consecutive days (starting
- * from that day and going backward) for which the stock price was less than or
- * equal to the price of that day. if the prices of the stock in the last four
- * days is '[7,34,1,2]' and the price of the stock today is 8, then the span of
- * today is 3 because starting from today, the price of the stock was less than
- * or equal 8 for 3 consecutive days.
- */
-
-struct Span {
- price: i32,
- days: i32,
-}
-
-struct StockSpanner {
- spans: Vec<Span>,
-}
-
-impl StockSpanner {
- fn new() -> Self {
- StockSpanner { spans: Vec::new() }
- }
- fn next(&mut self, price: i32) -> i32 {
- let mut days = 1;
- while let Some(span) = self.spans.last() {
- if span.price <= price {
- days += span.days;
- self.spans.pop();
- } else {
- break;
- }
- }
- self.spans.push(Span { price, days });
- days
- }
-}
-
-fn main() {
- let mut obj = StockSpanner::new();
- println!("{}", obj.next(100));
- println!("{}", obj.next(80));
- println!("{}", obj.next(60));
- println!("{}", obj.next(70));
- println!("{}", obj.next(60));
- println!("{}", obj.next(75));
- println!("{}", obj.next(85));
-}
diff --git a/other/optimal_partition_string.cpp b/other/optimal_partition_string.cpp
deleted file mode 100644
index e39bd62..0000000
--- a/other/optimal_partition_string.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-// 2405. Optimal Partition of String
-#include "leetcode.h"
-
-/*
- * given a string 's', partition the string into one or more substrings such
- * that the characters in each substring are unique. that is, no letter appears
- * in a single substring more than once. return the minimum number of substrings
- * in such a partition note that each character should belong to exactly one
- * substring in a partition
- */
-
-class Solution {
-public:
- int partitionString(string s) {
- int cnt[26] = {}, ans = 1;
- for (int i = 0; i < s.size(); ++i) {
- if (cnt[s[i] - 'a']) {
- ++ans;
- fill(begin(cnt), end(cnt), 0);
- }
- ++cnt[s[i] - 'a'];
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.partitionString("abacaba")); // expect: 4
- printf("%d\n", obj.partitionString("ssssss")); // expect: 6
-}
diff --git a/other/orderly_queue.cpp b/other/orderly_queue.cpp
deleted file mode 100644
index 23053d2..0000000
--- a/other/orderly_queue.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string orderlyQueue(string s, int k) {
- if (k > 1) {
- sort(s.begin(), s.end());
- return s;
- }
- string ans = s;
- for (int i = 1; i < s.size(); i++)
- ans = min(ans, s.substr(i) + s.substr(0, i));
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.orderlyQueue("cba", 1);
-}
diff --git a/other/orderly_queue.rs b/other/orderly_queue.rs
deleted file mode 100644
index 0931d7b..0000000
--- a/other/orderly_queue.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn orderly_queue(s: String, k: i32) -> String {
- if k == 1 {
- let ss = s.chars().chain(s.chars()).collect::<Vec<_>>();
- let mut v = ss.windows(s.len()).collect::<Vec<_>>();
- v.sort();
- v[0].iter().copied().collect()
- } else {
- let mut v = s.chars().collect::<Vec<_>>();
- v.sort();
- v.iter().collect()
- }
- }
-}
-
-fn main() {
- let s = String::from("cba");
- let k = 1;
- print!("{}", Solution::orderly_queue(s, k));
-}
diff --git a/other/out_of_bounds_paths.cpp b/other/out_of_bounds_paths.cpp
deleted file mode 100644
index af5ce3f..0000000
--- a/other/out_of_bounds_paths.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
- if (!maxMove)
- return 0;
- vector<vector<int>> curr(m + 2, vector<int>(n + 2));
- vector<vector<int>> last(m + 2, vector<int>(n + 2));
- for (int i = 1; i <= m; i++) {
- curr[i][1]++;
- curr[i][n]++;
- }
- for (int j = 1; j <= n; j++) {
- curr[1][j]++;
- curr[m][j]++;
- }
- int ans = curr[startRow + 1][startColumn + 1];
- for (int d = 1; d < maxMove; d++) {
- curr.swap(last);
- for (int i = 1; i <= m; i++)
- for (int j = 1; j <= n; j++)
- curr[i][j] = (((long)last[i - 1][j] + last[i + 1][j] +
- last[i][j - 1] + last[i][j + 1]) %
- 1000000007L);
- ans = (ans + curr[startRow + 1][startColumn + 1]) % 1000000007L;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.findPaths(2, 2, 2, 0, 0);
-}
diff --git a/other/pacific_atlantic_water_flow.cpp b/other/pacific_atlantic_water_flow.cpp
deleted file mode 100644
index 8876d9f..0000000
--- a/other/pacific_atlantic_water_flow.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vvd pacificAtlantic(vvd & heights) {
- n = heights.size();
- m = heights[0].size();
- vvd(bool) flag1(n, vector<bool>(m)), flag2(n, vector<bool>(m));
- vvd ans;
- for (int i = 0; i < n; i++)
- dfs(heights, flag1, i, 0);
- for (int i = 1; i < m; i++)
- dfs(heights, flag1, 0, i);
- for (int i = 0; i < n; i++)
- dfs(heights, flag2, i, m - 1);
- for (int i = 0; i < m - 1; i++)
- dfs(heights, flag2, n - 1, i);
- for (int i = 0; i < n; i++)
- for (int j = 0; j < m; j++)
- if (flag1[i][j] && flag2[i][j])
- ans.push_back({i, j});
- return ans;
- }
-
-private:
- int n, m;
- void dfs(vvd & grid, vvd(bool) & flag, int x, int y) {
- flag[x][y] = true;
- if (x - 1 >= 0 && !flag[x - 1][y] && grid[x - 1][y] >= grid[x][y])
- dfs(grid, flag, x - 1, y);
- if (x + 1 < n && !flag[x + 1][y] && grid[x + 1][y] >= grid[x][y])
- dfs(grid, flag, x + 1, y);
- if (y - 1 >= 0 && !flag[x][y - 1] && grid[x][y - 1] >= grid[x][y])
- dfs(grid, flag, x, y - 1);
- if (y + 1 < m && !flag[x][y + 1] && grid[x][y + 1] >= grid[x][y])
- dfs(grid, flag, x, y + 1);
- }
-};
diff --git a/other/paint_house3.cpp b/other/paint_house3.cpp
deleted file mode 100644
index 1185109..0000000
--- a/other/paint_house3.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minCost(vector<int> &houses, vector<vector<int>> &cost, int m, int n,
- int target) {
- int INF = 1000000;
- vector<vector<vector<int>>> dp(
- m, vector<vector<int>>(target + 1, vector<int>(n, INF)));
- for (int i = 1; i <= n; i++) {
- if (houses[0] == i)
- dp[0][1][i - 1] = 0;
- else if (!houses[0])
- dp[0][1][i - 1] = cost[0][i - 1];
- }
- for (int i = 1; i < m; i++) {
- for (int k = 1; k <= min(target, i + 1); k++) {
- for (int j = 1; j <= n; j++) {
- if (houses[i] && j != houses[i])
- continue;
- int same = dp[i - 1][k][j - 1];
- int diff = INF;
- for (int r = 1; r <= n; r++)
- if (r != j)
- diff = min(diff, dp[i - 1][k - 1][r - 1]);
- int paintCost = cost[i][j - 1] * int(!houses[i]);
- dp[i][k][j - 1] = min(same, diff) + paintCost;
- }
- }
- }
- int ans = *min_element(dp.back().back().begin(), dp.back().back().end());
- return (ans < INF) ? ans : -1;
- }
-};
diff --git a/other/painting_grid_three_colour.cpp b/other/painting_grid_three_colour.cpp
deleted file mode 100644
index 11fb014..0000000
--- a/other/painting_grid_three_colour.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-// 1931. Painting a Grid With Three Different Colors
-#include "leetcode.h"
-
-/*
- * given two integers 'm' and 'n'. consider an 'm x n' grid where each cell is
- * initially white. you can painteach cell red, green, or blue. all cells must
- * be painted. return the number of ways to colour the grid with no two adjacent
- * cells having the same colour.
- */
-
-class Solution {
- int memo[1000][1024] = {};
- vector<int> nei_memo[1024] = {};
- int m, n, mod = 1e9 + 7;
- int dp(int c, int prev) {
- if (c == n)
- return 1;
- if (memo[c][prev])
- return memo[c][prev];
- int res = 0;
- for (int nei : neighbours(prev))
- res = (res + dp(c + 1, nei)) % mod;
- return memo[c][prev] = res;
- }
- vector<int> neighbours(int prev) {
- if (!nei_memo[prev].empty())
- return nei_memo[prev];
- dfs(0, prev, 0, nei_memo[prev]);
- return nei_memo[prev];
- }
- void dfs(int r, int prev, int curr, vector<int> &out) {
- if (r == m) {
- out.push_back(curr);
- return;
- }
- for (int i = 0; i <= 3; i++)
- if (get_colour(prev, r) != i && (!r || get_colour(curr, r - 1) != i))
- dfs(r + 1, prev, set_colour(curr, r, i), out);
- }
- int get_colour(int mask, int pos) { return (mask >> (2 * pos)) & 3; }
- int set_colour(int mask, int pos, int colour) {
- return mask | (colour << (2 * pos));
- }
-
-public:
- int colorTheGrid(int m, int n) {
- this->m = m;
- this->n = n;
- return dp(0, 0);
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.colorTheGrid(1, 1)); // expect: 3
- printf("%d\n", obj.colorTheGrid(1, 2)); // expect: 6
- printf("%d\n", obj.colorTheGrid(5, 5)); // expect: 580986
-}
diff --git a/other/painting_walls.cpp b/other/painting_walls.cpp
deleted file mode 100644
index 5f70012..0000000
--- a/other/painting_walls.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-// 2742. Painting the Walls
-#include "leetcode.h"
-
-/*
- * you are given two 0-indexed integer arrays, cost and time of size n
- * representing the costs and the time taken to paint n walls respectively.
- * there are two painters available:
- * - a paid painter that paints the i'th wall in 'time[i]' units of time and
- * takes 'cost[i]' units of money
- * - a free painter that paints any wall in 1 unit of time at a cost of 0. but
- * the free painter can only be used if the paid painter is already occupied
- * return the minimum amount of money required to paint the 'n' walls.
- */
-
-class Solution {
-public:
- int paintWalls(vector<int> &cost, vector<int> &time) {
- this->n = cost.size();
- vvd memo(n, vector<int>(n + 1));
- this->cost = cost;
- this->time = time;
- return dfs(0, n, memo);
- }
-
-private:
- int memo[501][501];
- vector<int> cost;
- vector<int> time;
- int n;
- int dfs(int curr, int left_wall, vvd & memo) {
- if (left_wall <= 0)
- return 0;
- if (curr == n)
- return 1e9;
- if (memo[curr][left_wall] != -1)
- return memo[curr][left_wall];
- int paid = cost[curr] + dfs(curr + 1, left_wall - 1 - time[curr], memo);
- int free = dfs(curr + 1, left_wall, memo);
- memo[curr][left_wall] = min(paid, free);
- return memo[curr][left_wall];
- }
-};
-
-int main() {
- Solution obj;
- vector<int> c1 = {1, 2, 3, 2}, c2 = {2, 3, 4, 2};
- vector<int> t1 = {1, 2, 3, 2}, t2 = {1, 1, 1, 1};
- printf("%d\n", obj.paintWalls(c1, t1)); // expect: 3
- printf("%d\n", obj.paintWalls(c2, t2)); // expect: 4
-}
diff --git a/other/pairs_spells_potions.cpp b/other/pairs_spells_potions.cpp
deleted file mode 100644
index 255b4a0..0000000
--- a/other/pairs_spells_potions.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-// 2300. Successful Pairs of Spells and Potions
-#include "leetcode.h"
-
-/*
- * given two positive integer arrays 'spells' and 'potions', of length n and m
- * respectively where 'spells[i]' represents the strength of the i'th spell and
- * 'potions[j] represents the strength of the j'th potion. also given an integer
- * success. a spell and potion pair is considered successful if the product of
- * their strengths is at least 'success'. return an integer array 'pairs' of
- * lengthn where 'pairs[i]' is the number of potions that will form a successful
- * pair with the i'th spell.
- */
-
-class Solution {
-public:
- vector<int> successfulPairs(vector<int> &spells, vector<int> &potions,
- long long success) {
- int m = potions.size();
- vector<int> ans;
- sort(potions.begin(), potions.end());
- for (auto i : spells) {
- int left = 0, right = m - 1, mid;
- while (left <= right) {
- mid = (left + right) >> 1;
- if ((long long)i * potions[mid] >= success)
- right = mid - 1;
- else
- left = mid + 1;
- }
- ans.push_back(m - left);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> s1 = {5, 1, 3}, s2 = {3, 1, 2};
- vector<int> p1 = {1, 2, 4, 4, 5}, p2 = {8, 5, 8};
- for (auto i : obj.successfulPairs(s1, p1, 7))
- printf("%d ", i); // expec: 4 0 3
- printf("\n");
- for (auto i : obj.successfulPairs(s2, p2, 16))
- printf("%d ", i); // expec: 2 0 2
-}
diff --git a/other/palindrome_linked_list.cpp b/other/palindrome_linked_list.cpp
deleted file mode 100644
index 1b08a0c..0000000
--- a/other/palindrome_linked_list.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool isPalindrome(ListNode *head) {
- ListNode *slow = head, *fast = head, *prev, *temp;
- while (fast && fast->next) {
- slow = slow->next;
- fast = fast->next->next;
- }
- prev = slow;
- slow = slow->next;
- prev->next = NULL;
- while (slow) {
- temp = slow->next;
- slow->next = prev;
- prev = slow;
- slow = temp
- }
- fast = head;
- slow = prev;
- while (slow) {
- if (fast->val != slow->val)
- return false;
- else {
- fast = fast->next;
- slow = slow->next;
- }
- }
- return true;
- }
-};
diff --git a/other/palindrome_number.rs b/other/palindrome_number.rs
deleted file mode 100644
index bd3c641..0000000
--- a/other/palindrome_number.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-struct Solution;
-
-impl Solution {
- fn is_palindrome(mut x: i32) -> bool {
- if x < 0 {
- return false;
- }
- let mut nums = Vec::with_capacity(10);
- while x != 0 {
- nums.push(x % 10);
- x /= 10;
- }
- for i in 0..(nums.len() / 2) {
- if nums[i] != nums[nums.len() - i - 1] {
- return false;
- }
- }
- true
- }
-}
-
-fn main() {
- print!("{}", Solution::is_palindrome(121));
-}
diff --git a/other/palindrome_pairs.cpp b/other/palindrome_pairs.cpp
deleted file mode 100644
index 8048069..0000000
--- a/other/palindrome_pairs.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vvd palindromePairs(vector<string> &words) {
- unordered_map<string, int> um;
- for (int i = 0; i < words.size(); i++) {
- string x = words[i];
- reverse(x.begin(), x.end());
- um[x] = i;
- }
- vvd ans;
- for (int j = 0; j < words.size(); j++) {
- string str = words[j];
- for (int i = 0; i <= str.size(); i++) {
- string prefix = str.substr(0, i), suffix = str.substr(i);
- if (!prefix.empty() && isPalindrome(prefix) && um.count(suffix) &&
- j != um[suffix])
- ans.push_back({um[suffix], j});
- if (isPalindrome(suffix) && um.count(prefix) && j != um[prefix])
- ans.push_back({j, um[prefix]});
- }
- }
- return ans;
- }
-
-private:
- bool isPalindrome(string &str) {
- int i = 0, j = str.size() - 1;
- while (i < j) {
- if (str[i] != str[j])
- return false;
- i++;
- j--;
- }
- return true;
- }
-};
diff --git a/other/palindrome_partitioning.cpp b/other/palindrome_partitioning.cpp
deleted file mode 100644
index 6a49703..0000000
--- a/other/palindrome_partitioning.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-// 131. Palindrome Partitioning
-#include "leetcode.h"
-#include <vector>
-
-/*
- * given: string 's', parition 's' such that every substring of the parition
- * is a palindrome. return all possible palindrome paritioning of 's'.
- */
-
-class Solution {
-public:
- vvd(string) partition(string s) {
- vvd(string) ans;
- if (s.empty())
- return ans;
- vector<string> path;
- dfs(0, s, path, ans);
- return ans;
- }
-
-private:
- void dfs(int idx, string &s, vector<string> &path, vvd(string) & res) {
- if (idx == s.size())
- res.push_back(path);
- return;
- for (int i = idx; i < s.size(); ++i) {
- if (isPalindrome(s, idx, i)) {
- path.push_back(s.substr(idx, i - idx + 1));
- dfs(i + 1, s, path, res);
- path.pop_back();
- }
- }
- }
- bool isPalindrome(const string &s, int start, int end) {
- while (start <= end)
- if (s[start++] != s[end--])
- return false;
- return true;
- }
-};
-
-int main() {
- Solution obj;
- for (auto i : obj.partition("aab"))
- for (auto j : i)
- cout << j << ' '; // expect: [["a","a","b"],["aa","b"]]
- for (auto i : obj.partition("a"))
- for (auto j : i)
- cout << j << ' '; // expect: [["a"]]
-}
diff --git a/other/parallel_courses3.cpp b/other/parallel_courses3.cpp
deleted file mode 100644
index 70e50e3..0000000
--- a/other/parallel_courses3.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-// 2050. Parallel Courses III
-#include "leetcode.h"
-
-/*
- * given an integer 'n' which indicates that there are n courses labeled from 1
- * to n. you are also given a 2d integer array rleations where relations[j] =
- * pre_course[j], denotes that course pre_course has to be completed before
- * next_course. furthermore, you are given a 0-indexed integer array 'time'
- * where 'time[i]' denotes how many months it takes to complete the '(i + 1)'th
- * course. you must find the minimum number of months needed to complete all the
- * courses following these rules. you may start taking courses at any time if
- * the prerequisites have been met, and any number of courses can be taken at
- * the same time. return the minimum number of monthsneeded to omplete all the
- * courses.
- */
-
-class Solution {
-public:
- int minimumTime(int n, vvd & relations, vector<int> &time) {
- vector<int> in_deg(n + 1);
- vvd g(n + 1);
- for (auto r : relations) {
- int a = r[0];
- int b = r[1];
- g[a].push_back(b);
- in_deg[b]++;
- }
- vector<int> finish_time(n + 1);
- queue<int> q;
- for (int i = 1; i <= n; i++)
- if (!in_deg[i])
- q.push(i);
- while (!q.empty()) {
- int curr = q.front();
- q.pop();
- finish_time[curr] += time[curr - 1];
- for (auto next : g[curr]) {
- in_deg[next]--;
- finish_time[next] = max(finish_time[next], finish_time[curr]);
- if (!in_deg[next])
- q.push(next);
- }
- }
- return *max_element(finish_time.begin(), finish_time.end());
- }
-};
-
-int main() {
- Solution obj;
- vvd r1 = {{1, 3}, {2, 3}}, r2 = {{1, 5}, {2, 5}, {3, 5}, {3, 4}, {4, 5}};
- vector<int> t1 = {3, 2, 5}, t2 = {1, 2, 3, 4, 5};
- printf("%d\n", obj.minimumTime(3, r1, t1)); // expect: 8
- printf("%d\n", obj.minimumTime(5, r2, t2)); // expect: 12
-}
diff --git a/other/partition_array_max_sum.cpp b/other/partition_array_max_sum.cpp
deleted file mode 100644
index 98efe07..0000000
--- a/other/partition_array_max_sum.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-// 1043. Partition Array for Maximum Sum
-#include "leetcode.h"
-
-/*
- * given an integeer array 'arr', partition the array into contiguous subarrays
- * of length at most 'k'. after partitioning, each subarray has their values
- * changed to become the maximum value of that subarray. return the largest sum
- * of the given array after partitioning. test cases are generated so that
- * answer fits in a 32-bit integer
- */
-
-class Solution {
-public:
- int maxSumAfterPartitioning(vector<int> &arr, int k) {
- int n = arr.size();
- vector<int> dp(n + 1);
- for (int i = 1; i <= n; ++i) {
- int curr = 0, best = 0;
- for (int j = 1; j <= k && i - j >= 0; ++j) {
- curr = max(curr, arr[i - j]);
- best = max(best, dp[i - j] + curr * j);
- }
- dp[i] = best;
- }
- return dp[n];
- }
-};
-
-int main() {
- Solution obj;
- vector<int> a1 = {1, 15, 7, 9, 2, 5, 10},
- a2 = {1, 4, 1, 5, 7, 3, 6, 1, 9, 9, 3}, a3 = {1};
- printf("%d\n", obj.maxSumAfterPartitioning(a1, 3)); // expect: 84
- printf("%d\n", obj.maxSumAfterPartitioning(a2, 4)); // expect: 83
- printf("%d\n", obj.maxSumAfterPartitioning(a3, 1)); // expect: 1
-}
diff --git a/other/partition_array_pivot.rs b/other/partition_array_pivot.rs
deleted file mode 100644
index 8a126da..0000000
--- a/other/partition_array_pivot.rs
+++ /dev/null
@@ -1,32 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn pivot_array(nums: Vec<i32>, pivot: i32) -> Vec<i32> {
- let mut greater = vec![];
- let mut same = 0;
- let ans = vec![];
- for n in nums {
- if n < pivot {
- ans.push(n);
- } else if n == pivot {
- same += 1;
- } else {
- greater.push(n);
- }
- }
- for _ in 0..same {
- ans.push(pivot);
- }
- for g in greater {
- ans.push(g);
- }
- ans
- }
-}
-
-fn main() {
- let s = Solution;
- let nums = vec![9,12,5,10,14,3,10];
- let pivot = 10;
- print!("{}", s.pivot_array(nums, pivot));
-}
diff --git a/other/partition_list.cpp b/other/partition_list.cpp
deleted file mode 100644
index b2e44a9..0000000
--- a/other/partition_list.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- ListNode *partition(ListNode *head, int x) {
- ListNode *fTmp = new ListNode(0), *bTmp = new ListNode(0), *front = fTmp,
- *back = bTmp, *curr = head;
- while (curr) {
- if (curr->val < x) {
- front->next = curr;
- front = curr;
- } else {
- back->next = curr;
- back = curr;
- }
- }
- front->next = bTmp->next, back->next = nullptr;
- return fTmp->next;
- }
-};
diff --git a/other/partition_min_binary_array.cpp b/other/partition_min_binary_array.cpp
deleted file mode 100644
index 8cec267..0000000
--- a/other/partition_min_binary_array.cpp
+++ /dev/null
@@ -1,18 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minPartitions(string n) {
- char ans = '0';
- for (char c : n)
- if (c > ans)
- ans = c;
- return ans - '0';
- }
-};
-
-int main() {
- Solution obj;
- string n = "32";
- cout << obj.minPartitions(n);
-}
diff --git a/other/pascals_triangle.cpp b/other/pascals_triangle.cpp
deleted file mode 100644
index 343c116..0000000
--- a/other/pascals_triangle.cpp
+++ /dev/null
@@ -1,19 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<vector<int>> generate(int numRows) {
- vector<vector<int>> ans(numRows);
- for (int i = 0; i < numRows; i++) {
- vector<int> row(i + 1, 1);
- int mid = i >> 1;
- for (int j = 1; j <= mid; j++) {
- int val = ans[i - 1][j - 1] + ans[i - 1][j];
- row[j] = val;
- row[row.size() - j - 1] = val;
- }
- ans[i] = row;
- }
- return ans;
- }
-};
diff --git a/other/path_max_probability.cpp b/other/path_max_probability.cpp
deleted file mode 100644
index 467829e..0000000
--- a/other/path_max_probability.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-// 1514. Path with Maximum Probability
-#include "leetcode.h"
-
-/*
- * given an undirected weighted graph of 'n' nodes (0-indexed). represented by
- * an edge list where 'edges[i] = [a, b]' is an undirected edge connecting the
- * nodes 'a' and 'b' with a probability of success of traversing that edge
- * 'succ_prob[i]'. given two nodes 'start, end', find the path with the maximum
- * probability of success to go from 'start' to 'end' and return its success
- * probability. if there is no path from 'start' to 'end', return 0. your answer
- * will be accepted if it differs from the correct answer by at most '1e-5'
- */
-
-class Solution {
-public:
- double maxProbability(int n, vvd & edges, vector<double> &succ_prob,
- int start, int end) {
- vector<vector<pair<int, double>>> vvp(n);
- for (int i = 0; i < edges.size(); i++) {
- vvp[edges[i][0]].push_back({edges[i][1], succ_prob[i]});
- vvp[edges[i][1]].push_back({edges[i][0], succ_prob[i]});
- }
- vector<int> seen(n, 0);
- priority_queue<pair<double, int>> pqp;
- pqp.push({(double)1.0, start});
- vector<double> mx(n, (double)0.0);
- mx[start] = 1.0;
- while (!pqp.empty()) {
- auto top = pqp.top();
- pqp.pop();
- double prob_a = top.first;
- int node = top.second;
- if (!seen[node]) {
- seen[node]++;
- for (auto to : vvp[node])
- if (mx[to.first] < to.second * prob_a) {
- mx[to.first] = to.second * prob_a;
- pqp.push({mx[to.first], to.first});
- }
- }
- }
- return mx[end];
- }
-};
-
-int main() {
- Solution obj;
- vvd e1 = {{0, 1}, {1, 2}, {0, 2}}, e2 = {{0, 1}, {1, 2}, {0, 2}};
- vector<double> sp1 = {0.5, 0.5, 0.2}, sp2 = {0.5, 0.5, 0.3};
- printf("%f\n", obj.maxProbability(3, e1, sp1, 0, 2)); // expect: 0.25000
- printf("%f\n", obj.maxProbability(3, e2, sp2, 0, 2)); // expect: 0.30000
-}
diff --git a/other/path_min_effort.cpp b/other/path_min_effort.cpp
deleted file mode 100644
index 0b93590..0000000
--- a/other/path_min_effort.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minimumEffortPath(vector<vector<int>> &heights) {
- int m = heights.size(), n = heights[0].size();
- int dirs[5] = {-1, 0, 1, 0, -1};
- vector<vector<int>> efforts(m, vector<int>(n, INT_MAX));
- priority_queue<pair<int, int>, vector<pair<int, int>>,
- greater<pair<int, int>>>
- pq;
- pq.emplace(0, 0);
- while (!pq.empty()) {
- int effort = pq.top().first;
- int x = pq.top().second / 100, y = pq.top().second % 100;
- pq.pop();
- if (x == m - 1 && y == n - 1)
- return effort;
- if (effort >= efforts[x][y])
- continue;
- efforts[x][y] = effort;
- for (int i = 0; i < 4; i++) {
- int nX = x + dirs[i], nY = +dirs[i + 1];
- if (nX < 0 || nX >= m || nY < 0 || nY >= n)
- continue;
- int nEffort = max(effort, abs(heights[x][y] - heights[nX][nY]));
- pq.emplace(nEffort, nX * 100 + nY);
- }
- }
- return -1;
- }
-};
-
-int min() {}
diff --git a/other/path_min_effort1.cpp b/other/path_min_effort1.cpp
deleted file mode 100644
index d9066cd..0000000
--- a/other/path_min_effort1.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-#include "leetcode.h"
-#include <algorithm>
-#include <climits>
-#include <cmath>
-#include <functional>
-#include <utility>
-#include <vector>
-
-class Solution {
- const int d4x[4] = {-1, 0, 1, 0}, d4y[4] = {0, 1, 0, -1};
-
-public:
- int minimumEffortPath(vector<vector<int>> &heights) {
- int n = heights.size(), m = heights[0].size();
- priority_queue<pair<int, int>, vector<pair<int, int>>,
- greater<pair<int, int>>>
- pq;
- vector<vector<int>> dis(n, vector<int>(m, INT_MAX));
- dis[0][0] = 0;
- pq.push({0, {0, 0}});
- while (!pq.empty()) {
- pair<int, pair<int, int>> curr = pq.top();
- pq.pop();
- int d = curr.first, r = curr.second.first, c = curr.second.second;
- if (r == n - 1 && c == m - 1)
- return d;
- for (int i = 0; i < 4; ++i) {
- int nX = r + d4x[i], nY = x + d4y[i];
- if (nX < 0 || nX >= n || nY < 0 || nY >= m)
- continue;
- int nD = max(d, abs(h[nX][nY] - h[r][c]));
- if (nD < dis[nX][nY]) {
- dis[nX][nY] = nD;
- pq.push({nD, {nX, nY}});
- }
- }
- }
- return 0;
- }
-};
-
-int main() {}
diff --git a/other/path_sum.cpp b/other/path_sum.cpp
deleted file mode 100644
index 41498ca..0000000
--- a/other/path_sum.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool hasPathSum(TreeNode *root, int targetSum) {
- if (root == NULL)
- return false;
- stack<pair<TreeNode *, int>> s;
- s.push({root, root->val});
- while (!s.empty()) {
- TreeNode *curr = s.top().first;
- int total = s.top().second;
- s.pop();
- if (curr->right)
- s.push({curr->right, total + curr->right->val});
- if (curr->left)
- s.push({curr->left, total + curr->left->val});
- if (!curr->right && !curr->left && total == targetSum)
- return true;
- }
- return false;
- }
-};
diff --git a/other/path_sum2.cpp b/other/path_sum2.cpp
deleted file mode 100644
index 3ccfc65..0000000
--- a/other/path_sum2.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vvd pathSum(TreeNode *root, int targetSum) {
- vvd ans;
- vector<int> d;
- dfs(root, targetSum, d, ans);
- return ans;
- }
-
-private:
- void dfs(TreeNode *root, int targetSum, vector<int> d, vvd & ans) {
- if (root == NULL)
- return;
- d.push_back(root->val);
- targetSum -= root->val;
- if (targetSum == 0 && root->left == NULL && root->right == NULL) {
- ans.push_back(d);
- return;
- }
- dfs(root->left, targetSum, d, ans);
- dfs(root->right, targetSum, d, ans);
- }
-};
diff --git a/other/peak_idx_mountain_arr.cpp b/other/peak_idx_mountain_arr.cpp
deleted file mode 100644
index 2900091..0000000
--- a/other/peak_idx_mountain_arr.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-// 852. Peak Index in a Mountain Array
-#include "leetcode.h"
-
-class Solution {
-public:
- int peakIndexInMountainArray(vector<int> &arr) {
- int left = 1, right = arr.size() - 1;
- while (left < right) {
- int mid = (left + right) / 2;
- if (arr[mid] < arr[mid + 1])
- left = mid + 1;
- else
- right = mid;
- }
- return left;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> a1 = {0, 1, 0}, a2 = {0, 2, 1, 0}, a3 = {0, 10, 5, 2};
- printf("%d\n", obj.peakIndexInMountainArray(a1)); // expect: 1
- printf("%d\n", obj.peakIndexInMountainArray(a2)); // expect: 1
- printf("%d\n", obj.peakIndexInMountainArray(a3)); // expect: 1
-}
diff --git a/other/peeking_iterator.cpp b/other/peeking_iterator.cpp
deleted file mode 100644
index 1c4d0b9..0000000
--- a/other/peeking_iterator.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-#include "leetcode.h"
-
-class Iterator {
- struct Data;
- Data *data;
-
-public:
- Iterator(const vector<int> &nums);
- Iterator(const Iterator &iter);
- int next();
- bool hasNext() const;
-};
-
-class PeekingIterator : public Iterator {
-public:
- int nextVal;
- PeekingIterator(const vector<int> &nums) : Iterator(nums) {
- nextVal = Iterator::next();
- }
- int peek() { return nextVal; }
- int next() {
- int tmp = nextVal;
- if (Iterator::hasNext())
- nextVal = Iterator::next();
- else
- nextVal = NULL;
- return tmp;
- }
- bool hasNext() const { return (nextVal != NULL); }
-};
-
-int main() {}
diff --git a/other/percentage_letter_string.cpp b/other/percentage_letter_string.cpp
deleted file mode 100644
index 18744ea..0000000
--- a/other/percentage_letter_string.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int percentageLetter(string s, char letter) {
- int n = s.size();
- int freq = 0;
- for (int i = 0; i < n; i++)
- if (s[i] == letter)
- freq++;
- return (freq * 100) / n;
- }
-};
-
-int main() {
- string s = "foobar";
- char letter = 'o';
- Solution obj;
- cout << obj.percentageLetter(s, letter);
-}
diff --git a/other/perfect_squares.cpp b/other/perfect_squares.cpp
deleted file mode 100644
index 677c4a0..0000000
--- a/other/perfect_squares.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int numSquares(int n) {
- vector<int> dp(n + 1, INT_MAX);
- dp[0] = 0;
- for (int target = 1; target <= n; target++) {
- int mmCount = INT_MAX;
- for (int num = 1; num <= sqrt(target); num++) {
- int sqNum = pow(num, 2), curr = 1 + dp[target - sqNum];
- mmCount = min(mmCount, curr);
- }
- dp[target] = mmCount;
- }
- return dp[n];
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.numSquares(12);
-}
diff --git a/other/perfect_squares.rs b/other/perfect_squares.rs
deleted file mode 100644
index 3887e40..0000000
--- a/other/perfect_squares.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-use std::cmp::min;
-struct Solution;
-
-impl Solution {
- pub fn num_squares(n: i32) -> i32 {
- let mut dp: Vec<i32> = vec![std::i32::MAX; n as usize + 1];
- dp[0] = 0;
- for i in 1..(n as usize + 1) {
- let mut j: usize = 1;
- while j * j <= i {
- dp[i] = min(dp[i], dp[i - j * j] + 1);
- j += 1;
- }
- }
- dp[n as usize]
- }
-}
-
-fn main() {
- print!("{}", Solution::num_squares(12));
-}
diff --git a/other/permutation_in_string.cpp b/other/permutation_in_string.cpp
deleted file mode 100644
index f4e09f3..0000000
--- a/other/permutation_in_string.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-// 567. Permutation in String
-#include "leetcode.h"
-
-/*
- * given two strings 's1 s2' return true if 's2' contains a permutation of 's1'
- * or false otherwise. in other words, return true if one of 's1's permutations
- * is in the substring of 's2'
- */
-
-class Solution {
-public:
- bool checkInclusion(string s1, string s2) {
- if (s2.size() < s1.size())
- return false;
- vector<int> freq1(26, 0), freq2(26, 0);
- for (char c : s1)
- freq1[c - 'a']++;
- int i = 0, j = 0;
- while (j < s2.size()) {
- freq2[s2[j] - 'a']++;
- if (j - i + 1 == s1.size())
- if (cmp(freq1, freq2))
- return true;
- if (j - i + 1 < s1.size())
- j++;
- else {
- freq2[s2[i] - 'a']--;
- i++, j++;
- }
- }
- return false;
- }
-
-private:
- bool cmp(vector<int> a, vector<int> b) {
- for (int i = 0; i < 26; i++)
- if (a[i] != b[i])
- return false;
- return true;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.checkInclusion("ab", "eidbaooo") << endl; // expect: 1
- cout << obj.checkInclusion("ab", "eidboaoo") << endl; // expect: 0
-}
diff --git a/other/permutation_sequence.cpp b/other/permutation_sequence.cpp
deleted file mode 100644
index a77286b..0000000
--- a/other/permutation_sequence.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-#include "leetcode.h"
-#include <vector>
-
-class Solution {
-public:
- vector<int> fact;
- string getPermutation(int n, int k) { int n = k - 1; }
-
-private:
- void helper(int k) {
- fact = vector<int>(k);
- fact[0] = 1;
- if (k == 1)
- return;
- fact[1] = 1;
- for (int i = 2; i < k; i++)
- fact[i] = i * fact[i - 1];
- }
-};
-
-int main() {
- Solution obj;
- int n = 3, k = 3;
- cout << obj.getPermutation(n, k);
-}
diff --git a/other/permutations.cpp b/other/permutations.cpp
deleted file mode 100644
index 2e86fc0..0000000
--- a/other/permutations.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<vector<int>> permute(vector<int> &nums) {
- vector<vector<int>> ans;
- int idx = 0;
- helper(nums, ans, idx);
- return ans;
- }
-
-private:
- void helper(vector<int> &nums, vector<vector<int>> &ans, int idx) {
- if (idx >= nums.size()) {
- ans.push_back(nums);
- return;
- }
- for (int i = idx; i < nums.size(); i++) {
- swap(nums[idx], nums[i]);
- helper(nums, ans, idx + 1);
- swap(nums[idx], nums[i]);
- }
- }
-};
-
-int main() {}
diff --git a/other/permutations2.cpp b/other/permutations2.cpp
deleted file mode 100644
index 16d0162..0000000
--- a/other/permutations2.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<vector<int>> permuteUnique(vector<int> &nums) {
- vector<vector<int>> ans;
- helper(0, nums, ans);
- return ans;
- }
-
-private:
- void helper(int i, vector<int> &nums, vector<vector<int>> &ans) {
- if (i == nums.size()) {
- ans.emplace_back(nums);
- return;
- }
- unordered_set<int> us;
- for (int j = i; j < nums.size(); j++) {
- if (us.count(nums[j]) == 1)
- continue;
- us.insert(nums[j]);
- swap(nums[i], nums[j]);
- helper(i + 1, nums, ans);
- swap(nums[i], nums[j]);
- }
- }
-};
-
-int main() {}
diff --git a/other/poor-pigs.cpp b/other/poor-pigs.cpp
deleted file mode 100644
index 7455583..0000000
--- a/other/poor-pigs.cpp
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int poorPigs(int buckets, int poisonTime, int totalTime) {
- return ceil(log(buckets) / log(totalTime / poisonTime + 1));
- }
-};
diff --git a/other/possible_bipartition.cpp b/other/possible_bipartition.cpp
deleted file mode 100644
index 6dd4175..0000000
--- a/other/possible_bipartition.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool possibleBipartition(int n, vvd & dislikes) {
- enum color { green = -1, uncolored, blue };
- if (n == 1 || dislikes.size() == 0)
- return true;
- unordered_map<int, vector<int>> dislikeTable;
- unordered_map<int, int> colorTable;
- function<bool(int, int)> helper;
- helper = [&](int personID, int color) -> bool {
- colorTable[personID] = color;
- for (const int &other : dislikeTable[personID]) {
- if (colorTable[other] == color)
- return false;
- if (colorTable[other] == uncolored && (!helper(other, -color)))
- return false;
- }
- return true;
- };
- for (const auto &relation : dislikes) {
- int p1 = relation[0], p2 = relation[1];
- dislikeTable[p1].emplace_back(p2);
- dislikeTable[p2].emplace_back(p1);
- }
- for (int i = 1; i <= n; i++)
- if (colorTable[i] == uncolored && (!helper(i, blue)))
- return false;
- return true;
- }
-};
-
-int main() {
- Solution obj;
- vvd dislikes1 = {{1, 2}, {1, 3}, {2, 4}},
- dislikes2 = {{1, 2}, {1, 3}, {2, 3}},
- dislikes3 = {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {1, 5}};
- testBool(obj.possibleBipartition(4, dislikes1));
- // true: [2,3] [1,4]
- testBool(obj.possibleBipartition(3, dislikes2));
- // false
- testBool(obj.possibleBipartition(5, dislikes3));
- // false
-}
diff --git a/other/possible_bipartition.rs b/other/possible_bipartition.rs
deleted file mode 100644
index 13b8cf5..0000000
--- a/other/possible_bipartition.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-use std::collections::VecDeque;
-struct Solution;
-
-impl Solution {
- pub fn possible_bipartition(n: i32, dislikes: Vec<Vec<i32>>) -> bool {
- let mut dmap: Vec<Vec<usize>> = vec![vec![]; n as usize];
- for d in dislikes.iter() {
- dmap[d[0] as usize - 1].push(d[1] as usize - 1);
- dmap[d[1] as usize - 1].push(d[0] as usize - 1);
- }
- let mut v: Vec<Option<bool>> = vec![None; n as usize];
- for i in 0..n as usize {
- if v[i].is_some() {
- continue;
- }
- let mut vd: VecDeque<(usize, bool)> = VecDeque::new();
- vd.push_back((i, true));
- while let Some(last) = vd.pop_front() {
- if let Some(b) = v[last.0] {
- if b != last.1 {
- return false;
- }
- continue;
- }
- v[last.0] = Some(last.1);
- for j in dmap[last.0].iter() {
- if v[*j].is_none() {
- vd.push_back((*j, !last.1));
- }
- }
- }
- }
- true
- }
-}
-
-fn main() {
- let dislikes = vec![vec![1,2], vec![1,3], vec![2,4]];
- print!("{}", Solution::possible_bipartition(4, dislikes));
-}
diff --git a/other/power_3.cpp b/other/power_3.cpp
deleted file mode 100644
index f92e6e3..0000000
--- a/other/power_3.cpp
+++ /dev/null
@@ -1,19 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool isPowerOfThree(int n) {
- if (n > 1)
- while (n % 3 == 0)
- n /= 3;
- return n == 1;
- }
-};
-
-int main() {
- Solution obj;
- if (obj.isPowerOfThree(27))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/power_of_four.cpp b/other/power_of_four.cpp
deleted file mode 100644
index ecf6de0..0000000
--- a/other/power_of_four.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool isPowerOfFour(int num) {
- if (num < 0)
- return false;
- int ans = 0, pos = 1, ones = 0;
- while (num) {
- if (num & 1)
- ans += 1, ones = pos;
- num >>= 1, pos += 1;
- }
- return ans == 1 && ones & 1;
- }
-};
-
-int main() {
- Solution obj;
- if (obj.isPowerOfFour(16))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/power_of_four.rs b/other/power_of_four.rs
deleted file mode 100644
index f20335f..0000000
--- a/other/power_of_four.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-//INCOMPLETE
-struct Solution;
-
-impl Solution {
- pub fn is_power_of_four(num: i32) -> bool {
- if num < 0 {
- return false;
- }
- let (ans, pos, ones) = (0, 1, 0);
- while num {
- if num & 1 {
- ans += 1;
- ones = pos;
- }
- num >>= 1;
- pos += 1;
- }
- ans == 1 && ones & 1
- }
-}
-
-fn main() {
- print!("{}", Solution::is_power_of_four(16));
-}
diff --git a/other/power_of_two.cpp b/other/power_of_two.cpp
deleted file mode 100644
index 7e38aeb..0000000
--- a/other/power_of_two.cpp
+++ /dev/null
@@ -1,11 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool isPowerOfTwo(int n) { if (n) }
-};
-
-int main() {
- Solution obj;
- obj.isPowerOfTwo(16);
-}
diff --git a/other/predict_winner.cpp b/other/predict_winner.cpp
deleted file mode 100644
index edf9ee3..0000000
--- a/other/predict_winner.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 486. Predict the Winner
-#include "leetcode.h"
-
-/*
- * given an integer array 'nums'. two players are playing a game with this
- * array: player 1 and player 2. player 1 and player 2 take turns, with player 1
- * starting first. both players start the game with a score of zero. at each
- * turn, the player takes one of the numbers from either end of the array (ie.
- * 'nums[0]', or 'nums[nums.len - 1]') which reduces the size of the array by
- * one. the player adds the chosen number to their score. the game ends when
- * there are no more elements in the array. return 'true' if player 1 can win
- * the game. if the scores of both players are equal, then player 1 is still the
- * winner, and you should also return 'true'. you may assume that both players
- * are playing optimally.
- */
-
-class Solution {
- bool check_win(int ans, int total) { return ans >= total - ans; }
- int max_score(vector<int> &nums, int total, int i, int j) {
- if (i > j)
- return 0;
- return total - min(max_score(nums, total - nums[i], i + 1, j),
- max_score(nums, total - nums[j], i, j - 1));
- }
-
-public:
- bool PredictTheWinner(vector<int> &nums) {
- int total = 0;
- for (auto i : nums)
- total += i;
- return check_win(max_score(nums, total, 0, nums.size() - 1), total);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 5, 2}, n2 = {1, 5, 233, 7};
- printf("%d\n", obj.PredictTheWinner(n1)); // expect: 0
- printf("%d\n", obj.PredictTheWinner(n2)); // expect: 1
-}
diff --git a/other/prefix_suffix_search.cpp b/other/prefix_suffix_search.cpp
deleted file mode 100644
index 67d4d4f..0000000
--- a/other/prefix_suffix_search.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "leetcode.h"
-
-class WordFilter {
-public:
- WordFilter(vector<string> &words) {
- int n = words.size();
- for (int i = 0; i < n; i++) {
- string word = words[i];
- int wordSize = word.size();
- for (int j = 1; j <= wordSize; j++) {
- string p = word.substr(0, j);
- for (int k = 0; k < wordSize; k++) {
- string s = word.substr(k, wordSize);
- hashMap[p + '|' + s] = i + 1;
- }
- }
- }
- }
- int f(string prefix, string suffix) {
- string s = prefix + '|' + suffix;
- return hashMap[s] - 1;
- }
-
-private:
- unordered_map<string, int> hashMap;
-};
diff --git a/other/profitable_schemes.cpp b/other/profitable_schemes.cpp
deleted file mode 100644
index d0f353a..0000000
--- a/other/profitable_schemes.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-// 879. Profitable Schemes
-#include "leetcode.h"
-
-/*
- * there is a group of 'n' members, and a list of various crimes
- * they could commit. the i'th crime generates a 'profit[i]' and
- * requires 'group[i]' members to participate in it. if a member
- * participates in one crime, that member cannot participate in
- * another crime. a profitable scheme is any subset of these crimes
- * that generates at least 'min_profit', and the total number of
- * members participating in that subset of crimes is at most 'n'
- * return the number of schemes that can be chosen.
- */
-
-struct scheme {
- int n;
- int min_profit;
- vector<int> group;
- vector<int> profit;
-};
-
-class Solution {
- vector<int> g, p;
- int mp, mod = 1e9 + 7, dp[101][101][101];
- int find(int id, int n, int total_profit) {
- if (id == p.size())
- return 0;
- if (dp[id][n][total_profit != -1])
- return dp[id][n][total_profit];
- int res = 0;
- if (n >= g[id]) {
- int new_profit = max(0, total_profit - p[id]);
- if (new_profit <= 0)
- res += (1 + find(id + 1, n - g[id], new_profit) % mod) % mod;
- else
- res += find(id + 1, n - g[id], new_profit) % mod;
- }
- res %= mod;
- res += find(id + 1, n, total_profit) % mod;
- res %= mod;
- return dp[id][n][total_profit] = res % mod;
- }
-
-public:
- int profitableSchemes(int n, int min_profit, vector<int> &group,
- vector<int> &profit) {
- mp = min_profit;
- p = profit;
- g = group;
- for (int i = 0; i < 101; i++)
- for (int j = 0; j < 101; j++)
- for (int k = 0; k < 101; k++)
- dp[i][j][k] = -1;
- int ans = find(0, n, mp) % mod;
- if (!mp)
- ans++;
- ans %= mod;
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- scheme one = {.n = 5, .min_profit = 3, .group = {2, 2}, .profit = {2, 3}};
- scheme two = {
- .n = 10, .min_profit = 5, .group = {2, 3, 5}, .profit = {6, 7, 8}};
- printf("%d\n", obj.profitableSchemes(one.n, one.min_profit, one.group,
- one.profit)); // expect: 2
- printf("%d\n", obj.profitableSchemes(two.n, two.min_profit, two.group,
- two.profit)); // expect: 7
-}
diff --git a/other/pseudo_palindrome_binary_tree.cpp b/other/pseudo_palindrome_binary_tree.cpp
deleted file mode 100644
index 63b2cac..0000000
--- a/other/pseudo_palindrome_binary_tree.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int pseudoPalindromicPaths(TreeNode *root) {
- vector<int> v(10, 0);
- dfs(root, v);
- return count;
- }
-
-private:
- int count = 0;
- void dfs(TreeNode *root, vector<int> v) {
- if (root == NULL)
- return;
- v[root->val]++;
- if (root->left == NULL && root->right == NULL) {
- int oddCount = 0;
- for (auto x : v)
- if (x % 2)
- oddCount++;
- if (oddCount <= 1)
- count++;
- return;
- }
- dfs(root->left, v);
- dfs(root->right, v);
- }
-};
diff --git a/other/push_dominoes.cpp b/other/push_dominoes.cpp
deleted file mode 100644
index 859dad9..0000000
--- a/other/push_dominoes.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "leetcode.h"
-#include <string>
-
-class Solution {
-public:
- string pushDominoes(string dominoes) {
- dominoes = 'L' + dominoes + 'R';
- string ans = "";
- for (int i = 0, j = 1; j < dominoes.size(); ++j) {
- if (dominoes[j] == '.')
- continue;
- int middle = j - i - 1;
- if (i > 0)
- ans += dominoes[i];
- if (dominoes[i] == dominoes[j])
- ans += string(middle, dominoes[i]);
- else if (dominoes[i] == 'L' && dominoes[j] == 'R')
- ans += string(middle, '.');
- else
- ans += string(middle / 2, 'R') + string(middle % 2, '.') +
- string(middle / 2, 'L');
- i = j;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.pushDominoes("RR.L");
-}
diff --git a/other/queue_reconstruction.cpp b/other/queue_reconstruction.cpp
deleted file mode 100644
index 17ea0ea..0000000
--- a/other/queue_reconstruction.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<vector<int>> reconstructQueue(vector<vector<int>> &people) {
- sort(people.begin(), people.end(), cmp);
- vector<vector<int>> ans;
- for (int i = 0; i < people.size(); i++)
- ans.insert(ans.begin() + people[i][1], people[i]);
- return ans;
- }
-
-private:
- static bool cmp(vector<int> &p1, vector<int> &p2) {
- if (p1[0] != p2[0])
- return p1[0] > p2[0];
- else
- return p1[1] < p2[1];
- }
-};
diff --git a/other/range_sum_bst.cpp b/other/range_sum_bst.cpp
deleted file mode 100644
index 046aee2..0000000
--- a/other/range_sum_bst.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int rangeSumBST(TreeNode *root, int low, int high) {
- queue<TreeNode *> q;
- q.push(root);
- int sum = 0, v;
- while (q.size()) {
- root = q.front();
- q.pop();
- v = root->val;
- if (v >= low && v <= high)
- sum += v;
- if (v > low && root->left)
- q.push(root->left);
- if (v < high && root->right)
- q.push(root->right);
- }
- return sum;
- }
-};
diff --git a/other/range_sum_bst.rs b/other/range_sum_bst.rs
deleted file mode 100644
index f793202..0000000
--- a/other/range_sum_bst.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-#[derive(Debug, PartialEq, Eq)]
-pub struct TreeNode {
- pub val: i32,
- pub left: Option<Rc<RefCell<TreeNode>>>,
- pub right: Option<Rc<RefCell<TreeNode>>>
-}
-
-impl TreeNode {
- #[inline]
- pub fn new(val: i32) -> Self {
- TreeNode {
- val,
- left: None,
- right: None
- }
- }
-}
-
-use std::rc::Rc;
-use std::cell::RefCell;
-impl Solution {
- pub fn range_sum_bst(root: Option<Rc<RefCell<TreeNode>>>, low: i32, high: i32) -> i32 {
- if let Some(root) = root {
- let mut sum = 0;
- if low <= root.borrow().val && root.borrow().val <= high {
- sum += root.borrow().val;
- }
- if low < root.borrow().val {
- sum += Self::range_sum_bst(root.borrow().left.clone(), low, high);
- }
- if high > root.borrow().val {
- sum += Self::range_sum_bst(root.borrow().right.clone(), low, high);
- }
- return sum;
- }
- 0
- }
-}
diff --git a/other/range_sum_query_2d.cpp b/other/range_sum_query_2d.cpp
deleted file mode 100644
index 9c77900..0000000
--- a/other/range_sum_query_2d.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 304. Range Sum Query 2D - Immutable
-#include "leetcode.h"
-
-/*
- * given a 2d matrix 'matrix', handle multiple queries of the following type:
- * calculate the sum of the elements of 'matrix' inside the rectangle defined by
- * its upper left corner '(row1, col1)' and lower right corer '(row2, col2)'.
- * you must design an algorithm where 'sumRegion' works on 'O(1)' time
- * complexity.
- */
-
-class NumMatrix {
-public:
- vector<vector<int>> sum;
- NumMatrix(vector<vector<int>> &matrix) {
- int m = matrix.size(), n = matrix[0].size();
- sum = vector<vector<int>>(m + 1, vector<int>(n + 1));
- for (int i = 1; i <= m; i++)
- for (int j = 1; j <= n; j++)
- sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] +
- matrix[i - 1][j - 1];
- }
- int sumRegion(int row1, int col1, int row2, int col2) {
- row1++, col1++, row2++, col2++;
- return sum[row2][col2] - sum[row2][col1 - 1] - sum[row1 - 1][col2] +
- sum[row1 - 1][col1 - 1];
- }
-};
-
-int main() {
- vvd matrix = {{3, 0, 1, 4, 2},
- {5, 6, 3, 2, 1},
- {1, 2, 0, 1, 5},
- {4, 1, 0, 1, 7},
- {1, 0, 3, 0, 5}};
- NumMatrix *obj = new NumMatrix(matrix);
- printf("%d\n", obj->sumRegion(2, 1, 4, 3)); // expect: 8
- printf("%d\n", obj->sumRegion(1, 1, 2, 2)); // expect: 11
- printf("%d\n", obj->sumRegion(1, 2, 2, 4)); // expect: 12
-}
diff --git a/other/range_sum_query_mutable.cpp b/other/range_sum_query_mutable.cpp
deleted file mode 100644
index cdc0230..0000000
--- a/other/range_sum_query_mutable.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-#include "leetcode.h"
-
-struct segNode {
- int start, end, sum;
- segNode *left, *right;
- segNode(int a, int b)
- : start(a), end(b), sum(0), left(nullptr), right(nullptr) {}
-};
-
-class NumArray {
-public:
- segNode *root;
- NumArray(vector<int> &nums) { root = buildTree(nums, 0, nums.size() - 1); }
- void update(int index, int val) { modifyTree(index, val, root); }
- int sumRange(int left, int right) { return queryTree(left, right, root); }
-
-private:
- segNode *buildTree(vector<int> &nums, int start, int end) {
- if (start > end)
- return nullptr;
- segNode *root = new segNode(start, end);
- if (start == end) {
- root->sum = nums[start];
- return root;
- }
- int mid = start + (end - start) / 2;
- root->left = buildTree(nums, start, mid);
- root->right = buildTree(nums, mid + 1, end);
- root->sum = root->left->sum + root->right->sum;
- return root;
- }
- int modifyTree(int i, int val, segNode *root) {
- if (root == nullptr)
- return 0;
- int diff;
- if (root->start == i && root->end == i) {
- diff = val - root->sum;
- root->sum = val;
- return diff;
- }
- int mid = (root->start + root->end) / 2;
- if (i > mid)
- diff = modifyTree(i, val, root->right);
- else
- diff = modifyTree(i, val, root->left);
- root->sum = root->sum + diff;
- return diff;
- }
- int queryTree(int i, int j, segNode *root) {
- if (root == nullptr)
- return 0;
- if (root->start == i && root->end == j)
- return root->sum;
- int mid = (root->start + root->end) / 2;
- if (i > mid)
- return queryTree(i, j, root->right);
- if (j <= mid)
- return queryTree(i, j, root->left);
- return queryTree(i, mid, root->left) + queryTree(mid + 1, j, root->right);
- }
-};
diff --git a/other/ransom_note.cpp b/other/ransom_note.cpp
deleted file mode 100644
index 1a78e07..0000000
--- a/other/ransom_note.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool canConstruct(string ransomNote, string magazine) {
- int count[26] = {0};
- for (char ch : magazine)
- count[ch - 'a']++;
- for (char ch : ransomNote)
- if (count[ch - 'a']-- <= 0)
- return false;
- return true;
- }
-};
-
-int main() {
- Solution obj;
- string ransomNote = "a", magazine = "b";
- if (obj.canConstruct(ransomNote, magazine))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/rectangle_area.cpp b/other/rectangle_area.cpp
deleted file mode 100644
index fa56d94..0000000
--- a/other/rectangle_area.cpp
+++ /dev/null
@@ -1,16 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2,
- int by2) {
- return (ax2 - ax1) * (ay2 - ay1) + (bx2 - bx1) * (by2 - by1) -
- max(min(ax2, bx2) - max(ax1, bx1), 0) *
- max(min(ay2, by2) - max(ay1, by1), 0);
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.computeArea(-3, 0, 3, 4, 0, -1, 9, 2);
-}
diff --git a/other/rectangle_area.rs b/other/rectangle_area.rs
deleted file mode 100644
index 4d9c013..0000000
--- a/other/rectangle_area.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn compute_area(ax1: i32, ay1: i32, ax2: i32, ay2: i32, bx1: i32, by1: i32, bx2: i32, by2: i32) -> i32 {
- (ax2 - ax1) * (ay2 - ay1) +
- (bx2 - bx1) * (by2 - by1) -
- 0.max(ax2.min(bx2) - ax1.max(bx1)) *
- 0.max(ay2.min(by2) - ay1.max(by1))
- }
-}
-
-fn main() {
- print!("{}", Solution::compute_area(-3, 0, 3, 4, 0, -1, 9, 2));
-}
diff --git a/other/rectangle_fewest_squares.cpp b/other/rectangle_fewest_squares.cpp
deleted file mode 100644
index ef56533..0000000
--- a/other/rectangle_fewest_squares.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maxDepth = 0;
- int tilingRectangle(int n, int m) {
- if (n > m)
- swap(n, m);
- vector<int> s;
- for (int i = 0; i < n; i++)
- s.push_back(m);
- maxDepth = max(n, m);
- dfs(s, 0);
- return maxDepth;
- }
-
-private:
- typedef long long key;
- unordered_map<key, int> dp;
- key hash(vector<int> &j) {
- key r = 0;
- for (int n : j)
- r = (r << 4LL) + n;
- return r;
- }
- void dfs(vector<int> j, int depth) {
- key h = hash(j);
- if (h == 0) {
- maxDepth = min(maxDepth, depth);
- return;
- }
- if (depth >= maxDepth || dp.count(h))
- return;
- auto topLeft = max_element(j.begin(), j.end());
- int width = 1;
- for (auto top = topLeft + 1; top != j.end() && *top == *topLeft; top++)
- width++;
- for (int w = min(width, *topLeft); w > 0; w--) {
- for (int i = 0; i < w; i++)
- *(topLeft + i) -= w;
- dfs(j, depth + 1);
- for (int i = 0; i < w; i++)
- *(topLeft + i) += w;
- }
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.tilingRectangle(2, 3);
-}
diff --git a/other/reduce_array_size_half.cpp b/other/reduce_array_size_half.cpp
deleted file mode 100644
index fd922dc..0000000
--- a/other/reduce_array_size_half.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minSetSize(vector<int> &arr) {
- int ans = 0, n = arr.size(), n1 = 0;
- vector<int> j;
- unordered_map<int, int> um;
- for (int i = 0; i < n; i++)
- um[arr[i]]++;
- for (auto x : um)
- j.push_back(x.second);
- if (j.size() == 1)
- return 1;
- sort(j.begin(), j.end());
- for (int i = j.size() - 1; i >= 0; i--) {
- if (ans >= n / 2)
- return n1;
- n1++;
- ans = ans + j[i];
- }
- return 0;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> arr = {3, 3, 3, 3, 5, 5, 5, 2, 2, 7};
- cout << obj.minSetSize(arr);
-}
diff --git a/other/reducing_dishes.cpp b/other/reducing_dishes.cpp
deleted file mode 100644
index 3982095..0000000
--- a/other/reducing_dishes.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// 1402. Reducing Dishes
-#include "leetcode.h"
-
-/*
- * a chef has collected data on the 'satisfaction' level of his 'n' dishes. chef
- * can cook any dish in 1 unit of time. like-time coefficient of a dish is
- * defined as the time taken to cook that dish including previous dishes
- * multiplied by its satisfaction level - eg. 'time[i] * satisfaction[i]'.
- * return maximum sum of like-time coefficient that the chef can obtain after
- * dishes preparation. dishes can be prepared in any order and the chef can
- * discard some dishes to get this maximum value.
- */
-
-class Solution {
-public:
- int maxSatisfaction(vector<int> &satisfaction) {
- sort(satisfaction.begin(), satisfaction.end(), greater<int>());
- int n = satisfaction.size(), pre_sum = 0, ans = 0;
- for (int i = 0; i < n; i++) {
- pre_sum += satisfaction[i];
- if (pre_sum < 0)
- break;
- ans += pre_sum;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> s1 = {-1, -8, 0, 5, -9};
- vector<int> s2 = {4, 3, 2};
- vector<int> s3 = {-1, -4, -5};
- printf("%d\n", obj.maxSatisfaction(s1)); // expect: 14
- printf("%d\n", obj.maxSatisfaction(s2)); // expect: 20
- printf("%d\n", obj.maxSatisfaction(s3)); // expect: 0
-}
diff --git a/other/remove_adjacent_dup.cpp b/other/remove_adjacent_dup.cpp
deleted file mode 100644
index c0cc341..0000000
--- a/other/remove_adjacent_dup.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string removeDuplicates(string s, int k) {
- // cout << s << endl << k << endl;
- if (s.size() < k)
- return s;
- stack<pair<char, int>> stk;
- for (int i = 0; i < s.size(); ++i) {
- if (stk.empty() || stk.top().first != s[i])
- stk.push({s[i], 1});
- else {
- auto prev = stk.top();
- stk.pop();
- stk.push({s[i], prev.second + 1});
- }
- if (stk.top().second == k)
- stk.pop();
- }
- string ans = "";
- while (!stk.empty()) {
- auto curr = stk.top();
- stk.pop();
- while (curr.second--)
- ans.push_back(curr.first);
- }
- reverse(ans.begin(), ans.end());
- // cout << ans;
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- obj.removeDuplicates("deeedbbcccbdaa", 3);
-}
diff --git a/other/remove_adjacent_dup_str.cpp b/other/remove_adjacent_dup_str.cpp
deleted file mode 100644
index 80b61ab..0000000
--- a/other/remove_adjacent_dup_str.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string removeDuplicates(string s) {
- string ans;
- for (char &c : s) {
- if (ans.size() && c == ans.back())
- ans.pop_back();
- else
- ans.push_back(c);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.removeDuplicates("abbaca");
-}
diff --git a/other/remove_adjacent_dup_str.rs b/other/remove_adjacent_dup_str.rs
deleted file mode 100644
index 063cfbb..0000000
--- a/other/remove_adjacent_dup_str.rs
+++ /dev/null
@@ -1,20 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn remove_duplicates(s: String) -> String {
- let mut ans = String::new();
- for c in s.chars() {
- if ans.len() > 0 && ans.chars().last() == Some(c) {
- ans.pop();
- } else {
- ans.push(c);
- }
- }
- ans
- }
-}
-
-fn main() {
- let s = "abbaca".to_string();
- print!("{}", Solution::remove_duplicates(s));
-}
diff --git a/other/remove_boxes.cpp b/other/remove_boxes.cpp
deleted file mode 100644
index 47f62a9..0000000
--- a/other/remove_boxes.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 546. Remove Boxes
-#include "leetcode.h"
-
-/*
- * given several 'boxes' with different colours represented by different
- * positive numbers. you may experience several rounds to remove boxes until
- * there is no box left. each time you can choose some continuous boxes with the
- * same colour (ie. composed of 'k' boxes, 'k >= 1'), remove them and get 'k *
- * k' points. return the maximum points you can get.
- */
-
-class Solution {
- int dp[100][100][100] = {0};
- int dfs(vector<int> &boxes, int i, int j, int k) {
- if (j < i)
- return 0;
- if (dp[i][j][k])
- return dp[i][j][k];
- int res = (1 + k) * (1 + k) + dfs(boxes, i + 1, j, 0);
- for (int m = i + 1; m <= j; m++)
- if (boxes[m] == boxes[i])
- res = max(res, dfs(boxes, i + 1, m - 1, 0) + dfs(boxes, m, j, k + 1));
- dp[i][j][k] = res;
- return res;
- }
-
-public:
- int removeBoxes(vector<int> &boxes) {
- int n = boxes.size();
- return dfs(boxes, 0, n - 1, 0);
- }
-};
-
-int main() {
- Solution obj;
- vector<int> b1 = {1, 3, 2, 2, 2, 3, 4, 3, 1}, b2 = {1, 1, 1}, b3 = {1};
- printf("%d\n", obj.removeBoxes(b1)); // expect: 23
- printf("%d\n", obj.removeBoxes(b2)); // expect: 9
- printf("%d\n", obj.removeBoxes(b3)); // expect: 1
-}
diff --git a/other/remove_dupplicate.cpp b/other/remove_dupplicate.cpp
deleted file mode 100644
index 2628677..0000000
--- a/other/remove_dupplicate.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int removeDuplicates(vector<int> &nums) {
- if (nums.size() == 0)
- return 0;
- int ans = 0;
- for (int i = 1; i < nums.size(); i++) {
- if (nums[ans] != nums[i])
- ans++;
- nums[ans] = nums[i];
- }
- return ans + 1;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
- cout << obj.removeDuplicates(nums);
-}
diff --git a/other/remove_dupplicate.rs b/other/remove_dupplicate.rs
deleted file mode 100644
index c192b22..0000000
--- a/other/remove_dupplicate.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn remove_duplicates(nums: &mut Vec<i32>) -> i32 {
- match nums.is_empty() {
- true => 0,
- false => {
- let mut prev = 0;
- for i in 1..nums.len() {
- if nums[prev] != nums[i] {
- prev += 1;
- nums[prev] = nums[i];
- }
- }
- (prev + 1) as i32
- }
- }
- }
-}
-
-fn main() {
- let mut nums = vec![0,0,1,1,1,2,2,3,3,4];
- print!("{}", Solution::remove_duplicates(nums));
-}
diff --git a/other/remove_element.cpp b/other/remove_element.cpp
deleted file mode 100644
index 644f239..0000000
--- a/other/remove_element.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int removeElement(vector<int> &nums, int val) {
- int idx = 0, k = nums.size();
- while (idx < k) {
- if (nums[idx] == val) {
- // cout << "idx " << idx << endl;
- // cout << "k " << k << endl;
- nums[idx] = nums[k - 1];
- --k;
- } else
- ++idx;
- }
- return k;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {0, 1, 2, 2, 3, 0, 4, 2};
- int val = 2;
- for (int i = 0; i < nums.size(); i++)
- cout << nums[i] << ' ';
- cout << endl << nums.size() << endl;
- cout << obj.removeElement(nums, val);
-}
diff --git a/other/remove_element.rs b/other/remove_element.rs
deleted file mode 100644
index fec38b6..0000000
--- a/other/remove_element.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-use std::convert::TryInto;
-struct Solution;
-
-impl Solution {
- pub fn remove_element(mut nums: Vec<i32>, val: i32) -> i32 {
- let (mut idx, mut k) = (0, nums.len());
- while idx < k {
- if nums[idx] == val {
- nums[idx] = nums[k - 1];
- k -= 1;
- } else {
- idx += 1;
- }
- }
- k.try_into().unwrap()
- }
-}
-
-fn main() {
- let nums = vec![0,1,2,2,3,0,4,2];
- print!("{}", Solution::remove_element(nums, 2));
-}
diff --git a/other/remove_max_num_edge_traverse.cpp b/other/remove_max_num_edge_traverse.cpp
deleted file mode 100644
index 8cc215a..0000000
--- a/other/remove_max_num_edge_traverse.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-// 1579. Remove Max Number of Edges to Keep Graph Fully Traversable
-#include "leetcode.h"
-
-/*
- * alice and bob have an undirected graph of 'n' nodes and three
- * types of edges:
- * type1: can be traversed by alice only
- * type2: can be traversed by bob only
- * type3: can be traversed by both alice and bob
- * given an array of 'edges' where 'edges[i] = [typei, ui, vi]'
- * represents a bidirectional edge of type 'typei' between nodes
- * 'ui' and 'vi', find the maximum number of edges you can remove
- * so that after removing the edges, the graph can still be fully
- * traversed by alice and bob if starting from any node, they can
- * reach all other nodes. return the maximum number of edges you
- * can remove, or return -1 if alice and bob cannot traverse graph
- */
-
-class Solution {
-public:
- int find(vector<int> &ds, int i) {
- return ds[i] < 0 ? i : ds[i] = find(ds, ds[i]);
- }
- int maxNumEdgesToRemove(int n, vvd & edges) {
- vector<int> ds_both(n + 1, -1);
- int used = 0;
- for (int type = 3; type > 0; --type) {
- auto ds_one = ds_both;
- auto &ds = type == 3 ? ds_both : ds_one;
- for (auto &e : edges) {
- if (e[0] == type) {
- int i = find(ds, e[1]), j = find(ds, e[2]);
- if (i != j) {
- ++used;
- if (ds[j] < ds[i])
- swap(i, j);
- ds[i] += ds[j];
- ds[j] = i;
- }
- }
- }
- if (type != 3 && ds[find(ds, 1)] != -n)
- return -1;
- }
- return edges.size() - used;
- }
-};
-
-int main() {
- Solution obj;
- vvd
- e1 = {{3, 1, 2}, {3, 2, 3}, {1, 1, 3}, {1, 2, 4}, {1, 1, 2}, {2, 3, 4}};
- vvd e2 = {{3, 1, 2}, {3, 2, 3}, {1, 1, 4}, {2, 1, 4}};
- vvd e3 = {{3, 2, 3}, {1, 1, 2}, {2, 3, 4}};
- printf("%d\n", obj.maxNumEdgesToRemove(4, e1));
- printf("%d\n", obj.maxNumEdgesToRemove(4, e2));
- printf("%d\n", obj.maxNumEdgesToRemove(4, e3));
-}
diff --git a/other/remove_nth_node.cpp b/other/remove_nth_node.cpp
deleted file mode 100644
index 38f8a72..0000000
--- a/other/remove_nth_node.cpp
+++ /dev/null
@@ -1,18 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- ListNode *removeNthFromEnd(ListNode *head, int n) {
- ListNode *fast = head, *slow = head;
- for (int i = 0; i < n; i++)
- fast = fast->next;
- if (!fast)
- return head->next;
- while (fast->next) {
- fast = fast->next;
- slow = slow->next;
- }
- slow->next = slow->next->next;
- return head;
- }
-};
diff --git a/other/remove_palindromic_subsequence.cpp b/other/remove_palindromic_subsequence.cpp
deleted file mode 100644
index cbf7182..0000000
--- a/other/remove_palindromic_subsequence.cpp
+++ /dev/null
@@ -1,19 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int removePalindromeSub(string s) {
- if (s.size() == 0)
- return 0;
- for (int i = 0, j = s.size() - 1; i < j; i++, j--)
- if (s[i] != s[j])
- return 2;
- return 1;
- }
-};
-
-int main() {
- string s = "ababa";
- Solution obj;
- cout << obj.removePalindromeSub(s);
-}
diff --git a/other/remove_star_string.cpp b/other/remove_star_string.cpp
deleted file mode 100644
index c7cbfb5..0000000
--- a/other/remove_star_string.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// 2390. Removing Stars From a String
-#include "leetcode.h"
-
-/*
- * given a string 's', which contains stars (*). in one operation
- * you can choose a start in 's', remove the closest non-star
- * character to its left, as well remove the star itself.
- * return string after all stars have been removed. note, the
- * input will be generated such that the operation is always
- * possible, and the resulting string will always be unique
- */
-
-class Solution {
-public:
- string removeStars(string s) {
- stack<char> stk;
- string ans;
- vector<char> vec;
- for (int i = 0; i < s.size(); i++) {
- if (s[i] != '*')
- stk.emplace(s[i]);
- else
- stk.pop();
- }
- while (!stk.empty()) {
- vec.emplace_back(stk.top());
- stk.pop();
- }
- reverse(vec.begin(), vec.end());
- for (int i = 0; i < vec.size(); i++)
- ans += vec[i];
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.removeStars("leet**cod*e") << endl; // expect: lecoe
- cout << obj.removeStars("erase*****") << endl; // expect: null
-}
diff --git a/other/remove_stones.cpp b/other/remove_stones.cpp
deleted file mode 100644
index f267b0c..0000000
--- a/other/remove_stones.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minStoneSum(vector<int> &piles, int k) {
- priority_queue<int> pq(piles.begin(), piles.end());
- int ans = accumulate(piles.begin(), piles.end(), 0);
- while (k--) {
- int i = pq.top();
- pq.pop();
- pq.push(i - i / 2);
- ans -= i / 2;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> piles1 = {5, 4, 9}, piles2 = {4, 3, 6, 7};
- cout << obj.minStoneSum(piles1, 2); // expect: 12
- cout << endl;
- cout << obj.minStoneSum(piles2, 3); // expect: 12
-}
diff --git a/other/remove_stones.rs b/other/remove_stones.rs
deleted file mode 100644
index e55eade..0000000
--- a/other/remove_stones.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-use std::collections::BinaryHeap;
-struct Solution;
-
-impl Solution {
- pub fn min_stone_sum(piles: Vec<i32>, mut k: i32) -> i32 {
- let mut max_heap = BinaryHeap::<i32>::new();
- for i in piles {
- max_heap.push(i);
- }
- while k > 0 {
- if let Some(top) = max_heap.pop() {
- let removed = top - top / 2;
- max_heap.push(removed);
- }
- k -= 1;
- }
- max_heap.iter().sum()
- }
-}
-
-fn main() {
- let piles1 = vec![5,4,9];
- let piles2 = vec![4,3,6,7];
- println!("{}", Solution::min_stone_sum(piles1, 2)); //expect: 12
- println!("{}", Solution::min_stone_sum(piles2, 3)); //expect: 12
-}
diff --git a/other/remove_subfolder_filesystem.cpp b/other/remove_subfolder_filesystem.cpp
deleted file mode 100644
index 5ec1813..0000000
--- a/other/remove_subfolder_filesystem.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-// 1233. Remove Sub-Folders from the Filesystem
-#include "leetcode.h"
-
-/*
- * given a list of folders 'folder', return the folders after removing all the
- * sub-folders in those folders. you may return the answer in any order. if a
- * 'folder[i]' is located within another 'folder[j]', it is called a sub-folder
- * of it. a sub-folder of 'folder[j]' must start with 'folder[j]', followed by
- * '/'. the format of a path is one ormore concatenated strings of the form: '/'
- * followed by one or more lowercase english letters.
- */
-
-class Solution {
-public:
- vector<string> removeSubfolders(vector<string> &folder) {
- sort(folder.begin(), folder.end());
- vector<string> ans;
- for (auto i : folder) {
- if (!ans.size()) {
- ans.push_back(i);
- continue;
- }
- string parent = ans[ans.size() - 1];
- if (i.substr(0, parent.size() + 1) != parent + '/')
- ans.push_back(i);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<string> f1 = {"/a", "/a/b", "/c/d", "/c/d/e", "/c/f"},
- rsf1 = obj.removeSubfolders(f1);
- vector<string> f2 = {"/a", "/a/b/c", "/a/b/d"},
- rsf2 = obj.removeSubfolders(f2);
- vector<string> f3 = {"/a/b/c", "/a/b/ca", "/a/b/d"},
- rsf3 = obj.removeSubfolders(f3);
- for (int i = 0; i < rsf1.size(); i++)
- cout << rsf1[i] << ' '; // expect: ["/a","/c/d","/c/f"]
- printf("\n");
- for (int i = 0; i < rsf2.size(); i++)
- cout << rsf2[i] << ' '; // expect: ["/a"]
- printf("\n");
- for (int i = 0; i < rsf3.size(); i++)
- cout << rsf3[i] << ' '; // expect: ["/a/b/c","/a/b/ca","/a/b/d"]
- printf("\n");
-}
diff --git a/other/remove_substring.cpp b/other/remove_substring.cpp
deleted file mode 100644
index a5572be..0000000
--- a/other/remove_substring.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-// 1910. Remove All Occurrences of a Substring
-#include "leetcode.h"
-
-/*
- * given two strings 's' and 'part', perform the following operation on 's'
- * until all occurrences of the substring 'part' are removed; find the leftmost
- * occurrence of the substring 'part' and remove it from 's'. return 's' after
- * removing all occurrences of 'part'. a substring is a contiguous sequence of
- * characters in a string
- */
-
-class Solution {
-public:
- string removeOccurrences(string s, string part) {
- while (s.size() && s.find(part) < s.size())
- s.erase(s.find(part), part.size());
- return s;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.removeOccurrences("daabcbaabcbc", "abc") << endl; // expect: dab
- cout << obj.removeOccurrences("axxxxyyyyb", "xy") << endl; // expect: ab
-}
diff --git a/other/reorder_route_city_zero.cpp b/other/reorder_route_city_zero.cpp
deleted file mode 100644
index 10ae61a..0000000
--- a/other/reorder_route_city_zero.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-// 1466. Reorder Routes to Make All Paths Lead to the City Zero
-#include "leetcode.h"
-
-/*
- * there are 'n' cities numbered from 0 to 'n - 1' and 'n - 1'
- * roads such that there is only one way to travel between two
- * different cities (this network forms a tree). last year, the
- * ministry of transport decided to orient the roads in one
- * direction because they are too narrow.
- * roads are represented by 'connections' where 'connections[i] = [ai, bi]'
- * represents a road from city 'ai' to city 'bi'.
- * this year, there will be a big event in the capital (city 0),
- * and many people will want to travel to the city. task consists
- * reorienting some roads such that each city can visit city 0.
- * return minimum number of edges changed.
- */
-
-class Solution {
-public:
- int minReorder(int n, vvd & connections) {
- vvd ans(n);
- for (auto &c : connections) {
- ans[c[0]].push_back(c[1]);
- ans[c[1]].push_back(-c[0]);
- }
- return dfs(ans, vector<bool>(n) = {}, 0);
- }
-
-private:
- int dfs(vvd & res, vector<bool> visited, int from) {
- auto change = 0;
- visited[from] = true;
- for (auto to : res[from])
- if (!visited[abs(to)])
- change += dfs(res, visited, abs(to)) + (to > 0);
- return change;
- }
-};
-
-int main() {
- Solution obj;
- vvd connections1 = {{0, 1}, {1, 3}, {2, 3}, {4, 0}, {4, 5}};
- vvd connections2 = {{1, 0}, {1, 2}, {3, 2}, {3, 4}};
- vvd connections3 = {{1, 0}, {2, 0}};
- cout << obj.minReorder(6, connections1) << endl; // expect: 3
- cout << obj.minReorder(5, connections2) << endl; // expect: 2
- cout << obj.minReorder(3, connections3) << endl; // expect: 0
-}
diff --git a/other/reordered_power2.cpp b/other/reordered_power2.cpp
deleted file mode 100644
index d458052..0000000
--- a/other/reordered_power2.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool reorderedPowerOf2(int n) {
- string ans1 = to_string(n);
- sort(ans1.begin(), ans1.end());
- for (int i = 0; i < 30; i++) {
- string ans2 = to_string(1 << i);
- sort(ans2.begin(), ans2.end());
- if (ans1 == ans2)
- return true;
- }
- return false;
- }
-};
-
-int main() {
- Solution obj;
- if (obj.reorderedPowerOf2(10))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/reorganise_string.cpp b/other/reorganise_string.cpp
deleted file mode 100644
index 7a42643..0000000
--- a/other/reorganise_string.cpp
+++ /dev/null
@@ -1,41 +0,0 @@
-// 767. Reorganize String
-#include "leetcode.h"
-
-/*
- * given a string 's', rearrange the characters of 's' so that any two adjacent
- * characters are not the same. return any possible arrangement of 's', or
- * return "" if not possible.
- */
-
-class Solution {
-public:
- string reorganizeString(string s) {
- vector<int> cnt(26);
- int most_freq = 0, i = 0;
- for (char c : s)
- if (++cnt[c - 'a'] > cnt[most_freq])
- most_freq = (c - 'a');
- if (2 * cnt[most_freq] - 1 > s.size())
- return "";
- while (cnt[most_freq]) {
- s[i] = ('a' + most_freq);
- i += 2;
- cnt[most_freq]--;
- }
- for (int j = 0; j < 26; j++)
- while (cnt[j]) {
- if (i >= s.size())
- i = 1;
- s[i] = ('a' + j);
- cnt[j]--;
- i += 2;
- }
- return s;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.reorganizeString("aab"); // expect: aba
- cout << obj.reorganizeString("aaab"); // expect:
-}
diff --git a/other/repeated_substring_pattern.cpp b/other/repeated_substring_pattern.cpp
deleted file mode 100644
index 4e2d8d8..0000000
--- a/other/repeated_substring_pattern.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-// 459. Repeated Substring Pattern
-#include "leetcode.h"
-
-/*
- * given a string 's', check if it can be constructed by taking a substring of
- * it and appending multiple copies of the substring together.
- */
-
-class Solution {
-public:
- bool repeatedSubstringPattern(string s) {
- int i = 1, j = 0, n = s.size();
- vector<int> dp(n + 1, 0);
- while (i < n) {
- if (s[i] == s[j])
- dp[++i] = ++j;
- else if (!j)
- i++;
- else
- j = dp[j];
- }
- return dp[n] && dp[n] % (n - dp[n]) == 0;
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.repeatedSubstringPattern("abab")); // expect: 1
- printf("%d\n", obj.repeatedSubstringPattern("aba")); // expect: 0
- printf("%d\n", obj.repeatedSubstringPattern("abcabcabcabc")); // expect: 1
-}
diff --git a/other/restore_array.cpp b/other/restore_array.cpp
deleted file mode 100644
index 4f4a59a..0000000
--- a/other/restore_array.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// 1416. Restore The Array
-#include "leetcode.h"
-
-/*
- * a progamme was supposed to print an array of integers. the programme forgot
- * to print whitespace and the array is printing as a string of digits 's' and
- * all we know is that all integers in the array were in the range [1, k] and
- * there are no leading zeros in the array. given the string 's' and the integer
- * 'k', return the number of possible arrays that can be printed as 's' using
- * the mentioned programme. return modulo 10^9+7
- */
-
-class Solution {
-public:
- int numberOfArrays(string s, int k) {
- vector<int> dp(s.size() + 1);
- dp[s.size()] = 1;
- for (int i = s.size() - 1; i >= 0; --i) {
- if (s[i] == '0')
- continue;
- for (long sz = 1, n = 0; i + sz <= s.size(); ++sz) {
- n = n * 10 + s[i + sz - 1] - '0';
- if (n > k)
- break;
- dp[i] = (dp[i] + dp[i + sz]) % 1000000007;
- }
- }
- return dp[0];
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.numberOfArrays("1000", 10000)); // expect: 1
- printf("%d\n", obj.numberOfArrays("1000", 10)); // expect: 0
- printf("%d\n", obj.numberOfArrays("1317", 2000)); // expect: 8
-}
diff --git a/other/restore_ip_addr.cpp b/other/restore_ip_addr.cpp
deleted file mode 100644
index eba5de2..0000000
--- a/other/restore_ip_addr.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-// 93. Restore IP Addresses
-#include "leetcode.h"
-
-/*
- * a valid ip address consists of exactly 4 integers separated by single dots
- * each integer is between 0 and 255 (inclusive) and cannot have leading 0's
- * given: string 's' containing only digits, return all possible valid ip
- * addresses that can be formed by insert dots into 's'. digits cannot be
- * reordered or removed. return addresses in any order.
- */
-
-class Solution {
-public:
- vector<string> restoreIpAddresses(string s) {
- vector<string> ans;
- string ip;
- dfs(s, 0, 0, ip, ans);
- return ans;
- }
-
-private:
- void dfs(string s, int start, int step, string ip, vector<string> &res) {
- if (start == s.size() && step == 4) {
- ip.erase(ip.end() - 1);
- res.push_back(ip);
- return;
- }
- if (s.size() - start > (4 - step) * 3)
- return;
- if (s.size() - start < (4 - step))
- return;
- int num = 0;
- for (int i = start; i < start + 3; i++) {
- num = num * 10 + (s[i] - '0');
- if (num <= 255) {
- ip += s[i];
- dfs(s, i + 1, step + 1, ip + '.', res);
- }
- if (num == 0)
- break;
- }
- }
-};
-
-int main() {
- Solution obj;
- for (auto i : obj.restoreIpAddresses("25525511135"))
- cout << i; // expect: 255.255.11.135","255.255.111.35
- cout << endl;
- for (auto i : obj.restoreIpAddresses("0000"))
- cout << i; // expect: 0.0.0.0
- cout << endl;
- for (auto i : obj.restoreIpAddresses("101023"))
- cout << i; // expect: 1.0.10.23,1.0.102.3,10.1.0.23,10.10.2.3,101.0.2.3
- cout << endl;
-}
diff --git a/other/reverse_integer.cpp b/other/reverse_integer.cpp
deleted file mode 100644
index 14f55cd..0000000
--- a/other/reverse_integer.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-// 7. Reverse Integer
-#include "leetcode.h"
-
-/*
- * given a signed 32-bit integer 'x', return 'x' with its digits reversed. if
- * reversing 'x' causes the value to go outside the signed 32-bit integer range,
- * then return 0
- */
-
-class Solution {
-public:
- int reverse(int x) {
- int ans = 0;
- while (x) {
- int tmp = ans * 10 + x % 10;
- if (tmp / 10 != ans)
- return 0;
- ans = tmp;
- x /= 10;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- printf("%d --> %d\n", 123, obj.reverse(123));
- printf("%d --> %d\n", -123, obj.reverse(-123));
- printf("%d --> %d\n", 120, obj.reverse(120));
-}
diff --git a/other/reverse_linked_list.cpp b/other/reverse_linked_list.cpp
deleted file mode 100644
index e3a1793..0000000
--- a/other/reverse_linked_list.cpp
+++ /dev/null
@@ -1,16 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- ListNode *reverseList(ListNode *head) {
- ListNode *pre = new ListNode(0), *curr = head;
- pre->next = head;
- while (curr && curr->next) {
- ListNode *tmp = pre->next;
- pre->next = curr->next;
- curr->next = curr->next->next;
- pre->next->next = tmp;
- }
- return pre->next;
- }
-};
diff --git a/other/reverse_linked_list2.cpp b/other/reverse_linked_list2.cpp
deleted file mode 100644
index dbbb261..0000000
--- a/other/reverse_linked_list2.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- ListNode *reverseBetween(ListNode *head, int left, int right) {
- if (head == NULL || head->next == NULL)
- return head;
- ListNode *tmp = new ListNode(-1);
- tmp->next = head;
- ListNode *itL = tmp, *preL = NULL;
- for (int i = 0; i < left; i++) {
- preL = itL;
- itL = itL->next;
- }
- ListNode *itR = itL, *preR = preL;
- for (int i = left; i <= right; i++) {
- ListNode *forward = itR->next;
- itR->next = preR;
- preR = itR;
- itR = forward;
- }
- preL->next = preR;
- itL->next = itR;
- return tmp->next;
- }
-};
diff --git a/other/reverse_string.cpp b/other/reverse_string.cpp
deleted file mode 100644
index f5940a0..0000000
--- a/other/reverse_string.cpp
+++ /dev/null
@@ -1,15 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- void reverseString(vector<char> &s) {
- int i = 0, j = s.size() - 1;
- while (i <= j) {
- char tmp = s[i];
- s[i] = s[j];
- s[j] = tmp;
- i++;
- j--;
- }
- }
-};
diff --git a/other/reverse_string2.cpp b/other/reverse_string2.cpp
deleted file mode 100644
index 839a26f..0000000
--- a/other/reverse_string2.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string reverseStr(string s, int k) {
- int len = s.size(), rem = len % (2 * k);
- int start = 0, end = 2 * k, actual = len - rem;
- string ans = "";
- while (actual) {
- string tmp = s.substr(start, end);
- reverse(tmp.begin(), tmp.begin() + k);
- start += 2 * k;
- ans += tmp;
- actual -= 2 * k;
- }
- if (rem > 0) {
- if (rem < k) {
- string tmp = s.substr(len - rem, rem);
- reverse(tmp.begin(), tmp.end());
- ans += tmp;
- } else if (rem <= 2 * k) {
- string tmp = s.substr(len - rem, rem);
- reverse(tmp.begin(), tmp.begin() + k);
- ans += tmp;
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.reverseStr("abcdefg", 2);
-}
diff --git a/other/reverse_string3.cpp b/other/reverse_string3.cpp
deleted file mode 100644
index 0cc2cf5..0000000
--- a/other/reverse_string3.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string reverseWords(string s) {
- int i = 0;
- for (int j = 0; j < s.size(); ++j) {
- if (s[j] == ' ') {
- reverse(s.begin() + i, s.begin() + j);
- i = j + 1;
- }
- }
- reverse(s.begin() + i, s.end());
- return s;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.reverseWords("Let's take LeetCode contest");
-}
diff --git a/other/reverse_vowel_string.cpp b/other/reverse_vowel_string.cpp
deleted file mode 100644
index aa9a039..0000000
--- a/other/reverse_vowel_string.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string reverseVowels(string s) {
- int i = 0, j = s.size() - 1;
- while (i < j) {
- i = s.find_first_of("aeiouAEIOU", i);
- j = s.find_last_of("aeiouAEIOU", j);
- if (i < j)
- swap(s[i++], s[j--]);
- }
- return s;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.reverseVowels("hello");
-}
diff --git a/other/reverse_vowel_string.rs b/other/reverse_vowel_string.rs
deleted file mode 100644
index 4ae282d..0000000
--- a/other/reverse_vowel_string.rs
+++ /dev/null
@@ -1,33 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn reverse_vowels(s: String) -> String {
- let (mut i, mut j) = (0, s.len().checked_sub(1).unwrap_or(0));
- let mut cs = s.chars().collect::<Vec<char>>();
- while i < j {
- if !Self::is_vowel(cs[i].to_ascii_lowercase()) {
- i += 1;
- continue
- }
- if !Self::is_vowel(cs[j].to_ascii_lowercase()) {
- j -= 1;
- continue
- }
- cs.swap(i, j);
- i += 1;
- j -= 1;
- }
- cs.iter().collect()
- }
- fn is_vowel(c: char) -> bool {
- match c {
- 'a' | 'e' | 'i' | 'o' | 'u' => true,
- _ => false
- }
- }
-}
-
-fn main() {
- let s = "hello".to_string();
- print!("{}", Solution::reverse_vowels(s));
-}
diff --git a/other/reverse_word_string.cpp b/other/reverse_word_string.cpp
deleted file mode 100644
index 0259e04..0000000
--- a/other/reverse_word_string.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string reverseWords(string s) {
- reverse(s.begin(), s.end());
- int l = 0, r = 0, i = 0, n = s.size();
- while (i < n) {
- while (i < n && s[i] != ' ')
- s[r++] = s[i++];
- if (l < r) {
- reverse(s.begin() + l, s.begin() + r);
- if (r == n)
- break;
- s[r++] = ' ';
- l = r;
- }
- ++i;
- }
- if (r > 0 && s[r - 1] == ' ')
- --r;
- s.resize(r);
- return s;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.reverseWords("the sky is blue");
-}
diff --git a/other/reverse_word_string.rs b/other/reverse_word_string.rs
deleted file mode 100644
index 6acc9a4..0000000
--- a/other/reverse_word_string.rs
+++ /dev/null
@@ -1,31 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn reverse_words(s: String) -> String {
- let mut s: Vec<char> = s.trim().chars().rev().collect();
- s.push(' ');
- let mut i: usize = 0;
- for j in 0..s.len() {
- if s[j] == ' ' {
- s[i..j].reverse();
- i = j + 1;
- }
- }
- s.pop();
- let mut i = 1;
- for j in 1..s.len() {
- if s[j] == ' ' && s[j - 1] == ' ' {
- continue;
- }
- s[i] = s[j];
- i += 1;
- }
- s.truncate(i);
- s.into_iter().collect()
- }
-}
-
-fn main() {
- let s = "the sky is blue".to_string();
- print!("{}", Solution::reverse_words(s));
-}
diff --git a/other/roman_2_int.cpp b/other/roman_2_int.cpp
deleted file mode 100644
index 1389754..0000000
--- a/other/roman_2_int.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int romanToInt(string s) {
- int ans = 0, num = 0;
- for (int i = s.size() - 1; ~i; i--) {
- switch (s[i]) {
- case 'I':
- num = 1;
- break;
- case 'V':
- num = 5;
- break;
- case 'X':
- num = 10;
- break;
- case 'L':
- num = 50;
- break;
- case 'C':
- num = 100;
- break;
- case 'D':
- num = 500;
- break;
- case 'M':
- num = 1000;
- break;
- }
- if (4 * num < ans)
- ans -= num;
- else
- ans += num;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.romanToInt("MCMXCIVMCMXCIV");
-}
diff --git a/other/rotate_function.cpp b/other/rotate_function.cpp
deleted file mode 100644
index 1bfd7f5..0000000
--- a/other/rotate_function.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int maxRotateFunction(vector<int> &nums) {
- long sum = 0, fn = 0;
- int len = nums.size();
- for (int i = 0; i < len; i++) {
- sum += nums[i];
- fn += (i * nums[i]);
- }
- long l = 1, r, newFn = fn;
- while (l < len) {
- r = l + len - 1;
- long removed = (l - 1) * nums[l - 1];
- long added = r * nums[r % len];
- newFn -= newFn - removed + added - sum;
- fn = max(fn, newFn);
- l++;
- }
- return fn;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {4, 3, 2, 6};
- cout << obj.maxRotateFunction(nums);
-}
diff --git a/other/rotate_image.cpp b/other/rotate_image.cpp
deleted file mode 100644
index 10d0638..0000000
--- a/other/rotate_image.cpp
+++ /dev/null
@@ -1,18 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- void rotate(vector<vector<int>> &matrix) {
- int n = matrix.size(), depth = n / 2;
- for (int i = 0; i < depth; i++) {
- int len = n - 2 * i - 1, opp = n - 1 - i;
- for (int j = 0; j < len; j++) {
- int tmp = matrix[i][i + j];
- matrix[i][i + j] = matrix[opp - j][i];
- matrix[opp - j][i] = matrix[opp][opp - j];
- matrix[opp][opp - j] = matrix[i + j][opp];
- matrix[i + j][opp] = tmp;
- }
- }
- }
-};
diff --git a/other/rotate_image.rs b/other/rotate_image.rs
deleted file mode 100644
index 376545d..0000000
--- a/other/rotate_image.rs
+++ /dev/null
@@ -1,27 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn rotate(mut matrix: Vec<Vec<i32>>) {
- let n = matrix.len();
- let depth = n / 2;
- for i in 0..depth {
- let (len, opp) = (n - 2 * i - 1, n - 1 - i);
- for j in 0..len {
- let tmp = matrix[i][i + j];
- matrix[i][i + j] = matrix[opp - j][i];
- matrix[opp - j][i] = matrix[opp][opp - j];
- matrix[opp][opp - j] = matrix[i + j][opp];
- matrix[i + j][opp] = tmp;
- }
- }
- }
-}
-
-fn main() {
- let matrix = vec![
- vec![1,2,3],
- vec![4,5,6],
- vec![7,8,9]
- ];
- print!("{:?}", Solution::rotate(matrix));
-}
diff --git a/other/running_sum_1d_array.cpp b/other/running_sum_1d_array.cpp
deleted file mode 100644
index b82e0ad..0000000
--- a/other/running_sum_1d_array.cpp
+++ /dev/null
@@ -1,18 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> runningSum(vector<int> &nums) {
- vector<int> ans;
- int count = 0, n = nums.size();
- for (int i = 0; i < n; i++)
- count += nums[i], ans.push_back(count);
- return ans;
- }
-};
-
-int main() {
- vector<int> nums = {1, 2, 3, 4};
- Solution obj;
- obj.runningSum(nums);
-}
diff --git a/other/same_tree.cpp b/other/same_tree.cpp
deleted file mode 100644
index 71c2563..0000000
--- a/other/same_tree.cpp
+++ /dev/null
@@ -1,14 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool isSameTree(TreeNode *p, TreeNode *q) {
- if (p == NULL && q == NULL)
- return true;
- if (p == NULL || q == NULL)
- return false;
- if (p->val != q->val)
- return false;
- return isSameTree(p->right, q->right) && isSameTree(p->left, q->left);
- }
-};
diff --git a/other/same_tree.rs b/other/same_tree.rs
deleted file mode 100644
index 3d94ffb..0000000
--- a/other/same_tree.rs
+++ /dev/null
@@ -1,71 +0,0 @@
-use std::rc::Rc;
-use std::cell::Ref;
-use std::cell::RefCell;
-use std::collections::VecDeque;
-type NodeRef = Option<Rc<RefCell<TreeNode>>>;
-#[derive(Debug, PartialEq, Eq)]
-pub struct TreeNode {
- pub val: i32,
- pub left: NodeRef,
- pub right: NodeRef
-}
-
-impl TreeNode {
- #[inline]
- pub fn new(val: i32) -> Self {
- TreeNode {
- val,
- left: None,
- right: None
- }
- }
-}
-
-struct Solution;
-
-impl Solution {
- pub fn is_same_tree(p: NodeRef, q: NodeRef) -> bool {
- //p == q
- let mut dq: VecDeque<(NodeRef, NodeRef)> = VecDeque::new();
- match (p, q) {
- (Some(p), Some(q)) => {
- dq.push_back((Some(Rc::clone(&p)), Some(Rc::clone(&q))));
- }
- (None, None) => return true,
- _ => return false
- }
- while !dq.is_empty() {
- let (p, q) = dq.pop_front().unwrap();
- if !match (&p, &q) {
- (Some(p), Some(q)) => p.borrow().val == q.borrow().val,
- (None, None) => true,
- _ => false
- } {
- return false;
- }
- if let (Some(p), Some(q)) = (p, q) {
- let (p, q) = (
- Solution::clone_nodes(p.borrow()),
- Solution::clone_nodes(q.borrow())
- );
- dq.push_back((p.0, q.0));
- dq.push_back((p.1, q.1));
- }
- }
- true
- }
- fn clone_nodes(tree: Ref<TreeNode>) -> (NodeRef, NodeRef) {
- (
- if tree.left.is_some() {
- Some(Rc::clone(tree.left.as_ref().unwrap()))
- } else {
- None
- },
- if tree.right.is_some() {
- Some(Rc::clone(tree.right.as_ref().unwrap()))
- } else {
- None
- }
- )
- }
-}
diff --git a/other/satisfiability_eqaulity.cpp b/other/satisfiability_eqaulity.cpp
deleted file mode 100644
index b0a1f8b..0000000
--- a/other/satisfiability_eqaulity.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool equationsPossible(vector<string> &equations) {
- for (int i = 0; i < 26; ++i)
- uf[i] = i;
- for (string e : equations)
- if (e[1] == '=')
- uf[find(e[0] - 'a')] = find(e[3] - 'a');
- for (string e : equations)
- if (e[1] == '!' && find(e[0] - 'a') == find(e[3] - 'a'))
- return false;
- return true;
- }
-
-private:
- int uf[26];
- int find(int x) {
- if (x != uf[x])
- uf[x] = find(uf[x]);
- return uf[x];
- }
-};
-
-int main() {
- Solution obj;
- vector<string> equations = {"a==b", "b!=a"};
- if (obj.equationsPossible(equations))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/scramble_string.cpp b/other/scramble_string.cpp
deleted file mode 100644
index da6b92d..0000000
--- a/other/scramble_string.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-// 87. Scramble String
-#include "leetcode.h"
-
-/*
- * string 's' can be scrambled to get string 't' using the following algorithm:
- * if length of string is 1, exit
- * if lenght of string is > 1:
- * split string into two non-empty substrings at random index
- * randomly decide to swap two substrings or to keep them in same order
- * apply step 1 recursively
- * given two strings 's1' and 's2' of the same length, return true if 's2' is a
- * scrambled string of 's1', otherwise return false
- */
-
-class Solution {
-public:
- bool isScramble(string s1, string s2) {
- if (s1.size() != s2.size())
- return false;
- return is_scrambled(s1, s2);
- }
-
-private:
- unordered_map<string, bool> um;
- bool is_scrambled(string s1, string s2) {
- int n = s1.size();
- if (s1 == s2 || n == 0)
- return true;
- string key = s1 + ' ' + s2;
- if (um.find(key) != um.end())
- return um[key];
- bool flag = false;
- for (int i = 1; i < n; i++) {
- if (is_scrambled(s1.substr(0, i), s2.substr(n - i, i)) &&
- is_scrambled(s1.substr(i, n - i), s2.substr(0, n - i))) {
- flag |= true;
- break;
- }
- if (is_scrambled(s1.substr(0, i), s2.substr(0, i)) &&
- is_scrambled(s1.substr(i, n - i), s2.substr(i, n - i))) {
- flag |= true;
- break;
- }
- }
- um[key] = flag;
- return flag;
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.isScramble("great", "rgeat")); // expect: 1
- printf("%d\n", obj.isScramble("abcde", "caebd")); // expect: 0
- printf("%d\n", obj.isScramble("a", "a")); // expect: 1
-}
diff --git a/other/search_2d_matrix.cpp b/other/search_2d_matrix.cpp
deleted file mode 100644
index 3d8ce04..0000000
--- a/other/search_2d_matrix.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-// 74. Search a 2D Matrix
-#include "leetcode.h"
-
-/*
- * given an 'm x n' integer matrix 'matrxi' with the following two properties:
- * - each row is sorted in non-decreasing order.
- * - the first integer of each row is greater than the last integer of the
- * previous row. given an integer 'target', return true if 'target' is in
- * 'matrix', or false otherwise. you must write a solution in 'O(log(m * n))'
- * time complexity
- */
-
-class Solution {
-public:
- bool searchMatrix(vvd & matrix, int target) {
- int rows = matrix.size(), cols = matrix[0].size(), row = 0, col = cols - 1;
- while (row < rows && col > -1) {
- int curr = matrix[row][col];
- if (curr == target)
- return true;
- if (target > curr)
- row++;
- else
- col--;
- }
- return false;
- }
-};
-
-int main() {
- Solution obj;
- vvd matrix = {{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}};
- printf("%d\n", obj.searchMatrix(matrix, 3)); // expect: 1
- printf("%d\n", obj.searchMatrix(matrix, 13)); // expect: 0
-}
diff --git a/other/search_2d_matrix2.cpp b/other/search_2d_matrix2.cpp
deleted file mode 100644
index 9834431..0000000
--- a/other/search_2d_matrix2.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool searchMatrix(vector<vector<int>> &matrix, int target) {
- int m = matrix.size(), n = matrix[0].size();
- if (m == 0)
- return false;
- int i = 0, j = n - 1;
- while (i < m && j >= 0) {
- if (matrix[i][j] == target)
- return true;
- else if (matrix[i][j] > target)
- j--;
- else
- i++;
- }
- return false;
- }
-};
diff --git a/other/search_rotated_array.cpp b/other/search_rotated_array.cpp
deleted file mode 100644
index 7001f32..0000000
--- a/other/search_rotated_array.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// 33. Search in Rotated Sorted Array
-#include "leetcode.h"
-
-/*
- * there is an integer array 'nums' sorted in ascending order (with distinct
- * values). prior to being passed to your function, 'nums' is possibly rotated
- * at an unknown pivot index 'k(1 <= k < nums.length)' such tht the resulting
- * array is '[nums[k], nums[k + 1], ..., nums[n - 1], nums[0], nums[1], ...,
- * nums[k - 1]]' (0-indxed). for example, '[0,1,2,4,5,6,7]' might be rotated at
- * pivot index 3 and become '[4,5,6,7,0,1,2]'. given the array 'nums' after the
- * possible rotation and an integer 'target', return the index of 'target' if it
- * is in 'nums', or -1 otherwise. you must write an algorithm with 'O(log n)'
- * runtime complexity
- */
-
-class Solution {
-public:
- int search(vector<int> &nums, int target) {
- int left = 0, right = nums.size() - 1;
- while (left < right) {
- int mid = (left + right) / 2;
- if ((nums[0] > target) ^ (nums[0] > nums[mid]) ^ (target > nums[mid]))
- left = mid + 1;
- else
- right = mid;
- }
- return left == right && nums[left] == target ? left : -1;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {4, 5, 6, 7, 0, 1, 2}, n2 = {4, 5, 6, 7, 0, 1, 2}, n3 = {1};
- printf("%d\n", obj.search(n1, 0)); // expect: 4
- printf("%d\n", obj.search(n2, 3)); // expect: -1
- printf("%d\n", obj.search(n3, 0)); // expect: -1
-}
diff --git a/other/search_rotated_array2.cpp b/other/search_rotated_array2.cpp
deleted file mode 100644
index 0054f04..0000000
--- a/other/search_rotated_array2.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-// 81. Search in Rotated Sorted Array II
-#include "leetcode.h"
-
-/*
- * there is an integer array 'nums' sorted in non-decreasing order (not
- * necessarily with distinct values). before being passed to your function,
- * 'nums' is rotated at an unknown pivot index 'k(0 <= k < nums.length)' such
- * that the resulting array is '[nums[k], nums[k + 1], ..., nums[n - 1],
- * nums[0], nums[1], ..., nums[k - 1]]' (0-indexed). for example
- * '[0,1,2,4,4,4,5,6,6,7]' might be rotated at a pivot index 5 and become
- * '[4,5,6,6,7,0,1,2,4,4]'. given the array 'nums' after the rotation and an
- * integer 'target', return true if 'target' is in 'nums' of 'false' if it is
- * not in 'nums'. you must decrease the overall operation steps as much as
- * possible.
- */
-
-class Solution {
-public:
- bool search(vector<int> &nums, int target) {
- int left = 0, right = nums.size() - 1;
- while (left <= right) {
- int mid = left + (right - left) / 2;
- if (nums[mid] == target)
- return true;
- if (nums[left] == nums[mid] && nums[right] == nums[mid])
- left++, right--;
- else if (nums[left] <= nums[mid]) {
- if (nums[left] <= target && nums[mid] > target)
- right = mid - 1;
- else
- left = mid + 1;
- } else {
- if (nums[mid] < target && nums[right] >= target)
- left = mid + 1;
- else
- right = mid - 1;
- }
- }
- return false;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {2, 5, 6, 0, 0, 1, 2};
- printf("%d\n", obj.search(nums, 0)); // expect: 1
- printf("%d\n", obj.search(nums, 3)); // expect: 0
-}
diff --git a/other/search_suggestion_sys.cpp b/other/search_suggestion_sys.cpp
deleted file mode 100644
index 404c987..0000000
--- a/other/search_suggestion_sys.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "leetcode.h"
-#include <vector>
-
-class Solution {
-public:
- vector<vector<string>> suggestedProducts(vector<string> &products,
- string searchWord) {
- auto it = products.begin();
- sort(it, products.end());
- vector<vector<string>> ans;
- string curr = "";
- for (char c : searchWord) {
- curr += c;
- vector<string> suggested;
- it = lower_bound(it, products.end(), curr);
- for (int i = 0; i < 3 && it + i != products.end(); i++) {
- string &s = *(it + i);
- if (s.find(curr))
- break;
- suggested.push_back(s);
- }
- ans.push_back(suggested);
- }
- return ans;
- }
-};
diff --git a/other/set_matrix_0.rs b/other/set_matrix_0.rs
deleted file mode 100644
index 78c434a..0000000
--- a/other/set_matrix_0.rs
+++ /dev/null
@@ -1,44 +0,0 @@
-// 73. Set Matrix Zeroes
-// given an 'm x n' integer matrix 'matrix', if an element is 0,
-// set its entire row and column to 0's. must be done in place
-// (https://en.wikipedia.org/wiki/In-place_algorithm)
-
-impl Solution {
- pub fn set_zeroes(matrix: &mut Vec<Vec<i32>>) {
- let n_rows = matrix.len();
- let n_cols = matrix[0].len();
- let mut first_row = false;
- let mut first_col = false;
- for row in 0..n_rows {
- for col in 0..n_cols {
- if matrix[row][col] == 0 {
- if row == 0 {
- first_row = true;
- }
- if col == 0 {
- first_col = true;
- }
- matrix[0][col] = 0;
- matrix[row][0] = 0;
- }
- }
- }
- for row in 1..n_rows {
- for col in 1..n_cols {
- if matrix[row][0] == 0 || matrix[0][col] == 0 {
- matrix[row][col] = 0
- }
- }
- }
- if first_row {
- for col in 0..n_cols {
- matrix[0][col] = 0;
- }
- }
- if first_col {
- for row in 0..n_rows {
- matrix[row][0] = 0;
- }
- }
- }
-}
diff --git a/other/set_mismatch.cpp b/other/set_mismatch.cpp
deleted file mode 100644
index 8c216bc..0000000
--- a/other/set_mismatch.cpp
+++ /dev/null
@@ -1,19 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> findErrorNums(vector<int> &nums) {
- int p = 0, ac1 = 0, ac2 = 0;
- for (uint i = 0; i < nums.size(); ++i)
- p ^= (i + 1) ^ nums[i];
- p &= -p;
- for (uint i = 0; i < nums.size(); ++i) {
- ((nums[i] & p) == 0) ? ac1 ^= nums[i] : ac2 ^= nums[i];
- (((i + 1) & p) == 0) ? ac1 ^= i + 1 : ac2 ^= i + 1;
- }
- for (auto n : nums)
- if (n == ac1)
- return {ac1, ac2};
- return {ac2, ac1};
- }
-};
diff --git a/other/set_mismatch.rs b/other/set_mismatch.rs
deleted file mode 100644
index b490f8e..0000000
--- a/other/set_mismatch.rs
+++ /dev/null
@@ -1,37 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn find_error_nums(nums: Vec<i32>) -> Vec<i32> {
- let mut xor = nums.iter().zip(1..=nums.len() as i32).fold(0, |acc, (&num, i)| acc ^ num ^ i);
- xor &= -xor;
- let (mut n0, mut n1) = (0, 0);
- for &n in &nums {
- if n & xor == 0 {
- n0 ^= n;
- } else {
- n1 ^= n;
- }
- }
- for i in 1..=nums.len() as i32 {
- if i & xor == 0 {
- n0 ^= i;
- } else {
- n1 ^= i;
- }
- }
- for &n in &nums {
- if n == n0 {
- return vec![n0, n1];
- }
- if n == n1 {
- return vec![n1, n0];
- }
- }
- unreachable!()
- }
-}
-
-fn main() {
- let nums = vec![1,2,2,4];
- print!("{:?}", Solution::find_error_nums(nums));
-}
diff --git a/other/short_encoding_words.cpp b/other/short_encoding_words.cpp
deleted file mode 100644
index 528191f..0000000
--- a/other/short_encoding_words.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int minimumLengthEncoding(vector<string> &words) {
- unordered_set<string> us(words.begin(), words.end());
- for (string w : us)
- for (int i = 1; i < w.size(); ++i)
- us.erase(w.substr(i));
- int ans = 0;
- for (string w : us)
- ans += w.size() + 1;
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<string> words = {"time", "me", "bell"};
- cout << obj.minimumLengthEncoding(words);
-}
diff --git a/other/shortest_bridge.cpp b/other/shortest_bridge.cpp
deleted file mode 100644
index 818d384..0000000
--- a/other/shortest_bridge.cpp
+++ /dev/null
@@ -1,82 +0,0 @@
-// 934. Shortest Bridge
-#include "leetcode.h"
-
-/*
- * given an 'n x n' binary matrix grid where 1 represents land and 0 represents
- * water. an island is a 4 directionally connected group of 1's not connected to
- * any other 1's. there are exactly two islands in a 'grid'. you may change 0's
- * to 1's to connect the two islands to form one island. return the smallest
- * numbe of 0's you must flip to connect the two islands.
- */
-
-class Solution {
- queue<pair<int, int>> qp;
- void dfs(vvd & grid, int i, int j) {
- if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() ||
- grid[i][j] == 2 || !grid[i][j])
- return;
- grid[i][j] = 2;
- qp.push({i, j});
- dfs(grid, i + 1, j);
- dfs(grid, i - 1, j);
- dfs(grid, i, j + 1);
- dfs(grid, i, j - 1);
- }
- int bfs(vvd & grid) {
- int d = 0, min_dist = INT_MAX;
- vvd dir = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
- while (!qp.empty()) {
- int n = qp.size();
- while (n--) {
- auto a = qp.front();
- qp.pop();
- for (int h = 0; h < 4; h++) {
- int x = dir[h][0] + a.first;
- int y = dir[h][1] + a.second;
- if (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() &&
- grid[x][y])
- min_dist = min(min_dist, d);
- else if (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() &&
- !grid[x][y]) {
- qp.push({x, y});
- grid[x][y] = 2;
- }
- }
- }
- d++;
- }
- return min_dist;
- }
-
-public:
- int shotestBridge(vvd & grid) {
- bool flag = false;
- for (int i = 0; i < grid.size(); i++) {
- for (int j = 0; j < grid[0].size(); j++) {
- if (grid[i][j] && !flag) {
- dfs(grid, i, j);
- qp.push({i, j});
- flag = true;
- break;
- }
- }
- if (flag)
- break;
- }
- return bfs(grid);
- }
-};
-
-int main() {
- Solution obj;
- vvd g1 = {{0, 1}, {1, 0}};
- vvd g2 = {{0, 1, 0}, {0, 0, 0}, {0, 0, 1}};
- vvd g3 = {{1, 1, 1, 1, 1},
- {1, 0, 0, 0, 1},
- {1, 0, 1, 0, 1},
- {1, 0, 0, 0, 1},
- {1, 1, 1, 1, 1}};
- printf("%d\n", obj.shotestBridge(g1)); // expect: 1
- printf("%d\n", obj.shotestBridge(g2)); // expect: 2
- printf("%d\n", obj.shotestBridge(g3)); // expect: 1
-}
diff --git a/other/shortest_dist_road_addition1.cpp b/other/shortest_dist_road_addition1.cpp
deleted file mode 100644
index deea04c..0000000
--- a/other/shortest_dist_road_addition1.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-// 3243. Shortest Distance After Road Addition Queries I
-#include "leetcode.h"
-
-/*
- * you are given an integer 'n' and a 2d integer array 'queries'. there are 'n'
- * cities numbered from 0 to 'n - 1'. initially there is a unidirectional road
- * from city 'i' to city 'i + 1' for all '0 <= i < n - 1'. 'queries[i] = [u_i,
- * v_i]' represents the addition of a new unidirectional road from city 'u_i' to
- * city 'v_i'. after each query, you need to find the length of the shortest
- * path from city 0 to city 'n - 1'. return an array 'answer' where for each 'i'
- * in the range of '[0, queries.length - 1]', 'answer[i]' is the length of the
- * shortest path from city 0 to city 'n - 1' after processing the first 'i + 1'
- * queries.
- */
-
-class Solution {
-public:
- vector<int> shortestDistanceAfterQueries(int n,
- vector<vector<int>> &queries) {
- vector<int> ans;
- unordered_map<int, vector<int>> mp;
- for (int i = 0; i < n - 1; i++)
- mp[i].push_back(i + 1);
- for (auto i : queries) {
- mp[i[0]].push_back(i[1]);
- vector<int> dp(n, INT_MAX);
- dp[n - 1] = 0;
- for (int j = n - 2; j >= 0; --j)
- for (int next : mp[j])
- dp[j] = min(dp[j], dp[next] + 1);
- ans.push_back(dp[0]);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd q1 = {{2, 4}, {0, 2}, {0, 4}}, q2 = {{0, 3}, {0, 3}};
- vector<int> sdaq1 = obj.shortestDistanceAfterQueries(5, q1);
- vector<int> sdaq2 = obj.shortestDistanceAfterQueries(4, q2);
- for (auto i : sdaq1)
- printf("%d ", i); // expect: 3 2 1
- printf("\n");
- for (auto i : sdaq2)
- printf("%d ", i); // expect: 1 1
- printf("\n");
-}
diff --git a/other/shortest_path_alternate_color.cpp b/other/shortest_path_alternate_color.cpp
deleted file mode 100644
index a5cf369..0000000
--- a/other/shortest_path_alternate_color.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-// 1129. Shortest Path with Alternating Colors
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> shortestAlternatingPaths(int n, vvd & redEdges,
- vvd & blueEdges) {
- vector<int> ans(n, -1), v1(n, 0), v2(n, 0);
- vector<vector<pair<int, int>>> vvp(n);
- queue<pair<int, int>> qp;
- for (auto &it : redEdges)
- vvp[it[0]].push_back({it[1], 1});
- for (auto &it : blueEdges)
- vvp[it[0]].push_back({it[1], 2});
- ans[0] = 0, v1[0] = 1, v2[0] = 1;
- int tmp = 1;
- for (auto &it : vvp[0]) {
- qp.push(it);
- if (ans[it.first] == -1)
- ans[it.first] = tmp;
- }
- while (!qp.empty()) {
- int len = qp.size();
- tmp++;
- for (int i = 0; i < len; ++i) {
- auto val = qp.front();
- qp.pop();
- if (val.second == 1)
- v1[val.first] = 1;
- else
- v2[val.first] = 1;
- for (auto &it : vvp[val.first]) {
- if (val.second == 1 && (v2[it.first] || it.second == 1))
- continue;
- if (val.second == 2 && (v1[it.first] || it.second == 2))
- continue;
- qp.push(it);
- if (ans[it.first] == -1)
- ans[it.first] = tmp;
- }
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd re1 = {{0, 1}, {1, 2}}, be1 = {};
- vvd re2 = {{0, 1}}, be2 = {{2, 1}};
- for (auto i : obj.shortestAlternatingPaths(3, re1, be1))
- cout << i << ' '; // expect: 0 1 -1
- cout << endl;
- for (auto i : obj.shortestAlternatingPaths(3, re2, be2))
- cout << i << ' '; // expect: 0 1 -1
-}
diff --git a/other/shortest_path_binary_matrix.cpp b/other/shortest_path_binary_matrix.cpp
deleted file mode 100644
index fd586fe..0000000
--- a/other/shortest_path_binary_matrix.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-// 1091. Shortest Path in Binary Matrix
-#include "leetcode.h"
-
-/*
- * given an n x n binary matrix 'grid', return the length of the shortest clear
- * path in the matrix. if there is no clear path, return -1. a clear path in a
- * binary matrix is a path from the top-left cell (ie. 0,0) to the bottom-right
- * cell (ie. n - 1, n - 1) such thatyt
- * - all the visited cells are of the path 0
- * - all the adjacent cells of the path are 8-directionally connected (ie. they
- * are different and they share an edge of a corner) the length of a clear path
- * is the number of visited cells of this path
- */
-
-class Solution {
-public:
- int shortestPathBinaryMatrix(vector<vector<int>> &grid) {
- if (grid[0][0] || grid.back().back())
- return -1;
- int ans = 2, n = 1, nr = grid[0].size() - 1, nc = grid.size() - 1;
- queue<pair<int, int>> qp;
- if (!nr && !nc)
- return 1 - (grid[0][0] << 1);
- qp.push({0, 0});
- grid[0][0] = -1;
- while (n) {
- while (n--) {
- auto [cx, cy] = qp.front();
- qp.pop();
- for (int i = max(0, cx - 1), lmtx = min(cx + 1, nr); i <= lmtx; i++)
- for (int j = max(0, cy - 1), lmty = min(cy + 1, nc); j <= lmty; j++) {
- if (i == nr && j == nc)
- return ans;
- if (!grid[j][i]) {
- grid[j][i] = -1;
- qp.push({i, j});
- }
- }
- }
- ans++;
- n = qp.size();
- }
- return -1;
- }
-};
-
-int main() {
- Solution obj;
- vvd g1 = {{0, 1}, {1, 0}};
- vvd g2 = {{0, 0, 0}, {1, 1, 0}, {1, 1, 0}};
- vvd g3 = {{1, 0, 0}, {1, 1, 0}, {1, 1, 0}};
- printf("%d\n", obj.shortestPathBinaryMatrix(g1)); // expect: 2
- printf("%d\n", obj.shortestPathBinaryMatrix(g2)); // expect: 4
- printf("%d\n", obj.shortestPathBinaryMatrix(g3)); // expect: -1
-}
diff --git a/other/shortest_path_grid_obstacle.cpp b/other/shortest_path_grid_obstacle.cpp
deleted file mode 100644
index daaa361..0000000
--- a/other/shortest_path_grid_obstacle.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int shortestPath(vvd & grid, int k) {
- int rows = grid.size(), cols = grid[0].size();
- int minStep = max(0, rows + cols - 2), obstacles = minStep - 1,
- minStepNext = minStep;
- if (obstacles <= k)
- return minStep;
- vvd dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
- list<vector<int>> togo;
- togo.push_back({0, 0, k});
- vector<int> visited(rows * cols, -1);
- visited[0] = k;
- int steps = 0;
- while (togo.size()) {
- steps++;
- minStep = minStepNext;
- for (int i = togo.size(); i > 0; i--) {
- int a = togo.front()[0], b = togo.front()[1], c = togo.front()[2];
- togo.pop_front();
- for (auto &d : dirs) {
- int aa = a + d[0], bb = b + d[1];
- if (aa < 0 || aa >= rows || bb < 0 || bb >= cols)
- continue;
- int cc = c - grid[aa][bb];
- if (visited[aa * cols + bb] >= cc)
- continue;
- int stepsToTarget = rows - aa - 1 + cols - bb - 1;
- if (stepsToTarget - 1 <= cc && stepsToTarget == minStep - 1)
- return steps + stepsToTarget;
- togo.push_back({aa, bb, cc});
- visited[aa * cols + bb] = cc;
- minStepNext = min(minStepNext, stepsToTarget);
- }
- }
- }
- return -1;
- }
-};
-
-int main() {
- Solution obj;
- vvd grid = {{0, 0, 0}, {1, 1, 0}, {0, 0, 0}, {0, 1, 1}, {0, 0, 0}};
- int k = 1;
- cout << obj.shortestPath(grid, k);
-}
diff --git a/other/shortest_path_grid_obstacle.rs b/other/shortest_path_grid_obstacle.rs
deleted file mode 100644
index ba35681..0000000
--- a/other/shortest_path_grid_obstacle.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-use std::collections::VecDeque;
-struct Solution;
-
-impl Solution {
- pub fn shortest_path(grid: Vec<Vec<i32>>, k: i32) -> i32 {
- let m = grid.len() as i32; let n = grid[0].len() as i32;
- let dir = [-1, 0, 1, 0, -1];
- let mut dq = VecDeque::new();
- let mut visited = vec![vec![0; n as usize]; m as usize];
- let mut ans = 0;
- dq.push_back((0,0,k));
- visited[0][0] = k + 1;
- while !dq.is_empty() {
- for _ in 0..dq.len() {
- let (row, col, left) = dq.pop_front().unwrap();
- if row == m - 1 && col == n - 1 {
- return ans;
- }
- for (&i, &j) in dir.iter().zip(dir.iter().skip(1)){
- let (new_row, new_col) = (row + i, col + j);
- if new_row < 0 || new_row >= m || new_col < 0 || new_col >= n
- || visited[new_row as usize][new_col as usize] >= left + 1 {
- continue;
- }
- if grid[new_row as usize][new_col as usize] == 0 {
- dq.push_back((new_row, new_col, left));
- visited[new_row as usize][new_col as usize] = left + 1;
- } else if left > 0 {
- dq.push_back((new_row, new_col, left - 1));
- visited[new_row as usize][new_col as usize] = left;
- }
- }
- }
- ans += 1;
- }
- -1
- }
-}
diff --git a/other/shortest_path_keys.cpp b/other/shortest_path_keys.cpp
deleted file mode 100644
index 15ffe90..0000000
--- a/other/shortest_path_keys.cpp
+++ /dev/null
@@ -1,109 +0,0 @@
-// 864. Shortest Path to Get All Keys
-#include "leetcode.h"
-
-/*
- * given an 'm x n' grid 'grid' where:
- * - '.' is an empty cell
- * - '#' is a wall
- * - '@' is the starting point
- * - lowercase letters represent keys
- * - uppercase letters represent locks
- * you start at the starting point and one move consists of walking one space in
- * one of the four cardinal directions. you cannot walk outside the grid, or
- * walk into a wall. if you walk over a key, you can pick it up and you cannot
- * walk over a lock unless you have its corresponding key. for some '1 <= k <=
- * 6', there is exactly one lowercase and one uppercase letter of the first 'k'
- * letters of the english alphabet in the grid. this means that there is exactly
- * one key for each lock, and one lock for each key; and also that the letters
- * used to represent the keys and locks were chosen in the same order as the
- * english alphabet. return the lowest number of moves to acquire all keys. if
- * it is impossible, return -1
- */
-
-class Info {
-public:
- pair<int, int> p;
- vector<int> keys;
- int cnt;
- Info(pair<int, int> p, vector<int> keys, int cnt) {
- this->p = p;
- this->keys = keys;
- this->cnt = cnt;
- }
- int get_state() {
- int state = 0;
- for (int i = 0; i < keys.size(); i++) {
- state <<= 1;
- state += keys[i];
- }
- return state;
- }
-};
-
-class Solution {
-public:
- int shortestPathAllKeys(vector<string> &grid) {
- pair<int, int> start;
- int m = grid.size(), n = grid[0].size(), key_cnt = 0;
- if (!m)
- return -1;
- for (int i = 0; i < m; i++)
- for (int j = 0; j < n; j++) {
- if (grid[i][j] == '@')
- start = make_pair(i, j);
- else if (grid[i][j] >= 'a' && grid[i][j] <= 'f')
- key_cnt++;
- }
- queue<Info> q;
- vector<int> keys_start(key_cnt, 0);
- q.push(Info(start, keys_start, 0));
- int ans = -1;
- vector<vector<vector<int>>> vis;
- for (int i = 0; i < 1 << key_cnt; i++) {
- vvd tmp(m, vector<int>(n, 0));
- vis.push_back(tmp);
- }
- while (!q.empty()) {
- auto curr = q.front();
- q.pop();
- int state = curr.get_state();
- if (state == (1 << key_cnt) - 1) {
- ans = curr.cnt;
- break;
- }
- if (vis[state][curr.p.first][curr.p.second])
- continue;
- vis[state][curr.p.first][curr.p.second] = 1;
- int dx[] = {0, 1, 0, -1};
- int dy[] = {1, 0, -1, 0};
- for (int i = 0; i < 4; i++) {
- int xx = curr.p.first + dx[i];
- int yy = curr.p.second + dy[i];
- auto keys = curr.keys;
- auto cnt = curr.cnt + 1;
- if (xx >= 0 && xx < m && yy >= 0 && yy < n) {
- if (grid[xx][yy] >= 'a' && grid[xx][yy] <= 'f') {
- int no = grid[xx][yy] - 'a';
- keys[no] = 1;
- } else if (grid[xx][yy] >= 'A' && grid[xx][yy] <= 'F') {
- int no = grid[xx][yy] - 'A';
- if (!keys[no])
- continue;
- } else if (grid[xx][yy] == '#')
- continue;
- q.push(Info(make_pair(xx, yy), keys, cnt));
- }
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<string> g1 = {"@.a..", "###.#", "b.A.B"},
- g2 = {"@..aA", "..B#.", "....b"}, g3 = {"@Aa"};
- printf("%d\n", obj.shortestPathAllKeys(g1)); // expect: 8
- printf("%d\n", obj.shortestPathAllKeys(g2)); // expect: 6
- printf("%d\n", obj.shortestPathAllKeys(g3)); // expect: -1
-}
diff --git a/other/shortest_path_vis_nodes.cpp b/other/shortest_path_vis_nodes.cpp
deleted file mode 100644
index 23d95ea..0000000
--- a/other/shortest_path_vis_nodes.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-// 847. Shortest Path Visiting All Nodes
-#include "leetcode.h"
-
-/*
- * you have an undirected, connected graph of 'n' nodes labeled from 0 to 'n -
- * 1'. you are given an array 'graph' where 'graph[i]' is a list of all the
- * nodes connected with node 'i' by an edge. return the length of the shortest
- * path that visits every node. you may start and stop any any node. you may
- * revisit nodes multiple times and you may reused edges.
- */
-
-class Solution {
-public:
- class tuple {
- public:
- int node;
- int mask;
- int cost;
- tuple(int node, int mask, int cost) {
- this->node = node;
- this->mask = mask;
- this->cost = cost;
- }
- };
-
- int shortestPathLength(vvd & graph) {
- int n = graph.size();
- queue<tuple> q;
- set<pair<int, int>> vis;
- int all = (1 << n) - 1;
- for (int i = 0; i < n; i++) {
- int mask_val = 1 << i;
- tuple curr(i, mask_val, 1);
- q.push(curr);
- vis.insert({i, mask_val});
- }
- while (!q.empty()) {
- tuple curr = q.front();
- q.pop();
- if (curr.mask == all)
- return curr.cost - 1;
- for (auto adj : graph[curr.node]) {
- int both_vis = curr.mask;
- both_vis = both_vis | (1 << adj);
- tuple node(adj, both_vis, curr.cost + 1);
- if (vis.find({adj, both_vis}) == vis.end()) {
- vis.insert({adj, both_vis});
- q.push(node);
- }
- }
- }
- return -1;
- }
-};
-
-int main() {
- Solution obj;
- vvd g1 = {{1, 2, 3}, {0}, {0}},
- g2 = {{1}, {0, 2, 4}, {1, 3, 4}, {2}, {1, 2}};
- printf("%d\n", obj.shortestPathLength(g1)); // expect: 4
- printf("%d\n", obj.shortestPathLength(g2)); // expect: 4
-}
diff --git a/other/shortest_unsorted_subarr.cpp b/other/shortest_unsorted_subarr.cpp
deleted file mode 100644
index 849f524..0000000
--- a/other/shortest_unsorted_subarr.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int findUnsortedSubarray(vector<int> &nums) {
- int end = -1, start = 0;
- int max = nums[0], min = nums[nums.size() - 1];
- for (int i = 1; i < nums.size(); i++) {
- if (max > nums[i])
- end = i;
- else
- max = nums[i];
- }
- for (int i = nums.size() - 2; i >= 0; i--) {
- if (min < nums[i])
- start = i;
- else
- min = nums[i];
- }
- return end - start + 1;
- }
-};
-
-int main() {
- vector<int> nums = {2, 6, 4, 8, 10, 9, 15};
- Solution obj;
- for (int i = 0; i < nums.size(); i++)
- cout << nums[i] << ' ';
- cout << endl << obj.findUnsortedSubarray(nums);
-}
diff --git a/other/shuffle_the_array.cpp b/other/shuffle_the_array.cpp
deleted file mode 100644
index f7dddea..0000000
--- a/other/shuffle_the_array.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-// 1470. Shuffle the Array
-#include "leetcode.h"
-
-/*
- * given array 'nums' consisting of '2n' elements in the form
- * [x1, x2, ..., xn, y1, y2, ..., yn]
- * return the array in the form [x1, y1, x2, y2, ..., xn, yn]
- */
-
-class Solution {
-public:
- vector<int> shuffle(vector<int> &nums, int n) {
- int len = nums.size();
- for (int i = n; i < len; i++)
- nums[i] = (nums[i] << 10) | nums[i - n];
- int idx = 0;
- for (int i = n; i < len; i++, idx += 2) {
- nums[idx] = nums[i] & 1023;
- nums[idx + 1] = nums[i] >> 10;
- }
- return nums;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums1 = {2, 5, 1, 3, 4, 7};
- vector<int> nums2 = {1, 2, 3, 4, 4, 3, 2, 1};
- vector<int> nums3 = {1, 1, 2, 2};
- for (auto i : obj.shuffle(nums1, 3))
- cout << i << ' '; // expect: 2,3,5,4,1,7
- cout << endl;
- for (auto i : obj.shuffle(nums2, 4))
- cout << i << ' '; // expect: 1,4,2,3,3,2,4,1
- cout << endl;
- for (auto i : obj.shuffle(nums3, 2))
- cout << i << ' '; // expect: 1,2,1,2
- cout << endl;
-}
diff --git a/other/similar_string_group.cpp b/other/similar_string_group.cpp
deleted file mode 100644
index 273df4f..0000000
--- a/other/similar_string_group.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-// 839. Similar String Groups
-#include "leetcode.h"
-
-/*
- * two strings 'x' and 'y' are similar if we can swap two letters
- * of 'x' so that it equals 'y'. also two strings 'x' and 'y' are
- * given a list of 'strs' of strings where every string in 'strs'
- * is an anagram of every other string in 'strs'. how many groups?
- */
-
-class disjointSet {
- vector<int> v;
- int sz;
-
-public:
- void make_set(int n) {
- v.resize(n);
- iota(v.begin(), v.end(), 0);
- sz = n;
- }
- disjointSet(int n) { make_set(n); }
- int find(int i) {
- if (i != v[i])
- v[i] = find(v[i]);
- return v[i];
- }
- void join(int i, int j) {
- int r_i = find(i), r_j = find(j);
- if (r_i != r_j) {
- v[r_i] = r_j;
- sz--;
- }
- }
- int size() { return sz; }
-};
-
-class Solution {
- bool similar(string a, string b) {
- int n = 0;
- for (int i = 0; i < a.size(); i++)
- if (a[i] != b[i] && ++n > 2)
- return false;
- return true;
- }
-
-public:
- int numSimilarGroups(vector<string> &strs) {
- disjointSet ds(strs.size());
- for (int i = 0; i < strs.size(); i++)
- for (int j = i + 1; j < strs.size(); j++)
- if (similar(strs[i], strs[j]))
- ds.join(i, j);
- return ds.size();
- }
-};
-
-int main() {
- Solution obj;
- vector<string> s1 = {"tars", "rats", "arts", "star"};
- vector<string> s2 = {"omv", "ovm"};
- printf("%d\n", obj.numSimilarGroups(s1));
- printf("%d\n", obj.numSimilarGroups(s2));
-}
diff --git a/other/simplify_path.cpp b/other/simplify_path.cpp
deleted file mode 100644
index 09852f3..0000000
--- a/other/simplify_path.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-// 71. Simplify Path
-#include "leetcode.h"
-
-// given a string 'path', which is an absolute path (starting with a slash) to a
-// file or directory in a unix-style file system, convert it to the simplified
-// canonical path
-
-class Solution {
-public:
- string simplifyPath(string path) {
- vector<string> stack;
- string ans, tmp;
- stringstream p(path);
- while (getline(p, tmp, '/')) {
- if (tmp == "" || tmp == ".")
- continue;
- if (!stack.empty() && tmp == "..")
- stack.pop_back();
- else if (tmp != "..")
- stack.push_back(tmp);
- }
- for (auto s : stack)
- ans += "/" + s;
- return stack.empty() ? "/" : ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.simplifyPath("/home/") << endl; // expect: /home/
- cout << obj.simplifyPath("/../") << endl; // expect: /
- cout << obj.simplifyPath("/home//foo/") << endl; // expect: /home/foo
-}
diff --git a/other/single_element_sorted_arr.cpp b/other/single_element_sorted_arr.cpp
deleted file mode 100644
index e9bd894..0000000
--- a/other/single_element_sorted_arr.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-// 540. Single Element in a Sorted Array
-#include "leetcode.h"
-
-/*
- * given a sorted array consisting of only integers where very element appears
- * exactly twice, except for one element which appears exactly once. return the
- * single element that appears only once. solution func must be o(ln) time and
- * o(1) space complexity.
- */
-
-class Solution {
-public:
- int singleNonDuplicate(vector<int> &nums) {
- int low = 0, high = nums.size() - 1, mid;
- while (low < high) {
- mid = (low + high) / 2;
- if ((mid % 2 && nums[mid - 1] == nums[mid]) ||
- (!(mid % 2) && nums[mid] == nums[mid + 1]))
- low = mid + 1;
- else
- high = mid;
- }
- return nums[low];
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums1 = {1, 1, 2, 3, 3, 4, 4, 8, 8},
- nums2 = {3, 3, 7, 7, 10, 11, 11};
- cout << obj.singleNonDuplicate(nums1) << endl; // expect: 2
- cout << obj.singleNonDuplicate(nums2) << endl; // expect: 10
-}
diff --git a/other/single_number.cpp b/other/single_number.cpp
deleted file mode 100644
index e9a5878..0000000
--- a/other/single_number.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int singleNumber(vector<int> &nums) {
- int ans;
- /*
- * unordered_map to track frequency
- * unordered_map<key data type, value data type>
- * both are int in this case.
- */
- unordered_map<int, int> freq;
- for (int i = 0; i < nums.size(); i++)
- /*
- * store frequency
- * given 4, 1, 2, 1, 2
- * 4 -> once
- * 1 -> twice
- * 2 -> twice
- * output: 4
- */
- freq[nums[i]]++;
- for (auto i : freq) // traverse map
- if (i.second == 1) { // if frequency of any element is 1...
- ans = i.first; // that's the answer
- break; // exit loop because we have our answer
- }
- return ans;
- }
-};
-
-int main() {
- vector<int> nums = {4, 1, 2, 1, 2};
- Solution obj;
- for (int i = 0; i < nums.size(); i++)
- cout << nums[i] << ' ';
- cout << endl << obj.singleNumber(nums);
-}
diff --git a/other/single_number.rs b/other/single_number.rs
deleted file mode 100644
index c724ebf..0000000
--- a/other/single_number.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn single_number(nums: Vec<i32>) -> i32 {
- let mut n = nums;
- n.sort();
- let mut tmp = vec![n[0]];
- for i in 1..n.len() {
- if tmp.len() == 0 || tmp[tmp.len() - 1] != n[i] {
- tmp.push(n[i]);
- } else {
- tmp.pop();
- }
- }
- tmp[0]
- }
-}
-
-fn main() {
- let nums = vec![2,2,1];
- print!("{}", Solution::single_number(nums));
-}
diff --git a/other/single_number2.cpp b/other/single_number2.cpp
deleted file mode 100644
index 907fee0..0000000
--- a/other/single_number2.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-// 137. Single Number II
-#include "leetcode.h"
-
-/*
- * given an integer array 'nums' where every element appears three times except
- * for one, which appears exactly once. find the single element and return it.
- * you must implement a solution with a linear runtime complexity and use only
- * constant extra space.
- */
-
-class Solution {
-public:
- int singleNumber(vector<int> &nums) {
- unordered_map<int, int> um;
- for (auto i : nums)
- um[i]++;
- for (auto i : um)
- if (i.second == 1)
- return i.first;
- return -1;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {2, 2, 3, 2}, n2 = {0, 1, 0, 1, 0, 1, 99};
- printf("%d\n", obj.singleNumber(n1)); // expect: 3
- printf("%d\n", obj.singleNumber(n2)); // expect: 99
-}
diff --git a/other/single_product_array.cpp b/other/single_product_array.cpp
deleted file mode 100644
index 262bd0e..0000000
--- a/other/single_product_array.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-// 1822. Sign of the Product of an Array
-#include "leetcode.h"
-
-/*
- * there is a function signFunc(x) that returns
- * 1 if x is positive
- * -1 if x is negative
- * 0 if x is equal to 0
- * given an integer array 'nums', let 'product' be the product
- * of all values in the array 'nums' return signFunc(product)
- */
-
-class Solution {
-public:
- int arraySign(vector<int> &nums) {
- int sign = 1;
- for (auto n : nums) {
- if (!n)
- return 0;
- else if (n < 0)
- sign = -sign;
- }
- return sign;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {-1, -2, -3, -4, 3, 2, 1};
- vector<int> n2 = {1, 5, 0, 2, -3};
- vector<int> n3 = {-1, 1, -1, 1, -1};
- printf("%d\n", obj.arraySign(n1)); // expect: 1
- printf("%d\n", obj.arraySign(n2)); // expect: 0
- printf("%d\n", obj.arraySign(n3)); // expect: -1
-}
diff --git a/other/single_threaded_cpu.cpp b/other/single_threaded_cpu.cpp
deleted file mode 100644
index db32185..0000000
--- a/other/single_threaded_cpu.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> getOrder(vvd & tasks) {
- vector<int> ans, idx(tasks.size());
- priority_queue<pair<int, int>> pqp;
- iota(begin(idx), end(idx), 0);
- sort(begin(idx), end(idx),
- [&](int i, int j) { return tasks[i][0] < tasks[j][0]; });
- for (long i = 0, time = 1; i < idx.size() || !pqp.empty();) {
- for (; i < idx.size() && tasks[idx[i]][0] <= time; ++i)
- pqp.push({-tasks[idx[i]][1], -idx[i]});
- if (!pqp.empty()) {
- auto [procTime, j] = pqp.top();
- pqp.pop();
- time -= procTime;
- ans.push_back(-j);
- } else
- time = tasks[idx[i]][0];
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd tasks = {{1, 2}, {2, 4}, {3, 2}, {4, 1}};
- for (auto i : obj.getOrder(tasks))
- cout << i << ' '; // expect 0,2,3,1
-}
diff --git a/other/single_threaded_cpu.rs b/other/single_threaded_cpu.rs
deleted file mode 100644
index 4defcb7..0000000
--- a/other/single_threaded_cpu.rs
+++ /dev/null
@@ -1,59 +0,0 @@
-use std::collections::BinaryHeap;
-use std::cmp::Ordering;
-struct Solution;
-#[derive(PartialEq, Eq, Copy, Clone)]
-struct Task {
- pub enqueue_time: i32,
- pub processing_time: i32,
- pub initial_idx: usize
-}
-
-impl PartialOrd for Task {
- fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
- if other.processing_time == self.processing_time {
- return Some(other.initial_idx.cmp(&self.initial_idx));
- }
- Some(other.processing_time.cmp(&self.processing_time))
- }
-}
-
-impl Ord for Task {
- fn cmp(&self, other: &Self) -> Ordering {
- if other.processing_time == self.processing_time {
- return other.initial_idx.cmp(&self.initial_idx);
- }
- other.processing_time.cmp(&self.processing_time)
- }
-}
-
-impl Solution {
- pub fn get_order(tasks: Vec<Vec<i32>>) -> Vec<i32> {
- let mut tasks = tasks.into_iter().enumerate().map(|(idx, task)| {
- Task {
- enqueue_time: task[0],
- processing_time: task[1],
- initial_idx: idx
- }
- }).collect::<Vec<Task>>();
- let (mut output, mut current_time) = (vec![], 0);
- let mut available_tasks: BinaryHeap<Task> = BinaryHeap::new();
- while tasks.len() > 0 || available_tasks.len() > 0 {
- while tasks.len() > 0 && tasks[tasks.len() - 1].enqueue_time <= current_time {
- let task = tasks.pop().unwrap();
- available_tasks.push(task);
- }
- if let Some(task) = available_tasks.pop() {
- output.push(task.initial_idx as i32);
- current_time += task.processing_time;
- } else {
- current_time = tasks[tasks.len() - 1].enqueue_time;
- }
- }
- output
- }
-}
-
-fn main() {
- let tasks = vec![vec![1,2],vec![2,4],vec![3,2],vec![4,1]];
- print!("{:?}", Solution::get_order(tasks));
-}
diff --git a/other/skyline_problem.cpp b/other/skyline_problem.cpp
deleted file mode 100644
index b19c87a..0000000
--- a/other/skyline_problem.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vvd getSkyline(vvd & buildings) {
- vvd ans;
- map<int, vector<pair<int, int>>> mvp;
- for (auto &b : buildings) {
- mvp[b[0]].push_back({b[2], 0});
- mvp[b[1]].push_back({b[2], 1});
- }
- multiset<int> m;
- for (auto &[pos, heights] : mvp) {
- for (auto &[height, type] : heights) {
- if (type == 0)
- m.insert(height);
- else
- m.erase(m.find(height));
- }
- int newHeight = m.empty() ? 0 : *m.begin();
- if (!ans.empty() && ans.back()[1] == newHeight)
- continue;
- else
- ans.push_back(vector<int>({pos, newHeight}));
- }
- return ans;
- }
-};
diff --git a/other/sliding_puzzle.cpp b/other/sliding_puzzle.cpp
deleted file mode 100644
index 9b772f1..0000000
--- a/other/sliding_puzzle.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-// 773. Sliding Puzzle
-#include "leetcode.h"
-
-/*
- * on an empty 2 x 3 board there are five tiles labeled from 1 to 5 and an empty
- * square represented by 0. a move consists of choosing 0 and a 4-directionall
- * adjacent number and swapping it. the state of the board is solved if and only
- * if the board is '[[1,2,3],[4,5,0]]'. given the puzzle 'board', return the
- * least number of moves required so that the state of the board is solved. if
- * it is impossible for the state of the board to be solved, return -1
- */
-
-class Solution {
-public:
- int slidingPuzzle(vector<vector<int>> &board) {
- string begin = "", end = "123450";
- vector<vector<int>> moves = {{1, 3}, {0, 2, 4}, {1, 5},
- {0, 4}, {1, 3, 5}, {2, 4}};
- for (int i = 0; i < board.size(); i++)
- for (int j = 0; j < board[0].size(); j++)
- begin += to_string(board[i][j]);
- unordered_set<string> vis;
- vis.insert(begin);
- queue<pair<string, int>> qp;
- qp.push({begin, 0});
- while (!qp.empty()) {
- auto p = qp.front();
- qp.pop();
- string curr = p.first;
- int dist = p.second, idx = curr.find("0");
- if (curr == end)
- return dist;
- for (auto &i : moves[idx]) {
- string next = curr;
- swap(next[idx], next[i]);
- if (!vis.count(next)) {
- vis.insert(next);
- qp.push({next, dist + 1});
- }
- }
- }
- return -1;
- }
-};
-
-int main() {
- Solution obj;
- vvd b1 = {{1, 2, 3}, {4, 0, 5}}, b2 = {{1, 2, 3}, {5, 4, 0}},
- b3 = {{4, 1, 2}, {5, 0, 3}};
- printf("%d\n", obj.slidingPuzzle(b1)); // expect 1
- printf("%d\n", obj.slidingPuzzle(b2)); // expect -1
- printf("%d\n", obj.slidingPuzzle(b3)); // expect 5
-}
diff --git a/other/sliding_window_max.cpp b/other/sliding_window_max.cpp
deleted file mode 100644
index 8468604..0000000
--- a/other/sliding_window_max.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-// 239. Sliding Window Maximum
-#include "leetcode.h"
-
-/*
- * given an array of integers 'nums', there is a sliding window of size 'k',
- * which is moving from the very left of the array to the very right. you can
- * only see the 'k' numbers in each window. each time the sliding window moves
- * right by one position. return the max sliding window.
- */
-
-class Solution {
-public:
- vector<int> maxSlidingWindow(vector<int> &nums, int k) {
- deque<int> dq;
- vector<int> ans;
- for (int i = 0; i < nums.size(); i++) {
- if (!dq.empty() && dq.front() == i - k)
- dq.pop_front();
- while (!dq.empty() && nums[dq.back()] < nums[i])
- dq.pop_back();
- dq.push_back(i);
- if (i >= k - 1)
- ans.push_back(nums[dq.front()]);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 3, -1, -3, 5, 3, 6, 7}, n2 = {1};
- for (auto i : obj.maxSlidingWindow(n1, 3))
- printf("%d ", i); // expect: 3,3,5,5,6,7
- printf("\n");
- for (auto i : obj.maxSlidingWindow(n2, 1))
- printf("%d ", i); // expect: 1
- printf("\n");
-}
diff --git a/other/smallest_num_set.cpp b/other/smallest_num_set.cpp
deleted file mode 100644
index f05147b..0000000
--- a/other/smallest_num_set.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-// 2336. Smallest Number in Infinite Set
-#include "leetcode.h"
-
-/*
- * you have a set which contains all positive integers [1,2,3,...]
- * implement the SmallestInfiniteSet class:
- * - SmallestInfiniteSet() initialises the SmallestInfiniteSet
- * object to contain all positive integers
- * - int popSmallest() removes and returns the smallest integer
- * contained in the infinite set
- * - void addBack(int num) adds a positive integer num back into
- * the infinite set, if it is not already in the infinite set
- */
-
-class SmallestInfiniteSet {
-public:
- int k = 1;
- unordered_map<int, int> um;
- SmallestInfiniteSet() {
- for (int i = 1; i <= 1000; i++)
- um[i] = i;
- }
- int popSmallest() {
- int d = um[k];
- um.erase(k);
- for (int i = k + 1; i <= 1000; i++) {
- if (um.find(i) != um.end()) {
- k = i;
- break;
- }
- }
- return d;
- }
- void addBack(int num) {
- um[num] = num;
- if (num < k)
- k = num;
- }
-};
-
-int main() {
- SmallestInfiniteSet *obj = new SmallestInfiniteSet();
- int param_1 = obj->popSmallest();
- obj->addBack(2);
-}
diff --git a/other/smallest_string_swaps.cpp b/other/smallest_string_swaps.cpp
deleted file mode 100644
index c521309..0000000
--- a/other/smallest_string_swaps.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> parent;
- string smallestStringWithSwaps(string s, vector<vector<int>> &pairs) {
- parent.resize(s.length());
- map<int, set<int>> obj;
- set<int> idx;
- string ans = s;
- for (int i = 0; i < parent.size(); i++)
- parent[i] = i;
- for (int i = 0; i < pairs.size(); i++) {
- int u = pairs[i][0];
- int v = pairs[i][1];
- int fx = findParent(u);
- int fy = findParent(v);
- if (fx != fy)
- parent[fy] = fx;
- }
- for (int i = 0; i < pairs.size(); i++) {
- int u = pairs[i][0];
- int v = pairs[i][1];
- int fx = findParent(u);
- obj[fx].insert(u);
- obj[fx].insert(v);
- }
- for (auto it = obj.begin(); it != obj.end(); it++) {
- idx = it->second;
- vector<pair<char, int>> t;
- auto index = idx.begin();
- for (index = idx.begin(); index != idx.end(); index++) {
- int pos = *index;
- char ch = s[pos];
- t.push_back({ch, pos});
- }
- sort(t.begin(), t.end());
- index = idx.begin();
- for (int i = 0; i < t.size(); i++) {
- ans[*index] = t[i].first;
- index++;
- }
- }
- return ans;
- }
-
-private:
- int findParent(int n) {
- if (parent[n] == n)
- return n;
- return parent[n] = findParent(parent[n]);
- }
-};
-
-int main() {}
diff --git a/other/smallest_sufficient_team.cpp b/other/smallest_sufficient_team.cpp
deleted file mode 100644
index 473e218..0000000
--- a/other/smallest_sufficient_team.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-// 1125. Smallest Sufficient Team
-#include "leetcode.h"
-
-/*
- * in a project, you have a list of required required skills ' req_skills' and a
- * list of people. the i'th person 'people[i]' contains a list of skills that
- * the person has. consider a sufficient team: a set of people such that for
- * every required skill in 'req_skills', there is at least one person in the
- * tema who has that skill. we can represent these teams by the index of each
- * person. return any sufficient team of the smallest possible size, represented
- * by the index of each person. you may return the answer in any order. it is
- * guaranteed an answer exists
- */
-
-class Solution {
-public:
- vector<int> smallestSufficientTeam(vector<string> &req_skills,
- vvd(string) & people) {
- int n = req_skills.size();
- unordered_map<int, vector<int>> ans;
- ans.reserve(1 << n);
- ans[0] = {};
- unordered_map<string, int> skill_map;
- for (int i = 0; i < n; i++)
- skill_map[req_skills[i]] = i;
- for (int i = 0; i < people.size(); i++) {
- int curr = 0;
- for (int j = 0; j < people[i].size(); j++)
- curr |= 1 << skill_map[people[i][j]];
- for (auto k = ans.begin(); k != ans.end(); k++) {
- int com = k->first | curr;
- if (ans.find(com) == ans.end() ||
- ans[com].size() > 1 + ans[k->first].size()) {
- ans[com] = k->second;
- ans[com].push_back(i);
- }
- }
- }
- return ans[(1 << n) - 1];
- }
-};
-
-int main() {
- Solution obj;
- vector<string> rs1 = {"java", "nodejs", "reactjs"};
- vvd(string) p1 = {{"java"}, {"nodejs"}, {"nodejs", "reactjs"}};
- vector<string> rs2 = {"algorithms", "math", "java",
- "reactjs", "csharp", "aws"};
- vvd(string) p2 = {{"algorithms", "math", "java"},
- {"algorithms", "math", "reactjs"},
- {"java", "csharp", "aws"},
- {"reactjs", "csharp"},
- {"csharp", "math"},
- {"aws", "java"}};
- for (auto i : obj.smallestSufficientTeam(rs1, p1))
- printf("%d ", i); // expect: 0 2
- printf("\n");
- for (auto i : obj.smallestSufficientTeam(rs2, p2))
- printf("%d ", i); // expect: 1 2
- printf("\n");
-}
diff --git a/other/snakes_ladders.cpp b/other/snakes_ladders.cpp
deleted file mode 100644
index 160b473..0000000
--- a/other/snakes_ladders.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-// 909. Snakes and Ladders
-#include "leetcode.h"
-
-typedef pair<int, int> pii;
-class Solution {
-public:
- int snakesAndLadders(vvd & board) {
- int rows = board.size(), cols = board[0].size();
- int target = rows * cols, r, c, p;
- vector<int> visited(rows * cols + 1); // cells on board starting from 1
- priority_queue<pii, vector<pii>, greater<pii>> pq;
- pq.push(make_pair(0, 1));
- visited[1] = true;
- while (pq.size()) {
- auto stepPos = pq.top();
- pq.pop();
- int s = stepPos.first / 1000 + 1;
- for (int i = 1; i <= 6; i++) {
- auto p = stepPos.second + i;
- if (visited[p])
- continue;
- visited[p] = true;
- r = rows - (p - 1) / cols - 1;
- c = (p - 1) % cols;
- if ((rows - r - 1) % 2)
- c = cols - c - 1;
- int ladder = board[r][c];
- if (ladder > 0 && ladder <= target)
- p = ladder;
- if (p == target)
- return s;
- pq.push(make_pair(s * 1000 + 500 - p, p));
- }
- }
- return -1;
- }
-};
-
-int main() {
- Solution obj;
- vvd board1 = {{-1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1},
- {-1, -1, -1, -1, -1, -1}, {-1, 35, -1, -1, 13, -1},
- {-1, -1, -1, -1, -1, -1}, {-1, 15, -1, -1, -1, -1}};
- vvd board2 = {{-1, -1}, {-1, 3}};
- cout << obj.snakesAndLadders(board1) << endl; // expect: 4
- cout << obj.snakesAndLadders(board2) << endl; // expect: 1
-}
diff --git a/other/snapshot_array.cpp b/other/snapshot_array.cpp
deleted file mode 100644
index 42d165b..0000000
--- a/other/snapshot_array.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-// 1146. Snapshot Array
-#include "leetcode.h"
-
-/*
- * implement a 'SnapshotArray' class that supports the following interface
- * - 'SnapshotArray(int length)' initialises an array-like data structure with
- * the given length. initially, each element equals zero.
- * - 'void set(index, val)' sets the element at the given 'index' to be equal to
- * 'val'
- * - 'int snap()' takes a snapshot of the array and retusn the 'snap_id': the
- * total number of times we called 'snap()' minus 1
- * - 'int get(index, snap_id)' returns the value at the given 'index', at the
- * time we took the snapshot with the given 'snap_id'
- */
-
-class SnapshotArray {
- int curr_snap = 0;
- vector<vector<pair<int, int>>> vvp;
-
-public:
- SnapshotArray(int length) { vvp = vector<vector<pair<int, int>>>(length); }
- void set(int index, int val) {
- if (vvp[index].empty() || vvp[index].back().first != curr_snap)
- vvp[index].push_back({curr_snap, val});
- else
- vvp[index].back().second = val;
- }
- int snap() { return curr_snap++; }
- int get(int index, int snap_id) {
- auto i = upper_bound(begin(vvp[index]), end(vvp[index]),
- pair<int, int>(snap_id, INT_MAX));
- return i == begin(vvp[index]) ? 0 : prev(i)->second;
- }
-};
-
-int main() {
- SnapshotArray *obj = new SnapshotArray(3);
- obj->set(0, 5);
- printf("%d\n", obj->snap()); // expect: 0
- obj->set(0, 6);
- printf("%d\n", obj->get(0, 0)); // expect: 5
-}
diff --git a/other/sort_array.cpp b/other/sort_array.cpp
deleted file mode 100644
index 655726d..0000000
--- a/other/sort_array.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-// 912. Sort an Array
-#include "leetcode.h"
-#include <vector>
-
-class Solution {
-public:
- vector<int> sortArray(vector<int> &nums) {
- int end_idx, curr_idx, n = nums.size();
- if (n <= 1)
- return {};
- for (int i = n - 1; i; i--)
- for (int j = 0; j < i; j++)
- if (nums[j] > nums[j + 1])
- swap(nums[j], nums[j + 1]);
- return nums;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {5, 2, 3, 1}, n2 = {5, 1, 1, 2, 0, 0};
- for (auto i : obj.sortArray(n1))
- cout << i << ' '; // expect: 1,2,3,5
- cout << endl;
- for (auto i : obj.sortArray(n2))
- cout << i << ' '; // expect: 0,0,1,1,2,5
-}
diff --git a/other/sort_array_parity.cpp b/other/sort_array_parity.cpp
deleted file mode 100644
index 33f02b1..0000000
--- a/other/sort_array_parity.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> sortArrayByParity(vector<int> &nums) {
- /*
- * important to assign vector values first:
- * vector... var(size, vals)
- */
- vector<int> ans(nums.size(), 0);
-
- /*
- * start at first element (0)
- * end at "last" element minus 1
- * because arrays initialize at 0
- */
- int start = 0, end = nums.size() - 1;
-
- for (int i = 0; i < nums.size(); i++) {
- if (nums[i] % 2 == 1)
- /*
- * odd
- * assign "last" array value to current nums value
- * and incrementally decrease end when necessary
- */
- ans[end--] = nums[i];
- else
- /*
- * even
- * assign "first" array value to current nums value
- * and incrementally increase start when necessary
- */
- ans[start++] = nums[i];
- }
- return ans;
- }
-};
-
-int main() {
- vector<int> nums = {3, 1, 2, 4};
- Solution obj;
- for (int i = 0; i < nums.size(); i++)
- cout << nums[i] << ' ';
- cout << endl;
- obj.sortArrayByParity(nums);
-}
diff --git a/other/sort_char_freq.cpp b/other/sort_char_freq.cpp
deleted file mode 100644
index ea7d8af..0000000
--- a/other/sort_char_freq.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- string frequencySort(string s) {
- unordered_map<char, int> freq;
- for (auto a : s)
- freq[a]++;
- priority_queue<pair<int, char>> pqp;
- for (auto [a, f] : freq)
- pqp.push({f, a});
- string ans;
- pair<int, char> curr;
- while (!pqp.empty()) {
- curr = pqp.top();
- pqp.pop();
- ans += string(curr.first, curr.second);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.frequencySort("tree");
-}
diff --git a/other/sort_char_freq.rs b/other/sort_char_freq.rs
deleted file mode 100644
index a9d0e13..0000000
--- a/other/sort_char_freq.rs
+++ /dev/null
@@ -1,16 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn frequency_sort(s: String) -> String {
- let mut map = std::collections::HashMap::with_capacity(26 * 2);
- s.chars().for_each(|b| * map.entry(b).or_insert(0) += 1);
- let mut v = map.into_iter().map(|(c, n)| (c, n)).collect::<Vec<_>>();
- v.sort_unstable_by_key(|pair| - pair.1);
- v.into_iter().flat_map(|(c, n)| vec![c; n as usize]).collect()
- }
-}
-
-fn main() {
- let s = String::from("tree");
- print!("{}", Solution::frequency_sort(s));
-}
diff --git a/other/sort_items_dependencies.cpp b/other/sort_items_dependencies.cpp
deleted file mode 100644
index 1887d05..0000000
--- a/other/sort_items_dependencies.cpp
+++ /dev/null
@@ -1,74 +0,0 @@
-// 1203. Sort Items by Groups Respecting Dependencies
-#include "leetcode.h"
-
-/*
- * there are 'n' items in each belonging to zero or one of 'm' groups where
- * 'group[i]' is the group that the i'th item beglons to and it's equal to '-1'
- * if the i'th item beglongs to no group. the items and the groups are zero
- * indexed. a group can have no item belonging to it. return a sorted list of
- * the items such that
- * - the items that belong to the same group are next to each other in the
- * sorted list
- * - there are some relations between these items where 'beforeItems[i]' is a
- * list containing all the items that should come before the i'th item in the
- * sorted array (to the left of the i'th item) return any solution if there is
- * more than one solution and return an empty list if there is no solution.
- */
-
-class Solution {
- bool top_sort(vector<unordered_set<int>> &al, int i, vector<int> &res,
- vector<int> &stat) {
- if (stat[i])
- return stat[i] == 2;
- stat[i] = 1;
- for (auto n : al[i])
- if (!top_sort(al, n, res, stat))
- return false;
- stat[i] = 2;
- res.push_back(i);
- return true;
- }
-
-public:
- vector<int> sortItems(int n, int m, vector<int> &group,
- vvd & beforeItems) {
- vector<int> ans(n), stat(n + 2 * m), ans_tmp;
- vector<unordered_set<int>> al(n + 2 * m);
- for (auto i = 0; i < n; ++i) {
- if (group[i] != -1) {
- al[n + group[i]].insert(i);
- al[i].insert(n + m + group[i]);
- }
- for (auto j : beforeItems[i]) {
- if (group[i] != -1 && group[i] == group[j])
- al[j].insert(i);
- else {
- auto ig = group[i] == -1 ? i : n + group[i];
- auto jg = group[j] == -1 ? j : n + m + group[j];
- al[jg].insert(ig);
- }
- }
- }
- for (int n = al.size() - 1; n >= 0; --n)
- if (!top_sort(al, n, ans_tmp, stat))
- return {};
- reverse(begin(ans_tmp), end(ans_tmp));
- copy_if(begin(ans_tmp), end(ans_tmp), ans.begin(),
- [&](int i) { return i < n; });
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> g1 = {-1, -1, 1, 0, 0, 1, 0, -1},
- g2 = {-1, -1, 1, 0, 0, 1, 0, -1};
- vvd bi1 = {{}, {6}, {5}, {6}, {3, 6}, {}, {}, {}},
- bi2 = {{}, {6}, {5}, {6}, {3}, {}, {4}, {}};
- for (auto i : obj.sortItems(8, 2, g1, bi1))
- printf("%d ", i); // expect: [6,3,4,1,5,2,0,7]
- printf("\n");
- for (auto i : obj.sortItems(8, 2, g2, bi2))
- printf("%d ", i); // expect: []
- printf("\n");
-}
diff --git a/other/sort_matrix_diagonal.cpp b/other/sort_matrix_diagonal.cpp
deleted file mode 100644
index 61f3486..0000000
--- a/other/sort_matrix_diagonal.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- unordered_map<int, vector<int>> umv;
- vector<vector<int>> diagonalSort(vector<vector<int>> &mat) {
- int m = mat.size(), n = mat[0].size();
- for (int i = 0; i < m; i++)
- for (int j = 0; j < n; j++)
- umv[i - j].push_back(mat[i][j]);
- for (int i = -(n - 1); i < m; i++)
- sort(umv[i].begin(), umv[i].end());
- for (int i = m - 1; i >= 0; i--) {
- for (int j = n - 1; j >= 0; j--) {
- mat[i][j] = umv[i - j].back();
- umv[i - j].pop_back();
- }
- }
- return mat;
- }
-};
diff --git a/other/sorted_arrary_bst.cpp b/other/sorted_arrary_bst.cpp
deleted file mode 100644
index e859528..0000000
--- a/other/sorted_arrary_bst.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- TreeNode *sortedArrayToBST(vector<int> &nums) {
- int start = 0, end = nums.size() - 1;
- TreeNode *root = helper(start, end, nums);
- return root;
- }
-
-private:
- TreeNode *helper(int start, int end, vector<int> &nums) {
- if (start > end)
- return NULL;
- int mid = start + (end - start) / 2;
- TreeNode *node = new TreeNode(nums[mid]);
- node->left = helper(start, mid - 1, nums);
- node->right = helper(mid + 1, end, nums);
- return node;
- }
-};
diff --git a/other/soup_servings.cpp b/other/soup_servings.cpp
deleted file mode 100644
index 1733c21..0000000
--- a/other/soup_servings.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-// 808. Soup Servings
-#include "leetcode.h"
-
-/*
- * there are two types of soup: type a, and type b. initially, we have 'n' ml of
- * each type of soup. there are four kinds of operations:
- * 1. serve 100 ml of soup a and 0ml of soup b
- * 2. serve 75ml of soup a and 25ml of soup b
- * 3. serve 50ml of soup a and 50ml of soup b
- * 4. serve 25ml of soup a and 75ml of soup b
- * when we serve some soup, we give it to someone, and we no longer have it.
- * each turn, we will choose from the four operations with an equal probability
- * of '0.25'. if the remaining volume of soup is not enough to complete the
- * operation, we will serve as much as possible. we stop once we no longer have
- * some quantity of both types of soup. note that we do not have an operation
- * where all 100 ml's of soup b are used first. return the probability that soup
- * a will be empty first, plus half the probability that a and b become empty at
- * the same time. answers within '10^-5' of the actual answer will be accepted.
- */
-
-class Solution {
- unordered_map<int, unordered_map<int, double>> store;
- double helper(int a, int b) {
- if (!a && b)
- return 1;
- else if (!a && !b)
- return 0.5;
- else if (a && !b)
- return 0;
- if (store[a][b])
- return store[a][b];
- double prob = 0;
- prob += 0.25 * helper(a - min(a, 100), b);
- prob += 0.25 * helper(a - min(a, 75), b - min(b, 25));
- prob += 0.25 * helper(a - min(a, 50), b - min(b, 50));
- prob += 0.25 * helper(a - min(a, 25), b - min(b, 75));
- store[a][b] = prob;
- return prob;
- }
-
-public:
- double soupServings(int n) {
- if (n >= 5000)
- return 1.0;
- else
- return helper(n, n);
- }
-};
-
-int main() {
- Solution obj;
- printf("%f\n", obj.soupServings(50)); // expect: 0.62500
- printf("%f\n", obj.soupServings(100)); // expect: 0.71875
-}
diff --git a/other/spiral_matrix.cpp b/other/spiral_matrix.cpp
deleted file mode 100644
index d1c294b..0000000
--- a/other/spiral_matrix.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// 54. Spiral Matrix
-#include "leetcode.h"
-
-// given an m x n 'matrix', return all elements of the 'matrix' in spiral order
-
-class Solution {
-public:
- vector<int> spiralOrder(vvd & matrix) {
- vvd dirs{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
- int rows = matrix.size(), cols = matrix[0].size();
- vector<int> ans, n_step{cols, rows - 1};
- if (!rows || !cols)
- return ans;
- int i_dir = 0, i_row = 0, i_col = -1;
- while (n_step[i_dir % 2]) {
- for (int i = 0; i < n_step[i_dir % 2]; ++i) {
- i_row += dirs[i_dir][0];
- i_col += dirs[i_dir][1];
- ans.push_back(matrix[i_row][i_col]);
- }
- n_step[i_dir % 2]--;
- i_dir = (i_dir + 1) % 4;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd m1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
- vvd m2 = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
- for (auto i : obj.spiralOrder(m1))
- printf("%d, ", i);
- printf("\n"); // expect: 1,2,3,6,9,8,7,4,5
- for (auto i : obj.spiralOrder(m2))
- printf("%d, ", i); // expect: 1,2,3,4,8,12,11,10,9,5,6,7
-}
diff --git a/other/spiral_matrix2.cpp b/other/spiral_matrix2.cpp
deleted file mode 100644
index dc8dc11..0000000
--- a/other/spiral_matrix2.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-// 59. Spiral Matrix II
-#include "leetcode.h"
-
-// given a positive integer 'n', generate an n x n 'matrix' filled with
-// elements from 1 to 'n^2' in spiral order
-
-class Solution {
-public:
- vvd generateMatrix(int n) {
- vvd matrix(n, vector<int>(n));
- int num = 1, row = 0, col = 0, dir = 0;
- vector<int> d_r = {0, 1, 0, -1}, d_c = {1, 0, -1, 0};
- while (num <= n * n) {
- matrix[row][col] = num;
- num++;
- int next_row = row + d_r[dir];
- int next_col = col + d_c[dir];
- if (next_row < 0 || next_row >= n || next_col < 0 || next_col >= n ||
- matrix[next_row][next_col])
- dir = (dir + 1) % 4;
- row += d_r[dir];
- col += d_c[dir];
- }
- return matrix;
- }
-};
diff --git a/other/split_array_consec_subseq.cpp b/other/split_array_consec_subseq.cpp
deleted file mode 100644
index 622e296..0000000
--- a/other/split_array_consec_subseq.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool isPossible(vector<int> &nums) {
- unordered_map<int, int> um;
- for (auto &it : nums)
- um[it]++;
- for (auto &it : nums) {
- if (um[it] == 0)
- continue;
- int freq = um[it], curr = it, count = 0;
- while (um.count(curr) && um[curr] >= freq) {
- freq = fmax(freq, um[curr]);
- um[curr]--;
- count++;
- curr++;
- }
- if (count < 3)
- return false;
- }
- return true;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {1, 2, 3, 4, 5};
- if (obj.isPossible(nums))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/stack_using_queues.cpp b/other/stack_using_queues.cpp
deleted file mode 100644
index 61e2c88..0000000
--- a/other/stack_using_queues.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class MyStack {
-public:
- queue<int> q;
- MyStack() {}
- void push(int x) {
- int n = q.size();
- q.push(x);
- while (n--) {
- q.push(q.front());
- q.pop();
- }
- }
- int pop() {
- int ans = top();
- q.pop();
- return ans;
- }
- int top() { return q.front(); }
- bool empty() { return q.empty(); }
-};
-
-int main() {}
diff --git a/other/stamping_sequence.cpp b/other/stamping_sequence.cpp
deleted file mode 100644
index b9ba317..0000000
--- a/other/stamping_sequence.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> movesToStamp(string stamp, string target) {
- if (stamp == target)
- return {0};
- int sLen = stamp.size(), tLen = target.size() - sLen + 1, i, j;
- vector<int> ans;
- bool tDiff = true, sDiff;
- while (tDiff) {
- for (i = 0, tDiff = false; i < tLen; i++) {
- for (j = 0, sDiff = false; j < sLen; j++) {
- if (target[i + j] == '*')
- continue;
- else if (target[i + j] != stamp[j])
- break;
- else
- sDiff = true;
- }
- if (j == sLen && sDiff) {
- for (j = i, tDiff = true; j < sLen + i; j++)
- target[j] = '*';
- ans.push_back(i);
- }
- }
- for (i = 0; i < target.size(); i++)
- if (target[i] != '*')
- return {};
- reverse(ans.begin(), ans.end());
- }
- return ans;
- }
-};
diff --git a/other/steps_arr_increasing.cpp b/other/steps_arr_increasing.cpp
deleted file mode 100644
index 2beb625..0000000
--- a/other/steps_arr_increasing.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-// 2289. Steps to Make Array Non-decreasing
-#include "leetcode.h"
-
-/*
- * given a 0-indexed integer array 'nums'. in one step, remofe all elements
- * 'nums[i]' where 'nums[i - 1] > nums[i]' for all '0 < i < nums.size()'. return
- * the number of steps performed until 'nums' becomes non-decreasing
- */
-
-class Solution {
-public:
- int totalSteps(vector<int> &nums) {
- int n = nums.size(), ans = 0;
- vector<int> stack, dp(n);
- for (int i = n - 1; i >= 0; --i) {
- while (!stack.empty() && nums[i] > nums[stack.back()]) {
- dp[i] = max(++dp[i], dp[stack.back()]);
- stack.pop_back();
- ans = max(ans, dp[i]);
- }
- stack.push_back(i);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {5, 3, 4, 4, 7, 3, 6, 11, 8, 5, 11}, n2 = {4, 5, 7, 7, 13};
- printf("%d\n", obj.totalSteps(n1)); // expect: 3
- printf("%d\n", obj.totalSteps(n2)); // expect: 0
-}
diff --git a/other/stone_game2.cpp b/other/stone_game2.cpp
deleted file mode 100644
index 7ebc520..0000000
--- a/other/stone_game2.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-// 1140. Stone Game II
-#include "leetcode.h"
-
-/*
- * alice and bob continue their games with piles of stones. there are a number
- * of piles arranged in a row, and each pile has a positive integer number of
- * stones 'piles[i]'. the objective of the game is to end with the most stones.
- * alice and bob take turns, with alice starting first. initiall, 'M = 1'. on
- * each player's turn, that player can take all the stones on the 'X' remaining
- * piles, where '1 <= X <= 2M'. then, we set 'M = max(M, X)'. the game continues
- * until all the stones have been take. assuming alice and bob play optimally,
- * return maximum stones alice can get.
- */
-
-class Solution {
-public:
- int stoneGameII(vector<int> &piles) {
- int n = piles.size();
- vvd dp(n + 1, vector<int>(n + 1, 0));
- vector<int> sum(n + 1, 0);
- for (int i = n - 1; i >= 0; i--)
- sum[i] = sum[i + 1] + piles[i];
- for (int i = 0; i <= n; i++)
- dp[i][n] = sum[i];
- for (int i = n - 1; i >= 0; i--)
- for (int j = n - 1; j >= 1; j--)
- for (int k = 1; k <= 2 * j && i + j <= n; j++)
- dp[i][j] = max(dp[i][j], sum[i] - dp[i + k][max(j, k)]);
- return dp[0][1];
- }
-};
-
-int main() {
- Solution obj;
- vector<int> p1 = {2, 7, 9, 4, 4};
- vector<int> p2 = {1, 2, 3, 4, 5, 100};
- printf("%d\n", obj.stoneGameII(p1)); // expect: 10
- printf("%d\n", obj.stoneGameII(p2)); // expect: 104
-}
diff --git a/other/stone_game3.cpp b/other/stone_game3.cpp
deleted file mode 100644
index 947d65f..0000000
--- a/other/stone_game3.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-// 1406. Stone Game III
-#include <stdio.h>
-
-/*
- * alice and bob continue their games with piles of stones. there are several
- * stones arranged in a row, and each stone has an associated value which is an
- * integer given in the array 'stone_value'. alice and bob take turns with alice
- * starting first. on each player's turn, that player can take 1,2, or 3 stones
- * from the first remaining stones in row. the score of each player is the sum
- * of the values of the stones taken the score of each player is initially zero.
- * the objective of the game is to end with the highest score, and the winner is
- * the player with the highest score and there could be a tie. the game
- * continues until all the stones have been taken. assume alice and bob play
- * optimally. return "Alice", "Bob", or "Tie" accordingly
- */
-
-int min(int a, int b, int c) {
- if (a <= b && a <= c)
- return a;
- if (b <= a && b <= c)
- return b;
- return c;
-}
-
-char *stoneGameIII(int *stone_value, int stone_value_size) {
- int dp[50005] = {0}, sum = 0;
- for (int i = stone_value_size - 1; i >= 0; --i) {
- sum += stone_value[i];
- dp[i] = sum - min(dp[i + 1], dp[i + 2], dp[i + 3]);
- }
- if (dp[0] * 2 == sum)
- return "Tie";
- if (dp[0] * 2 > sum)
- return "Alice";
- else
- return "Bob";
-}
-
-int main() {
- int sv1[] = {1, 2, 3, 7};
- int sv2[] = {1, 2, 3, -9};
- int sv3[] = {1, 2, 3, 6};
- printf("%s\n", stoneGameIII(sv1, 4)); // expect: Bob
- printf("%s\n", stoneGameIII(sv2, 4)); // expect: Alice
- printf("%s\n", stoneGameIII(sv3, 4)); // expect: Tie
-}
diff --git a/other/stone_game4.cpp b/other/stone_game4.cpp
deleted file mode 100644
index 2eddb18..0000000
--- a/other/stone_game4.cpp
+++ /dev/null
@@ -1,16 +0,0 @@
-#include "leetcode.h"
-#include <vector>
-
-class Solution {
-public:
- int stoneGameVI(vector<int> &aliceValues, vector<int> &bobValues) {
- vector<array<int, 3>> n;
- int a = 0, b = 0, sz = aliceValues.size();
- }
-};
-
-int main() {
- Solution obj;
- vector<int> aliceValues = {1, 3}, bobValues = {2, 1};
- cout << obj.stoneGameVI(aliceValues, bobValues);
-}
diff --git a/other/strange_printer.cpp b/other/strange_printer.cpp
deleted file mode 100644
index 8a5dc93..0000000
--- a/other/strange_printer.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-// 664. Strange Printer
-#include "leetcode.h"
-
-/*
- * there is a strange printer with the following two special properties:
- * - the printer can only print a sequence of the same character each time
- * - at each turn, the printer can print new characters starting from and eding
- * at any place and will cover the origin existing characters given a string
- * 's', return the minimum number of turns the printer needed to print it.
- */
-
-class Solution {
-public:
- int strangePrinter(string s) {
- int n = s.size();
- vector<vector<int>> dp(n + 1, vector<int>(n));
- for (int i = n - 1; i >= 0; i--)
- for (int j = i; j < n; j++) {
- dp[i][j] = 1 + dp[i + 1][j];
- for (int k = i + 1; k <= j; k++)
- if (s[k] == s[i])
- dp[i][j] = min(dp[i][j], dp[i + 1][k - 1] + dp[k][j]);
- }
- return dp[0][n - 1];
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.strangePrinter("aaabbb")); // expect: 2
- printf("%d\n", obj.strangePrinter("aba")); // expect: 2
-}
diff --git a/other/string_compression.cpp b/other/string_compression.cpp
deleted file mode 100644
index 5f9b9c6..0000000
--- a/other/string_compression.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int compress(vector<char> &chars) {
- string ans;
- int c = 1, i;
- for (i = 1; i < chars.size(); i++) {
- if (chars[i] == chars[i - 1])
- c++;
- else if (chars[i] != chars[i - 1] && c == 1)
- ans += chars[i - 1];
- else {
- ans += chars[i - 1];
- ans += to_string(c);
- c = 1;
- }
- }
- if (c == 1)
- ans += chars[i - 1];
- else
- ans += chars[i - 1] + to_string(c);
- for (int i = 0; i < ans.size(); i++)
- chars[i] = ans[i];
- vector<char>::iterator it, ty;
- it = chars.begin() + ans.size();
- ty = chars.begin() + chars.size();
- chars.erase(it, ty);
- return ans.size();
- }
-};
diff --git a/other/string_compression.rs b/other/string_compression.rs
deleted file mode 100644
index 1d5db7d..0000000
--- a/other/string_compression.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn compress(chars: &mut Vec<char>) -> i32 {
- let (mut i, mut j, mut count, mut last_char) = (0, 1, 1, chars[0]);
- while j < chars.len() {
- if chars[j] == last_char {
- count += 1;
- } else {
- chars[i] = last_char;
- i += 1;
- if count > 1 {
- count.to_string().chars().for_each(|x| {
- chars[i] = x;
- i += 1;
- });
- }
- last_char = chars[j];
- count = 1;
- }
- j += 1;
- }
- chars[i] = last_char;
- i += 1;
- if count > 1 {
- count.to_string().chars().for_each(|x| {
- chars[i] = x;
- i += 1;
- });
- }
- i as i32
- }
-}
-
-fn main() {
- let mut c = vec!['a','a','b','b','c','c','c'];
- print!("{}", Solution::compress(&mut c));
-}
diff --git a/other/string_compression2.cpp b/other/string_compression2.cpp
deleted file mode 100644
index f4c41c8..0000000
--- a/other/string_compression2.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int getLengthOfOptimalCompression(string s, int k) {
- memset(dp, -1, sizeof(dp));
- str = s, p = s.size();
- return solve(0, k);
- }
-
-private:
- const static int N = 127;
- int dp[N][N], p;
- string str;
- inline int helper(int x) { return x == 1 ? 0 : x < 10 ? 1 : x < 100 ? 2 : 3; }
- int solve(int left, int k) {
- if (k < 0)
- return N;
- if (left >= p || p - left <= k)
- return 0;
- int &ans = dp[left][k];
- if (ans != -1)
- return ans;
- ans = N;
- int count[26] = {0};
- for (int i = left, j = 0; i < p; i++) {
- j = max(j, ++count[str[j] - 'a']);
- ans = min(ans, 1 + helper(j) + solve(i + 1, k - (i - left + 1 - j)));
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.getLengthOfOptimalCompression("aaabcccd", 2);
-}
diff --git a/other/string_compression2.rs b/other/string_compression2.rs
deleted file mode 100644
index 792a0ac..0000000
--- a/other/string_compression2.rs
+++ /dev/null
@@ -1,54 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn get_length_of_optimal_compression(s: String, k: i32) -> i32 {
- #[inline]
- fn len_of_chars(n: i32) -> i32 {
- match n {
- 1 => 1,
- 2..=9 => 2,
- 10..=99 => 3,
- _ => 4,
- }
- }
- fn dfs(v: &[u8], dp: &mut [[i32; 101]; 101], left: i32, k_s: i32) -> i32 {
- let mut k = k_s;
- if v.len() as i32 - left <= k {
- return 0;
- }
- if dp[left as usize][k as usize] >= 0 {
- return dp[left as usize][k as usize];
- }
- let mut ans = if k > 0 {
- dfs(v, dp, left + 1, k - 1)
- } else {
- std::i32::MAX
- };
- let mut c = 1;
- for i in left + 1..=v.len() as i32 {
- ans = ans.min(dfs(v, dp, i, k) + len_of_chars(c));
- if i == v.len() as i32 {
- break;
- }
- if v[i as usize] == v[left as usize] {
- c += 1;
- } else {
- k -= 1;
- if k < 0 {
- break;
- }
- }
- }
- dp[left as usize][k_s as usize] = ans;
- ans
- }
- let mut dp = [[-1; 101]; 101];
- let v = s.as_bytes();
- dfs(v, &mut dp, 0, k)
- }
-}
-
-fn main() {
- let s = String::from("aaabcccd");
- print!("{}", Solution::get_length_of_optimal_compression(s, 2));
-}
diff --git a/other/string_without_3a3b.cpp b/other/string_without_3a3b.cpp
deleted file mode 100644
index 738d000..0000000
--- a/other/string_without_3a3b.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-// 984. String Without AAA or BBB
-#include "leetcode.h"
-
-/*
- * given two integers 'a' and 'b', return any string 's' such that
- * - 's' has length 'a + b' and contains exactly 'a' a letters and exactly 'b' b
- * letters.
- * - the substring 'aaa' does not occur in 's' and
- * - the substring 'bbb' does not occur in 's'
- */
-
-class Solution {
-public:
- string strWithout3a3b(int a, int b) {
- string ans = "";
- int cnta = 0, cntb = 0, total = a + b;
- for (int i = 0; i < total; i++) {
- if ((b >= a && cntb < 2) || (cnta == 2 && b)) {
- ans += 'b';
- b--;
- cntb++;
- cnta = 0;
- } else if ((a >= b && cnta < 2) || (cntb == 2 && a)) {
- ans += 'a';
- a--;
- cnta++;
- cntb = 0;
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.strWithout3a3b(1, 2) << endl; // expect: "abb"
- cout << obj.strWithout3a3b(4, 1) << endl; // expect: "aabaa"
-}
diff --git a/other/subarr_fixed_bound.cpp b/other/subarr_fixed_bound.cpp
deleted file mode 100644
index 658c766..0000000
--- a/other/subarr_fixed_bound.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-// 2444. Count Subarrays With Fixed Bounds
-#include "leetcode.h"
-
-/*
- * given integer array 'nums' and two integers 'min_k' and 'max_k'. a fixed
- * bound subarr of 'nums' is a subarray that satisfies the following conditions:
- * minimum value in subarray is equal to 'min_k'. the max value in subarray is
- * equal to 'max_k'. return number of fixed-bound subarrays.
- */
-
-class Solution {
-public:
- long long countSubarrays(vector<int> &nums, int min_k, int max_k) {
- long long ans = 0, n = nums.size();
- for (int i = 0, j = 0; i <= n; ++i)
- if (i == n || nums[i] < min_k || nums[i] > max_k)
- for (int p1 = j, p2 = j; j <= i; ++j) {
- while (p1 < i && (p1 < j || nums[p1] != min_k))
- ++p1;
- while (p2 < i && (p2 < j || nums[p2] != max_k))
- ++p2;
- ans += i - max(p1, p2);
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {1, 3, 5, 2, 7, 5}, n2 = {1, 1, 1, 1};
- cout << obj.countSubarrays(n1, 1, 5) << endl; // expect: 2
- cout << obj.countSubarrays(n2, 1, 1) << endl; // expect: 10
-}
diff --git a/other/subarr_product_less_k.cpp b/other/subarr_product_less_k.cpp
deleted file mode 100644
index 64cb1b4..0000000
--- a/other/subarr_product_less_k.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int numSubarrayProductLessThanK(vector<int> &nums, int k) {
- if (k == 0)
- return 0;
- int count = 0, prod = 1;
- for (int low = 0, high = 0; high < nums.size(); high++) {
- prod *= nums[high];
- while (low <= high && prod >= k)
- prod /= nums[low++];
- count += (high - low + 1);
- }
- return count;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {10, 5, 2, 6};
- cout << obj.numSubarrayProductLessThanK(nums, 100);
-}
diff --git a/other/subarr_sum_divisible_k.cpp b/other/subarr_sum_divisible_k.cpp
deleted file mode 100644
index 3661c96..0000000
--- a/other/subarr_sum_divisible_k.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-// 974. Subarray Sums Divisible by K
-#include "leetcode.h"
-#include <vector>
-
-/*
- * given: integer array 'nums' and integer 'k'
- * return: number of non-empty subarrays that
- * have a sum divisible by 'k'.
- * a subarray is a contiguous part of an array
- */
-
-class Solution {
-public:
- int subarraysDivByK(vector<int> &nums, int k) {
- vector<int> count(k);
- count[0] = 1;
- int prefix = 0, ans = 0;
- for (int i : nums) {
- prefix = (prefix + i % k + k) % k;
- ans += count[prefix]++;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums1 = {4, 5, 0, -2, -3, 1}, nums2 = {5};
- cout << obj.subarraysDivByK(nums1, 5); // expect: 7
- cout << obj.subarraysDivByK(nums2, 9); // expect: 0
- return 0;
-}
diff --git a/other/substr_largest_variance.cpp b/other/substr_largest_variance.cpp
deleted file mode 100644
index 6df445c..0000000
--- a/other/substr_largest_variance.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-// 2272. Substring With Largest Variance
-#include "leetcode.h"
-
-/*
- * the variance of a string is defined as the largest difference between the
- * number of ocurrences of any '2' characters present in the string. note the
- * two characters may or may not be the same. given a string 's', consisting of
- * lowercase english letters only, return the largest variance possible among
- * all substrings 's'. a substring is a contiguous sequence of characters witin
- * a string.
- */
-
-class Solution {
-public:
- int largestVariance(string s) {
- vector<int> arr(26);
- for (auto i : s)
- arr[i - 'a']++;
- int ans = 0;
- for (char i = 'a'; i <= 'z'; i++) {
- for (char j = 'a'; j <= 'z'; j++) {
- if (j == i || !arr[i - 'a'] || !arr[j - 'a'])
- continue;
- for (int k = 1; k <= 2; k++) {
- int a1 = 0, a2 = 0;
- for (auto l : s) {
- if (l == i)
- a1++;
- if (l == j)
- a2++;
- if (a2 > a1)
- a1 = 0, a2 = 0;
- if (a1 && a2)
- ans = max(ans, a1 - a2);
- }
- reverse(s.begin(), s.end());
- }
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.largestVariance("aababbb")); // expect: 3
- printf("%d\n", obj.largestVariance("abcde")); // expect: 0
-};
diff --git a/other/sum_dist_tree.cpp b/other/sum_dist_tree.cpp
deleted file mode 100644
index 10fc449..0000000
--- a/other/sum_dist_tree.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> sumOfDistancesInTree(int n, vvd & edges) {
- tree.resize(n);
- ans.assign(n, 0);
- count.assign(n, 1);
- for (auto e : edges) {
- tree[e[0]].insert(e[1]);
- tree[e[1]].insert(e[0]);
- }
- dfs(0, -1);
- dfs2(0, -1);
- return ans;
- }
-
-private:
- vector<unordered_set<int>> tree;
- vector<int> ans, count;
- void dfs(int root, int pre) {
- for (auto i : tree[root]) {
- if (i == pre)
- continue;
- dfs(i, root);
- count[root] += count[i];
- ans[root] += ans[i] + count[i];
- }
- }
- void dfs2(int root, int pre) {
- for (auto i : tree[root]) {
- if (i == pre)
- continue;
- ans[i] = ans[root] - count[i] + count.size() - count[i];
- dfs2(i, root);
- }
- }
-};
-
-int main() {
- Solution obj;
- vvd edges = {{0, 1}, {0, 2}, {2, 3}, {2, 4}, {2, 5}};
- for (auto i : obj.sumOfDistancesInTree(6, edges))
- cout << i << ' '; // expect: 8 12 6 10 10 10
-}
diff --git a/other/sum_dist_tree.rs b/other/sum_dist_tree.rs
deleted file mode 100644
index d000d83..0000000
--- a/other/sum_dist_tree.rs
+++ /dev/null
@@ -1,49 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn sum_of_distances_in_tree(n: i32, edges: Vec<Vec<i32>>) -> Vec<i32> {
- let n = n as usize;
- let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
- for e in edges.iter() {
- adj[e[0] as usize].push(e[1] as usize);
- adj[e[1] as usize].push(e[0] as usize);
- }
- let mut dp = vec![[0; 2]; n];
- Self::get_depth_sum_count(0, n, &mut dp, &adj);
- let mut ans = vec![0; n];
- Self::get_ans(0, n, 0, &mut ans, &dp, &adj);
- ans
- }
- fn get_depth_sum_count(i: usize, parent: usize, dp: &mut Vec<[i32; 2]>, adj: &Vec<Vec<usize>>) {
- dp[i][1] = 1;
- for &j in adj[i].iter() {
- if j == parent {
- continue;
- }
- Self::get_depth_sum_count(j, i, dp, adj);
- dp[i][0] += dp[j][0] + dp[j][1];
- dp[i][1] += dp[j][1];
- }
- }
- fn get_ans(i: usize, parent: usize, acc_sum: i32, ans: &mut Vec<i32>, dp: &Vec<[i32; 2]>, adj: &Vec<Vec<usize>>) {
- ans[i] = acc_sum + dp[i][0];
- for &j in adj[i].iter() {
- if j == parent {
- continue;
- }
- let sum2 = acc_sum + dp[i][0] + dp.len() as i32 - dp[j][0] - dp[j][1] * 2;
- Self::get_ans(j, i, sum2, ans, dp, adj);
- }
- }
-}
-
-fn main() {
- let edges = vec![
- vec![0,1],
- vec![0,2],
- vec![2,3],
- vec![2,4],
- vec![2,5]
- ];
- print!("{:?}", Solution::sum_of_distances_in_tree(6, edges));
-}
diff --git a/other/sum_even_num_queries.cpp b/other/sum_even_num_queries.cpp
deleted file mode 100644
index a58e3b2..0000000
--- a/other/sum_even_num_queries.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> sumEvenAfterQueries(vector<int> &nums, vvd & queries) {
- int evenSum = 0;
- for (auto x : nums)
- if (x % 2 == 0)
- evenSum += x;
- vector<int> ans;
- for (auto q : queries) {
- int val = q[0], idx = q[1];
- if (nums[idx] % 2 == 0)
- evenSum -= nums[idx];
- nums[idx] += val;
- if (nums[idx] % 2 == 0)
- evenSum += nums[idx];
- ans.push_back(evenSum);
- }
- return ans;
- }
-};
diff --git a/other/sum_root_leaf_num.cpp b/other/sum_root_leaf_num.cpp
deleted file mode 100644
index d1bc9c6..0000000
--- a/other/sum_root_leaf_num.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-// 129. Sum Root to Leaf Numbers
-#include "leetcode.h"
-
-/*
- * given 'root' of binary tree containing digits 0-9 only. each root-to-leaf
- * pattern in the tree represents a number. eg. root-to-leaf path 1->2->3
- * represents the integer 123. return total sum of all root-to-leaf numbers.
- * test cases will fit in 32-bit integer. a leaf node is a node with no children
- */
-
-class Solution {
-public:
- int sumNumbers(TreeNode *root) {
- int sum = 0, curr = 0, depth = 0;
- while (root) {
- if (root->left) {
- auto pre = root->left;
- depth = 1;
- while (pre->right && pre->right != root) {
- pre = pre->right;
- depth++;
- }
- if (!pre->right) {
- pre->right = root;
- curr = curr * 10 + root->val;
- root = root->left;
- } else {
- pre->right = nullptr;
- if (!pre->left)
- sum += curr;
- curr /= pow(10, depth);
- }
- } else {
- curr = curr * 10 + root->val;
- if (!root->right)
- sum += curr;
- root = root->right;
- }
- }
- return sum;
- }
-};
diff --git a/other/sum_subarr_mins.cpp b/other/sum_subarr_mins.cpp
deleted file mode 100644
index 8f90e37..0000000
--- a/other/sum_subarr_mins.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int sumSubarrayMins(vector<int> &arr) {
- vector<long> s, sums(arr.size(), 0);
- long j, ans = 0, mod = 1000000007;
- for (int i = 0; i < arr.size(); ++i) {
- while (!s.empty() && arr[s.back()] > arr[i])
- s.pop_back();
- j = !s.empty() ? s.back() : -1;
- sums[i] = ((j >= 0 ? sums[j] : 0) + (i - j) * arr[i]) % mod;
- s.push_back(i);
- }
- for (int i = 0; i < sums.size(); ++i)
- ans = (ans + sums[i]) % mod;
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> arr = {
- 117, 1315, 1336, 4213, 5634, 6288, 7640, 8533, 9688, 10186,
- 10593, 11896, 13673, 14707, 15484, 17429, 19639, 20416, 21375, 23601,
- 25800, 26485, 27893, 28026, 28695, 29121, 28642, 28023, 27642, 26324,
- 23844, 22069, 21124, 20181, 18957, 15736, 15364, 13749, 13612, 11062,
- 10319, 9755, 9367, 7977, 6463, 6049, 4886, 3071, 1331, 865};
- cout << obj.sumSubarrayMins(arr);
-}
diff --git a/other/sum_subarr_mins.rs b/other/sum_subarr_mins.rs
deleted file mode 100644
index ee28cb9..0000000
--- a/other/sum_subarr_mins.rs
+++ /dev/null
@@ -1,37 +0,0 @@
-use std::collections::VecDeque;
-struct Solution;
-
-impl Solution {
- pub fn sum_subarray_mins(arr: Vec<i32>) -> i32 {
- const MOD: i32 = 1e9 as i32 + 7;
- let n: usize = arr.len();
- let mut stk: VecDeque<isize> = {
- let mut stk: VecDeque<isize> = VecDeque::with_capacity(n);
- stk.push_back(-1);
- stk
- };
- let mut ans: i32 = 0;
- let mut dp: Vec<i32> = vec![0; n + 1];
- for i in 0..n {
- while let Some(&top) = stk.back() {
- if top != -1 && arr[i] <= arr[top as usize] {
- stk.pop_back();
- } else {
- break;
- }
- }
- if let Some(&top) = stk.back() {
- dp[i + 1] = (dp[top as usize + 1] + (i as i32 - top as i32) * arr[i]) % MOD;
- }
- stk.push_back(i as isize);
- ans += dp[i + 1];
- ans %= MOD;
- }
- ans
- }
-}
-
-fn main() {
- let arr = vec![3,1,2,4];
- print!("{}", Solution::sum_subarray_mins(arr));
-}
diff --git a/other/sum_subset_xor.cpp b/other/sum_subset_xor.cpp
deleted file mode 100644
index a3048f7..0000000
--- a/other/sum_subset_xor.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-#include "leetcode.h"
-
-/*
- 000 => {empty set}
- 001 => {set with only first element}
- 010 => {set with only second element}
- 011 => {set with first and second element}
- 100 ... and so on
- 101
- 110
- 111 => {subset with all three elements}
-*/
-
-class Solution {
-public:
- int subsetXORSum(vector<int> &nums) {
- int n = nums.size(), subsetNum = pow(2, n), ans = 0;
- for (int i = 1; i < subsetNum; ++i) {
- int runningXOR = 0;
- for (int j = 0, bits = i; j < nums.size(); ++j, bits >>= 1)
- if (bits & 1)
- runningXOR ^= nums[j];
- ans += runningXOR;
- }
- return ans;
- }
-};
-
-int main() {
- vector<int> nums = {3, 4, 5, 6, 7, 8};
- Solution obj;
- cout << obj.subsetXORSum(nums);
-}
diff --git a/other/summary_ranges.cpp b/other/summary_ranges.cpp
deleted file mode 100644
index d2feb9e..0000000
--- a/other/summary_ranges.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-// 228. Summary Ranges
-#include "leetcode.h"
-
-/*
- * given a sorted unique integer array 'nums'. a range '[a, b]' isthe set of all
- * integers from 'a' to 'b' (inclusive). return the smallest sorted list of
- * ranges that cover all the numbers in the array exactlyh. that is, each
- * element of 'nums' is covered by exactly one of the ranges, and there is no
- * integer 'x' such that 'x' is in one of the ranges but not in 'nums' each
- * range '[a, b]' in the list should be outgput as:
- * - "a->b" if a != b
- * - "a" if a == b
- */
-
-class Solution {
-public:
- vector<string> summaryRanges(vector<int> &nums) {
- int n = nums.size();
- vector<string> ans;
- string tmp = "";
- for (int i = 0; i < n; i++) {
- int j = i;
- while (j + 1 < n && nums[j + 1] == nums[j] + 1)
- j++;
- if (j > i) {
- tmp += to_string(nums[i]);
- tmp += "->";
- tmp += to_string(nums[j]);
- } else
- tmp += to_string(nums[i]);
- ans.push_back(tmp);
- tmp = "";
- i = j;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {0, 1, 2, 4, 5, 7}, n2 = {0, 2, 3, 4, 6, 8, 9};
- for (auto i : obj.summaryRanges(n1))
- cout << i << ' '; // expect: 0.2 4.5 7
- printf("\n");
- for (auto i : obj.summaryRanges(n2))
- cout << i << ' '; // expect: 0.4 6 8.9
-}
diff --git a/other/swap_node_linked_list.cpp b/other/swap_node_linked_list.cpp
deleted file mode 100644
index b5ad832..0000000
--- a/other/swap_node_linked_list.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-#include <iostream>
-using namespace std;
-
-struct ListNode {
- int val;
- ListNode *next;
- ListNode() : val(0), next(nullptr) {}
- ListNode(int x) : val(x), next(nullptr) {}
- ListNode(int x, ListNode *next) : val(x), next(next) {}
-};
-
-// implementation
-class Solution {
-public:
- ListNode *swapNodes(ListNode *head, int k) {
- ListNode *x = head, *y = head, *t = head;
- while (k > 1) {
- x = x->next;
- t = t->next;
- k--;
- }
-
- while (t->next) {
- y = y->next;
- t = t->next;
- }
-
- int temp = x->val;
- x->val = y->val;
- y->val = temp;
- return head;
- }
-};
-// end
-
-int main() {
- ListNode *l = new ListNode(1);
- l->next = new ListNode(2);
- l->next->next = new ListNode(3);
- l->next->next->next = new ListNode(4);
- l->next->next->next->next = new ListNode(5);
- int k = 2;
- Solution *sol = new Solution();
- sol->swapNodes(l, k);
-}
diff --git a/other/swap_nodes_pairs.cpp b/other/swap_nodes_pairs.cpp
deleted file mode 100644
index 139c336..0000000
--- a/other/swap_nodes_pairs.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-// 24. Swap Nodes in Pairs
-#include "leetcode.h"
-
-/*
- * given a linked list, swap every two adjacent nodes and return
- * its head. problem must be solved without modifying values
- * in the list's nodes (ie only nodes themselves may be changed)
- */
-
-class Solution {
-public:
- ListNode *swapPairs(ListNode *head) {
- if (!head || !head->next)
- return head;
- ListNode *tmp;
- tmp = head->next;
- head->next = swapPairs(head->next->next);
- tmp->next = head;
- return tmp;
- }
-};
diff --git a/other/symmetric_tree.cpp b/other/symmetric_tree.cpp
deleted file mode 100644
index fbd4bf3..0000000
--- a/other/symmetric_tree.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-// 101. Symmetric Tree
-#include "leetcode.h"
-
-// given 'root' of binary tree, check whether it is a mirror of itself
-
-class Solution {
-public:
- bool isSymmetric(TreeNode *root) {
- TreeNode *left, *right;
- if (!root)
- return true;
- queue<TreeNode *> q1, q2;
- q1.push(root->left);
- q2.push(root->right);
- while (!q1.empty() && !q2.empty()) {
- left = q1.front();
- q1.pop();
- right = q2.front();
- q2.pop();
- if (left == NULL && right == NULL)
- continue;
- if (left == NULL || right == NULL)
- return false;
- if (left->val != right->val)
- return false;
- q1.push(left->left);
- q1.push(left->right);
- q2.push(right->right);
- q2.push(right->left);
- }
- return true;
- }
-};
diff --git a/other/tallest_billboard.cpp b/other/tallest_billboard.cpp
deleted file mode 100644
index 1201823..0000000
--- a/other/tallest_billboard.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int tallestBillboard(vector<int> &rods) {
- unordered_map<int, int> dp;
- dp[0] = 0;
- for (int i : rods) {
- unordered_map<int, int> tmp;
- for (auto &it : dp) {
- int diff = it.first;
- tmp[diff + i] = max(tmp[diff + i], dp[diff] + i);
- tmp[diff - i] = max(tmp[diff - i], dp[diff]);
- }
- dp.clear();
- dp.insert(tmp.begin(), tmp.end());
- }
- return dp[0];
- }
-};
-
-int main() {
- Solution obj;
- vector<int> rods = {1, 2, 3, 6};
- cout << obj.tallestBillboard(rods);
-}
diff --git a/other/task_scheduler.cpp b/other/task_scheduler.cpp
deleted file mode 100644
index 553dd5d..0000000
--- a/other/task_scheduler.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-// 2365. Task Scheduler II
-#include "leetcode.h"
-
-/*
- * given a 0-indexed array of positive integers 'tasks', representing tasks that
- * need to be completed in order, where 'tasks[i]' represents the type of the
- * i'th task. you are also given a positve integer 'space' which represents the
- * minimum number of days that must pass after the completion of a task before
- * another task of the same type can be performed. each day until all tasks have
- * been completed, you must either
- * - complete the next task from 'tasks' or
- * - take a break
- * return the minimum number of days needed to complete all tasks.
- */
-
-class Solution {
-public:
- long long taskSchedulerII(vector<int> &tasks, int space) {
- unordered_map<int, long long> last;
- long long ans = 0;
- for (int t : tasks) {
- if (last.count(t))
- last[t] = ans = max(ans, last[t] + space) + 1;
- else
- last[t] = ++ans;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> t1 = {1, 2, 1, 2, 3, 1}, t2 = {5, 8, 8, 5};
- printf("%lld\n", obj.taskSchedulerII(t1, 3)); // expect: 9
- printf("%lld\n", obj.taskSchedulerII(t2, 2)); // expect: 6
-}
diff --git a/other/text_justification.cpp b/other/text_justification.cpp
deleted file mode 100644
index d45bead..0000000
--- a/other/text_justification.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<string> fullJustify(vector<string> &words, int maxWidth) {
- vector<string> ans, taken;
- int lineLen = 0;
- for (auto word : words) {
- if (lineLen + word.size() + taken.size() > maxWidth) {
- ans.push_back(lineBegin(taken, maxWidth - lineLen));
- taken.clear();
- taken.push_back(word);
- lineLen = word.size();
- } else {
- taken.push_back(word);
- lineLen += word.size();
- }
- }
- ans.push_back(lineEnd(taken, maxWidth - lineLen));
- return ans;
- }
-
-private:
- string lineBegin(vector<string> &v, int toFill) {
- string ans = "";
- if (v.size() == 1) {
- ans += v[0];
- while (toFill--)
- ans += ' ';
- return ans;
- }
- int space = toFill / (v.size() - 1);
- int extras = toFill % (v.size() - 1);
- ans += v[0];
- for (int i = 1; i < v.size(); i++) {
- for (int j = 0; j < space; j++)
- ans += ' ';
- if (extras) {
- extras--;
- ans += ' ';
- }
- }
- return ans;
- }
- string lineEnd(vector<string> &v, int toFill) {
- string ans = v[0];
- for (int i = 1; i < v.size(); i++) {
- toFill--;
- ans += ' ';
- ans += v[i];
- }
- while (toFill--)
- ans += ' ';
- return ans;
- }
-};
diff --git a/other/thousand_separator.cpp b/other/thousand_separator.cpp
deleted file mode 100644
index a0493f5..0000000
--- a/other/thousand_separator.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-#include <cmath>
-#include <string>
-
-class Solution {
-public:
- string thousandSeparator(int n) {
- string s = to_string(n);
- if (trunc(log10(n)) + 1 < 4)
- return s;
-
- return s;
- }
-};
-
-int main() {
- Solution obj;
- obj.thousandSeparator(1234);
- // cout << obj.thousandSeparator(1234);
-}
diff --git a/other/time_base_key_val.cpp b/other/time_base_key_val.cpp
deleted file mode 100644
index c23fb87..0000000
--- a/other/time_base_key_val.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-#include "leetcode.h"
-
-class TimeMap {
-public:
- unordered_map<string, vector<pair<int, string>>> umvp;
- TimeMap() {}
- void set(string key, string value, int timestamp) {
- umvp[key].push_back({timestamp, value});
- }
- string get(string key, int timestamp) {
- if (!umvp.count(key))
- return "";
- int start = 0, end = umvp[key].size();
- while (start < end) {
- int mid = start + (end - start) / 2;
- if (umvp[key][mid].first > timestamp)
- end = mid;
- else
- start = mid + 1;
- }
- return start > 0 && start <= umvp[key].size() ? umvp[key][start - 1].second
- : "";
- }
-};
-
-int main() {
- string key, value;
- int timestamp;
- TimeMap *obj = new TimeMap();
- obj->set(key, value, timestamp);
- string param_2 = obj->get(key, timestamp);
-}
diff --git a/other/toeplitz_matrix.cpp b/other/toeplitz_matrix.cpp
deleted file mode 100644
index f451196..0000000
--- a/other/toeplitz_matrix.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool isToeplitzMatrix(vvd & matrix) {
- int m = matrix.size(), n = matrix[0].size();
- for (int i = 1; i < m; i++)
- for (int j = 1; j < n; j++)
- if (matrix[i][j] != matrix[i - 1][j - 1])
- return false;
- return true;
- }
-};
-
-int main() {
- Solution obj;
- // true - all diagonals have the same elements
- vvd matrix = {{1, 2, 3, 4}, {5, 1, 2, 3}, {9, 5, 1, 2}};
- // false - diagonals do not share same elements
- vvd matrix2 = {{1, 2}, {2, 2}};
-
- if (obj.isToeplitzMatrix(matrix))
- cout << "true";
- else
- cout << "false";
- if (obj.isToeplitzMatrix(matrix2))
- cout << "\ntrue";
- else
- cout << "\nfalse";
-}
diff --git a/other/toeplitz_matrix.rs b/other/toeplitz_matrix.rs
deleted file mode 100644
index 03a46bb..0000000
--- a/other/toeplitz_matrix.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn is_toeplitz_matrix(matrix: Vec<Vec<i32>>) -> bool {
- let (m, n) = (matrix.len(), matrix[0].len());
- for i in 1..m {
- for j in 1..n {
- if matrix[i][j] != matrix[i - 1][j - 1] {
- return false;
- }
- }
- }
- true
- }
-}
-
-fn main() {
- let matrix = vec![vec![1,2,3,4],
- vec![5,1,2,3],
- vec![9,5,1,2]];
- print!("{}", Solution::is_toeplitz_matrix(matrix));
-}
diff --git a/other/top_k_freq_element.cpp b/other/top_k_freq_element.cpp
deleted file mode 100644
index 343595f..0000000
--- a/other/top_k_freq_element.cpp
+++ /dev/null
@@ -1,18 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> topKFrequent(vector<int> &nums, int k) {
- unordered_map<int, int> um;
- for (int n : nums)
- um[n]++;
- vector<int> ans;
- priority_queue<pair<int, int>> pqp;
- for (auto it = um.begin(); it != um.end(); it++) {
- pqp.push(make_pair(it->second, it->first));
- if (pqp.size() > um.size() - k)
- ans.push_back(pqp.top().second), pqp.pop();
- }
- return ans;
- }
-};
diff --git a/other/top_k_freq_element.rs b/other/top_k_freq_element.rs
deleted file mode 100644
index 82a2b03..0000000
--- a/other/top_k_freq_element.rs
+++ /dev/null
@@ -1,32 +0,0 @@
-//347. Top K Frequent Elements
-struct Solution;
-
-/*
-* given an integer array 'nums' and an integer 'k', return the 'k' most frequent elements. you may
-* return the answer in any order.
-*/
-
-impl Solution {
- pub fn top_k_frequent(nums: Vec<i32>, k: i32) -> Vec<i32> {
- let mut map = std::collections::HashMap::new();
- for x in nums {
- *map.entry(x).or_insert(0) += 1;
- }
- let mut arr = map.into_iter().collect::<Vec<(i32,i32)>>();
- arr.sort_by(|a,b| 1.1.cmp(&b.1));
- arr.reverse();
- let k = k as usize;
- let mut ans = vec![0;k];
- for i in 0..k {
- ans[i] = arr[i].0;
- }
- ans
- }
-}
-
-fn main() {
- let n1 = vec![1,1,1,2,2,3];
- let n2 = vec![1];
- print!("{}", Solution::top_k_frequent(n1, 2)); //expect: [1,2]
- print!("{}", Solution::top_k_frequent(n2, 1)); //expect: [1]
-}
diff --git a/other/top_k_freq_words.cpp b/other/top_k_freq_words.cpp
deleted file mode 100644
index eaf31d5..0000000
--- a/other/top_k_freq_words.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-#include "leetcode.h"
-
-struct Compare {
- bool operator()(pair<int, string> a, pair<int, string> b) {
- if (a.first == b.first)
- return a.second > b.second;
- else
- return a.first < b.first;
- }
-};
-
-class Solution {
-public:
- vector<string> topKFrequent(vector<string> &words, int k) {
- unordered_map<string, int> um;
- for (int i = 0; i < words.size(); i++)
- um[words[i]]++;
- priority_queue<pair<int, string>, vector<pair<int, string>>, Compare>
- pqpvpc;
- for (auto i : um)
- pqpvpc.push({i.second, i.first});
- vector<string> ans;
- while (k--) {
- ans.push_back(pqpvpc.top().second);
- pqpvpc.pop();
- }
- return ans;
- }
-};
diff --git a/other/top_k_freq_words.rs b/other/top_k_freq_words.rs
deleted file mode 100644
index 606c237..0000000
--- a/other/top_k_freq_words.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-use std::collections::BinaryHeap;
-use std::collections::HashMap;
-
-struct Solution;
-
-impl Solution {
- pub fn top_k_frequent(words: Vec<String>, k: i32) -> Vec<String> {
- let mut word_to_freq = HashMap::<String, i32>::new();
- for w in words {
- *word_to_freq.entry(w).or_default() += 1;
- }
- let mut heap = BinaryHeap::<(i32, String)>::new();
- for (word, freq) in word_to_freq {
- heap.push((-freq, word));
- if heap.len() > k as usize {
- heap.pop();
- }
- }
- let mut ans: Vec<String> = vec![];
- while let Some((_freq, word)) = heap.pop() {
- ans.push(word);
- }
- ans.reverse();
- ans
- }
-}
diff --git a/other/transpose_matrix.cpp b/other/transpose_matrix.cpp
deleted file mode 100644
index b6ab293..0000000
--- a/other/transpose_matrix.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-#include <vector>
-
-class Solution {
-public:
- vector<vector<int>> transpose(vector<vector<int>> &matrix) {
- int n = matrix.size(), m = matrix[0].size();
- vector<vector<int>> ans(m, vector<int>(n, 0));
- for (int i = 0; i < n; i++)
- for (int j = 0; j < m; j++)
- ans[j][i] = matrix[i][j];
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<vector<int>> matrix;
- obj.transpose(matrix);
-}
diff --git a/other/trapping_rain_water.cpp b/other/trapping_rain_water.cpp
deleted file mode 100644
index d2ced43..0000000
--- a/other/trapping_rain_water.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int trap(vector<int> &height) {
- if (height.size() <= 2)
- return 0;
- int n = height.size(), maxLeft = height[0], maxRight = height[n - 1];
- int left = 1, right = n - 2, ans = 0;
- while (left <= right) {
- if (maxLeft < maxRight) {
- if (height[left] > maxLeft)
- maxLeft = height[left];
- else
- ans += maxLeft - height[left];
- left += 1;
- } else {
- if (height[right] > maxRight)
- maxRight = height[right];
- else
- ans += maxRight - height[right];
- right -= 1;
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
- cout << obj.trap(height);
-}
diff --git a/other/trie_prefix.cpp b/other/trie_prefix.cpp
deleted file mode 100644
index b56e38b..0000000
--- a/other/trie_prefix.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-// 208. Implement Trie (Prefix Tree)
-#include "leetcode.h"
-
-class Trie {
-public:
- Trie() {}
- void insert(string word) {
- Trie *node = this;
- for (char c : word) {
- if (!node->next.count(c))
- node->next[c] = new Trie();
- node = node->next[c];
- }
- node->is_word = true;
- }
- bool search(string word) {
- Trie *node = this;
- for (char c : word) {
- if (!node->next.count(c))
- return false;
- node = node->next[c];
- }
- return node->is_word;
- }
- bool startsWith(string prefix) {
- Trie *node = this;
- for (char c : prefix) {
- if (!node->next.count(c))
- return false;
- node = node->next[c];
- }
- return true;
- }
-
-private:
- map<char, Trie *> next = {};
- bool is_word = false;
-};
-
-int main() {
- Trie *obj = new Trie();
- obj->insert("Trie");
- bool param_2 = obj->search("Trie");
- bool param_3 = obj->startsWith("Trie");
-}
diff --git a/other/two_sum.cpp b/other/two_sum.cpp
deleted file mode 100644
index e75565d..0000000
--- a/other/two_sum.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-// 1. Two Sum
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> twoSum(vector<int> &nums, int target) {
- vector<int> ans;
- unordered_map<int, int> um;
- int n = nums.size();
- for (int i = 0; i < n; i++) {
- int search_num = target - nums[i];
- if (um.find(search_num) != um.end()) {
- ans.push_back(um[search_num]);
- ans.push_back(i);
- break;
- }
- um[nums[i]] = i;
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n1 = {2, 7, 11, 15}, n2 = {3, 2, 4}, n3 = {3, 3};
- for (auto i : obj.twoSum(n1, 9))
- printf("%d ", i);
- printf("\n");
- for (auto i : obj.twoSum(n2, 6))
- printf("%d ", i);
- printf("\n");
- for (auto i : obj.twoSum(n3, 6))
- printf("%d ", i);
- printf("\n");
-}
diff --git a/other/two_sum_2.cpp b/other/two_sum_2.cpp
deleted file mode 100644
index 55741ac..0000000
--- a/other/two_sum_2.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-#include "leetcode.h"
-#include <vector>
-
-class Solution {
-public:
- vector<int> twoSum(vector<int> &numbers, int target) {
- vector<int> ans;
- for (int i = 0; i < numbers.size(); i++) {
- int low = 0, high = numbers.size() - 1;
- while (low <= high) {
- int mid = low + (high - low) / 2;
- if (numbers[mid] == target - numbers[i]) {
- if (mid == i)
- low = mid + 1;
- else
- return {i + 1, mid + 1};
- } else if (numbers[mid] < target - numbers[i])
- low = mid + 1;
- else
- high = mid - 1;
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> numbers = {2, 7, 11, 15};
- int target = 9;
- // expected output: 1,2
- obj.twoSum(numbers, target);
-}
diff --git a/other/two_sum_4.cpp b/other/two_sum_4.cpp
deleted file mode 100644
index c25bcc9..0000000
--- a/other/two_sum_4.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool findTarget(TreeNode *root, int k) {
- vector<int> nums;
- order(root, nums);
- for (int i = 0, j = nums.size() - 1; i < j;) {
- if (nums[i] + nums[j] == k)
- return true;
- (nums[i] + nums[j] < k) ? i++ : j--;
- }
- return false;
- }
-
-private:
- void order(TreeNode *root, vector<int> &nums) {
- if (root == NULL)
- return;
- order(root->left, nums);
- nums.push_back(root->val);
- order(root->right, nums);
- }
-};
diff --git a/other/ugly_number.cpp b/other/ugly_number.cpp
deleted file mode 100644
index 8af53f8..0000000
--- a/other/ugly_number.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool isUgly(int n) {
- if (n == 0)
- return false;
- for (int i : {2, 3, 5})
- while (n % i == 0)
- n /= i;
- return n == 1;
- }
-};
-
-int main() {
- Solution obj;
- if (obj.isUgly(6))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/ugly_number.rs b/other/ugly_number.rs
deleted file mode 100644
index e356ff2..0000000
--- a/other/ugly_number.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn is_ugly(mut n: i32) -> bool {
- if n == 0 {
- return false;
- }
- for i in vec![2,3,5] {
- while n % i == 0 {
- n /= i;
- }
- }
- n == 1
- }
-}
-
-fn main() {
- print!("{}", Solution::is_ugly(6));
-}
diff --git a/other/uncrossed_lines.cpp b/other/uncrossed_lines.cpp
deleted file mode 100644
index c8156b1..0000000
--- a/other/uncrossed_lines.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-// 1035. Uncrossed Lines
-#include "leetcode.h"
-
-/*
- * given two integer arrays 'nums1' and 'num2'. we write the integers of 'nums1'
- * and 'nums2' (in the order they are given) on two separate horizontal lines.
- * we may draw connecting lines: a straight line connecting two numbers
- * 'nums1[i]' and 'nums2[j]' such thatyr
- * - 'nums1[i] == nums2[j]' and
- * - the line we draw does not intersect any other connecting (non-horizontal)
- * line note that a connecting line cannot intereset even at the endpoints.
- * return the maximum number of connecting lines we can draw in this way.
- */
-
-class Solution {
-public:
- int maxUncrossedLines(vector<int> &nums1, vector<int> &nums2) {
- int n = nums1.size(), m = nums2.size();
- vvd dp(n + 1, vector<int>(m + 1, 0));
- for (int i = 1; i <= n; i++)
- for (int j = 1; j <= m; j++) {
- if (nums1[i - 1] == nums2[j - 1])
- dp[i][j] = 1 + dp[i - 1][j - 1];
- else
- dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
- }
- return dp[n][m];
- }
-};
-
-int main() {
- Solution obj;
- vector<int> n11 = {1, 4, 2}, n21 = {1, 2, 4};
- vector<int> n12 = {2, 5, 1, 2, 5}, n22 = {10, 5, 2, 1, 5, 2};
- vector<int> n13 = {1, 3, 7, 1, 7, 5}, n23 = {1, 9, 2, 5, 1};
- printf("%d\n", obj.maxUncrossedLines(n11, n21)); // expect: 2
- printf("%d\n", obj.maxUncrossedLines(n12, n22)); // expect: 3
- printf("%d\n", obj.maxUncrossedLines(n13, n23)); // expect: 2
-}
diff --git a/other/unique_bst.cpp b/other/unique_bst.cpp
deleted file mode 100644
index 7aefacd..0000000
--- a/other/unique_bst.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int numTrees(int n) {
- if (n == 1)
- return 1;
- vector<int> dp(n + 1);
- dp[0] = dp[1] = 1;
- for (int i = 2; i <= n; i++) {
- for (int j = 0; j < i; j++) {
- int k = i - 1 - j;
- dp[i] += (dp[j] * dp[k]);
- }
- }
- return dp[n];
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.numTrees(3);
-}
diff --git a/other/unique_bst2.cpp b/other/unique_bst2.cpp
deleted file mode 100644
index 438d9b7..0000000
--- a/other/unique_bst2.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-// 95. Unique Binary Search Trees II
-#include "leetcode.h"
-
-/*
- * given an integer 'n', return all the structurally unique BST's which has
- * exactly 'n' nodes of unique values from 1 to 'n'. return the answer in any
- * order.
- */
-
-class Solution {
- vector<TreeNode *> build(int from, int to) {
- vector<TreeNode *> res;
- if (to - from < 0)
- res.push_back(0);
- if (to - from == 0)
- res.push_back(new TreeNode(from));
- if (to - from > 0)
- for (int i = 0; i <= to; i++) {
- vector<TreeNode *> left = build(from, i - 1);
- vector<TreeNode *> right = build(i + 1, to);
- for (int j = 0; j < left.size(); j++)
- for (int k = 0; k < right.size(); k++) {
- TreeNode *height = new TreeNode(i);
- height->left = left[j];
- height->right = right[k];
- res.push_back(height);
- }
- }
- return res;
- }
-
-public:
- vector<TreeNode *> generateTrees(int n) { return build(1, n); }
-};
diff --git a/other/unique_morse_code_words.cpp b/other/unique_morse_code_words.cpp
deleted file mode 100644
index 2a6280e..0000000
--- a/other/unique_morse_code_words.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int uniqueMorseRepresentations(vector<string> &words) {
- vector<string> codes = {
- ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
- ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
- "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
- set<string> ans;
- for (auto word : words) {
- string curr = "";
- for (auto ch : word)
- curr += codes[ch - 97];
- ans.insert(curr);
- }
- return ans.size();
- }
-};
-
-int main() {
- Solution obj;
- vector<string> words = {"gin", "zen", "gig", "msg"};
- cout << obj.uniqueMorseRepresentations(words);
-}
diff --git a/other/unique_num_occurrences.cpp b/other/unique_num_occurrences.cpp
deleted file mode 100644
index 5c4871f..0000000
--- a/other/unique_num_occurrences.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool uniqueOccurrences(vector<int> &arr) {
- short m[2001] = {};
- for (auto n : arr)
- ++m[n + 1000];
- sort(begin(m), end(m));
- for (auto i = 1; i < 2001; ++i)
- if (m[i] && m[i] == m[i - 1])
- return false;
- return true;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> arr = {1, 2, 2, 1, 1, 3};
- if (obj.uniqueOccurrences(arr))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/unique_num_occurrences.rs b/other/unique_num_occurrences.rs
deleted file mode 100644
index d29c580..0000000
--- a/other/unique_num_occurrences.rs
+++ /dev/null
@@ -1,20 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn unique_occurrences(arr: Vec<i32>) -> bool {
- let (mut counter, mut set) = ([0; 2001], [false; 1000]);
- arr.iter().for_each(|&x| counter[(x + 1000) as usize] += 1);
- for &x in counter.iter().filter(|&&x| x > 0) {
- match set[x as usize] {
- true => return false,
- false => set[x as usize] = true
- }
- }
- true
- }
-}
-
-fn main() {
- let arr = vec![1,2,2,1,1,3];
- print!("{}", Solution::unique_occurrences(arr));
-}
diff --git a/other/unique_paths.cpp b/other/unique_paths.cpp
deleted file mode 100644
index 053a92b..0000000
--- a/other/unique_paths.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int uniquePaths(int m, int n) {
- int dp[m][n];
- for (int i = 0; i < m; i++) {
- for (int j = 0; j < n; j++) {
- if (i == 0 || j == 0)
- dp[i][j] = 1;
- else
- dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
- }
- }
- return dp[m - 1][n - 1];
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.uniquePaths(3, 7);
-}
diff --git a/other/unique_paths2.cpp b/other/unique_paths2.cpp
deleted file mode 100644
index fedb826..0000000
--- a/other/unique_paths2.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-// 63. Unique Paths II
-#include "leetcode.h"
-
-/*
- You are given an m x n integer array grid. There is a robot initially located
- at the top-left corner (i.e., grid[0][0]). The robot tries to move to the
- bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either
- down or right at any point in time.
-
- An obstacle and space are marked as 1 or 0 respectively in grid. A path that
- the robot takes cannot include any square that is an obstacle.
-
- Return the number of possible unique paths that the robot can take to reach
- the bottom-right corner.
-
- The testcases are generated so that the answer will be less than or equal to 2
- * 109.
- */
-
-class Solution {
-public:
- int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) {
- int m = obstacleGrid.size(), n = obstacleGrid[0].size();
- vvd dp(m + 1, vector<int>(n + 1, 0));
- dp[0][1] = 1;
- for (int i = 1; i <= m; ++i)
- for (int j = 1; j <= n; ++j)
- if (!obstacleGrid[i - 1][j - 1])
- dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
- return dp[m][n];
- }
-};
-
-int main() {
- Solution obj;
- vvd og1 = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}, og2 = {{0, 1}, {0, 0}};
- printf("%d\n", obj.uniquePathsWithObstacles(og1)); // expect: 2
- printf("%d\n", obj.uniquePathsWithObstacles(og2)); // expect: 1
-}
diff --git a/other/unique_paths3.cpp b/other/unique_paths3.cpp
deleted file mode 100644
index 37876fa..0000000
--- a/other/unique_paths3.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int uniquePathsIII(vvd & grid) {
- auto i1 = 0, j1 = 0, t_steps = 0;
- for (auto i = 0; i < grid.size(); ++i)
- for (auto j = 0; j < grid[0].size(); ++j) {
- if (grid[i][j] == 1)
- i1 = i, j1 = j;
- if (grid[i][j] != -1)
- ++t_steps;
- }
- return dfs(grid, i1, j1, 1, t_steps);
- }
-
-private:
- int dfs(vvd & grid, int i, int j, int step, int t_step) {
- if (i < 0 || j < 0 || i >= grid.size() || j >= grid[0].size() ||
- grid[i][j] == -1)
- return 0;
- if (grid[i][j] == 2)
- return step == t_step ? 1 : 0;
- grid[i][j] = -1;
- int paths = dfs(grid, i + 1, j, step + 1, t_step) +
- dfs(grid, i - 1, j, step + 1, t_step) +
- dfs(grid, i, j + 1, step + 1, t_step) +
- dfs(grid, i, j - 1, step + 1, t_step);
- grid[i][j] = 0;
- return paths;
- }
-};
-
-int main() {
- Solution obj;
- vvd grid = {{1, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 2, -1}};
- cout << obj.uniquePathsIII(grid); // expect: 2
-}
diff --git a/other/unique_paths3.rs b/other/unique_paths3.rs
deleted file mode 100644
index b83c50e..0000000
--- a/other/unique_paths3.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn unique_paths_iii(mut grid: Vec<Vec<i32>>) -> i32 {
- let (start_x, start_y) = (0..grid.len())
- .flat_map(|y| (0..grid[0].len()).map(move |x| (x, y)))
- .find(|&(x, y)| grid[y][x] == 1)
- .expect("grid does not have starting square!");
- let num_empty = grid.iter()
- .flat_map(|r| r.iter().filter(|&&c| c != -1)).count();
- Self::dfs(&mut grid, start_x, start_y, num_empty - 1) as _
- }
- fn dfs(grid: &mut Vec<Vec<i32>>, x: usize, y: usize, num_empty: usize) -> usize {
- if x >= grid[0].len() || y >= grid.len() {
- return 0;
- }
- match grid[y][x] {
- 0 | 1 => {
- grid[y][x] = -1;
- let curr_paths = [(0,1),(1,0),(0,-1),(-1,0)]
- .iter()
- .map(|&(dx, dy)| ((x as isize + dx) as _, (y as isize + dy) as _))
- .map(|(nx, ny)| Self::dfs(grid, nx, ny, num_empty - 1)).sum();
- grid[y][x] = 0;
- curr_paths
- }
- 2 if num_empty == 0 => 1,
- _ => 0
- }
- }
-}
-
-fn main() {
- let grid = vec![
- vec![1,0,0,0],
- vec![0,0,0,0],
- vec![0,0,2,-1]
- ];
- print!("{}", Solution::unique_paths_iii(grid));
-}
diff --git a/other/utf8_validation.cpp b/other/utf8_validation.cpp
deleted file mode 100644
index 0cb96d7..0000000
--- a/other/utf8_validation.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool validUtf8(vector<int> &data) {
- int m1 = 0x80, m2 = 0x20, m3 = 0x10, m4 = 0x08, m5 = 0xC0;
- for (int i = 0; i < data.size(); i++) {
- if ((m5 & data[i]) == m1)
- return false;
- int bytes{0};
- if ((m1 & data[i]) == 0)
- continue;
- else if ((m2 & data[i]) == 0)
- bytes = 1;
- else if ((m3 & data[i]) == 0)
- bytes = 2;
- else if ((m4 & data[i]) == 0)
- bytes = 3;
- else
- return false;
- while (bytes--) {
- i++;
- if (i >= data.size() || ((m5 & data[i]) != m1))
- return false;
- }
- }
- return true;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> data = {197, 130, 1};
- if (obj.validUtf8(data))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/valid_anagram.cpp b/other/valid_anagram.cpp
deleted file mode 100644
index 2c2586e..0000000
--- a/other/valid_anagram.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool isAnagram(string s, string t) {
- if (s == t)
- return true;
- if (s.size() != t.size())
- return false;
- unordered_map<char, int> up;
- for (int i = 0; i < s.size(); i++) {
- up[s[i]]++;
- up[t[i]]--;
- }
- for (auto it : up)
- if (it.second)
- return false;
- return true;
- }
-};
-
-int main() {
- Solution obj;
- string s = "anagram", t = "nagaram";
- if (obj.isAnagram(s, t))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/valid_arrangement_pairs.cpp b/other/valid_arrangement_pairs.cpp
deleted file mode 100644
index 0493141..0000000
--- a/other/valid_arrangement_pairs.cpp
+++ /dev/null
@@ -1,73 +0,0 @@
-// 2097. Valid Arrangement of Pairs
-#include "leetcode.h"
-
-/*
- * you are given a 0-indexed 2d integer array 'pairs' where 'pairs[i] =
- * [start_i, end_i]'. an arrangement of 'pairs' is valid for every index 'i'
- * where '1 <= i < pairs.length', we have 'end_i-1 == start_i'. return any valid
- * arrangement of 'pairs'. note, the inputs will be generated such that there
- * exists a valid arrangement of 'pairs'.
- */
-
-class Solution {
-private:
- void euler(unordered_map<int, stack<int>> &adj, vector<vector<int>> &res,
- int curr) {
- auto &st = adj[curr];
- while (!st.empty()) {
- int n = st.top();
- st.pop();
- euler(adj, res, n);
- res.push_back({curr, n});
- }
- }
-
-public:
- vector<vector<int>> validArrangement(vector<vector<int>> &pairs) {
- int m = pairs.size();
- unordered_map<int, stack<int>> adj;
- unordered_map<int, int> in, out;
- adj.reserve(m);
- in.reserve(m);
- out.reserve(m);
- for (int i = 0; i < m; i++) {
- int u = pairs[i][0], v = pairs[i][1];
- in[v]++;
- out[u]++;
- adj[u].push(v);
- }
- int start = -1;
- for (auto &p : adj) {
- int i = p.first;
- if (out[i] - in[i] == 1)
- start = i;
- }
- if (start == -1)
- start = adj.begin()->first;
- vector<vector<int>> ans;
- euler(adj, ans, start);
- reverse(ans.begin(), ans.end());
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vvd p1 = {{5, 1}, {4, 5}, {11, 9}, {9, 4}},
- p2 = {{1, 3}, {3, 2}, {2, 1}}, p3 = {{1, 2}, {1, 3}, {2, 1}};
- vvd va1 = obj.validArrangement(p1);
- vvd va2 = obj.validArrangement(p2);
- vvd va3 = obj.validArrangement(p3);
- for (int i = 0; i < va1.size(); i++)
- for (int j = 0; j < va1[0].size(); j++)
- printf("%d ", va1[i][j]); // expect: [[11,9],[9,4],[4,5],[5,1]]
- printf("\n");
- for (int i = 0; i < va2.size(); i++)
- for (int j = 0; j < va2[0].size(); j++)
- printf("%d ", va2[i][j]); // expect: [[1,3],[3,2],[2,1]]
- printf("\n");
- for (int i = 0; i < va3.size(); i++)
- for (int j = 0; j < va3[0].size(); j++)
- printf("%d ", va1[i][j]); // expect: [[1,2],[2,1],[1,3]]
- printf("\n");
-}
diff --git a/other/valid_number.cpp b/other/valid_number.cpp
deleted file mode 100644
index 6395fe0..0000000
--- a/other/valid_number.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool isNumber(string s) {
- int state = 0, flag = 0;
- while (s[0] == ' ' || s[s.size() - 1] == ' ')
- s.erase(s.size() - 1, 1);
- for (int i = 0; i < s.size(); i++) {
- if ('0' <= s[i] && s[i] <= '9') {
- flag = 1;
- if (state <= 2)
- state = 2;
- else
- state = (state <= 5) ? 5 : 7;
- } else if (s[i] == '+' || s[i] == '-') {
- if (state == 0 || state == 3)
- state++;
- else
- return false;
- } else if (s[i] == '.') {
- if (state <= 2)
- state = 6;
- else
- return false;
- } else if (s[i] == 'e') {
- if (flag && (state == 2 || state == 6 || state == 7))
- state = 3;
- else
- return false;
- } else
- return false;
- }
- return (state == 2 || state == 5 || (flag && state == 6) || state == 7);
- }
-};
-
-int main() {
- Solution obj;
- string s = "3";
- if (obj.isNumber(s))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/valid_parentheses.cpp b/other/valid_parentheses.cpp
deleted file mode 100644
index 9bab082..0000000
--- a/other/valid_parentheses.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-// 20. Valid Parentheses
-#include "leetcode.h"
-
-/*
- * given a string 's' containing just the characters '(, ), {, }, [, ]',
- * determine if the input string is valid. a input string is valid if open
- * brackets must be closed by the same type of brackets. open brackets must be
- * closed in the correct order. every close bracket has a corresponding open
- * bracket of the same type.
- */
-
-class Solution {
-public:
- bool isValid(string s) {
- stack<char> stk;
- for (int i = 0; i < s.size(); i++) {
- char ch = s[i];
- if (ch == '(' || ch == '{' || ch == '[')
- stk.push(ch);
- else {
- if (!stk.empty()) {
- char top = stk.top();
- if ((ch == ')' && top == '(') || (ch == '}' && top == '{') ||
- (ch == ']' && top == '['))
- stk.pop();
- else
- return false;
- } else
- return false;
- }
- }
- if (stk.empty())
- return true;
- return false;
- }
-};
-
-int main() {
- Solution obj;
- printf("%d\n", obj.isValid("()")); // expect: 1
- printf("%d\n", obj.isValid("()[]{}")); // expect: 1
- printf("%d\n", obj.isValid("(]")); // expect: 0
-}
diff --git a/other/valid_stack_seq.cpp b/other/valid_stack_seq.cpp
deleted file mode 100644
index 62250db..0000000
--- a/other/valid_stack_seq.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-// 946. Validate Stack Sequences
-#include "leetcode.h"
-
-/*
- * given two integer arrays 'pushed' & 'popped' each with distinct
- * values, return true if this could have been the result of a sequence
- * of push and pop operations on an initially empty stack, or false otherwise
- */
-
-class Solution {
-public:
- bool validateStackSequences(vector<int> &pushed, vector<int> &popped) {
- stack<int> s;
- int i = 0;
- for (int x : pushed) {
- s.push(x);
- while (s.size() && s.top() == popped[i]) {
- s.pop();
- i++;
- }
- }
- return !s.size();
- }
-};
-
-int main() {
- Solution obj;
- vector<int> pushed = {1, 2, 3, 4, 5};
- vector<int> p1 = {4, 5, 3, 2, 1}, p2 = {4, 3, 5, 1, 2};
- printf("%d\n", obj.validateStackSequences(pushed, p1)); // expect: 1
- printf("%d\n", obj.validateStackSequences(pushed, p2)); // expect: 0
-}
diff --git a/other/valid_sudoku.cpp b/other/valid_sudoku.cpp
deleted file mode 100644
index 0843d67..0000000
--- a/other/valid_sudoku.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-#include "leetcode.h"
-#include <vector>
-
-class Solution {
-public:
- bool isValidSudoku(vvd(char) & board) {
- vector<set<char>> rows(9), cols(9), blck(9);
- for (int i = 0; i < 9; i++)
- for (int j = 0; j < 9; j++)
- if (board[i][j] != '.') {
- int m = board[i][j], n = (i / 3) * 3 + j / 3;
- if (!rows[i].emplace(m).second) // rows
- return false;
- if (!cols[j].emplace(m).second) // columns
- return false;
- if (!blck[n].emplace(m).second) // blocks
- return false;
- }
- return true;
- }
-};
-
-int main() {
- Solution obj;
- vvd(char) board = {{'8', '3', '.', '.', '7', '.', '.', '.', '.'},
- {'6', '.', '.', '1', '9', '5', '.', '.', '.'},
- {'.', '9', '8', '.', '.', '.', '.', '6', '.'},
- {'8', '.', '.', '.', '6', '.', '.', '.', '3'},
- {'4', '.', '.', '8', '.', '3', '.', '.', '1'},
- {'7', '.', '.', '.', '2', '.', '.', '.', '6'},
- {'.', '6', '.', '.', '.', '.', '2', '8', '.'},
- {'.', '.', '.', '4', '1', '9', '.', '.', '5'},
- {'.', '.', '.', '.', '8', '.', '.', '7', '9'}};
- if (obj.isValidSudoku(board))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/valid_sudoku.rs b/other/valid_sudoku.rs
deleted file mode 100644
index 3c2f591..0000000
--- a/other/valid_sudoku.rs
+++ /dev/null
@@ -1,27 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn is_valid_sudoku(board: Vec<Vec<char>>) -> bool {
- let mut rows: [u16; 9] = [0; 9];
- let mut cols: [u16; 9] = [0; 9];
- let mut blck: [u16; 9] = [0; 9];
- for i in 0..9 {
- for j in 0..9 {
- match board[i][j] {
- '.' => continue,
- c => {
- let b: usize = (i / 3) * 3 + (j / 3);
- let curr = 1 << (c.to_digit(10).unwrap());
- if rows[i] & curr != 0 || cols[j] & curr != 0 || blck[b] & curr != 0 {
- return false;
- }
- rows[i] |= curr;
- cols[j] |= curr;
- blck[b] |= curr;
- }
- }
- }
- }
- true
- }
-}
diff --git a/other/validate_bst.cpp b/other/validate_bst.cpp
deleted file mode 100644
index 0785d47..0000000
--- a/other/validate_bst.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool isValidBST(TreeNode *root) {
- if (!root)
- return true;
- inOrder(root);
- for (int i = 1; i < tree.size(); i++)
- if (tree[i] <= tree[i - 1])
- return false;
- return true;
- }
-
-private:
- vector<int> tree;
- void inOrder(TreeNode *root) {
- if (!root)
- return;
- inOrder(root->left);
- tree.push_back(root->val);
- inOrder(root->right);
- }
-};
diff --git a/other/verify_alien_dict.cpp b/other/verify_alien_dict.cpp
deleted file mode 100644
index 009ac52..0000000
--- a/other/verify_alien_dict.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-// 953. Verifying an Alien Dictionary
-#include "leetcode.h"
-
-/*
- * in an alien language, they also use english lowercase letters but in
- * different 'order'. the 'order' of the alphabet is some permutation of
- * lowercase letters. given a sequence of 'words' written in the alien language,
- * and the 'order' of the alphabet, return 1 if and only if the given 'words'
- * are sorted lexicographically in this alien language.
- */
-
-class Solution {
-public:
- bool isAlienSorted(vector<string> &words, string order) {
- size_t indices[26]{};
- for (size_t i = 0; i < order.size(); ++i)
- indices[order[i] - 'a'] = i;
- return is_sorted(words.begin(), words.end(),
- [&indices](const string &w1, const string &w2) {
- auto l1 = w1.size(), l2 = w2.size();
- for (auto i = 0; i < min(l1, l2); ++i) {
- auto c1 = w1[i], c2 = w2[i];
- if (c1 != c2)
- return indices[c1 - 'a'] < indices[c2 - 'a'];
- }
- return l1 < l2;
- });
- }
-};
-
-int main() {
- Solution obj;
- vector<string> words1 = {"hello", "leetcode"};
- vector<string> words2 = {"word", "world", "row"};
- vector<string> words3 = {"apple", "app"};
- cout << obj.isAlienSorted(words1, "hlabcdefgijkmnopqrstuvwxyz")
- << endl; // expect: 1
- cout << obj.isAlienSorted(words2, "worldabcefghijkmnpqstuvxyz")
- << endl; // expect: 0
- cout << obj.isAlienSorted(words3, "abcdefghijklmnopqrstuvwxyz")
- << endl; // expect: 0
-}
diff --git a/other/vertical_order_bst.cpp b/other/vertical_order_bst.cpp
deleted file mode 100644
index a429d4d..0000000
--- a/other/vertical_order_bst.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vvd verticalTraversal(TreeNode *root) {
- map<int, map<int, multiset<int>>> mmm;
- queue<pair<TreeNode *, pair<int, int>>> qpp;
- qpp.push({root, {0, 0}});
- while (!qpp.empty()) {
- auto p = qpp.front();
- qpp.pop();
- TreeNode *node = p.first;
- int x = p.second.first, y = p.second.second;
- mmm[x][y].insert(node->val);
- if (node->left)
- qpp.push({node->left, {x - 1, y + 1}});
- if (node->right)
- qpp.push({node->right, {x + 1, y + 1}});
- }
- vvd ans;
- for (auto q : mmm) {
- vector<int> col;
- for (auto p : q.second)
- col.insert(col.end(), p.second.begin(), p.second.end());
- ans.push_back(col);
- }
- return ans;
- }
-};
diff --git a/other/ways_to_paint_nx3_grid.cpp b/other/ways_to_paint_nx3_grid.cpp
deleted file mode 100644
index b661af8..0000000
--- a/other/ways_to_paint_nx3_grid.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int numOfWays(int n) {
- long a = 6, b = 6, c, d, mod = 1e9 + 7;
- for (int i = 1; i < n; ++i) {
- c = a * 3 + b * 2;
- d = a * 2 + b * 2;
- a = c % mod;
- b = d % mod;
- }
- return (a + b) % mod;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.numOfWays(1);
-}
diff --git a/other/where_will_ball_fall.cpp b/other/where_will_ball_fall.cpp
deleted file mode 100644
index 4195778..0000000
--- a/other/where_will_ball_fall.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<int> findBall(vvd & grid) {
- int m = grid.size(), n = grid[0].size();
- vvd ugrid(m * 3, vector<int>(n * 3));
- for (auto i = 0; i < m; i++)
- for (auto j = 0; j < n; j++) {
- ugrid[i * 3 + 1][j * 3 + 1] = 1;
- ugrid[i * 3][j * 3] = ugrid[i * 3 + 2][j * 3 + 2] = grid[i][j] == 1;
- ugrid[i * 3][j * 3 + 2] = ugrid[i * 3 + 2][j * 3] = grid[i][j] != 1;
- }
- vector<int> ans;
- for (auto i = 0; i < n; ++i)
- ans.push_back(drop(i * 3 + 1, ugrid, m * 3, n * 3));
- return ans;
- }
-
-private:
- vector<pair<int, int>> dir{{1, 0}, {0, -1}, {0, 1}};
- int drop(int pos, vvd & ugrid, int m, int n) {
- queue<pair<int, int>> qp;
- qp.push({0, pos});
- while (!qp.empty()) {
- auto [i, j] = qp.front();
- qp.pop();
- if (i == m - 1)
- return j / 3;
- ugrid[i][j] = 1;
- for (auto [di, dj] : dir)
- if (j + dj >= 0 && j + dj < n && !ugrid[i + di][j + dj]) {
- qp.push({i + di, j + dj});
- break;
- }
- }
- return -1;
- }
-};
-
-int main() {
- Solution obj;
- vvd 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}};
- for (auto i : obj.findBall(grid))
- cout << i << ' ';
-}
diff --git a/other/where_will_ball_fall.rs b/other/where_will_ball_fall.rs
deleted file mode 100644
index 6a1bb58..0000000
--- a/other/where_will_ball_fall.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn find_ball(grid: Vec<Vec<i32>>) -> Vec<i32> {
- let n = grid[0].len();
- if n == 1 {
- return vec![-1];
- }
- (0..n).map(|i| {Self::exits(&grid, 0, i)}).collect()
- }
- fn exits(grid: &Vec<Vec<i32>>, row: usize, i: usize) -> i32 {
- let (m, n) = (grid.len(), grid[0].len());
- if i == usize::MAX ||i >= n {
- return -1;
- }
- let i2 = i + grid[row][i] as usize;
- if i2 >= n || i2 == usize::MAX {
- return -1;
- }
- let (dir1, dir2) = (grid[row][i], grid[row][i2]);
- if dir1 != dir2 {
- return -1;
- }
- if row == m - 1 {
- return i2 as i32;
- }
- Self::exits(&grid, row + 1, i2)
- }
-}
-
-fn main() {
- let grid = vec![vec![1,1,1,-1,-1],
- vec![1,1,1,-1,-1],
- vec![-1,-1,-1,1,1],
- vec![1,1,1,1,-1],
- vec![-1,-1,-1,-1,-1]];
- print!("{:?}", Solution::find_ball(grid));
-}
diff --git a/other/wiggle_subsequence.cpp b/other/wiggle_subsequence.cpp
deleted file mode 100644
index 22376d4..0000000
--- a/other/wiggle_subsequence.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int wiggleMaxLength(vector<int> &nums) {
- int ans = 1, i = 1;
- while (i < nums.size() && nums[i] == nums[i - 1])
- i++;
- if (i == nums.size())
- return 1;
- bool upper = nums[i - 1] > nums[i];
- for (; i < nums.size(); i++)
- if ((upper && nums[i] < nums[i - 1]) || !upper && nums[i] > nums[i - 1])
- upper = !upper, ans++;
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- vector<int> nums = {1, 17, 5, 10, 13, 15, 10, 5, 16, 8};
- cout << obj.wiggleMaxLength(nums);
-}
diff --git a/other/word_break.cpp b/other/word_break.cpp
deleted file mode 100644
index aa580c9..0000000
--- a/other/word_break.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-// 139. Word Break
-#include "leetcode.h"
-
-/*
- * given a string 's' and a dictionary of strings 'word_dict', return 'true' if
- * 's' can be segmented into a space-separated sequence of one or more
- * dictionary words. note that the same word in the dictionary may be reused
- * multiple times in the segmentation.
- */
-
-class Solution {
-public:
- bool wordBreak(string s, unordered_set<string> &word_dict) {
- if (!word_dict.size())
- return false;
- vector<bool> dp(s.size() + 1, false);
- dp[0] = true;
- for (int i = 1; i <= s.size(); i++)
- for (int j = i - 1; j >= 0; j--)
- if (dp[j]) {
- string word = s.substr(j, i - j);
- if (word_dict.find(word) != word_dict.end()) {
- dp[i] = true;
- break;
- }
- }
- return dp[s.size()];
- }
-};
-
-int main() {
- Solution obj;
- unordered_set<string> wd1 = {"leet", "code"}, wd2 = {"apple", "pen"},
- wd3 = {"cats", "dog", "sand", "and", "cat"};
- printf("%d\n", obj.wordBreak("leetcode", wd1)); // expect: 1
- printf("%d\n", obj.wordBreak("applepenapple", wd2)); // expect: 1
- printf("%d\n", obj.wordBreak("catsandog", wd3)); // expect: 0
-}
diff --git a/other/word_ladder.cpp b/other/word_ladder.cpp
deleted file mode 100644
index dfe6b00..0000000
--- a/other/word_ladder.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- int ladderLength(string beginWord, string endWord, vector<string> &wordList) {
- unordered_set<string> dict(wordList.begin(), wordList.end());
- queue<string> q;
- q.push(beginWord);
- int ladder = 1;
- while (!q.empty()) {
- int n = q.size(); //
- for (int i = 0; i < n; i++) {
- string word = q.front();
- q.pop();
- if (word == endWord)
- return ladder;
- dict.erase(word);
- for (int j = 0; j < word.size(); j++) {
- char c = word[j];
- for (int k = 0; k < 26; k++) {
- word[j] = 'a' + k;
- if (dict.find(word) != dict.end())
- q.push(word);
- }
- word[j] = c;
- }
- }
- ladder++;
- }
- return 0;
- }
-};
-
-int main() {
- Solution obj;
- string beginWord = "hit", endWord = "cog";
- vector<string> wordList = {"hot", "dot", "dog", "lot", "log", "cog"};
- cout << obj.ladderLength(beginWord, endWord, wordList);
-}
diff --git a/other/word_ladder2.cpp b/other/word_ladder2.cpp
deleted file mode 100644
index 12cff05..0000000
--- a/other/word_ladder2.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- vector<vector<string>> findLadders(string beginWord, string endWord,
- vector<string> &wordList) {
- unordered_map<string, int> um;
- vector<vector<string>> ans;
- for (const auto w : wordList)
- um.insert({w, INT_MAX});
- um[beginWord] = 0;
- queue<pair<string, vector<string>>> qpv;
- qpv.push({beginWord, {beginWord}});
- while (!qpv.empty()) {
- auto n = qpv.front();
- qpv.pop();
- string w = n.first;
- auto v = n.second;
- if (w == endWord)
- ans.push_back(v);
- continue;
- for (int i = 0; i < w.size(); i++) {
- string t = w;
- for (char c = 'a'; c <= 'z'; c++) {
- t[i] = c;
- if (t == w)
- continue;
- if (um.find(t) == um.end())
- continue;
- if (um[t] < v.size())
- continue;
- um[t] = v.size();
- v.push_back(t);
- qpv.push({t, v});
- v.pop_back();
- }
- }
- }
- return ans;
- }
-};
-
-int main() {
- Solution obj;
- string beginWord = "hit", endWord = "cog";
- vector<string> wordList = {"hot", "dot", "dog", "lot", "log", "cog"};
-}
diff --git a/other/word_pattern.cpp b/other/word_pattern.cpp
deleted file mode 100644
index 26ccbfd..0000000
--- a/other/word_pattern.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool wordPattern(string pattern, string s) {
- vector<int> patMap(26, 0);
- unordered_map<string, int> strMap;
- int i = 0, n = pattern.size();
- istringstream ss(s);
- string token;
- for (string token; ss >> token; ++i) {
- if (i == n || patMap[pattern[i] - 'a'] != strMap[token])
- return false;
- patMap[pattern[i] - 'a'] = strMap[token] = i + 1;
- }
- return i == n;
- }
-};
-
-int main() {
- Solution obj;
- testBool(obj.wordPattern("abba", "dog cat cat dog")); // true
- testBool(obj.wordPattern("abba", "dog cat cat fish")); // false
- testBool(obj.wordPattern("aaaa", "dog cat cat dog")); // false
-}
diff --git a/other/word_pattern.rs b/other/word_pattern.rs
deleted file mode 100644
index 6161b40..0000000
--- a/other/word_pattern.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-struct Solution;
-
-impl Solution {
- pub fn word_pattern(pattern: String, s: String) -> bool {
- use std::collections::{HashMap, HashSet};
- if pattern.len() != s.matches(' ').count() + 1 {
- return false;
- }
- let (mut hm, mut word_set) = (HashMap::new(), HashSet::new());
- for (word, c) in s.split_ascii_whitespace().zip(pattern.chars()) {
- if let Some(w) = hm.insert(c, word) {
- if w != word {
- return false;
- }
- } else if !word_set.insert(word) {
- return false;
- }
- }
- true
- }
-}
-
-fn main() {
- let (pattern, s) = (String::from("abba"), String::from("dog cat cat dog"));
- print!("{}", Solution::word_pattern(pattern, s));
-}
diff --git a/other/word_search.cpp b/other/word_search.cpp
deleted file mode 100644
index bbd072f..0000000
--- a/other/word_search.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-#include "leetcode.h"
-
-class Solution {
-public:
- bool exist(vvd(char) & board, string word) {
- int dirs[5] = {0, -1, 0, 1, 0};
- map<char, int> cnt;
- int m = board.size(), n = board[0].size(), l = word.size();
-
- for (char c : word)
- cnt[c] += 1;
-
- if (cnt[word[0]] > cnt[word[l - 1]])
- reverse(word.begin(), word.end());
-
- function<bool(int, int, int)> dfs;
- dfs = [&](int i, int j, int s) -> bool {
- if (s == l)
- return true;
-
- if (i < 0 or i >= m or j < 0 or j >= n)
- return false;
- if (board[i][j] != word[s])
- return false;
-
- board[i][j] = '#';
- for (int d = 0; d < 4; ++d)
- if (dfs(i + dirs[d], j + dirs[d + 1], s + 1))
- return true;
- board[i][j] = word[s];
-
- return false;
- };
-
- for (int i = 0; i < m; ++i)
- for (int j = 0; j < n; ++j)
- if (dfs(i, j, 0))
- return true;
-
- return false;
- }
-};
-
-int main() {
- Solution obj;
- vvd(char) board = {
- {'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}};
- string word = "ABCCED";
- if (obj.exist(board, word))
- cout << "true";
- else
- cout << "false";
-}
diff --git a/other/word_search2.cpp b/other/word_search2.cpp
deleted file mode 100644
index 8163966..0000000
--- a/other/word_search2.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-#include "leetcode.h"
-
-struct Trie {
- bool isEnd;
- string word;
- Trie *child[26];
- Trie() {
- isEnd = false;
- word = "";
- for (int i = 0; i < 26; i++)
- child[i] = NULL;
- }
-};
-
-class Solution {
-public:
- vector<string> ans;
- vector<string> findWords(vvd(char) & board, vector<string> &words) {
- int n = board.size(), m = board[0].size();
- for (auto w : words)
- insert(w);
- for (int i = 0; i < n; i++)
- for (int j = 0; j < m; j++)
- dfs(board, i, j, n, m, root);
- return ans;
- }
-
-private:
- vector<int> dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
- Trie *root = new Trie();
- void insert(string &s) {
- int n = s.size();
- Trie *curr = root;
- for (int i = 0; i < n; i++) {
- int idx = s[i] - 'a';
- if (curr->child[idx] == NULL)
- curr->child[idx] = new Trie();
- curr = curr->child[idx];
- }
- curr->isEnd = true;
- curr->word = s;
- }
- void dfs(vvd(char) & board, int i, int j, int n, int m, Trie *curr) {
- if (i < 0 || i >= n || j < 0 || j >= m || board[i][j] == '#')
- return;
- int idx = board[i][j] - 'a';
- if (curr->child[idx] == NULL)
- return;
- curr = curr->child[idx];
- if (curr->isEnd) {
- ans.push_back(curr->word);
- curr->isEnd = false;
- }
- char val = board[i][j];
- board[i][j] = '#';
- for (int k = 0; k < 4; k++) {
- int newI = i + dx[k], newJ = j + dy[k];
- dfs(board, newI, newJ, n, m, curr);
- }
- board[i][j] = val;
- }
-};
-
-int main() {
- Solution obj;
- vvd(char) board = {{'a', 'b'}, {'c', 'd'}};
- vector<string> words = {"abcb"};
- for (auto i : obj.findWords(board, words))
- cout << i << endl;
-}
diff --git a/other/word_search2.rs b/other/word_search2.rs
deleted file mode 100644
index 2c61941..0000000
--- a/other/word_search2.rs
+++ /dev/null
@@ -1,59 +0,0 @@
-#[derive(Default)]
-struct Solution;
-
-struct Trie {
- child: [Option<Box<Trie>>; 26],
- is_end: bool
-}
-
-impl Solution {
- pub fn find_words(board: Vec<Vec<char>>, words: Vec<String>) -> Vec<String> {
- let mut trie = Trie::default();
- for w in words {
- let mut node = &mut trie;
- for u in w.bytes() {
- node = node.child[(u - b'a') as usize].get_or_insert(Default::default());
- }
- node.is_end = true;
- }
- let (mut board, mut ans) = (board, Vec::new());
- for i in 0..board.len() {
- for j in 0..board[0].len() {
- Self::backtrack(
- &mut board,
- &mut trie,
- (i, j),
- &mut String::new(),
- &mut ans
- );
- }
- }
- ans
- }
- fn backtrack(board: &mut Vec<Vec<char>>, trie: &mut Trie, pos: (usize, usize), s: &mut String, ans: &mut Vec<String>) {
- let c = board[pos.0][pos.1];
- if let Some(node) = &mut trie.child[(c as u8 - b'a') as usize] {
- s.push(c);
- if node.is_end {
- ans.push(s.clone());
- node.is_end = false;
- }
- board[pos.0][pos.1] = '*';
- for d in [0,1,0,!0,0].windows(2) {
- let i = pos.0.wrapping_add(d[0]);
- let j = pos.1.wrapping_add(d[1]);
- if (0..board.len()).contains(&i) && (0..board[0].len()).contains(&j) && board[i][j] != '*' {
- Self::backtrack(board, node, (i, j), s, ans);
- }
- }
- board[pos.0][pos.1] = c;
- s.pop();
- }
- }
-}
-
-fn main() {
- let board = vec![vec!['a','b'], vec!['c','d']];
- let words = vec!["abcb".to_string()];
- print!("{:?}", Solution::find_words(board, words));
-}
diff --git a/other/word_subsets.cpp b/other/word_subsets.cpp
deleted file mode 100644
index d053375..0000000
--- a/other/word_subsets.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-// 916. Word Subsets
-#include "leetcode.h"
-
-/*
- * you are given two string arrays 'words1' and 'words2'. a string 'b' is a
- * subset of string 'a' if every letter in 'b' occurs in 'a' including
- * multiplicity. a string 'a' from 'words1' is universal if for every string 'b'
- * in 'words2', 'b' is a subset of 'a'. return an array of all the universal
- * strins in 'words1'. you may return the answer in any order.
- */
-
-class Solution {
-public:
- vector<string> wordSubsets(vector<string> &words1, vector<string> &words2) {
- vector<int> cnt(26), tmp(26);
- int i;
- for (string b : words2) {
- tmp = counter(b);
- for (i = 0; i < 26; ++i)
- cnt[i] = max(cnt[i], tmp[i]);
- }
- vector<string> ans;
- for (string a : words1) {
- tmp = counter(a);
- for (i = 0; i < 26; ++i)
- if (tmp[i] < cnt[i])
- break;
- if (i == 26)
- ans.push_back(a);
- }
- return ans;
- }
-
-private:
- vector<int> counter(string &word) {
- vector<int> cnt(26);
- for (char c : word)
- cnt[c - 'a']++;
- return cnt;
- }
-};
-
-int main() {
- Solution obj;
- vector<string> w11 = {"amazon", "apple", "facebook", "google", "leetcode"},
- w21 = {"e", "o"};
- vector<string> w12 = {"amazon", "apple", "facebook", "google", "leetcode"},
- w22 = {"l", "e"};
- vector<string> ws1 = obj.wordSubsets(w11, w21),
- ws2 = obj.wordSubsets(w12, w22);
- for (auto i : ws1)
- cout << i << ' '; // expect: ["facebook","google","leetcode"]
- printf("\n");
- for (auto i : ws2)
- cout << i << ' '; // expect: ["apple","google","leetcode"]
- printf("\n");
-}
diff --git a/other/zigzag_conversion.cpp b/other/zigzag_conversion.cpp
deleted file mode 100644
index f7e6b74..0000000
--- a/other/zigzag_conversion.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-// 6. Zigzag Conversion
-#include "leetcode.h"
-
-/*
- * the string "PAYPALISHIRING" is written in zigzag pattern on a given number
- * of rows like this:
- * P A H N
- * A P L S I I G
- * Y I R
- * and then read line by line: "PAHNAPLSIIGYIR". write function that will take
- * a string and mak this conversion give a number of rows.
- */
-
-class Solution {
-public:
- string convert(string s, int numRows) {
- if (numRows <= 1)
- return s;
- const int len = s.size();
- string *str = new string[numRows];
- int row = 0, step = 1;
- for (int i = 0; i < len; ++i) {
- str[row].push_back(s[i]);
- if (row == 0)
- step = 1;
- else if (row == numRows - 1)
- step = -1;
- row += step;
- }
- s.clear();
- for (int i = 0; i < numRows; ++i)
- s.append(str[i]);
- delete[] str;
- return s;
- }
-};
-
-int main() {
- Solution obj;
- cout << obj.convert("PAYPALISHIRING", 3) << endl; // expect: PAHNAPLSIIGYIR
- cout << obj.convert("PAYPALISHIRING", 4) << endl; // expect: PINALSIGYAHRPI
- cout << obj.convert("A", 1) << endl; // expect: A
-}
diff --git a/painting_grid_three_colours.c b/painting_grid_three_colours.c
new file mode 100644
index 0000000..82c9d53
--- /dev/null
+++ b/painting_grid_three_colours.c
@@ -0,0 +1,78 @@
+// 1931. Painting a Grid With Three Different Colors
+#include "leetcode.h"
+
+/*
+ * you are given two integers 'm' and 'n'. consider an 'm x n' grid where each
+ * cell is initially white. you can paint each cell red, green, or blue. all
+ * cells must be painted. return the number of ways to colour the grid with no
+ * two adjacent cells having the same colour. since the answer can be very
+ * large, return it modulo 10^9+7.
+ */
+
+int colorTheGrid(int m, int n) {
+ const int mod = 1e9 + 7;
+ int max_mask = 1;
+ for (int i = 0; i < m; ++i)
+ max_mask *= 3;
+ int states[48], s = 0;
+ for (int i = 0; i < max_mask; ++i) {
+ int curr = i, prev = -1;
+ bool valid = true;
+ for (int j = 0; j < m; ++j) {
+ int dir = curr % 3;
+ if (dir == prev) {
+ valid = false;
+ break;
+ }
+ prev = dir;
+ curr /= 3;
+ }
+ if (valid)
+ states[s++] = i;
+ }
+ int compat[48][48], compat_size[48];
+ for (int i = 0; i < s; ++i)
+ compat_size[i] = 0;
+ for (int i = 0; i < s; ++i)
+ for (int j = 0; j < s; ++j) {
+ int x = states[i], y = states[j];
+ bool valid = true;
+ for (int k = 0; k < m; ++k) {
+ if (x % 3 == y % 3) {
+ valid = false;
+ break;
+ }
+ x /= 3;
+ y /= 3;
+ }
+ if (valid)
+ compat[i][compat_size[i]++] = j;
+ }
+ int dp[48], copy[48];
+ for (int i = 0; i < s; ++i)
+ dp[i] = 1;
+ for (int i = 0; i < n - 1; ++i) {
+ for (int j = 0; j < s; ++j)
+ copy[j] = 0;
+ for (int j = 0; j < s; ++j) {
+ int dir = dp[j];
+ if (dir)
+ for (int k = 0; k < compat_size[j]; ++k) {
+ int new = compat[j][k];
+ copy[new] = (copy[new] + dir) % mod;
+ }
+ }
+ for (int j = 0; j < s; ++j)
+ dp[j] = copy[j];
+ }
+ long long ans = 0;
+ for (int i = 0; i < s; ++i)
+ ans = (ans + dp[i]) % mod;
+ return (int)ans;
+}
+
+int main() {
+ printf("%d\n", colorTheGrid(1, 1)); // expect: 3
+ printf("%d\n", colorTheGrid(1, 2)); // expect: 6
+ printf("%d\n", colorTheGrid(5, 5)); // expect: 580986
+}
diff --git a/painting_grid_three_colours.py b/painting_grid_three_colours.py
new file mode 100644
index 0000000..d33b1d8
--- /dev/null
+++ b/painting_grid_three_colours.py
@@ -0,0 +1,42 @@
+# 1931. Painting a Grid With Three Different Colors
+from collections import Counter
+
+"""
+you are given two integers 'm' and 'n'. consider an 'm x n' grid where each
+cell is initially white. you can paint each cell red, green, or blue. all
+cells must be painted. return the number of ways to colour the grid with no
+two adjacent cells having the same colour. since the answer can be very
+large, return it modulo 10^9+7.
+"""
+
+
+class Solution(object):
+ def colorTheGrid(self, m, n):
+ """
+ :type m: int
+ :type n: int
+ :rtype: int
+ """
+ dp = {(1 << (2 * m)) - 1: 1}
+ mod = 10**9 + 7
+ for i in range(m * n - 1, -1, -1):
+ copy = Counter()
+ x, y = divmod(i, m)
+ for j in dp:
+ valid = {0, 1, 2}
+ if y < m - 1:
+ valid.discard(j >> (2 * m - 2))
+ if x < n - 1:
+ valid.discard(j & 3)
+ for k in valid:
+ new = (j >> 2) + (k << (2 * m - 2))
+ copy[new] = (copy[new] + dp[j]) % mod
+ dp = copy
+ return sum(dp.values()) % mod
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.colorTheGrid(m=1, n=1))
+ print(obj.colorTheGrid(m=1, n=2))
+ print(obj.colorTheGrid(m=5, n=5))
diff --git a/partition_arr_max_diff_k.c b/partition_arr_max_diff_k.c
new file mode 100644
index 0000000..4a1e3aa
--- /dev/null
+++ b/partition_arr_max_diff_k.c
@@ -0,0 +1,32 @@
+// 2294. Partition Array Such That Maximum Difference Is K
+#include "leetcode.h"
+
+/*
+ * you are given an integer array 'nums' and an integer 'k'. you may partition
+ * 'nums' into one or more subsequences such that each element in 'nums' appears
+ * in exactly one of the subsequences. return the minimum number of subsequences
+ * needed such that the difference between the maximum and minimum values in
+ * each subsequence is at most 'k'. a subsequence is a sequence that can be
+ * derived from another sequence by deleting some or no elements without
+ * changing the order of the remaining elements.
+ */
+
+int cmp(const void *a, const void *b) { return (*(int *)a - *(int *)b); }
+
+int partitionArray(int *nums, int numsSize, int k) {
+ qsort(nums, numsSize, sizeof(int), cmp);
+ int ans = 1, j = 0;
+ for (int i = 1; i < numsSize; i++)
+ if (nums[i] - nums[j] > k) {
+ ans++;
+ j = i;
+ }
+ return ans;
+}
+
+int main() {
+ int n1[] = {3, 6, 1, 2, 5}, n2[] = {1, 2, 3}, n3[] = {2, 2, 4, 5};
+ printf("%d\n", partitionArray(n1, ARRAY_SIZE(n1), 2)); // expect: 2
+ printf("%d\n", partitionArray(n2, ARRAY_SIZE(n2), 1)); // expect: 2
+ printf("%d\n", partitionArray(n3, ARRAY_SIZE(n3), 0)); // expect: 3
+}
diff --git a/partition_arr_max_diff_k.py b/partition_arr_max_diff_k.py
new file mode 100644
index 0000000..555cdf9
--- /dev/null
+++ b/partition_arr_max_diff_k.py
@@ -0,0 +1,34 @@
+# 2294. Partition Array Such That Maximum Difference Is K
+
+"""
+you are given an integer array 'nums' and an integer 'k'. you may partition
+'nums' into one or more subsequences such that each element in 'nums' appears
+in exactly one of the subsequences. return the minimum number of subsequences
+needed such that the difference between the maximum and minimum values in
+each subsequence is at most 'k'. a subsequence is a sequence that can be
+derived from another sequence by deleting some or no elements without
+changing the order of the remaining elements.
+"""
+
+
+class Solution(object):
+ def partitionArray(self, nums, k):
+ """
+ :type nums: List[int]
+ :type k: int
+ :rtype: int
+ """
+ nums.sort()
+ ans, j = 1, 0
+ for i in range(len(nums)):
+ if nums[i] - nums[j] > k:
+ ans += 1
+ j = i
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.partitionArray(nums=[3, 6, 1, 2, 5], k=2))
+ print(obj.partitionArray(nums=[1, 2, 3], k=1))
+ print(obj.partitionArray(nums=[2, 2, 4, 5], k=0))
diff --git a/push_dominoes.c b/push_dominoes.c
new file mode 100644
index 0000000..9dbaa65
--- /dev/null
+++ b/push_dominoes.c
@@ -0,0 +1,47 @@
+// 838. Push Dominoes
+#include "leetcode.h"
+
+/*
+ * there are 'n' dominoes in a line, and we place each domino vertically
+ * upright. in the beginning, we simultaneously push some of the dominoes either
+ * to the left or to the right. after each second, each domino that is falling
+ * to the left pushes the adjacent domino on the left. similarly, the dominoes
+ * falling to the right push their adjacent dominoes standing on the right. when
+ * a vertical domino has dominoes falling on it from both sides, it stays still
+ * due to the balance of the forces. for the purpose of this question, we will
+ * consider that a falling domino expends no additional force to a falling or
+ * already fallen domino.
+ */
+
+char *pushDominoes(char *dominoes) {
+ int n = strlen(dominoes), right = -1;
+ for (int i = 0; i < n; ++i) {
+ if (dominoes[i] == 'L') {
+ if (right == -1) {
+ for (int j = i - 1; j >= 0 && dominoes[j] == '.'; --j)
+ dominoes[j] = 'L';
+ } else {
+ for (int j = right + 1, k = i - 1; j < k; ++j, --k) {
+ dominoes[j] = 'R';
+ dominoes[k] = 'L';
+ }
+ right = -1;
+ }
+ } else if (dominoes[i] == 'R') {
+ if (right != -1)
+ for (int j = right + 1; j < i; ++j)
+ dominoes[j] = 'R';
+ right = i;
+ }
+ }
+ if (right != -1)
+ for (int i = right + 1; i < n; ++i)
+ dominoes[i] = 'R';
+ return dominoes;
+}
+
+int main() {
+ char *d1 = "RR.L", *d2 = ".L.R...LR..L..";
+ printf("%s\n", pushDominoes(d1)); // expect: RR.L
+ printf("%s\n", pushDominoes(d2)); // expect: .L.R...LR..L..
+}
diff --git a/push_dominoes.py b/push_dominoes.py
new file mode 100644
index 0000000..a33dd56
--- /dev/null
+++ b/push_dominoes.py
@@ -0,0 +1,32 @@
+# 838. Push Dominoes
+
+"""
+there are 'n' dominoes in a line, and we place each domino vertically
+upright. in the beginning, we simultaneously push some of the dominoes either
+to the left or to the right. after each second, each domino that is falling
+to the left pushes the adjacent domino on the left. similarly, the dominoes
+falling to the right push their adjacent dominoes standing on the right. when
+a vertical domino has dominoes falling on it from both sides, it stays still
+due to the balance of the forces. for the purpose of this question, we will
+consider that a falling domino expends no additional force to a falling or
+already fallen domino.
+"""
+
+
+class Solution(object):
+ def pushDominoes(self, dominoes):
+ """
+ :type dominoes: str
+ :rtype: str
+ """
+ while "R." in dominoes or ".L" in dominoes:
+ dominoes = (
+ dominoes.replace("R.L", "xxx").replace(".L", "LL").replace("R.", "RR")
+ )
+ return dominoes.replace("xxx", "R.L")
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.pushDominoes(dominoes="RR.L"))
+ print(obj.pushDominoes(dominoes=".L.R...LR..L.."))
diff --git a/rabbits_in_forest.c b/rabbits_in_forest.c
new file mode 100644
index 0000000..caf618f
--- /dev/null
+++ b/rabbits_in_forest.c
@@ -0,0 +1,36 @@
+// 781. Rabbits in Forest
+#include "leetcode.h"
+
+/*
+ * there is a forest with an unknown number of rabbits. we asked 'n' rabbits
+ * "how many rabbithave the same colour as you?" and collected the answers in an
+ * integer array 'answers' where 'answers[i]' is the answer of the i'th rabbit.
+ * given the array 'answers', return the minimum number of rabbits that could be
+ * in the forest.
+ */
+
+int numRabbits(int *answers, int answersSize) {
+ int ans = 0;
+ for (int i = 0; i < answersSize - 1; i++) {
+ int freq = 0;
+ if (answers[i] != -1 && answers[i])
+ for (int j = i + 1; j < answersSize; j++) {
+ if (answers[i] == answers[j]) {
+ answers[j] = -1;
+ freq++;
+ }
+ if (freq == answers[i])
+ break;
+ }
+ }
+ for (int i = 0; i < answersSize; i++)
+ if (answers[i] != -1)
+ ans += (answers[i] + 1);
+ return ans;
+}
+
+int main() {
+ int a1[] = {1, 1, 2}, a2[] = {10, 10, 10};
+ printf("%d\n", numRabbits(a1, ARRAY_SIZE(a1))); // expect: 5
+ printf("%d\n", numRabbits(a2, ARRAY_SIZE(a2))); // expect: 11
+}
diff --git a/rabbits_in_forest.py b/rabbits_in_forest.py
new file mode 100644
index 0000000..7d91e99
--- /dev/null
+++ b/rabbits_in_forest.py
@@ -0,0 +1,30 @@
+# 781. Rabbits in Forest
+from collections import Counter
+
+"""
+there is a forest with an unknown number of rabbits. we asked 'n' rabbits
+"how many rabbithave the same colour as you?" and collected the answers in an
+integer array 'answers' where 'answers[i]' is the answer of the i'th rabbit.
+given the array 'answers', return the minimum number of rabbits that could be
+in the forest.
+"""
+
+
+class Solution(object):
+ def numRabbits(self, answers):
+ """
+ :type answers: List[int]
+ :rtype: int
+ """
+ ans, freq = 0, Counter()
+ for i in answers:
+ if freq[i] % (i + 1) == 0:
+ ans += i + 1
+ freq[i] += 1
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.numRabbits(answers=[1, 1, 2]))
+ print(obj.numRabbits(answers=[10, 10, 10]))
diff --git a/random_pick_weight.c b/random_pick_weight.c
new file mode 100644
index 0000000..c37bb40
--- /dev/null
+++ b/random_pick_weight.c
@@ -0,0 +1,57 @@
+// 528. Random Pick with Weight
+#include "leetcode.h"
+
+/*
+ * you are given a 0-indexed array of positive integers 'w' where 'w[i]'
+ * describes the weight of the i'th index. you need to implement the function
+ * 'pickIndex()' which randomly picks an index in the range '[0, w.len - 1]' and
+ * returns it. the probability of picking an index 'i' is 'w[i] / sum(w)'.
+ */
+
+typedef struct {
+ int size;
+ int *data;
+} Solution;
+
+Solution *solutionCreate(int *w, int wSize) {
+ Solution *obj = (Solution *)malloc(sizeof(Solution));
+ obj->data = (int *)malloc(wSize * sizeof(int));
+ obj->size = wSize;
+ obj->data[0] = w[0];
+ for (int i = 0; i < wSize; i++)
+ obj->data[i] = w[i] + obj->data[i - 1];
+ return obj;
+}
+
+int solutionPickIndex(Solution *obj) {
+ float rand_num = (float)rand() / RAND_MAX;
+ int target = rand_num * obj->data[obj->size - 1];
+ int left = 0, right = obj->size - 1;
+ while (left < right) {
+ int mid = left + (right - left) / 2;
+ if (obj->data[mid] > target)
+ right = mid;
+ else
+ left = mid + 1;
+ }
+ return left;
+}
+
+void solutionFree(Solution *obj) {
+ free(obj->data);
+ free(obj);
+}
+
+int main() {
+ int w1[] = {1}, w2[] = {1, 3};
+ Solution *obj1 = solutionCreate(w1, ARRAY_SIZE(w1));
+ Solution *obj2 = solutionCreate(w2, ARRAY_SIZE(w2));
+ printf("%d\n", solutionPickIndex(obj1)); // expect: 0
+ printf("%d\n", solutionPickIndex(obj2)); // expect: 1
+ printf("%d\n", solutionPickIndex(obj2)); // expect: 1
+ printf("%d\n", solutionPickIndex(obj2)); // expect: 1
+ printf("%d\n", solutionPickIndex(obj2)); // expect: 1
+ printf("%d\n", solutionPickIndex(obj2)); // expect: 0
+ solutionFree(obj1);
+ solutionFree(obj2);
+}
diff --git a/random_pick_weight.py b/random_pick_weight.py
new file mode 100644
index 0000000..3eda7fd
--- /dev/null
+++ b/random_pick_weight.py
@@ -0,0 +1,36 @@
+# 528. Random Pick with Weight
+from itertools import accumulate
+from bisect import bisect_left
+from random import randint
+
+"""
+you are given a 0-indexed array of positive integers 'w' where 'w[i]'
+describes the weight of the i'th index. you need to implement the function
+'pickIndex()' which randomly picks an index in the range '[0, w.len - 1]' and
+returns it. the probability of picking an index 'i' is 'w[i] / sum(w)'.
+"""
+
+
+class Solution(object):
+ def __init__(self, w):
+ """
+ :type w: List[int]
+ """
+ self.w = list(accumulate(w))
+
+ def pickIndex(self):
+ """
+ :rtype: int
+ """
+ return bisect_left(self.w, randint(1, self.w[-1]))
+
+
+if __name__ == "__main__":
+ obj1 = Solution([1])
+ obj2 = Solution([1, 3])
+ print(obj1.pickIndex())
+ print(obj1.pickIndex())
+ print(obj1.pickIndex())
+ print(obj1.pickIndex())
+ print(obj1.pickIndex())
+ print(obj1.pickIndex())
diff --git a/res_str_adj_remove.c b/res_str_adj_remove.c
new file mode 100644
index 0000000..c2792f0
--- /dev/null
+++ b/res_str_adj_remove.c
@@ -0,0 +1,42 @@
+// 3561. Resulting String After Adjacent Removals
+#include "leetcode.h"
+
+/*
+ * you are given a string 's' consisting of lowercase english letters. you must
+ * repeatedly perform the following operation while the string 's' has at least
+ * two consecutive characters: remove the leftmost pair of adjacent characters
+ * in the string that are consecutive in the alphabet, in either order, and
+ * shift the remaining characters to the left to fill the gap. return the
+ * resulting string after no more operations can be performed. note: consider
+ * the alphabet as circular, thus 'a' and 'z' are consecutive.
+ */
+
+bool helper(char a, char b) {
+ int c = fabs(a - b);
+ return c == 1 || c == 25;
+}
+
+char *resultingString(char *s) {
+ int n = strlen(s), top = -1;
+ char *ans = (char *)malloc((n + 1) * sizeof(char));
+ for (int i = 0; i < n; i++) {
+ if (top >= 0 && helper(ans[top], s[i]))
+ top--;
+ else
+ ans[++top] = s[i];
+ }
+ ans[top + 1] = '\0';
+ return ans;
+}
+
+int main() {
+ char *s1 = "abc", *rs1 = resultingString(s1);
+ char *s2 = "adcb", *rs2 = resultingString(s2);
+ char *s3 = "zadb", *rs3 = resultingString(s3);
+ printf("%s\n", rs1); // expect: c
+ printf("%s\n", rs2); // expect: null
+ printf("%s\n", rs3); // expect: db
+ free(rs1);
+ free(rs2);
+ free(rs3);
+}
diff --git a/res_str_adj_remove.py b/res_str_adj_remove.py
new file mode 100644
index 0000000..2949e18
--- /dev/null
+++ b/res_str_adj_remove.py
@@ -0,0 +1,38 @@
+# 3561. Resulting String After Adjacent Removals
+
+"""
+you are given a string 's' consisting of lowercase english letters. you must
+repeatedly perform the following operation while the string 's' has at least
+two consecutive characters: remove the leftmost pair of adjacent characters
+in the string that are consecutive in the alphabet, in either order, and
+shift the remaining characters to the left to fill the gap. return the
+resulting string after no more operations can be performed. note: consider
+the alphabet as circular, thus 'a' and 'z' are consecutive.
+"""
+
+
+class Solution(object):
+ def resultingString(self, s):
+ """
+ :type s: str
+ :rtype: str
+ """
+ ans = []
+
+ def helper(a):
+ c = abs(ord(ans[-1]) - ord(a))
+ return c == 1 or c == 25
+
+ for i in s:
+ if ans and helper(i):
+ ans.pop()
+ else:
+ ans.append(i)
+ return "".join(ans)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.resultingString(s="abc"))
+ print(obj.resultingString(s="adcb"))
+ print(obj.resultingString(s="zadb"))
diff --git a/self_dividing_numbers.c b/self_dividing_numbers.c
new file mode 100644
index 0000000..d0d19b6
--- /dev/null
+++ b/self_dividing_numbers.c
@@ -0,0 +1,53 @@
+// 728. Self Dividing Numbers
+#include "leetcode.h"
+
+/*
+ * a self-dividing number is a number that is divisible by every digit it
+ * contains. for example, 128 is a self-dividing number because 128 % 1 == 0,
+ * 128 % 2 == 0, and 128 % 8 == 0. a self-dividing number is not allowed to
+ * contain the digit zero. given two integers 'left' and 'right', return a list
+ * of all the self-dividing numbers in the range '[left, right]' (both
+ * inclusive).
+ */
+
+int *selfDividingNumbers(int left, int right, int *returnSize) {
+ int tracker, curr, digit;
+ bool valid;
+ int *ans = (int *)malloc((right - left + 1) * sizeof(int));
+ *returnSize = 0;
+ for (int i = left; i <= right; i++) {
+ curr = i;
+ valid = true;
+ tracker = 0;
+ while (curr > 0) {
+ if (i < 10)
+ break;
+ digit = curr % 10;
+ curr /= 10;
+ if (!digit)
+ valid = false;
+ else if (digit > 1 && !(tracker & (1 << digit))) {
+ valid = !(i % digit);
+ tracker |= (1 << digit);
+ }
+ if (!valid)
+ break;
+ }
+ if (valid)
+ ans[(*returnSize)++] = i;
+ }
+ return ans;
+}
+
+int main() {
+ int rs1, *sdn1 = selfDividingNumbers(1, 22, &rs1);
+ int rs2, *sdn2 = selfDividingNumbers(47, 85, &rs2);
+ for (int i = 0; i < rs1; i++)
+ printf("%d ", sdn1[i]); // expect: [1,2,3,4,5,6,7,8,9,11,12,15,22]
+ printf("\n");
+ for (int i = 0; i < rs1; i++)
+ printf("%d ", sdn2[i]); // expect: [48,55,66,77]
+ printf("\n");
+ free(sdn1);
+ free(sdn2);
+}
diff --git a/self_dividing_numbers.py b/self_dividing_numbers.py
new file mode 100644
index 0000000..66d8735
--- /dev/null
+++ b/self_dividing_numbers.py
@@ -0,0 +1,30 @@
+# 728. Self Dividing Numbers
+
+"""
+a self-dividing number is a number that is divisible by every digit it
+contains. for example, 128 is a self-dividing number because 128 % 1 == 0,
+128 % 2 == 0, and 128 % 8 == 0. a self-dividing number is not allowed to
+contain the digit zero. given two integers 'left' and 'right', return a list
+of all the self-dividing numbers in the range '[left, right]' (both
+inclusive).
+"""
+
+
+class Solution(object):
+ def selfDividingNumbers(self, left, right):
+ """
+ :type left: int
+ :type right: int
+ :rtype: List[int]
+ """
+ return [
+ i
+ for i in range(left, right + 1)
+ if all((j and (i % j == 0) for j in map(int, str(i))))
+ ]
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.selfDividingNumbers(left=1, right=22))
+ print(obj.selfDividingNumbers(left=47, right=85))
diff --git a/set_matrix_zeroes.c b/set_matrix_zeroes.c
new file mode 100644
index 0000000..be0e332
--- /dev/null
+++ b/set_matrix_zeroes.c
@@ -0,0 +1,44 @@
+// 73. Set Matrix Zeroes
+#include "leetcode.h"
+
+/*
+ * given an 'm x n' integer 'matrix', if an element is '0', set its entire row
+ * and columns to '0's. you must do it in place
+ */
+
+void setZeroes(int **matrix, int matrixSize, int *matrixColSize) {
+ bool *r = (bool *)calloc(matrixSize, sizeof(bool));
+ bool *c = (bool *)calloc(*matrixColSize, sizeof(bool));
+ for (int i = 0; i < matrixSize; ++i)
+ for (int j = 0; j < *matrixColSize; ++j)
+ if (!matrix[i][j]) {
+ r[i] = true;
+ r[j] = true;
+ }
+ for (int i = 0; i < matrixSize; ++i)
+ for (int j = 0; j < *matrixColSize; ++j)
+ if (r[i] || c[j])
+ matrix[i][j] = 0;
+}
+
+int main() {
+ int m1i[3][3] = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}},
+ m2i[3][4] = {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}};
+ struct two_d_arr m1, m2;
+ two_d_arr_init(&m1, ARRAY_SIZE(m1i), ARRAY_SIZE(m1i[0]), m1i);
+ two_d_arr_init(&m2, ARRAY_SIZE(m2i), ARRAY_SIZE(m2i[0]), m2i);
+ setZeroes(m1.arr, m1.row_size, m1.col_size);
+ setZeroes(m2.arr, m2.row_size, m2.col_size);
+ for (int i = 0; i < m1.row_size; i++) {
+ for (int j = 0; j < m1.col_size[i]; j++)
+ printf("%d ", m1i[i][j]); // expect: [[1,0,1],[0,0,0],[1,0,1]]
+ printf("\n");
+ }
+ for (int i = 0; i < m2.row_size; i++) {
+ for (int j = 0; j < m2.col_size[i]; j++)
+ printf("%d ", m2i[i][j]); // expect: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
+ printf("\n");
+ }
+ two_d_arr_free(&m1);
+ two_d_arr_free(&m2);
+}
diff --git a/set_matrix_zeroes.py b/set_matrix_zeroes.py
new file mode 100644
index 0000000..ce47131
--- /dev/null
+++ b/set_matrix_zeroes.py
@@ -0,0 +1,34 @@
+# 73. Set Matrix Zeroes
+
+"""
+given an 'm x n' integer 'matrix', if an element is '0', set its entire row
+and columns to '0's. you must do it in place
+"""
+
+
+class Solution(object):
+ def setZeroes(self, matrix):
+ """
+ :type matrix: List[List[int]]
+ :rtype: None Do not return anything, modify matrix in-place instead.
+ """
+ r, c = 0, 0
+ for i in range(len(matrix)):
+ for j in range(len(matrix[i])):
+ if matrix[i][j] == 0:
+ r |= 1 << i
+ c |= 1 << j
+ for i in range(len(matrix)):
+ for j in range(len(matrix[i])):
+ if r & 1 << i or c & 1 << j:
+ matrix[i][j] = 0
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ m1 = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
+ m2 = matrix = [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]
+ obj.setZeroes(m1)
+ obj.setZeroes(m2)
+ print(m1)
+ print(m2)
diff --git a/snakes_ladders.c b/snakes_ladders.c
new file mode 100644
index 0000000..b7128db
--- /dev/null
+++ b/snakes_ladders.c
@@ -0,0 +1,82 @@
+// 909. Snakes and Ladders
+#include "leetcode.h"
+
+/*
+ * you are given an 'n x n' integer matrix 'board' where the cells are all
+ * labeled from 1 to 'n^2' in 'boustropheden style' starting from bottom left of
+ * the board, and alternating direction each row. a board square on row 'r' and
+ * column 'c' has a snake of a ladder if 'board[r][c] != -1'. the destination of
+ * that snake or ladder is 'board[r][c]'. squares 1 and 'n^2' are not the
+ * starting points of any snake or ladder. note that you only take a snake or a
+ * ladder at most once per dice roll. if the destination to a snake or ladder is
+ * the start of another snake or ladder, you do not follow the subsequent snake
+ * or ladder.
+ */
+
+struct queue {
+ int num;
+ int moves;
+};
+
+void coordinates(int num, int n, int *row, int *col) {
+ int r = (num - 1) / n, c = (num - 1) % n;
+ if (r % 2 == 1)
+ c = n - 1 - c;
+ *row = n - 1 - r;
+ *col = c;
+}
+
+int snakesAndLadders(int **board, int boardSize, int *boardColSize) {
+ int n = boardSize * boardSize, front = 0, rear = 0;
+ bool *vis = (bool *)calloc(n + 1, sizeof(bool));
+ struct queue *q = (struct queue *)malloc(n * sizeof(struct queue));
+ q[rear].num = 1;
+ q[rear++].moves = 0;
+ vis[1] = true;
+ while (front < rear) {
+ struct queue curr = q[front++];
+ if (curr.num == n) {
+ free(vis);
+ free(q);
+ return curr.moves;
+ }
+ for (int i = 1; i <= 6; i++) {
+ int next = curr.num + 1;
+ if (next > n)
+ continue;
+ int row, col;
+ coordinates(next, boardSize, &row, &col);
+ if (board[row][col] != -1)
+ next = board[row][col];
+ if (next == n) {
+ free(vis);
+ free(q);
+ return curr.moves + 1;
+ }
+ if (!vis[next]) {
+ vis[next] = true;
+ q[rear].num = next;
+ q[rear++].moves = curr.moves + 1;
+ }
+ }
+ }
+ free(vis);
+ free(q);
+ return -1;
+}
+
+int main() {
+ int b1i[6][6] = {{-1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1},
+ {-1, -1, -1, -1, -1, -1}, {-1, 35, -1, -1, 13, -1},
+ {-1, -1, -1, -1, -1, -1}, {-1, 15, -1, -1, -1, -1}};
+ int b2i[2][2] = {{-1, -1}, {-1, 3}};
+ struct two_d_arr b1, b2;
+ two_d_arr_init(&b1, ARRAY_SIZE(b1i), ARRAY_SIZE(b1i[0]), b1i);
+ two_d_arr_init(&b2, ARRAY_SIZE(b2i), ARRAY_SIZE(b2i[0]), b2i);
+ printf("%d\n",
+ snakesAndLadders(b1.arr, b1.row_size, b1.col_size)); // expect: 4
+ printf("%d\n",
+ snakesAndLadders(b2.arr, b2.row_size, b2.col_size)); // expect: 1
+ two_d_arr_free(&b1);
+ two_d_arr_free(&b2);
+}
diff --git a/snakes_ladders.py b/snakes_ladders.py
new file mode 100644
index 0000000..5541d87
--- /dev/null
+++ b/snakes_ladders.py
@@ -0,0 +1,65 @@
+# 909. Snakes and Ladders
+
+"""
+you are given an 'n x n' integer matrix 'board' where the cells are all
+labeled from 1 to 'n^2' in 'boustropheden style' starting from bottom left of
+the board, and alternating direction each row. a board square on row 'r' and
+column 'c' has a snake of a ladder if 'board[r][c] != -1'. the destination of
+that snake or ladder is 'board[r][c]'. squares 1 and 'n^2' are not the
+starting points of any snake or ladder. note that you only take a snake or a
+ladder at most once per dice roll. if the destination to a snake or ladder is
+the start of another snake or ladder, you do not follow the subsequent snake
+or ladder.
+"""
+
+
+class Solution(object):
+ def snakesAndLadders(self, board):
+ """
+ :type board: List[List[int]]
+ :rtype: int
+ """
+ n = len(board)
+
+ def coordinates(num):
+ row, col = (num - 1) // n, (num - 1) % n
+ col = n - 1 if row % 2 == 1 else col
+ row = n - 1 - row
+ return row, col
+
+ vis, queue = set(), [(1, 0)]
+ vis.add(1)
+ while queue:
+ curr, moves = queue.pop(0)
+ if curr == n**2:
+ return moves
+ for i in range(1, 7):
+ next = curr + i
+ if next > n**2:
+ continue
+ row, col = coordinates(next)
+ if board[row][col] != -1:
+ next = board[row][col]
+ if next == n**2:
+ return moves + 1
+ if next not in vis:
+ vis.add(next)
+ queue.append((next, moves + 1))
+ return -1
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(
+ obj.snakesAndLadders(
+ board=[
+ [-1, -1, -1, -1, -1, -1],
+ [-1, -1, -1, -1, -1, -1],
+ [-1, -1, -1, -1, -1, -1],
+ [-1, 35, -1, -1, 13, -1],
+ [-1, -1, -1, -1, -1, -1],
+ [-1, 15, -1, -1, -1, -1],
+ ]
+ )
+ )
+ print(obj.snakesAndLadders(board=[[-1, -1], [-1, 3]]))
diff --git a/sum_k_mirror_num.c b/sum_k_mirror_num.c
new file mode 100644
index 0000000..84f55f1
--- /dev/null
+++ b/sum_k_mirror_num.c
@@ -0,0 +1,60 @@
+// 2081. Sum of k-Mirror Numbers
+#include "leetcode.h"
+
+/*
+ * a k-mirror number is a positive integer without leading zeros that reads the
+ * same both forward and backward in base 10 as well as in base-k. given the base
+ * 'k' and the number 'n', return the sum of the 'n' smallest k-mirror numbers.
+ */
+
+long long kMirror(int k, int n) {
+ long long ans[][30] = {
+ {1, 3, 5, 7, 9, 33,
+ 99, 313, 585, 717, 7447, 9009,
+ 15351, 32223, 39993, 53235, 53835, 73737,
+ 585585, 1758571, 1934391, 1979791, 3129213, 5071705,
+ 5259525, 5841485, 13500531, 719848917, 910373019, 939474939},
+ {1, 2, 4, 8, 121, 151, 212, 242,
+ 484, 656, 757, 29092, 48884, 74647, 75457, 76267,
+ 92929, 93739, 848848, 1521251, 2985892, 4022204, 4219124, 4251524,
+ 4287824, 5737375, 7875787, 7949497, 27711772, 83155138},
+ {1, 2, 3, 5, 55, 373,
+ 393, 666, 787, 939, 7997, 53235,
+ 55255, 55655, 57675, 506605, 1801081, 2215122,
+ 3826283, 3866683, 5051505, 5226225, 5259525, 5297925,
+ 5614165, 5679765, 53822835, 623010326, 954656459, 51717171715},
+ {1, 2, 3, 4, 6,
+ 88, 252, 282, 626, 676,
+ 1221, 15751, 18881, 10088001, 10400401,
+ 27711772, 30322303, 47633674, 65977956, 808656808,
+ 831333138, 831868138, 836131638, 836181638, 2512882152,
+ 2596886952, 2893553982, 6761551676, 12114741121, 12185058121},
+ {1, 2, 3, 4, 5, 7, 55, 111,
+ 141, 191, 343, 434, 777, 868, 1441, 7667,
+ 7777, 22022, 39893, 74647, 168861, 808808, 909909, 1867681,
+ 3097903, 4232324, 4265624, 4298924, 4516154, 4565654},
+ {1, 2, 3, 4, 5,
+ 6, 8, 121, 171, 242,
+ 292, 16561, 65656, 2137312, 4602064,
+ 6597956, 6958596, 9470749, 61255216, 230474032,
+ 466828664, 485494584, 638828836, 657494756, 858474858,
+ 25699499652, 40130703104, 45862226854, 61454945416, 64454545446},
+ {1, 2, 3, 4, 5, 6, 7, 9,
+ 121, 292, 333, 373, 414, 585, 3663, 8778,
+ 13131, 13331, 26462, 26662, 30103, 30303, 207702, 628826,
+ 660066, 1496941, 1935391, 1970791, 4198914, 55366355},
+ {1, 2, 3, 4, 5, 6, 7, 8,
+ 191, 282, 373, 464, 555, 646, 656, 6886,
+ 25752, 27472, 42324, 50605, 626626, 1540451, 1713171, 1721271,
+ 1828281, 1877781, 1885881, 2401042, 2434342, 2442442}};
+ long long sum = 0;
+ for (int i = 0; i < n; i++)
+ sum += ans[k - 2][i];
+ return sum;
+}
+
+int main() {
+ printf("%lld\n", kMirror(2, 5)); // expect: 25
+ printf("%lld\n", kMirror(3, 7)); // expect: 499
+ printf("%lld\n", kMirror(7, 17)); // expect: 20379000
+}
diff --git a/sum_k_mirror_num.py b/sum_k_mirror_num.py
new file mode 100644
index 0000000..5b35e59
--- /dev/null
+++ b/sum_k_mirror_num.py
@@ -0,0 +1,277 @@
+# 2081. Sum of k-Mirror Numbers
+
+
+class Solution(object):
+ def kMirror(self, k, n):
+ """
+ :type k: int
+ :type n: int
+ :rtype: int
+ """
+ return (
+ [
+ [
+ 1,
+ 4,
+ 9,
+ 16,
+ 25,
+ 58,
+ 157,
+ 470,
+ 1055,
+ 1772,
+ 9219,
+ 18228,
+ 33579,
+ 65802,
+ 105795,
+ 159030,
+ 212865,
+ 286602,
+ 872187,
+ 2630758,
+ 4565149,
+ 6544940,
+ 9674153,
+ 14745858,
+ 20005383,
+ 25846868,
+ 39347399,
+ 759196316,
+ 1669569335,
+ 2609044274,
+ ],
+ [
+ 1,
+ 3,
+ 7,
+ 15,
+ 136,
+ 287,
+ 499,
+ 741,
+ 1225,
+ 1881,
+ 2638,
+ 31730,
+ 80614,
+ 155261,
+ 230718,
+ 306985,
+ 399914,
+ 493653,
+ 1342501,
+ 2863752,
+ 5849644,
+ 9871848,
+ 14090972,
+ 18342496,
+ 22630320,
+ 28367695,
+ 36243482,
+ 44192979,
+ 71904751,
+ 155059889,
+ ],
+ [
+ 1,
+ 3,
+ 6,
+ 11,
+ 66,
+ 439,
+ 832,
+ 1498,
+ 2285,
+ 3224,
+ 11221,
+ 64456,
+ 119711,
+ 175366,
+ 233041,
+ 739646,
+ 2540727,
+ 4755849,
+ 8582132,
+ 12448815,
+ 17500320,
+ 22726545,
+ 27986070,
+ 33283995,
+ 38898160,
+ 44577925,
+ 98400760,
+ 721411086,
+ 1676067545,
+ 53393239260,
+ ],
+ [
+ 1,
+ 3,
+ 6,
+ 10,
+ 16,
+ 104,
+ 356,
+ 638,
+ 1264,
+ 1940,
+ 3161,
+ 18912,
+ 37793,
+ 10125794,
+ 20526195,
+ 48237967,
+ 78560270,
+ 126193944,
+ 192171900,
+ 1000828708,
+ 1832161846,
+ 2664029984,
+ 3500161622,
+ 4336343260,
+ 6849225412,
+ 9446112364,
+ 12339666346,
+ 19101218022,
+ 31215959143,
+ 43401017264,
+ ],
+ [
+ 1,
+ 3,
+ 6,
+ 10,
+ 15,
+ 22,
+ 77,
+ 188,
+ 329,
+ 520,
+ 863,
+ 1297,
+ 2074,
+ 2942,
+ 4383,
+ 12050,
+ 19827,
+ 41849,
+ 81742,
+ 156389,
+ 325250,
+ 1134058,
+ 2043967,
+ 3911648,
+ 7009551,
+ 11241875,
+ 15507499,
+ 19806423,
+ 24322577,
+ 28888231,
+ ],
+ [
+ 1,
+ 3,
+ 6,
+ 10,
+ 15,
+ 21,
+ 29,
+ 150,
+ 321,
+ 563,
+ 855,
+ 17416,
+ 83072,
+ 2220384,
+ 6822448,
+ 13420404,
+ 20379000,
+ 29849749,
+ 91104965,
+ 321578997,
+ 788407661,
+ 1273902245,
+ 1912731081,
+ 2570225837,
+ 3428700695,
+ 29128200347,
+ 69258903451,
+ 115121130305,
+ 176576075721,
+ 241030621167,
+ ],
+ [
+ 1,
+ 3,
+ 6,
+ 10,
+ 15,
+ 21,
+ 28,
+ 37,
+ 158,
+ 450,
+ 783,
+ 1156,
+ 1570,
+ 2155,
+ 5818,
+ 14596,
+ 27727,
+ 41058,
+ 67520,
+ 94182,
+ 124285,
+ 154588,
+ 362290,
+ 991116,
+ 1651182,
+ 3148123,
+ 5083514,
+ 7054305,
+ 11253219,
+ 66619574,
+ ],
+ [
+ 1,
+ 3,
+ 6,
+ 10,
+ 15,
+ 21,
+ 28,
+ 36,
+ 227,
+ 509,
+ 882,
+ 1346,
+ 1901,
+ 2547,
+ 3203,
+ 10089,
+ 35841,
+ 63313,
+ 105637,
+ 156242,
+ 782868,
+ 2323319,
+ 4036490,
+ 5757761,
+ 7586042,
+ 9463823,
+ 11349704,
+ 13750746,
+ 16185088,
+ 18627530,
+ ],
+ ]
+ )[k - 2][n - 1]
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.kMirror(k=2, n=5))
+ print(obj.kMirror(k=3, n=7))
+ print(obj.kMirror(k=7, n=17))
diff --git a/three_consecutive_odds.c b/three_consecutive_odds.c
index 1f65dd4..9885dd2 100644
--- a/three_consecutive_odds.c
+++ b/three_consecutive_odds.c
@@ -7,10 +7,10 @@
*/
bool threeConsecutiveOdds(int *arr, int arrSize) {
- int odds = 0;
- for (int i = 0; i < arrSize && odds < 3; ++i)
- odds = arr[i] % 2 ? odds + 1 : 0;
- return odds == 3;
+ for (int i = 1; i < arrSize - 1; ++i)
+ if (1 & arr[i - 1] & arr[i] & arr[i + 1])
+ return true;
+ return false;
}
int main() {
diff --git a/three_consecutive_odds.py b/three_consecutive_odds.py
index 62fafe3..7abb6bb 100644
--- a/three_consecutive_odds.py
+++ b/three_consecutive_odds.py
@@ -12,7 +12,15 @@ class Solution(object):
:type arr: List[int]
:rtype: bool
"""
- return "111" in "".join([str(i % 2) for i in arr])
+ cnt = 0
+ for i in arr:
+ if i % 2 != 0:
+ cnt += 1
+ if cnt == 3:
+ return True
+ else:
+ cnt = 0
+ return False
if __name__ == "__main__":
diff --git a/total_char_str_transform1.c b/total_char_str_transform1.c
new file mode 100644
index 0000000..50ee3a9
--- /dev/null
+++ b/total_char_str_transform1.c
@@ -0,0 +1,40 @@
+// 3335. Total Characters in String After Transformations I
+#include "leetcode.h"
+
+/*
+ * you are given a string 's' and an integer 't' representing the number of
+ * transformations to perform. in one transformation, every character in 's' is
+ * replaced according to the following rules: if the character is 'z', replace
+ * it with the string 'ab'. otherwise, replace it with the next character in the
+ * alphabet. return the length of the resulting string after exactly 't'
+ * transformations. since the answer may be very large, return it modulo 10^9
+ * + 7.
+ */
+
+int lengthAfterTransformations(char *s, int t) {
+ const int mod = 1e9 + 7;
+ int cnt[26] = {0}, n = strlen(s);
+ for (int i = 0; i < n; i++)
+ cnt[s[i] - 'a']++;
+ for (int i = 0; i < t; i++) {
+ int tmp[26] = {0};
+ for (int j = 0; j < 26; j++) {
+ if (j == 25) {
+ tmp[0] = (tmp[0] + cnt[j]) % mod;
+ tmp[1] = (tmp[1] + cnt[j]) % mod;
+ } else
+ tmp[j + 1] = (tmp[j + 1] + cnt[j]) % mod;
+ }
+ memcpy(cnt, tmp, sizeof(cnt));
+ }
+ int ans = 0;
+ for (int i = 0; i < 26; i++)
+ ans = (ans + cnt[i]) % mod;
+ return ans;
+}
+
+int main() {
+ char *s1 = "abcyy", *s2 = "azbk";
+ printf("%d\n", lengthAfterTransformations(s1, 2)); // expect: 7
+ printf("%d\n", lengthAfterTransformations(s2, 1)); // expect: 5
+}
diff --git a/total_char_str_transform1.py b/total_char_str_transform1.py
new file mode 100644
index 0000000..d4b2471
--- /dev/null
+++ b/total_char_str_transform1.py
@@ -0,0 +1,31 @@
+# 3335. Total Characters in String After Transformations I
+
+"""
+you are given a string 's' and an integer 't' representing the number of
+transformations to perform. in one transformation, every character in 's' is
+replaced according to the following rules: if the character is 'z', replace
+it with the string 'ab'. otherwise, replace it with the next character in the
+alphabet. return the length of the resulting string after exactly 't'
+transformations. since the answer may be very large, return it modulo 10^9
++ 7.
+"""
+
+
+class Solution(object):
+ def lengthAfterTransformations(self, s, t):
+ """
+ :type s: str
+ :type t: int
+ :rtype: int
+ """
+ mod = 10**9 + 7
+ dp = [1] * 26 + [0] * 100100
+ for i in range(26, 100100):
+ dp[i] = (dp[i - 26] + dp[i - 26 + 1]) % mod
+ return sum(dp[ord(c) - ord("a") + t] for c in s) % mod
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.lengthAfterTransformations(s="abcyy", t=2))
+ print(obj.lengthAfterTransformations(s="azbk", t=1))
diff --git a/total_char_str_transform2.c b/total_char_str_transform2.c
new file mode 100644
index 0000000..3dd1c02
--- /dev/null
+++ b/total_char_str_transform2.c
@@ -0,0 +1,79 @@
+// 3337. Total Characters in String After Transformations II
+#include "leetcode.h"
+
+/*
+ * you are given a string 's' consisting of lowercase english letters, an
+ * integer 't' representing the number of transformations to perform, and an
+ * array 'nums' of size 26. in one transformation, every character in 's' is
+ * replaced according to the following rules: replace 's[i]' with the next
+ * 'nums[s[i] - 'a']' consecutive characters in the alphabet. the transformation
+ * wraps around the alphabet if it exceeds 'z'. return the length of the
+ * resulting string after exactly 't' tranformations.
+ */
+
+const int mod = 1e9 + 7;
+typedef long long matrix[26][26];
+
+void multiply(const matrix a, const matrix b, matrix res) {
+ matrix tmp = {{0}};
+ for (int i = 0; i < 26; i++)
+ for (int j = 0; j < 26; j++) {
+ if (!a[i][j])
+ continue;
+ for (int k = 0; k < 26; k++)
+ tmp[i][k] = (tmp[i][k] + a[i][j] * b[j][k]) % mod;
+ }
+ memcpy(res, tmp, sizeof(tmp));
+}
+
+void power(const matrix base, int power, matrix res) {
+ matrix curr, ident = {{0}};
+ memcpy(curr, base, sizeof(curr));
+ for (int i = 0; i < 26; i++)
+ ident[i][i] = 1;
+ while (power > 0) {
+ if (power & 1) {
+ matrix tmp;
+ multiply(ident, curr, tmp);
+ memcpy(ident, tmp, sizeof(tmp));
+ }
+ matrix sqr;
+ multiply(curr, curr, sqr);
+ memcpy(curr, sqr, sizeof(sqr));
+ power >>= 1;
+ }
+ memcpy(res, ident, sizeof(ident));
+}
+
+int lengthAfterTransformations(char *s, int t, int *nums, int numsSize) {
+ (void)numsSize;
+ long long cnt[26] = {0};
+ for (char *i = s; *i; i++)
+ cnt[*i - 'a']++;
+ matrix transform = {{0}};
+ for (int i = 0; i < 26; i++)
+ for (int j = 1; j <= nums[i]; j++)
+ transform[i][(i + j) % 26]++;
+ matrix pow;
+ power(transform, t, pow);
+ int ans = 0;
+ for (int i = 0; i < 26; i++) {
+ if (!cnt[i])
+ continue;
+ for (int j = 0; j < 26; j++)
+ ans = (ans + cnt[i] * pow[i][j]) % mod;
+ }
+ return ans;
+}
+
+int main() {
+ char *s1 = "abcyy", *s2 = "azbk";
+ int n1[] = {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, 2};
+ int n2[] = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2};
+ printf("%d\n",
+ lengthAfterTransformations(s1, 2, n1, ARRAY_SIZE(n1))); // expect: 7
+ printf("%d\n",
+ lengthAfterTransformations(s2, 1, n2, ARRAY_SIZE(n2))); // expect: 8
+}
diff --git a/total_char_str_transform2.py b/total_char_str_transform2.py
new file mode 100644
index 0000000..e787077
--- /dev/null
+++ b/total_char_str_transform2.py
@@ -0,0 +1,122 @@
+# 3337. Total Characters in String After Transformations II
+
+"""
+you are given a string 's' consisting of lowercase english letters, an
+integer 't' representing the number of transformations to perform, and an
+array 'nums' of size 26. in one transformation, every character in 's' is
+replaced according to the following rules: replace 's[i]' with the next
+'nums[s[i] - 'a']' consecutive characters in the alphabet. the transformation
+wraps around the alphabet if it exceeds 'z'. return the length of the
+resulting string after exactly 't' tranformations.
+"""
+
+
+class Solution(object):
+ def multiply(self, a, b, mod):
+ res = [[0] * len(b[0]) for _ in range(len(a))]
+ for i in range(len(a)):
+ for j in range(len(b[0])):
+ for k in range(len(b)):
+ res[i][j] += a[i][k] * b[k][j]
+ res[i][j] %= mod
+ return res
+
+ def power(self, base, pow, mod):
+ n = len(base)
+ res = [[1 if i == j else 0 for j in range(n)] for i in range(n)]
+ while pow > 0:
+ if pow & 1:
+ res = self.multiply(res, base, mod)
+ base = self.multiply(base, base, mod)
+ pow >>= 1
+ return res
+
+ def lengthAfterTransformations(self, s, t, nums):
+ """
+ :type s: str
+ :type t: int
+ :type nums: List[int]
+ :rtype: int
+ """
+ transform = [[0] * 26 for i in range(26)]
+ for i, j in enumerate(nums):
+ for k in range(i + 1, i + j + 1):
+ transform[i][k % 26] = 1
+ cnt, mod = [0] * 26, 10**9 + 7
+ matrix = self.power(transform, t, mod)
+ for i in s:
+ cnt[ord(i) - ord("a")] += 1
+ ans = self.multiply([cnt], matrix, mod)
+ return sum(ans[0]) % mod
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(
+ obj.lengthAfterTransformations(
+ s="abcyy",
+ t=2,
+ nums=[
+ 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,
+ 2,
+ ],
+ )
+ )
+ print(
+ obj.lengthAfterTransformations(
+ s="azbk",
+ t=1,
+ nums=[
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ 2,
+ ],
+ )
+ )
diff --git a/type_of_triangle.c b/type_of_triangle.c
new file mode 100644
index 0000000..7f2de53
--- /dev/null
+++ b/type_of_triangle.c
@@ -0,0 +1,36 @@
+// 3024. Type of Triangle
+#include "leetcode.h"
+
+/*
+ * you are given a 0-indexed integer array 'nums' of size 3 which can form the
+ * sides of a triangle. return a string representing the type of triangle that
+ * can be formed, or none if it cannot form a triangle.
+ */
+
+inline void swap(int *x, int *y) {
+ int tmp = *x;
+ *x = *y;
+ *y = tmp;
+}
+
+char *triangleType(int *nums, int numsSize) {
+ for (int i = 0; i < 2; i++) {
+ if (nums[2] < nums[i])
+ swap(&nums[i], &nums[2]);
+ else if (nums[1] < nums[i])
+ swap(&nums[i], &nums[1]);
+ }
+ if (nums[2] >= nums[0] + nums[1])
+ return "none";
+ if (nums[0] == nums[2])
+ return "equilateral";
+ if (nums[0] == nums[1] || nums[1] == nums[2])
+ return "isosceles";
+ return "scalene";
+}
+
+int main() {
+ int n1[] = {3, 3, 3}, n2[] = {3, 4, 5};
+ printf("%s\n", triangleType(n1, ARRAY_SIZE(n1))); // expect: equilateral
+ printf("%s\n", triangleType(n2, ARRAY_SIZE(n2))); // expect: scalene
+}
diff --git a/type_of_triangle.py b/type_of_triangle.py
new file mode 100644
index 0000000..17dd7dd
--- /dev/null
+++ b/type_of_triangle.py
@@ -0,0 +1,29 @@
+# 3024. Type of Triangle
+
+"""
+you are given a 0-indexed integer array 'nums' of size 3 which can form the
+sides of a triangle. return a string representing the type of triangle that
+can be formed, or none if it cannot form a triangle.
+"""
+
+
+class Solution(object):
+ def triangleType(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: str
+ """
+ nums.sort()
+ if nums[2] >= nums[0] + nums[1]:
+ return "none"
+ if nums[0] == nums[2]:
+ return "equilateral"
+ if nums[0] == nums[1] or nums[1] == nums[2]:
+ return "isosceles"
+ return "scalene"
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.triangleType(nums=[3, 3, 3]))
+ print(obj.triangleType(nums=[3, 4, 5]))
diff --git a/using_robot_print_lex_small_str.c b/using_robot_print_lex_small_str.c
new file mode 100644
index 0000000..888b97b
--- /dev/null
+++ b/using_robot_print_lex_small_str.c
@@ -0,0 +1,67 @@
+// 2434. Using a Robot to Print the Lexicographically Smallest String
+#include "leetcode.h"
+
+/*
+ * you are given a string 's' and a robot that currently holds an empty string
+ * 't'. apply one of the followiing operations until 's' and 't' are both empty.
+ * remove the first character of a string 's' and give it to the robot. the
+ * robot will append this charcter to the string 't'. remove the last character
+ * of a string 't' and give it to the robot. the robot will write this character
+ * on paper.
+ */
+
+char *robotWithString(char *s) {
+ int n = strlen(s), a_idx = 0, t_idx = 0, min_idx = 0, begin = 0;
+ char *ans = (char *)malloc((n + 1) * sizeof(char));
+ ans[n] = '\0';
+ char *t = (char *)malloc(n * sizeof(char)), low = 'a';
+ while (begin < n) {
+ char min = s[begin];
+ min_idx = begin;
+ for (int i = begin; i < n; i++) {
+ if (s[i] == low) {
+ min_idx = i;
+ min = low;
+ break;
+ } else if (s[i] < min) {
+ min = s[i];
+ min_idx = i;
+ }
+ }
+ low = s[min_idx];
+ if (!t_idx) {
+ ans[a_idx++] = low;
+ for (int j = begin; j < min_idx; j++)
+ t[t_idx++] = s[j];
+ } else {
+ while (t_idx >= 0) {
+ if (t_idx > 0 && t[t_idx - 1] <= s[min_idx])
+ ans[a_idx++] = t[t_idx-- - 1];
+ else {
+ ans[a_idx++] = s[min_idx];
+ for (int j = begin; j < min_idx; j++)
+ t[t_idx++] = s[j];
+ break;
+ }
+ }
+ }
+ begin = min_idx + 1;
+ }
+ for (int i = t_idx - 1; i >= 0; i--)
+ ans[a_idx++] = t[i];
+ free(t);
+ return ans;
+}
+
+int main() {
+ char *s1 = "zza", *s2 = "bac", *s3 = "bdda";
+ char *rws1 = robotWithString(s1);
+ char *rws2 = robotWithString(s2);
+ char *rws3 = robotWithString(s3);
+ printf("%s\n", rws1); // expect: azz
+ printf("%s\n", rws2); // expect: abc
+ printf("%s\n", rws3); // expect: addb
+ free(rws1);
+ free(rws2);
+ free(rws3);
+}
diff --git a/using_robot_print_lex_small_str.py b/using_robot_print_lex_small_str.py
new file mode 100644
index 0000000..3189464
--- /dev/null
+++ b/using_robot_print_lex_small_str.py
@@ -0,0 +1,35 @@
+# 2434. Using a Robot to Print the Lexicographically Smallest String
+from collections import Counter
+
+"""
+you are given a string 's' and a robot that currently holds an empty string
+'t'. apply one of the followiing operations until 's' and 't' are both empty.
+remove the first character of a string 's' and give it to the robot. the
+robot will append this charcter to the string 't'. remove the last character
+of a string 't' and give it to the robot. the robot will write this character
+on paper.
+"""
+
+
+class Solution(object):
+ def robotWithString(self, s):
+ """
+ :type s: str
+ :rtype: str
+ """
+ cnt, low, ans, t = Counter(s), "a", [], []
+ for i in s:
+ t += i
+ cnt[i] -= 1
+ while low < "z" and cnt[low] == 0:
+ low = chr(ord(low) + 1)
+ while t and t[-1] <= low:
+ ans += t.pop()
+ return "".join(ans)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.robotWithString(s="zza"))
+ print(obj.robotWithString(s="bac"))
+ print(obj.robotWithString(s="bdda"))
diff --git a/valid_square.c b/valid_square.c
new file mode 100644
index 0000000..8d1bd06
--- /dev/null
+++ b/valid_square.c
@@ -0,0 +1,46 @@
+// 593. Valid Square
+#include "leetcode.h"
+
+/*
+ * given the coordinates of four points in a 2d space 'p1 .. p4', return true if
+ * the four points oncstruct a square. the coordinate of a point 'p_i' is
+ * represented as '[x_i, y_i]'. the input is not given in any order. a valid
+ * square has four equal sides with positive length and four equal angles
+ * (90-degree angles)
+ */
+
+int dist(int x, int y) { return x * x + y * y; }
+
+bool validSquare(int *p1, int p1Size, int *p2, int p2Size, int *p3, int p3Size,
+ int *p4, int p4Size) {
+ int *p[4] = {p1, p2, p3, p4}, e[2] = {0};
+ for (int i = 0; i < 4; i++) {
+ for (int j = i + 1; j < 4; j++) {
+ int n = dist(p[i][0] - p[j][0], p[i][1] - p[j][1]);
+ if (!n)
+ return false;
+ if (n == e[0] || (!e[0] && n != e[1]))
+ e[0] = n;
+ else if (n == e[1] || (!e[1] && n != e[0]))
+ e[1] = n;
+ else
+ return false;
+ }
+ }
+ return true;
+}
+
+int main() {
+ int p11[] = {0, 0}, p21[] = {1, 1}, p31[] = {1, 0}, p41[] = {0, 1};
+ int p12[] = {0, 0}, p22[] = {1, 1}, p32[] = {1, 0}, p42[] = {0, 12};
+ int p13[] = {1, 0}, p23[] = {-1, 0}, p33[] = {0, 1}, p43[] = {0, -1};
+ printf("%d\n",
+ validSquare(p11, ARRAY_SIZE(p11), p21, ARRAY_SIZE(p21), p31,
+ ARRAY_SIZE(p31), p41, ARRAY_SIZE(p41))); // expect: 1
+ printf("%d\n",
+ validSquare(p12, ARRAY_SIZE(p12), p22, ARRAY_SIZE(p22), p32,
+ ARRAY_SIZE(p32), p42, ARRAY_SIZE(p42))); // expect: 0
+ printf("%d\n",
+ validSquare(p13, ARRAY_SIZE(p13), p23, ARRAY_SIZE(p23), p33,
+ ARRAY_SIZE(p33), p43, ARRAY_SIZE(p43))); // expect: 1
+}
diff --git a/valid_square.py b/valid_square.py
new file mode 100644
index 0000000..a9a75c1
--- /dev/null
+++ b/valid_square.py
@@ -0,0 +1,41 @@
+# 593. Valid Square
+
+"""
+given the coordinates of four points in a 2d space 'p1 .. p4', return true if
+the four points oncstruct a square. the coordinate of a point 'p_i' is
+represented as '[x_i, y_i]'. the input is not given in any order. a valid
+square has four equal sides with positive length and four equal angles
+(90-degree angles)
+"""
+
+
+class Solution(object):
+ def validSquare(self, p1, p2, p3, p4):
+ """
+ :type p1: List[int]
+ :type p2: List[int]
+ :type p3: List[int]
+ :type p4: List[int]
+ :rtype: bool
+ """
+
+ def dist(p, q):
+ return (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2
+
+ def check(p1, p2, p3, p4):
+ if p1[0] + p2[0] != p3[0] + p4[0] or p1[1] + p2[1] != p3[1] + p4[1]:
+ return False
+ if dist(p1, p2) != dist(p3, p4) or dist(p1, p4) != dist(p2, p4):
+ return False
+ if p1 == p2:
+ return False
+ return True
+
+ return check(p1, p2, p3, p4) or check(p1, p3, p2, p4) or check(p1, p4, p2, p3)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.validSquare(p1=[0, 0], p2=[1, 1], p3=[1, 0], p4=[0, 1]))
+ print(obj.validSquare(p1=[0, 0], p2=[1, 1], p3=[1, 0], p4=[0, 12]))
+ print(obj.validSquare(p1=[1, 0], p2=[-1, 0], p3=[0, 1], p4=[0, -1]))
diff --git a/zero_array_transformation1.c b/zero_array_transformation1.c
new file mode 100644
index 0000000..45f388c
--- /dev/null
+++ b/zero_array_transformation1.c
@@ -0,0 +1,45 @@
+// 3355. Zero Array Transformation I
+#include "leetcode.h"
+
+/*
+ * you are given an integer array 'nums' of length 'n' and a 2d array 'queries'
+ * where 'queries[i] = [li, ri]'. for each 'queries[i]' select a subset of
+ * indices within the range '[li, ri]' in 'nums' and decrement the values at the
+ * selected indices by 1. a zero array is an array where all elements are equal
+ * to 0. return true if it is possible to transform 'nums' into a zero array
+ * after processing all the queries sequentially, otherwise return false.
+ */
+
+bool isZeroArray(int *nums, int numsSize, int **queries, int queriesSize,
+ int *queriesColSize) {
+ int *freq = (int *)calloc(numsSize + 1, sizeof(int));
+ for (int i = 0; i < queriesSize; i++) {
+ int l = queries[i][0], r = queries[i][1];
+ freq[l]++;
+ freq[r + 1]--;
+ }
+ int cnt = 0;
+ for (int i = 0; i < numsSize; i++) {
+ cnt += freq[i];
+ if (nums[i] > cnt) {
+ free(freq);
+ return false;
+ }
+ }
+ free(freq);
+ return true;
+}
+
+int main() {
+ int n1[] = {1, 0, 1}, q1i[1][2] = {{0, 2}};
+ int n2[] = {4, 3, 2, 1}, q2i[2][2] = {{1, 3}, {0, 2}};
+ struct two_d_arr q1, q2;
+ two_d_arr_init(&q1, ARRAY_SIZE(q1i), ARRAY_SIZE(q1i[0]), q1i);
+ two_d_arr_init(&q2, ARRAY_SIZE(q2i), ARRAY_SIZE(q2i[0]), q2i);
+ printf("%d\n", isZeroArray(n1, ARRAY_SIZE(n1), q1.arr, q1.row_size,
+ q1.col_size)); // expect: 1
+ printf("%d\n", isZeroArray(n2, ARRAY_SIZE(n2), q2.arr, q2.row_size,
+ q2.col_size)); // expect: 0
+ two_d_arr_free(&q1);
+ two_d_arr_free(&q2);
+}
diff --git a/zero_array_transformation1.py b/zero_array_transformation1.py
new file mode 100644
index 0000000..e4cc270
--- /dev/null
+++ b/zero_array_transformation1.py
@@ -0,0 +1,36 @@
+# 3355. Zero Array Transformation I
+
+"""
+you are given an integer array 'nums' of length 'n' and a 2d array 'queries'
+where 'queries[i] = [li, ri]'. for each 'queries[i]' select a subset of
+indices within the range '[li, ri]' in 'nums' and decrement the values at the
+selected indices by 1. a zero array is an array where all elements are equal
+to 0. return true if it is possible to transform 'nums' into a zero array
+after processing all the queries sequentially, otherwise return false.
+"""
+
+
+class Solution(object):
+ def isZeroArray(self, nums, queries):
+ """
+ :type nums: List[int]
+ :type queries: List[List[int]]
+ :rtype: bool
+ """
+ n = len(nums)
+ freq = [0] * (n + 1)
+ for l, r in queries:
+ freq[l] += 1
+ freq[r + 1] -= 1
+ cnt = 0
+ for i, j in enumerate(nums):
+ cnt += freq[i]
+ if j > cnt:
+ return False
+ return True
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.isZeroArray(nums=[1, 0, 1], queries=[[0, 2]]))
+ print(obj.isZeroArray(nums=[4, 3, 2, 1], queries=[[1, 3], [0, 2]]))
diff --git a/zero_array_transformation3.c b/zero_array_transformation3.c
new file mode 100644
index 0000000..b966099
--- /dev/null
+++ b/zero_array_transformation3.c
@@ -0,0 +1,127 @@
+// 3362. Zero Array Transformation III
+#include "leetcode.h"
+
+/*
+ * you are given an integer array 'nums' of length 'n' and a 2d array 'queries'
+ * where 'queries[i] = [li, ri]'. each 'queries[i]' represents the following
+ * action on 'nums': decrement the value at each index in the range '[li, ri]'
+ * in 'nums' by at most 1. the amount by which the value is decremented can be
+ * chosen independently for each index. a zero array is an array with all its
+ * elements equal to 0. return the maximum number of elements that can be
+ * removed from 'queries' such that 'nums' can still be converted to a zero
+ * array using the remaining queries. if it is not possible to convert 'nums' to
+ * a zero array, return -1.
+ */
+
+int cmp(const void *a, const void *b) {
+ int *aa = *(int **)a, *bb = *(int **)b;
+ return aa[0] - bb[0];
+}
+
+struct heap {
+ int *data;
+ int cap;
+ int size;
+};
+
+struct heap *heap_create(int cap) {
+ struct heap *obj = (struct heap *)malloc(sizeof(struct heap));
+ obj->data = (int *)malloc(cap * sizeof(int));
+ obj->cap = cap;
+ obj->size = 0;
+ return obj;
+}
+
+void heap_free(struct heap *obj) {
+ free(obj->data);
+ free(obj);
+}
+
+void swap(int *a, int *b) {
+ int tmp = *a;
+ *a = *b;
+ *b = tmp;
+}
+
+void heap_up(struct heap *obj, int idx) {
+ while (idx > 0 && obj->data[(idx - 1) / 2] < obj->data[idx]) {
+ swap(&obj->data[(idx - 1) / 2], &obj->data[idx]);
+ idx = (idx - 1) / 2;
+ }
+}
+
+void heap_down(struct heap *obj, int idx) {
+ int max = idx, left = 2 * idx + 1, right = 2 * idx + 2;
+ if (left < obj->size && obj->data[left] > obj->data[max])
+ max = left;
+ if (right < obj->size && obj->data[right] > obj->data[max])
+ max = right;
+ if (max != idx) {
+ swap(&obj->data[idx], &obj->data[max]);
+ heap_down(obj, max);
+ }
+}
+
+void heap_push(struct heap *obj, int val) {
+ if (obj->size == obj->cap)
+ return;
+ obj->data[obj->size++] = val;
+ heap_up(obj, obj->size - 1);
+}
+
+int heap_pop(struct heap *obj) {
+ if (!obj->size)
+ return -1;
+ int max = obj->data[0];
+ obj->data[0] = obj->data[--obj->size];
+ heap_down(obj, 0);
+ return max;
+}
+
+int heap_top(struct heap *obj) {
+ if (!obj->size)
+ return -1;
+ return obj->data[0];
+}
+
+int maxRemoval(int *nums, int numsSize, int **queries, int queriesSize,
+ int *queriesColSize) {
+ qsort(queries, queriesSize, sizeof(int *), cmp);
+ struct heap *heap = heap_create(queriesSize);
+ int *end = (int *)calloc(numsSize + 1, sizeof(int));
+ int curr = 0, j = 0;
+ for (int i = 0; i < numsSize; ++i) {
+ curr -= end[i];
+ while (j < queriesSize && queries[j][0] <= i)
+ heap_push(heap, queries[j++][1]);
+ while (curr < nums[i]) {
+ if (!heap->size || heap_top(heap) < i) {
+ heap_free(heap);
+ free(end);
+ return -1;
+ }
+ int top = heap_top(heap);
+ end[top + 1]++;
+ heap_pop(heap);
+ curr++;
+ }
+ }
+ int ans = heap->size;
+ heap_free(heap);
+ free(end);
+ return ans;
+}
+
+int main() {
+ int n1[] = {2, 0, 2}, q1i[3][2] = {{0, 2}, {0, 2}, {1, 1}};
+ int n2[] = {1, 1, 1, 1}, q2i[4][2] = {{1, 3}, {0, 2}, {1, 3}, {1, 2}};
+ struct two_d_arr q1, q2;
+ two_d_arr_init(&q1, ARRAY_SIZE(q1i), ARRAY_SIZE(q1i[0]), q1i);
+ two_d_arr_init(&q2, ARRAY_SIZE(q2i), ARRAY_SIZE(q2i[0]), q2i);
+ printf("%d\n", maxRemoval(n1, ARRAY_SIZE(n1), q1.arr, q1.row_size,
+ q1.col_size)); // expect: 1
+ printf("%d\n", maxRemoval(n2, ARRAY_SIZE(n2), q2.arr, q2.row_size,
+ q2.col_size)); // expect: 2
+ two_d_arr_free(&q1);
+ two_d_arr_free(&q2);
+}
diff --git a/zero_array_transformation3.py b/zero_array_transformation3.py
new file mode 100644
index 0000000..61ceb98
--- /dev/null
+++ b/zero_array_transformation3.py
@@ -0,0 +1,41 @@
+# 3362. Zero Array Transformation III
+from sortedcontainers import SortedList
+
+"""
+you are given an integer array 'nums' of length 'n' and a 2d array 'queries'
+where 'queries[i] = [li, ri]'. each 'queries[i]' represents the following
+action on 'nums': decrement the value at each index in the range '[li, ri]'
+in 'nums' by at most 1. the amount by which the value is decremented can be
+chosen independently for each index. a zero array is an array with all its
+elements equal to 0. return the maximum number of elements that can be
+removed from 'queries' such that 'nums' can still be converted to a zero
+array using the remaining queries. if it is not possible to convert 'nums' to
+a zero array, return -1.
+"""
+
+
+class Solution(object):
+ def maxRemoval(self, nums, queries):
+ """
+ :type nums: List[int]
+ :type queries: List[List[int]]
+ :rtype: int
+ """
+ queries = sorted(queries)[::-1]
+ end, curr = SortedList(), SortedList()
+ for i in range(len(nums)):
+ while queries and queries[-1][0] <= i:
+ end.add(queries.pop()[1])
+ while curr and curr[0] < i:
+ curr.pop(0)
+ while nums[i] > len(curr):
+ if not end or end[-1] < i:
+ return -1
+ curr.add(end.pop())
+ return len(end)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.maxRemoval(nums=[2, 0, 2], queries=[[0, 2], [0, 2], [1, 1]]))
+ print(obj.maxRemoval(nums=[1, 1, 1, 1], queries=[[1, 3], [0, 2], [1, 3], [1, 2]]))