From 7c60dee83b436e8e8a667bf9f191beced8de4fc3 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Mon, 10 Mar 2025 00:36:13 -0600 Subject: chore: move cpp and rust code to directory --- 01_matrix.cpp | 34 ---------- 132_pattern.cpp | 32 --------- 3sum_closest.cpp | 31 --------- add_arr_form_int.cpp | 44 ------------ add_binary.cpp | 30 -------- add_digits.cpp | 26 ------- add_row_tree.cpp | 29 -------- add_search_words_data.cpp | 35 ---------- add_space_string.cpp | 36 ---------- add_two_num2.cpp | 56 --------------- additive_number.cpp | 54 --------------- all_nodes_binary_tree.cpp | 53 --------------- all_path_src_target.cpp | 30 -------- all_path_src_target.rs | 54 --------------- all_possible_full_tree.cpp | 40 ----------- alphabet_board_path.cpp | 44 ------------ ancestors_node_acyclic_graph.cpp | 58 ---------------- arithmetic_progression.cpp | 44 ------------ arithmetic_slices2.cpp | 35 ---------- arithmetic_slices2.rs | 30 -------- asteroid_collision.cpp | 52 -------------- avg_levels_bst.cpp | 24 ------- avg_salary.cpp | 32 --------- bag_of_tokens.cpp | 27 -------- balanced_num.cpp | 55 --------------- basic_calculator.cpp | 37 ---------- basic_calculator.rs | 29 -------- best_buy_sell_stock.cpp | 31 --------- best_team_no_conflict.cpp | 28 -------- binary_search.cpp | 27 -------- binary_tree_factors.cpp | 31 --------- binary_tree_inorder.cpp | 23 ------- binary_tree_level_traverse.cpp | 31 --------- binary_tree_preorder.cpp | 28 -------- binary_tree_preorder.rs | 35 ---------- binary_tree_pruning.cpp | 15 ---- binary_tree_right_view.cpp | 24 ------- binary_tree_traversal.cpp | 24 ------- binary_tree_zigzag.cpp | 36 ---------- boats_save_people.cpp | 35 ---------- brainpower.cpp | 37 ---------- break_palindrom.cpp | 33 --------- browser_history.cpp | 45 ------------ bt_max_path_sum.cpp | 31 --------- bt_max_path_sum.rs | 38 ----------- buddy_strings.cpp | 46 ------------- build_matrix_conditions.cpp | 98 --------------------------- bulb_switcher.cpp | 19 ------ buy_sell_stock.cpp | 34 ---------- buy_sell_stock.rs | 33 --------- buy_sell_stock_fee.cpp | 35 ---------- can_place_flower.cpp | 35 ---------- candy.cpp | 37 ---------- capacity_ship_d_day.cpp | 50 -------------- cheapest_flight_k_stop.cpp | 46 ------------- check_complete_bt.cpp | 26 ------- check_existence_edge.cpp | 68 ------------------- check_knight_config.cpp | 59 ---------------- check_pangram_sentence.cpp | 19 ------ check_pangram_sentence.rs | 21 ------ check_straight_line.cpp | 35 ---------- check_string_cont_k.cpp | 30 -------- check_two_str_arr.cpp | 26 ------- check_two_str_arr.rs | 19 ------ check_valid_partition.cpp | 50 -------------- climbing_stairs.cpp | 31 --------- climbing_stairs.rs | 16 ----- clone_graph.cpp | 55 --------------- closest_node_2_nodes.cpp | 55 --------------- closest_node_2_nodes.rs | 45 ------------ coin_change.cpp | 22 ------ coin_change2.cpp | 31 --------- combination_sum3.cpp | 38 ----------- combination_sum4.cpp | 24 ------- combinations.cpp | 39 ----------- concatenated_words.cpp | 75 -------------------- concatenation_binary_num.cpp | 38 ----------- construct_array_multiple_sum.cpp | 30 -------- construct_bt_io_po.cpp | 31 --------- construct_quad_tree.cpp | 75 -------------------- construct_string_binary_tree.cpp | 21 ------ contains_duplicate2.cpp | 24 ------- contains_duplicate2.rs | 21 ------ contains_duplicate3.cpp | 52 -------------- contains_virus.cpp | 77 --------------------- continuous_subarr_sum.cpp | 31 --------- continuous_subarr_sum.rs | 24 ------- convert_sorted_bst.cpp | 29 -------- cost_hire_k_worker.cpp | 48 ------------- count_all_pickup_delivery.cpp | 23 ------- count_and_say.cpp | 26 ------- count_and_say.rs | 32 --------- count_complete_tree_node.cpp | 18 ----- count_complete_tree_node.rs | 51 -------------- count_distinct_int.cpp | 40 ----------- count_distinct_int.rs | 35 ---------- count_good_nodes_bst.cpp | 22 ------ count_ints_even_sum.cpp | 26 ------- count_negative_num_matrix.cpp | 37 ---------- count_odd_num_interval_range.cpp | 24 ------- count_possible_routes.cpp | 42 ------------ count_sorted_vowel.cpp | 20 ------ count_unreach_node.cpp | 48 ------------- count_vowels_permutation.cpp | 30 -------- count_ways_build_strs.cpp | 38 ----------- couples_holding_hands.cpp | 38 ----------- course_schedule.cpp | 44 ------------ course_schedule_3.cpp | 27 -------- create_bt_from_desc.cpp | 40 ----------- daily_temps.cpp | 28 -------- daily_temps.rs | 28 -------- data_stream_disjoint_interval.cpp | 45 ------------ decode_ways.cpp | 23 ------- decode_xor_array.cpp | 35 ---------- delete_col_sorted.cpp | 26 ------- delete_col_sorted.rs | 25 ------- delete_middle_node.cpp | 16 ----- delete_middle_node.rs | 52 -------------- delete_node_link_list.cpp | 10 --- delete_operation_2string.cpp | 26 ------- design_circular_queue.cpp | 53 --------------- design_food_rating_sys.cpp | 40 ----------- design_number_container.cpp | 39 ----------- design_parking_system.cpp | 40 ----------- design_underground_system.cpp | 20 ------ detect_capital.cpp | 21 ------ detect_capital.rs | 20 ------ determine_string_halves.cpp | 25 ------- determine_string_halves.rs | 18 ----- determine_strings_close.cpp | 28 -------- determine_strings_close.rs | 25 ------- detonate_max_bombs.cpp | 61 ----------------- diff_two_array.cpp | 35 ---------- discount_n_orders.cpp | 27 -------- divide_nodes_max_groups.cpp | 75 -------------------- domino_tromino_tiling.cpp | 28 -------- domino_tromino_tiling.rs | 20 ------ earliest_possible_full_bloom.cpp | 26 ------- earliest_possible_full_bloom.rs | 20 ------ edit_distance.cpp | 41 ----------- eliminate_monsters.cpp | 31 --------- encode_decode_tinyurl.cpp | 43 ------------ equal_row_col_pair.cpp | 34 ---------- erect_fence.cpp | 29 -------- erect_fence.rs | 27 -------- eval_reverse_polish_notation.cpp | 46 ------------- eval_reverse_polish_notation.rs | 29 -------- eventual_safe_states.cpp | 54 --------------- excel_sheet_column_title.cpp | 39 ----------- extra_char_string.cpp | 50 -------------- fair_distribution_cookie.cpp | 45 ------------ far_from_land.cpp | 44 ------------ fibonacci_number.cpp | 20 ------ find_all_anagrams.cpp | 40 ----------- find_building_alice_bob_meet.cpp | 59 ---------------- find_critical_edge_tree.cpp | 101 --------------------------- find_duplicate_file.cpp | 30 -------- find_duplicate_subtree.cpp | 30 -------- find_first_last_array.cpp | 22 ------ find_groups_farmland.cpp | 43 ------------ find_highest_altitude.cpp | 31 --------- find_k_beauty_num.cpp | 16 ----- find_k_closest_elements.cpp | 37 ---------- find_k_pair_sum.cpp | 50 -------------- find_max_sum_node_val.cpp | 43 ------------ find_median_data_stream.cpp | 29 -------- find_median_data_stream.rs | 41 ----------- find_orig_array_double.cpp | 19 ------ find_path_graph.cpp | 28 -------- find_path_graph.rs | 48 ------------- find_player_zero_one_loss.cpp | 21 ------ find_player_zero_one_loss.rs | 14 ---- find_replace_pattern.cpp | 32 --------- find_safest_path_grid.cpp | 89 ------------------------ find_score_arr_mark.cpp | 40 ----------- find_smallest_letter.cpp | 34 ---------- find_town_judge.cpp | 46 ------------- first_missing_positive.cpp | 12 ---- first_unique_char_string.cpp | 22 ------ flatten_binary_to_linked.cpp | 21 ------ flip_string_monotone_increase.cpp | 36 ---------- freedom_trail.cpp | 55 --------------- frog_jump.cpp | 47 ------------- fruit_into_baskets.cpp | 41 ----------- furthest_building_reach.cpp | 32 --------- gas_station.cpp | 25 ------- gas_station.rs | 26 ------- greatest_common_div_string.cpp | 36 ---------- greatest_sum_div_three.cpp | 43 ------------ group_anagrams.cpp | 18 ----- group_anagrams.rs | 15 ---- guess_number_high_low.cpp | 22 ------ guess_number_high_low.rs | 22 ------ hand_of_straights.cpp | 30 -------- happy_number.cpp | 37 ---------- house_robber.cpp | 21 ------ house_robber.rs | 18 ----- idx_first_occur_str.cpp | 51 -------------- image_overlap.cpp | 23 ------- image_overlap.rs | 35 ---------- implement_queue_stacks.cpp | 32 --------- increasing_triplet_subsequence.cpp | 26 ------- inform_employees.cpp | 44 ------------ insert_delete_getrandom.cpp | 45 ------------ insert_delete_getrandom.rs | 55 --------------- insert_interval.cpp | 39 ----------- int_roman.cpp | 22 ------ int_roman.rs | 26 ------- integer_break.cpp | 20 ------ interleaving_string.cpp | 39 ----------- invert_binary_tree.cpp | 26 ------- ipo.cpp | 52 -------------- is_graph_biparite.cpp | 52 -------------- jump_game.cpp | 24 ------- jump_game.rs | 18 ----- jump_game3.cpp | 27 -------- jump_game3.rs | 35 ---------- jump_game4.cpp | 52 -------------- jump_game6.cpp | 26 ------- k_inverse_pairs.cpp | 24 ------- k_radius_subarr.cpp | 45 ------------ keys_and_rooms.cpp | 32 --------- keys_and_rooms.rs | 23 ------- kids_max_num_candy.cpp | 42 ------------ knight_probability_chessboard.cpp | 41 ----------- koko_eating_bananas.cpp | 30 -------- kth_element_in_stream.cpp | 32 --------- kth_largest_element.cpp | 25 ------- kth_largest_element_stream.cpp | 43 ------------ kth_missing_pos_num.cpp | 30 -------- kth_smallest_lexicographical.cpp | 31 --------- kth_smallest_sorted_matrix.cpp | 30 -------- largest_colour_value_graph.cpp | 87 ------------------------ largest_int_add_target.cpp | 29 -------- largest_multiple_three.cpp | 37 ---------- largest_odd_num_string.cpp | 28 -------- largest_perimeter_triangle.cpp | 18 ----- last_day_cross.cpp | 62 ----------------- leaf_similar_trees.cpp | 28 -------- leaf_similar_trees.rs | 44 ------------ letter_combo_number.cpp | 32 --------- lexicographical_numbers.cpp | 43 ------------ lexicographically_small_string.cpp | 42 ------------ lfu_cache.cpp | 69 ------------------- linked_list_cycle2.cpp | 31 --------- linked_list_random.cpp | 40 ----------- longest_arithmetic_subseq.cpp | 37 ---------- longest_arithmetic_subseq_diff.cpp | 33 --------- longest_common_subseq.cpp | 20 ------ longest_common_subseq.rs | 23 ------- longest_consecutive_sequence.cpp | 36 ---------- longest_cycle_graph.cpp | 58 ---------------- longest_happy_string.cpp | 33 --------- longest_increasing_subseq.cpp | 48 ------------- longest_palindrome_concat.cpp | 29 -------- longest_palindrome_concat.rs | 39 ----------- longest_palindromic_subseq.cpp | 35 ---------- longest_palindromic_substr.cpp | 35 ---------- longest_path_diff_adjacent_char.cpp | 48 ------------- longest_path_diff_adjacent_char.rs | 77 --------------------- longest_string_chain.cpp | 34 ---------- longest_subarr_ones.cpp | 31 --------- longest_subseq_lim_sum.cpp | 31 --------- longest_subseq_lim_sum.rs | 17 ----- longest_substring_no_repeat.cpp | 29 -------- longest_valid_course.cpp | 49 -------------- longest_valid_parentheses.cpp | 41 ----------- longest_word_dict.cpp | 31 --------- longest_zigzag_bt.cpp | 46 ------------- lowest_common_ancestor.cpp | 33 --------- lowest_common_ancestor_bst.cpp | 17 ----- lru_cache.cpp | 60 ---------------- magnetic_force_2_balls.cpp | 46 ------------- make_array_increasing.cpp | 59 ---------------- make_string_great.cpp | 29 -------- make_string_great.rs | 21 ------ make_sum_divisible_p.cpp | 36 ---------- marbles_in_bags.cpp | 48 ------------- matchsticks_square.cpp | 46 ------------- matrix_diagonal_sum.cpp | 33 --------- max_69.cpp | 21 ------ max_69.rs | 11 --- max_area_cake.cpp | 25 ------- max_area_island.cpp | 24 ------- max_average_pass_ration.cpp | 57 ---------------- max_bags_rocks.cpp | 22 ------ max_bags_rocks.rs | 20 ------ max_consecutive_ones3.cpp | 27 -------- max_depth_binary_tree.cpp | 19 ------ max_diff_node_ancestor.cpp | 22 ------ max_diff_node_ancestor.rs | 61 ----------------- max_distance_closest_person.cpp | 39 ----------- max_erasure_value.cpp | 26 ------- max_ice_cream_bars.cpp | 39 ----------- max_ice_cream_bars.rs | 27 -------- max_len_concat_str.cpp | 30 -------- max_len_concat_str.rs | 29 -------- max_length_pair_chain.cpp | 33 --------- max_length_repeated_subarr.cpp | 26 ------- max_network_rank.cpp | 44 ------------ max_num_events_attended2.cpp | 46 ------------- max_num_ksum_pair.cpp | 22 ------ max_num_tasks_assign.cpp | 68 ------------------- max_num_vowel_substr.cpp | 30 -------- max_performance_team.cpp | 33 --------- max_points_from_cards.cpp | 23 ------- max_points_line.cpp | 50 -------------- max_points_line.rs | 91 ------------------------- max_product_3num.cpp | 40 ----------- max_product_split_bt.cpp | 19 ------ max_product_split_bt.rs | 43 ------------ max_product_word_len.cpp | 31 --------- max_profit_job.cpp | 28 -------- max_profit_job.rs | 30 -------- max_running_time_n_computer.cpp | 35 ---------- max_score_good_subarr.cpp | 36 ---------- max_score_mult_opp.cpp | 31 --------- max_score_n_operations.cpp | 59 ---------------- max_score_node_sequence.cpp | 43 ------------ max_subarray.cpp | 32 --------- max_subseq_score.cpp | 47 ------------- max_sum_3_noverlap_subarr.cpp | 57 ---------------- max_sum_binary_tree.cpp | 26 ------- max_sum_circular_subarr.cpp | 49 -------------- max_sum_rectangle.cpp | 33 --------- max_total_importance_road.cpp | 34 ---------- max_tranfer_requests.cpp | 46 ------------- max_twin_sum_list.cpp | 41 ----------- max_units_truck.cpp | 20 ------ max_val_k_coin_pile.cpp | 42 ------------ max_value_give_idx.cpp | 43 ------------ max_width_binary_tree.cpp | 40 ----------- maximise_confusion_exam.cpp | 41 ----------- maximise_grid_happiness.cpp | 66 ------------------ merge_sorted_array.cpp | 33 --------- merge_sorted_array.rs | 14 ---- merge_string_alt.cpp | 32 --------- middle_linked_list.cpp | 18 ----- middle_linked_list.rs | 28 -------- min_abs_diff_bst.cpp | 27 -------- min_ascii_strs.cpp | 38 ----------- min_avg_diff.cpp | 27 -------- min_avg_diff.rs | 23 ------- min_cost_arr_equal.cpp | 44 ------------ min_cost_change_expr.cpp | 40 ----------- min_cost_climbing_stairs.cpp | 16 ----- min_cost_convert_string1.cpp | 51 -------------- min_cost_cut_stick.cpp | 45 ------------ min_cost_ticket.cpp | 42 ------------ min_deletions_unique_char.cpp | 28 -------- min_depth_binary_tree.cpp | 34 ---------- min_deviation_arr.cpp | 36 ---------- min_difficulty_schedule.cpp | 36 ---------- min_dist_bst_node.cpp | 20 ------ min_dist_target_element.cpp | 20 ------ min_falling_path_sum.cpp | 45 ------------ min_falling_path_sum.rs | 23 ------- min_flips_abc.cpp | 22 ------ min_fuel_report_captial.cpp | 50 -------------- min_genetic_mutation.cpp | 33 --------- min_genetic_mutation.rs | 53 --------------- min_incr_arr_unique.cpp | 32 --------- min_insertion_make_palindrome.cpp | 32 --------- min_jump_reach_home.cpp | 44 ------------ min_max_array.cpp | 43 ------------ min_max_diff_pair.cpp | 47 ------------- min_move_palindrome.cpp | 34 ---------- min_moves_equal_array2.cpp | 18 ----- min_num_arrow_balloon.cpp | 30 -------- min_num_arrow_balloon.rs | 20 ------ min_num_days_disconnect_island.cpp | 62 ----------------- min_num_opp_arr_cont.cpp | 22 ------ min_num_refueling_stops.cpp | 22 ------ min_num_remove_mountain_arr.cpp | 51 -------------- min_num_vertices_node.cpp | 34 ---------- min_one_bit_0.cpp | 18 ----- min_one_bit_0.rs | 29 -------- min_operations_x_zero.cpp | 27 -------- min_path_sum.cpp | 29 -------- min_rounds_complete_all_tasks.cpp | 27 -------- min_rounds_complete_all_tasks.rs | 30 -------- min_score_path_city.cpp | 32 --------- min_size_subarr_sum.cpp | 32 --------- min_speed_arrive_time.cpp | 47 ------------- min_stack.cpp | 23 ------- min_swap_group_1.cpp | 40 ----------- min_time_apples_tree.cpp | 39 ----------- min_time_apples_tree.rs | 47 ------------- min_time_complete_trip.cpp | 36 ---------- min_time_rope_colorful.cpp | 25 ------- min_time_visit_cell_grid.cpp | 52 -------------- min_window_substring.cpp | 37 ---------- min_window_substring.rs | 43 ------------ mirror_reflection.cpp | 21 ------ missing_number.cpp | 18 ----- modify_graph_edge_weight.cpp | 91 ------------------------- most_stones_remove.cpp | 47 ------------- most_stones_remove.rs | 69 ------------------- most_water.cpp | 21 ------ my_calendar.cpp | 31 --------- my_calendar2.cpp | 56 --------------- my_calendar3.cpp | 21 ------ n_ary_tree_traverse.cpp | 25 ------- n_queens2.cpp | 35 ---------- naming_company.cpp | 37 ---------- nearest_exit_maze.cpp | 37 ---------- nearest_exit_maze.rs | 37 ---------- new_21_game.cpp | 40 ----------- next_greater_element2.cpp | 43 ------------ next_permutation.cpp | 37 ---------- non_decreasing_array.cpp | 27 -------- non_decreasing_subseq.cpp | 46 ------------- non_overlapping_interval.cpp | 38 ----------- nth_tribonacci_number.cpp | 61 ----------------- num_bad_pairs.cpp | 28 -------- num_bad_pairs.rs | 30 -------- num_closed_islands.cpp | 61 ----------------- num_cut_pizza.cpp | 58 ---------------- num_dice_roll_target_sum.cpp | 21 ------ num_enclaves.cpp | 45 ------------ num_even_nums.cpp | 29 -------- num_good_path.cpp | 75 -------------------- num_increasing_path.cpp | 54 --------------- num_longest_incr_subseq.cpp | 53 --------------- num_matching_subsequence.cpp | 34 ---------- num_music_playlists.cpp | 40 ----------- num_nodes_sub_tree.cpp | 47 ------------- num_nodes_sub_tree.rs | 39 ----------- num_op_connect_network.cpp | 41 ----------- num_people_aware_secret.cpp | 27 -------- num_same_consecutive_diff.cpp | 32 --------- num_smaller_num_self.cpp | 44 ------------ num_squareful_arrays.cpp | 59 ---------------- num_subseq_satisfy.cpp | 34 ---------- num_to_hex_binary.cpp | 55 --------------- num_valid_words_puzzle.cpp | 40 ----------- num_ways_dict.cpp | 35 ---------- num_ways_remain_place.cpp | 32 --------- num_ways_reorder_array.cpp | 57 ---------------- num_weak_char_game.cpp | 23 ------- num_zero_filled_subarr.cpp | 29 -------- number_1bits.cpp | 20 ------ number_atoms.cpp | 75 -------------------- number_islands.cpp | 30 -------- number_provinces.cpp | 41 ----------- number_steps_to_0.cpp | 20 ------ number_submatrices_sum_target.cpp | 24 ------- odd_even_linke_list.cpp | 22 ------ odd_even_linke_list.rs | 38 ----------- ones_and_zeroes.cpp | 36 ---------- online_stock_span.cpp | 43 ------------ online_stock_span.rs | 51 -------------- optimal_partition_string.cpp | 31 --------- orderly_queue.cpp | 20 ------ orderly_queue.rs | 22 ------ other/01_matrix.cpp | 34 ++++++++++ other/132_pattern.cpp | 32 +++++++++ other/3sum_closest.cpp | 31 +++++++++ other/add_arr_form_int.cpp | 44 ++++++++++++ other/add_binary.cpp | 30 ++++++++ other/add_digits.cpp | 26 +++++++ other/add_row_tree.cpp | 29 ++++++++ other/add_search_words_data.cpp | 35 ++++++++++ other/add_space_string.cpp | 36 ++++++++++ other/add_two_num2.cpp | 56 +++++++++++++++ other/additive_number.cpp | 54 +++++++++++++++ other/all_nodes_binary_tree.cpp | 53 +++++++++++++++ other/all_path_src_target.cpp | 30 ++++++++ other/all_path_src_target.rs | 54 +++++++++++++++ other/all_possible_full_tree.cpp | 40 +++++++++++ other/alphabet_board_path.cpp | 44 ++++++++++++ other/ancestors_node_acyclic_graph.cpp | 58 ++++++++++++++++ other/arithmetic_progression.cpp | 44 ++++++++++++ other/arithmetic_slices2.cpp | 35 ++++++++++ other/arithmetic_slices2.rs | 30 ++++++++ other/asteroid_collision.cpp | 52 ++++++++++++++ other/avg_levels_bst.cpp | 24 +++++++ other/avg_salary.cpp | 32 +++++++++ other/bag_of_tokens.cpp | 27 ++++++++ other/balanced_num.cpp | 55 +++++++++++++++ other/basic_calculator.cpp | 37 ++++++++++ other/basic_calculator.rs | 29 ++++++++ other/best_buy_sell_stock.cpp | 31 +++++++++ other/best_team_no_conflict.cpp | 28 ++++++++ other/binary_search.cpp | 27 ++++++++ other/binary_tree_factors.cpp | 31 +++++++++ other/binary_tree_inorder.cpp | 23 +++++++ other/binary_tree_level_traverse.cpp | 31 +++++++++ other/binary_tree_preorder.cpp | 28 ++++++++ other/binary_tree_preorder.rs | 35 ++++++++++ other/binary_tree_pruning.cpp | 15 ++++ other/binary_tree_right_view.cpp | 24 +++++++ other/binary_tree_traversal.cpp | 24 +++++++ other/binary_tree_zigzag.cpp | 36 ++++++++++ other/boats_save_people.cpp | 35 ++++++++++ other/brainpower.cpp | 37 ++++++++++ other/break_palindrom.cpp | 33 +++++++++ other/browser_history.cpp | 45 ++++++++++++ other/bt_max_path_sum.cpp | 31 +++++++++ other/bt_max_path_sum.rs | 38 +++++++++++ other/buddy_strings.cpp | 46 +++++++++++++ other/build_matrix_conditions.cpp | 98 +++++++++++++++++++++++++++ other/bulb_switcher.cpp | 19 ++++++ other/buy_sell_stock.cpp | 34 ++++++++++ other/buy_sell_stock.rs | 33 +++++++++ other/buy_sell_stock_fee.cpp | 35 ++++++++++ other/can_place_flower.cpp | 35 ++++++++++ other/candy.cpp | 37 ++++++++++ other/capacity_ship_d_day.cpp | 50 ++++++++++++++ other/cheapest_flight_k_stop.cpp | 46 +++++++++++++ other/check_complete_bt.cpp | 26 +++++++ other/check_existence_edge.cpp | 68 +++++++++++++++++++ other/check_knight_config.cpp | 59 ++++++++++++++++ other/check_pangram_sentence.cpp | 19 ++++++ other/check_pangram_sentence.rs | 21 ++++++ other/check_straight_line.cpp | 35 ++++++++++ other/check_string_cont_k.cpp | 30 ++++++++ other/check_two_str_arr.cpp | 26 +++++++ other/check_two_str_arr.rs | 19 ++++++ other/check_valid_partition.cpp | 50 ++++++++++++++ other/climbing_stairs.cpp | 31 +++++++++ other/climbing_stairs.rs | 16 +++++ other/clone_graph.cpp | 55 +++++++++++++++ other/closest_node_2_nodes.cpp | 55 +++++++++++++++ other/closest_node_2_nodes.rs | 45 ++++++++++++ other/coin_change.cpp | 22 ++++++ other/coin_change2.cpp | 31 +++++++++ other/combination_sum3.cpp | 38 +++++++++++ other/combination_sum4.cpp | 24 +++++++ other/combinations.cpp | 39 +++++++++++ other/concatenated_words.cpp | 75 ++++++++++++++++++++ other/concatenation_binary_num.cpp | 38 +++++++++++ other/construct_array_multiple_sum.cpp | 30 ++++++++ other/construct_bt_io_po.cpp | 31 +++++++++ other/construct_quad_tree.cpp | 75 ++++++++++++++++++++ other/construct_string_binary_tree.cpp | 21 ++++++ other/contains_duplicate2.cpp | 24 +++++++ other/contains_duplicate2.rs | 21 ++++++ other/contains_duplicate3.cpp | 52 ++++++++++++++ other/contains_virus.cpp | 77 +++++++++++++++++++++ other/continuous_subarr_sum.cpp | 31 +++++++++ other/continuous_subarr_sum.rs | 24 +++++++ other/convert_sorted_bst.cpp | 29 ++++++++ other/cost_hire_k_worker.cpp | 48 +++++++++++++ other/count_all_pickup_delivery.cpp | 23 +++++++ other/count_and_say.cpp | 26 +++++++ other/count_and_say.rs | 32 +++++++++ other/count_complete_tree_node.cpp | 18 +++++ other/count_complete_tree_node.rs | 51 ++++++++++++++ other/count_distinct_int.cpp | 40 +++++++++++ other/count_distinct_int.rs | 35 ++++++++++ other/count_good_nodes_bst.cpp | 22 ++++++ other/count_ints_even_sum.cpp | 26 +++++++ other/count_negative_num_matrix.cpp | 37 ++++++++++ other/count_odd_num_interval_range.cpp | 24 +++++++ other/count_possible_routes.cpp | 42 ++++++++++++ other/count_sorted_vowel.cpp | 20 ++++++ other/count_unreach_node.cpp | 48 +++++++++++++ other/count_vowels_permutation.cpp | 30 ++++++++ other/count_ways_build_strs.cpp | 38 +++++++++++ other/couples_holding_hands.cpp | 38 +++++++++++ other/course_schedule.cpp | 44 ++++++++++++ other/course_schedule_3.cpp | 27 ++++++++ other/create_bt_from_desc.cpp | 40 +++++++++++ other/daily_temps.cpp | 28 ++++++++ other/daily_temps.rs | 28 ++++++++ other/data_stream_disjoint_interval.cpp | 45 ++++++++++++ other/decode_ways.cpp | 23 +++++++ other/decode_xor_array.cpp | 35 ++++++++++ other/delete_col_sorted.cpp | 26 +++++++ other/delete_col_sorted.rs | 25 +++++++ other/delete_middle_node.cpp | 16 +++++ other/delete_middle_node.rs | 52 ++++++++++++++ other/delete_node_link_list.cpp | 10 +++ other/delete_operation_2string.cpp | 26 +++++++ other/design_circular_queue.cpp | 53 +++++++++++++++ other/design_food_rating_sys.cpp | 40 +++++++++++ other/design_number_container.cpp | 39 +++++++++++ other/design_parking_system.cpp | 40 +++++++++++ other/design_underground_system.cpp | 20 ++++++ other/detect_capital.cpp | 21 ++++++ other/detect_capital.rs | 20 ++++++ other/determine_string_halves.cpp | 25 +++++++ other/determine_string_halves.rs | 18 +++++ other/determine_strings_close.cpp | 28 ++++++++ other/determine_strings_close.rs | 25 +++++++ other/detonate_max_bombs.cpp | 61 +++++++++++++++++ other/diff_two_array.cpp | 35 ++++++++++ other/discount_n_orders.cpp | 27 ++++++++ other/divide_nodes_max_groups.cpp | 75 ++++++++++++++++++++ other/domino_tromino_tiling.cpp | 28 ++++++++ other/domino_tromino_tiling.rs | 20 ++++++ other/earliest_possible_full_bloom.cpp | 26 +++++++ other/earliest_possible_full_bloom.rs | 20 ++++++ other/edit_distance.cpp | 41 +++++++++++ other/eliminate_monsters.cpp | 31 +++++++++ other/encode_decode_tinyurl.cpp | 43 ++++++++++++ other/equal_row_col_pair.cpp | 34 ++++++++++ other/erect_fence.cpp | 29 ++++++++ other/erect_fence.rs | 27 ++++++++ other/eval_reverse_polish_notation.cpp | 46 +++++++++++++ other/eval_reverse_polish_notation.rs | 29 ++++++++ other/eventual_safe_states.cpp | 54 +++++++++++++++ other/excel_sheet_column_title.cpp | 39 +++++++++++ other/extra_char_string.cpp | 50 ++++++++++++++ other/fair_distribution_cookie.cpp | 45 ++++++++++++ other/far_from_land.cpp | 44 ++++++++++++ other/fibonacci_number.cpp | 20 ++++++ other/find_all_anagrams.cpp | 40 +++++++++++ other/find_building_alice_bob_meet.cpp | 59 ++++++++++++++++ other/find_critical_edge_tree.cpp | 101 +++++++++++++++++++++++++++ other/find_duplicate_file.cpp | 30 ++++++++ other/find_duplicate_subtree.cpp | 30 ++++++++ other/find_first_last_array.cpp | 22 ++++++ other/find_groups_farmland.cpp | 43 ++++++++++++ other/find_highest_altitude.cpp | 31 +++++++++ other/find_k_beauty_num.cpp | 16 +++++ other/find_k_closest_elements.cpp | 37 ++++++++++ other/find_k_pair_sum.cpp | 50 ++++++++++++++ other/find_max_sum_node_val.cpp | 43 ++++++++++++ other/find_median_data_stream.cpp | 29 ++++++++ other/find_median_data_stream.rs | 41 +++++++++++ other/find_orig_array_double.cpp | 19 ++++++ other/find_path_graph.cpp | 28 ++++++++ other/find_path_graph.rs | 48 +++++++++++++ other/find_player_zero_one_loss.cpp | 21 ++++++ other/find_player_zero_one_loss.rs | 14 ++++ other/find_replace_pattern.cpp | 32 +++++++++ other/find_safest_path_grid.cpp | 89 ++++++++++++++++++++++++ other/find_score_arr_mark.cpp | 40 +++++++++++ other/find_smallest_letter.cpp | 34 ++++++++++ other/find_town_judge.cpp | 46 +++++++++++++ other/first_missing_positive.cpp | 12 ++++ other/first_unique_char_string.cpp | 22 ++++++ other/flatten_binary_to_linked.cpp | 21 ++++++ other/flip_string_monotone_increase.cpp | 36 ++++++++++ other/freedom_trail.cpp | 55 +++++++++++++++ other/frog_jump.cpp | 47 +++++++++++++ other/fruit_into_baskets.cpp | 41 +++++++++++ other/furthest_building_reach.cpp | 32 +++++++++ other/gas_station.cpp | 25 +++++++ other/gas_station.rs | 26 +++++++ other/greatest_common_div_string.cpp | 36 ++++++++++ other/greatest_sum_div_three.cpp | 43 ++++++++++++ other/group_anagrams.cpp | 18 +++++ other/group_anagrams.rs | 15 ++++ other/guess_number_high_low.cpp | 22 ++++++ other/guess_number_high_low.rs | 22 ++++++ other/hand_of_straights.cpp | 30 ++++++++ other/happy_number.cpp | 37 ++++++++++ other/house_robber.cpp | 21 ++++++ other/house_robber.rs | 18 +++++ other/idx_first_occur_str.cpp | 51 ++++++++++++++ other/image_overlap.cpp | 23 +++++++ other/image_overlap.rs | 35 ++++++++++ other/implement_queue_stacks.cpp | 32 +++++++++ other/increasing_triplet_subsequence.cpp | 26 +++++++ other/inform_employees.cpp | 44 ++++++++++++ other/insert_delete_getrandom.cpp | 45 ++++++++++++ other/insert_delete_getrandom.rs | 55 +++++++++++++++ other/insert_interval.cpp | 39 +++++++++++ other/int_roman.cpp | 22 ++++++ other/int_roman.rs | 26 +++++++ other/integer_break.cpp | 20 ++++++ other/interleaving_string.cpp | 39 +++++++++++ other/invert_binary_tree.cpp | 26 +++++++ other/ipo.cpp | 52 ++++++++++++++ other/is_graph_biparite.cpp | 52 ++++++++++++++ other/jump_game.cpp | 24 +++++++ other/jump_game.rs | 18 +++++ other/jump_game3.cpp | 27 ++++++++ other/jump_game3.rs | 35 ++++++++++ other/jump_game4.cpp | 52 ++++++++++++++ other/jump_game6.cpp | 26 +++++++ other/k_inverse_pairs.cpp | 24 +++++++ other/k_radius_subarr.cpp | 45 ++++++++++++ other/keys_and_rooms.cpp | 32 +++++++++ other/keys_and_rooms.rs | 23 +++++++ other/kids_max_num_candy.cpp | 42 ++++++++++++ other/knight_probability_chessboard.cpp | 41 +++++++++++ other/koko_eating_bananas.cpp | 30 ++++++++ other/kth_element_in_stream.cpp | 32 +++++++++ other/kth_largest_element.cpp | 25 +++++++ other/kth_largest_element_stream.cpp | 43 ++++++++++++ other/kth_missing_pos_num.cpp | 30 ++++++++ other/kth_smallest_lexicographical.cpp | 31 +++++++++ other/kth_smallest_sorted_matrix.cpp | 30 ++++++++ other/largest_colour_value_graph.cpp | 87 ++++++++++++++++++++++++ other/largest_int_add_target.cpp | 29 ++++++++ other/largest_multiple_three.cpp | 37 ++++++++++ other/largest_odd_num_string.cpp | 28 ++++++++ other/largest_perimeter_triangle.cpp | 18 +++++ other/last_day_cross.cpp | 62 +++++++++++++++++ other/leaf_similar_trees.cpp | 28 ++++++++ other/leaf_similar_trees.rs | 44 ++++++++++++ other/letter_combo_number.cpp | 32 +++++++++ other/lexicographical_numbers.cpp | 43 ++++++++++++ other/lexicographically_small_string.cpp | 42 ++++++++++++ other/lfu_cache.cpp | 69 +++++++++++++++++++ other/linked_list_cycle2.cpp | 31 +++++++++ other/linked_list_random.cpp | 40 +++++++++++ other/longest_arithmetic_subseq.cpp | 37 ++++++++++ other/longest_arithmetic_subseq_diff.cpp | 33 +++++++++ other/longest_common_subseq.cpp | 20 ++++++ other/longest_common_subseq.rs | 23 +++++++ other/longest_consecutive_sequence.cpp | 36 ++++++++++ other/longest_cycle_graph.cpp | 58 ++++++++++++++++ other/longest_happy_string.cpp | 33 +++++++++ other/longest_increasing_subseq.cpp | 48 +++++++++++++ other/longest_palindrome_concat.cpp | 29 ++++++++ other/longest_palindrome_concat.rs | 39 +++++++++++ other/longest_palindromic_subseq.cpp | 35 ++++++++++ other/longest_palindromic_substr.cpp | 35 ++++++++++ other/longest_path_diff_adjacent_char.cpp | 48 +++++++++++++ other/longest_path_diff_adjacent_char.rs | 77 +++++++++++++++++++++ other/longest_string_chain.cpp | 34 ++++++++++ other/longest_subarr_ones.cpp | 31 +++++++++ other/longest_subseq_lim_sum.cpp | 31 +++++++++ other/longest_subseq_lim_sum.rs | 17 +++++ other/longest_substring_no_repeat.cpp | 29 ++++++++ other/longest_valid_course.cpp | 49 ++++++++++++++ other/longest_valid_parentheses.cpp | 41 +++++++++++ other/longest_word_dict.cpp | 31 +++++++++ other/longest_zigzag_bt.cpp | 46 +++++++++++++ other/lowest_common_ancestor.cpp | 33 +++++++++ other/lowest_common_ancestor_bst.cpp | 17 +++++ other/lru_cache.cpp | 60 ++++++++++++++++ other/magnetic_force_2_balls.cpp | 46 +++++++++++++ other/make_array_increasing.cpp | 59 ++++++++++++++++ other/make_string_great.cpp | 29 ++++++++ other/make_string_great.rs | 21 ++++++ other/make_sum_divisible_p.cpp | 36 ++++++++++ other/marbles_in_bags.cpp | 48 +++++++++++++ other/matchsticks_square.cpp | 46 +++++++++++++ other/matrix_diagonal_sum.cpp | 33 +++++++++ other/max_69.cpp | 21 ++++++ other/max_69.rs | 11 +++ other/max_area_cake.cpp | 25 +++++++ other/max_area_island.cpp | 24 +++++++ other/max_average_pass_ration.cpp | 57 ++++++++++++++++ other/max_bags_rocks.cpp | 22 ++++++ other/max_bags_rocks.rs | 20 ++++++ other/max_consecutive_ones3.cpp | 27 ++++++++ other/max_depth_binary_tree.cpp | 19 ++++++ other/max_diff_node_ancestor.cpp | 22 ++++++ other/max_diff_node_ancestor.rs | 61 +++++++++++++++++ other/max_distance_closest_person.cpp | 39 +++++++++++ other/max_erasure_value.cpp | 26 +++++++ other/max_ice_cream_bars.cpp | 39 +++++++++++ other/max_ice_cream_bars.rs | 27 ++++++++ other/max_len_concat_str.cpp | 30 ++++++++ other/max_len_concat_str.rs | 29 ++++++++ other/max_length_pair_chain.cpp | 33 +++++++++ other/max_length_repeated_subarr.cpp | 26 +++++++ other/max_network_rank.cpp | 44 ++++++++++++ other/max_num_events_attended2.cpp | 46 +++++++++++++ other/max_num_ksum_pair.cpp | 22 ++++++ other/max_num_tasks_assign.cpp | 68 +++++++++++++++++++ other/max_num_vowel_substr.cpp | 30 ++++++++ other/max_performance_team.cpp | 33 +++++++++ other/max_points_from_cards.cpp | 23 +++++++ other/max_points_line.cpp | 50 ++++++++++++++ other/max_points_line.rs | 91 +++++++++++++++++++++++++ other/max_product_3num.cpp | 40 +++++++++++ other/max_product_split_bt.cpp | 19 ++++++ other/max_product_split_bt.rs | 43 ++++++++++++ other/max_product_word_len.cpp | 31 +++++++++ other/max_profit_job.cpp | 28 ++++++++ other/max_profit_job.rs | 30 ++++++++ other/max_running_time_n_computer.cpp | 35 ++++++++++ other/max_score_good_subarr.cpp | 36 ++++++++++ other/max_score_mult_opp.cpp | 31 +++++++++ other/max_score_n_operations.cpp | 59 ++++++++++++++++ other/max_score_node_sequence.cpp | 43 ++++++++++++ other/max_subarray.cpp | 32 +++++++++ other/max_subseq_score.cpp | 47 +++++++++++++ other/max_sum_3_noverlap_subarr.cpp | 57 ++++++++++++++++ other/max_sum_binary_tree.cpp | 26 +++++++ other/max_sum_circular_subarr.cpp | 49 ++++++++++++++ other/max_sum_rectangle.cpp | 33 +++++++++ other/max_total_importance_road.cpp | 34 ++++++++++ other/max_tranfer_requests.cpp | 46 +++++++++++++ other/max_twin_sum_list.cpp | 41 +++++++++++ other/max_units_truck.cpp | 20 ++++++ other/max_val_k_coin_pile.cpp | 42 ++++++++++++ other/max_value_give_idx.cpp | 43 ++++++++++++ other/max_width_binary_tree.cpp | 40 +++++++++++ other/maximise_confusion_exam.cpp | 41 +++++++++++ other/maximise_grid_happiness.cpp | 66 ++++++++++++++++++ other/merge_sorted_array.cpp | 33 +++++++++ other/merge_sorted_array.rs | 14 ++++ other/merge_string_alt.cpp | 32 +++++++++ other/middle_linked_list.cpp | 18 +++++ other/middle_linked_list.rs | 28 ++++++++ other/min_abs_diff_bst.cpp | 27 ++++++++ other/min_ascii_strs.cpp | 38 +++++++++++ other/min_avg_diff.cpp | 27 ++++++++ other/min_avg_diff.rs | 23 +++++++ other/min_cost_arr_equal.cpp | 44 ++++++++++++ other/min_cost_change_expr.cpp | 40 +++++++++++ other/min_cost_climbing_stairs.cpp | 16 +++++ other/min_cost_convert_string1.cpp | 51 ++++++++++++++ other/min_cost_cut_stick.cpp | 45 ++++++++++++ other/min_cost_ticket.cpp | 42 ++++++++++++ other/min_deletions_unique_char.cpp | 28 ++++++++ other/min_depth_binary_tree.cpp | 34 ++++++++++ other/min_deviation_arr.cpp | 36 ++++++++++ other/min_difficulty_schedule.cpp | 36 ++++++++++ other/min_dist_bst_node.cpp | 20 ++++++ other/min_dist_target_element.cpp | 20 ++++++ other/min_falling_path_sum.cpp | 45 ++++++++++++ other/min_falling_path_sum.rs | 23 +++++++ other/min_flips_abc.cpp | 22 ++++++ other/min_fuel_report_captial.cpp | 50 ++++++++++++++ other/min_genetic_mutation.cpp | 33 +++++++++ other/min_genetic_mutation.rs | 53 +++++++++++++++ other/min_incr_arr_unique.cpp | 32 +++++++++ other/min_insertion_make_palindrome.cpp | 32 +++++++++ other/min_jump_reach_home.cpp | 44 ++++++++++++ other/min_max_array.cpp | 43 ++++++++++++ other/min_max_diff_pair.cpp | 47 +++++++++++++ other/min_move_palindrome.cpp | 34 ++++++++++ other/min_moves_equal_array2.cpp | 18 +++++ other/min_num_arrow_balloon.cpp | 30 ++++++++ other/min_num_arrow_balloon.rs | 20 ++++++ other/min_num_days_disconnect_island.cpp | 62 +++++++++++++++++ other/min_num_opp_arr_cont.cpp | 22 ++++++ other/min_num_refueling_stops.cpp | 22 ++++++ other/min_num_remove_mountain_arr.cpp | 51 ++++++++++++++ other/min_num_vertices_node.cpp | 34 ++++++++++ other/min_one_bit_0.cpp | 18 +++++ other/min_one_bit_0.rs | 29 ++++++++ other/min_operations_x_zero.cpp | 27 ++++++++ other/min_path_sum.cpp | 29 ++++++++ other/min_rounds_complete_all_tasks.cpp | 27 ++++++++ other/min_rounds_complete_all_tasks.rs | 30 ++++++++ other/min_score_path_city.cpp | 32 +++++++++ other/min_size_subarr_sum.cpp | 32 +++++++++ other/min_speed_arrive_time.cpp | 47 +++++++++++++ other/min_stack.cpp | 23 +++++++ other/min_swap_group_1.cpp | 40 +++++++++++ other/min_time_apples_tree.cpp | 39 +++++++++++ other/min_time_apples_tree.rs | 47 +++++++++++++ other/min_time_complete_trip.cpp | 36 ++++++++++ other/min_time_rope_colorful.cpp | 25 +++++++ other/min_time_visit_cell_grid.cpp | 52 ++++++++++++++ other/min_window_substring.cpp | 37 ++++++++++ other/min_window_substring.rs | 43 ++++++++++++ other/mirror_reflection.cpp | 21 ++++++ other/missing_number.cpp | 18 +++++ other/modify_graph_edge_weight.cpp | 91 +++++++++++++++++++++++++ other/most_stones_remove.cpp | 47 +++++++++++++ other/most_stones_remove.rs | 69 +++++++++++++++++++ other/most_water.cpp | 21 ++++++ other/my_calendar.cpp | 31 +++++++++ other/my_calendar2.cpp | 56 +++++++++++++++ other/my_calendar3.cpp | 21 ++++++ other/n_ary_tree_traverse.cpp | 25 +++++++ other/n_queens2.cpp | 35 ++++++++++ other/naming_company.cpp | 37 ++++++++++ other/nearest_exit_maze.cpp | 37 ++++++++++ other/nearest_exit_maze.rs | 37 ++++++++++ other/new_21_game.cpp | 40 +++++++++++ other/next_greater_element2.cpp | 43 ++++++++++++ other/next_permutation.cpp | 37 ++++++++++ other/non_decreasing_array.cpp | 27 ++++++++ other/non_decreasing_subseq.cpp | 46 +++++++++++++ other/non_overlapping_interval.cpp | 38 +++++++++++ other/nth_tribonacci_number.cpp | 61 +++++++++++++++++ other/num_bad_pairs.cpp | 28 ++++++++ other/num_bad_pairs.rs | 30 ++++++++ other/num_closed_islands.cpp | 61 +++++++++++++++++ other/num_cut_pizza.cpp | 58 ++++++++++++++++ other/num_dice_roll_target_sum.cpp | 21 ++++++ other/num_enclaves.cpp | 45 ++++++++++++ other/num_even_nums.cpp | 29 ++++++++ other/num_good_path.cpp | 75 ++++++++++++++++++++ other/num_increasing_path.cpp | 54 +++++++++++++++ other/num_longest_incr_subseq.cpp | 53 +++++++++++++++ other/num_matching_subsequence.cpp | 34 ++++++++++ other/num_music_playlists.cpp | 40 +++++++++++ other/num_nodes_sub_tree.cpp | 47 +++++++++++++ other/num_nodes_sub_tree.rs | 39 +++++++++++ other/num_op_connect_network.cpp | 41 +++++++++++ other/num_people_aware_secret.cpp | 27 ++++++++ other/num_same_consecutive_diff.cpp | 32 +++++++++ other/num_smaller_num_self.cpp | 44 ++++++++++++ other/num_squareful_arrays.cpp | 59 ++++++++++++++++ other/num_subseq_satisfy.cpp | 34 ++++++++++ other/num_to_hex_binary.cpp | 55 +++++++++++++++ other/num_valid_words_puzzle.cpp | 40 +++++++++++ other/num_ways_dict.cpp | 35 ++++++++++ other/num_ways_remain_place.cpp | 32 +++++++++ other/num_ways_reorder_array.cpp | 57 ++++++++++++++++ other/num_weak_char_game.cpp | 23 +++++++ other/num_zero_filled_subarr.cpp | 29 ++++++++ other/number_1bits.cpp | 20 ++++++ other/number_atoms.cpp | 75 ++++++++++++++++++++ other/number_islands.cpp | 30 ++++++++ other/number_provinces.cpp | 41 +++++++++++ other/number_steps_to_0.cpp | 20 ++++++ other/number_submatrices_sum_target.cpp | 24 +++++++ other/odd_even_linke_list.cpp | 22 ++++++ other/odd_even_linke_list.rs | 38 +++++++++++ other/ones_and_zeroes.cpp | 36 ++++++++++ other/online_stock_span.cpp | 43 ++++++++++++ other/online_stock_span.rs | 51 ++++++++++++++ other/optimal_partition_string.cpp | 31 +++++++++ other/orderly_queue.cpp | 20 ++++++ other/orderly_queue.rs | 22 ++++++ other/out_of_bounds_paths.cpp | 35 ++++++++++ other/pacific_atlantic_water_flow.cpp | 38 +++++++++++ other/paint_house3.cpp | 34 ++++++++++ other/painting_grid_three_colour.cpp | 58 ++++++++++++++++ other/painting_walls.cpp | 50 ++++++++++++++ other/pairs_spells_potions.cpp | 45 ++++++++++++ other/palindrome_linked_list.cpp | 32 +++++++++ other/palindrome_number.rs | 24 +++++++ other/palindrome_pairs.cpp | 38 +++++++++++ other/palindrome_partitioning.cpp | 50 ++++++++++++++ other/parallel_courses3.cpp | 54 +++++++++++++++ other/partition_array_max_sum.cpp | 36 ++++++++++ other/partition_array_pivot.rs | 32 +++++++++ other/partition_list.cpp | 20 ++++++ other/partition_min_binary_array.cpp | 18 +++++ other/pascals_triangle.cpp | 19 ++++++ other/path_max_probability.cpp | 52 ++++++++++++++ other/path_min_effort.cpp | 34 ++++++++++ other/path_min_effort1.cpp | 42 ++++++++++++ other/path_sum.cpp | 23 +++++++ other/path_sum2.cpp | 25 +++++++ other/peak_idx_mountain_arr.cpp | 25 +++++++ other/peeking_iterator.cpp | 32 +++++++++ other/percentage_letter_string.cpp | 20 ++++++ other/perfect_squares.cpp | 23 +++++++ other/perfect_squares.rs | 21 ++++++ other/permutation_in_string.cpp | 47 +++++++++++++ other/permutation_sequence.cpp | 25 +++++++ other/permutations.cpp | 26 +++++++ other/permutations2.cpp | 29 ++++++++ other/poor-pigs.cpp | 8 +++ other/possible_bipartition.cpp | 45 ++++++++++++ other/possible_bipartition.rs | 40 +++++++++++ other/power_3.cpp | 19 ++++++ other/power_of_four.cpp | 24 +++++++ other/power_of_four.rs | 24 +++++++ other/power_of_two.cpp | 11 +++ other/predict_winner.cpp | 40 +++++++++++ other/prefix_suffix_search.cpp | 26 +++++++ other/profitable_schemes.cpp | 71 +++++++++++++++++++ other/pseudo_palindrome_binary_tree.cpp | 29 ++++++++ other/push_dominoes.cpp | 31 +++++++++ other/queue_reconstruction.cpp | 20 ++++++ other/range_sum_bst.cpp | 22 ++++++ other/range_sum_bst.rs | 38 +++++++++++ other/range_sum_query_2d.cpp | 40 +++++++++++ other/range_sum_query_mutable.cpp | 61 +++++++++++++++++ other/ransom_note.cpp | 23 +++++++ other/rectangle_area.cpp | 16 +++++ other/rectangle_area.rs | 14 ++++ other/rectangle_fewest_squares.cpp | 51 ++++++++++++++ other/reduce_array_size_half.cpp | 30 ++++++++ other/reducing_dishes.cpp | 37 ++++++++++ other/remove_adjacent_dup.cpp | 37 ++++++++++ other/remove_adjacent_dup_str.cpp | 20 ++++++ other/remove_adjacent_dup_str.rs | 20 ++++++ other/remove_boxes.cpp | 40 +++++++++++ other/remove_dupplicate.cpp | 22 ++++++ other/remove_dupplicate.rs | 24 +++++++ other/remove_element.cpp | 28 ++++++++ other/remove_element.rs | 22 ++++++ other/remove_max_num_edge_traverse.cpp | 58 ++++++++++++++++ other/remove_nth_node.cpp | 18 +++++ other/remove_palindromic_subsequence.cpp | 19 ++++++ other/remove_star_string.cpp | 40 +++++++++++ other/remove_stones.cpp | 24 +++++++ other/remove_stones.rs | 26 +++++++ other/remove_subfolder_filesystem.cpp | 48 +++++++++++++ other/remove_substring.cpp | 25 +++++++ other/reorder_route_city_zero.cpp | 48 +++++++++++++ other/reordered_power2.cpp | 24 +++++++ other/reorganise_string.cpp | 41 +++++++++++ other/repeated_substring_pattern.cpp | 31 +++++++++ other/restore_array.cpp | 37 ++++++++++ other/restore_ip_addr.cpp | 56 +++++++++++++++ other/reverse_integer.cpp | 30 ++++++++ other/reverse_linked_list.cpp | 16 +++++ other/reverse_linked_list2.cpp | 26 +++++++ other/reverse_string.cpp | 15 ++++ other/reverse_string2.cpp | 34 ++++++++++ other/reverse_string3.cpp | 21 ++++++ other/reverse_vowel_string.cpp | 20 ++++++ other/reverse_vowel_string.rs | 33 +++++++++ other/reverse_word_string.cpp | 30 ++++++++ other/reverse_word_string.rs | 31 +++++++++ other/roman_2_int.cpp | 43 ++++++++++++ other/rotate_function.cpp | 29 ++++++++ other/rotate_image.cpp | 18 +++++ other/rotate_image.rs | 27 ++++++++ other/running_sum_1d_array.cpp | 18 +++++ other/same_tree.cpp | 14 ++++ other/same_tree.rs | 71 +++++++++++++++++++ other/satisfiability_eqaulity.cpp | 33 +++++++++ other/scramble_string.cpp | 55 +++++++++++++++ other/search_2d_matrix.cpp | 35 ++++++++++ other/search_2d_matrix2.cpp | 20 ++++++ other/search_rotated_array.cpp | 37 ++++++++++ other/search_rotated_array2.cpp | 48 +++++++++++++ other/search_suggestion_sys.cpp | 26 +++++++ other/set_matrix_0.rs | 44 ++++++++++++ other/set_mismatch.cpp | 19 ++++++ other/set_mismatch.rs | 37 ++++++++++ other/short_encoding_words.cpp | 21 ++++++ other/shortest_bridge.cpp | 82 ++++++++++++++++++++++ other/shortest_dist_road_addition1.cpp | 48 +++++++++++++ other/shortest_path_alternate_color.cpp | 56 +++++++++++++++ other/shortest_path_binary_matrix.cpp | 55 +++++++++++++++ other/shortest_path_grid_obstacle.cpp | 48 +++++++++++++ other/shortest_path_grid_obstacle.rs | 38 +++++++++++ other/shortest_path_keys.cpp | 109 ++++++++++++++++++++++++++++++ other/shortest_path_vis_nodes.cpp | 62 +++++++++++++++++ other/shortest_unsorted_subarr.cpp | 30 ++++++++ other/shuffle_the_array.cpp | 39 +++++++++++ other/similar_string_group.cpp | 63 +++++++++++++++++ other/simplify_path.cpp | 33 +++++++++ other/single_element_sorted_arr.cpp | 33 +++++++++ other/single_number.cpp | 38 +++++++++++ other/single_number.rs | 22 ++++++ other/single_number2.cpp | 29 ++++++++ other/single_product_array.cpp | 35 ++++++++++ other/single_threaded_cpu.cpp | 31 +++++++++ other/single_threaded_cpu.rs | 59 ++++++++++++++++ other/skyline_problem.cpp | 28 ++++++++ other/sliding_puzzle.cpp | 53 +++++++++++++++ other/sliding_window_max.cpp | 38 +++++++++++ other/smallest_num_set.cpp | 45 ++++++++++++ other/smallest_string_swaps.cpp | 55 +++++++++++++++ other/smallest_sufficient_team.cpp | 61 +++++++++++++++++ other/snakes_ladders.cpp | 47 +++++++++++++ other/snapshot_array.cpp | 42 ++++++++++++ other/sort_array.cpp | 27 ++++++++ other/sort_array_parity.cpp | 46 +++++++++++++ other/sort_char_freq.cpp | 26 +++++++ other/sort_char_freq.rs | 16 +++++ other/sort_items_dependencies.cpp | 74 ++++++++++++++++++++ other/sort_matrix_diagonal.cpp | 21 ++++++ other/sorted_arrary_bst.cpp | 21 ++++++ other/soup_servings.cpp | 54 +++++++++++++++ other/spiral_matrix.cpp | 37 ++++++++++ other/spiral_matrix2.cpp | 26 +++++++ other/split_array_consec_subseq.cpp | 33 +++++++++ other/stack_using_queues.cpp | 24 +++++++ other/stamping_sequence.cpp | 34 ++++++++++ other/steps_arr_increasing.cpp | 32 +++++++++ other/stone_game2.cpp | 39 +++++++++++ other/stone_game3.cpp | 46 +++++++++++++ other/stone_game4.cpp | 16 +++++ other/strange_printer.cpp | 32 +++++++++ other/string_compression.cpp | 31 +++++++++ other/string_compression.rs | 38 +++++++++++ other/string_compression2.cpp | 37 ++++++++++ other/string_compression2.rs | 54 +++++++++++++++ other/string_without_3a3b.cpp | 38 +++++++++++ other/subarr_fixed_bound.cpp | 33 +++++++++ other/subarr_product_less_k.cpp | 23 +++++++ other/subarr_sum_divisible_k.cpp | 32 +++++++++ other/substr_largest_variance.cpp | 48 +++++++++++++ other/sum_dist_tree.cpp | 45 ++++++++++++ other/sum_dist_tree.rs | 49 ++++++++++++++ other/sum_even_num_queries.cpp | 22 ++++++ other/sum_root_leaf_num.cpp | 42 ++++++++++++ other/sum_subarr_mins.cpp | 30 ++++++++ other/sum_subarr_mins.rs | 37 ++++++++++ other/sum_subset_xor.cpp | 33 +++++++++ other/summary_ranges.cpp | 47 +++++++++++++ other/swap_node_linked_list.cpp | 45 ++++++++++++ other/swap_nodes_pairs.cpp | 21 ++++++ other/symmetric_tree.cpp | 33 +++++++++ other/tallest_billboard.cpp | 26 +++++++ other/task_scheduler.cpp | 36 ++++++++++ other/text_justification.cpp | 56 +++++++++++++++ other/thousand_separator.cpp | 20 ++++++ other/time_base_key_val.cpp | 32 +++++++++ other/toeplitz_matrix.cpp | 30 ++++++++ other/toeplitz_matrix.rs | 22 ++++++ other/top_k_freq_element.cpp | 18 +++++ other/top_k_freq_element.rs | 32 +++++++++ other/top_k_freq_words.cpp | 29 ++++++++ other/top_k_freq_words.rs | 26 +++++++ other/transpose_matrix.cpp | 20 ++++++ other/trapping_rain_water.cpp | 33 +++++++++ other/trie_prefix.cpp | 45 ++++++++++++ other/two_sum.cpp | 35 ++++++++++ other/two_sum_2.cpp | 33 +++++++++ other/two_sum_4.cpp | 24 +++++++ other/ugly_number.cpp | 21 ++++++ other/ugly_number.rs | 19 ++++++ other/uncrossed_lines.cpp | 39 +++++++++++ other/unique_bst.cpp | 23 +++++++ other/unique_bst2.cpp | 34 ++++++++++ other/unique_morse_code_words.cpp | 25 +++++++ other/unique_num_occurrences.cpp | 24 +++++++ other/unique_num_occurrences.rs | 20 ++++++ other/unique_paths.cpp | 22 ++++++ other/unique_paths2.cpp | 39 +++++++++++ other/unique_paths3.cpp | 38 +++++++++++ other/unique_paths3.rs | 40 +++++++++++ other/utf8_validation.cpp | 38 +++++++++++ other/valid_anagram.cpp | 29 ++++++++ other/valid_arrangement_pairs.cpp | 73 ++++++++++++++++++++ other/valid_number.cpp | 45 ++++++++++++ other/valid_parentheses.cpp | 43 ++++++++++++ other/valid_stack_seq.cpp | 32 +++++++++ other/valid_sudoku.cpp | 38 +++++++++++ other/valid_sudoku.rs | 27 ++++++++ other/validate_bst.cpp | 24 +++++++ other/verify_alien_dict.cpp | 42 ++++++++++++ other/vertical_order_bst.cpp | 29 ++++++++ other/ways_to_paint_nx3_grid.cpp | 20 ++++++ other/where_will_ball_fall.cpp | 50 ++++++++++++++ other/where_will_ball_fall.rs | 38 +++++++++++ other/wiggle_subsequence.cpp | 23 +++++++ other/word_break.cpp | 38 +++++++++++ other/word_ladder.cpp | 39 +++++++++++ other/word_ladder2.cpp | 47 +++++++++++++ other/word_pattern.cpp | 25 +++++++ other/word_pattern.rs | 26 +++++++ other/word_search.cpp | 53 +++++++++++++++ other/word_search2.cpp | 70 +++++++++++++++++++ other/word_search2.rs | 59 ++++++++++++++++ other/word_subsets.cpp | 57 ++++++++++++++++ other/zigzag_conversion.cpp | 43 ++++++++++++ out_of_bounds_paths.cpp | 35 ---------- pacific_atlantic_water_flow.cpp | 38 ----------- paint_house3.cpp | 34 ---------- painting_grid_three_colour.cpp | 58 ---------------- painting_walls.cpp | 50 -------------- pairs_spells_potions.cpp | 45 ------------ palindrome_linked_list.cpp | 32 --------- palindrome_number.rs | 24 ------- palindrome_pairs.cpp | 38 ----------- palindrome_partitioning.cpp | 50 -------------- parallel_courses3.cpp | 54 --------------- partition_array_max_sum.cpp | 36 ---------- partition_array_pivot.rs | 32 --------- partition_list.cpp | 20 ------ partition_min_binary_array.cpp | 18 ----- pascals_triangle.cpp | 19 ------ path_max_probability.cpp | 52 -------------- path_min_effort.cpp | 34 ---------- path_min_effort1.cpp | 42 ------------ path_sum.cpp | 23 ------- path_sum2.cpp | 25 ------- peak_idx_mountain_arr.cpp | 25 ------- peeking_iterator.cpp | 32 --------- percentage_letter_string.cpp | 20 ------ perfect_squares.cpp | 23 ------- perfect_squares.rs | 21 ------ permutation_in_string.cpp | 47 ------------- permutation_sequence.cpp | 25 ------- permutations.cpp | 26 ------- permutations2.cpp | 29 -------- poor-pigs.cpp | 8 --- possible_bipartition.cpp | 45 ------------ possible_bipartition.rs | 40 ----------- power_3.cpp | 19 ------ power_of_four.cpp | 24 ------- power_of_four.rs | 24 ------- power_of_two.cpp | 11 --- predict_winner.cpp | 40 ----------- prefix_suffix_search.cpp | 26 ------- profitable_schemes.cpp | 71 ------------------- pseudo_palindrome_binary_tree.cpp | 29 -------- push_dominoes.cpp | 31 --------- queue_reconstruction.cpp | 20 ------ range_sum_bst.cpp | 22 ------ range_sum_bst.rs | 38 ----------- range_sum_query_2d.cpp | 40 ----------- range_sum_query_mutable.cpp | 61 ----------------- ransom_note.cpp | 23 ------- rectangle_area.cpp | 16 ----- rectangle_area.rs | 14 ---- rectangle_fewest_squares.cpp | 51 -------------- reduce_array_size_half.cpp | 30 -------- reducing_dishes.cpp | 37 ---------- remove_adjacent_dup.cpp | 37 ---------- remove_adjacent_dup_str.cpp | 20 ------ remove_adjacent_dup_str.rs | 20 ------ remove_boxes.cpp | 40 ----------- remove_dupplicate.cpp | 22 ------ remove_dupplicate.rs | 24 ------- remove_element.cpp | 28 -------- remove_element.rs | 22 ------ remove_max_num_edge_traverse.cpp | 58 ---------------- remove_nth_node.cpp | 18 ----- remove_palindromic_subsequence.cpp | 19 ------ remove_star_string.cpp | 40 ----------- remove_stones.cpp | 24 ------- remove_stones.rs | 26 ------- remove_subfolder_filesystem.cpp | 48 ------------- remove_substring.cpp | 25 ------- reorder_route_city_zero.cpp | 48 ------------- reordered_power2.cpp | 24 ------- reorganise_string.cpp | 41 ----------- repeated_substring_pattern.cpp | 31 --------- restore_array.cpp | 37 ---------- restore_ip_addr.cpp | 56 --------------- reverse_integer.cpp | 30 -------- reverse_linked_list.cpp | 16 ----- reverse_linked_list2.cpp | 26 ------- reverse_string.cpp | 15 ---- reverse_string2.cpp | 34 ---------- reverse_string3.cpp | 21 ------ reverse_vowel_string.cpp | 20 ------ reverse_vowel_string.rs | 33 --------- reverse_word_string.cpp | 30 -------- reverse_word_string.rs | 31 --------- roman_2_int.cpp | 43 ------------ rotate_function.cpp | 29 -------- rotate_image.cpp | 18 ----- rotate_image.rs | 27 -------- running_sum_1d_array.cpp | 18 ----- same_tree.cpp | 14 ---- same_tree.rs | 71 ------------------- satisfiability_eqaulity.cpp | 33 --------- scramble_string.cpp | 55 --------------- search_2d_matrix.cpp | 35 ---------- search_2d_matrix2.cpp | 20 ------ search_rotated_array.cpp | 37 ---------- search_rotated_array2.cpp | 48 ------------- search_suggestion_sys.cpp | 26 ------- set_matrix_0.rs | 44 ------------ set_mismatch.cpp | 19 ------ set_mismatch.rs | 37 ---------- short_encoding_words.cpp | 21 ------ shortest_bridge.cpp | 82 ---------------------- shortest_dist_road_addition1.cpp | 48 ------------- shortest_path_alternate_color.cpp | 56 --------------- shortest_path_binary_matrix.cpp | 55 --------------- shortest_path_grid_obstacle.cpp | 48 ------------- shortest_path_grid_obstacle.rs | 38 ----------- shortest_path_keys.cpp | 109 ------------------------------ shortest_path_vis_nodes.cpp | 62 ----------------- shortest_unsorted_subarr.cpp | 30 -------- shuffle_the_array.cpp | 39 ----------- similar_string_group.cpp | 63 ----------------- simplify_path.cpp | 33 --------- single_element_sorted_arr.cpp | 33 --------- single_number.cpp | 38 ----------- single_number.rs | 22 ------ single_number2.cpp | 29 -------- single_product_array.cpp | 35 ---------- single_threaded_cpu.cpp | 31 --------- single_threaded_cpu.rs | 59 ---------------- skyline_problem.cpp | 28 -------- sliding_puzzle.cpp | 53 --------------- sliding_window_max.cpp | 38 ----------- smallest_num_set.cpp | 45 ------------ smallest_string_swaps.cpp | 55 --------------- smallest_sufficient_team.cpp | 61 ----------------- snakes_ladders.cpp | 47 ------------- snapshot_array.cpp | 42 ------------ sort_array.cpp | 27 -------- sort_array_parity.cpp | 46 ------------- sort_char_freq.cpp | 26 ------- sort_char_freq.rs | 16 ----- sort_items_dependencies.cpp | 74 -------------------- sort_matrix_diagonal.cpp | 21 ------ sorted_arrary_bst.cpp | 21 ------ soup_servings.cpp | 54 --------------- spiral_matrix.cpp | 37 ---------- spiral_matrix2.cpp | 26 ------- split_array_consec_subseq.cpp | 33 --------- stack_using_queues.cpp | 24 ------- stamping_sequence.cpp | 34 ---------- steps_arr_increasing.cpp | 32 --------- stone_game2.cpp | 39 ----------- stone_game3.cpp | 46 ------------- stone_game4.cpp | 16 ----- strange_printer.cpp | 32 --------- string_compression.cpp | 31 --------- string_compression.rs | 38 ----------- string_compression2.cpp | 37 ---------- string_compression2.rs | 54 --------------- string_without_3a3b.cpp | 38 ----------- subarr_fixed_bound.cpp | 33 --------- subarr_product_less_k.cpp | 23 ------- subarr_sum_divisible_k.cpp | 32 --------- substr_largest_variance.cpp | 48 ------------- sum_dist_tree.cpp | 45 ------------ sum_dist_tree.rs | 49 -------------- sum_even_num_queries.cpp | 22 ------ sum_root_leaf_num.cpp | 42 ------------ sum_subarr_mins.cpp | 30 -------- sum_subarr_mins.rs | 37 ---------- sum_subset_xor.cpp | 33 --------- summary_ranges.cpp | 47 ------------- swap_node_linked_list.cpp | 45 ------------ swap_nodes_pairs.cpp | 21 ------ symmetric_tree.cpp | 33 --------- tallest_billboard.cpp | 26 ------- task_scheduler.cpp | 36 ---------- text_justification.cpp | 56 --------------- thousand_separator.cpp | 20 ------ time_base_key_val.cpp | 32 --------- toeplitz_matrix.cpp | 30 -------- toeplitz_matrix.rs | 22 ------ top_k_freq_element.cpp | 18 ----- top_k_freq_element.rs | 32 --------- top_k_freq_words.cpp | 29 -------- top_k_freq_words.rs | 26 ------- transpose_matrix.cpp | 20 ------ trapping_rain_water.cpp | 33 --------- trie_prefix.cpp | 45 ------------ two_sum.cpp | 35 ---------- two_sum_2.cpp | 33 --------- two_sum_4.cpp | 24 ------- ugly_number.cpp | 21 ------ ugly_number.rs | 19 ------ uncrossed_lines.cpp | 39 ----------- unique_bst.cpp | 23 ------- unique_bst2.cpp | 34 ---------- unique_morse_code_words.cpp | 25 ------- unique_num_occurrences.cpp | 24 ------- unique_num_occurrences.rs | 20 ------ unique_paths.cpp | 22 ------ unique_paths2.cpp | 39 ----------- unique_paths3.cpp | 38 ----------- unique_paths3.rs | 40 ----------- utf8_validation.cpp | 38 ----------- valid_anagram.cpp | 29 -------- valid_arrangement_pairs.cpp | 73 -------------------- valid_number.cpp | 45 ------------ valid_parentheses.cpp | 43 ------------ valid_stack_seq.cpp | 32 --------- valid_sudoku.cpp | 38 ----------- valid_sudoku.rs | 27 -------- validate_bst.cpp | 24 ------- verify_alien_dict.cpp | 42 ------------ vertical_order_bst.cpp | 29 -------- ways_to_paint_nx3_grid.cpp | 20 ------ where_will_ball_fall.cpp | 50 -------------- where_will_ball_fall.rs | 38 ----------- wiggle_subsequence.cpp | 23 ------- word_break.cpp | 38 ----------- word_ladder.cpp | 39 ----------- word_ladder2.cpp | 47 ------------- word_pattern.cpp | 25 ------- word_pattern.rs | 26 ------- word_search.cpp | 53 --------------- word_search2.cpp | 70 ------------------- word_search2.rs | 59 ---------------- word_subsets.cpp | 57 ---------------- zigzag_conversion.cpp | 43 ------------ 1354 files changed, 24214 insertions(+), 24214 deletions(-) delete mode 100644 01_matrix.cpp delete mode 100644 132_pattern.cpp delete mode 100644 3sum_closest.cpp delete mode 100644 add_arr_form_int.cpp delete mode 100644 add_binary.cpp delete mode 100644 add_digits.cpp delete mode 100644 add_row_tree.cpp delete mode 100644 add_search_words_data.cpp delete mode 100644 add_space_string.cpp delete mode 100644 add_two_num2.cpp delete mode 100644 additive_number.cpp delete mode 100644 all_nodes_binary_tree.cpp delete mode 100644 all_path_src_target.cpp delete mode 100644 all_path_src_target.rs delete mode 100644 all_possible_full_tree.cpp delete mode 100644 alphabet_board_path.cpp delete mode 100644 ancestors_node_acyclic_graph.cpp delete mode 100644 arithmetic_progression.cpp delete mode 100644 arithmetic_slices2.cpp delete mode 100644 arithmetic_slices2.rs delete mode 100644 asteroid_collision.cpp delete mode 100644 avg_levels_bst.cpp delete mode 100644 avg_salary.cpp delete mode 100644 bag_of_tokens.cpp delete mode 100644 balanced_num.cpp delete mode 100644 basic_calculator.cpp delete mode 100644 basic_calculator.rs delete mode 100644 best_buy_sell_stock.cpp delete mode 100644 best_team_no_conflict.cpp delete mode 100644 binary_search.cpp delete mode 100644 binary_tree_factors.cpp delete mode 100644 binary_tree_inorder.cpp delete mode 100644 binary_tree_level_traverse.cpp delete mode 100644 binary_tree_preorder.cpp delete mode 100644 binary_tree_preorder.rs delete mode 100644 binary_tree_pruning.cpp delete mode 100644 binary_tree_right_view.cpp delete mode 100644 binary_tree_traversal.cpp delete mode 100644 binary_tree_zigzag.cpp delete mode 100644 boats_save_people.cpp delete mode 100644 brainpower.cpp delete mode 100644 break_palindrom.cpp delete mode 100644 browser_history.cpp delete mode 100644 bt_max_path_sum.cpp delete mode 100644 bt_max_path_sum.rs delete mode 100644 buddy_strings.cpp delete mode 100644 build_matrix_conditions.cpp delete mode 100644 bulb_switcher.cpp delete mode 100644 buy_sell_stock.cpp delete mode 100644 buy_sell_stock.rs delete mode 100644 buy_sell_stock_fee.cpp delete mode 100644 can_place_flower.cpp delete mode 100644 candy.cpp delete mode 100644 capacity_ship_d_day.cpp delete mode 100644 cheapest_flight_k_stop.cpp delete mode 100644 check_complete_bt.cpp delete mode 100644 check_existence_edge.cpp delete mode 100644 check_knight_config.cpp delete mode 100644 check_pangram_sentence.cpp delete mode 100644 check_pangram_sentence.rs delete mode 100644 check_straight_line.cpp delete mode 100644 check_string_cont_k.cpp delete mode 100644 check_two_str_arr.cpp delete mode 100644 check_two_str_arr.rs delete mode 100644 check_valid_partition.cpp delete mode 100644 climbing_stairs.cpp delete mode 100644 climbing_stairs.rs delete mode 100644 clone_graph.cpp delete mode 100644 closest_node_2_nodes.cpp delete mode 100644 closest_node_2_nodes.rs delete mode 100644 coin_change.cpp delete mode 100644 coin_change2.cpp delete mode 100644 combination_sum3.cpp delete mode 100644 combination_sum4.cpp delete mode 100644 combinations.cpp delete mode 100644 concatenated_words.cpp delete mode 100644 concatenation_binary_num.cpp delete mode 100644 construct_array_multiple_sum.cpp delete mode 100644 construct_bt_io_po.cpp delete mode 100644 construct_quad_tree.cpp delete mode 100644 construct_string_binary_tree.cpp delete mode 100644 contains_duplicate2.cpp delete mode 100644 contains_duplicate2.rs delete mode 100644 contains_duplicate3.cpp delete mode 100644 contains_virus.cpp delete mode 100644 continuous_subarr_sum.cpp delete mode 100644 continuous_subarr_sum.rs delete mode 100644 convert_sorted_bst.cpp delete mode 100644 cost_hire_k_worker.cpp delete mode 100644 count_all_pickup_delivery.cpp delete mode 100644 count_and_say.cpp delete mode 100644 count_and_say.rs delete mode 100644 count_complete_tree_node.cpp delete mode 100644 count_complete_tree_node.rs delete mode 100644 count_distinct_int.cpp delete mode 100644 count_distinct_int.rs delete mode 100644 count_good_nodes_bst.cpp delete mode 100644 count_ints_even_sum.cpp delete mode 100644 count_negative_num_matrix.cpp delete mode 100644 count_odd_num_interval_range.cpp delete mode 100644 count_possible_routes.cpp delete mode 100644 count_sorted_vowel.cpp delete mode 100644 count_unreach_node.cpp delete mode 100644 count_vowels_permutation.cpp delete mode 100644 count_ways_build_strs.cpp delete mode 100644 couples_holding_hands.cpp delete mode 100644 course_schedule.cpp delete mode 100644 course_schedule_3.cpp delete mode 100644 create_bt_from_desc.cpp delete mode 100644 daily_temps.cpp delete mode 100644 daily_temps.rs delete mode 100644 data_stream_disjoint_interval.cpp delete mode 100644 decode_ways.cpp delete mode 100644 decode_xor_array.cpp delete mode 100644 delete_col_sorted.cpp delete mode 100644 delete_col_sorted.rs delete mode 100644 delete_middle_node.cpp delete mode 100644 delete_middle_node.rs delete mode 100644 delete_node_link_list.cpp delete mode 100644 delete_operation_2string.cpp delete mode 100644 design_circular_queue.cpp delete mode 100644 design_food_rating_sys.cpp delete mode 100644 design_number_container.cpp delete mode 100644 design_parking_system.cpp delete mode 100644 design_underground_system.cpp delete mode 100644 detect_capital.cpp delete mode 100644 detect_capital.rs delete mode 100644 determine_string_halves.cpp delete mode 100644 determine_string_halves.rs delete mode 100644 determine_strings_close.cpp delete mode 100644 determine_strings_close.rs delete mode 100644 detonate_max_bombs.cpp delete mode 100644 diff_two_array.cpp delete mode 100644 discount_n_orders.cpp delete mode 100644 divide_nodes_max_groups.cpp delete mode 100644 domino_tromino_tiling.cpp delete mode 100644 domino_tromino_tiling.rs delete mode 100644 earliest_possible_full_bloom.cpp delete mode 100644 earliest_possible_full_bloom.rs delete mode 100644 edit_distance.cpp delete mode 100644 eliminate_monsters.cpp delete mode 100644 encode_decode_tinyurl.cpp delete mode 100644 equal_row_col_pair.cpp delete mode 100644 erect_fence.cpp delete mode 100644 erect_fence.rs delete mode 100644 eval_reverse_polish_notation.cpp delete mode 100644 eval_reverse_polish_notation.rs delete mode 100644 eventual_safe_states.cpp delete mode 100644 excel_sheet_column_title.cpp delete mode 100644 extra_char_string.cpp delete mode 100644 fair_distribution_cookie.cpp delete mode 100644 far_from_land.cpp delete mode 100644 fibonacci_number.cpp delete mode 100644 find_all_anagrams.cpp delete mode 100644 find_building_alice_bob_meet.cpp delete mode 100644 find_critical_edge_tree.cpp delete mode 100644 find_duplicate_file.cpp delete mode 100644 find_duplicate_subtree.cpp delete mode 100644 find_first_last_array.cpp delete mode 100644 find_groups_farmland.cpp delete mode 100644 find_highest_altitude.cpp delete mode 100644 find_k_beauty_num.cpp delete mode 100644 find_k_closest_elements.cpp delete mode 100644 find_k_pair_sum.cpp delete mode 100644 find_max_sum_node_val.cpp delete mode 100644 find_median_data_stream.cpp delete mode 100644 find_median_data_stream.rs delete mode 100644 find_orig_array_double.cpp delete mode 100644 find_path_graph.cpp delete mode 100644 find_path_graph.rs delete mode 100644 find_player_zero_one_loss.cpp delete mode 100644 find_player_zero_one_loss.rs delete mode 100644 find_replace_pattern.cpp delete mode 100644 find_safest_path_grid.cpp delete mode 100644 find_score_arr_mark.cpp delete mode 100644 find_smallest_letter.cpp delete mode 100644 find_town_judge.cpp delete mode 100644 first_missing_positive.cpp delete mode 100644 first_unique_char_string.cpp delete mode 100644 flatten_binary_to_linked.cpp delete mode 100644 flip_string_monotone_increase.cpp delete mode 100644 freedom_trail.cpp delete mode 100644 frog_jump.cpp delete mode 100644 fruit_into_baskets.cpp delete mode 100644 furthest_building_reach.cpp delete mode 100644 gas_station.cpp delete mode 100644 gas_station.rs delete mode 100644 greatest_common_div_string.cpp delete mode 100644 greatest_sum_div_three.cpp delete mode 100644 group_anagrams.cpp delete mode 100644 group_anagrams.rs delete mode 100644 guess_number_high_low.cpp delete mode 100644 guess_number_high_low.rs delete mode 100644 hand_of_straights.cpp delete mode 100644 happy_number.cpp delete mode 100644 house_robber.cpp delete mode 100644 house_robber.rs delete mode 100644 idx_first_occur_str.cpp delete mode 100644 image_overlap.cpp delete mode 100644 image_overlap.rs delete mode 100644 implement_queue_stacks.cpp delete mode 100644 increasing_triplet_subsequence.cpp delete mode 100644 inform_employees.cpp delete mode 100644 insert_delete_getrandom.cpp delete mode 100644 insert_delete_getrandom.rs delete mode 100644 insert_interval.cpp delete mode 100644 int_roman.cpp delete mode 100644 int_roman.rs delete mode 100644 integer_break.cpp delete mode 100644 interleaving_string.cpp delete mode 100644 invert_binary_tree.cpp delete mode 100644 ipo.cpp delete mode 100644 is_graph_biparite.cpp delete mode 100644 jump_game.cpp delete mode 100644 jump_game.rs delete mode 100644 jump_game3.cpp delete mode 100644 jump_game3.rs delete mode 100644 jump_game4.cpp delete mode 100644 jump_game6.cpp delete mode 100644 k_inverse_pairs.cpp delete mode 100644 k_radius_subarr.cpp delete mode 100644 keys_and_rooms.cpp delete mode 100644 keys_and_rooms.rs delete mode 100644 kids_max_num_candy.cpp delete mode 100644 knight_probability_chessboard.cpp delete mode 100644 koko_eating_bananas.cpp delete mode 100644 kth_element_in_stream.cpp delete mode 100644 kth_largest_element.cpp delete mode 100644 kth_largest_element_stream.cpp delete mode 100644 kth_missing_pos_num.cpp delete mode 100644 kth_smallest_lexicographical.cpp delete mode 100644 kth_smallest_sorted_matrix.cpp delete mode 100644 largest_colour_value_graph.cpp delete mode 100644 largest_int_add_target.cpp delete mode 100644 largest_multiple_three.cpp delete mode 100644 largest_odd_num_string.cpp delete mode 100644 largest_perimeter_triangle.cpp delete mode 100644 last_day_cross.cpp delete mode 100644 leaf_similar_trees.cpp delete mode 100644 leaf_similar_trees.rs delete mode 100644 letter_combo_number.cpp delete mode 100644 lexicographical_numbers.cpp delete mode 100644 lexicographically_small_string.cpp delete mode 100644 lfu_cache.cpp delete mode 100644 linked_list_cycle2.cpp delete mode 100644 linked_list_random.cpp delete mode 100644 longest_arithmetic_subseq.cpp delete mode 100644 longest_arithmetic_subseq_diff.cpp delete mode 100644 longest_common_subseq.cpp delete mode 100644 longest_common_subseq.rs delete mode 100644 longest_consecutive_sequence.cpp delete mode 100644 longest_cycle_graph.cpp delete mode 100644 longest_happy_string.cpp delete mode 100644 longest_increasing_subseq.cpp delete mode 100644 longest_palindrome_concat.cpp delete mode 100644 longest_palindrome_concat.rs delete mode 100644 longest_palindromic_subseq.cpp delete mode 100644 longest_palindromic_substr.cpp delete mode 100644 longest_path_diff_adjacent_char.cpp delete mode 100644 longest_path_diff_adjacent_char.rs delete mode 100644 longest_string_chain.cpp delete mode 100644 longest_subarr_ones.cpp delete mode 100644 longest_subseq_lim_sum.cpp delete mode 100644 longest_subseq_lim_sum.rs delete mode 100644 longest_substring_no_repeat.cpp delete mode 100644 longest_valid_course.cpp delete mode 100644 longest_valid_parentheses.cpp delete mode 100644 longest_word_dict.cpp delete mode 100644 longest_zigzag_bt.cpp delete mode 100644 lowest_common_ancestor.cpp delete mode 100644 lowest_common_ancestor_bst.cpp delete mode 100644 lru_cache.cpp delete mode 100644 magnetic_force_2_balls.cpp delete mode 100644 make_array_increasing.cpp delete mode 100644 make_string_great.cpp delete mode 100644 make_string_great.rs delete mode 100644 make_sum_divisible_p.cpp delete mode 100644 marbles_in_bags.cpp delete mode 100644 matchsticks_square.cpp delete mode 100644 matrix_diagonal_sum.cpp delete mode 100644 max_69.cpp delete mode 100644 max_69.rs delete mode 100644 max_area_cake.cpp delete mode 100644 max_area_island.cpp delete mode 100644 max_average_pass_ration.cpp delete mode 100644 max_bags_rocks.cpp delete mode 100644 max_bags_rocks.rs delete mode 100644 max_consecutive_ones3.cpp delete mode 100644 max_depth_binary_tree.cpp delete mode 100644 max_diff_node_ancestor.cpp delete mode 100644 max_diff_node_ancestor.rs delete mode 100644 max_distance_closest_person.cpp delete mode 100644 max_erasure_value.cpp delete mode 100644 max_ice_cream_bars.cpp delete mode 100644 max_ice_cream_bars.rs delete mode 100644 max_len_concat_str.cpp delete mode 100644 max_len_concat_str.rs delete mode 100644 max_length_pair_chain.cpp delete mode 100644 max_length_repeated_subarr.cpp delete mode 100644 max_network_rank.cpp delete mode 100644 max_num_events_attended2.cpp delete mode 100644 max_num_ksum_pair.cpp delete mode 100644 max_num_tasks_assign.cpp delete mode 100644 max_num_vowel_substr.cpp delete mode 100644 max_performance_team.cpp delete mode 100644 max_points_from_cards.cpp delete mode 100644 max_points_line.cpp delete mode 100644 max_points_line.rs delete mode 100644 max_product_3num.cpp delete mode 100644 max_product_split_bt.cpp delete mode 100644 max_product_split_bt.rs delete mode 100644 max_product_word_len.cpp delete mode 100644 max_profit_job.cpp delete mode 100644 max_profit_job.rs delete mode 100644 max_running_time_n_computer.cpp delete mode 100644 max_score_good_subarr.cpp delete mode 100644 max_score_mult_opp.cpp delete mode 100644 max_score_n_operations.cpp delete mode 100644 max_score_node_sequence.cpp delete mode 100644 max_subarray.cpp delete mode 100644 max_subseq_score.cpp delete mode 100644 max_sum_3_noverlap_subarr.cpp delete mode 100644 max_sum_binary_tree.cpp delete mode 100644 max_sum_circular_subarr.cpp delete mode 100644 max_sum_rectangle.cpp delete mode 100644 max_total_importance_road.cpp delete mode 100644 max_tranfer_requests.cpp delete mode 100644 max_twin_sum_list.cpp delete mode 100644 max_units_truck.cpp delete mode 100644 max_val_k_coin_pile.cpp delete mode 100644 max_value_give_idx.cpp delete mode 100644 max_width_binary_tree.cpp delete mode 100644 maximise_confusion_exam.cpp delete mode 100644 maximise_grid_happiness.cpp delete mode 100644 merge_sorted_array.cpp delete mode 100644 merge_sorted_array.rs delete mode 100644 merge_string_alt.cpp delete mode 100644 middle_linked_list.cpp delete mode 100644 middle_linked_list.rs delete mode 100644 min_abs_diff_bst.cpp delete mode 100644 min_ascii_strs.cpp delete mode 100644 min_avg_diff.cpp delete mode 100644 min_avg_diff.rs delete mode 100644 min_cost_arr_equal.cpp delete mode 100644 min_cost_change_expr.cpp delete mode 100644 min_cost_climbing_stairs.cpp delete mode 100644 min_cost_convert_string1.cpp delete mode 100644 min_cost_cut_stick.cpp delete mode 100644 min_cost_ticket.cpp delete mode 100644 min_deletions_unique_char.cpp delete mode 100644 min_depth_binary_tree.cpp delete mode 100644 min_deviation_arr.cpp delete mode 100644 min_difficulty_schedule.cpp delete mode 100644 min_dist_bst_node.cpp delete mode 100644 min_dist_target_element.cpp delete mode 100644 min_falling_path_sum.cpp delete mode 100644 min_falling_path_sum.rs delete mode 100644 min_flips_abc.cpp delete mode 100644 min_fuel_report_captial.cpp delete mode 100644 min_genetic_mutation.cpp delete mode 100644 min_genetic_mutation.rs delete mode 100644 min_incr_arr_unique.cpp delete mode 100644 min_insertion_make_palindrome.cpp delete mode 100644 min_jump_reach_home.cpp delete mode 100644 min_max_array.cpp delete mode 100644 min_max_diff_pair.cpp delete mode 100644 min_move_palindrome.cpp delete mode 100644 min_moves_equal_array2.cpp delete mode 100644 min_num_arrow_balloon.cpp delete mode 100644 min_num_arrow_balloon.rs delete mode 100644 min_num_days_disconnect_island.cpp delete mode 100644 min_num_opp_arr_cont.cpp delete mode 100644 min_num_refueling_stops.cpp delete mode 100644 min_num_remove_mountain_arr.cpp delete mode 100644 min_num_vertices_node.cpp delete mode 100644 min_one_bit_0.cpp delete mode 100644 min_one_bit_0.rs delete mode 100644 min_operations_x_zero.cpp delete mode 100644 min_path_sum.cpp delete mode 100644 min_rounds_complete_all_tasks.cpp delete mode 100644 min_rounds_complete_all_tasks.rs delete mode 100644 min_score_path_city.cpp delete mode 100644 min_size_subarr_sum.cpp delete mode 100644 min_speed_arrive_time.cpp delete mode 100644 min_stack.cpp delete mode 100644 min_swap_group_1.cpp delete mode 100644 min_time_apples_tree.cpp delete mode 100644 min_time_apples_tree.rs delete mode 100644 min_time_complete_trip.cpp delete mode 100644 min_time_rope_colorful.cpp delete mode 100644 min_time_visit_cell_grid.cpp delete mode 100644 min_window_substring.cpp delete mode 100644 min_window_substring.rs delete mode 100644 mirror_reflection.cpp delete mode 100644 missing_number.cpp delete mode 100644 modify_graph_edge_weight.cpp delete mode 100644 most_stones_remove.cpp delete mode 100644 most_stones_remove.rs delete mode 100644 most_water.cpp delete mode 100644 my_calendar.cpp delete mode 100644 my_calendar2.cpp delete mode 100644 my_calendar3.cpp delete mode 100644 n_ary_tree_traverse.cpp delete mode 100644 n_queens2.cpp delete mode 100644 naming_company.cpp delete mode 100644 nearest_exit_maze.cpp delete mode 100644 nearest_exit_maze.rs delete mode 100644 new_21_game.cpp delete mode 100644 next_greater_element2.cpp delete mode 100644 next_permutation.cpp delete mode 100644 non_decreasing_array.cpp delete mode 100644 non_decreasing_subseq.cpp delete mode 100644 non_overlapping_interval.cpp delete mode 100644 nth_tribonacci_number.cpp delete mode 100644 num_bad_pairs.cpp delete mode 100644 num_bad_pairs.rs delete mode 100644 num_closed_islands.cpp delete mode 100644 num_cut_pizza.cpp delete mode 100644 num_dice_roll_target_sum.cpp delete mode 100644 num_enclaves.cpp delete mode 100644 num_even_nums.cpp delete mode 100644 num_good_path.cpp delete mode 100644 num_increasing_path.cpp delete mode 100644 num_longest_incr_subseq.cpp delete mode 100644 num_matching_subsequence.cpp delete mode 100644 num_music_playlists.cpp delete mode 100644 num_nodes_sub_tree.cpp delete mode 100644 num_nodes_sub_tree.rs delete mode 100644 num_op_connect_network.cpp delete mode 100644 num_people_aware_secret.cpp delete mode 100644 num_same_consecutive_diff.cpp delete mode 100644 num_smaller_num_self.cpp delete mode 100644 num_squareful_arrays.cpp delete mode 100644 num_subseq_satisfy.cpp delete mode 100644 num_to_hex_binary.cpp delete mode 100644 num_valid_words_puzzle.cpp delete mode 100644 num_ways_dict.cpp delete mode 100644 num_ways_remain_place.cpp delete mode 100644 num_ways_reorder_array.cpp delete mode 100644 num_weak_char_game.cpp delete mode 100644 num_zero_filled_subarr.cpp delete mode 100644 number_1bits.cpp delete mode 100644 number_atoms.cpp delete mode 100644 number_islands.cpp delete mode 100644 number_provinces.cpp delete mode 100644 number_steps_to_0.cpp delete mode 100644 number_submatrices_sum_target.cpp delete mode 100644 odd_even_linke_list.cpp delete mode 100644 odd_even_linke_list.rs delete mode 100644 ones_and_zeroes.cpp delete mode 100644 online_stock_span.cpp delete mode 100644 online_stock_span.rs delete mode 100644 optimal_partition_string.cpp delete mode 100644 orderly_queue.cpp delete mode 100644 orderly_queue.rs create mode 100644 other/01_matrix.cpp create mode 100644 other/132_pattern.cpp create mode 100644 other/3sum_closest.cpp create mode 100644 other/add_arr_form_int.cpp create mode 100644 other/add_binary.cpp create mode 100644 other/add_digits.cpp create mode 100644 other/add_row_tree.cpp create mode 100644 other/add_search_words_data.cpp create mode 100644 other/add_space_string.cpp create mode 100644 other/add_two_num2.cpp create mode 100644 other/additive_number.cpp create mode 100644 other/all_nodes_binary_tree.cpp create mode 100644 other/all_path_src_target.cpp create mode 100644 other/all_path_src_target.rs create mode 100644 other/all_possible_full_tree.cpp create mode 100644 other/alphabet_board_path.cpp create mode 100644 other/ancestors_node_acyclic_graph.cpp create mode 100644 other/arithmetic_progression.cpp create mode 100644 other/arithmetic_slices2.cpp create mode 100644 other/arithmetic_slices2.rs create mode 100644 other/asteroid_collision.cpp create mode 100644 other/avg_levels_bst.cpp create mode 100644 other/avg_salary.cpp create mode 100644 other/bag_of_tokens.cpp create mode 100644 other/balanced_num.cpp create mode 100644 other/basic_calculator.cpp create mode 100644 other/basic_calculator.rs create mode 100644 other/best_buy_sell_stock.cpp create mode 100644 other/best_team_no_conflict.cpp create mode 100644 other/binary_search.cpp create mode 100644 other/binary_tree_factors.cpp create mode 100644 other/binary_tree_inorder.cpp create mode 100644 other/binary_tree_level_traverse.cpp create mode 100644 other/binary_tree_preorder.cpp create mode 100644 other/binary_tree_preorder.rs create mode 100644 other/binary_tree_pruning.cpp create mode 100644 other/binary_tree_right_view.cpp create mode 100644 other/binary_tree_traversal.cpp create mode 100644 other/binary_tree_zigzag.cpp create mode 100644 other/boats_save_people.cpp create mode 100644 other/brainpower.cpp create mode 100644 other/break_palindrom.cpp create mode 100644 other/browser_history.cpp create mode 100644 other/bt_max_path_sum.cpp create mode 100644 other/bt_max_path_sum.rs create mode 100644 other/buddy_strings.cpp create mode 100644 other/build_matrix_conditions.cpp create mode 100644 other/bulb_switcher.cpp create mode 100644 other/buy_sell_stock.cpp create mode 100644 other/buy_sell_stock.rs create mode 100644 other/buy_sell_stock_fee.cpp create mode 100644 other/can_place_flower.cpp create mode 100644 other/candy.cpp create mode 100644 other/capacity_ship_d_day.cpp create mode 100644 other/cheapest_flight_k_stop.cpp create mode 100644 other/check_complete_bt.cpp create mode 100644 other/check_existence_edge.cpp create mode 100644 other/check_knight_config.cpp create mode 100644 other/check_pangram_sentence.cpp create mode 100644 other/check_pangram_sentence.rs create mode 100644 other/check_straight_line.cpp create mode 100644 other/check_string_cont_k.cpp create mode 100644 other/check_two_str_arr.cpp create mode 100644 other/check_two_str_arr.rs create mode 100644 other/check_valid_partition.cpp create mode 100644 other/climbing_stairs.cpp create mode 100644 other/climbing_stairs.rs create mode 100644 other/clone_graph.cpp create mode 100644 other/closest_node_2_nodes.cpp create mode 100644 other/closest_node_2_nodes.rs create mode 100644 other/coin_change.cpp create mode 100644 other/coin_change2.cpp create mode 100644 other/combination_sum3.cpp create mode 100644 other/combination_sum4.cpp create mode 100644 other/combinations.cpp create mode 100644 other/concatenated_words.cpp create mode 100644 other/concatenation_binary_num.cpp create mode 100644 other/construct_array_multiple_sum.cpp create mode 100644 other/construct_bt_io_po.cpp create mode 100644 other/construct_quad_tree.cpp create mode 100644 other/construct_string_binary_tree.cpp create mode 100644 other/contains_duplicate2.cpp create mode 100644 other/contains_duplicate2.rs create mode 100644 other/contains_duplicate3.cpp create mode 100644 other/contains_virus.cpp create mode 100644 other/continuous_subarr_sum.cpp create mode 100644 other/continuous_subarr_sum.rs create mode 100644 other/convert_sorted_bst.cpp create mode 100644 other/cost_hire_k_worker.cpp create mode 100644 other/count_all_pickup_delivery.cpp create mode 100644 other/count_and_say.cpp create mode 100644 other/count_and_say.rs create mode 100644 other/count_complete_tree_node.cpp create mode 100644 other/count_complete_tree_node.rs create mode 100644 other/count_distinct_int.cpp create mode 100644 other/count_distinct_int.rs create mode 100644 other/count_good_nodes_bst.cpp create mode 100644 other/count_ints_even_sum.cpp create mode 100644 other/count_negative_num_matrix.cpp create mode 100644 other/count_odd_num_interval_range.cpp create mode 100644 other/count_possible_routes.cpp create mode 100644 other/count_sorted_vowel.cpp create mode 100644 other/count_unreach_node.cpp create mode 100644 other/count_vowels_permutation.cpp create mode 100644 other/count_ways_build_strs.cpp create mode 100644 other/couples_holding_hands.cpp create mode 100644 other/course_schedule.cpp create mode 100644 other/course_schedule_3.cpp create mode 100644 other/create_bt_from_desc.cpp create mode 100644 other/daily_temps.cpp create mode 100644 other/daily_temps.rs create mode 100644 other/data_stream_disjoint_interval.cpp create mode 100644 other/decode_ways.cpp create mode 100644 other/decode_xor_array.cpp create mode 100644 other/delete_col_sorted.cpp create mode 100644 other/delete_col_sorted.rs create mode 100644 other/delete_middle_node.cpp create mode 100644 other/delete_middle_node.rs create mode 100644 other/delete_node_link_list.cpp create mode 100644 other/delete_operation_2string.cpp create mode 100644 other/design_circular_queue.cpp create mode 100644 other/design_food_rating_sys.cpp create mode 100644 other/design_number_container.cpp create mode 100644 other/design_parking_system.cpp create mode 100644 other/design_underground_system.cpp create mode 100644 other/detect_capital.cpp create mode 100644 other/detect_capital.rs create mode 100644 other/determine_string_halves.cpp create mode 100644 other/determine_string_halves.rs create mode 100644 other/determine_strings_close.cpp create mode 100644 other/determine_strings_close.rs create mode 100644 other/detonate_max_bombs.cpp create mode 100644 other/diff_two_array.cpp create mode 100644 other/discount_n_orders.cpp create mode 100644 other/divide_nodes_max_groups.cpp create mode 100644 other/domino_tromino_tiling.cpp create mode 100644 other/domino_tromino_tiling.rs create mode 100644 other/earliest_possible_full_bloom.cpp create mode 100644 other/earliest_possible_full_bloom.rs create mode 100644 other/edit_distance.cpp create mode 100644 other/eliminate_monsters.cpp create mode 100644 other/encode_decode_tinyurl.cpp create mode 100644 other/equal_row_col_pair.cpp create mode 100644 other/erect_fence.cpp create mode 100644 other/erect_fence.rs create mode 100644 other/eval_reverse_polish_notation.cpp create mode 100644 other/eval_reverse_polish_notation.rs create mode 100644 other/eventual_safe_states.cpp create mode 100644 other/excel_sheet_column_title.cpp create mode 100644 other/extra_char_string.cpp create mode 100644 other/fair_distribution_cookie.cpp create mode 100644 other/far_from_land.cpp create mode 100644 other/fibonacci_number.cpp create mode 100644 other/find_all_anagrams.cpp create mode 100644 other/find_building_alice_bob_meet.cpp create mode 100644 other/find_critical_edge_tree.cpp create mode 100644 other/find_duplicate_file.cpp create mode 100644 other/find_duplicate_subtree.cpp create mode 100644 other/find_first_last_array.cpp create mode 100644 other/find_groups_farmland.cpp create mode 100644 other/find_highest_altitude.cpp create mode 100644 other/find_k_beauty_num.cpp create mode 100644 other/find_k_closest_elements.cpp create mode 100644 other/find_k_pair_sum.cpp create mode 100644 other/find_max_sum_node_val.cpp create mode 100644 other/find_median_data_stream.cpp create mode 100644 other/find_median_data_stream.rs create mode 100644 other/find_orig_array_double.cpp create mode 100644 other/find_path_graph.cpp create mode 100644 other/find_path_graph.rs create mode 100644 other/find_player_zero_one_loss.cpp create mode 100644 other/find_player_zero_one_loss.rs create mode 100644 other/find_replace_pattern.cpp create mode 100644 other/find_safest_path_grid.cpp create mode 100644 other/find_score_arr_mark.cpp create mode 100644 other/find_smallest_letter.cpp create mode 100644 other/find_town_judge.cpp create mode 100644 other/first_missing_positive.cpp create mode 100644 other/first_unique_char_string.cpp create mode 100644 other/flatten_binary_to_linked.cpp create mode 100644 other/flip_string_monotone_increase.cpp create mode 100644 other/freedom_trail.cpp create mode 100644 other/frog_jump.cpp create mode 100644 other/fruit_into_baskets.cpp create mode 100644 other/furthest_building_reach.cpp create mode 100644 other/gas_station.cpp create mode 100644 other/gas_station.rs create mode 100644 other/greatest_common_div_string.cpp create mode 100644 other/greatest_sum_div_three.cpp create mode 100644 other/group_anagrams.cpp create mode 100644 other/group_anagrams.rs create mode 100644 other/guess_number_high_low.cpp create mode 100644 other/guess_number_high_low.rs create mode 100644 other/hand_of_straights.cpp create mode 100644 other/happy_number.cpp create mode 100644 other/house_robber.cpp create mode 100644 other/house_robber.rs create mode 100644 other/idx_first_occur_str.cpp create mode 100644 other/image_overlap.cpp create mode 100644 other/image_overlap.rs create mode 100644 other/implement_queue_stacks.cpp create mode 100644 other/increasing_triplet_subsequence.cpp create mode 100644 other/inform_employees.cpp create mode 100644 other/insert_delete_getrandom.cpp create mode 100644 other/insert_delete_getrandom.rs create mode 100644 other/insert_interval.cpp create mode 100644 other/int_roman.cpp create mode 100644 other/int_roman.rs create mode 100644 other/integer_break.cpp create mode 100644 other/interleaving_string.cpp create mode 100644 other/invert_binary_tree.cpp create mode 100644 other/ipo.cpp create mode 100644 other/is_graph_biparite.cpp create mode 100644 other/jump_game.cpp create mode 100644 other/jump_game.rs create mode 100644 other/jump_game3.cpp create mode 100644 other/jump_game3.rs create mode 100644 other/jump_game4.cpp create mode 100644 other/jump_game6.cpp create mode 100644 other/k_inverse_pairs.cpp create mode 100644 other/k_radius_subarr.cpp create mode 100644 other/keys_and_rooms.cpp create mode 100644 other/keys_and_rooms.rs create mode 100644 other/kids_max_num_candy.cpp create mode 100644 other/knight_probability_chessboard.cpp create mode 100644 other/koko_eating_bananas.cpp create mode 100644 other/kth_element_in_stream.cpp create mode 100644 other/kth_largest_element.cpp create mode 100644 other/kth_largest_element_stream.cpp create mode 100644 other/kth_missing_pos_num.cpp create mode 100644 other/kth_smallest_lexicographical.cpp create mode 100644 other/kth_smallest_sorted_matrix.cpp create mode 100644 other/largest_colour_value_graph.cpp create mode 100644 other/largest_int_add_target.cpp create mode 100644 other/largest_multiple_three.cpp create mode 100644 other/largest_odd_num_string.cpp create mode 100644 other/largest_perimeter_triangle.cpp create mode 100644 other/last_day_cross.cpp create mode 100644 other/leaf_similar_trees.cpp create mode 100644 other/leaf_similar_trees.rs create mode 100644 other/letter_combo_number.cpp create mode 100644 other/lexicographical_numbers.cpp create mode 100644 other/lexicographically_small_string.cpp create mode 100644 other/lfu_cache.cpp create mode 100644 other/linked_list_cycle2.cpp create mode 100644 other/linked_list_random.cpp create mode 100644 other/longest_arithmetic_subseq.cpp create mode 100644 other/longest_arithmetic_subseq_diff.cpp create mode 100644 other/longest_common_subseq.cpp create mode 100644 other/longest_common_subseq.rs create mode 100644 other/longest_consecutive_sequence.cpp create mode 100644 other/longest_cycle_graph.cpp create mode 100644 other/longest_happy_string.cpp create mode 100644 other/longest_increasing_subseq.cpp create mode 100644 other/longest_palindrome_concat.cpp create mode 100644 other/longest_palindrome_concat.rs create mode 100644 other/longest_palindromic_subseq.cpp create mode 100644 other/longest_palindromic_substr.cpp create mode 100644 other/longest_path_diff_adjacent_char.cpp create mode 100644 other/longest_path_diff_adjacent_char.rs create mode 100644 other/longest_string_chain.cpp create mode 100644 other/longest_subarr_ones.cpp create mode 100644 other/longest_subseq_lim_sum.cpp create mode 100644 other/longest_subseq_lim_sum.rs create mode 100644 other/longest_substring_no_repeat.cpp create mode 100644 other/longest_valid_course.cpp create mode 100644 other/longest_valid_parentheses.cpp create mode 100644 other/longest_word_dict.cpp create mode 100644 other/longest_zigzag_bt.cpp create mode 100644 other/lowest_common_ancestor.cpp create mode 100644 other/lowest_common_ancestor_bst.cpp create mode 100644 other/lru_cache.cpp create mode 100644 other/magnetic_force_2_balls.cpp create mode 100644 other/make_array_increasing.cpp create mode 100644 other/make_string_great.cpp create mode 100644 other/make_string_great.rs create mode 100644 other/make_sum_divisible_p.cpp create mode 100644 other/marbles_in_bags.cpp create mode 100644 other/matchsticks_square.cpp create mode 100644 other/matrix_diagonal_sum.cpp create mode 100644 other/max_69.cpp create mode 100644 other/max_69.rs create mode 100644 other/max_area_cake.cpp create mode 100644 other/max_area_island.cpp create mode 100644 other/max_average_pass_ration.cpp create mode 100644 other/max_bags_rocks.cpp create mode 100644 other/max_bags_rocks.rs create mode 100644 other/max_consecutive_ones3.cpp create mode 100644 other/max_depth_binary_tree.cpp create mode 100644 other/max_diff_node_ancestor.cpp create mode 100644 other/max_diff_node_ancestor.rs create mode 100644 other/max_distance_closest_person.cpp create mode 100644 other/max_erasure_value.cpp create mode 100644 other/max_ice_cream_bars.cpp create mode 100644 other/max_ice_cream_bars.rs create mode 100644 other/max_len_concat_str.cpp create mode 100644 other/max_len_concat_str.rs create mode 100644 other/max_length_pair_chain.cpp create mode 100644 other/max_length_repeated_subarr.cpp create mode 100644 other/max_network_rank.cpp create mode 100644 other/max_num_events_attended2.cpp create mode 100644 other/max_num_ksum_pair.cpp create mode 100644 other/max_num_tasks_assign.cpp create mode 100644 other/max_num_vowel_substr.cpp create mode 100644 other/max_performance_team.cpp create mode 100644 other/max_points_from_cards.cpp create mode 100644 other/max_points_line.cpp create mode 100644 other/max_points_line.rs create mode 100644 other/max_product_3num.cpp create mode 100644 other/max_product_split_bt.cpp create mode 100644 other/max_product_split_bt.rs create mode 100644 other/max_product_word_len.cpp create mode 100644 other/max_profit_job.cpp create mode 100644 other/max_profit_job.rs create mode 100644 other/max_running_time_n_computer.cpp create mode 100644 other/max_score_good_subarr.cpp create mode 100644 other/max_score_mult_opp.cpp create mode 100644 other/max_score_n_operations.cpp create mode 100644 other/max_score_node_sequence.cpp create mode 100644 other/max_subarray.cpp create mode 100644 other/max_subseq_score.cpp create mode 100644 other/max_sum_3_noverlap_subarr.cpp create mode 100644 other/max_sum_binary_tree.cpp create mode 100644 other/max_sum_circular_subarr.cpp create mode 100644 other/max_sum_rectangle.cpp create mode 100644 other/max_total_importance_road.cpp create mode 100644 other/max_tranfer_requests.cpp create mode 100644 other/max_twin_sum_list.cpp create mode 100644 other/max_units_truck.cpp create mode 100644 other/max_val_k_coin_pile.cpp create mode 100644 other/max_value_give_idx.cpp create mode 100644 other/max_width_binary_tree.cpp create mode 100644 other/maximise_confusion_exam.cpp create mode 100644 other/maximise_grid_happiness.cpp create mode 100644 other/merge_sorted_array.cpp create mode 100644 other/merge_sorted_array.rs create mode 100644 other/merge_string_alt.cpp create mode 100644 other/middle_linked_list.cpp create mode 100644 other/middle_linked_list.rs create mode 100644 other/min_abs_diff_bst.cpp create mode 100644 other/min_ascii_strs.cpp create mode 100644 other/min_avg_diff.cpp create mode 100644 other/min_avg_diff.rs create mode 100644 other/min_cost_arr_equal.cpp create mode 100644 other/min_cost_change_expr.cpp create mode 100644 other/min_cost_climbing_stairs.cpp create mode 100644 other/min_cost_convert_string1.cpp create mode 100644 other/min_cost_cut_stick.cpp create mode 100644 other/min_cost_ticket.cpp create mode 100644 other/min_deletions_unique_char.cpp create mode 100644 other/min_depth_binary_tree.cpp create mode 100644 other/min_deviation_arr.cpp create mode 100644 other/min_difficulty_schedule.cpp create mode 100644 other/min_dist_bst_node.cpp create mode 100644 other/min_dist_target_element.cpp create mode 100644 other/min_falling_path_sum.cpp create mode 100644 other/min_falling_path_sum.rs create mode 100644 other/min_flips_abc.cpp create mode 100644 other/min_fuel_report_captial.cpp create mode 100644 other/min_genetic_mutation.cpp create mode 100644 other/min_genetic_mutation.rs create mode 100644 other/min_incr_arr_unique.cpp create mode 100644 other/min_insertion_make_palindrome.cpp create mode 100644 other/min_jump_reach_home.cpp create mode 100644 other/min_max_array.cpp create mode 100644 other/min_max_diff_pair.cpp create mode 100644 other/min_move_palindrome.cpp create mode 100644 other/min_moves_equal_array2.cpp create mode 100644 other/min_num_arrow_balloon.cpp create mode 100644 other/min_num_arrow_balloon.rs create mode 100644 other/min_num_days_disconnect_island.cpp create mode 100644 other/min_num_opp_arr_cont.cpp create mode 100644 other/min_num_refueling_stops.cpp create mode 100644 other/min_num_remove_mountain_arr.cpp create mode 100644 other/min_num_vertices_node.cpp create mode 100644 other/min_one_bit_0.cpp create mode 100644 other/min_one_bit_0.rs create mode 100644 other/min_operations_x_zero.cpp create mode 100644 other/min_path_sum.cpp create mode 100644 other/min_rounds_complete_all_tasks.cpp create mode 100644 other/min_rounds_complete_all_tasks.rs create mode 100644 other/min_score_path_city.cpp create mode 100644 other/min_size_subarr_sum.cpp create mode 100644 other/min_speed_arrive_time.cpp create mode 100644 other/min_stack.cpp create mode 100644 other/min_swap_group_1.cpp create mode 100644 other/min_time_apples_tree.cpp create mode 100644 other/min_time_apples_tree.rs create mode 100644 other/min_time_complete_trip.cpp create mode 100644 other/min_time_rope_colorful.cpp create mode 100644 other/min_time_visit_cell_grid.cpp create mode 100644 other/min_window_substring.cpp create mode 100644 other/min_window_substring.rs create mode 100644 other/mirror_reflection.cpp create mode 100644 other/missing_number.cpp create mode 100644 other/modify_graph_edge_weight.cpp create mode 100644 other/most_stones_remove.cpp create mode 100644 other/most_stones_remove.rs create mode 100644 other/most_water.cpp create mode 100644 other/my_calendar.cpp create mode 100644 other/my_calendar2.cpp create mode 100644 other/my_calendar3.cpp create mode 100644 other/n_ary_tree_traverse.cpp create mode 100644 other/n_queens2.cpp create mode 100644 other/naming_company.cpp create mode 100644 other/nearest_exit_maze.cpp create mode 100644 other/nearest_exit_maze.rs create mode 100644 other/new_21_game.cpp create mode 100644 other/next_greater_element2.cpp create mode 100644 other/next_permutation.cpp create mode 100644 other/non_decreasing_array.cpp create mode 100644 other/non_decreasing_subseq.cpp create mode 100644 other/non_overlapping_interval.cpp create mode 100644 other/nth_tribonacci_number.cpp create mode 100644 other/num_bad_pairs.cpp create mode 100644 other/num_bad_pairs.rs create mode 100644 other/num_closed_islands.cpp create mode 100644 other/num_cut_pizza.cpp create mode 100644 other/num_dice_roll_target_sum.cpp create mode 100644 other/num_enclaves.cpp create mode 100644 other/num_even_nums.cpp create mode 100644 other/num_good_path.cpp create mode 100644 other/num_increasing_path.cpp create mode 100644 other/num_longest_incr_subseq.cpp create mode 100644 other/num_matching_subsequence.cpp create mode 100644 other/num_music_playlists.cpp create mode 100644 other/num_nodes_sub_tree.cpp create mode 100644 other/num_nodes_sub_tree.rs create mode 100644 other/num_op_connect_network.cpp create mode 100644 other/num_people_aware_secret.cpp create mode 100644 other/num_same_consecutive_diff.cpp create mode 100644 other/num_smaller_num_self.cpp create mode 100644 other/num_squareful_arrays.cpp create mode 100644 other/num_subseq_satisfy.cpp create mode 100644 other/num_to_hex_binary.cpp create mode 100644 other/num_valid_words_puzzle.cpp create mode 100644 other/num_ways_dict.cpp create mode 100644 other/num_ways_remain_place.cpp create mode 100644 other/num_ways_reorder_array.cpp create mode 100644 other/num_weak_char_game.cpp create mode 100644 other/num_zero_filled_subarr.cpp create mode 100644 other/number_1bits.cpp create mode 100644 other/number_atoms.cpp create mode 100644 other/number_islands.cpp create mode 100644 other/number_provinces.cpp create mode 100644 other/number_steps_to_0.cpp create mode 100644 other/number_submatrices_sum_target.cpp create mode 100644 other/odd_even_linke_list.cpp create mode 100644 other/odd_even_linke_list.rs create mode 100644 other/ones_and_zeroes.cpp create mode 100644 other/online_stock_span.cpp create mode 100644 other/online_stock_span.rs create mode 100644 other/optimal_partition_string.cpp create mode 100644 other/orderly_queue.cpp create mode 100644 other/orderly_queue.rs create mode 100644 other/out_of_bounds_paths.cpp create mode 100644 other/pacific_atlantic_water_flow.cpp create mode 100644 other/paint_house3.cpp create mode 100644 other/painting_grid_three_colour.cpp create mode 100644 other/painting_walls.cpp create mode 100644 other/pairs_spells_potions.cpp create mode 100644 other/palindrome_linked_list.cpp create mode 100644 other/palindrome_number.rs create mode 100644 other/palindrome_pairs.cpp create mode 100644 other/palindrome_partitioning.cpp create mode 100644 other/parallel_courses3.cpp create mode 100644 other/partition_array_max_sum.cpp create mode 100644 other/partition_array_pivot.rs create mode 100644 other/partition_list.cpp create mode 100644 other/partition_min_binary_array.cpp create mode 100644 other/pascals_triangle.cpp create mode 100644 other/path_max_probability.cpp create mode 100644 other/path_min_effort.cpp create mode 100644 other/path_min_effort1.cpp create mode 100644 other/path_sum.cpp create mode 100644 other/path_sum2.cpp create mode 100644 other/peak_idx_mountain_arr.cpp create mode 100644 other/peeking_iterator.cpp create mode 100644 other/percentage_letter_string.cpp create mode 100644 other/perfect_squares.cpp create mode 100644 other/perfect_squares.rs create mode 100644 other/permutation_in_string.cpp create mode 100644 other/permutation_sequence.cpp create mode 100644 other/permutations.cpp create mode 100644 other/permutations2.cpp create mode 100644 other/poor-pigs.cpp create mode 100644 other/possible_bipartition.cpp create mode 100644 other/possible_bipartition.rs create mode 100644 other/power_3.cpp create mode 100644 other/power_of_four.cpp create mode 100644 other/power_of_four.rs create mode 100644 other/power_of_two.cpp create mode 100644 other/predict_winner.cpp create mode 100644 other/prefix_suffix_search.cpp create mode 100644 other/profitable_schemes.cpp create mode 100644 other/pseudo_palindrome_binary_tree.cpp create mode 100644 other/push_dominoes.cpp create mode 100644 other/queue_reconstruction.cpp create mode 100644 other/range_sum_bst.cpp create mode 100644 other/range_sum_bst.rs create mode 100644 other/range_sum_query_2d.cpp create mode 100644 other/range_sum_query_mutable.cpp create mode 100644 other/ransom_note.cpp create mode 100644 other/rectangle_area.cpp create mode 100644 other/rectangle_area.rs create mode 100644 other/rectangle_fewest_squares.cpp create mode 100644 other/reduce_array_size_half.cpp create mode 100644 other/reducing_dishes.cpp create mode 100644 other/remove_adjacent_dup.cpp create mode 100644 other/remove_adjacent_dup_str.cpp create mode 100644 other/remove_adjacent_dup_str.rs create mode 100644 other/remove_boxes.cpp create mode 100644 other/remove_dupplicate.cpp create mode 100644 other/remove_dupplicate.rs create mode 100644 other/remove_element.cpp create mode 100644 other/remove_element.rs create mode 100644 other/remove_max_num_edge_traverse.cpp create mode 100644 other/remove_nth_node.cpp create mode 100644 other/remove_palindromic_subsequence.cpp create mode 100644 other/remove_star_string.cpp create mode 100644 other/remove_stones.cpp create mode 100644 other/remove_stones.rs create mode 100644 other/remove_subfolder_filesystem.cpp create mode 100644 other/remove_substring.cpp create mode 100644 other/reorder_route_city_zero.cpp create mode 100644 other/reordered_power2.cpp create mode 100644 other/reorganise_string.cpp create mode 100644 other/repeated_substring_pattern.cpp create mode 100644 other/restore_array.cpp create mode 100644 other/restore_ip_addr.cpp create mode 100644 other/reverse_integer.cpp create mode 100644 other/reverse_linked_list.cpp create mode 100644 other/reverse_linked_list2.cpp create mode 100644 other/reverse_string.cpp create mode 100644 other/reverse_string2.cpp create mode 100644 other/reverse_string3.cpp create mode 100644 other/reverse_vowel_string.cpp create mode 100644 other/reverse_vowel_string.rs create mode 100644 other/reverse_word_string.cpp create mode 100644 other/reverse_word_string.rs create mode 100644 other/roman_2_int.cpp create mode 100644 other/rotate_function.cpp create mode 100644 other/rotate_image.cpp create mode 100644 other/rotate_image.rs create mode 100644 other/running_sum_1d_array.cpp create mode 100644 other/same_tree.cpp create mode 100644 other/same_tree.rs create mode 100644 other/satisfiability_eqaulity.cpp create mode 100644 other/scramble_string.cpp create mode 100644 other/search_2d_matrix.cpp create mode 100644 other/search_2d_matrix2.cpp create mode 100644 other/search_rotated_array.cpp create mode 100644 other/search_rotated_array2.cpp create mode 100644 other/search_suggestion_sys.cpp create mode 100644 other/set_matrix_0.rs create mode 100644 other/set_mismatch.cpp create mode 100644 other/set_mismatch.rs create mode 100644 other/short_encoding_words.cpp create mode 100644 other/shortest_bridge.cpp create mode 100644 other/shortest_dist_road_addition1.cpp create mode 100644 other/shortest_path_alternate_color.cpp create mode 100644 other/shortest_path_binary_matrix.cpp create mode 100644 other/shortest_path_grid_obstacle.cpp create mode 100644 other/shortest_path_grid_obstacle.rs create mode 100644 other/shortest_path_keys.cpp create mode 100644 other/shortest_path_vis_nodes.cpp create mode 100644 other/shortest_unsorted_subarr.cpp create mode 100644 other/shuffle_the_array.cpp create mode 100644 other/similar_string_group.cpp create mode 100644 other/simplify_path.cpp create mode 100644 other/single_element_sorted_arr.cpp create mode 100644 other/single_number.cpp create mode 100644 other/single_number.rs create mode 100644 other/single_number2.cpp create mode 100644 other/single_product_array.cpp create mode 100644 other/single_threaded_cpu.cpp create mode 100644 other/single_threaded_cpu.rs create mode 100644 other/skyline_problem.cpp create mode 100644 other/sliding_puzzle.cpp create mode 100644 other/sliding_window_max.cpp create mode 100644 other/smallest_num_set.cpp create mode 100644 other/smallest_string_swaps.cpp create mode 100644 other/smallest_sufficient_team.cpp create mode 100644 other/snakes_ladders.cpp create mode 100644 other/snapshot_array.cpp create mode 100644 other/sort_array.cpp create mode 100644 other/sort_array_parity.cpp create mode 100644 other/sort_char_freq.cpp create mode 100644 other/sort_char_freq.rs create mode 100644 other/sort_items_dependencies.cpp create mode 100644 other/sort_matrix_diagonal.cpp create mode 100644 other/sorted_arrary_bst.cpp create mode 100644 other/soup_servings.cpp create mode 100644 other/spiral_matrix.cpp create mode 100644 other/spiral_matrix2.cpp create mode 100644 other/split_array_consec_subseq.cpp create mode 100644 other/stack_using_queues.cpp create mode 100644 other/stamping_sequence.cpp create mode 100644 other/steps_arr_increasing.cpp create mode 100644 other/stone_game2.cpp create mode 100644 other/stone_game3.cpp create mode 100644 other/stone_game4.cpp create mode 100644 other/strange_printer.cpp create mode 100644 other/string_compression.cpp create mode 100644 other/string_compression.rs create mode 100644 other/string_compression2.cpp create mode 100644 other/string_compression2.rs create mode 100644 other/string_without_3a3b.cpp create mode 100644 other/subarr_fixed_bound.cpp create mode 100644 other/subarr_product_less_k.cpp create mode 100644 other/subarr_sum_divisible_k.cpp create mode 100644 other/substr_largest_variance.cpp create mode 100644 other/sum_dist_tree.cpp create mode 100644 other/sum_dist_tree.rs create mode 100644 other/sum_even_num_queries.cpp create mode 100644 other/sum_root_leaf_num.cpp create mode 100644 other/sum_subarr_mins.cpp create mode 100644 other/sum_subarr_mins.rs create mode 100644 other/sum_subset_xor.cpp create mode 100644 other/summary_ranges.cpp create mode 100644 other/swap_node_linked_list.cpp create mode 100644 other/swap_nodes_pairs.cpp create mode 100644 other/symmetric_tree.cpp create mode 100644 other/tallest_billboard.cpp create mode 100644 other/task_scheduler.cpp create mode 100644 other/text_justification.cpp create mode 100644 other/thousand_separator.cpp create mode 100644 other/time_base_key_val.cpp create mode 100644 other/toeplitz_matrix.cpp create mode 100644 other/toeplitz_matrix.rs create mode 100644 other/top_k_freq_element.cpp create mode 100644 other/top_k_freq_element.rs create mode 100644 other/top_k_freq_words.cpp create mode 100644 other/top_k_freq_words.rs create mode 100644 other/transpose_matrix.cpp create mode 100644 other/trapping_rain_water.cpp create mode 100644 other/trie_prefix.cpp create mode 100644 other/two_sum.cpp create mode 100644 other/two_sum_2.cpp create mode 100644 other/two_sum_4.cpp create mode 100644 other/ugly_number.cpp create mode 100644 other/ugly_number.rs create mode 100644 other/uncrossed_lines.cpp create mode 100644 other/unique_bst.cpp create mode 100644 other/unique_bst2.cpp create mode 100644 other/unique_morse_code_words.cpp create mode 100644 other/unique_num_occurrences.cpp create mode 100644 other/unique_num_occurrences.rs create mode 100644 other/unique_paths.cpp create mode 100644 other/unique_paths2.cpp create mode 100644 other/unique_paths3.cpp create mode 100644 other/unique_paths3.rs create mode 100644 other/utf8_validation.cpp create mode 100644 other/valid_anagram.cpp create mode 100644 other/valid_arrangement_pairs.cpp create mode 100644 other/valid_number.cpp create mode 100644 other/valid_parentheses.cpp create mode 100644 other/valid_stack_seq.cpp create mode 100644 other/valid_sudoku.cpp create mode 100644 other/valid_sudoku.rs create mode 100644 other/validate_bst.cpp create mode 100644 other/verify_alien_dict.cpp create mode 100644 other/vertical_order_bst.cpp create mode 100644 other/ways_to_paint_nx3_grid.cpp create mode 100644 other/where_will_ball_fall.cpp create mode 100644 other/where_will_ball_fall.rs create mode 100644 other/wiggle_subsequence.cpp create mode 100644 other/word_break.cpp create mode 100644 other/word_ladder.cpp create mode 100644 other/word_ladder2.cpp create mode 100644 other/word_pattern.cpp create mode 100644 other/word_pattern.rs create mode 100644 other/word_search.cpp create mode 100644 other/word_search2.cpp create mode 100644 other/word_search2.rs create mode 100644 other/word_subsets.cpp create mode 100644 other/zigzag_conversion.cpp delete mode 100644 out_of_bounds_paths.cpp delete mode 100644 pacific_atlantic_water_flow.cpp delete mode 100644 paint_house3.cpp delete mode 100644 painting_grid_three_colour.cpp delete mode 100644 painting_walls.cpp delete mode 100644 pairs_spells_potions.cpp delete mode 100644 palindrome_linked_list.cpp delete mode 100644 palindrome_number.rs delete mode 100644 palindrome_pairs.cpp delete mode 100644 palindrome_partitioning.cpp delete mode 100644 parallel_courses3.cpp delete mode 100644 partition_array_max_sum.cpp delete mode 100644 partition_array_pivot.rs delete mode 100644 partition_list.cpp delete mode 100644 partition_min_binary_array.cpp delete mode 100644 pascals_triangle.cpp delete mode 100644 path_max_probability.cpp delete mode 100644 path_min_effort.cpp delete mode 100644 path_min_effort1.cpp delete mode 100644 path_sum.cpp delete mode 100644 path_sum2.cpp delete mode 100644 peak_idx_mountain_arr.cpp delete mode 100644 peeking_iterator.cpp delete mode 100644 percentage_letter_string.cpp delete mode 100644 perfect_squares.cpp delete mode 100644 perfect_squares.rs delete mode 100644 permutation_in_string.cpp delete mode 100644 permutation_sequence.cpp delete mode 100644 permutations.cpp delete mode 100644 permutations2.cpp delete mode 100644 poor-pigs.cpp delete mode 100644 possible_bipartition.cpp delete mode 100644 possible_bipartition.rs delete mode 100644 power_3.cpp delete mode 100644 power_of_four.cpp delete mode 100644 power_of_four.rs delete mode 100644 power_of_two.cpp delete mode 100644 predict_winner.cpp delete mode 100644 prefix_suffix_search.cpp delete mode 100644 profitable_schemes.cpp delete mode 100644 pseudo_palindrome_binary_tree.cpp delete mode 100644 push_dominoes.cpp delete mode 100644 queue_reconstruction.cpp delete mode 100644 range_sum_bst.cpp delete mode 100644 range_sum_bst.rs delete mode 100644 range_sum_query_2d.cpp delete mode 100644 range_sum_query_mutable.cpp delete mode 100644 ransom_note.cpp delete mode 100644 rectangle_area.cpp delete mode 100644 rectangle_area.rs delete mode 100644 rectangle_fewest_squares.cpp delete mode 100644 reduce_array_size_half.cpp delete mode 100644 reducing_dishes.cpp delete mode 100644 remove_adjacent_dup.cpp delete mode 100644 remove_adjacent_dup_str.cpp delete mode 100644 remove_adjacent_dup_str.rs delete mode 100644 remove_boxes.cpp delete mode 100644 remove_dupplicate.cpp delete mode 100644 remove_dupplicate.rs delete mode 100644 remove_element.cpp delete mode 100644 remove_element.rs delete mode 100644 remove_max_num_edge_traverse.cpp delete mode 100644 remove_nth_node.cpp delete mode 100644 remove_palindromic_subsequence.cpp delete mode 100644 remove_star_string.cpp delete mode 100644 remove_stones.cpp delete mode 100644 remove_stones.rs delete mode 100644 remove_subfolder_filesystem.cpp delete mode 100644 remove_substring.cpp delete mode 100644 reorder_route_city_zero.cpp delete mode 100644 reordered_power2.cpp delete mode 100644 reorganise_string.cpp delete mode 100644 repeated_substring_pattern.cpp delete mode 100644 restore_array.cpp delete mode 100644 restore_ip_addr.cpp delete mode 100644 reverse_integer.cpp delete mode 100644 reverse_linked_list.cpp delete mode 100644 reverse_linked_list2.cpp delete mode 100644 reverse_string.cpp delete mode 100644 reverse_string2.cpp delete mode 100644 reverse_string3.cpp delete mode 100644 reverse_vowel_string.cpp delete mode 100644 reverse_vowel_string.rs delete mode 100644 reverse_word_string.cpp delete mode 100644 reverse_word_string.rs delete mode 100644 roman_2_int.cpp delete mode 100644 rotate_function.cpp delete mode 100644 rotate_image.cpp delete mode 100644 rotate_image.rs delete mode 100644 running_sum_1d_array.cpp delete mode 100644 same_tree.cpp delete mode 100644 same_tree.rs delete mode 100644 satisfiability_eqaulity.cpp delete mode 100644 scramble_string.cpp delete mode 100644 search_2d_matrix.cpp delete mode 100644 search_2d_matrix2.cpp delete mode 100644 search_rotated_array.cpp delete mode 100644 search_rotated_array2.cpp delete mode 100644 search_suggestion_sys.cpp delete mode 100644 set_matrix_0.rs delete mode 100644 set_mismatch.cpp delete mode 100644 set_mismatch.rs delete mode 100644 short_encoding_words.cpp delete mode 100644 shortest_bridge.cpp delete mode 100644 shortest_dist_road_addition1.cpp delete mode 100644 shortest_path_alternate_color.cpp delete mode 100644 shortest_path_binary_matrix.cpp delete mode 100644 shortest_path_grid_obstacle.cpp delete mode 100644 shortest_path_grid_obstacle.rs delete mode 100644 shortest_path_keys.cpp delete mode 100644 shortest_path_vis_nodes.cpp delete mode 100644 shortest_unsorted_subarr.cpp delete mode 100644 shuffle_the_array.cpp delete mode 100644 similar_string_group.cpp delete mode 100644 simplify_path.cpp delete mode 100644 single_element_sorted_arr.cpp delete mode 100644 single_number.cpp delete mode 100644 single_number.rs delete mode 100644 single_number2.cpp delete mode 100644 single_product_array.cpp delete mode 100644 single_threaded_cpu.cpp delete mode 100644 single_threaded_cpu.rs delete mode 100644 skyline_problem.cpp delete mode 100644 sliding_puzzle.cpp delete mode 100644 sliding_window_max.cpp delete mode 100644 smallest_num_set.cpp delete mode 100644 smallest_string_swaps.cpp delete mode 100644 smallest_sufficient_team.cpp delete mode 100644 snakes_ladders.cpp delete mode 100644 snapshot_array.cpp delete mode 100644 sort_array.cpp delete mode 100644 sort_array_parity.cpp delete mode 100644 sort_char_freq.cpp delete mode 100644 sort_char_freq.rs delete mode 100644 sort_items_dependencies.cpp delete mode 100644 sort_matrix_diagonal.cpp delete mode 100644 sorted_arrary_bst.cpp delete mode 100644 soup_servings.cpp delete mode 100644 spiral_matrix.cpp delete mode 100644 spiral_matrix2.cpp delete mode 100644 split_array_consec_subseq.cpp delete mode 100644 stack_using_queues.cpp delete mode 100644 stamping_sequence.cpp delete mode 100644 steps_arr_increasing.cpp delete mode 100644 stone_game2.cpp delete mode 100644 stone_game3.cpp delete mode 100644 stone_game4.cpp delete mode 100644 strange_printer.cpp delete mode 100644 string_compression.cpp delete mode 100644 string_compression.rs delete mode 100644 string_compression2.cpp delete mode 100644 string_compression2.rs delete mode 100644 string_without_3a3b.cpp delete mode 100644 subarr_fixed_bound.cpp delete mode 100644 subarr_product_less_k.cpp delete mode 100644 subarr_sum_divisible_k.cpp delete mode 100644 substr_largest_variance.cpp delete mode 100644 sum_dist_tree.cpp delete mode 100644 sum_dist_tree.rs delete mode 100644 sum_even_num_queries.cpp delete mode 100644 sum_root_leaf_num.cpp delete mode 100644 sum_subarr_mins.cpp delete mode 100644 sum_subarr_mins.rs delete mode 100644 sum_subset_xor.cpp delete mode 100644 summary_ranges.cpp delete mode 100644 swap_node_linked_list.cpp delete mode 100644 swap_nodes_pairs.cpp delete mode 100644 symmetric_tree.cpp delete mode 100644 tallest_billboard.cpp delete mode 100644 task_scheduler.cpp delete mode 100644 text_justification.cpp delete mode 100644 thousand_separator.cpp delete mode 100644 time_base_key_val.cpp delete mode 100644 toeplitz_matrix.cpp delete mode 100644 toeplitz_matrix.rs delete mode 100644 top_k_freq_element.cpp delete mode 100644 top_k_freq_element.rs delete mode 100644 top_k_freq_words.cpp delete mode 100644 top_k_freq_words.rs delete mode 100644 transpose_matrix.cpp delete mode 100644 trapping_rain_water.cpp delete mode 100644 trie_prefix.cpp delete mode 100644 two_sum.cpp delete mode 100644 two_sum_2.cpp delete mode 100644 two_sum_4.cpp delete mode 100644 ugly_number.cpp delete mode 100644 ugly_number.rs delete mode 100644 uncrossed_lines.cpp delete mode 100644 unique_bst.cpp delete mode 100644 unique_bst2.cpp delete mode 100644 unique_morse_code_words.cpp delete mode 100644 unique_num_occurrences.cpp delete mode 100644 unique_num_occurrences.rs delete mode 100644 unique_paths.cpp delete mode 100644 unique_paths2.cpp delete mode 100644 unique_paths3.cpp delete mode 100644 unique_paths3.rs delete mode 100644 utf8_validation.cpp delete mode 100644 valid_anagram.cpp delete mode 100644 valid_arrangement_pairs.cpp delete mode 100644 valid_number.cpp delete mode 100644 valid_parentheses.cpp delete mode 100644 valid_stack_seq.cpp delete mode 100644 valid_sudoku.cpp delete mode 100644 valid_sudoku.rs delete mode 100644 validate_bst.cpp delete mode 100644 verify_alien_dict.cpp delete mode 100644 vertical_order_bst.cpp delete mode 100644 ways_to_paint_nx3_grid.cpp delete mode 100644 where_will_ball_fall.cpp delete mode 100644 where_will_ball_fall.rs delete mode 100644 wiggle_subsequence.cpp delete mode 100644 word_break.cpp delete mode 100644 word_ladder.cpp delete mode 100644 word_ladder2.cpp delete mode 100644 word_pattern.cpp delete mode 100644 word_pattern.rs delete mode 100644 word_search.cpp delete mode 100644 word_search2.cpp delete mode 100644 word_search2.rs delete mode 100644 word_subsets.cpp delete mode 100644 zigzag_conversion.cpp diff --git a/01_matrix.cpp b/01_matrix.cpp deleted file mode 100644 index f6d9c2d..0000000 --- a/01_matrix.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector> updateMatrix(vector> &mat) { - int m = mat.size(), n = mat[0].size(); - vector> ans(m, vector(n, INT_MAX)); - queue> 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> 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/132_pattern.cpp b/132_pattern.cpp deleted file mode 100644 index a9f0c43..0000000 --- a/132_pattern.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool find132pattern(vector &nums) { - int n = nums.size(), minI[n]; - stack 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 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/3sum_closest.cpp b/3sum_closest.cpp deleted file mode 100644 index 3050ee0..0000000 --- a/3sum_closest.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int threeSumClosest(vector &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 nums = {-1, 2, 1, -4}; - int target = 1; - cout << obj.threeSumClosest(nums, target); -} diff --git a/add_arr_form_int.cpp b/add_arr_form_int.cpp deleted file mode 100644 index 1cb8f7a..0000000 --- a/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 addToArrayForm(vector &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 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/add_binary.cpp b/add_binary.cpp deleted file mode 100644 index 9afc1dc..0000000 --- a/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/add_digits.cpp b/add_digits.cpp deleted file mode 100644 index ec8abfa..0000000 --- a/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/add_row_tree.cpp b/add_row_tree.cpp deleted file mode 100644 index 54ebfb4..0000000 --- a/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 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/add_search_words_data.cpp b/add_search_words_data.cpp deleted file mode 100644 index 5c5e0f4..0000000 --- a/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> 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/add_space_string.cpp b/add_space_string.cpp deleted file mode 100644 index 9a9b7ea..0000000 --- a/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 &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 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/add_two_num2.cpp b/add_two_num2.cpp deleted file mode 100644 index 8cc7121..0000000 --- a/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/additive_number.cpp b/additive_number.cpp deleted file mode 100644 index d62c2e5..0000000 --- a/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/all_nodes_binary_tree.cpp b/all_nodes_binary_tree.cpp deleted file mode 100644 index 909352b..0000000 --- a/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 &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 distanceK(TreeNode *root, TreeNode *target, int k) { - unordered_map back_edge; - unordered_set visited; - vector ans; - dfs(root, back_edge, target); - queue 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/all_path_src_target.cpp b/all_path_src_target.cpp deleted file mode 100644 index 4ad02ef..0000000 --- a/all_path_src_target.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vvd allPathsSourceTarget(vvd & graph) { - vvd ans; - vector path; - dfs(graph, ans, path, 0); - return ans; - } - -private: - void dfs(vvd & graph, vvd & ans, vector &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/all_path_src_target.rs b/all_path_src_target.rs deleted file mode 100644 index c406cd8..0000000 --- a/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> { - 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/all_possible_full_tree.cpp b/all_possible_full_tree.cpp deleted file mode 100644 index ca54570..0000000 --- a/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 allPossibleFBT(int n) { - unordered_map> memo; - vector 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 left = allPossibleFBT(i); - vector 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/alphabet_board_path.cpp b/alphabet_board_path.cpp deleted file mode 100644 index 874e201..0000000 --- a/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> 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/ancestors_node_acyclic_graph.cpp b/ancestors_node_acyclic_graph.cpp deleted file mode 100644 index 71b6fb7..0000000 --- a/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> &res, - vector> &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> getAncestors(int n, vector> &edges) { - vector> 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/arithmetic_progression.cpp b/arithmetic_progression.cpp deleted file mode 100644 index 4c1c996..0000000 --- a/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 &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 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/arithmetic_slices2.cpp b/arithmetic_slices2.cpp deleted file mode 100644 index 38668b7..0000000 --- a/arithmetic_slices2.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int numberOfArithmeticSlices(vector &nums) { - unordered_map> num_idx; - vvd dp(nums.size(), vector(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 nums = {2, 4, 6, 8, 10}; - cout << obj.numberOfArithmeticSlices(nums); -} diff --git a/arithmetic_slices2.rs b/arithmetic_slices2.rs deleted file mode 100644 index 41162f0..0000000 --- a/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 { - let (n, mut ans) = (nums.len(), 0); - let mut map: Vec> = 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/asteroid_collision.cpp b/asteroid_collision.cpp deleted file mode 100644 index e27f138..0000000 --- a/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 asteroidCollision(vector &asteroids) { - int n = asteroids.size(); - stack 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 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 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/avg_levels_bst.cpp b/avg_levels_bst.cpp deleted file mode 100644 index a18d38d..0000000 --- a/avg_levels_bst.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector averageOfLevels(TreeNode *root) { - vector ans; - queue 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/avg_salary.cpp b/avg_salary.cpp deleted file mode 100644 index 12d49ce..0000000 --- a/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 &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 s1 = {4000, 3000, 1000, 2000}; - vector 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/bag_of_tokens.cpp b/bag_of_tokens.cpp deleted file mode 100644 index d645d2b..0000000 --- a/bag_of_tokens.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int bagOfTokensScore(vector &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 tokens = {100}; - int power = 50; - cout << obj.bagOfTokensScore(tokens, power); -} diff --git a/balanced_num.cpp b/balanced_num.cpp deleted file mode 100644 index 779cb06..0000000 --- a/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 all; - for (int i = 0; i <= 1224444; ++i) { - int v = i; - unordered_map 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 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/basic_calculator.cpp b/basic_calculator.cpp deleted file mode 100644 index 80e0ffe..0000000 --- a/basic_calculator.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int calculate(string s) { - stack> 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/basic_calculator.rs b/basic_calculator.rs deleted file mode 100644 index d33a18c..0000000 --- a/basic_calculator.rs +++ /dev/null @@ -1,29 +0,0 @@ -struct Solution; - -impl Solution { - pub fn calculate(s: String) -> i32 { - let mut sp: Vec = 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/best_buy_sell_stock.cpp b/best_buy_sell_stock.cpp deleted file mode 100644 index 31b2a17..0000000 --- a/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 &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 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/best_team_no_conflict.cpp b/best_team_no_conflict.cpp deleted file mode 100644 index 0773202..0000000 --- a/best_team_no_conflict.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int bestTeamScore(vector &scores, vector &ages) { - int n = scores.size(), ans = 0; - vector dp(n, 0); - vector> 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 scores = {1, 3, 5, 10, 15}, ages = {1, 2, 3, 4, 5}; - cout << obj.bestTeamScore(scores, ages); -} diff --git a/binary_search.cpp b/binary_search.cpp deleted file mode 100644 index 478281e..0000000 --- a/binary_search.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// 704. Binary Search -#include "leetcode.h" - -class Solution { -public: - int search(vector &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 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/binary_tree_factors.cpp b/binary_tree_factors.cpp deleted file mode 100644 index fef1b69..0000000 --- a/binary_tree_factors.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int numFactoredBinaryTrees(vector &arr) { - sort(arr.begin(), arr.end()); - int n = arr.size(); - long ans = 0; - unordered_map 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 arr = {2, 4}; - cout << obj.numFactoredBinaryTrees(arr); -} diff --git a/binary_tree_inorder.cpp b/binary_tree_inorder.cpp deleted file mode 100644 index a677d27..0000000 --- a/binary_tree_inorder.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector inorderTraversal(TreeNode *root) { - vector ans; - stack 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/binary_tree_level_traverse.cpp b/binary_tree_level_traverse.cpp deleted file mode 100644 index 47a69da..0000000 --- a/binary_tree_level_traverse.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector> levelOrder(TreeNode *root) { - vector> ans; - if (!root) - return ans; - queue q; - q.push(root); - q.push(NULL); - vector 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/binary_tree_preorder.cpp b/binary_tree_preorder.cpp deleted file mode 100644 index 7bba435..0000000 --- a/binary_tree_preorder.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector preorderTraversal(TreeNode *root) { - // morris traversal - vector 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/binary_tree_preorder.rs b/binary_tree_preorder.rs deleted file mode 100644 index da6e0b8..0000000 --- a/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>>, - pub right: Option>>, -} - -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>>) -> Vec { - let mut ans: Vec = Vec::new(); - let mut stack: Vec>>> = 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/binary_tree_pruning.cpp b/binary_tree_pruning.cpp deleted file mode 100644 index 3bac07d..0000000 --- a/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/binary_tree_right_view.cpp b/binary_tree_right_view.cpp deleted file mode 100644 index e5a040c..0000000 --- a/binary_tree_right_view.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector rightSideView(TreeNode *root) { - queue q; - vector 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/binary_tree_traversal.cpp b/binary_tree_traversal.cpp deleted file mode 100644 index 601e21c..0000000 --- a/binary_tree_traversal.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - TreeNode *buildTree(vector &preorder, vector &inorder) { - unordered_map 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 &preorder, unordered_map &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/binary_tree_zigzag.cpp b/binary_tree_zigzag.cpp deleted file mode 100644 index 186a99f..0000000 --- a/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 q; - vvd ans; - q.push(root); - int level = 0; - while (!q.empty()) { - int sz = q.size(); - vector 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/boats_save_people.cpp b/boats_save_people.cpp deleted file mode 100644 index 7221191..0000000 --- a/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 &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 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/brainpower.cpp b/brainpower.cpp deleted file mode 100644 index 6708336..0000000 --- a/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 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/break_palindrom.cpp b/break_palindrom.cpp deleted file mode 100644 index d10c0e6..0000000 --- a/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/browser_history.cpp b/browser_history.cpp deleted file mode 100644 index df7d3cd..0000000 --- a/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(); - 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 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/bt_max_path_sum.cpp b/bt_max_path_sum.cpp deleted file mode 100644 index ff39808..0000000 --- a/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/bt_max_path_sum.rs b/bt_max_path_sum.rs deleted file mode 100644 index b0cb984..0000000 --- a/bt_max_path_sum.rs +++ /dev/null @@ -1,38 +0,0 @@ -#[derive(Debug, PartialEq, Eq)] -pub struct TreeNode { - pub val: i32, - pub left: Option>>, - pub right: Option>> -} - -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>>) -> i32 { - let mut ans = std::i32::MIN; - Solution::dfs(&root, &mut ans); - ans - } - fn dfs(node: &Option>>, 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/buddy_strings.cpp b/buddy_strings.cpp deleted file mode 100644 index 22ce6d8..0000000 --- a/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 cnt; - for (auto i : s) { - cnt[i]++; - if (cnt[i] > 1) - return true; - } - return false; - } - vector 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/build_matrix_conditions.cpp b/build_matrix_conditions.cpp deleted file mode 100644 index e192dda..0000000 --- a/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 colour; - vector visited; - bool dfs(int v, vector> &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> &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> &graph, vector &res) { - visited[v] = true; - for (int i : graph[v]) - if (!visited[i]) - dfs2(i, graph, res); - res.push_back(v); - } - void topo_sort(vector> &graph, int n, vector &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> buildMatrix(int k, vector> &rowConditions, - vector> &colConditions) { - vector> 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 a1, a2; - topo_sort(g1, k, a1); - topo_sort(g1, k, a2); - vector> ans(k, vector(k)); - map 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/bulb_switcher.cpp b/bulb_switcher.cpp deleted file mode 100644 index 9fd9374..0000000 --- a/bulb_switcher.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// 319. Bulb Switcher -#include -#include - -/* - * 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/buy_sell_stock.cpp b/buy_sell_stock.cpp deleted file mode 100644 index 122ee2a..0000000 --- a/buy_sell_stock.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maxProfit(int k, vector &prices) { - if (k == 0) - return 0; - if (prices.size() == 0 || prices.size() == 1) - return 0; - vvd dp(k + 1, vector(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 prices = {2, 4, 1}; - cout << obj.maxProfit(k, prices); -} diff --git a/buy_sell_stock.rs b/buy_sell_stock.rs deleted file mode 100644 index 268482f..0000000 --- a/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 { - 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/buy_sell_stock_fee.cpp b/buy_sell_stock_fee.cpp deleted file mode 100644 index 0375c56..0000000 --- a/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 &prices, int fee) { - int n = prices.size(); - if (n < 2) - return 0; - vector 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 p1 = {1, 3, 2, 8, 4, 9}; - vector 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/can_place_flower.cpp b/can_place_flower.cpp deleted file mode 100644 index 72846ff..0000000 --- a/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 &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 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/candy.cpp b/candy.cpp deleted file mode 100644 index 83915b0..0000000 --- a/candy.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int candy(vector &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 ratings = {}; - cout << obj.candy(ratings); -} diff --git a/capacity_ship_d_day.cpp b/capacity_ship_d_day.cpp deleted file mode 100644 index 3612105..0000000 --- a/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 &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 &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 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/cheapest_flight_k_stop.cpp b/cheapest_flight_k_stop.cpp deleted file mode 100644 index 84cb206..0000000 --- a/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 tp; -class Solution { -public: - int findCheapestPrice(int n, vvd & flights, int src, int dst, int k) { - vector>> vvp(n); - for (const auto &f : flights) - vvp[f[0]].emplace_back(f[1], f[2]); - priority_queue, greater> 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/check_complete_bt.cpp b/check_complete_bt.cpp deleted file mode 100644 index 4054423..0000000 --- a/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 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/check_existence_edge.cpp b/check_existence_edge.cpp deleted file mode 100644 index c2bd8e9..0000000 --- a/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 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 distanceLimitedPathsExist(int n, vvd & edge_list, - vvd & queries) { - vector 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 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 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/check_knight_config.cpp b/check_knight_config.cpp deleted file mode 100644 index 1d97495..0000000 --- a/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/check_pangram_sentence.cpp b/check_pangram_sentence.cpp deleted file mode 100644 index 67f1af2..0000000 --- a/check_pangram_sentence.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool checkIfPangram(string sentence) { - set 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/check_pangram_sentence.rs b/check_pangram_sentence.rs deleted file mode 100644 index 0f69c31..0000000 --- a/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/check_straight_line.cpp b/check_straight_line.cpp deleted file mode 100644 index 745738b..0000000 --- a/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/check_string_cont_k.cpp b/check_string_cont_k.cpp deleted file mode 100644 index e041052..0000000 --- a/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/check_two_str_arr.cpp b/check_two_str_arr.cpp deleted file mode 100644 index 5e4d8a7..0000000 --- a/check_two_str_arr.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool arrayStringsAreEqual(vector &word1, vector &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 word1 = {"ab", "c"}, word2 = {"a", "bc"}; - if (obj.arrayStringsAreEqual(word1, word2)) - cout << "true"; - else - cout << "false"; -} diff --git a/check_two_str_arr.rs b/check_two_str_arr.rs deleted file mode 100644 index 7fd2a2d..0000000 --- a/check_two_str_arr.rs +++ /dev/null @@ -1,19 +0,0 @@ -struct Solution; - -impl Solution { - pub fn array_strings_are_equal(word1: Vec, word2: Vec) -> 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/check_valid_partition.cpp b/check_valid_partition.cpp deleted file mode 100644 index 3f4cd76..0000000 --- a/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 &nums, int i, vector &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 &nums) { - vector dp(nums.size(), -1); - return solve(nums, 0, dp); - } -}; - -int main() { - Solution obj; - vector 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/climbing_stairs.cpp b/climbing_stairs.cpp deleted file mode 100644 index afc3d7e..0000000 --- a/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/climbing_stairs.rs b/climbing_stairs.rs deleted file mode 100644 index e3bf42d..0000000 --- a/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/clone_graph.cpp b/clone_graph.cpp deleted file mode 100644 index fc372a0..0000000 --- a/clone_graph.cpp +++ /dev/null @@ -1,55 +0,0 @@ -// 133. Clone Graph -#include -#include -#include -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 neighbors; - Node() { - val = 0; - neighbors = vector(); - } - Node(int _val) { - val = _val; - neighbors = vector(); - } - Node(int _val, vector _neighbors) { - val = _val; - neighbors = _neighbors; - } -}; - -class Solution { - Node *dfs(Node *curr, unordered_map &um) { - vector 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 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/closest_node_2_nodes.cpp b/closest_node_2_nodes.cpp deleted file mode 100644 index 7b85f22..0000000 --- a/closest_node_2_nodes.cpp +++ /dev/null @@ -1,55 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int closestMeetingNode(vector &edges, int node1, int node2) { - pair p1 = dfs(edges, node1, node2); - pair 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 dfs(vector &edges, int node1, int node2) { - unordered_map um; - int n = edges.size(); - vector 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 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 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/closest_node_2_nodes.rs b/closest_node_2_nodes.rs deleted file mode 100644 index ea3ee86..0000000 --- a/closest_node_2_nodes.rs +++ /dev/null @@ -1,45 +0,0 @@ -struct Solution; - -impl Solution { - pub fn closest_meeting_node(edges: Vec, 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/coin_change.cpp b/coin_change.cpp deleted file mode 100644 index 5d31f7a..0000000 --- a/coin_change.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int coinChange(vector &coins, int amount) { - int m = amount + 1; - vector 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 coins = {1, 2, 5}; - int amount = 11; - Solution obj; - cout << obj.coinChange(coins, amount); -} diff --git a/coin_change2.cpp b/coin_change2.cpp deleted file mode 100644 index 4680c95..0000000 --- a/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 &coins) { - vector 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 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/combination_sum3.cpp b/combination_sum3.cpp deleted file mode 100644 index bde03a3..0000000 --- a/combination_sum3.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector> combinationSum3(int k, int n) { - vector> ans; - vector sol; - helper(ans, sol, k, n); - return ans; - } - void print(vector> &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> &ans, vector 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> ans; - obj.print(ans); -} diff --git a/combination_sum4.cpp b/combination_sum4.cpp deleted file mode 100644 index b05bc96..0000000 --- a/combination_sum4.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int combinationSum4(vector &nums, int target) { - vector 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 nums = {1, 2, 3}; - int target = 4; - cout << obj.combinationSum4(nums, target); -} diff --git a/combinations.cpp b/combinations.cpp deleted file mode 100644 index 94d4bfc..0000000 --- a/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 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/concatenated_words.cpp b/concatenated_words.cpp deleted file mode 100644 index 9263d87..0000000 --- a/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 findAllConcatenatedWordsInADict(vector &words) { - sort(words.begin(), words.end(), - [](string &w1, string &w2) { return (w1.length() <= w2.length()); }); - vector ans; - root = new Trie(); - for (string w : words) { - if (w.length() == 0) - continue; - vector 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 words1 = {"cat", "cats", "catsdogcats", - "dog", "dogcatsdog", "hippopotamuses", - "rat", "ratcatdogcat"}; - vector 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/concatenation_binary_num.cpp b/concatenation_binary_num.cpp deleted file mode 100644 index b212c09..0000000 --- a/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/construct_array_multiple_sum.cpp b/construct_array_multiple_sum.cpp deleted file mode 100644 index 5d2751d..0000000 --- a/construct_array_multiple_sum.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool isPossible(vector &target) { - long total = 0; - int i; - priority_queue 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 target = {9, 3, 5}; - cout << obj.isPossible(target); -} diff --git a/construct_bt_io_po.cpp b/construct_bt_io_po.cpp deleted file mode 100644 index 6fb9163..0000000 --- a/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 &inorder, vector &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 um; - TreeNode *construct(vector &inorder, vector &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/construct_quad_tree.cpp b/construct_quad_tree.cpp deleted file mode 100644 index 845cefe..0000000 --- a/construct_quad_tree.cpp +++ /dev/null @@ -1,75 +0,0 @@ -// 427. Construct Quad Tree -#include -using namespace std; -#define vvd(data) vector> - -/* - * 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 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/construct_string_binary_tree.cpp b/construct_string_binary_tree.cpp deleted file mode 100644 index a63e3c9..0000000 --- a/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/contains_duplicate2.cpp b/contains_duplicate2.cpp deleted file mode 100644 index 9af7758..0000000 --- a/contains_duplicate2.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool containsNearbyDuplicate(vector &nums, int k) { - unordered_map 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 nums = {1, 2, 3, 1}; - if (obj.containsNearbyDuplicate(nums, 3)) - cout << "true"; - else - cout << "false"; -} diff --git a/contains_duplicate2.rs b/contains_duplicate2.rs deleted file mode 100644 index b016e21..0000000 --- a/contains_duplicate2.rs +++ /dev/null @@ -1,21 +0,0 @@ -use std::collections::HashMap; -struct Solution; - -impl Solution { - pub fn contains_nearby_duplicate(nums: Vec, 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/contains_duplicate3.cpp b/contains_duplicate3.cpp deleted file mode 100644 index 6e1467c..0000000 --- a/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 &nums, int index_diff, - int value_diff) { - int n = nums.size(); - if (n == 0 || index_diff < 0 || value_diff < 0) - return false; - unordered_map 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 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/contains_virus.cpp b/contains_virus.cpp deleted file mode 100644 index d0040c5..0000000 --- a/contains_virus.cpp +++ /dev/null @@ -1,77 +0,0 @@ -// 749. Contain Virus -#include "leetcode.h" - -class Cluster { -public: - set> c; - set> 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(m)); - auto cmp = [](const Cluster &A, const Cluster &B) { - return A.uc.size() < B.uc.size(); - }; - priority_queue, 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/continuous_subarr_sum.cpp b/continuous_subarr_sum.cpp deleted file mode 100644 index ceaf3ce..0000000 --- a/continuous_subarr_sum.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool checkSubarraySum(vector &nums, int k) { - unordered_map 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 nums = {23, 2, 4, 6, 7}; - int k = 6; - if (obj.checkSubarraySum(nums, k)) - cout << "true"; - else - cout << "false"; -} diff --git a/continuous_subarr_sum.rs b/continuous_subarr_sum.rs deleted file mode 100644 index 2e1567e..0000000 --- a/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, k: i32) -> bool { - let mut mod_k_val = HashSet::::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/convert_sorted_bst.cpp b/convert_sorted_bst.cpp deleted file mode 100644 index 8b5b656..0000000 --- a/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/cost_hire_k_worker.cpp b/cost_hire_k_worker.cpp deleted file mode 100644 index 5bb0860..0000000 --- a/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 &costs, int k, int candidates) { - int i = 0, j = costs.size() - 1; - priority_queue, greater> 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 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/count_all_pickup_delivery.cpp b/count_all_pickup_delivery.cpp deleted file mode 100644 index 0d82d5a..0000000 --- a/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 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/count_and_say.cpp b/count_and_say.cpp deleted file mode 100644 index a1086b4..0000000 --- a/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/count_and_say.rs b/count_and_say.rs deleted file mode 100644 index 55a1fec..0000000 --- a/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 = 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/count_complete_tree_node.cpp b/count_complete_tree_node.cpp deleted file mode 100644 index 5929110..0000000 --- a/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/count_complete_tree_node.rs b/count_complete_tree_node.rs deleted file mode 100644 index 4859862..0000000 --- a/count_complete_tree_node.rs +++ /dev/null @@ -1,51 +0,0 @@ -#[derive(Debug, PartialEq, Eq)] -pub struct TreeNode { - pub val: i32, - pub left: Option>>, - pub right: Option>> -} - -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>>) -> 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/count_distinct_int.cpp b/count_distinct_int.cpp deleted file mode 100644 index ff5c1d6..0000000 --- a/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 &nums) { - // unordered set constructor to insert 'nums' - // note: a set only maintains unique values in it - unordered_set 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 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/count_distinct_int.rs b/count_distinct_int.rs deleted file mode 100644 index 32ce622..0000000 --- a/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 { - let mut hs: HashSet = 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/count_good_nodes_bst.cpp b/count_good_nodes_bst.cpp deleted file mode 100644 index b6b9b3e..0000000 --- a/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/count_ints_even_sum.cpp b/count_ints_even_sum.cpp deleted file mode 100644 index 83070c6..0000000 --- a/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/count_negative_num_matrix.cpp b/count_negative_num_matrix.cpp deleted file mode 100644 index f7c776d..0000000 --- a/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 row : grid) - for (int i : row) - if (i < 0) - ans++; - return ans; - for (vector 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/count_odd_num_interval_range.cpp b/count_odd_num_interval_range.cpp deleted file mode 100644 index f690d01..0000000 --- a/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/count_possible_routes.cpp b/count_possible_routes.cpp deleted file mode 100644 index 228fb2e..0000000 --- a/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 &locations, int start, int finish, int fuel) { - int n = locations.size(), mod = 1e9 + 7, ans = 0; - vvd dp(n, vector(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 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/count_sorted_vowel.cpp b/count_sorted_vowel.cpp deleted file mode 100644 index e113311..0000000 --- a/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/count_unreach_node.cpp b/count_unreach_node.cpp deleted file mode 100644 index bf7413b..0000000 --- a/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> 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 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> m, long long cnt, - vector 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/count_vowels_permutation.cpp b/count_vowels_permutation.cpp deleted file mode 100644 index 807a1f4..0000000 --- a/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(5, -1)); - for (int i = 0; i < 5; i++) - ans += dp(n, i), ans %= mod; - return ans; - } - -private: - int mod = 1e9 + 7; - vector> 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/count_ways_build_strs.cpp b/count_ways_build_strs.cpp deleted file mode 100644 index d388b2f..0000000 --- a/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 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/couples_holding_hands.cpp b/couples_holding_hands.cpp deleted file mode 100644 index 7c3069a..0000000 --- a/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 &row) { - int ans = 0, n = row.size(); - vector 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 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/course_schedule.cpp b/course_schedule.cpp deleted file mode 100644 index 4a249d2..0000000 --- a/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 adj[], vector &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 adj[num_courses]; - for (auto edge : prerequisites) - adj[edge[1]].push_back(edge[0]); - vector 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/course_schedule_3.cpp b/course_schedule_3.cpp deleted file mode 100644 index e13d2ca..0000000 --- a/course_schedule_3.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int scheduleCourse(vector> &courses) { - int time = 0; - priority_queue 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 a, vector b) { return a[1] < b[1]; } -}; diff --git a/create_bt_from_desc.cpp b/create_bt_from_desc.cpp deleted file mode 100644 index 9ad6b4a..0000000 --- a/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> &descriptions) { - unordered_map get_node; - unordered_map 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/daily_temps.cpp b/daily_temps.cpp deleted file mode 100644 index e244252..0000000 --- a/daily_temps.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector dailyTemperatures(vector &temperatures) { - int n = temperatures.size(); - vector nge(n, 0); - stack 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 t1 = {73, 74, 75, 71, 69, 72, 76, 73}; - vector t2 = {30, 40, 50, 60}; - vector 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/daily_temps.rs b/daily_temps.rs deleted file mode 100644 index 63b1f2b..0000000 --- a/daily_temps.rs +++ /dev/null @@ -1,28 +0,0 @@ -struct Solution; - -impl Solution { - pub fn daily_temperatures(temperatures: Vec) -> Vec { - let n = temperatures.len(); - let mut ans: Vec = vec![0; n]; - let mut stk: Vec = 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/data_stream_disjoint_interval.cpp b/data_stream_disjoint_interval.cpp deleted file mode 100644 index 3682ee2..0000000 --- a/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 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/decode_ways.cpp b/decode_ways.cpp deleted file mode 100644 index c03bd67..0000000 --- a/decode_ways.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int numDecodings(string s) { - int n = s.size(); - vector 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/decode_xor_array.cpp b/decode_xor_array.cpp deleted file mode 100644 index 7ee4139..0000000 --- a/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 decode(vector encoded, int first) { - for (int &i : encoded) { - swap(i, first); - first ^= i; - } - encoded.push_back(first); - return encoded; - } -}; - -int main() { - Solution obj; - vector 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/delete_col_sorted.cpp b/delete_col_sorted.cpp deleted file mode 100644 index 4954032..0000000 --- a/delete_col_sorted.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minDeletionSize(vector &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 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/delete_col_sorted.rs b/delete_col_sorted.rs deleted file mode 100644 index 1b7d24a..0000000 --- a/delete_col_sorted.rs +++ /dev/null @@ -1,25 +0,0 @@ -struct Solution; - -impl Solution { - pub fn min_deletion_size(strs: Vec) -> i32 { - let mut ans = 0; - let mut new_strs: Vec> = Vec::new(); - for i in 0..strs.len() { - new_strs.push(strs[i].chars().collect::>()); - } - 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/delete_middle_node.cpp b/delete_middle_node.cpp deleted file mode 100644 index 1493046..0000000 --- a/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/delete_middle_node.rs b/delete_middle_node.rs deleted file mode 100644 index 289d8dd..0000000 --- a/delete_middle_node.rs +++ /dev/null @@ -1,52 +0,0 @@ -pub struct Solution; -pub struct ListNode { - pub val: i32, - pub next: Option> -} - -impl ListNode { - #[inline] - fn new(val: i32) -> self { - ListNode { - next: None, - val - } - } -} - -impl Solution { - pub fn delete_middle(head: Option>) -> Option> { - 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/delete_node_link_list.cpp b/delete_node_link_list.cpp deleted file mode 100644 index cefe915..0000000 --- a/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/delete_operation_2string.cpp b/delete_operation_2string.cpp deleted file mode 100644 index b6e38e4..0000000 --- a/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 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/design_circular_queue.cpp b/design_circular_queue.cpp deleted file mode 100644 index 697e17b..0000000 --- a/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/design_food_rating_sys.cpp b/design_food_rating_sys.cpp deleted file mode 100644 index bdfef0c..0000000 --- a/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 f2c; - unordered_map f2r; - unordered_map>> c2r; - -public: - FoodRatings(vector &foods, vector &cuisines, - vector &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/design_number_container.cpp b/design_number_container.cpp deleted file mode 100644 index bc37a6a..0000000 --- a/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 idxs; - unordered_map> 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/design_parking_system.cpp b/design_parking_system.cpp deleted file mode 100644 index 5cfaf74..0000000 --- a/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 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/design_underground_system.cpp b/design_underground_system.cpp deleted file mode 100644 index f0904d2..0000000 --- a/design_underground_system.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class UndergroundSystem { -public: - unordered_map> checkIns; - unordered_map> 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/detect_capital.cpp b/detect_capital.cpp deleted file mode 100644 index 27aa46b..0000000 --- a/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/detect_capital.rs b/detect_capital.rs deleted file mode 100644 index 454381d..0000000 --- a/detect_capital.rs +++ /dev/null @@ -1,20 +0,0 @@ -struct Solution; - -impl Solution { - pub fn detect_capital_use(word: String) -> bool { - let v: Vec = 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/determine_string_halves.cpp b/determine_string_halves.cpp deleted file mode 100644 index fd249e1..0000000 --- a/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/determine_string_halves.rs b/determine_string_halves.rs deleted file mode 100644 index f7f4303..0000000 --- a/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 = 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::() == 0 - } -} - -fn main() { - let s = String::from("book"); - print!("{}", Solution::halves_are_alike(s)); -} diff --git a/determine_strings_close.cpp b/determine_strings_close.cpp deleted file mode 100644 index 89e2322..0000000 --- a/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 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/determine_strings_close.rs b/determine_strings_close.rs deleted file mode 100644 index f293b6d..0000000 --- a/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/detonate_max_bombs.cpp b/detonate_max_bombs.cpp deleted file mode 100644 index 4d92b98..0000000 --- a/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 &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 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/diff_two_array.cpp b/diff_two_array.cpp deleted file mode 100644 index 6695ae7..0000000 --- a/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 &n1, vector &n2) { - unordered_set 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 n11 = {1, 2, 3}, n21 = {2, 4, 6}; - vector 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/discount_n_orders.cpp b/discount_n_orders.cpp deleted file mode 100644 index a76d21e..0000000 --- a/discount_n_orders.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include "leetcode.h" - -class Cashier { -public: - Cashier(int n, int discount, vector &products, vector &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 product, vector 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 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/divide_nodes_max_groups.cpp b/divide_nodes_max_groups.cpp deleted file mode 100644 index ea07a34..0000000 --- a/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> &edges) { - vector vis(n); - vector> 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 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 vis(n); - vis[x] = true; - queue 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/domino_tromino_tiling.cpp b/domino_tromino_tiling.cpp deleted file mode 100644 index 80a97d0..0000000 --- a/domino_tromino_tiling.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "leetcode.h" -#include - -class Solution { -public: - int numTilings(int n) { - int mod = 1e9; - mod += 7; - vector 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/domino_tromino_tiling.rs b/domino_tromino_tiling.rs deleted file mode 100644 index 554f147..0000000 --- a/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/earliest_possible_full_bloom.cpp b/earliest_possible_full_bloom.cpp deleted file mode 100644 index f990e62..0000000 --- a/earliest_possible_full_bloom.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int earliestFullBloom(vector &plantTime, vector &growTime) { - int n = plantTime.size(); - vector> 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 plantTime = {1, 4, 3}, growTime = {2, 3, 1}; - cout << obj.earliestFullBloom(plantTime, growTime); -} diff --git a/earliest_possible_full_bloom.rs b/earliest_possible_full_bloom.rs deleted file mode 100644 index b8e6444..0000000 --- a/earliest_possible_full_bloom.rs +++ /dev/null @@ -1,20 +0,0 @@ -struct Solution; - -impl Solution { - pub fn earliest_full_bloom(plant_time: Vec, grow_time: Vec) -> 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/edit_distance.cpp b/edit_distance.cpp deleted file mode 100644 index 4103e83..0000000 --- a/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(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/eliminate_monsters.cpp b/eliminate_monsters.cpp deleted file mode 100644 index b0a1711..0000000 --- a/eliminate_monsters.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - typedef pair p; - int eliminateMaxium(vector &dist, vector &speed) { - priority_queue, greater

> 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 dist = {1, 3, 4}, speed = {1, 1, 1}; - cout << obj.eliminateMaxium(dist, speed); -} diff --git a/encode_decode_tinyurl.cpp b/encode_decode_tinyurl.cpp deleted file mode 100644 index d7b9d98..0000000 --- a/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 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(longUrl, code)); - code_url.insert(pair(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/equal_row_col_pair.cpp b/equal_row_col_pair.cpp deleted file mode 100644 index 426291c..0000000 --- a/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, int> mv; - for (int i = 0; i < grid.size(); i++) - mv[grid[i]]++; - for (int i = 0; i < grid[0].size(); i++) { - vector 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/erect_fence.cpp b/erect_fence.cpp deleted file mode 100644 index 9d26fb9..0000000 --- a/erect_fence.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - using tree = vector; - vector outerTrees(vector &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 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 unique(dv.begin(), dv.end()); - return vector(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/erect_fence.rs b/erect_fence.rs deleted file mode 100644 index 6dee425..0000000 --- a/erect_fence.rs +++ /dev/null @@ -1,27 +0,0 @@ -use std::collections::VecDeque; -type Tree = Vec; -struct Solution; - -impl Solution { - pub fn outer_trees(mut trees: Vec) -> Vec { - 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 = 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/eval_reverse_polish_notation.cpp b/eval_reverse_polish_notation.cpp deleted file mode 100644 index 4cd39b8..0000000 --- a/eval_reverse_polish_notation.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int evalRPN(vector &tokens) { - unordered_map> 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 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(stk.top()); - } -}; - -int main() { - Solution obj; - vector tokens1 = {"2", "1", "+", "3", "*"}; - // output: 9 - // ((2 + 1) * 3) - cout << obj.evalRPN(tokens1); - vector tokens2 = {"4", "13", "5", "/", "+"}; - // output: 6 - // (4 + (13 / 5)) - cout << obj.evalRPN(tokens2); - vector 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/eval_reverse_polish_notation.rs b/eval_reverse_polish_notation.rs deleted file mode 100644 index 11a36e3..0000000 --- a/eval_reverse_polish_notation.rs +++ /dev/null @@ -1,29 +0,0 @@ -struct Solution; - -impl Solution { - pub fn eval_rpn(tokens: Vec) -> 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/eventual_safe_states.cpp b/eventual_safe_states.cpp deleted file mode 100644 index 6e41e3e..0000000 --- a/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 eventualSafeNodes(vector> &graph) { - int n = graph.size(); - vector> g(n); - vector 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 q; - for (int i = 0; i < n; i++) - if (!dp[i]) - q.push(i); - vector 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/excel_sheet_column_title.cpp b/excel_sheet_column_title.cpp deleted file mode 100644 index 3de395f..0000000 --- a/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/extra_char_string.cpp b/extra_char_string.cpp deleted file mode 100644 index b26cb93..0000000 --- a/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 &dp, string s, unordered_set &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 &dictionary) { - unordered_set d; - for (auto i : dictionary) - d.insert(hash_func(i)); - vector dp(s.size(), -1); - return min_cost(0, dp, s, d); - } -}; - -int main() { - Solution obj; - string s1 = "leetscode", s2 = "sayhelloworld"; - vector 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/fair_distribution_cookie.cpp b/fair_distribution_cookie.cpp deleted file mode 100644 index 69e0ab4..0000000 --- a/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 &cookies, vector &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 &cookies, int k) { - int n = cookies.size(); - vector v(k, 0); - solve(0, cookies, v, k); - return ans; - } -}; - -int main() { - Solution obj; - vector 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/far_from_land.cpp b/far_from_land.cpp deleted file mode 100644 index 651b8a7..0000000 --- a/far_from_land.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maxDistance(vector> &grid) { - int ans = -1; - if (grid.empty() || grid[0].empty()) - return ans; - - vector> gridValues(grid.size(), - vector(grid[0].size(), INT_MAX)); - queue> 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 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/fibonacci_number.cpp b/fibonacci_number.cpp deleted file mode 100644 index 69e46ee..0000000 --- a/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/find_all_anagrams.cpp b/find_all_anagrams.cpp deleted file mode 100644 index 39fe153..0000000 --- a/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 findAnagrams(string s, string p) { - int ssz = s.size(), psz = p.size(); - if (ssz < psz) - return {}; - vector 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/find_building_alice_bob_meet.cpp b/find_building_alice_bob_meet.cpp deleted file mode 100644 index 2288095..0000000 --- a/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 leftmostBuildingQueries(vector &heights, - vector> &queries) { - int hn = heights.size(), qn = queries.size(); - vector>> q(hn); - priority_queue, vector>, greater>> pq; - vector 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 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 lmbq1 = obj.leftmostBuildingQueries(h1, q1); - vector 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/find_critical_edge_tree.cpp b/find_critical_edge_tree.cpp deleted file mode 100644 index 898fd81..0000000 --- a/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 f, rank; - -public: - UnionFind(int n) { - rank = vector(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 &a, const vector &b) { return a[2] < b[2]; }); - int origin_mst = get_mst(n, edges, -1); - vector 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/find_duplicate_file.cpp b/find_duplicate_file.cpp deleted file mode 100644 index 17ff6f0..0000000 --- a/find_duplicate_file.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vvd(string) findDuplicate(vector &paths) { - unordered_map> 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/find_duplicate_subtree.cpp b/find_duplicate_subtree.cpp deleted file mode 100644 index 5880fc8..0000000 --- a/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 findDuplicateSubtrees(TreeNode *root) { - unordered_map> map; - vector 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> &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/find_first_last_array.cpp b/find_first_last_array.cpp deleted file mode 100644 index 7f5f989..0000000 --- a/find_first_last_array.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector searchRange(vector &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 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/find_groups_farmland.cpp b/find_groups_farmland.cpp deleted file mode 100644 index d496633..0000000 --- a/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/find_highest_altitude.cpp b/find_highest_altitude.cpp deleted file mode 100644 index c67dbac..0000000 --- a/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 &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 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/find_k_beauty_num.cpp b/find_k_beauty_num.cpp deleted file mode 100644 index a8a224e..0000000 --- a/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/find_k_closest_elements.cpp b/find_k_closest_elements.cpp deleted file mode 100644 index e15810c..0000000 --- a/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 findClosestElements(vector &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(arr.begin() + l, arr.begin() + l + k); - } -}; - -int main() { - Solution obj; - vector a1 = {1, 2, 3, 4, 5}, a2 = {1, 2, 3, 4, 5}; - vector fce1 = obj.findClosestElements(a1, 4, 3); - vector 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/find_k_pair_sum.cpp b/find_k_pair_sum.cpp deleted file mode 100644 index 94b779a..0000000 --- a/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 &nums1, vector &nums2, int k) { - priority_queue>, vector>>, - greater>>> - 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> 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 n11 = {1, 7, 11}, n21 = {2, 4, 6}; - vector n12 = {1, 1, 2}, n22 = {1, 2, 3}; - vector 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/find_max_sum_node_val.cpp b/find_max_sum_node_val.cpp deleted file mode 100644 index 60c43b8..0000000 --- a/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 &nums, int k, - vector> &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 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/find_median_data_stream.cpp b/find_median_data_stream.cpp deleted file mode 100644 index 14fbcc3..0000000 --- a/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 small, large; -}; - -int main() { - MedianFinder *obj = new MedianFinder(); - obj->addNum(69); - double param_2 = obj->findMedian(); -} diff --git a/find_median_data_stream.rs b/find_median_data_stream.rs deleted file mode 100644 index 1ef5252..0000000 --- a/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, - large: BinaryHeap>, - 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/find_orig_array_double.cpp b/find_orig_array_double.cpp deleted file mode 100644 index a434616..0000000 --- a/find_orig_array_double.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector findOriginalArray(vector &changed) { - int count[100001] = {}, i = 0; - vector 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() - : ans; - } -}; diff --git a/find_path_graph.cpp b/find_path_graph.cpp deleted file mode 100644 index 9f6c8ae..0000000 --- a/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 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 &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/find_path_graph.rs b/find_path_graph.rs deleted file mode 100644 index a74a654..0000000 --- a/find_path_graph.rs +++ /dev/null @@ -1,48 +0,0 @@ -struct Solution; - -impl Solution { - pub fn valid_path(n: i32, edges: Vec>, source: i32, destination: i32) -> bool { - let n: usize = n as usize; - let mut roots: Vec = { - let mut ans: Vec = vec![0; n]; - for i in 0..n { - ans[i] = i; - } - ans - }; - let mut ranks: Vec = 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, ranks: &mut Vec) { - 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 { - 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/find_player_zero_one_loss.cpp b/find_player_zero_one_loss.cpp deleted file mode 100644 index 5aba77e..0000000 --- a/find_player_zero_one_loss.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vvd findWinners(vvd & matches) { - map lost; - for (auto m : matches) { - if (!lost.count(m[0])) - lost[m[0]] = 0; - lost[m[1]]++; - } - vector 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/find_player_zero_one_loss.rs b/find_player_zero_one_loss.rs deleted file mode 100644 index a0ae44e..0000000 --- a/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> { - let mut lost: BTreeMap = 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/find_replace_pattern.cpp b/find_replace_pattern.cpp deleted file mode 100644 index a00bfcb..0000000 --- a/find_replace_pattern.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector findAndReplacePattern(vector &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 ans; - unordered_map 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/find_safest_path_grid.cpp b/find_safest_path_grid.cpp deleted file mode 100644 index e6dcc3b..0000000 --- a/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> &grid) { - if (grid[0][0] < d || grid[n - 1][n - 1] < d) - return false; - queue> qp; - vector> vis(n, vector(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> &grid) { - n = grid.size(); - if (grid[0][0] || grid[n - 1][n - 1]) - return 0; - queue> 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/find_score_arr_mark.cpp b/find_score_arr_mark.cpp deleted file mode 100644 index 42f2e6a..0000000 --- a/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 &nums) { - long long ans = 0; - set> 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 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/find_smallest_letter.cpp b/find_smallest_letter.cpp deleted file mode 100644 index 01a5562..0000000 --- a/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 &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 l1_2 = {'c', 'f', 'j'}; - vector 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/find_town_judge.cpp b/find_town_judge.cpp deleted file mode 100644 index 5607688..0000000 --- a/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> graph(n + 1, unordered_set()); - 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/first_missing_positive.cpp b/first_missing_positive.cpp deleted file mode 100644 index 48fc05d..0000000 --- a/first_missing_positive.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include "leetcode.h" -#include - -class Solution { -public: - vector firstMissingPositive(vector &nums) {} -}; - -int main() { - Solution obj; - vector nums1 = {1, 2, 0}, nums2 = {} -} diff --git a/first_unique_char_string.cpp b/first_unique_char_string.cpp deleted file mode 100644 index 5f55821..0000000 --- a/first_unique_char_string.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int firstUniqChar(string s) { - unordered_map> 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/flatten_binary_to_linked.cpp b/flatten_binary_to_linked.cpp deleted file mode 100644 index 82751c7..0000000 --- a/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/flip_string_monotone_increase.cpp b/flip_string_monotone_increase.cpp deleted file mode 100644 index 35e0e0c..0000000 --- a/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/freedom_trail.cpp b/freedom_trail.cpp deleted file mode 100644 index 2763f8c..0000000 --- a/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> idx_map; - for (int i = 0; i < n; ++i) - idx_map[ring[i]].push_back(i); - vector>> 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/frog_jump.cpp b/frog_jump.cpp deleted file mode 100644 index d9a21fc..0000000 --- a/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 &stones, map &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 &stones) { - int n = stones.size(); - map mp; - for (int i = 0; i < n; i++) - mp[stones[i]] = i; - vvd dp(n + 1, vector(n + 1, -1)); - return process(stones, mp, 0, 0, dp); - } -}; - -int main() { - Solution obj; - vector 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/fruit_into_baskets.cpp b/fruit_into_baskets.cpp deleted file mode 100644 index e613659..0000000 --- a/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 &fruits) { - int n = fruits.size(), ans = 0; - unordered_map 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 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/furthest_building_reach.cpp b/furthest_building_reach.cpp deleted file mode 100644 index 6baff33..0000000 --- a/furthest_building_reach.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int furthestBuilding(vector &heights, int bricks, int ladders) { - int n = heights.size() - 1; - priority_queue 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 heights = {4, 2, 7, 6, 9, 14, 12}; - int bricks = 5, ladders = 1; - cout << obj.furthestBuilding(heights, bricks, ladders); -} diff --git a/gas_station.cpp b/gas_station.cpp deleted file mode 100644 index 2fdc7fb..0000000 --- a/gas_station.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int canCompleteCircuit(vector &gas, vector &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 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/gas_station.rs b/gas_station.rs deleted file mode 100644 index 0554f5b..0000000 --- a/gas_station.rs +++ /dev/null @@ -1,26 +0,0 @@ -struct Solution; - -impl Solution { - pub fn can_complete_circuit(gas: Vec, cost: Vec) -> 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/greatest_common_div_string.cpp b/greatest_common_div_string.cpp deleted file mode 100644 index 420eb10..0000000 --- a/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/greatest_sum_div_three.cpp b/greatest_sum_div_three.cpp deleted file mode 100644 index c828e58..0000000 --- a/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 &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 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/group_anagrams.cpp b/group_anagrams.cpp deleted file mode 100644 index a2a7c8a..0000000 --- a/group_anagrams.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vvd(string) groupAnagrams(vector &strs) { - map, vector> groups; - for (string s : strs) { - array 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/group_anagrams.rs b/group_anagrams.rs deleted file mode 100644 index 212fc15..0000000 --- a/group_anagrams.rs +++ /dev/null @@ -1,15 +0,0 @@ -use std::collections::HashMap; -struct Solution; - -impl Solution { - pub fn group_anagrams(strs: Vec) -> Vec> { - 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/guess_number_high_low.cpp b/guess_number_high_low.cpp deleted file mode 100644 index d31ca99..0000000 --- a/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/guess_number_high_low.rs b/guess_number_high_low.rs deleted file mode 100644 index 4cd717b..0000000 --- a/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/hand_of_straights.cpp b/hand_of_straights.cpp deleted file mode 100644 index b08c7fa..0000000 --- a/hand_of_straights.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool isNStraightHand(vector &hand, int groupSize) { - if (hand.size() % groupSize != 0) - return false; - map 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 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/happy_number.cpp b/happy_number.cpp deleted file mode 100644 index e946b96..0000000 --- a/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/house_robber.cpp b/house_robber.cpp deleted file mode 100644 index a08aa54..0000000 --- a/house_robber.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int rob(vector &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 nums = {1, 2, 3, 1}; - cout << obj.rob(nums); // expect 4 -} diff --git a/house_robber.rs b/house_robber.rs deleted file mode 100644 index ce4afd9..0000000 --- a/house_robber.rs +++ /dev/null @@ -1,18 +0,0 @@ -struct Solution; - -impl Solution { - pub fn rob(nums: Vec) -> 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/idx_first_occur_str.cpp b/idx_first_occur_str.cpp deleted file mode 100644 index 0f24457..0000000 --- a/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 - -/* - * 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 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 kmp(string needle) { - int n = needle.size(); - vector 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/image_overlap.cpp b/image_overlap.cpp deleted file mode 100644 index bc6eeba..0000000 --- a/image_overlap.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int largestOverlap(vvd & img1, vvd & img2) { - vector la, lb; - int n = img1.size(); - unordered_map 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/image_overlap.rs b/image_overlap.rs deleted file mode 100644 index fa6fbd6..0000000 --- a/image_overlap.rs +++ /dev/null @@ -1,35 +0,0 @@ -impl Solution { - pub fn largest_overlap(img1: Vec>, img2: Vec>) -> 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],img2: &[Vec], 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/implement_queue_stacks.cpp b/implement_queue_stacks.cpp deleted file mode 100644 index 551ce9f..0000000 --- a/implement_queue_stacks.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "leetcode.h" - -class MyQueue { -public: - stack 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/increasing_triplet_subsequence.cpp b/increasing_triplet_subsequence.cpp deleted file mode 100644 index 41a9f0e..0000000 --- a/increasing_triplet_subsequence.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool increasingTriplet(vector &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 nums = {1, 2, 3, 4, 5}; - if (obj.increasingTriplet(nums)) - cout << "true"; - else - cout << "false"; -} diff --git a/inform_employees.cpp b/inform_employees.cpp deleted file mode 100644 index 700ccc3..0000000 --- a/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 &manager, vector &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 &manager, - vector &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 m1 = {-1}, m2 = {2, 2, -1, 2, 2, 2}; - vector 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/insert_delete_getrandom.cpp b/insert_delete_getrandom.cpp deleted file mode 100644 index 5bb76da..0000000 --- a/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 data; - vector 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/insert_delete_getrandom.rs b/insert_delete_getrandom.rs deleted file mode 100644 index 12a772f..0000000 --- a/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, - idx_map: HashMap -} - -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/insert_interval.cpp b/insert_interval.cpp deleted file mode 100644 index 50e16f8..0000000 --- a/insert_interval.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vvd insert(vvd & intervals, vector &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 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/int_roman.cpp b/int_roman.cpp deleted file mode 100644 index e3a8a22..0000000 --- a/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/int_roman.rs b/int_roman.rs deleted file mode 100644 index 9e8aa9e..0000000 --- a/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/integer_break.cpp b/integer_break.cpp deleted file mode 100644 index c015be2..0000000 --- a/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 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/interleaving_string.cpp b/interleaving_string.cpp deleted file mode 100644 index ed2a5b9..0000000 --- a/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/invert_binary_tree.cpp b/invert_binary_tree.cpp deleted file mode 100644 index e8f0585..0000000 --- a/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 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/ipo.cpp b/ipo.cpp deleted file mode 100644 index 61d5baa..0000000 --- a/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 &profits, - vector &capital) { - priority_queue pq; - int x = 0; - vector> 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 profits = {1, 2, 3}; - vector 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/is_graph_biparite.cpp b/is_graph_biparite.cpp deleted file mode 100644 index 4a6b4fc..0000000 --- a/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 colour(n); - queue 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/jump_game.cpp b/jump_game.cpp deleted file mode 100644 index 153d9aa..0000000 --- a/jump_game.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool canJump(vector &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 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/jump_game.rs b/jump_game.rs deleted file mode 100644 index e7f36b0..0000000 --- a/jump_game.rs +++ /dev/null @@ -1,18 +0,0 @@ -struct Solution; - -impl Solution { - pub fn can_jump(nums: Vec) -> 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/jump_game3.cpp b/jump_game3.cpp deleted file mode 100644 index 03f7d37..0000000 --- a/jump_game3.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool canReach(vector &arr, int start) { - vector visited(arr.size(), false); - return dfs(arr, start, visited); - } - -private: - bool dfs(vector &arr, int curr, vector &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 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/jump_game3.rs b/jump_game3.rs deleted file mode 100644 index a973fad..0000000 --- a/jump_game3.rs +++ /dev/null @@ -1,35 +0,0 @@ -use std::collections::VecDeque; -struct Solution; - -impl Solution { - pub fn can_reach(arr: Vec, start: i32) -> bool { - let mut arr = arr; - let mut vd: VecDeque = 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/jump_game4.cpp b/jump_game4.cpp deleted file mode 100644 index 8496d94..0000000 --- a/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 &arr) { - int n = arr.size(), step = 0; - unordered_map> idx_val; - for (int i = 0; i < n; i++) - idx_val[arr[i]].push_back(i); - vector visited(n); - visited[0] = true; - queue 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 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 a1 = {100, -23, -23, 404, 100, 23, 23, 23, 3, 404}; - vector 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/jump_game6.cpp b/jump_game6.cpp deleted file mode 100644 index 81bbf05..0000000 --- a/jump_game6.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maxResult(vector &nums, int k) { - int ans = 0; - deque 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 nums = {1, -1, -2, 4, -7, 3}; - int k = 2; - cout << obj.maxResult(nums, k); -} diff --git a/k_inverse_pairs.cpp b/k_inverse_pairs.cpp deleted file mode 100644 index 5601d19..0000000 --- a/k_inverse_pairs.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int kInversePairs(int n, int k) { - vector dp(k + 1, 0); - int mod = 1e9 + 7; - for (int i = 1; i <= n; i++) { - vector 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/k_radius_subarr.cpp b/k_radius_subarr.cpp deleted file mode 100644 index 91184bb..0000000 --- a/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 getAverages(vector &nums, int k) { - vector 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 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/keys_and_rooms.cpp b/keys_and_rooms.cpp deleted file mode 100644 index 59308ef..0000000 --- a/keys_and_rooms.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool canVisitAllRooms(vvd & rooms) { - stack dfs; - dfs.push(0); - unordered_set 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/keys_and_rooms.rs b/keys_and_rooms.rs deleted file mode 100644 index 678c732..0000000 --- a/keys_and_rooms.rs +++ /dev/null @@ -1,23 +0,0 @@ -struct Solution; - -impl Solution { - pub fn can_visit_all_rooms(rooms: Vec>) -> 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/kids_max_num_candy.cpp b/kids_max_num_candy.cpp deleted file mode 100644 index 8be7b4c..0000000 --- a/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 kidsWithCandies(vector &candies, int extra) { - int m = 0; - vector 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 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/knight_probability_chessboard.cpp b/knight_probability_chessboard.cpp deleted file mode 100644 index 0c5094d..0000000 --- a/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>> 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/koko_eating_bananas.cpp b/koko_eating_bananas.cpp deleted file mode 100644 index 3076169..0000000 --- a/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 &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 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/kth_element_in_stream.cpp b/kth_element_in_stream.cpp deleted file mode 100644 index 75e5234..0000000 --- a/kth_element_in_stream.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "leetcode.h" - -class KthLargest { -private: - int k; - priority_queue, greater> pq; - -public: - KthLargest(int k, vector &nums) { - this->k = k; - auto endPointer = nums.begin() + min(k, nums.size()); - pq = priority_queue, greater>(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 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/kth_largest_element.cpp b/kth_largest_element.cpp deleted file mode 100644 index c9a60c2..0000000 --- a/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 &nums, int k) { - priority_queue pq(nums.begin(), nums.end()); - for (int i = 1; i < k; i++) - pq.pop(); - return pq.top(); - } -}; - -int main() { - Solution obj; - vector nums = {3, 2, 1, 5, 6, 4}; - int k = 2; - cout << obj.findKthLargest(nums, k); -} diff --git a/kth_largest_element_stream.cpp b/kth_largest_element_stream.cpp deleted file mode 100644 index 3ef8b3c..0000000 --- a/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, greater> pq; - int size; - -public: - KthLargest(int k, vector &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 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/kth_missing_pos_num.cpp b/kth_missing_pos_num.cpp deleted file mode 100644 index a7f81f7..0000000 --- a/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 &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 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/kth_smallest_lexicographical.cpp b/kth_smallest_lexicographical.cpp deleted file mode 100644 index 71478e9..0000000 --- a/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(curr), last = first + 1; - first <= n; first *= 10, last *= 10) - cnt += static_cast((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/kth_smallest_sorted_matrix.cpp b/kth_smallest_sorted_matrix.cpp deleted file mode 100644 index aad9458..0000000 --- a/kth_smallest_sorted_matrix.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int kthSmallest(vector> &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> matrix; - int k; - obj.kthSmallest(matrix, k); -} diff --git a/largest_colour_value_graph.cpp b/largest_colour_value_graph.cpp deleted file mode 100644 index 5307742..0000000 --- a/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 &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 target(colours_size); - for (auto &e : edges) { - al[e[0]].push_back(e[1]); - target[e[1]] = true; - } - vector> vp; - for (int i = 0; i < colours_size; ++i) - if (!target[i]) - vp.push_back({i, -1}); - int ans = 0; - vector 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 cnt(colours_size, -1); - auto q = vp; - while (!q.empty()) { - vector> 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/largest_int_add_target.cpp b/largest_int_add_target.cpp deleted file mode 100644 index 91015d0..0000000 --- a/largest_int_add_target.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - string largestNumber(vector &cost, int target) { - vector 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 cost = {4, 3, 2, 5, 6, 7, 2, 5, 5}; - int target = 9; - cout << obj.largestNumber(cost, target); -} diff --git a/largest_multiple_three.cpp b/largest_multiple_three.cpp deleted file mode 100644 index 1c9e3e1..0000000 --- a/largest_multiple_three.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - string largestMultipleOfThree(vector &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 digits = {8, 1, 9}; - cout << obj.largestMultipleOfThree(digits); -} diff --git a/largest_odd_num_string.cpp b/largest_odd_num_string.cpp deleted file mode 100644 index 019d609..0000000 --- a/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/largest_perimeter_triangle.cpp b/largest_perimeter_triangle.cpp deleted file mode 100644 index 64b3682..0000000 --- a/largest_perimeter_triangle.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int largestPerimeter(vector &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 nums = {2, 1, 2}; - cout << obj.largestPerimeter(nums); -} diff --git a/last_day_cross.cpp b/last_day_cross.cpp deleted file mode 100644 index 4bf2e6b..0000000 --- a/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(col, 1)); - p = vector(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 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/leaf_similar_trees.cpp b/leaf_similar_trees.cpp deleted file mode 100644 index 319fbbf..0000000 --- a/leaf_similar_trees.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool leafSimilar(TreeNode *root1, TreeNode *root2) { - stack 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 &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/leaf_similar_trees.rs b/leaf_similar_trees.rs deleted file mode 100644 index 6dcaae1..0000000 --- a/leaf_similar_trees.rs +++ /dev/null @@ -1,44 +0,0 @@ -#[derive(Debug, PartialEq, Eq)] -pub struct TreeNode { - pub val: i32, - pub left: Option>>, - pub right: Option>> -} - -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>>, root2: Option>>) -> bool { - let mut leaves1 = Vec::::new(); - Solution::get_leaves(root1, &mut leaves1); - let mut leaves2 = Vec::::new(); - Solution::get_leaves(root2, &mut leaves2); - leaves1 == leaves2 - } - fn get_leaves(node: Option>>, leaves: &mut Vec) { - 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/letter_combo_number.cpp b/letter_combo_number.cpp deleted file mode 100644 index c15a628..0000000 --- a/letter_combo_number.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector letterCombinations(string digits) { - if (digits.empty()) - return {}; - vector ans; - ans.push_back(""); - for (auto digit : digits) { - vector 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 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/lexicographical_numbers.cpp b/lexicographical_numbers.cpp deleted file mode 100644 index ab48ce5..0000000 --- a/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 ans; - vector 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 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/lexicographically_small_string.cpp b/lexicographically_small_string.cpp deleted file mode 100644 index 3a58189..0000000 --- a/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 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 &ds, int p) { - return ds[p] == -1 ? p : ds[p] = dsFind(ds, ds[p]); - } - void dsMerge(vector &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/lfu_cache.cpp b/lfu_cache.cpp deleted file mode 100644 index c0c857a..0000000 --- a/lfu_cache.cpp +++ /dev/null @@ -1,69 +0,0 @@ -// 460. LFU Cache -#include -#include -using namespace std; - -// https://en.wikipedia.org/wiki/Least_frequently_used -// http://dhruvbird.com/lfu.pdf - -struct Node { - int value; - list::iterator itr; -}; - -class LFUCache { -private: - unordered_map umVal; - unordered_map umCount; - unordered_map> 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/linked_list_cycle2.cpp b/linked_list_cycle2.cpp deleted file mode 100644 index 43dccea..0000000 --- a/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/linked_list_random.cpp b/linked_list_random.cpp deleted file mode 100644 index ae147c5..0000000 --- a/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/longest_arithmetic_subseq.cpp b/longest_arithmetic_subseq.cpp deleted file mode 100644 index 5cc91a7..0000000 --- a/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 &nums) { - int n = nums.size(), ans = 0; - vvd dp(n, vector(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 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/longest_arithmetic_subseq_diff.cpp b/longest_arithmetic_subseq_diff.cpp deleted file mode 100644 index dc6e9ff..0000000 --- a/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 &arr, int difference) { - int ans = 1; - unordered_map 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 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/longest_common_subseq.cpp b/longest_common_subseq.cpp deleted file mode 100644 index 56cbaf9..0000000 --- a/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/longest_common_subseq.rs b/longest_common_subseq.rs deleted file mode 100644 index 212070a..0000000 --- a/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![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/longest_consecutive_sequence.cpp b/longest_consecutive_sequence.cpp deleted file mode 100644 index 2fda5e6..0000000 --- a/longest_consecutive_sequence.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int longestConsecutive(vector &nums) { - unordered_set 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 nums = {100, 4, 200, 1, 3, 2}; - cout << obj.longestConsecutive(nums); -} diff --git a/longest_cycle_graph.cpp b/longest_cycle_graph.cpp deleted file mode 100644 index b0cdf49..0000000 --- a/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 &edges) { - vector vis(edges.size(), 0); - for (int i = 0; i < edges.size(); i++) { - if (vis[i]) - continue; - vector store; - dfs(edges, i, vis, store); - } - return max_len; - } - -private: - int max_len = -1; - void dfs(vector &edges, int si, vector &vis, vector &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 e1 = {3, 3, 4, 2, 3}; - vector e2 = {2, -1, 3, 1}; - printf("%d\n", obj.longestCycle(e1)); - printf("%d\n", obj.longestCycle(e2)); -} diff --git a/longest_happy_string.cpp b/longest_happy_string.cpp deleted file mode 100644 index ea3ad78..0000000 --- a/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/longest_increasing_subseq.cpp b/longest_increasing_subseq.cpp deleted file mode 100644 index 127a984..0000000 --- a/longest_increasing_subseq.cpp +++ /dev/null @@ -1,48 +0,0 @@ -#include "leetcode.h" - -class maxBit { -public: - vector 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 &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 &arr) { - vector 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 nums = {10, 9, 2, 5, 3, 7, 101, 18}; - cout << obj.lengthOisLIS(nums); -} diff --git a/longest_palindrome_concat.cpp b/longest_palindrome_concat.cpp deleted file mode 100644 index 3a42e0a..0000000 --- a/longest_palindrome_concat.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int longestPalindrome(vector &words) { - unordered_map 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 words = {"lc", "cl", "gg"}; - cout << obj.longestPalindrome(words); -} diff --git a/longest_palindrome_concat.rs b/longest_palindrome_concat.rs deleted file mode 100644 index 2a97ed4..0000000 --- a/longest_palindrome_concat.rs +++ /dev/null @@ -1,39 +0,0 @@ -struct Solution; - -impl Solution { - pub fn longest_palindrome(words: Vec) -> 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/longest_palindromic_subseq.cpp b/longest_palindromic_subseq.cpp deleted file mode 100644 index f2a074f..0000000 --- a/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 dp(n, 0); - for (int i = n - 1; i >= 0; i--) { - vector 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/longest_palindromic_substr.cpp b/longest_palindromic_substr.cpp deleted file mode 100644 index 4ecba25..0000000 --- a/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/longest_path_diff_adjacent_char.cpp b/longest_path_diff_adjacent_char.cpp deleted file mode 100644 index 0f60da9..0000000 --- a/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 &parent, string s) { - int n = parent.size(), ans = 1; - queue q; - vector 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 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/longest_path_diff_adjacent_char.rs b/longest_path_diff_adjacent_char.rs deleted file mode 100644 index b35568c..0000000 --- a/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, 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 = s.chars().collect(); - Self::dfs(0, &graph, &sa); - let mut ans: i32 = 0; - unsafe { - ans = res; - } - ans - } - fn dfs(root: usize, graph: &HashMap>, s: &Vec) -> 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/longest_string_chain.cpp b/longest_string_chain.cpp deleted file mode 100644 index afa805c..0000000 --- a/longest_string_chain.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int longestStrChain(vector &words) { - vector> vus(17); - for (auto i : words) - vus[i.size()].insert(i); - unordered_map 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 words = {"a", "b", "ba", "bca", "bda", "bdca"}; - cout << obj.longestStrChain(words); -} diff --git a/longest_subarr_ones.cpp b/longest_subarr_ones.cpp deleted file mode 100644 index 35f2353..0000000 --- a/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 &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 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/longest_subseq_lim_sum.cpp b/longest_subseq_lim_sum.cpp deleted file mode 100644 index 9613667..0000000 --- a/longest_subseq_lim_sum.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector answerQueries(vector &nums, vector &queries) { - int n = nums.size(), m = queries.size(); - sort(nums.begin(), nums.end()); - vector 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 nums = {4, 5, 2, 1}, queries = {3, 10, 21}; - for (auto i : obj.answerQueries(nums, queries)) - cout << i << ' '; -} diff --git a/longest_subseq_lim_sum.rs b/longest_subseq_lim_sum.rs deleted file mode 100644 index 037b606..0000000 --- a/longest_subseq_lim_sum.rs +++ /dev/null @@ -1,17 +0,0 @@ -struct Solution; - -impl Solution { - pub fn answer_queries(mut nums: Vec, queries: Vec) -> Vec { - 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/longest_substring_no_repeat.cpp b/longest_substring_no_repeat.cpp deleted file mode 100644 index 0735fc7..0000000 --- a/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 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(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/longest_valid_course.cpp b/longest_valid_course.cpp deleted file mode 100644 index 87f07a6..0000000 --- a/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 longestObstacleCourseAtEachEachPosition(vector &obstacles) { - vector 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 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/longest_valid_parentheses.cpp b/longest_valid_parentheses.cpp deleted file mode 100644 index 953e8be..0000000 --- a/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 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/longest_word_dict.cpp b/longest_word_dict.cpp deleted file mode 100644 index 3be4538..0000000 --- a/longest_word_dict.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - string findLongestWord(string s, vector &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 dictionary = {"ale", "apple", "monkey", "plea"}; - cout << obj.findLongestWord(s, dictionary); -} diff --git a/longest_zigzag_bt.cpp b/longest_zigzag_bt.cpp deleted file mode 100644 index b0ebe7f..0000000 --- a/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, 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/lowest_common_ancestor.cpp b/lowest_common_ancestor.cpp deleted file mode 100644 index ec99f32..0000000 --- a/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 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 subs; - }; -}; diff --git a/lowest_common_ancestor_bst.cpp b/lowest_common_ancestor_bst.cpp deleted file mode 100644 index d496c2c..0000000 --- a/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/lru_cache.cpp b/lru_cache.cpp deleted file mode 100644 index f8d1656..0000000 --- a/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 li; - typedef pair pii; - typedef unordered_map 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/magnetic_force_2_balls.cpp b/magnetic_force_2_balls.cpp deleted file mode 100644 index 8416deb..0000000 --- a/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 &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 &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 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/make_array_increasing.cpp b/make_array_increasing.cpp deleted file mode 100644 index 482c0da..0000000 --- a/make_array_increasing.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// 1187. Make Array Strictly Increasing -#include -#include -#include -#include -#include -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 &arr1, vector &arr2, - vector> &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 &arr1, vector &arr2) { - sort(arr2.begin(), arr2.end()); - vector> dp(2001); - int val = check(0, INT_MIN, arr1, arr2, dp); - if (val == INT_MAX) - return -1; - return val; - } -}; - -int main() { - Solution obj; - vector a1123 = {1, 5, 3, 6, 7}; - vector 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/make_string_great.cpp b/make_string_great.cpp deleted file mode 100644 index 190bbed..0000000 --- a/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/make_string_great.rs b/make_string_great.rs deleted file mode 100644 index 76a28a2..0000000 --- a/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, 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/make_sum_divisible_p.cpp b/make_sum_divisible_p.cpp deleted file mode 100644 index 993c955..0000000 --- a/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 &nums, int p) { - int n = nums.size(), ans = n, req = 0, curr = 0; - for (auto i : nums) - req = (req + i) % p; - unordered_map 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 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/marbles_in_bags.cpp b/marbles_in_bags.cpp deleted file mode 100644 index 4640eb9..0000000 --- a/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 &weights, int k) { - priority_queue pq1; - priority_queue, greater> 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 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/matchsticks_square.cpp b/matchsticks_square.cpp deleted file mode 100644 index f2422b8..0000000 --- a/matchsticks_square.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool makesquare(vector &matchsticks) { - sort(matchsticks.begin(), matchsticks.end(), greater()); - 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 &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 matchsticks = {1, 1, 2, 2, 2}; - if (obj.makesquare(matchsticks)) - cout << "true"; - else - cout << "false"; -} diff --git a/matrix_diagonal_sum.cpp b/matrix_diagonal_sum.cpp deleted file mode 100644 index 90e7fd5..0000000 --- a/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/max_69.cpp b/max_69.cpp deleted file mode 100644 index bc8abeb..0000000 --- a/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/max_69.rs b/max_69.rs deleted file mode 100644 index 0bead97..0000000 --- a/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/max_area_cake.cpp b/max_area_cake.cpp deleted file mode 100644 index da1f745..0000000 --- a/max_area_cake.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maxArea(int h, int w, vector &horizontalCuts, - vector &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 horizontalCuts = {1, 2, 4}; - vector verticalCuts = {1, 3}; - cout << obj.maxArea(h, w, horizontalCuts, verticalCuts); -} diff --git a/max_area_island.cpp b/max_area_island.cpp deleted file mode 100644 index aad8b2d..0000000 --- a/max_area_island.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maxAreaOfIsland(vector> &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> &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/max_average_pass_ration.cpp b/max_average_pass_ration.cpp deleted file mode 100644 index e9ebb25..0000000 --- a/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 a, pair 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> &classes, int extraStudents) { - double acc = 0; - priority_queue, vector>, cmp> pq; - for (vector i : classes) - pq.push(make_pair(i[0], i[1])); - while (extraStudents--) { - pair curr = pq.top(); - pq.pop(); - curr.first++; - curr.second++; - pq.push(curr); - } - while (!pq.empty()) { - pair 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/max_bags_rocks.cpp b/max_bags_rocks.cpp deleted file mode 100644 index 35c66bc..0000000 --- a/max_bags_rocks.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maximumBags(vector &capacity, vector &rocks, - int additionalRocks) { - vector 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 capacity = {2, 3, 4, 5}, rocks = {1, 2, 4, 4}; - cout << obj.maximumBags(capacity, rocks, 2); -} diff --git a/max_bags_rocks.rs b/max_bags_rocks.rs deleted file mode 100644 index 808c393..0000000 --- a/max_bags_rocks.rs +++ /dev/null @@ -1,20 +0,0 @@ -struct Solution; - -impl Solution { - pub fn maximum_bags(capacity: Vec, rocks: Vec, mut additional_rocks: i32) -> i32 { - let mut bag_space = (0..rocks.len()).map(|i| capacity[i] - rocks[i]) - .filter(|&d| d > 0) - .collect::>(); - 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/max_consecutive_ones3.cpp b/max_consecutive_ones3.cpp deleted file mode 100644 index cff044f..0000000 --- a/max_consecutive_ones3.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int longestOnes(vector &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 nums = {1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0}; - int k = 2; - cout << obj.longestOnes(nums, k); -} diff --git a/max_depth_binary_tree.cpp b/max_depth_binary_tree.cpp deleted file mode 100644 index e5ecc10..0000000 --- a/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/max_diff_node_ancestor.cpp b/max_diff_node_ancestor.cpp deleted file mode 100644 index ab96947..0000000 --- a/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/max_diff_node_ancestor.rs b/max_diff_node_ancestor.rs deleted file mode 100644 index 671bd27..0000000 --- a/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>>, - pub right: Option>> -} - -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>) -> 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>>) -> i32 { - if let Some(node_ref) = root { - Self::minMax(Rc::clone(&node_ref)).ans - } else { - panic!("bad input"); - } - } -} diff --git a/max_distance_closest_person.cpp b/max_distance_closest_person.cpp deleted file mode 100644 index a9203fe..0000000 --- a/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 &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 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/max_erasure_value.cpp b/max_erasure_value.cpp deleted file mode 100644 index dd72746..0000000 --- a/max_erasure_value.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maximumUniqueSubarray(vector &nums) { - int ans = 0; - unordered_set 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 nums = {5, 2, 1, 2, 5, 2, 1, 2, 5}; - cout << obj.maximumUniqueSubarray(nums); -} diff --git a/max_ice_cream_bars.cpp b/max_ice_cream_bars.cpp deleted file mode 100644 index e391f87..0000000 --- a/max_ice_cream_bars.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maxIceCream(vector &costs, int coins) { - int k = costs.size(); - vector dp(k + 1, -1); - sort(costs.begin(), costs.end()); - return dfs(dp, costs, coins, 0, k); - } - -private: - int dfs(vector &dp, vector &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 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/max_ice_cream_bars.rs b/max_ice_cream_bars.rs deleted file mode 100644 index 6691a3b..0000000 --- a/max_ice_cream_bars.rs +++ /dev/null @@ -1,27 +0,0 @@ -struct Solution; - -impl Solution { - pub fn max_ice_cream(costs: Vec, 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/max_len_concat_str.cpp b/max_len_concat_str.cpp deleted file mode 100644 index b364d26..0000000 --- a/max_len_concat_str.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maxLength(vector &arr) { - int ans = 0; - vector> 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> 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 arr = {"un", "iq", "ue"}; - cout << obj.maxLength(arr); -} diff --git a/max_len_concat_str.rs b/max_len_concat_str.rs deleted file mode 100644 index 8ce0c2b..0000000 --- a/max_len_concat_str.rs +++ /dev/null @@ -1,29 +0,0 @@ -struct Solution; - -impl Solution { - pub fn max_length(arr: Vec) -> i32 { - let mut ans: u32 = 0; - let mut unique: Vec = 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 = 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/max_length_pair_chain.cpp b/max_length_pair_chain.cpp deleted file mode 100644 index c8ef536..0000000 --- a/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 &a, vector &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/max_length_repeated_subarr.cpp b/max_length_repeated_subarr.cpp deleted file mode 100644 index 6e8ef68..0000000 --- a/max_length_repeated_subarr.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int findLength(vector &nums1, vector &nums2) { - int m = nums1.size(), n = nums2.size(); - vvd dp(m + 1, vector(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 nums1 = {1, 2, 3, 2, 1}, nums2 = {3, 2, 1, 4, 7}; - cout << obj.findLength(nums1, nums2); -} diff --git a/max_network_rank.cpp b/max_network_rank.cpp deleted file mode 100644 index 86b0e4c..0000000 --- a/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> 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/max_num_events_attended2.cpp b/max_num_events_attended2.cpp deleted file mode 100644 index 95c1563..0000000 --- a/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 &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(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/max_num_ksum_pair.cpp b/max_num_ksum_pair.cpp deleted file mode 100644 index 13c6980..0000000 --- a/max_num_ksum_pair.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maxOperations(vector &nums, int k) { - unordered_map 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 nums = {1, 2, 3, 4}; - Solution obj; - cout << obj.maxOperations(nums, 5); -} diff --git a/max_num_tasks_assign.cpp b/max_num_tasks_assign.cpp deleted file mode 100644 index 370fdda..0000000 --- a/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 &tasks, vector &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 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 t1 = {3, 2, 1}, t2 = {5, 4}, t3 = {10, 15, 30}; - vector 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/max_num_vowel_substr.cpp b/max_num_vowel_substr.cpp deleted file mode 100644 index fe24499..0000000 --- a/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 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/max_performance_team.cpp b/max_performance_team.cpp deleted file mode 100644 index a7e4be8..0000000 --- a/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 &speed, vector &efficiency, - int k) { - priority_queue, greater> pqvg; - vector> 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 speed = {2, 10, 3, 1, 5, 8}, efficiency = {5, 4, 3, 9, 7, 2}; - cout << obj.maxPerformance(n, speed, efficiency, k); -} diff --git a/max_points_from_cards.cpp b/max_points_from_cards.cpp deleted file mode 100644 index 23fc78e..0000000 --- a/max_points_from_cards.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maxScore(vector &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 cardPoints = {1, 2, 3, 4, 5, 6, 1}; - int k = 3; - cout << obj.maxScore(cardPoints, k); -} diff --git a/max_points_line.cpp b/max_points_line.cpp deleted file mode 100644 index 3e34be4..0000000 --- a/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 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/max_points_line.rs b/max_points_line.rs deleted file mode 100644 index ee9c03d..0000000 --- a/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>) -> 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 = 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/max_product_3num.cpp b/max_product_3num.cpp deleted file mode 100644 index 1886bdb..0000000 --- a/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 &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 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/max_product_split_bt.cpp b/max_product_split_bt.cpp deleted file mode 100644 index 71fc9a4..0000000 --- a/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/max_product_split_bt.rs b/max_product_split_bt.rs deleted file mode 100644 index 6aec321..0000000 --- a/max_product_split_bt.rs +++ /dev/null @@ -1,43 +0,0 @@ -#[derive(Debug, PartialEq, Eq)] -pub struct TreeNode { - pub val: i32, - pub left: Option>>, - pub right: Option>>, -} - -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>>) -> 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>>, sums: &mut Vec) -> 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/max_product_word_len.cpp b/max_product_word_len.cpp deleted file mode 100644 index e119ea1..0000000 --- a/max_product_word_len.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maxProduct(vector &words) { - int n = words.size(), ans = 0; - vector> 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 words = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef"}; - cout << obj.maxProduct(words); -} diff --git a/max_profit_job.cpp b/max_profit_job.cpp deleted file mode 100644 index 811874b..0000000 --- a/max_profit_job.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int jobScheduling(vector &startTime, vector &endTime, - vector &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 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 startTime = {1, 2, 3, 3}; - vector endTime = {3, 4, 5, 6}; - vector profit = {50, 10, 40, 70}; - cout << obj.jobScheduling(startTime, endTime, profit); // 120 -} diff --git a/max_profit_job.rs b/max_profit_job.rs deleted file mode 100644 index fe1fafe..0000000 --- a/max_profit_job.rs +++ /dev/null @@ -1,30 +0,0 @@ -struct Solution; - -impl Solution { - pub fn job_scheduling(start_time: Vec, end_time: Vec, profit: Vec) -> i32 { - let mut jobs: Vec = (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/max_running_time_n_computer.cpp b/max_running_time_n_computer.cpp deleted file mode 100644 index e5a10b5..0000000 --- a/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 &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 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/max_score_good_subarr.cpp b/max_score_good_subarr.cpp deleted file mode 100644 index 3c7bc89..0000000 --- a/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 &nums, int k) { - nums.push_back(0); - stack 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 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/max_score_mult_opp.cpp b/max_score_mult_opp.cpp deleted file mode 100644 index 7758a29..0000000 --- a/max_score_mult_opp.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maximumScore(vector &nums, vector &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 &nums, vector &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 nums = {1, 2, 3}, multipliers = {3, 2, 1}; - cout << obj.maximumScore(nums, multipliers); -} diff --git a/max_score_n_operations.cpp b/max_score_n_operations.cpp deleted file mode 100644 index a2dc2b9..0000000 --- a/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 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 &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 &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 n1 = {1, 2}; - vector n2 = {3, 4, 6, 8}; - vector 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/max_score_node_sequence.cpp b/max_score_node_sequence.cpp deleted file mode 100644 index b4df5d5..0000000 --- a/max_score_node_sequence.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maximumScore(vector &scores, vector> &edges) { - const int n = scores.size(); - vector> adj(n); - for (const vector &edge : edges) { - adj[edge[0]].push_back(edge[1]); - adj[edge[1]].push_back(edge[0]); - } - for (vector &a : adj) { - priority_queue, vector>, 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 &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/max_subarray.cpp b/max_subarray.cpp deleted file mode 100644 index 7356925..0000000 --- a/max_subarray.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maxSubArray(vector &nums) { - return helper(nums, 0, nums.size() - 1); - } - -private: - int helper(vector &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 nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; - Solution obj; - cout << obj.maxSubArray(nums); -} diff --git a/max_subseq_score.cpp b/max_subseq_score.cpp deleted file mode 100644 index a739d77..0000000 --- a/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 &nums1, vector &nums2, int k) { - int n = nums1.size(); - vector> 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, greater> 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 n11 = {1, 3, 3, 2}, n21 = {2, 1, 3, 4}; - vector 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/max_sum_3_noverlap_subarr.cpp b/max_sum_3_noverlap_subarr.cpp deleted file mode 100644 index c326ad3..0000000 --- a/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 maxSumOfThreeSubarrays(vector &nums, int k) { - int n = nums.size(), max_sum = 0; - vector 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 n1 = {1, 2, 1, 2, 6, 7, 5, 1}, n2 = {1, 2, 1, 2, 1, 2, 1, 2, 1}; - vector msots1 = obj.maxSumOfThreeSubarrays(n1, 2); - vector 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/max_sum_binary_tree.cpp b/max_sum_binary_tree.cpp deleted file mode 100644 index 64d1d20..0000000 --- a/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 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/max_sum_circular_subarr.cpp b/max_sum_circular_subarr.cpp deleted file mode 100644 index a86eafa..0000000 --- a/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 &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::iterator p, vector::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 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/max_sum_rectangle.cpp b/max_sum_rectangle.cpp deleted file mode 100644 index 9b252e1..0000000 --- a/max_sum_rectangle.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maxSumSubmatrix(vector> &matrix, int k) { - int ans = INT_MIN, rows = matrix.size(), cols = matrix[0].size(); - for (int l = 0; l < cols; ++l) { - vector 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 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/max_total_importance_road.cpp b/max_total_importance_road.cpp deleted file mode 100644 index 82380ab..0000000 --- a/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> &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/max_tranfer_requests.cpp b/max_tranfer_requests.cpp deleted file mode 100644 index 2f0e499..0000000 --- a/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/max_twin_sum_list.cpp b/max_twin_sum_list.cpp deleted file mode 100644 index dd635e1..0000000 --- a/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/max_units_truck.cpp b/max_units_truck.cpp deleted file mode 100644 index f95e777..0000000 --- a/max_units_truck.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maximumUnits(vector> &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 &a, vector &b) { return a[1] > b[1]; } -}; diff --git a/max_val_k_coin_pile.cpp b/max_val_k_coin_pile.cpp deleted file mode 100644 index 6452a7b..0000000 --- a/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 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/max_value_give_idx.cpp b/max_value_give_idx.cpp deleted file mode 100644 index ee6c25f..0000000 --- a/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/max_width_binary_tree.cpp b/max_width_binary_tree.cpp deleted file mode 100644 index 3f69177..0000000 --- a/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> 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/maximise_confusion_exam.cpp b/maximise_confusion_exam.cpp deleted file mode 100644 index 0de5eaf..0000000 --- a/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/maximise_grid_happiness.cpp b/maximise_grid_happiness.cpp deleted file mode 100644 index 612c111..0000000 --- a/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/merge_sorted_array.cpp b/merge_sorted_array.cpp deleted file mode 100644 index 6a98a38..0000000 --- a/merge_sorted_array.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - void merge(vector &nums1, int m, vector &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 nums1 = {1, 2, 3, 0, 0, 0}; - vector 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/merge_sorted_array.rs b/merge_sorted_array.rs deleted file mode 100644 index 1e2704d..0000000 --- a/merge_sorted_array.rs +++ /dev/null @@ -1,14 +0,0 @@ -struct Solution; - -impl Solution { - pub fn merge(nums1: &mut Vec, m: i32, nums2: &mut Vec, 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/merge_string_alt.cpp b/merge_string_alt.cpp deleted file mode 100644 index d69c5fc..0000000 --- a/merge_string_alt.cpp +++ /dev/null @@ -1,32 +0,0 @@ -// 1768. Merge Strings Alternately -#include -#include -#include - -/* - * 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/middle_linked_list.cpp b/middle_linked_list.cpp deleted file mode 100644 index ba3a2a0..0000000 --- a/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/middle_linked_list.rs b/middle_linked_list.rs deleted file mode 100644 index ed84409..0000000 --- a/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> -} - -impl ListNode { - #[inline] - fn new(val: i32) -> Self { - ListNode { - next: None, - val - } - } -} - -impl Solution { - pub fn middle_node(head: Option>) -> Option> { - let mut curr = &head; - let mut node_vec: Vec>> = 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/min_abs_diff_bst.cpp b/min_abs_diff_bst.cpp deleted file mode 100644 index 0c0ef82..0000000 --- a/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/min_ascii_strs.cpp b/min_ascii_strs.cpp deleted file mode 100644 index 07433d6..0000000 --- a/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/min_avg_diff.cpp b/min_avg_diff.cpp deleted file mode 100644 index 4bbc2b1..0000000 --- a/min_avg_diff.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minimumAverageDifference(vector &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 nums = {2, 5, 3, 9, 5, 3}; - cout << obj.minimumAverageDifference(nums); -} diff --git a/min_avg_diff.rs b/min_avg_diff.rs deleted file mode 100644 index 71c18aa..0000000 --- a/min_avg_diff.rs +++ /dev/null @@ -1,23 +0,0 @@ -struct Solution; - -impl Solution { - pub fn minimum_average_difference(nums: Vec) -> i32 { - let (mut left, mut ans, mut min) = (0, 0, i64::MAX); - let mut right = nums.iter().map(|&x| x as i64).sum::(); - 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/min_cost_arr_equal.cpp b/min_cost_arr_equal.cpp deleted file mode 100644 index 3d2b95c..0000000 --- a/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 &nums, vector &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 &nums, vector &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 n1 = {1, 3, 5, 2}, c1 = {2, 3, 1, 14}; - vector 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/min_cost_change_expr.cpp b/min_cost_change_expr.cpp deleted file mode 100644 index c75d10c..0000000 --- a/min_cost_change_expr.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minOperationsToFlip(string expression) { - vector>> vva(1); - for (auto ch : expression) { - if (ch == '(') - vva.push_back(vector>()); - 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 eval(vector> &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/min_cost_climbing_stairs.cpp b/min_cost_climbing_stairs.cpp deleted file mode 100644 index 3df886a..0000000 --- a/min_cost_climbing_stairs.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minCostClimbingStairs(vector &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 cost = {10, 15, 20}; - cout << obj.minCostClimbingStairs(cost); -} diff --git a/min_cost_convert_string1.cpp b/min_cost_convert_string1.cpp deleted file mode 100644 index 914eff9..0000000 --- a/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 &original, - vector &changed, vector &cost) { - long long ans = 0; - vector> n(26, vector(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 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 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/min_cost_cut_stick.cpp b/min_cost_cut_stick.cpp deleted file mode 100644 index 5622868..0000000 --- a/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 &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 &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 c1 = {1, 3, 4, 5}; - vector 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/min_cost_ticket.cpp b/min_cost_ticket.cpp deleted file mode 100644 index 1d00853..0000000 --- a/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 &days, vector &costs) { - unordered_map tickets; - tickets[1] = costs[0]; - tickets[7] = costs[1]; - tickets[30] = costs[2]; - vector 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 d1 = {1, 4, 6, 7, 8, 20}, - d2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31}; - vector 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/min_deletions_unique_char.cpp b/min_deletions_unique_char.cpp deleted file mode 100644 index c971b21..0000000 --- a/min_deletions_unique_char.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minDeletions(string s) { - vector 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/min_depth_binary_tree.cpp b/min_depth_binary_tree.cpp deleted file mode 100644 index 7661fb2..0000000 --- a/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 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/min_deviation_arr.cpp b/min_deviation_arr.cpp deleted file mode 100644 index 47099a6..0000000 --- a/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 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 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/min_difficulty_schedule.cpp b/min_difficulty_schedule.cpp deleted file mode 100644 index 40fab6e..0000000 --- a/min_difficulty_schedule.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include "leetcode.h" -#include -#include - -class Solution { -public: - int minDifficulty(vector &jobDifficulty, int d) { - int n = jobDifficulty.size(); - if (n < d) - return -1; - vector 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 jobDifficulty = {6, 5, 4, 3, 2, 1}; - cout << obj.minDifficulty(jobDifficulty, 2); -} diff --git a/min_dist_bst_node.cpp b/min_dist_bst_node.cpp deleted file mode 100644 index 5222628..0000000 --- a/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/min_dist_target_element.cpp b/min_dist_target_element.cpp deleted file mode 100644 index 662c5ec..0000000 --- a/min_dist_target_element.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int getMinDistance(vector &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 nums = {1, 2, 3, 4, 5}; - int target = 5, start = 3; - // expect 1 - cout << obj.getMinDistance(nums, target, start); -} diff --git a/min_falling_path_sum.cpp b/min_falling_path_sum.cpp deleted file mode 100644 index 3bc2940..0000000 --- a/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(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/min_falling_path_sum.rs b/min_falling_path_sum.rs deleted file mode 100644 index 4b704c1..0000000 --- a/min_falling_path_sum.rs +++ /dev/null @@ -1,23 +0,0 @@ -struct Solution; - -impl Solution { - pub fn min_falling_path_sum(matrix: Vec>) -> 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/min_flips_abc.cpp b/min_flips_abc.cpp deleted file mode 100644 index b51b261..0000000 --- a/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/min_fuel_report_captial.cpp b/min_fuel_report_captial.cpp deleted file mode 100644 index 4e3e2d6..0000000 --- a/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/min_genetic_mutation.cpp b/min_genetic_mutation.cpp deleted file mode 100644 index 8bbf503..0000000 --- a/min_genetic_mutation.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minMutation(string start, string end, vector &bank) { - deque> dqp({{start, 0}}); - set s(bank.begin(), bank.end()); - vector 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 bank = {"AACCGGTA"}; - cout << obj.minMutation(start, end, bank); -} diff --git a/min_genetic_mutation.rs b/min_genetic_mutation.rs deleted file mode 100644 index 1362636..0000000 --- a/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) -> 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/min_incr_arr_unique.cpp b/min_incr_arr_unique.cpp deleted file mode 100644 index 9121d48..0000000 --- a/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 &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 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/min_insertion_make_palindrome.cpp b/min_insertion_make_palindrome.cpp deleted file mode 100644 index 7af74da..0000000 --- a/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 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/min_jump_reach_home.cpp b/min_jump_reach_home.cpp deleted file mode 100644 index 7510c8c..0000000 --- a/min_jump_reach_home.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minimumJumps(vector &forbidden, int a, int b, int x) { - unordered_set f(forbidden.begin(), forbidden.end()); - vvd visited(2, vector(5000)); - queue> 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 forbidden = {14, 4, 18, 1, 15}; - int a = 3, b = 15, x = 9; - cout << obj.minimumJumps(forbidden, a, b, x); -} diff --git a/min_max_array.cpp b/min_max_array.cpp deleted file mode 100644 index 6da3f2b..0000000 --- a/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 &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 &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 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/min_max_diff_pair.cpp b/min_max_diff_pair.cpp deleted file mode 100644 index ac6dc3b..0000000 --- a/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 &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 &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 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/min_move_palindrome.cpp b/min_move_palindrome.cpp deleted file mode 100644 index 6455889..0000000 --- a/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/min_moves_equal_array2.cpp b/min_moves_equal_array2.cpp deleted file mode 100644 index e5fcfd0..0000000 --- a/min_moves_equal_array2.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minMoves2(vector &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 nums = {1, 2, 3}; - cout << obj.minMoves2(nums); -} diff --git a/min_num_arrow_balloon.cpp b/min_num_arrow_balloon.cpp deleted file mode 100644 index 8c79da0..0000000 --- a/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 &x, vector &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/min_num_arrow_balloon.rs b/min_num_arrow_balloon.rs deleted file mode 100644 index 6204bfe..0000000 --- a/min_num_arrow_balloon.rs +++ /dev/null @@ -1,20 +0,0 @@ -struct Solution; - -impl Solution { - pub fn find_min_arrow_shots(mut points: Vec>) -> 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/min_num_days_disconnect_island.cpp b/min_num_days_disconnect_island.cpp deleted file mode 100644 index ff54c44..0000000 --- a/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> &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 dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1}; - void dfs(int x, int y, vector> &grid, vector> &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> &grid) { - int res = 0, n = grid.size(), m = grid[0].size(); - vector> vis(n, vector(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/min_num_opp_arr_cont.cpp b/min_num_opp_arr_cont.cpp deleted file mode 100644 index 5dcb40f..0000000 --- a/min_num_opp_arr_cont.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minOperations(vector &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 nums = {4, 2, 5, 3}; - cout << obj.minOperations(nums); -} diff --git a/min_num_refueling_stops.cpp b/min_num_refueling_stops.cpp deleted file mode 100644 index 34d929b..0000000 --- a/min_num_refueling_stops.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minRefuelStops(int target, int startFuel, vector> &stations) { - int n = stations.size(), ans = 0; - priority_queue 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/min_num_remove_mountain_arr.cpp b/min_num_remove_mountain_arr.cpp deleted file mode 100644 index 007c8c6..0000000 --- a/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 &nums) { - int n = nums.size(); - vector 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 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/min_num_vertices_node.cpp b/min_num_vertices_node.cpp deleted file mode 100644 index 2d53fed..0000000 --- a/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 findSmallestSetOfVertices(int n, vvd & edges) { - vector 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/min_one_bit_0.cpp b/min_one_bit_0.cpp deleted file mode 100644 index 9820ace..0000000 --- a/min_one_bit_0.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - unordered_map 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/min_one_bit_0.rs b/min_one_bit_0.rs deleted file mode 100644 index 1b52362..0000000 --- a/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/min_operations_x_zero.cpp b/min_operations_x_zero.cpp deleted file mode 100644 index 011839e..0000000 --- a/min_operations_x_zero.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minOperations(vector &nums, int x) { - unordered_map 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 nums = {1, 1, 4, 2, 3}; - int x = 5; - cout << obj.minOperations(nums, x); -} diff --git a/min_path_sum.cpp b/min_path_sum.cpp deleted file mode 100644 index 46c2ff1..0000000 --- a/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(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/min_rounds_complete_all_tasks.cpp b/min_rounds_complete_all_tasks.cpp deleted file mode 100644 index 0d78073..0000000 --- a/min_rounds_complete_all_tasks.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minimumRounds(vector &tasks) { - unordered_map 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 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/min_rounds_complete_all_tasks.rs b/min_rounds_complete_all_tasks.rs deleted file mode 100644 index 1c9b7dd..0000000 --- a/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 { - 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/min_score_path_city.cpp b/min_score_path_city.cpp deleted file mode 100644 index 16f4c87..0000000 --- a/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> graph; - for (auto r : roads) - graph[r[0]][r[1]] = graph[r[1]][r[0]] = r[2]; - unordered_set vis; - function 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/min_size_subarr_sum.cpp b/min_size_subarr_sum.cpp deleted file mode 100644 index 3e54b2b..0000000 --- a/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 &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 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/min_speed_arrive_time.cpp b/min_speed_arrive_time.cpp deleted file mode 100644 index 55cfa98..0000000 --- a/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 &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 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 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/min_stack.cpp b/min_stack.cpp deleted file mode 100644 index 745c537..0000000 --- a/min_stack.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include "leetcode.h" - -class MinStack { -public: - stack 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/min_swap_group_1.cpp b/min_swap_group_1.cpp deleted file mode 100644 index 89ab5dd..0000000 --- a/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 &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 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/min_time_apples_tree.cpp b/min_time_apples_tree.cpp deleted file mode 100644 index 81d97d7..0000000 --- a/min_time_apples_tree.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minTime(int n, vvd & edges, vector &hasApple) { - unordered_map 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 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/min_time_apples_tree.rs b/min_time_apples_tree.rs deleted file mode 100644 index 537e5cc..0000000 --- a/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>, has_apple: Vec) -> i32 { - let mut adj_list: Vec> = 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 = HashSet::new(); - Self::dfs(0, adj_list, &mut vis, has_apple, &mut total); - total - } - fn dfs(node: i32, adj_list: Vec>, vis: &mut HashSet, - has_apple: Vec, 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/min_time_complete_trip.cpp b/min_time_complete_trip.cpp deleted file mode 100644 index 2e325a2..0000000 --- a/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 &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 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/min_time_rope_colorful.cpp b/min_time_rope_colorful.cpp deleted file mode 100644 index 9e34c1c..0000000 --- a/min_time_rope_colorful.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minCost(string colors, vector &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 neededTime = {1, 2, 3, 4, 5}; - cout << obj.minCost(colors, neededTime); -} diff --git a/min_time_visit_cell_grid.cpp b/min_time_visit_cell_grid.cpp deleted file mode 100644 index 58a0099..0000000 --- a/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> &grid) { - if (grid[0][1] > 1 && grid[1][0] > 1) - return -1; - int m = grid.size(), n = grid[0].size(); - vector> dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; - vector> vis(m, vector(n, false)); - priority_queue, vector>, 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/min_window_substring.cpp b/min_window_substring.cpp deleted file mode 100644 index c529687..0000000 --- a/min_window_substring.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - string minWindow(string s, string t) { - unordered_map 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/min_window_substring.rs b/min_window_substring.rs deleted file mode 100644 index f23402b..0000000 --- a/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/mirror_reflection.cpp b/mirror_reflection.cpp deleted file mode 100644 index 447ce5e..0000000 --- a/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/missing_number.cpp b/missing_number.cpp deleted file mode 100644 index 03dd331..0000000 --- a/missing_number.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int missingNumber(vector &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 nums = {9, 6, 4, 2, 3, 5, 7, 0, 1}; - cout << obj.missingNumber(nums); -} diff --git a/modify_graph_edge_weight.cpp b/modify_graph_edge_weight.cpp deleted file mode 100644 index 289098f..0000000 --- a/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 bfs(vector>> &adj, - vector> &edges, int source, int destination, - int target, bool modify) { - priority_queue, vector>, greater<>> pq; - vector 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> modifiedGraphEdges(int n, vector> &edges, - int source, int destination, - int target) { - vector>> 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/most_stones_remove.cpp b/most_stones_remove.cpp deleted file mode 100644 index 97499f8..0000000 --- a/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> &stones) { - int n = stones.size(), c = 0; - unordered_map> 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 seen; - function 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/most_stones_remove.rs b/most_stones_remove.rs deleted file mode 100644 index d32137f..0000000 --- a/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>) -> i32 { - let mut ans = 0; - let mut parent: Vec = (0..stones.len()).collect(); - let mut rows: HashMap = HashMap::new(); - let mut cols: HashMap = 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) -> 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 { - 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/most_water.cpp b/most_water.cpp deleted file mode 100644 index 89d4e19..0000000 --- a/most_water.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#include -using namespace std; - -class Solution { -public: - int maxArea(vector &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/my_calendar.cpp b/my_calendar.cpp deleted file mode 100644 index 472884e..0000000 --- a/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> books; - -public: - bool book(int start, int end) { - for (pair 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/my_calendar2.cpp b/my_calendar2.cpp deleted file mode 100644 index 2012a35..0000000 --- a/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> books; - -public: - bool book(int start, int end) { - for (pair p : books) - if (max(p.first, start) < min(end, p.second)) - return false; - books.push_back({start, end}); - return true; - } -}; - -class MyCalendarTwo { - vector> books; - -public: - bool book(int start, int end) { - MyCalendar overlaps; - for (pair p : books) - if (max(p.first, start) < min(end, p.second)) { - pair 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 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/my_calendar3.cpp b/my_calendar3.cpp deleted file mode 100644 index 25de075..0000000 --- a/my_calendar3.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#include "leetcode.h" - -class MyCalendarThree { -public: - map 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/n_ary_tree_traverse.cpp b/n_ary_tree_traverse.cpp deleted file mode 100644 index 9c89682..0000000 --- a/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 q; - q.push(root); - while (!q.empty()) { - int n = q.size(); - vector 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/n_queens2.cpp b/n_queens2.cpp deleted file mode 100644 index 2af1bcd..0000000 --- a/n_queens2.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int totalNQueens(int n) { - vector col(n, true); - vector anti(2 * n - 1, true); - vector main(2 * n - 1, true); - vector row(n, 0); - int count = 0; - helper(0, row, col, main, anti, count); - return count; - } - -private: - void helper(int i, vector &row, vector &col, vector &main, - vector &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/naming_company.cpp b/naming_company.cpp deleted file mode 100644 index 24de89f..0000000 --- a/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 &ideas) { - long long ans = 0, cnt[26][26] = {}; - unordered_set 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 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/nearest_exit_maze.cpp b/nearest_exit_maze.cpp deleted file mode 100644 index 2e0a4cf..0000000 --- a/nearest_exit_maze.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int nearestExit(vvd(char) & maze, vector &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> 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 entrance = {1, 2}; - cout << obj.nearestExit(maze, entrance); -} diff --git a/nearest_exit_maze.rs b/nearest_exit_maze.rs deleted file mode 100644 index 3f314f2..0000000 --- a/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>, entrance: Vec) -> 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/new_21_game.cpp b/new_21_game.cpp deleted file mode 100644 index dc21609..0000000 --- a/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 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/next_greater_element2.cpp b/next_greater_element2.cpp deleted file mode 100644 index c6a8412..0000000 --- a/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 nextGreatestElements(vector &nums) { - int n = nums.size(); - nums.resize(n * 2); - for (int i = n; i < n * 2; i++) - nums[i] = nums[i - n]; - vector ans(n, -1); - stack 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 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/next_permutation.cpp b/next_permutation.cpp deleted file mode 100644 index 95e70f4..0000000 --- a/next_permutation.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include -#include -using namespace std; - -class Solution { -public: - void nextPermutation(vector &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 &nums, int start) { - int i = start, j = nums.size() - 1; - while (i < j) { - swap(nums, i, j); - i++; - j--; - } - } - - void swap(vector &nums, int i, int j) { - int temp = nums[i]; - nums[i] = nums[j]; - nums[j] = temp; - } -}; - -int main() {} diff --git a/non_decreasing_array.cpp b/non_decreasing_array.cpp deleted file mode 100644 index 6ea4280..0000000 --- a/non_decreasing_array.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool checkPossibility(vector &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 nums = {4, 2, 3}; - cout << obj.checkPossibility(nums); -} diff --git a/non_decreasing_subseq.cpp b/non_decreasing_subseq.cpp deleted file mode 100644 index b94510f..0000000 --- a/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> findSubsequences(vector &nums) { - set> seqs = {vector(0)}; - for (int i = 0; i < nums.size(); i++) { - vector> 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> ans; - for (auto s : seqs) - if (s.size() > 1) - ans.push_back(s); - return ans; - } -}; - -int main() { - Solution obj; - vector 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/non_overlapping_interval.cpp b/non_overlapping_interval.cpp deleted file mode 100644 index 228f691..0000000 --- a/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 &a, vector &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 prev = intervals[0]; - for (vector 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/nth_tribonacci_number.cpp b/nth_tribonacci_number.cpp deleted file mode 100644 index cabdb39..0000000 --- a/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/num_bad_pairs.cpp b/num_bad_pairs.cpp deleted file mode 100644 index 144e6ef..0000000 --- a/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 &nums) { - long long ans = 0; - unordered_map 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 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/num_bad_pairs.rs b/num_bad_pairs.rs deleted file mode 100644 index 88119d8..0000000 --- a/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) -> i64 { - let mut hm: HashMap = 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/num_closed_islands.cpp b/num_closed_islands.cpp deleted file mode 100644 index ba0635c..0000000 --- a/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/num_cut_pizza.cpp b/num_cut_pizza.cpp deleted file mode 100644 index 526e21d..0000000 --- a/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 &pizza, int k) { - int m = pizza.size(), n = pizza[0].size(); - vvd cnt(m + 1, vector(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) dp(m + 1, vvd(long)(n + 1, vector(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 p1 = {"A..", "AAA", "..."}; - vector p2 = {"A..", "AA.", "..."}; - vector 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/num_dice_roll_target_sum.cpp b/num_dice_roll_target_sum.cpp deleted file mode 100644 index abb7596..0000000 --- a/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(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/num_enclaves.cpp b/num_enclaves.cpp deleted file mode 100644 index 2629d65..0000000 --- a/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/num_even_nums.cpp b/num_even_nums.cpp deleted file mode 100644 index 1513c72..0000000 --- a/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 &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 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/num_good_path.cpp b/num_good_path.cpp deleted file mode 100644 index 79fae31..0000000 --- a/num_good_path.cpp +++ /dev/null @@ -1,75 +0,0 @@ -#include "leetcode.h" - -class UnionFind { -private: - vector id, rank; - int cnt; - -public: - UnionFind(int cnt) : cnt(cnt) { - id = vector(cnt); - rank = vector(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 &vals, vvd & edges) { - int n = vals.size(), goodPaths = 0; - vvd adj(n); - map> 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 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 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/num_increasing_path.cpp b/num_increasing_path.cpp deleted file mode 100644 index 4f60d46..0000000 --- a/num_increasing_path.cpp +++ /dev/null @@ -1,54 +0,0 @@ -// 2328. Number of Increasing Paths in a Grid -#include -#include -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> &grid, int i, int j, vector> &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> &grid) { - int m = grid.size(), n = grid[0].size(), ans = 0; - if (m == 1 && n == 1) - return 1; - vector> dp(m, vector(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> 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/num_longest_incr_subseq.cpp b/num_longest_incr_subseq.cpp deleted file mode 100644 index bf6529b..0000000 --- a/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 &nums) { - if (nums.empty()) - return 0; - vector>> 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 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/num_matching_subsequence.cpp b/num_matching_subsequence.cpp deleted file mode 100644 index a97d464..0000000 --- a/num_matching_subsequence.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int numMatchingSubseq(string s, vector &words) { - int ans = 0; - unordered_map 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 words = {"a", "bb", "acd", "ace"}; - cout << obj.numMatchingSubseq(s, words); -} diff --git a/num_music_playlists.cpp b/num_music_playlists.cpp deleted file mode 100644 index 78cad3c..0000000 --- a/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(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/num_nodes_sub_tree.cpp b/num_nodes_sub_tree.cpp deleted file mode 100644 index 4edb9ad..0000000 --- a/num_nodes_sub_tree.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector countSubTrees(int n, vvd & edges, string labels) { - vector 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 &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/num_nodes_sub_tree.rs b/num_nodes_sub_tree.rs deleted file mode 100644 index ca52f7b..0000000 --- a/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>, labels: String) -> Vec { - let mut map = HashMap::>::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::::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>, labels: &str, - x: usize, visited: &mut HashSet, ans: &mut Vec) -> [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/num_op_connect_network.cpp b/num_op_connect_network.cpp deleted file mode 100644 index 2a9e2e4..0000000 --- a/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 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 &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/num_people_aware_secret.cpp b/num_people_aware_secret.cpp deleted file mode 100644 index 80a4b91..0000000 --- a/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 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/num_same_consecutive_diff.cpp b/num_same_consecutive_diff.cpp deleted file mode 100644 index 0602ce1..0000000 --- a/num_same_consecutive_diff.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector numsSameConsecDiff(int n, int k) { - vector 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 &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/num_smaller_num_self.cpp b/num_smaller_num_self.cpp deleted file mode 100644 index 49b3ed3..0000000 --- a/num_smaller_num_self.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector countSmaller(vector &nums) { - int n = nums.size(); - vector> vp(n); - vector 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 &count, vector> &vp, int left, int mid, - int right) { - vector> 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 &count, vector> &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/num_squareful_arrays.cpp b/num_squareful_arrays.cpp deleted file mode 100644 index a7fc481..0000000 --- a/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 &nums) { - int n = nums.size(), cnt = 1; - sort(nums.begin(), nums.end()); - vector 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(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 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/num_subseq_satisfy.cpp b/num_subseq_satisfy.cpp deleted file mode 100644 index 6eb1a12..0000000 --- a/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 &nums, int target) { - int ans = 0, mod = 1000000007; - vector 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 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/num_to_hex_binary.cpp b/num_to_hex_binary.cpp deleted file mode 100644 index 81470fd..0000000 --- a/num_to_hex_binary.cpp +++ /dev/null @@ -1,55 +0,0 @@ -#include "leetcode.h" -#include - -/* - * 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/num_valid_words_puzzle.cpp b/num_valid_words_puzzle.cpp deleted file mode 100644 index 9286280..0000000 --- a/num_valid_words_puzzle.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector findNumOfValidWords(vector &words, - vector &puzzles) { - unordered_map um; - for (auto w : words) - um[(mask(w))]++; - vector 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 words = {"aaaa", "asas", "able", "ability", - "actt", "actor", "access"}; - vector puzzles = {"aboveyz", "abrodyz", "abslute", - "absoryz", "actresz", "gaswxyz"}; - for (const auto &i : obj.findNumOfValidWords(words, puzzles)) - cout << i << endl; -} diff --git a/num_ways_dict.cpp b/num_ways_dict.cpp deleted file mode 100644 index 582c2f9..0000000 --- a/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 &words, string target) { - int n = target.length(), mod = 1e9 + 7; - vector ans(n + 1); - ans[0] = 1; - for (int i = 0; i < words[0].length(); ++i) { - vector 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 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/num_ways_remain_place.cpp b/num_ways_remain_place.cpp deleted file mode 100644 index eee14e5..0000000 --- a/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 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/num_ways_reorder_array.cpp b/num_ways_reorder_array.cpp deleted file mode 100644 index 9adcb55..0000000 --- a/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 &nums) { - if (nums.size() < 3) - return 1; - vector 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 &nums) { return dfs(nums) - 1; } -}; - -int main() { - Solution obj; - vector 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/num_weak_char_game.cpp b/num_weak_char_game.cpp deleted file mode 100644 index 06fa2db..0000000 --- a/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 &a, vector &b) { - if (a[0] != b[0]) - return a[0] > b[0]; - return a[1] < b[1]; - } -}; diff --git a/num_zero_filled_subarr.cpp b/num_zero_filled_subarr.cpp deleted file mode 100644 index 8ba45f3..0000000 --- a/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 &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 n1 = {1, 3, 0, 0, 2, 0, 0, 4}; - vector n2 = {0, 0, 0, 2, 0, 0}; - vector 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/number_1bits.cpp b/number_1bits.cpp deleted file mode 100644 index c8e0ac3..0000000 --- a/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/number_atoms.cpp b/number_atoms.cpp deleted file mode 100644 index 2f05d3f..0000000 --- a/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 cnts = parse_formula(formula, i); - for (pair p : cnts) { - ans += p.first; - if (p.second > 1) - ans += to_string(p.second); - } - return ans; - } - -private: - map parse_formula(string &s, int &i) { - map cnts; - const int n = s.size(); - while (i < n && s[i] != ')') { - map cnt = parse_unit(s, i); - merge(cnts, cnt, 1); - } - return cnts; - } - map parse_unit(string &s, int &i) { - map cnts; - const int n = s.size(); - if (s[i] == '(') { - map 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 &cnts, map &cnt, int times) { - for (pair 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/number_islands.cpp b/number_islands.cpp deleted file mode 100644 index 96b8e0b..0000000 --- a/number_islands.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int numIslands(vector> &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> &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/number_provinces.cpp b/number_provinces.cpp deleted file mode 100644 index 2f733f9..0000000 --- a/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 &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 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/number_steps_to_0.cpp b/number_steps_to_0.cpp deleted file mode 100644 index 2683dca..0000000 --- a/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/number_submatrices_sum_target.cpp b/number_submatrices_sum_target.cpp deleted file mode 100644 index db5a84f..0000000 --- a/number_submatrices_sum_target.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int numSubmatrixSumTarget(vector> &matrix, int target) { - int xLen = matrix[0].size(), yLen = matrix.size(), ans = 0; - unordered_map 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/odd_even_linke_list.cpp b/odd_even_linke_list.cpp deleted file mode 100644 index 4ee4bac..0000000 --- a/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/odd_even_linke_list.rs b/odd_even_linke_list.rs deleted file mode 100644 index 89e96c1..0000000 --- a/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> -} - -impl ListNode { - #[inline] - fn new(val: i32) -> Self { - ListNode { - next: None, - val - } - } -} - -impl Solution { - pub fn odd_even_list(mut head: Option>) -> Option> { - 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/ones_and_zeroes.cpp b/ones_and_zeroes.cpp deleted file mode 100644 index 851f1e8..0000000 --- a/ones_and_zeroes.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include "leetcode.h" -#include - -class Solution { -public: - int findMaxForm(vector &strs, int m, int n) { - vector> 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> &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 strs = {"10", "0001", "111001", "1", "0"}; - int m = 5, n = 3; - cout << obj.findMaxForm(strs, m, n); -} diff --git a/online_stock_span.cpp b/online_stock_span.cpp deleted file mode 100644 index 340f32e..0000000 --- a/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> 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/online_stock_span.rs b/online_stock_span.rs deleted file mode 100644 index a967028..0000000 --- a/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, -} - -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/optimal_partition_string.cpp b/optimal_partition_string.cpp deleted file mode 100644 index e39bd62..0000000 --- a/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/orderly_queue.cpp b/orderly_queue.cpp deleted file mode 100644 index 23053d2..0000000 --- a/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/orderly_queue.rs b/orderly_queue.rs deleted file mode 100644 index 0931d7b..0000000 --- a/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::>(); - let mut v = ss.windows(s.len()).collect::>(); - v.sort(); - v[0].iter().copied().collect() - } else { - let mut v = s.chars().collect::>(); - 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/01_matrix.cpp b/other/01_matrix.cpp new file mode 100644 index 0000000..f6d9c2d --- /dev/null +++ b/other/01_matrix.cpp @@ -0,0 +1,34 @@ +#include "leetcode.h" + +class Solution { +public: + vector> updateMatrix(vector> &mat) { + int m = mat.size(), n = mat[0].size(); + vector> ans(m, vector(n, INT_MAX)); + queue> 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> 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 new file mode 100644 index 0000000..a9f0c43 --- /dev/null +++ b/other/132_pattern.cpp @@ -0,0 +1,32 @@ +#include "leetcode.h" + +class Solution { +public: + bool find132pattern(vector &nums) { + int n = nums.size(), minI[n]; + stack 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 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 new file mode 100644 index 0000000..3050ee0 --- /dev/null +++ b/other/3sum_closest.cpp @@ -0,0 +1,31 @@ +#include "leetcode.h" + +class Solution { +public: + int threeSumClosest(vector &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 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 new file mode 100644 index 0000000..1cb8f7a --- /dev/null +++ b/other/add_arr_form_int.cpp @@ -0,0 +1,44 @@ +// 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 addToArrayForm(vector &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 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 new file mode 100644 index 0000000..9afc1dc --- /dev/null +++ b/other/add_binary.cpp @@ -0,0 +1,30 @@ +// 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 new file mode 100644 index 0000000..ec8abfa --- /dev/null +++ b/other/add_digits.cpp @@ -0,0 +1,26 @@ +// 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 new file mode 100644 index 0000000..54ebfb4 --- /dev/null +++ b/other/add_row_tree.cpp @@ -0,0 +1,29 @@ +#include "leetcode.h" + +class Solution { +public: + TreeNode *addOneRow(TreeNode *root, int val, int depth) { + if (depth-- == 1) + return new TreeNode(val, root, nullptr); + queue 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 new file mode 100644 index 0000000..5c5e0f4 --- /dev/null +++ b/other/add_search_words_data.cpp @@ -0,0 +1,35 @@ +#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> 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 new file mode 100644 index 0000000..9a9b7ea --- /dev/null +++ b/other/add_space_string.cpp @@ -0,0 +1,36 @@ +// 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 &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 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 new file mode 100644 index 0000000..8cc7121 --- /dev/null +++ b/other/add_two_num2.cpp @@ -0,0 +1,56 @@ +// 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 new file mode 100644 index 0000000..d62c2e5 --- /dev/null +++ b/other/additive_number.cpp @@ -0,0 +1,54 @@ +// 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 new file mode 100644 index 0000000..909352b --- /dev/null +++ b/other/all_nodes_binary_tree.cpp @@ -0,0 +1,53 @@ +// 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 &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 distanceK(TreeNode *root, TreeNode *target, int k) { + unordered_map back_edge; + unordered_set visited; + vector ans; + dfs(root, back_edge, target); + queue 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 new file mode 100644 index 0000000..4ad02ef --- /dev/null +++ b/other/all_path_src_target.cpp @@ -0,0 +1,30 @@ +#include "leetcode.h" + +class Solution { +public: + vvd allPathsSourceTarget(vvd & graph) { + vvd ans; + vector path; + dfs(graph, ans, path, 0); + return ans; + } + +private: + void dfs(vvd & graph, vvd & ans, vector &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 new file mode 100644 index 0000000..c406cd8 --- /dev/null +++ b/other/all_path_src_target.rs @@ -0,0 +1,54 @@ +use std::collections::VecDeque; +struct Solution; + +impl Solution { + pub fn all_paths_source_target(graph: Vec>) -> Vec> { + 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 new file mode 100644 index 0000000..ca54570 --- /dev/null +++ b/other/all_possible_full_tree.cpp @@ -0,0 +1,40 @@ +// 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 allPossibleFBT(int n) { + unordered_map> memo; + vector 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 left = allPossibleFBT(i); + vector 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 new file mode 100644 index 0000000..874e201 --- /dev/null +++ b/other/alphabet_board_path.cpp @@ -0,0 +1,44 @@ +// 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> 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 new file mode 100644 index 0000000..71b6fb7 --- /dev/null +++ b/other/ancestors_node_acyclic_graph.cpp @@ -0,0 +1,58 @@ +// 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> &res, + vector> &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> getAncestors(int n, vector> &edges) { + vector> 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 new file mode 100644 index 0000000..4c1c996 --- /dev/null +++ b/other/arithmetic_progression.cpp @@ -0,0 +1,44 @@ +// 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 &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 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 new file mode 100644 index 0000000..38668b7 --- /dev/null +++ b/other/arithmetic_slices2.cpp @@ -0,0 +1,35 @@ +#include "leetcode.h" + +class Solution { +public: + int numberOfArithmeticSlices(vector &nums) { + unordered_map> num_idx; + vvd dp(nums.size(), vector(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 nums = {2, 4, 6, 8, 10}; + cout << obj.numberOfArithmeticSlices(nums); +} diff --git a/other/arithmetic_slices2.rs b/other/arithmetic_slices2.rs new file mode 100644 index 0000000..41162f0 --- /dev/null +++ b/other/arithmetic_slices2.rs @@ -0,0 +1,30 @@ +use std::collections::HashMap; +struct Solution; + +impl Solution { + pub fn number_of_arithmetic_slices(nums: Vec) -> i32 { + let (n, mut ans) = (nums.len(), 0); + let mut map: Vec> = 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 new file mode 100644 index 0000000..e27f138 --- /dev/null +++ b/other/asteroid_collision.cpp @@ -0,0 +1,52 @@ +// 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 asteroidCollision(vector &asteroids) { + int n = asteroids.size(); + stack 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 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 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 new file mode 100644 index 0000000..a18d38d --- /dev/null +++ b/other/avg_levels_bst.cpp @@ -0,0 +1,24 @@ +#include "leetcode.h" + +class Solution { +public: + vector averageOfLevels(TreeNode *root) { + vector ans; + queue 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 new file mode 100644 index 0000000..12d49ce --- /dev/null +++ b/other/avg_salary.cpp @@ -0,0 +1,32 @@ +// 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 &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 s1 = {4000, 3000, 1000, 2000}; + vector 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 new file mode 100644 index 0000000..d645d2b --- /dev/null +++ b/other/bag_of_tokens.cpp @@ -0,0 +1,27 @@ +#include "leetcode.h" + +class Solution { +public: + int bagOfTokensScore(vector &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 tokens = {100}; + int power = 50; + cout << obj.bagOfTokensScore(tokens, power); +} diff --git a/other/balanced_num.cpp b/other/balanced_num.cpp new file mode 100644 index 0000000..779cb06 --- /dev/null +++ b/other/balanced_num.cpp @@ -0,0 +1,55 @@ +// 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 all; + for (int i = 0; i <= 1224444; ++i) { + int v = i; + unordered_map 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 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 new file mode 100644 index 0000000..80e0ffe --- /dev/null +++ b/other/basic_calculator.cpp @@ -0,0 +1,37 @@ +#include "leetcode.h" + +class Solution { +public: + int calculate(string s) { + stack> 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 new file mode 100644 index 0000000..d33a18c --- /dev/null +++ b/other/basic_calculator.rs @@ -0,0 +1,29 @@ +struct Solution; + +impl Solution { + pub fn calculate(s: String) -> i32 { + let mut sp: Vec = 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 new file mode 100644 index 0000000..31b2a17 --- /dev/null +++ b/other/best_buy_sell_stock.cpp @@ -0,0 +1,31 @@ +// 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 &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 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 new file mode 100644 index 0000000..0773202 --- /dev/null +++ b/other/best_team_no_conflict.cpp @@ -0,0 +1,28 @@ +#include "leetcode.h" + +class Solution { +public: + int bestTeamScore(vector &scores, vector &ages) { + int n = scores.size(), ans = 0; + vector dp(n, 0); + vector> 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 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 new file mode 100644 index 0000000..478281e --- /dev/null +++ b/other/binary_search.cpp @@ -0,0 +1,27 @@ +// 704. Binary Search +#include "leetcode.h" + +class Solution { +public: + int search(vector &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 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 new file mode 100644 index 0000000..fef1b69 --- /dev/null +++ b/other/binary_tree_factors.cpp @@ -0,0 +1,31 @@ +#include "leetcode.h" + +class Solution { +public: + int numFactoredBinaryTrees(vector &arr) { + sort(arr.begin(), arr.end()); + int n = arr.size(); + long ans = 0; + unordered_map 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 arr = {2, 4}; + cout << obj.numFactoredBinaryTrees(arr); +} diff --git a/other/binary_tree_inorder.cpp b/other/binary_tree_inorder.cpp new file mode 100644 index 0000000..a677d27 --- /dev/null +++ b/other/binary_tree_inorder.cpp @@ -0,0 +1,23 @@ +#include "leetcode.h" + +class Solution { +public: + vector inorderTraversal(TreeNode *root) { + vector ans; + stack 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 new file mode 100644 index 0000000..47a69da --- /dev/null +++ b/other/binary_tree_level_traverse.cpp @@ -0,0 +1,31 @@ +#include "leetcode.h" + +class Solution { +public: + vector> levelOrder(TreeNode *root) { + vector> ans; + if (!root) + return ans; + queue q; + q.push(root); + q.push(NULL); + vector 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 new file mode 100644 index 0000000..7bba435 --- /dev/null +++ b/other/binary_tree_preorder.cpp @@ -0,0 +1,28 @@ +#include "leetcode.h" + +class Solution { +public: + vector preorderTraversal(TreeNode *root) { + // morris traversal + vector 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 new file mode 100644 index 0000000..da6e0b8 --- /dev/null +++ b/other/binary_tree_preorder.rs @@ -0,0 +1,35 @@ +use std::rc::Rc; +use std::cell::RefCell; +#[derive(Debug, PartialEq, Eq)] +pub struct TreeNode { + pub val: i32, + pub left: Option>>, + pub right: Option>>, +} + +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>>) -> Vec { + let mut ans: Vec = Vec::new(); + let mut stack: Vec>>> = 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 new file mode 100644 index 0000000..3bac07d --- /dev/null +++ b/other/binary_tree_pruning.cpp @@ -0,0 +1,15 @@ +#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 new file mode 100644 index 0000000..e5a040c --- /dev/null +++ b/other/binary_tree_right_view.cpp @@ -0,0 +1,24 @@ +#include "leetcode.h" + +class Solution { +public: + vector rightSideView(TreeNode *root) { + queue q; + vector 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 new file mode 100644 index 0000000..601e21c --- /dev/null +++ b/other/binary_tree_traversal.cpp @@ -0,0 +1,24 @@ +#include "leetcode.h" + +class Solution { +public: + TreeNode *buildTree(vector &preorder, vector &inorder) { + unordered_map 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 &preorder, unordered_map &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 new file mode 100644 index 0000000..186a99f --- /dev/null +++ b/other/binary_tree_zigzag.cpp @@ -0,0 +1,36 @@ +// 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 q; + vvd ans; + q.push(root); + int level = 0; + while (!q.empty()) { + int sz = q.size(); + vector 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 new file mode 100644 index 0000000..7221191 --- /dev/null +++ b/other/boats_save_people.cpp @@ -0,0 +1,35 @@ +// 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 &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 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 new file mode 100644 index 0000000..6708336 --- /dev/null +++ b/other/brainpower.cpp @@ -0,0 +1,37 @@ +// 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 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 new file mode 100644 index 0000000..d10c0e6 --- /dev/null +++ b/other/break_palindrom.cpp @@ -0,0 +1,33 @@ +// 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 new file mode 100644 index 0000000..df7d3cd --- /dev/null +++ b/other/browser_history.cpp @@ -0,0 +1,45 @@ +// 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(); + 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 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 new file mode 100644 index 0000000..ff39808 --- /dev/null +++ b/other/bt_max_path_sum.cpp @@ -0,0 +1,31 @@ +// 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 new file mode 100644 index 0000000..b0cb984 --- /dev/null +++ b/other/bt_max_path_sum.rs @@ -0,0 +1,38 @@ +#[derive(Debug, PartialEq, Eq)] +pub struct TreeNode { + pub val: i32, + pub left: Option>>, + pub right: Option>> +} + +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>>) -> i32 { + let mut ans = std::i32::MIN; + Solution::dfs(&root, &mut ans); + ans + } + fn dfs(node: &Option>>, 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 new file mode 100644 index 0000000..22ce6d8 --- /dev/null +++ b/other/buddy_strings.cpp @@ -0,0 +1,46 @@ +// 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 cnt; + for (auto i : s) { + cnt[i]++; + if (cnt[i] > 1) + return true; + } + return false; + } + vector 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 new file mode 100644 index 0000000..e192dda --- /dev/null +++ b/other/build_matrix_conditions.cpp @@ -0,0 +1,98 @@ +// 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 colour; + vector visited; + bool dfs(int v, vector> &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> &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> &graph, vector &res) { + visited[v] = true; + for (int i : graph[v]) + if (!visited[i]) + dfs2(i, graph, res); + res.push_back(v); + } + void topo_sort(vector> &graph, int n, vector &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> buildMatrix(int k, vector> &rowConditions, + vector> &colConditions) { + vector> 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 a1, a2; + topo_sort(g1, k, a1); + topo_sort(g1, k, a2); + vector> ans(k, vector(k)); + map 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 new file mode 100644 index 0000000..9fd9374 --- /dev/null +++ b/other/bulb_switcher.cpp @@ -0,0 +1,19 @@ +// 319. Bulb Switcher +#include +#include + +/* + * 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 new file mode 100644 index 0000000..122ee2a --- /dev/null +++ b/other/buy_sell_stock.cpp @@ -0,0 +1,34 @@ +#include "leetcode.h" + +class Solution { +public: + int maxProfit(int k, vector &prices) { + if (k == 0) + return 0; + if (prices.size() == 0 || prices.size() == 1) + return 0; + vvd dp(k + 1, vector(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 prices = {2, 4, 1}; + cout << obj.maxProfit(k, prices); +} diff --git a/other/buy_sell_stock.rs b/other/buy_sell_stock.rs new file mode 100644 index 0000000..268482f --- /dev/null +++ b/other/buy_sell_stock.rs @@ -0,0 +1,33 @@ +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 { + 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 new file mode 100644 index 0000000..0375c56 --- /dev/null +++ b/other/buy_sell_stock_fee.cpp @@ -0,0 +1,35 @@ +// 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 &prices, int fee) { + int n = prices.size(); + if (n < 2) + return 0; + vector 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 p1 = {1, 3, 2, 8, 4, 9}; + vector 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 new file mode 100644 index 0000000..72846ff --- /dev/null +++ b/other/can_place_flower.cpp @@ -0,0 +1,35 @@ +// 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 &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 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 new file mode 100644 index 0000000..83915b0 --- /dev/null +++ b/other/candy.cpp @@ -0,0 +1,37 @@ +#include "leetcode.h" + +class Solution { +public: + int candy(vector &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 ratings = {}; + cout << obj.candy(ratings); +} diff --git a/other/capacity_ship_d_day.cpp b/other/capacity_ship_d_day.cpp new file mode 100644 index 0000000..3612105 --- /dev/null +++ b/other/capacity_ship_d_day.cpp @@ -0,0 +1,50 @@ +// 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 &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 &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 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 new file mode 100644 index 0000000..84cb206 --- /dev/null +++ b/other/cheapest_flight_k_stop.cpp @@ -0,0 +1,46 @@ +// 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 tp; +class Solution { +public: + int findCheapestPrice(int n, vvd & flights, int src, int dst, int k) { + vector>> vvp(n); + for (const auto &f : flights) + vvp[f[0]].emplace_back(f[1], f[2]); + priority_queue, greater> 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 new file mode 100644 index 0000000..4054423 --- /dev/null +++ b/other/check_complete_bt.cpp @@ -0,0 +1,26 @@ +// 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 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 new file mode 100644 index 0000000..c2bd8e9 --- /dev/null +++ b/other/check_existence_edge.cpp @@ -0,0 +1,68 @@ +// 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 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 distanceLimitedPathsExist(int n, vvd & edge_list, + vvd & queries) { + vector 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 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 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 new file mode 100644 index 0000000..1d97495 --- /dev/null +++ b/other/check_knight_config.cpp @@ -0,0 +1,59 @@ +// 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 new file mode 100644 index 0000000..67f1af2 --- /dev/null +++ b/other/check_pangram_sentence.cpp @@ -0,0 +1,19 @@ +#include "leetcode.h" + +class Solution { +public: + bool checkIfPangram(string sentence) { + set 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 new file mode 100644 index 0000000..0f69c31 --- /dev/null +++ b/other/check_pangram_sentence.rs @@ -0,0 +1,21 @@ +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 new file mode 100644 index 0000000..745738b --- /dev/null +++ b/other/check_straight_line.cpp @@ -0,0 +1,35 @@ +// 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 new file mode 100644 index 0000000..e041052 --- /dev/null +++ b/other/check_string_cont_k.cpp @@ -0,0 +1,30 @@ +#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 new file mode 100644 index 0000000..5e4d8a7 --- /dev/null +++ b/other/check_two_str_arr.cpp @@ -0,0 +1,26 @@ +#include "leetcode.h" + +class Solution { +public: + bool arrayStringsAreEqual(vector &word1, vector &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 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 new file mode 100644 index 0000000..7fd2a2d --- /dev/null +++ b/other/check_two_str_arr.rs @@ -0,0 +1,19 @@ +struct Solution; + +impl Solution { + pub fn array_strings_are_equal(word1: Vec, word2: Vec) -> 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 new file mode 100644 index 0000000..3f4cd76 --- /dev/null +++ b/other/check_valid_partition.cpp @@ -0,0 +1,50 @@ +// 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 &nums, int i, vector &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 &nums) { + vector dp(nums.size(), -1); + return solve(nums, 0, dp); + } +}; + +int main() { + Solution obj; + vector 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 new file mode 100644 index 0000000..afc3d7e --- /dev/null +++ b/other/climbing_stairs.cpp @@ -0,0 +1,31 @@ +#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 new file mode 100644 index 0000000..e3bf42d --- /dev/null +++ b/other/climbing_stairs.rs @@ -0,0 +1,16 @@ +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 new file mode 100644 index 0000000..fc372a0 --- /dev/null +++ b/other/clone_graph.cpp @@ -0,0 +1,55 @@ +// 133. Clone Graph +#include +#include +#include +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 neighbors; + Node() { + val = 0; + neighbors = vector(); + } + Node(int _val) { + val = _val; + neighbors = vector(); + } + Node(int _val, vector _neighbors) { + val = _val; + neighbors = _neighbors; + } +}; + +class Solution { + Node *dfs(Node *curr, unordered_map &um) { + vector 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 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 new file mode 100644 index 0000000..7b85f22 --- /dev/null +++ b/other/closest_node_2_nodes.cpp @@ -0,0 +1,55 @@ +#include "leetcode.h" + +class Solution { +public: + int closestMeetingNode(vector &edges, int node1, int node2) { + pair p1 = dfs(edges, node1, node2); + pair 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 dfs(vector &edges, int node1, int node2) { + unordered_map um; + int n = edges.size(); + vector 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 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 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 new file mode 100644 index 0000000..ea3ee86 --- /dev/null +++ b/other/closest_node_2_nodes.rs @@ -0,0 +1,45 @@ +struct Solution; + +impl Solution { + pub fn closest_meeting_node(edges: Vec, 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 new file mode 100644 index 0000000..5d31f7a --- /dev/null +++ b/other/coin_change.cpp @@ -0,0 +1,22 @@ +#include "leetcode.h" + +class Solution { +public: + int coinChange(vector &coins, int amount) { + int m = amount + 1; + vector 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 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 new file mode 100644 index 0000000..4680c95 --- /dev/null +++ b/other/coin_change2.cpp @@ -0,0 +1,31 @@ +// 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 &coins) { + vector 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 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 new file mode 100644 index 0000000..bde03a3 --- /dev/null +++ b/other/combination_sum3.cpp @@ -0,0 +1,38 @@ +#include "leetcode.h" + +class Solution { +public: + vector> combinationSum3(int k, int n) { + vector> ans; + vector sol; + helper(ans, sol, k, n); + return ans; + } + void print(vector> &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> &ans, vector 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> ans; + obj.print(ans); +} diff --git a/other/combination_sum4.cpp b/other/combination_sum4.cpp new file mode 100644 index 0000000..b05bc96 --- /dev/null +++ b/other/combination_sum4.cpp @@ -0,0 +1,24 @@ +#include "leetcode.h" + +class Solution { +public: + int combinationSum4(vector &nums, int target) { + vector 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 nums = {1, 2, 3}; + int target = 4; + cout << obj.combinationSum4(nums, target); +} diff --git a/other/combinations.cpp b/other/combinations.cpp new file mode 100644 index 0000000..94d4bfc --- /dev/null +++ b/other/combinations.cpp @@ -0,0 +1,39 @@ +// 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 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 new file mode 100644 index 0000000..9263d87 --- /dev/null +++ b/other/concatenated_words.cpp @@ -0,0 +1,75 @@ +// 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 findAllConcatenatedWordsInADict(vector &words) { + sort(words.begin(), words.end(), + [](string &w1, string &w2) { return (w1.length() <= w2.length()); }); + vector ans; + root = new Trie(); + for (string w : words) { + if (w.length() == 0) + continue; + vector 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 words1 = {"cat", "cats", "catsdogcats", + "dog", "dogcatsdog", "hippopotamuses", + "rat", "ratcatdogcat"}; + vector 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 new file mode 100644 index 0000000..b212c09 --- /dev/null +++ b/other/concatenation_binary_num.cpp @@ -0,0 +1,38 @@ +#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 new file mode 100644 index 0000000..5d2751d --- /dev/null +++ b/other/construct_array_multiple_sum.cpp @@ -0,0 +1,30 @@ +#include "leetcode.h" + +class Solution { +public: + bool isPossible(vector &target) { + long total = 0; + int i; + priority_queue 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 target = {9, 3, 5}; + cout << obj.isPossible(target); +} diff --git a/other/construct_bt_io_po.cpp b/other/construct_bt_io_po.cpp new file mode 100644 index 0000000..6fb9163 --- /dev/null +++ b/other/construct_bt_io_po.cpp @@ -0,0 +1,31 @@ +// 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 &inorder, vector &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 um; + TreeNode *construct(vector &inorder, vector &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 new file mode 100644 index 0000000..845cefe --- /dev/null +++ b/other/construct_quad_tree.cpp @@ -0,0 +1,75 @@ +// 427. Construct Quad Tree +#include +using namespace std; +#define vvd(data) vector> + +/* + * 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 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 new file mode 100644 index 0000000..a63e3c9 --- /dev/null +++ b/other/construct_string_binary_tree.cpp @@ -0,0 +1,21 @@ +#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 new file mode 100644 index 0000000..9af7758 --- /dev/null +++ b/other/contains_duplicate2.cpp @@ -0,0 +1,24 @@ +#include "leetcode.h" + +class Solution { +public: + bool containsNearbyDuplicate(vector &nums, int k) { + unordered_map 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 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 new file mode 100644 index 0000000..b016e21 --- /dev/null +++ b/other/contains_duplicate2.rs @@ -0,0 +1,21 @@ +use std::collections::HashMap; +struct Solution; + +impl Solution { + pub fn contains_nearby_duplicate(nums: Vec, 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 new file mode 100644 index 0000000..6e1467c --- /dev/null +++ b/other/contains_duplicate3.cpp @@ -0,0 +1,52 @@ +// 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 &nums, int index_diff, + int value_diff) { + int n = nums.size(); + if (n == 0 || index_diff < 0 || value_diff < 0) + return false; + unordered_map 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 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 new file mode 100644 index 0000000..d0040c5 --- /dev/null +++ b/other/contains_virus.cpp @@ -0,0 +1,77 @@ +// 749. Contain Virus +#include "leetcode.h" + +class Cluster { +public: + set> c; + set> 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(m)); + auto cmp = [](const Cluster &A, const Cluster &B) { + return A.uc.size() < B.uc.size(); + }; + priority_queue, 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 new file mode 100644 index 0000000..ceaf3ce --- /dev/null +++ b/other/continuous_subarr_sum.cpp @@ -0,0 +1,31 @@ +#include "leetcode.h" + +class Solution { +public: + bool checkSubarraySum(vector &nums, int k) { + unordered_map 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 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 new file mode 100644 index 0000000..2e1567e --- /dev/null +++ b/other/continuous_subarr_sum.rs @@ -0,0 +1,24 @@ +use std::collections::HashSet; +struct Solution; + +impl Solution { + pub fn check_subarray_sum(nums: Vec, k: i32) -> bool { + let mut mod_k_val = HashSet::::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 new file mode 100644 index 0000000..8b5b656 --- /dev/null +++ b/other/convert_sorted_bst.cpp @@ -0,0 +1,29 @@ +// 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 new file mode 100644 index 0000000..5bb0860 --- /dev/null +++ b/other/cost_hire_k_worker.cpp @@ -0,0 +1,48 @@ +// 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 &costs, int k, int candidates) { + int i = 0, j = costs.size() - 1; + priority_queue, greater> 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 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 new file mode 100644 index 0000000..0d82d5a --- /dev/null +++ b/other/count_all_pickup_delivery.cpp @@ -0,0 +1,23 @@ +#include "leetcode.h" +#define lli long long int + +class Solution { +public: + int countOrders(int n) { + lli mod = 1e9 + 7; + vector 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 new file mode 100644 index 0000000..a1086b4 --- /dev/null +++ b/other/count_and_say.cpp @@ -0,0 +1,26 @@ +#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 new file mode 100644 index 0000000..55a1fec --- /dev/null +++ b/other/count_and_say.rs @@ -0,0 +1,32 @@ +struct Solution; + +impl Solution { + pub fn count_and_say(n: i32) -> String { + if n == 1 { + return "1".to_string(); + } + let mut output: Vec = 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 new file mode 100644 index 0000000..5929110 --- /dev/null +++ b/other/count_complete_tree_node.cpp @@ -0,0 +1,18 @@ +#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 new file mode 100644 index 0000000..4859862 --- /dev/null +++ b/other/count_complete_tree_node.rs @@ -0,0 +1,51 @@ +#[derive(Debug, PartialEq, Eq)] +pub struct TreeNode { + pub val: i32, + pub left: Option>>, + pub right: Option>> +} + +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>>) -> 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 new file mode 100644 index 0000000..ff5c1d6 --- /dev/null +++ b/other/count_distinct_int.cpp @@ -0,0 +1,40 @@ +// 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 &nums) { + // unordered set constructor to insert 'nums' + // note: a set only maintains unique values in it + unordered_set 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 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 new file mode 100644 index 0000000..32ce622 --- /dev/null +++ b/other/count_distinct_int.rs @@ -0,0 +1,35 @@ +//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 { + let mut hs: HashSet = 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 new file mode 100644 index 0000000..b6b9b3e --- /dev/null +++ b/other/count_good_nodes_bst.cpp @@ -0,0 +1,22 @@ +#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 new file mode 100644 index 0000000..83070c6 --- /dev/null +++ b/other/count_ints_even_sum.cpp @@ -0,0 +1,26 @@ +// 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 new file mode 100644 index 0000000..f7c776d --- /dev/null +++ b/other/count_negative_num_matrix.cpp @@ -0,0 +1,37 @@ +// 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 row : grid) + for (int i : row) + if (i < 0) + ans++; + return ans; + for (vector 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 new file mode 100644 index 0000000..f690d01 --- /dev/null +++ b/other/count_odd_num_interval_range.cpp @@ -0,0 +1,24 @@ +// 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 new file mode 100644 index 0000000..228fb2e --- /dev/null +++ b/other/count_possible_routes.cpp @@ -0,0 +1,42 @@ +// 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 &locations, int start, int finish, int fuel) { + int n = locations.size(), mod = 1e9 + 7, ans = 0; + vvd dp(n, vector(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 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 new file mode 100644 index 0000000..e113311 --- /dev/null +++ b/other/count_sorted_vowel.cpp @@ -0,0 +1,20 @@ +#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 new file mode 100644 index 0000000..bf7413b --- /dev/null +++ b/other/count_unreach_node.cpp @@ -0,0 +1,48 @@ +// 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> 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 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> m, long long cnt, + vector 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 new file mode 100644 index 0000000..807a1f4 --- /dev/null +++ b/other/count_vowels_permutation.cpp @@ -0,0 +1,30 @@ +#include "leetcode.h" +class Solution { +public: + int countVowelPermutation(int n) { + int ans = 0; + memo.resize(n + 1, vector(5, -1)); + for (int i = 0; i < 5; i++) + ans += dp(n, i), ans %= mod; + return ans; + } + +private: + int mod = 1e9 + 7; + vector> 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 new file mode 100644 index 0000000..d388b2f --- /dev/null +++ b/other/count_ways_build_strs.cpp @@ -0,0 +1,38 @@ +// 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 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 new file mode 100644 index 0000000..7c3069a --- /dev/null +++ b/other/couples_holding_hands.cpp @@ -0,0 +1,38 @@ +// 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 &row) { + int ans = 0, n = row.size(); + vector 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 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 new file mode 100644 index 0000000..4a249d2 --- /dev/null +++ b/other/course_schedule.cpp @@ -0,0 +1,44 @@ +// 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 adj[], vector &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 adj[num_courses]; + for (auto edge : prerequisites) + adj[edge[1]].push_back(edge[0]); + vector 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 new file mode 100644 index 0000000..e13d2ca --- /dev/null +++ b/other/course_schedule_3.cpp @@ -0,0 +1,27 @@ +#include "leetcode.h" + +class Solution { +public: + int scheduleCourse(vector> &courses) { + int time = 0; + priority_queue 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 a, vector b) { return a[1] < b[1]; } +}; diff --git a/other/create_bt_from_desc.cpp b/other/create_bt_from_desc.cpp new file mode 100644 index 0000000..9ad6b4a --- /dev/null +++ b/other/create_bt_from_desc.cpp @@ -0,0 +1,40 @@ +// 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> &descriptions) { + unordered_map get_node; + unordered_map 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 new file mode 100644 index 0000000..e244252 --- /dev/null +++ b/other/daily_temps.cpp @@ -0,0 +1,28 @@ +#include "leetcode.h" + +class Solution { +public: + vector dailyTemperatures(vector &temperatures) { + int n = temperatures.size(); + vector nge(n, 0); + stack 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 t1 = {73, 74, 75, 71, 69, 72, 76, 73}; + vector t2 = {30, 40, 50, 60}; + vector 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 new file mode 100644 index 0000000..63b1f2b --- /dev/null +++ b/other/daily_temps.rs @@ -0,0 +1,28 @@ +struct Solution; + +impl Solution { + pub fn daily_temperatures(temperatures: Vec) -> Vec { + let n = temperatures.len(); + let mut ans: Vec = vec![0; n]; + let mut stk: Vec = 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 new file mode 100644 index 0000000..3682ee2 --- /dev/null +++ b/other/data_stream_disjoint_interval.cpp @@ -0,0 +1,45 @@ +// 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 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 new file mode 100644 index 0000000..c03bd67 --- /dev/null +++ b/other/decode_ways.cpp @@ -0,0 +1,23 @@ +#include "leetcode.h" + +class Solution { +public: + int numDecodings(string s) { + int n = s.size(); + vector 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 new file mode 100644 index 0000000..7ee4139 --- /dev/null +++ b/other/decode_xor_array.cpp @@ -0,0 +1,35 @@ +// 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 decode(vector encoded, int first) { + for (int &i : encoded) { + swap(i, first); + first ^= i; + } + encoded.push_back(first); + return encoded; + } +}; + +int main() { + Solution obj; + vector 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 new file mode 100644 index 0000000..4954032 --- /dev/null +++ b/other/delete_col_sorted.cpp @@ -0,0 +1,26 @@ +#include "leetcode.h" + +class Solution { +public: + int minDeletionSize(vector &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 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 new file mode 100644 index 0000000..1b7d24a --- /dev/null +++ b/other/delete_col_sorted.rs @@ -0,0 +1,25 @@ +struct Solution; + +impl Solution { + pub fn min_deletion_size(strs: Vec) -> i32 { + let mut ans = 0; + let mut new_strs: Vec> = Vec::new(); + for i in 0..strs.len() { + new_strs.push(strs[i].chars().collect::>()); + } + 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 new file mode 100644 index 0000000..1493046 --- /dev/null +++ b/other/delete_middle_node.cpp @@ -0,0 +1,16 @@ +#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 new file mode 100644 index 0000000..289d8dd --- /dev/null +++ b/other/delete_middle_node.rs @@ -0,0 +1,52 @@ +pub struct Solution; +pub struct ListNode { + pub val: i32, + pub next: Option> +} + +impl ListNode { + #[inline] + fn new(val: i32) -> self { + ListNode { + next: None, + val + } + } +} + +impl Solution { + pub fn delete_middle(head: Option>) -> Option> { + 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 new file mode 100644 index 0000000..cefe915 --- /dev/null +++ b/other/delete_node_link_list.cpp @@ -0,0 +1,10 @@ +#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 new file mode 100644 index 0000000..b6e38e4 --- /dev/null +++ b/other/delete_operation_2string.cpp @@ -0,0 +1,26 @@ +#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 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 new file mode 100644 index 0000000..697e17b --- /dev/null +++ b/other/design_circular_queue.cpp @@ -0,0 +1,53 @@ +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 new file mode 100644 index 0000000..bdfef0c --- /dev/null +++ b/other/design_food_rating_sys.cpp @@ -0,0 +1,40 @@ +// 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 f2c; + unordered_map f2r; + unordered_map>> c2r; + +public: + FoodRatings(vector &foods, vector &cuisines, + vector &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 new file mode 100644 index 0000000..bc37a6a --- /dev/null +++ b/other/design_number_container.cpp @@ -0,0 +1,39 @@ +// 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 idxs; + unordered_map> 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 new file mode 100644 index 0000000..5cfaf74 --- /dev/null +++ b/other/design_parking_system.cpp @@ -0,0 +1,40 @@ +// 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 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 new file mode 100644 index 0000000..f0904d2 --- /dev/null +++ b/other/design_underground_system.cpp @@ -0,0 +1,20 @@ +class UndergroundSystem { +public: + unordered_map> checkIns; + unordered_map> 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 new file mode 100644 index 0000000..27aa46b --- /dev/null +++ b/other/detect_capital.cpp @@ -0,0 +1,21 @@ +#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 new file mode 100644 index 0000000..454381d --- /dev/null +++ b/other/detect_capital.rs @@ -0,0 +1,20 @@ +struct Solution; + +impl Solution { + pub fn detect_capital_use(word: String) -> bool { + let v: Vec = 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 new file mode 100644 index 0000000..fd249e1 --- /dev/null +++ b/other/determine_string_halves.cpp @@ -0,0 +1,25 @@ +#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 new file mode 100644 index 0000000..f7f4303 --- /dev/null +++ b/other/determine_string_halves.rs @@ -0,0 +1,18 @@ +use std::collections::HashSet; +struct Solution; + +impl Solution { + pub fn halves_are_alike(s: String) -> bool { + let vowels: HashSet = 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::() == 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 new file mode 100644 index 0000000..89e2322 --- /dev/null +++ b/other/determine_strings_close.cpp @@ -0,0 +1,28 @@ +#include "leetcode.h" + +class Solution { +public: + bool closeStrings(string word1, string word2) { + if (word1.size() != word2.size()) + return false; + vector 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 new file mode 100644 index 0000000..f293b6d --- /dev/null +++ b/other/determine_strings_close.rs @@ -0,0 +1,25 @@ +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 new file mode 100644 index 0000000..4d92b98 --- /dev/null +++ b/other/detonate_max_bombs.cpp @@ -0,0 +1,61 @@ +// 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 &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 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 new file mode 100644 index 0000000..6695ae7 --- /dev/null +++ b/other/diff_two_array.cpp @@ -0,0 +1,35 @@ +// 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 &n1, vector &n2) { + unordered_set 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 n11 = {1, 2, 3}, n21 = {2, 4, 6}; + vector 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 new file mode 100644 index 0000000..a76d21e --- /dev/null +++ b/other/discount_n_orders.cpp @@ -0,0 +1,27 @@ +#include "leetcode.h" + +class Cashier { +public: + Cashier(int n, int discount, vector &products, vector &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 product, vector 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 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 new file mode 100644 index 0000000..ea07a34 --- /dev/null +++ b/other/divide_nodes_max_groups.cpp @@ -0,0 +1,75 @@ +// 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> &edges) { + vector vis(n); + vector> 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 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 vis(n); + vis[x] = true; + queue 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 new file mode 100644 index 0000000..80a97d0 --- /dev/null +++ b/other/domino_tromino_tiling.cpp @@ -0,0 +1,28 @@ +#include "leetcode.h" +#include + +class Solution { +public: + int numTilings(int n) { + int mod = 1e9; + mod += 7; + vector 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 new file mode 100644 index 0000000..554f147 --- /dev/null +++ b/other/domino_tromino_tiling.rs @@ -0,0 +1,20 @@ +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 new file mode 100644 index 0000000..f990e62 --- /dev/null +++ b/other/earliest_possible_full_bloom.cpp @@ -0,0 +1,26 @@ +#include "leetcode.h" + +class Solution { +public: + int earliestFullBloom(vector &plantTime, vector &growTime) { + int n = plantTime.size(); + vector> 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 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 new file mode 100644 index 0000000..b8e6444 --- /dev/null +++ b/other/earliest_possible_full_bloom.rs @@ -0,0 +1,20 @@ +struct Solution; + +impl Solution { + pub fn earliest_full_bloom(plant_time: Vec, grow_time: Vec) -> 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 new file mode 100644 index 0000000..4103e83 --- /dev/null +++ b/other/edit_distance.cpp @@ -0,0 +1,41 @@ +// 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(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 new file mode 100644 index 0000000..b0a1711 --- /dev/null +++ b/other/eliminate_monsters.cpp @@ -0,0 +1,31 @@ +#include "leetcode.h" + +class Solution { +public: + typedef pair p; + int eliminateMaxium(vector &dist, vector &speed) { + priority_queue, greater

> 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 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 new file mode 100644 index 0000000..d7b9d98 --- /dev/null +++ b/other/encode_decode_tinyurl.cpp @@ -0,0 +1,43 @@ +// 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 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(longUrl, code)); + code_url.insert(pair(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 new file mode 100644 index 0000000..426291c --- /dev/null +++ b/other/equal_row_col_pair.cpp @@ -0,0 +1,34 @@ +// 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, int> mv; + for (int i = 0; i < grid.size(); i++) + mv[grid[i]]++; + for (int i = 0; i < grid[0].size(); i++) { + vector 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 new file mode 100644 index 0000000..9d26fb9 --- /dev/null +++ b/other/erect_fence.cpp @@ -0,0 +1,29 @@ +#include "leetcode.h" + +class Solution { +public: + using tree = vector; + vector outerTrees(vector &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 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 unique(dv.begin(), dv.end()); + return vector(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 new file mode 100644 index 0000000..6dee425 --- /dev/null +++ b/other/erect_fence.rs @@ -0,0 +1,27 @@ +use std::collections::VecDeque; +type Tree = Vec; +struct Solution; + +impl Solution { + pub fn outer_trees(mut trees: Vec) -> Vec { + 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 = 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 new file mode 100644 index 0000000..4cd39b8 --- /dev/null +++ b/other/eval_reverse_polish_notation.cpp @@ -0,0 +1,46 @@ +#include "leetcode.h" + +class Solution { +public: + int evalRPN(vector &tokens) { + unordered_map> 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 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(stk.top()); + } +}; + +int main() { + Solution obj; + vector tokens1 = {"2", "1", "+", "3", "*"}; + // output: 9 + // ((2 + 1) * 3) + cout << obj.evalRPN(tokens1); + vector tokens2 = {"4", "13", "5", "/", "+"}; + // output: 6 + // (4 + (13 / 5)) + cout << obj.evalRPN(tokens2); + vector 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 new file mode 100644 index 0000000..11a36e3 --- /dev/null +++ b/other/eval_reverse_polish_notation.rs @@ -0,0 +1,29 @@ +struct Solution; + +impl Solution { + pub fn eval_rpn(tokens: Vec) -> 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 new file mode 100644 index 0000000..6e41e3e --- /dev/null +++ b/other/eventual_safe_states.cpp @@ -0,0 +1,54 @@ +// 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 eventualSafeNodes(vector> &graph) { + int n = graph.size(); + vector> g(n); + vector 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 q; + for (int i = 0; i < n; i++) + if (!dp[i]) + q.push(i); + vector 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 new file mode 100644 index 0000000..3de395f --- /dev/null +++ b/other/excel_sheet_column_title.cpp @@ -0,0 +1,39 @@ +// 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 new file mode 100644 index 0000000..b26cb93 --- /dev/null +++ b/other/extra_char_string.cpp @@ -0,0 +1,50 @@ +// 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 &dp, string s, unordered_set &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 &dictionary) { + unordered_set d; + for (auto i : dictionary) + d.insert(hash_func(i)); + vector dp(s.size(), -1); + return min_cost(0, dp, s, d); + } +}; + +int main() { + Solution obj; + string s1 = "leetscode", s2 = "sayhelloworld"; + vector 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 new file mode 100644 index 0000000..69e0ab4 --- /dev/null +++ b/other/fair_distribution_cookie.cpp @@ -0,0 +1,45 @@ +// 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 &cookies, vector &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 &cookies, int k) { + int n = cookies.size(); + vector v(k, 0); + solve(0, cookies, v, k); + return ans; + } +}; + +int main() { + Solution obj; + vector 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 new file mode 100644 index 0000000..651b8a7 --- /dev/null +++ b/other/far_from_land.cpp @@ -0,0 +1,44 @@ +#include "leetcode.h" + +class Solution { +public: + int maxDistance(vector> &grid) { + int ans = -1; + if (grid.empty() || grid[0].empty()) + return ans; + + vector> gridValues(grid.size(), + vector(grid[0].size(), INT_MAX)); + queue> 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 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 new file mode 100644 index 0000000..69e46ee --- /dev/null +++ b/other/fibonacci_number.cpp @@ -0,0 +1,20 @@ +#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 new file mode 100644 index 0000000..39fe153 --- /dev/null +++ b/other/find_all_anagrams.cpp @@ -0,0 +1,40 @@ +// 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 findAnagrams(string s, string p) { + int ssz = s.size(), psz = p.size(); + if (ssz < psz) + return {}; + vector 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 new file mode 100644 index 0000000..2288095 --- /dev/null +++ b/other/find_building_alice_bob_meet.cpp @@ -0,0 +1,59 @@ +// 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 leftmostBuildingQueries(vector &heights, + vector> &queries) { + int hn = heights.size(), qn = queries.size(); + vector>> q(hn); + priority_queue, vector>, greater>> pq; + vector 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 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 lmbq1 = obj.leftmostBuildingQueries(h1, q1); + vector 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 new file mode 100644 index 0000000..898fd81 --- /dev/null +++ b/other/find_critical_edge_tree.cpp @@ -0,0 +1,101 @@ +// 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 f, rank; + +public: + UnionFind(int n) { + rank = vector(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 &a, const vector &b) { return a[2] < b[2]; }); + int origin_mst = get_mst(n, edges, -1); + vector 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 new file mode 100644 index 0000000..17ff6f0 --- /dev/null +++ b/other/find_duplicate_file.cpp @@ -0,0 +1,30 @@ +#include "leetcode.h" + +class Solution { +public: + vvd(string) findDuplicate(vector &paths) { + unordered_map> 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 new file mode 100644 index 0000000..5880fc8 --- /dev/null +++ b/other/find_duplicate_subtree.cpp @@ -0,0 +1,30 @@ +// 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 findDuplicateSubtrees(TreeNode *root) { + unordered_map> map; + vector 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> &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 new file mode 100644 index 0000000..7f5f989 --- /dev/null +++ b/other/find_first_last_array.cpp @@ -0,0 +1,22 @@ +#include "leetcode.h" + +class Solution { +public: + vector searchRange(vector &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 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 new file mode 100644 index 0000000..d496633 --- /dev/null +++ b/other/find_groups_farmland.cpp @@ -0,0 +1,43 @@ +#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 new file mode 100644 index 0000000..c67dbac --- /dev/null +++ b/other/find_highest_altitude.cpp @@ -0,0 +1,31 @@ +// 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 &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 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 new file mode 100644 index 0000000..a8a224e --- /dev/null +++ b/other/find_k_beauty_num.cpp @@ -0,0 +1,16 @@ +#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 new file mode 100644 index 0000000..e15810c --- /dev/null +++ b/other/find_k_closest_elements.cpp @@ -0,0 +1,37 @@ +// 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 findClosestElements(vector &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(arr.begin() + l, arr.begin() + l + k); + } +}; + +int main() { + Solution obj; + vector a1 = {1, 2, 3, 4, 5}, a2 = {1, 2, 3, 4, 5}; + vector fce1 = obj.findClosestElements(a1, 4, 3); + vector 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 new file mode 100644 index 0000000..94b779a --- /dev/null +++ b/other/find_k_pair_sum.cpp @@ -0,0 +1,50 @@ +// 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 &nums1, vector &nums2, int k) { + priority_queue>, vector>>, + greater>>> + 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> 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 n11 = {1, 7, 11}, n21 = {2, 4, 6}; + vector n12 = {1, 1, 2}, n22 = {1, 2, 3}; + vector 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 new file mode 100644 index 0000000..60c43b8 --- /dev/null +++ b/other/find_max_sum_node_val.cpp @@ -0,0 +1,43 @@ +// 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 &nums, int k, + vector> &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 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 new file mode 100644 index 0000000..14fbcc3 --- /dev/null +++ b/other/find_median_data_stream.cpp @@ -0,0 +1,29 @@ +#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 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 new file mode 100644 index 0000000..1ef5252 --- /dev/null +++ b/other/find_median_data_stream.rs @@ -0,0 +1,41 @@ +use std::cmp::Reverse; +use std::collections::BinaryHeap; +#[derive(Default)] +struct MedianFinder { + small: BinaryHeap, + large: BinaryHeap>, + 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 new file mode 100644 index 0000000..a434616 --- /dev/null +++ b/other/find_orig_array_double.cpp @@ -0,0 +1,19 @@ +#include "leetcode.h" + +class Solution { +public: + vector findOriginalArray(vector &changed) { + int count[100001] = {}, i = 0; + vector 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() + : ans; + } +}; diff --git a/other/find_path_graph.cpp b/other/find_path_graph.cpp new file mode 100644 index 0000000..9f6c8ae --- /dev/null +++ b/other/find_path_graph.cpp @@ -0,0 +1,28 @@ +#include "leetcode.h" + +class Solution { +public: + bool validPath(int n, vvd & edges, int source, int destination) { + vector 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 &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 new file mode 100644 index 0000000..a74a654 --- /dev/null +++ b/other/find_path_graph.rs @@ -0,0 +1,48 @@ +struct Solution; + +impl Solution { + pub fn valid_path(n: i32, edges: Vec>, source: i32, destination: i32) -> bool { + let n: usize = n as usize; + let mut roots: Vec = { + let mut ans: Vec = vec![0; n]; + for i in 0..n { + ans[i] = i; + } + ans + }; + let mut ranks: Vec = 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, ranks: &mut Vec) { + 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 { + 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 new file mode 100644 index 0000000..5aba77e --- /dev/null +++ b/other/find_player_zero_one_loss.cpp @@ -0,0 +1,21 @@ +#include "leetcode.h" + +class Solution { +public: + vvd findWinners(vvd & matches) { + map lost; + for (auto m : matches) { + if (!lost.count(m[0])) + lost[m[0]] = 0; + lost[m[1]]++; + } + vector 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 new file mode 100644 index 0000000..a0ae44e --- /dev/null +++ b/other/find_player_zero_one_loss.rs @@ -0,0 +1,14 @@ +use std::collections::BTreeMap; +struct Solution; + +impl Solution { + pub fn find_winners(matches: Vec>) -> Vec> { + let mut lost: BTreeMap = 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 new file mode 100644 index 0000000..a00bfcb --- /dev/null +++ b/other/find_replace_pattern.cpp @@ -0,0 +1,32 @@ +#include "leetcode.h" + +class Solution { +public: + vector findAndReplacePattern(vector &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 ans; + unordered_map 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 new file mode 100644 index 0000000..e6dcc3b --- /dev/null +++ b/other/find_safest_path_grid.cpp @@ -0,0 +1,89 @@ +// 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> &grid) { + if (grid[0][0] < d || grid[n - 1][n - 1] < d) + return false; + queue> qp; + vector> vis(n, vector(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> &grid) { + n = grid.size(); + if (grid[0][0] || grid[n - 1][n - 1]) + return 0; + queue> 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 new file mode 100644 index 0000000..42f2e6a --- /dev/null +++ b/other/find_score_arr_mark.cpp @@ -0,0 +1,40 @@ +// 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 &nums) { + long long ans = 0; + set> 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 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 new file mode 100644 index 0000000..01a5562 --- /dev/null +++ b/other/find_smallest_letter.cpp @@ -0,0 +1,34 @@ +// 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 &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 l1_2 = {'c', 'f', 'j'}; + vector 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 new file mode 100644 index 0000000..5607688 --- /dev/null +++ b/other/find_town_judge.cpp @@ -0,0 +1,46 @@ +// 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> graph(n + 1, unordered_set()); + 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 new file mode 100644 index 0000000..48fc05d --- /dev/null +++ b/other/first_missing_positive.cpp @@ -0,0 +1,12 @@ +#include "leetcode.h" +#include + +class Solution { +public: + vector firstMissingPositive(vector &nums) {} +}; + +int main() { + Solution obj; + vector nums1 = {1, 2, 0}, nums2 = {} +} diff --git a/other/first_unique_char_string.cpp b/other/first_unique_char_string.cpp new file mode 100644 index 0000000..5f55821 --- /dev/null +++ b/other/first_unique_char_string.cpp @@ -0,0 +1,22 @@ +#include "leetcode.h" + +class Solution { +public: + int firstUniqChar(string s) { + unordered_map> 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 new file mode 100644 index 0000000..82751c7 --- /dev/null +++ b/other/flatten_binary_to_linked.cpp @@ -0,0 +1,21 @@ +#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 new file mode 100644 index 0000000..35e0e0c --- /dev/null +++ b/other/flip_string_monotone_increase.cpp @@ -0,0 +1,36 @@ +#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 new file mode 100644 index 0000000..2763f8c --- /dev/null +++ b/other/freedom_trail.cpp @@ -0,0 +1,55 @@ +// 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> idx_map; + for (int i = 0; i < n; ++i) + idx_map[ring[i]].push_back(i); + vector>> 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 new file mode 100644 index 0000000..d9a21fc --- /dev/null +++ b/other/frog_jump.cpp @@ -0,0 +1,47 @@ +// 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 &stones, map &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 &stones) { + int n = stones.size(); + map mp; + for (int i = 0; i < n; i++) + mp[stones[i]] = i; + vvd dp(n + 1, vector(n + 1, -1)); + return process(stones, mp, 0, 0, dp); + } +}; + +int main() { + Solution obj; + vector 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 new file mode 100644 index 0000000..e613659 --- /dev/null +++ b/other/fruit_into_baskets.cpp @@ -0,0 +1,41 @@ +// 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 &fruits) { + int n = fruits.size(), ans = 0; + unordered_map 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 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 new file mode 100644 index 0000000..6baff33 --- /dev/null +++ b/other/furthest_building_reach.cpp @@ -0,0 +1,32 @@ +#include "leetcode.h" + +class Solution { +public: + int furthestBuilding(vector &heights, int bricks, int ladders) { + int n = heights.size() - 1; + priority_queue 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 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 new file mode 100644 index 0000000..2fdc7fb --- /dev/null +++ b/other/gas_station.cpp @@ -0,0 +1,25 @@ +#include "leetcode.h" + +class Solution { +public: + int canCompleteCircuit(vector &gas, vector &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 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 new file mode 100644 index 0000000..0554f5b --- /dev/null +++ b/other/gas_station.rs @@ -0,0 +1,26 @@ +struct Solution; + +impl Solution { + pub fn can_complete_circuit(gas: Vec, cost: Vec) -> 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 new file mode 100644 index 0000000..420eb10 --- /dev/null +++ b/other/greatest_common_div_string.cpp @@ -0,0 +1,36 @@ +// 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 new file mode 100644 index 0000000..c828e58 --- /dev/null +++ b/other/greatest_sum_div_three.cpp @@ -0,0 +1,43 @@ +// 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 &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 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 new file mode 100644 index 0000000..a2a7c8a --- /dev/null +++ b/other/group_anagrams.cpp @@ -0,0 +1,18 @@ +#include "leetcode.h" + +class Solution { +public: + vvd(string) groupAnagrams(vector &strs) { + map, vector> groups; + for (string s : strs) { + array 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 new file mode 100644 index 0000000..212fc15 --- /dev/null +++ b/other/group_anagrams.rs @@ -0,0 +1,15 @@ +use std::collections::HashMap; +struct Solution; + +impl Solution { + pub fn group_anagrams(strs: Vec) -> Vec> { + 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 new file mode 100644 index 0000000..d31ca99 --- /dev/null +++ b/other/guess_number_high_low.cpp @@ -0,0 +1,22 @@ +#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 new file mode 100644 index 0000000..4cd717b --- /dev/null +++ b/other/guess_number_high_low.rs @@ -0,0 +1,22 @@ +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 new file mode 100644 index 0000000..b08c7fa --- /dev/null +++ b/other/hand_of_straights.cpp @@ -0,0 +1,30 @@ +#include "leetcode.h" + +class Solution { +public: + bool isNStraightHand(vector &hand, int groupSize) { + if (hand.size() % groupSize != 0) + return false; + map 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 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 new file mode 100644 index 0000000..e946b96 --- /dev/null +++ b/other/happy_number.cpp @@ -0,0 +1,37 @@ +#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 new file mode 100644 index 0000000..a08aa54 --- /dev/null +++ b/other/house_robber.cpp @@ -0,0 +1,21 @@ +#include "leetcode.h" + +class Solution { +public: + int rob(vector &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 nums = {1, 2, 3, 1}; + cout << obj.rob(nums); // expect 4 +} diff --git a/other/house_robber.rs b/other/house_robber.rs new file mode 100644 index 0000000..ce4afd9 --- /dev/null +++ b/other/house_robber.rs @@ -0,0 +1,18 @@ +struct Solution; + +impl Solution { + pub fn rob(nums: Vec) -> 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 new file mode 100644 index 0000000..0f24457 --- /dev/null +++ b/other/idx_first_occur_str.cpp @@ -0,0 +1,51 @@ +// 28. Find the Index of the First Occurrence in a String +#include "leetcode.h" +#include + +/* + * 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 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 kmp(string needle) { + int n = needle.size(); + vector 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 new file mode 100644 index 0000000..bc6eeba --- /dev/null +++ b/other/image_overlap.cpp @@ -0,0 +1,23 @@ +#include "leetcode.h" + +class Solution { +public: + int largestOverlap(vvd & img1, vvd & img2) { + vector la, lb; + int n = img1.size(); + unordered_map 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 new file mode 100644 index 0000000..fa6fbd6 --- /dev/null +++ b/other/image_overlap.rs @@ -0,0 +1,35 @@ +impl Solution { + pub fn largest_overlap(img1: Vec>, img2: Vec>) -> 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],img2: &[Vec], 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 new file mode 100644 index 0000000..551ce9f --- /dev/null +++ b/other/implement_queue_stacks.cpp @@ -0,0 +1,32 @@ +#include "leetcode.h" + +class MyQueue { +public: + stack 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 new file mode 100644 index 0000000..41a9f0e --- /dev/null +++ b/other/increasing_triplet_subsequence.cpp @@ -0,0 +1,26 @@ +#include "leetcode.h" + +class Solution { +public: + bool increasingTriplet(vector &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 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 new file mode 100644 index 0000000..700ccc3 --- /dev/null +++ b/other/inform_employees.cpp @@ -0,0 +1,44 @@ +// 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 &manager, vector &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 &manager, + vector &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 m1 = {-1}, m2 = {2, 2, -1, 2, 2, 2}; + vector 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 new file mode 100644 index 0000000..5bb76da --- /dev/null +++ b/other/insert_delete_getrandom.cpp @@ -0,0 +1,45 @@ +#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 data; + vector 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 new file mode 100644 index 0000000..12a772f --- /dev/null +++ b/other/insert_delete_getrandom.rs @@ -0,0 +1,55 @@ +extern crate rand; +use rand::{Rng, thread_rng, rngs::ThreadRng}; +use std::collections::HashMap; + +struct RandomizedSet { + rng: ThreadRng, + data: Vec, + idx_map: HashMap +} + +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 new file mode 100644 index 0000000..50e16f8 --- /dev/null +++ b/other/insert_interval.cpp @@ -0,0 +1,39 @@ +#include "leetcode.h" + +class Solution { +public: + vvd insert(vvd & intervals, vector &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 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 new file mode 100644 index 0000000..e3a8a22 --- /dev/null +++ b/other/int_roman.cpp @@ -0,0 +1,22 @@ +#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 new file mode 100644 index 0000000..9e8aa9e --- /dev/null +++ b/other/int_roman.rs @@ -0,0 +1,26 @@ +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 new file mode 100644 index 0000000..c015be2 --- /dev/null +++ b/other/integer_break.cpp @@ -0,0 +1,20 @@ +#include "leetcode.h" + +class Solution { +public: + int integerBreak(int n) { + if (n <= 2) + return true; + vector 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 new file mode 100644 index 0000000..ed2a5b9 --- /dev/null +++ b/other/interleaving_string.cpp @@ -0,0 +1,39 @@ +#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 new file mode 100644 index 0000000..e8f0585 --- /dev/null +++ b/other/invert_binary_tree.cpp @@ -0,0 +1,26 @@ +// 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 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 new file mode 100644 index 0000000..61d5baa --- /dev/null +++ b/other/ipo.cpp @@ -0,0 +1,52 @@ +// 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 &profits, + vector &capital) { + priority_queue pq; + int x = 0; + vector> 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 profits = {1, 2, 3}; + vector 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 new file mode 100644 index 0000000..4a6b4fc --- /dev/null +++ b/other/is_graph_biparite.cpp @@ -0,0 +1,52 @@ +// 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 colour(n); + queue 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 new file mode 100644 index 0000000..153d9aa --- /dev/null +++ b/other/jump_game.cpp @@ -0,0 +1,24 @@ +#include "leetcode.h" + +class Solution { +public: + bool canJump(vector &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 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 new file mode 100644 index 0000000..e7f36b0 --- /dev/null +++ b/other/jump_game.rs @@ -0,0 +1,18 @@ +struct Solution; + +impl Solution { + pub fn can_jump(nums: Vec) -> 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 new file mode 100644 index 0000000..03f7d37 --- /dev/null +++ b/other/jump_game3.cpp @@ -0,0 +1,27 @@ +#include "leetcode.h" + +class Solution { +public: + bool canReach(vector &arr, int start) { + vector visited(arr.size(), false); + return dfs(arr, start, visited); + } + +private: + bool dfs(vector &arr, int curr, vector &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 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 new file mode 100644 index 0000000..a973fad --- /dev/null +++ b/other/jump_game3.rs @@ -0,0 +1,35 @@ +use std::collections::VecDeque; +struct Solution; + +impl Solution { + pub fn can_reach(arr: Vec, start: i32) -> bool { + let mut arr = arr; + let mut vd: VecDeque = 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 new file mode 100644 index 0000000..8496d94 --- /dev/null +++ b/other/jump_game4.cpp @@ -0,0 +1,52 @@ +// 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 &arr) { + int n = arr.size(), step = 0; + unordered_map> idx_val; + for (int i = 0; i < n; i++) + idx_val[arr[i]].push_back(i); + vector visited(n); + visited[0] = true; + queue 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 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 a1 = {100, -23, -23, 404, 100, 23, 23, 23, 3, 404}; + vector 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 new file mode 100644 index 0000000..81bbf05 --- /dev/null +++ b/other/jump_game6.cpp @@ -0,0 +1,26 @@ +#include "leetcode.h" + +class Solution { +public: + int maxResult(vector &nums, int k) { + int ans = 0; + deque 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 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 new file mode 100644 index 0000000..5601d19 --- /dev/null +++ b/other/k_inverse_pairs.cpp @@ -0,0 +1,24 @@ +#include "leetcode.h" + +class Solution { +public: + int kInversePairs(int n, int k) { + vector dp(k + 1, 0); + int mod = 1e9 + 7; + for (int i = 1; i <= n; i++) { + vector 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 new file mode 100644 index 0000000..91184bb --- /dev/null +++ b/other/k_radius_subarr.cpp @@ -0,0 +1,45 @@ +// 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 getAverages(vector &nums, int k) { + vector 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 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 new file mode 100644 index 0000000..59308ef --- /dev/null +++ b/other/keys_and_rooms.cpp @@ -0,0 +1,32 @@ +#include "leetcode.h" + +class Solution { +public: + bool canVisitAllRooms(vvd & rooms) { + stack dfs; + dfs.push(0); + unordered_set 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 new file mode 100644 index 0000000..678c732 --- /dev/null +++ b/other/keys_and_rooms.rs @@ -0,0 +1,23 @@ +struct Solution; + +impl Solution { + pub fn can_visit_all_rooms(rooms: Vec>) -> 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 new file mode 100644 index 0000000..8be7b4c --- /dev/null +++ b/other/kids_max_num_candy.cpp @@ -0,0 +1,42 @@ +// 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 kidsWithCandies(vector &candies, int extra) { + int m = 0; + vector 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 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 new file mode 100644 index 0000000..0c5094d --- /dev/null +++ b/other/knight_probability_chessboard.cpp @@ -0,0 +1,41 @@ +// 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>> 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 new file mode 100644 index 0000000..3076169 --- /dev/null +++ b/other/koko_eating_bananas.cpp @@ -0,0 +1,30 @@ +// 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 &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 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 new file mode 100644 index 0000000..75e5234 --- /dev/null +++ b/other/kth_element_in_stream.cpp @@ -0,0 +1,32 @@ +#include "leetcode.h" + +class KthLargest { +private: + int k; + priority_queue, greater> pq; + +public: + KthLargest(int k, vector &nums) { + this->k = k; + auto endPointer = nums.begin() + min(k, nums.size()); + pq = priority_queue, greater>(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 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 new file mode 100644 index 0000000..c9a60c2 --- /dev/null +++ b/other/kth_largest_element.cpp @@ -0,0 +1,25 @@ +// 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 &nums, int k) { + priority_queue pq(nums.begin(), nums.end()); + for (int i = 1; i < k; i++) + pq.pop(); + return pq.top(); + } +}; + +int main() { + Solution obj; + vector 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 new file mode 100644 index 0000000..3ef8b3c --- /dev/null +++ b/other/kth_largest_element_stream.cpp @@ -0,0 +1,43 @@ +// 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, greater> pq; + int size; + +public: + KthLargest(int k, vector &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 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 new file mode 100644 index 0000000..a7f81f7 --- /dev/null +++ b/other/kth_missing_pos_num.cpp @@ -0,0 +1,30 @@ +// 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 &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 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 new file mode 100644 index 0000000..71478e9 --- /dev/null +++ b/other/kth_smallest_lexicographical.cpp @@ -0,0 +1,31 @@ +// 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(curr), last = first + 1; + first <= n; first *= 10, last *= 10) + cnt += static_cast((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 new file mode 100644 index 0000000..aad9458 --- /dev/null +++ b/other/kth_smallest_sorted_matrix.cpp @@ -0,0 +1,30 @@ +#include "leetcode.h" + +class Solution { +public: + int kthSmallest(vector> &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> matrix; + int k; + obj.kthSmallest(matrix, k); +} diff --git a/other/largest_colour_value_graph.cpp b/other/largest_colour_value_graph.cpp new file mode 100644 index 0000000..5307742 --- /dev/null +++ b/other/largest_colour_value_graph.cpp @@ -0,0 +1,87 @@ +// 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 &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 target(colours_size); + for (auto &e : edges) { + al[e[0]].push_back(e[1]); + target[e[1]] = true; + } + vector> vp; + for (int i = 0; i < colours_size; ++i) + if (!target[i]) + vp.push_back({i, -1}); + int ans = 0; + vector 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 cnt(colours_size, -1); + auto q = vp; + while (!q.empty()) { + vector> 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 new file mode 100644 index 0000000..91015d0 --- /dev/null +++ b/other/largest_int_add_target.cpp @@ -0,0 +1,29 @@ +#include "leetcode.h" + +class Solution { +public: + string largestNumber(vector &cost, int target) { + vector 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 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 new file mode 100644 index 0000000..1c9e3e1 --- /dev/null +++ b/other/largest_multiple_three.cpp @@ -0,0 +1,37 @@ +#include "leetcode.h" + +class Solution { +public: + string largestMultipleOfThree(vector &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 digits = {8, 1, 9}; + cout << obj.largestMultipleOfThree(digits); +} diff --git a/other/largest_odd_num_string.cpp b/other/largest_odd_num_string.cpp new file mode 100644 index 0000000..019d609 --- /dev/null +++ b/other/largest_odd_num_string.cpp @@ -0,0 +1,28 @@ +#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 new file mode 100644 index 0000000..64b3682 --- /dev/null +++ b/other/largest_perimeter_triangle.cpp @@ -0,0 +1,18 @@ +#include "leetcode.h" + +class Solution { +public: + int largestPerimeter(vector &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 nums = {2, 1, 2}; + cout << obj.largestPerimeter(nums); +} diff --git a/other/last_day_cross.cpp b/other/last_day_cross.cpp new file mode 100644 index 0000000..4bf2e6b --- /dev/null +++ b/other/last_day_cross.cpp @@ -0,0 +1,62 @@ +// 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(col, 1)); + p = vector(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 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 new file mode 100644 index 0000000..319fbbf --- /dev/null +++ b/other/leaf_similar_trees.cpp @@ -0,0 +1,28 @@ +#include "leetcode.h" + +class Solution { +public: + bool leafSimilar(TreeNode *root1, TreeNode *root2) { + stack 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 &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 new file mode 100644 index 0000000..6dcaae1 --- /dev/null +++ b/other/leaf_similar_trees.rs @@ -0,0 +1,44 @@ +#[derive(Debug, PartialEq, Eq)] +pub struct TreeNode { + pub val: i32, + pub left: Option>>, + pub right: Option>> +} + +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>>, root2: Option>>) -> bool { + let mut leaves1 = Vec::::new(); + Solution::get_leaves(root1, &mut leaves1); + let mut leaves2 = Vec::::new(); + Solution::get_leaves(root2, &mut leaves2); + leaves1 == leaves2 + } + fn get_leaves(node: Option>>, leaves: &mut Vec) { + 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 new file mode 100644 index 0000000..c15a628 --- /dev/null +++ b/other/letter_combo_number.cpp @@ -0,0 +1,32 @@ +#include "leetcode.h" + +class Solution { +public: + vector letterCombinations(string digits) { + if (digits.empty()) + return {}; + vector ans; + ans.push_back(""); + for (auto digit : digits) { + vector 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 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 new file mode 100644 index 0000000..ab48ce5 --- /dev/null +++ b/other/lexicographical_numbers.cpp @@ -0,0 +1,43 @@ +// 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 ans; + vector 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 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 new file mode 100644 index 0000000..3a58189 --- /dev/null +++ b/other/lexicographically_small_string.cpp @@ -0,0 +1,42 @@ +#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 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 &ds, int p) { + return ds[p] == -1 ? p : ds[p] = dsFind(ds, ds[p]); + } + void dsMerge(vector &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 new file mode 100644 index 0000000..c0c857a --- /dev/null +++ b/other/lfu_cache.cpp @@ -0,0 +1,69 @@ +// 460. LFU Cache +#include +#include +using namespace std; + +// https://en.wikipedia.org/wiki/Least_frequently_used +// http://dhruvbird.com/lfu.pdf + +struct Node { + int value; + list::iterator itr; +}; + +class LFUCache { +private: + unordered_map umVal; + unordered_map umCount; + unordered_map> 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 new file mode 100644 index 0000000..43dccea --- /dev/null +++ b/other/linked_list_cycle2.cpp @@ -0,0 +1,31 @@ +// 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 new file mode 100644 index 0000000..ae147c5 --- /dev/null +++ b/other/linked_list_random.cpp @@ -0,0 +1,40 @@ +// 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 new file mode 100644 index 0000000..5cc91a7 --- /dev/null +++ b/other/longest_arithmetic_subseq.cpp @@ -0,0 +1,37 @@ +// 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 &nums) { + int n = nums.size(), ans = 0; + vvd dp(n, vector(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 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 new file mode 100644 index 0000000..dc6e9ff --- /dev/null +++ b/other/longest_arithmetic_subseq_diff.cpp @@ -0,0 +1,33 @@ +// 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 &arr, int difference) { + int ans = 1; + unordered_map 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 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 new file mode 100644 index 0000000..56cbaf9 --- /dev/null +++ b/other/longest_common_subseq.cpp @@ -0,0 +1,20 @@ +#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 new file mode 100644 index 0000000..212070a --- /dev/null +++ b/other/longest_common_subseq.rs @@ -0,0 +1,23 @@ +struct Solution; + +impl Solution { + pub fn longest_common_subsequence(text1: String, text2: String) -> i32 { + let mut dp: Vec> = 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 new file mode 100644 index 0000000..2fda5e6 --- /dev/null +++ b/other/longest_consecutive_sequence.cpp @@ -0,0 +1,36 @@ +#include "leetcode.h" + +class Solution { +public: + int longestConsecutive(vector &nums) { + unordered_set 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 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 new file mode 100644 index 0000000..b0cdf49 --- /dev/null +++ b/other/longest_cycle_graph.cpp @@ -0,0 +1,58 @@ +// 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 &edges) { + vector vis(edges.size(), 0); + for (int i = 0; i < edges.size(); i++) { + if (vis[i]) + continue; + vector store; + dfs(edges, i, vis, store); + } + return max_len; + } + +private: + int max_len = -1; + void dfs(vector &edges, int si, vector &vis, vector &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 e1 = {3, 3, 4, 2, 3}; + vector 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 new file mode 100644 index 0000000..ea3ad78 --- /dev/null +++ b/other/longest_happy_string.cpp @@ -0,0 +1,33 @@ +// 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 new file mode 100644 index 0000000..127a984 --- /dev/null +++ b/other/longest_increasing_subseq.cpp @@ -0,0 +1,48 @@ +#include "leetcode.h" + +class maxBit { +public: + vector 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 &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 &arr) { + vector 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 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 new file mode 100644 index 0000000..3a42e0a --- /dev/null +++ b/other/longest_palindrome_concat.cpp @@ -0,0 +1,29 @@ +#include "leetcode.h" + +class Solution { +public: + int longestPalindrome(vector &words) { + unordered_map 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 words = {"lc", "cl", "gg"}; + cout << obj.longestPalindrome(words); +} diff --git a/other/longest_palindrome_concat.rs b/other/longest_palindrome_concat.rs new file mode 100644 index 0000000..2a97ed4 --- /dev/null +++ b/other/longest_palindrome_concat.rs @@ -0,0 +1,39 @@ +struct Solution; + +impl Solution { + pub fn longest_palindrome(words: Vec) -> 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 new file mode 100644 index 0000000..f2a074f --- /dev/null +++ b/other/longest_palindromic_subseq.cpp @@ -0,0 +1,35 @@ +// 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 dp(n, 0); + for (int i = n - 1; i >= 0; i--) { + vector 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 new file mode 100644 index 0000000..4ecba25 --- /dev/null +++ b/other/longest_palindromic_substr.cpp @@ -0,0 +1,35 @@ +#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 new file mode 100644 index 0000000..0f60da9 --- /dev/null +++ b/other/longest_path_diff_adjacent_char.cpp @@ -0,0 +1,48 @@ +// 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 &parent, string s) { + int n = parent.size(), ans = 1; + queue q; + vector 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 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 new file mode 100644 index 0000000..b35568c --- /dev/null +++ b/other/longest_path_diff_adjacent_char.rs @@ -0,0 +1,77 @@ +// 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, 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 = s.chars().collect(); + Self::dfs(0, &graph, &sa); + let mut ans: i32 = 0; + unsafe { + ans = res; + } + ans + } + fn dfs(root: usize, graph: &HashMap>, s: &Vec) -> 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 new file mode 100644 index 0000000..afa805c --- /dev/null +++ b/other/longest_string_chain.cpp @@ -0,0 +1,34 @@ +#include "leetcode.h" + +class Solution { +public: + int longestStrChain(vector &words) { + vector> vus(17); + for (auto i : words) + vus[i.size()].insert(i); + unordered_map 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 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 new file mode 100644 index 0000000..35f2353 --- /dev/null +++ b/other/longest_subarr_ones.cpp @@ -0,0 +1,31 @@ +// 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 &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 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 new file mode 100644 index 0000000..9613667 --- /dev/null +++ b/other/longest_subseq_lim_sum.cpp @@ -0,0 +1,31 @@ +#include "leetcode.h" + +class Solution { +public: + vector answerQueries(vector &nums, vector &queries) { + int n = nums.size(), m = queries.size(); + sort(nums.begin(), nums.end()); + vector 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 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 new file mode 100644 index 0000000..037b606 --- /dev/null +++ b/other/longest_subseq_lim_sum.rs @@ -0,0 +1,17 @@ +struct Solution; + +impl Solution { + pub fn answer_queries(mut nums: Vec, queries: Vec) -> Vec { + 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 new file mode 100644 index 0000000..0735fc7 --- /dev/null +++ b/other/longest_substring_no_repeat.cpp @@ -0,0 +1,29 @@ +#include "leetcode.h" + +class Solution { +public: + int lengthOfLongestSubstring(string s) { + if (s.size() == 0) + return 0; + map 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(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 new file mode 100644 index 0000000..87f07a6 --- /dev/null +++ b/other/longest_valid_course.cpp @@ -0,0 +1,49 @@ +// 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 longestObstacleCourseAtEachEachPosition(vector &obstacles) { + vector 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 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 new file mode 100644 index 0000000..953e8be --- /dev/null +++ b/other/longest_valid_parentheses.cpp @@ -0,0 +1,41 @@ +#include "leetcode.h" + +class Solution { +public: + int longestValidParentheses(string s) { + int n = s.size(), ans = 0; + stack 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 new file mode 100644 index 0000000..3be4538 --- /dev/null +++ b/other/longest_word_dict.cpp @@ -0,0 +1,31 @@ +#include "leetcode.h" + +class Solution { +public: + string findLongestWord(string s, vector &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 dictionary = {"ale", "apple", "monkey", "plea"}; + cout << obj.findLongestWord(s, dictionary); +} diff --git a/other/longest_zigzag_bt.cpp b/other/longest_zigzag_bt.cpp new file mode 100644 index 0000000..b0ebe7f --- /dev/null +++ b/other/longest_zigzag_bt.cpp @@ -0,0 +1,46 @@ +// 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, 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 new file mode 100644 index 0000000..ec99f32 --- /dev/null +++ b/other/lowest_common_ancestor.cpp @@ -0,0 +1,33 @@ +#include "leetcode.h" + +class Solution { +public: + TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) { + frame ans; + stack 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 subs; + }; +}; diff --git a/other/lowest_common_ancestor_bst.cpp b/other/lowest_common_ancestor_bst.cpp new file mode 100644 index 0000000..d496c2c --- /dev/null +++ b/other/lowest_common_ancestor_bst.cpp @@ -0,0 +1,17 @@ +#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 new file mode 100644 index 0000000..f8d1656 --- /dev/null +++ b/other/lru_cache.cpp @@ -0,0 +1,60 @@ +// 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 li; + typedef pair pii; + typedef unordered_map 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 new file mode 100644 index 0000000..8416deb --- /dev/null +++ b/other/magnetic_force_2_balls.cpp @@ -0,0 +1,46 @@ +// 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 &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 &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 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 new file mode 100644 index 0000000..482c0da --- /dev/null +++ b/other/make_array_increasing.cpp @@ -0,0 +1,59 @@ +// 1187. Make Array Strictly Increasing +#include +#include +#include +#include +#include +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 &arr1, vector &arr2, + vector> &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 &arr1, vector &arr2) { + sort(arr2.begin(), arr2.end()); + vector> dp(2001); + int val = check(0, INT_MIN, arr1, arr2, dp); + if (val == INT_MAX) + return -1; + return val; + } +}; + +int main() { + Solution obj; + vector a1123 = {1, 5, 3, 6, 7}; + vector 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 new file mode 100644 index 0000000..190bbed --- /dev/null +++ b/other/make_string_great.cpp @@ -0,0 +1,29 @@ +#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 new file mode 100644 index 0000000..76a28a2 --- /dev/null +++ b/other/make_string_great.rs @@ -0,0 +1,21 @@ +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, 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 new file mode 100644 index 0000000..993c955 --- /dev/null +++ b/other/make_sum_divisible_p.cpp @@ -0,0 +1,36 @@ +// 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 &nums, int p) { + int n = nums.size(), ans = n, req = 0, curr = 0; + for (auto i : nums) + req = (req + i) % p; + unordered_map 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 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 new file mode 100644 index 0000000..4640eb9 --- /dev/null +++ b/other/marbles_in_bags.cpp @@ -0,0 +1,48 @@ +// 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 &weights, int k) { + priority_queue pq1; + priority_queue, greater> 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 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 new file mode 100644 index 0000000..f2422b8 --- /dev/null +++ b/other/matchsticks_square.cpp @@ -0,0 +1,46 @@ +#include "leetcode.h" + +class Solution { +public: + bool makesquare(vector &matchsticks) { + sort(matchsticks.begin(), matchsticks.end(), greater()); + 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 &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 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 new file mode 100644 index 0000000..90e7fd5 --- /dev/null +++ b/other/matrix_diagonal_sum.cpp @@ -0,0 +1,33 @@ +// 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 new file mode 100644 index 0000000..bc8abeb --- /dev/null +++ b/other/max_69.cpp @@ -0,0 +1,21 @@ +#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 new file mode 100644 index 0000000..0bead97 --- /dev/null +++ b/other/max_69.rs @@ -0,0 +1,11 @@ +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 new file mode 100644 index 0000000..da1f745 --- /dev/null +++ b/other/max_area_cake.cpp @@ -0,0 +1,25 @@ +#include "leetcode.h" + +class Solution { +public: + int maxArea(int h, int w, vector &horizontalCuts, + vector &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 horizontalCuts = {1, 2, 4}; + vector verticalCuts = {1, 3}; + cout << obj.maxArea(h, w, horizontalCuts, verticalCuts); +} diff --git a/other/max_area_island.cpp b/other/max_area_island.cpp new file mode 100644 index 0000000..aad8b2d --- /dev/null +++ b/other/max_area_island.cpp @@ -0,0 +1,24 @@ +#include "leetcode.h" + +class Solution { +public: + int maxAreaOfIsland(vector> &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> &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 new file mode 100644 index 0000000..e9ebb25 --- /dev/null +++ b/other/max_average_pass_ration.cpp @@ -0,0 +1,57 @@ +// 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 a, pair 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> &classes, int extraStudents) { + double acc = 0; + priority_queue, vector>, cmp> pq; + for (vector i : classes) + pq.push(make_pair(i[0], i[1])); + while (extraStudents--) { + pair curr = pq.top(); + pq.pop(); + curr.first++; + curr.second++; + pq.push(curr); + } + while (!pq.empty()) { + pair 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 new file mode 100644 index 0000000..35c66bc --- /dev/null +++ b/other/max_bags_rocks.cpp @@ -0,0 +1,22 @@ +#include "leetcode.h" + +class Solution { +public: + int maximumBags(vector &capacity, vector &rocks, + int additionalRocks) { + vector 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 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 new file mode 100644 index 0000000..808c393 --- /dev/null +++ b/other/max_bags_rocks.rs @@ -0,0 +1,20 @@ +struct Solution; + +impl Solution { + pub fn maximum_bags(capacity: Vec, rocks: Vec, mut additional_rocks: i32) -> i32 { + let mut bag_space = (0..rocks.len()).map(|i| capacity[i] - rocks[i]) + .filter(|&d| d > 0) + .collect::>(); + 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 new file mode 100644 index 0000000..cff044f --- /dev/null +++ b/other/max_consecutive_ones3.cpp @@ -0,0 +1,27 @@ +#include "leetcode.h" + +class Solution { +public: + int longestOnes(vector &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 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 new file mode 100644 index 0000000..e5ecc10 --- /dev/null +++ b/other/max_depth_binary_tree.cpp @@ -0,0 +1,19 @@ +// 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 new file mode 100644 index 0000000..ab96947 --- /dev/null +++ b/other/max_diff_node_ancestor.cpp @@ -0,0 +1,22 @@ +#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 new file mode 100644 index 0000000..671bd27 --- /dev/null +++ b/other/max_diff_node_ancestor.rs @@ -0,0 +1,61 @@ +use std::cmp; +use std::rc::Rc; +use std::cell::RefCell; + +#[derive(Debug, PartialEq, Eq)] +pub struct TreeNode { + pub val: i32, + pub left: Option>>, + pub right: Option>> +} + +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>) -> 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>>) -> 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 new file mode 100644 index 0000000..a9203fe --- /dev/null +++ b/other/max_distance_closest_person.cpp @@ -0,0 +1,39 @@ +// 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 &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 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 new file mode 100644 index 0000000..dd72746 --- /dev/null +++ b/other/max_erasure_value.cpp @@ -0,0 +1,26 @@ +#include "leetcode.h" + +class Solution { +public: + int maximumUniqueSubarray(vector &nums) { + int ans = 0; + unordered_set 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 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 new file mode 100644 index 0000000..e391f87 --- /dev/null +++ b/other/max_ice_cream_bars.cpp @@ -0,0 +1,39 @@ +#include "leetcode.h" + +class Solution { +public: + int maxIceCream(vector &costs, int coins) { + int k = costs.size(); + vector dp(k + 1, -1); + sort(costs.begin(), costs.end()); + return dfs(dp, costs, coins, 0, k); + } + +private: + int dfs(vector &dp, vector &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 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 new file mode 100644 index 0000000..6691a3b --- /dev/null +++ b/other/max_ice_cream_bars.rs @@ -0,0 +1,27 @@ +struct Solution; + +impl Solution { + pub fn max_ice_cream(costs: Vec, 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 new file mode 100644 index 0000000..b364d26 --- /dev/null +++ b/other/max_len_concat_str.cpp @@ -0,0 +1,30 @@ +#include "leetcode.h" + +class Solution { +public: + int maxLength(vector &arr) { + int ans = 0; + vector> 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> 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 arr = {"un", "iq", "ue"}; + cout << obj.maxLength(arr); +} diff --git a/other/max_len_concat_str.rs b/other/max_len_concat_str.rs new file mode 100644 index 0000000..8ce0c2b --- /dev/null +++ b/other/max_len_concat_str.rs @@ -0,0 +1,29 @@ +struct Solution; + +impl Solution { + pub fn max_length(arr: Vec) -> i32 { + let mut ans: u32 = 0; + let mut unique: Vec = 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 = 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 new file mode 100644 index 0000000..c8ef536 --- /dev/null +++ b/other/max_length_pair_chain.cpp @@ -0,0 +1,33 @@ +// 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 &a, vector &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 new file mode 100644 index 0000000..6e8ef68 --- /dev/null +++ b/other/max_length_repeated_subarr.cpp @@ -0,0 +1,26 @@ +#include "leetcode.h" + +class Solution { +public: + int findLength(vector &nums1, vector &nums2) { + int m = nums1.size(), n = nums2.size(); + vvd dp(m + 1, vector(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 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 new file mode 100644 index 0000000..86b0e4c --- /dev/null +++ b/other/max_network_rank.cpp @@ -0,0 +1,44 @@ +// 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> 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 new file mode 100644 index 0000000..95c1563 --- /dev/null +++ b/other/max_num_events_attended2.cpp @@ -0,0 +1,46 @@ +// 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 &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(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 new file mode 100644 index 0000000..13c6980 --- /dev/null +++ b/other/max_num_ksum_pair.cpp @@ -0,0 +1,22 @@ +#include "leetcode.h" + +class Solution { +public: + int maxOperations(vector &nums, int k) { + unordered_map 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 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 new file mode 100644 index 0000000..370fdda --- /dev/null +++ b/other/max_num_tasks_assign.cpp @@ -0,0 +1,68 @@ +// 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 &tasks, vector &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 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 t1 = {3, 2, 1}, t2 = {5, 4}, t3 = {10, 15, 30}; + vector 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 new file mode 100644 index 0000000..fe24499 --- /dev/null +++ b/other/max_num_vowel_substr.cpp @@ -0,0 +1,30 @@ +// 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 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 new file mode 100644 index 0000000..a7e4be8 --- /dev/null +++ b/other/max_performance_team.cpp @@ -0,0 +1,33 @@ +#include "leetcode.h" + +class Solution { +public: + const int mod = 1e9 + 7; + int maxPerformance(int n, vector &speed, vector &efficiency, + int k) { + priority_queue, greater> pqvg; + vector> 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 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 new file mode 100644 index 0000000..23fc78e --- /dev/null +++ b/other/max_points_from_cards.cpp @@ -0,0 +1,23 @@ +#include "leetcode.h" + +class Solution { +public: + int maxScore(vector &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 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 new file mode 100644 index 0000000..3e34be4 --- /dev/null +++ b/other/max_points_line.cpp @@ -0,0 +1,50 @@ +#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 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 new file mode 100644 index 0000000..ee9c03d --- /dev/null +++ b/other/max_points_line.rs @@ -0,0 +1,91 @@ +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>) -> 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 = 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 new file mode 100644 index 0000000..1886bdb --- /dev/null +++ b/other/max_product_3num.cpp @@ -0,0 +1,40 @@ +// 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 &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 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 new file mode 100644 index 0000000..71fc9a4 --- /dev/null +++ b/other/max_product_split_bt.cpp @@ -0,0 +1,19 @@ +#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 new file mode 100644 index 0000000..6aec321 --- /dev/null +++ b/other/max_product_split_bt.rs @@ -0,0 +1,43 @@ +#[derive(Debug, PartialEq, Eq)] +pub struct TreeNode { + pub val: i32, + pub left: Option>>, + pub right: Option>>, +} + +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>>) -> 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>>, sums: &mut Vec) -> 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 new file mode 100644 index 0000000..e119ea1 --- /dev/null +++ b/other/max_product_word_len.cpp @@ -0,0 +1,31 @@ +#include "leetcode.h" + +class Solution { +public: + int maxProduct(vector &words) { + int n = words.size(), ans = 0; + vector> 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 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 new file mode 100644 index 0000000..811874b --- /dev/null +++ b/other/max_profit_job.cpp @@ -0,0 +1,28 @@ +#include "leetcode.h" + +class Solution { +public: + int jobScheduling(vector &startTime, vector &endTime, + vector &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 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 startTime = {1, 2, 3, 3}; + vector endTime = {3, 4, 5, 6}; + vector 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 new file mode 100644 index 0000000..fe1fafe --- /dev/null +++ b/other/max_profit_job.rs @@ -0,0 +1,30 @@ +struct Solution; + +impl Solution { + pub fn job_scheduling(start_time: Vec, end_time: Vec, profit: Vec) -> i32 { + let mut jobs: Vec = (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 new file mode 100644 index 0000000..e5a10b5 --- /dev/null +++ b/other/max_running_time_n_computer.cpp @@ -0,0 +1,35 @@ +// 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 &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 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 new file mode 100644 index 0000000..3c7bc89 --- /dev/null +++ b/other/max_score_good_subarr.cpp @@ -0,0 +1,36 @@ +// 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 &nums, int k) { + nums.push_back(0); + stack 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 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 new file mode 100644 index 0000000..7758a29 --- /dev/null +++ b/other/max_score_mult_opp.cpp @@ -0,0 +1,31 @@ +#include "leetcode.h" + +class Solution { +public: + int maximumScore(vector &nums, vector &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 &nums, vector &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 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 new file mode 100644 index 0000000..a2dc2b9 --- /dev/null +++ b/other/max_score_n_operations.cpp @@ -0,0 +1,59 @@ +// 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 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 &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 &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 n1 = {1, 2}; + vector n2 = {3, 4, 6, 8}; + vector 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 new file mode 100644 index 0000000..b4df5d5 --- /dev/null +++ b/other/max_score_node_sequence.cpp @@ -0,0 +1,43 @@ +#include "leetcode.h" + +class Solution { +public: + int maximumScore(vector &scores, vector> &edges) { + const int n = scores.size(); + vector> adj(n); + for (const vector &edge : edges) { + adj[edge[0]].push_back(edge[1]); + adj[edge[1]].push_back(edge[0]); + } + for (vector &a : adj) { + priority_queue, vector>, 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 &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 new file mode 100644 index 0000000..7356925 --- /dev/null +++ b/other/max_subarray.cpp @@ -0,0 +1,32 @@ +#include "leetcode.h" + +class Solution { +public: + int maxSubArray(vector &nums) { + return helper(nums, 0, nums.size() - 1); + } + +private: + int helper(vector &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 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 new file mode 100644 index 0000000..a739d77 --- /dev/null +++ b/other/max_subseq_score.cpp @@ -0,0 +1,47 @@ +// 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 &nums1, vector &nums2, int k) { + int n = nums1.size(); + vector> 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, greater> 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 n11 = {1, 3, 3, 2}, n21 = {2, 1, 3, 4}; + vector 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 new file mode 100644 index 0000000..c326ad3 --- /dev/null +++ b/other/max_sum_3_noverlap_subarr.cpp @@ -0,0 +1,57 @@ +// 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 maxSumOfThreeSubarrays(vector &nums, int k) { + int n = nums.size(), max_sum = 0; + vector 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 n1 = {1, 2, 1, 2, 6, 7, 5, 1}, n2 = {1, 2, 1, 2, 1, 2, 1, 2, 1}; + vector msots1 = obj.maxSumOfThreeSubarrays(n1, 2); + vector 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 new file mode 100644 index 0000000..64d1d20 --- /dev/null +++ b/other/max_sum_binary_tree.cpp @@ -0,0 +1,26 @@ +// 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 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 new file mode 100644 index 0000000..a86eafa --- /dev/null +++ b/other/max_sum_circular_subarr.cpp @@ -0,0 +1,49 @@ +// 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 &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::iterator p, vector::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 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 new file mode 100644 index 0000000..9b252e1 --- /dev/null +++ b/other/max_sum_rectangle.cpp @@ -0,0 +1,33 @@ +#include "leetcode.h" + +class Solution { +public: + int maxSumSubmatrix(vector> &matrix, int k) { + int ans = INT_MIN, rows = matrix.size(), cols = matrix[0].size(); + for (int l = 0; l < cols; ++l) { + vector 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 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 new file mode 100644 index 0000000..82380ab --- /dev/null +++ b/other/max_total_importance_road.cpp @@ -0,0 +1,34 @@ +// 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> &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 new file mode 100644 index 0000000..2f0e499 --- /dev/null +++ b/other/max_tranfer_requests.cpp @@ -0,0 +1,46 @@ +// 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 new file mode 100644 index 0000000..dd635e1 --- /dev/null +++ b/other/max_twin_sum_list.cpp @@ -0,0 +1,41 @@ +// 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 new file mode 100644 index 0000000..f95e777 --- /dev/null +++ b/other/max_units_truck.cpp @@ -0,0 +1,20 @@ +#include "leetcode.h" + +class Solution { +public: + int maximumUnits(vector> &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 &a, vector &b) { return a[1] > b[1]; } +}; diff --git a/other/max_val_k_coin_pile.cpp b/other/max_val_k_coin_pile.cpp new file mode 100644 index 0000000..6452a7b --- /dev/null +++ b/other/max_val_k_coin_pile.cpp @@ -0,0 +1,42 @@ +// 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 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 new file mode 100644 index 0000000..ee6c25f --- /dev/null +++ b/other/max_value_give_idx.cpp @@ -0,0 +1,43 @@ +// 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 new file mode 100644 index 0000000..3f69177 --- /dev/null +++ b/other/max_width_binary_tree.cpp @@ -0,0 +1,40 @@ +// 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> 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 new file mode 100644 index 0000000..0de5eaf --- /dev/null +++ b/other/maximise_confusion_exam.cpp @@ -0,0 +1,41 @@ +// 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 new file mode 100644 index 0000000..612c111 --- /dev/null +++ b/other/maximise_grid_happiness.cpp @@ -0,0 +1,66 @@ +// 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 new file mode 100644 index 0000000..6a98a38 --- /dev/null +++ b/other/merge_sorted_array.cpp @@ -0,0 +1,33 @@ +#include "leetcode.h" + +class Solution { +public: + void merge(vector &nums1, int m, vector &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 nums1 = {1, 2, 3, 0, 0, 0}; + vector 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 new file mode 100644 index 0000000..1e2704d --- /dev/null +++ b/other/merge_sorted_array.rs @@ -0,0 +1,14 @@ +struct Solution; + +impl Solution { + pub fn merge(nums1: &mut Vec, m: i32, nums2: &mut Vec, 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 new file mode 100644 index 0000000..d69c5fc --- /dev/null +++ b/other/merge_string_alt.cpp @@ -0,0 +1,32 @@ +// 1768. Merge Strings Alternately +#include +#include +#include + +/* + * 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 new file mode 100644 index 0000000..ba3a2a0 --- /dev/null +++ b/other/middle_linked_list.cpp @@ -0,0 +1,18 @@ +#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 new file mode 100644 index 0000000..ed84409 --- /dev/null +++ b/other/middle_linked_list.rs @@ -0,0 +1,28 @@ +#[derive(PartialEq, Eq, Clone, Debug)] +struct Solution; +pub struct ListNode { + pub val: i32, + pub next: Option> +} + +impl ListNode { + #[inline] + fn new(val: i32) -> Self { + ListNode { + next: None, + val + } + } +} + +impl Solution { + pub fn middle_node(head: Option>) -> Option> { + let mut curr = &head; + let mut node_vec: Vec>> = 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 new file mode 100644 index 0000000..0c0ef82 --- /dev/null +++ b/other/min_abs_diff_bst.cpp @@ -0,0 +1,27 @@ +// 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 new file mode 100644 index 0000000..07433d6 --- /dev/null +++ b/other/min_ascii_strs.cpp @@ -0,0 +1,38 @@ +// 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 new file mode 100644 index 0000000..4bbc2b1 --- /dev/null +++ b/other/min_avg_diff.cpp @@ -0,0 +1,27 @@ +#include "leetcode.h" + +class Solution { +public: + int minimumAverageDifference(vector &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 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 new file mode 100644 index 0000000..71c18aa --- /dev/null +++ b/other/min_avg_diff.rs @@ -0,0 +1,23 @@ +struct Solution; + +impl Solution { + pub fn minimum_average_difference(nums: Vec) -> i32 { + let (mut left, mut ans, mut min) = (0, 0, i64::MAX); + let mut right = nums.iter().map(|&x| x as i64).sum::(); + 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 new file mode 100644 index 0000000..3d2b95c --- /dev/null +++ b/other/min_cost_arr_equal.cpp @@ -0,0 +1,44 @@ +// 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 &nums, vector &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 &nums, vector &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 n1 = {1, 3, 5, 2}, c1 = {2, 3, 1, 14}; + vector 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 new file mode 100644 index 0000000..c75d10c --- /dev/null +++ b/other/min_cost_change_expr.cpp @@ -0,0 +1,40 @@ +#include "leetcode.h" + +class Solution { +public: + int minOperationsToFlip(string expression) { + vector>> vva(1); + for (auto ch : expression) { + if (ch == '(') + vva.push_back(vector>()); + 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 eval(vector> &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 new file mode 100644 index 0000000..3df886a --- /dev/null +++ b/other/min_cost_climbing_stairs.cpp @@ -0,0 +1,16 @@ +#include "leetcode.h" + +class Solution { +public: + int minCostClimbingStairs(vector &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 cost = {10, 15, 20}; + cout << obj.minCostClimbingStairs(cost); +} diff --git a/other/min_cost_convert_string1.cpp b/other/min_cost_convert_string1.cpp new file mode 100644 index 0000000..914eff9 --- /dev/null +++ b/other/min_cost_convert_string1.cpp @@ -0,0 +1,51 @@ +// 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 &original, + vector &changed, vector &cost) { + long long ans = 0; + vector> n(26, vector(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 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 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 new file mode 100644 index 0000000..5622868 --- /dev/null +++ b/other/min_cost_cut_stick.cpp @@ -0,0 +1,45 @@ +// 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 &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 &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 c1 = {1, 3, 4, 5}; + vector 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 new file mode 100644 index 0000000..1d00853 --- /dev/null +++ b/other/min_cost_ticket.cpp @@ -0,0 +1,42 @@ +// 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 &days, vector &costs) { + unordered_map tickets; + tickets[1] = costs[0]; + tickets[7] = costs[1]; + tickets[30] = costs[2]; + vector 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 d1 = {1, 4, 6, 7, 8, 20}, + d2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31}; + vector 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_deletions_unique_char.cpp b/other/min_deletions_unique_char.cpp new file mode 100644 index 0000000..c971b21 --- /dev/null +++ b/other/min_deletions_unique_char.cpp @@ -0,0 +1,28 @@ +#include "leetcode.h" + +class Solution { +public: + int minDeletions(string s) { + vector 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 new file mode 100644 index 0000000..7661fb2 --- /dev/null +++ b/other/min_depth_binary_tree.cpp @@ -0,0 +1,34 @@ +// 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 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 new file mode 100644 index 0000000..47099a6 --- /dev/null +++ b/other/min_deviation_arr.cpp @@ -0,0 +1,36 @@ +// 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 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 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 new file mode 100644 index 0000000..40fab6e --- /dev/null +++ b/other/min_difficulty_schedule.cpp @@ -0,0 +1,36 @@ +#include "leetcode.h" +#include +#include + +class Solution { +public: + int minDifficulty(vector &jobDifficulty, int d) { + int n = jobDifficulty.size(); + if (n < d) + return -1; + vector 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 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 new file mode 100644 index 0000000..5222628 --- /dev/null +++ b/other/min_dist_bst_node.cpp @@ -0,0 +1,20 @@ +// 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 new file mode 100644 index 0000000..662c5ec --- /dev/null +++ b/other/min_dist_target_element.cpp @@ -0,0 +1,20 @@ +#include "leetcode.h" + +class Solution { +public: + int getMinDistance(vector &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 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 new file mode 100644 index 0000000..3bc2940 --- /dev/null +++ b/other/min_falling_path_sum.cpp @@ -0,0 +1,45 @@ +#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(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 new file mode 100644 index 0000000..4b704c1 --- /dev/null +++ b/other/min_falling_path_sum.rs @@ -0,0 +1,23 @@ +struct Solution; + +impl Solution { + pub fn min_falling_path_sum(matrix: Vec>) -> 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 new file mode 100644 index 0000000..b51b261 --- /dev/null +++ b/other/min_flips_abc.cpp @@ -0,0 +1,22 @@ +// 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 new file mode 100644 index 0000000..4e3e2d6 --- /dev/null +++ b/other/min_fuel_report_captial.cpp @@ -0,0 +1,50 @@ +// 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 new file mode 100644 index 0000000..8bbf503 --- /dev/null +++ b/other/min_genetic_mutation.cpp @@ -0,0 +1,33 @@ +#include "leetcode.h" + +class Solution { +public: + int minMutation(string start, string end, vector &bank) { + deque> dqp({{start, 0}}); + set s(bank.begin(), bank.end()); + vector 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 bank = {"AACCGGTA"}; + cout << obj.minMutation(start, end, bank); +} diff --git a/other/min_genetic_mutation.rs b/other/min_genetic_mutation.rs new file mode 100644 index 0000000..1362636 --- /dev/null +++ b/other/min_genetic_mutation.rs @@ -0,0 +1,53 @@ +use std::collections::HashSet; +struct Solution; + +impl Solution { + pub fn min_mutation(start: String, end: String, mut bank: Vec) -> 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 new file mode 100644 index 0000000..9121d48 --- /dev/null +++ b/other/min_incr_arr_unique.cpp @@ -0,0 +1,32 @@ +// 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 &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 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 new file mode 100644 index 0000000..7af74da --- /dev/null +++ b/other/min_insertion_make_palindrome.cpp @@ -0,0 +1,32 @@ +// 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 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 new file mode 100644 index 0000000..7510c8c --- /dev/null +++ b/other/min_jump_reach_home.cpp @@ -0,0 +1,44 @@ +#include "leetcode.h" + +class Solution { +public: + int minimumJumps(vector &forbidden, int a, int b, int x) { + unordered_set f(forbidden.begin(), forbidden.end()); + vvd visited(2, vector(5000)); + queue> 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 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 new file mode 100644 index 0000000..6da3f2b --- /dev/null +++ b/other/min_max_array.cpp @@ -0,0 +1,43 @@ +// 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 &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 &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 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 new file mode 100644 index 0000000..ac6dc3b --- /dev/null +++ b/other/min_max_diff_pair.cpp @@ -0,0 +1,47 @@ +// 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 &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 &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 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 new file mode 100644 index 0000000..6455889 --- /dev/null +++ b/other/min_move_palindrome.cpp @@ -0,0 +1,34 @@ +// 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 new file mode 100644 index 0000000..e5fcfd0 --- /dev/null +++ b/other/min_moves_equal_array2.cpp @@ -0,0 +1,18 @@ +#include "leetcode.h" + +class Solution { +public: + int minMoves2(vector &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 nums = {1, 2, 3}; + cout << obj.minMoves2(nums); +} diff --git a/other/min_num_arrow_balloon.cpp b/other/min_num_arrow_balloon.cpp new file mode 100644 index 0000000..8c79da0 --- /dev/null +++ b/other/min_num_arrow_balloon.cpp @@ -0,0 +1,30 @@ +#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 &x, vector &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 new file mode 100644 index 0000000..6204bfe --- /dev/null +++ b/other/min_num_arrow_balloon.rs @@ -0,0 +1,20 @@ +struct Solution; + +impl Solution { + pub fn find_min_arrow_shots(mut points: Vec>) -> 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 new file mode 100644 index 0000000..ff54c44 --- /dev/null +++ b/other/min_num_days_disconnect_island.cpp @@ -0,0 +1,62 @@ +// 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> &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 dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1}; + void dfs(int x, int y, vector> &grid, vector> &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> &grid) { + int res = 0, n = grid.size(), m = grid[0].size(); + vector> vis(n, vector(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 new file mode 100644 index 0000000..5dcb40f --- /dev/null +++ b/other/min_num_opp_arr_cont.cpp @@ -0,0 +1,22 @@ +#include "leetcode.h" + +class Solution { +public: + int minOperations(vector &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 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 new file mode 100644 index 0000000..34d929b --- /dev/null +++ b/other/min_num_refueling_stops.cpp @@ -0,0 +1,22 @@ +#include "leetcode.h" + +class Solution { +public: + int minRefuelStops(int target, int startFuel, vector> &stations) { + int n = stations.size(), ans = 0; + priority_queue 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 new file mode 100644 index 0000000..007c8c6 --- /dev/null +++ b/other/min_num_remove_mountain_arr.cpp @@ -0,0 +1,51 @@ +// 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 &nums) { + int n = nums.size(); + vector 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 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 new file mode 100644 index 0000000..2d53fed --- /dev/null +++ b/other/min_num_vertices_node.cpp @@ -0,0 +1,34 @@ +// 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 findSmallestSetOfVertices(int n, vvd & edges) { + vector 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 new file mode 100644 index 0000000..9820ace --- /dev/null +++ b/other/min_one_bit_0.cpp @@ -0,0 +1,18 @@ +#include "leetcode.h" + +class Solution { +public: + unordered_map 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 new file mode 100644 index 0000000..1b52362 --- /dev/null +++ b/other/min_one_bit_0.rs @@ -0,0 +1,29 @@ +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 new file mode 100644 index 0000000..011839e --- /dev/null +++ b/other/min_operations_x_zero.cpp @@ -0,0 +1,27 @@ +#include "leetcode.h" + +class Solution { +public: + int minOperations(vector &nums, int x) { + unordered_map 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 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 new file mode 100644 index 0000000..46c2ff1 --- /dev/null +++ b/other/min_path_sum.cpp @@ -0,0 +1,29 @@ +// 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(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 new file mode 100644 index 0000000..0d78073 --- /dev/null +++ b/other/min_rounds_complete_all_tasks.cpp @@ -0,0 +1,27 @@ +#include "leetcode.h" + +class Solution { +public: + int minimumRounds(vector &tasks) { + unordered_map 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 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 new file mode 100644 index 0000000..1c9b7dd --- /dev/null +++ b/other/min_rounds_complete_all_tasks.rs @@ -0,0 +1,30 @@ +use std::collections::HashMap; +struct Solution; + +impl Solution { + pub fn minimum_rounds(tasks: Vec) -> 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 new file mode 100644 index 0000000..16f4c87 --- /dev/null +++ b/other/min_score_path_city.cpp @@ -0,0 +1,32 @@ +// 2492. Minimum Score of a Path Between Two Cities +#include "leetcode.h" + +class Solution { +public: + int minScore(int n, vvd & roads) { + unordered_map> graph; + for (auto r : roads) + graph[r[0]][r[1]] = graph[r[1]][r[0]] = r[2]; + unordered_set vis; + function 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 new file mode 100644 index 0000000..3e54b2b --- /dev/null +++ b/other/min_size_subarr_sum.cpp @@ -0,0 +1,32 @@ +// 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 &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 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 new file mode 100644 index 0000000..55cfa98 --- /dev/null +++ b/other/min_speed_arrive_time.cpp @@ -0,0 +1,47 @@ +// 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 &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 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 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 new file mode 100644 index 0000000..745c537 --- /dev/null +++ b/other/min_stack.cpp @@ -0,0 +1,23 @@ +#include "leetcode.h" + +class MinStack { +public: + stack 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 new file mode 100644 index 0000000..89ab5dd --- /dev/null +++ b/other/min_swap_group_1.cpp @@ -0,0 +1,40 @@ +// 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 &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 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 new file mode 100644 index 0000000..81d97d7 --- /dev/null +++ b/other/min_time_apples_tree.cpp @@ -0,0 +1,39 @@ +#include "leetcode.h" + +class Solution { +public: + int minTime(int n, vvd & edges, vector &hasApple) { + unordered_map 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 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 new file mode 100644 index 0000000..537e5cc --- /dev/null +++ b/other/min_time_apples_tree.rs @@ -0,0 +1,47 @@ +use std::collections::HashSet; +struct Solution; + +impl Solution { + pub fn min_time(n: i32, edges: Vec>, has_apple: Vec) -> i32 { + let mut adj_list: Vec> = 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 = HashSet::new(); + Self::dfs(0, adj_list, &mut vis, has_apple, &mut total); + total + } + fn dfs(node: i32, adj_list: Vec>, vis: &mut HashSet, + has_apple: Vec, 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 new file mode 100644 index 0000000..2e325a2 --- /dev/null +++ b/other/min_time_complete_trip.cpp @@ -0,0 +1,36 @@ +// 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 &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 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 new file mode 100644 index 0000000..9e34c1c --- /dev/null +++ b/other/min_time_rope_colorful.cpp @@ -0,0 +1,25 @@ +#include "leetcode.h" + +class Solution { +public: + int minCost(string colors, vector &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 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 new file mode 100644 index 0000000..58a0099 --- /dev/null +++ b/other/min_time_visit_cell_grid.cpp @@ -0,0 +1,52 @@ +// 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> &grid) { + if (grid[0][1] > 1 && grid[1][0] > 1) + return -1; + int m = grid.size(), n = grid[0].size(); + vector> dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + vector> vis(m, vector(n, false)); + priority_queue, vector>, 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 new file mode 100644 index 0000000..c529687 --- /dev/null +++ b/other/min_window_substring.cpp @@ -0,0 +1,37 @@ +#include "leetcode.h" + +class Solution { +public: + string minWindow(string s, string t) { + unordered_map 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 new file mode 100644 index 0000000..f23402b --- /dev/null +++ b/other/min_window_substring.rs @@ -0,0 +1,43 @@ +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 new file mode 100644 index 0000000..447ce5e --- /dev/null +++ b/other/mirror_reflection.cpp @@ -0,0 +1,21 @@ +#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 new file mode 100644 index 0000000..03dd331 --- /dev/null +++ b/other/missing_number.cpp @@ -0,0 +1,18 @@ +#include "leetcode.h" + +class Solution { +public: + int missingNumber(vector &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 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 new file mode 100644 index 0000000..289098f --- /dev/null +++ b/other/modify_graph_edge_weight.cpp @@ -0,0 +1,91 @@ +// 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 bfs(vector>> &adj, + vector> &edges, int source, int destination, + int target, bool modify) { + priority_queue, vector>, greater<>> pq; + vector 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> modifiedGraphEdges(int n, vector> &edges, + int source, int destination, + int target) { + vector>> 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 new file mode 100644 index 0000000..97499f8 --- /dev/null +++ b/other/most_stones_remove.cpp @@ -0,0 +1,47 @@ +// 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> &stones) { + int n = stones.size(), c = 0; + unordered_map> 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 seen; + function 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 new file mode 100644 index 0000000..d32137f --- /dev/null +++ b/other/most_stones_remove.rs @@ -0,0 +1,69 @@ +// 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>) -> i32 { + let mut ans = 0; + let mut parent: Vec = (0..stones.len()).collect(); + let mut rows: HashMap = HashMap::new(); + let mut cols: HashMap = 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) -> 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 { + 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 new file mode 100644 index 0000000..89d4e19 --- /dev/null +++ b/other/most_water.cpp @@ -0,0 +1,21 @@ +#include +using namespace std; + +class Solution { +public: + int maxArea(vector &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 new file mode 100644 index 0000000..472884e --- /dev/null +++ b/other/my_calendar.cpp @@ -0,0 +1,31 @@ +// 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> books; + +public: + bool book(int start, int end) { + for (pair 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 new file mode 100644 index 0000000..2012a35 --- /dev/null +++ b/other/my_calendar2.cpp @@ -0,0 +1,56 @@ +// 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> books; + +public: + bool book(int start, int end) { + for (pair p : books) + if (max(p.first, start) < min(end, p.second)) + return false; + books.push_back({start, end}); + return true; + } +}; + +class MyCalendarTwo { + vector> books; + +public: + bool book(int start, int end) { + MyCalendar overlaps; + for (pair p : books) + if (max(p.first, start) < min(end, p.second)) { + pair 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 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 new file mode 100644 index 0000000..25de075 --- /dev/null +++ b/other/my_calendar3.cpp @@ -0,0 +1,21 @@ +#include "leetcode.h" + +class MyCalendarThree { +public: + map 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 new file mode 100644 index 0000000..9c89682 --- /dev/null +++ b/other/n_ary_tree_traverse.cpp @@ -0,0 +1,25 @@ +#include "leetcode.h" + +class Solution { +public: + vvd levelOrder(Node *root) { + vvd ans; + if (!root) + return ans; + queue q; + q.push(root); + while (!q.empty()) { + int n = q.size(); + vector 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 new file mode 100644 index 0000000..2af1bcd --- /dev/null +++ b/other/n_queens2.cpp @@ -0,0 +1,35 @@ +#include "leetcode.h" + +class Solution { +public: + int totalNQueens(int n) { + vector col(n, true); + vector anti(2 * n - 1, true); + vector main(2 * n - 1, true); + vector row(n, 0); + int count = 0; + helper(0, row, col, main, anti, count); + return count; + } + +private: + void helper(int i, vector &row, vector &col, vector &main, + vector &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 new file mode 100644 index 0000000..24de89f --- /dev/null +++ b/other/naming_company.cpp @@ -0,0 +1,37 @@ +// 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 &ideas) { + long long ans = 0, cnt[26][26] = {}; + unordered_set 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 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 new file mode 100644 index 0000000..2e0a4cf --- /dev/null +++ b/other/nearest_exit_maze.cpp @@ -0,0 +1,37 @@ +#include "leetcode.h" + +class Solution { +public: + int nearestExit(vvd(char) & maze, vector &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> 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 entrance = {1, 2}; + cout << obj.nearestExit(maze, entrance); +} diff --git a/other/nearest_exit_maze.rs b/other/nearest_exit_maze.rs new file mode 100644 index 0000000..3f314f2 --- /dev/null +++ b/other/nearest_exit_maze.rs @@ -0,0 +1,37 @@ +use std::collections::VecDeque; +use std::collections::HashSet; +struct Solution; + +impl Solution { + pub fn nearest_exit(maze: Vec>, entrance: Vec) -> 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 new file mode 100644 index 0000000..dc21609 --- /dev/null +++ b/other/new_21_game.cpp @@ -0,0 +1,40 @@ +// 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 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 new file mode 100644 index 0000000..c6a8412 --- /dev/null +++ b/other/next_greater_element2.cpp @@ -0,0 +1,43 @@ +// 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 nextGreatestElements(vector &nums) { + int n = nums.size(); + nums.resize(n * 2); + for (int i = n; i < n * 2; i++) + nums[i] = nums[i - n]; + vector ans(n, -1); + stack 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 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 new file mode 100644 index 0000000..95e70f4 --- /dev/null +++ b/other/next_permutation.cpp @@ -0,0 +1,37 @@ +#include +#include +using namespace std; + +class Solution { +public: + void nextPermutation(vector &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 &nums, int start) { + int i = start, j = nums.size() - 1; + while (i < j) { + swap(nums, i, j); + i++; + j--; + } + } + + void swap(vector &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 new file mode 100644 index 0000000..6ea4280 --- /dev/null +++ b/other/non_decreasing_array.cpp @@ -0,0 +1,27 @@ +#include "leetcode.h" + +class Solution { +public: + bool checkPossibility(vector &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 nums = {4, 2, 3}; + cout << obj.checkPossibility(nums); +} diff --git a/other/non_decreasing_subseq.cpp b/other/non_decreasing_subseq.cpp new file mode 100644 index 0000000..b94510f --- /dev/null +++ b/other/non_decreasing_subseq.cpp @@ -0,0 +1,46 @@ +// 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> findSubsequences(vector &nums) { + set> seqs = {vector(0)}; + for (int i = 0; i < nums.size(); i++) { + vector> 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> ans; + for (auto s : seqs) + if (s.size() > 1) + ans.push_back(s); + return ans; + } +}; + +int main() { + Solution obj; + vector 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 new file mode 100644 index 0000000..228f691 --- /dev/null +++ b/other/non_overlapping_interval.cpp @@ -0,0 +1,38 @@ +// 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 &a, vector &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 prev = intervals[0]; + for (vector 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 new file mode 100644 index 0000000..cabdb39 --- /dev/null +++ b/other/nth_tribonacci_number.cpp @@ -0,0 +1,61 @@ +// 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 new file mode 100644 index 0000000..144e6ef --- /dev/null +++ b/other/num_bad_pairs.cpp @@ -0,0 +1,28 @@ +// 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 &nums) { + long long ans = 0; + unordered_map 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 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 new file mode 100644 index 0000000..88119d8 --- /dev/null +++ b/other/num_bad_pairs.rs @@ -0,0 +1,30 @@ +// 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) -> i64 { + let mut hm: HashMap = 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 new file mode 100644 index 0000000..ba0635c --- /dev/null +++ b/other/num_closed_islands.cpp @@ -0,0 +1,61 @@ +// 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 new file mode 100644 index 0000000..526e21d --- /dev/null +++ b/other/num_cut_pizza.cpp @@ -0,0 +1,58 @@ +// 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 &pizza, int k) { + int m = pizza.size(), n = pizza[0].size(); + vvd cnt(m + 1, vector(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) dp(m + 1, vvd(long)(n + 1, vector(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 p1 = {"A..", "AAA", "..."}; + vector p2 = {"A..", "AA.", "..."}; + vector 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 new file mode 100644 index 0000000..abb7596 --- /dev/null +++ b/other/num_dice_roll_target_sum.cpp @@ -0,0 +1,21 @@ +#include "leetcode.h" + +class Solution { +public: + int numRollsToTarget(int n, int k, int target) { + int mod = 1000000007; + vvd dp(n + 1, vector(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 new file mode 100644 index 0000000..2629d65 --- /dev/null +++ b/other/num_enclaves.cpp @@ -0,0 +1,45 @@ +// 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 new file mode 100644 index 0000000..1513c72 --- /dev/null +++ b/other/num_even_nums.cpp @@ -0,0 +1,29 @@ +#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 &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 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 new file mode 100644 index 0000000..79fae31 --- /dev/null +++ b/other/num_good_path.cpp @@ -0,0 +1,75 @@ +#include "leetcode.h" + +class UnionFind { +private: + vector id, rank; + int cnt; + +public: + UnionFind(int cnt) : cnt(cnt) { + id = vector(cnt); + rank = vector(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 &vals, vvd & edges) { + int n = vals.size(), goodPaths = 0; + vvd adj(n); + map> 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 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 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 new file mode 100644 index 0000000..4f60d46 --- /dev/null +++ b/other/num_increasing_path.cpp @@ -0,0 +1,54 @@ +// 2328. Number of Increasing Paths in a Grid +#include +#include +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> &grid, int i, int j, vector> &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> &grid) { + int m = grid.size(), n = grid[0].size(), ans = 0; + if (m == 1 && n == 1) + return 1; + vector> dp(m, vector(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> 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 new file mode 100644 index 0000000..bf6529b --- /dev/null +++ b/other/num_longest_incr_subseq.cpp @@ -0,0 +1,53 @@ +// 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 &nums) { + if (nums.empty()) + return 0; + vector>> 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 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 new file mode 100644 index 0000000..a97d464 --- /dev/null +++ b/other/num_matching_subsequence.cpp @@ -0,0 +1,34 @@ +#include "leetcode.h" + +class Solution { +public: + int numMatchingSubseq(string s, vector &words) { + int ans = 0; + unordered_map 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 words = {"a", "bb", "acd", "ace"}; + cout << obj.numMatchingSubseq(s, words); +} diff --git a/other/num_music_playlists.cpp b/other/num_music_playlists.cpp new file mode 100644 index 0000000..78cad3c --- /dev/null +++ b/other/num_music_playlists.cpp @@ -0,0 +1,40 @@ +// 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(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 new file mode 100644 index 0000000..4edb9ad --- /dev/null +++ b/other/num_nodes_sub_tree.cpp @@ -0,0 +1,47 @@ +#include "leetcode.h" + +class Solution { +public: + vector countSubTrees(int n, vvd & edges, string labels) { + vector 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 &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 new file mode 100644 index 0000000..ca52f7b --- /dev/null +++ b/other/num_nodes_sub_tree.rs @@ -0,0 +1,39 @@ +use std::collections::{HashMap, HashSet}; +struct Solution; + +impl Solution { + pub fn count_sub_trees(n: i32, edges: Vec>, labels: String) -> Vec { + let mut map = HashMap::>::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::::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>, labels: &str, + x: usize, visited: &mut HashSet, ans: &mut Vec) -> [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 new file mode 100644 index 0000000..2a9e2e4 --- /dev/null +++ b/other/num_op_connect_network.cpp @@ -0,0 +1,41 @@ +// 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 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 &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 new file mode 100644 index 0000000..80a4b91 --- /dev/null +++ b/other/num_people_aware_secret.cpp @@ -0,0 +1,27 @@ +#include "leetcode.h" + +class Solution { +public: + int peopleAwareOfSecret(int n, int delay, int forget) { + long long sharing = 0, mod = 1000000007; + deque 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 new file mode 100644 index 0000000..0602ce1 --- /dev/null +++ b/other/num_same_consecutive_diff.cpp @@ -0,0 +1,32 @@ +#include "leetcode.h" + +class Solution { +public: + vector numsSameConsecDiff(int n, int k) { + vector 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 &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 new file mode 100644 index 0000000..49b3ed3 --- /dev/null +++ b/other/num_smaller_num_self.cpp @@ -0,0 +1,44 @@ +#include "leetcode.h" + +class Solution { +public: + vector countSmaller(vector &nums) { + int n = nums.size(); + vector> vp(n); + vector 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 &count, vector> &vp, int left, int mid, + int right) { + vector> 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 &count, vector> &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 new file mode 100644 index 0000000..a7fc481 --- /dev/null +++ b/other/num_squareful_arrays.cpp @@ -0,0 +1,59 @@ +// 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 &nums) { + int n = nums.size(), cnt = 1; + sort(nums.begin(), nums.end()); + vector 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(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 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 new file mode 100644 index 0000000..6eb1a12 --- /dev/null +++ b/other/num_subseq_satisfy.cpp @@ -0,0 +1,34 @@ +// 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 &nums, int target) { + int ans = 0, mod = 1000000007; + vector 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 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 new file mode 100644 index 0000000..81470fd --- /dev/null +++ b/other/num_to_hex_binary.cpp @@ -0,0 +1,55 @@ +#include "leetcode.h" +#include + +/* + * 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 new file mode 100644 index 0000000..9286280 --- /dev/null +++ b/other/num_valid_words_puzzle.cpp @@ -0,0 +1,40 @@ +#include "leetcode.h" + +class Solution { +public: + vector findNumOfValidWords(vector &words, + vector &puzzles) { + unordered_map um; + for (auto w : words) + um[(mask(w))]++; + vector 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 words = {"aaaa", "asas", "able", "ability", + "actt", "actor", "access"}; + vector puzzles = {"aboveyz", "abrodyz", "abslute", + "absoryz", "actresz", "gaswxyz"}; + for (const auto &i : obj.findNumOfValidWords(words, puzzles)) + cout << i << endl; +} diff --git a/other/num_ways_dict.cpp b/other/num_ways_dict.cpp new file mode 100644 index 0000000..582c2f9 --- /dev/null +++ b/other/num_ways_dict.cpp @@ -0,0 +1,35 @@ +// 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 &words, string target) { + int n = target.length(), mod = 1e9 + 7; + vector ans(n + 1); + ans[0] = 1; + for (int i = 0; i < words[0].length(); ++i) { + vector 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 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 new file mode 100644 index 0000000..eee14e5 --- /dev/null +++ b/other/num_ways_remain_place.cpp @@ -0,0 +1,32 @@ +// 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 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 new file mode 100644 index 0000000..9adcb55 --- /dev/null +++ b/other/num_ways_reorder_array.cpp @@ -0,0 +1,57 @@ +// 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 &nums) { + if (nums.size() < 3) + return 1; + vector 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 &nums) { return dfs(nums) - 1; } +}; + +int main() { + Solution obj; + vector 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 new file mode 100644 index 0000000..06fa2db --- /dev/null +++ b/other/num_weak_char_game.cpp @@ -0,0 +1,23 @@ +#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 &a, vector &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 new file mode 100644 index 0000000..8ba45f3 --- /dev/null +++ b/other/num_zero_filled_subarr.cpp @@ -0,0 +1,29 @@ +// 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 &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 n1 = {1, 3, 0, 0, 2, 0, 0, 4}; + vector n2 = {0, 0, 0, 2, 0, 0}; + vector 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 new file mode 100644 index 0000000..c8e0ac3 --- /dev/null +++ b/other/number_1bits.cpp @@ -0,0 +1,20 @@ +#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 new file mode 100644 index 0000000..2f05d3f --- /dev/null +++ b/other/number_atoms.cpp @@ -0,0 +1,75 @@ +// 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 cnts = parse_formula(formula, i); + for (pair p : cnts) { + ans += p.first; + if (p.second > 1) + ans += to_string(p.second); + } + return ans; + } + +private: + map parse_formula(string &s, int &i) { + map cnts; + const int n = s.size(); + while (i < n && s[i] != ')') { + map cnt = parse_unit(s, i); + merge(cnts, cnt, 1); + } + return cnts; + } + map parse_unit(string &s, int &i) { + map cnts; + const int n = s.size(); + if (s[i] == '(') { + map 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 &cnts, map &cnt, int times) { + for (pair 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 new file mode 100644 index 0000000..96b8e0b --- /dev/null +++ b/other/number_islands.cpp @@ -0,0 +1,30 @@ +#include "leetcode.h" + +class Solution { +public: + int numIslands(vector> &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> &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 new file mode 100644 index 0000000..2f733f9 --- /dev/null +++ b/other/number_provinces.cpp @@ -0,0 +1,41 @@ +// 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 &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 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 new file mode 100644 index 0000000..2683dca --- /dev/null +++ b/other/number_steps_to_0.cpp @@ -0,0 +1,20 @@ +#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 new file mode 100644 index 0000000..db5a84f --- /dev/null +++ b/other/number_submatrices_sum_target.cpp @@ -0,0 +1,24 @@ +#include "leetcode.h" + +class Solution { +public: + int numSubmatrixSumTarget(vector> &matrix, int target) { + int xLen = matrix[0].size(), yLen = matrix.size(), ans = 0; + unordered_map 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 new file mode 100644 index 0000000..4ee4bac --- /dev/null +++ b/other/odd_even_linke_list.cpp @@ -0,0 +1,22 @@ +#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 new file mode 100644 index 0000000..89e96c1 --- /dev/null +++ b/other/odd_even_linke_list.rs @@ -0,0 +1,38 @@ +#[derive(PartialEq, Eq, Clone, Debug)] +pub struct ListNode { + pub val: i32, + pub next: Option> +} + +impl ListNode { + #[inline] + fn new(val: i32) -> Self { + ListNode { + next: None, + val + } + } +} + +impl Solution { + pub fn odd_even_list(mut head: Option>) -> Option> { + 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 new file mode 100644 index 0000000..851f1e8 --- /dev/null +++ b/other/ones_and_zeroes.cpp @@ -0,0 +1,36 @@ +#include "leetcode.h" +#include + +class Solution { +public: + int findMaxForm(vector &strs, int m, int n) { + vector> 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> &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 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 new file mode 100644 index 0000000..340f32e --- /dev/null +++ b/other/online_stock_span.cpp @@ -0,0 +1,43 @@ +// 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> 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 new file mode 100644 index 0000000..a967028 --- /dev/null +++ b/other/online_stock_span.rs @@ -0,0 +1,51 @@ +// 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, +} + +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 new file mode 100644 index 0000000..e39bd62 --- /dev/null +++ b/other/optimal_partition_string.cpp @@ -0,0 +1,31 @@ +// 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 new file mode 100644 index 0000000..23053d2 --- /dev/null +++ b/other/orderly_queue.cpp @@ -0,0 +1,20 @@ +#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 new file mode 100644 index 0000000..0931d7b --- /dev/null +++ b/other/orderly_queue.rs @@ -0,0 +1,22 @@ +struct Solution; + +impl Solution { + pub fn orderly_queue(s: String, k: i32) -> String { + if k == 1 { + let ss = s.chars().chain(s.chars()).collect::>(); + let mut v = ss.windows(s.len()).collect::>(); + v.sort(); + v[0].iter().copied().collect() + } else { + let mut v = s.chars().collect::>(); + 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 new file mode 100644 index 0000000..af5ce3f --- /dev/null +++ b/other/out_of_bounds_paths.cpp @@ -0,0 +1,35 @@ +#include "leetcode.h" + +class Solution { +public: + int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { + if (!maxMove) + return 0; + vector> curr(m + 2, vector(n + 2)); + vector> last(m + 2, vector(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 new file mode 100644 index 0000000..8876d9f --- /dev/null +++ b/other/pacific_atlantic_water_flow.cpp @@ -0,0 +1,38 @@ +#include "leetcode.h" + +class Solution { +public: + vvd pacificAtlantic(vvd & heights) { + n = heights.size(); + m = heights[0].size(); + vvd(bool) flag1(n, vector(m)), flag2(n, vector(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 new file mode 100644 index 0000000..1185109 --- /dev/null +++ b/other/paint_house3.cpp @@ -0,0 +1,34 @@ +#include "leetcode.h" + +class Solution { +public: + int minCost(vector &houses, vector> &cost, int m, int n, + int target) { + int INF = 1000000; + vector>> dp( + m, vector>(target + 1, vector(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 new file mode 100644 index 0000000..11fb014 --- /dev/null +++ b/other/painting_grid_three_colour.cpp @@ -0,0 +1,58 @@ +// 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 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 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 &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 new file mode 100644 index 0000000..5f70012 --- /dev/null +++ b/other/painting_walls.cpp @@ -0,0 +1,50 @@ +// 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 &cost, vector &time) { + this->n = cost.size(); + vvd memo(n, vector(n + 1)); + this->cost = cost; + this->time = time; + return dfs(0, n, memo); + } + +private: + int memo[501][501]; + vector cost; + vector 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 c1 = {1, 2, 3, 2}, c2 = {2, 3, 4, 2}; + vector 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 new file mode 100644 index 0000000..255b4a0 --- /dev/null +++ b/other/pairs_spells_potions.cpp @@ -0,0 +1,45 @@ +// 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 successfulPairs(vector &spells, vector &potions, + long long success) { + int m = potions.size(); + vector 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 s1 = {5, 1, 3}, s2 = {3, 1, 2}; + vector 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 new file mode 100644 index 0000000..1b08a0c --- /dev/null +++ b/other/palindrome_linked_list.cpp @@ -0,0 +1,32 @@ +#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 new file mode 100644 index 0000000..bd3c641 --- /dev/null +++ b/other/palindrome_number.rs @@ -0,0 +1,24 @@ +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 new file mode 100644 index 0000000..8048069 --- /dev/null +++ b/other/palindrome_pairs.cpp @@ -0,0 +1,38 @@ +#include "leetcode.h" + +class Solution { +public: + vvd palindromePairs(vector &words) { + unordered_map 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 new file mode 100644 index 0000000..6a49703 --- /dev/null +++ b/other/palindrome_partitioning.cpp @@ -0,0 +1,50 @@ +// 131. Palindrome Partitioning +#include "leetcode.h" +#include + +/* + * 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 path; + dfs(0, s, path, ans); + return ans; + } + +private: + void dfs(int idx, string &s, vector &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 new file mode 100644 index 0000000..70e50e3 --- /dev/null +++ b/other/parallel_courses3.cpp @@ -0,0 +1,54 @@ +// 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 &time) { + vector 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 finish_time(n + 1); + queue 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 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 new file mode 100644 index 0000000..98efe07 --- /dev/null +++ b/other/partition_array_max_sum.cpp @@ -0,0 +1,36 @@ +// 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 &arr, int k) { + int n = arr.size(); + vector 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 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 new file mode 100644 index 0000000..8a126da --- /dev/null +++ b/other/partition_array_pivot.rs @@ -0,0 +1,32 @@ +struct Solution; + +impl Solution { + pub fn pivot_array(nums: Vec, pivot: i32) -> Vec { + 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 new file mode 100644 index 0000000..b2e44a9 --- /dev/null +++ b/other/partition_list.cpp @@ -0,0 +1,20 @@ +#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 new file mode 100644 index 0000000..8cec267 --- /dev/null +++ b/other/partition_min_binary_array.cpp @@ -0,0 +1,18 @@ +#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 new file mode 100644 index 0000000..343c116 --- /dev/null +++ b/other/pascals_triangle.cpp @@ -0,0 +1,19 @@ +#include "leetcode.h" + +class Solution { +public: + vector> generate(int numRows) { + vector> ans(numRows); + for (int i = 0; i < numRows; i++) { + vector 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 new file mode 100644 index 0000000..467829e --- /dev/null +++ b/other/path_max_probability.cpp @@ -0,0 +1,52 @@ +// 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 &succ_prob, + int start, int end) { + vector>> 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 seen(n, 0); + priority_queue> pqp; + pqp.push({(double)1.0, start}); + vector 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 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 new file mode 100644 index 0000000..0b93590 --- /dev/null +++ b/other/path_min_effort.cpp @@ -0,0 +1,34 @@ +#include "leetcode.h" + +class Solution { +public: + int minimumEffortPath(vector> &heights) { + int m = heights.size(), n = heights[0].size(); + int dirs[5] = {-1, 0, 1, 0, -1}; + vector> efforts(m, vector(n, INT_MAX)); + priority_queue, vector>, + greater>> + 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 new file mode 100644 index 0000000..d9066cd --- /dev/null +++ b/other/path_min_effort1.cpp @@ -0,0 +1,42 @@ +#include "leetcode.h" +#include +#include +#include +#include +#include +#include + +class Solution { + const int d4x[4] = {-1, 0, 1, 0}, d4y[4] = {0, 1, 0, -1}; + +public: + int minimumEffortPath(vector> &heights) { + int n = heights.size(), m = heights[0].size(); + priority_queue, vector>, + greater>> + pq; + vector> dis(n, vector(m, INT_MAX)); + dis[0][0] = 0; + pq.push({0, {0, 0}}); + while (!pq.empty()) { + pair> 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 new file mode 100644 index 0000000..41498ca --- /dev/null +++ b/other/path_sum.cpp @@ -0,0 +1,23 @@ +#include "leetcode.h" + +class Solution { +public: + bool hasPathSum(TreeNode *root, int targetSum) { + if (root == NULL) + return false; + stack> 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 new file mode 100644 index 0000000..3ccfc65 --- /dev/null +++ b/other/path_sum2.cpp @@ -0,0 +1,25 @@ +#include "leetcode.h" + +class Solution { +public: + vvd pathSum(TreeNode *root, int targetSum) { + vvd ans; + vector d; + dfs(root, targetSum, d, ans); + return ans; + } + +private: + void dfs(TreeNode *root, int targetSum, vector 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 new file mode 100644 index 0000000..2900091 --- /dev/null +++ b/other/peak_idx_mountain_arr.cpp @@ -0,0 +1,25 @@ +// 852. Peak Index in a Mountain Array +#include "leetcode.h" + +class Solution { +public: + int peakIndexInMountainArray(vector &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 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 new file mode 100644 index 0000000..1c4d0b9 --- /dev/null +++ b/other/peeking_iterator.cpp @@ -0,0 +1,32 @@ +#include "leetcode.h" + +class Iterator { + struct Data; + Data *data; + +public: + Iterator(const vector &nums); + Iterator(const Iterator &iter); + int next(); + bool hasNext() const; +}; + +class PeekingIterator : public Iterator { +public: + int nextVal; + PeekingIterator(const vector &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 new file mode 100644 index 0000000..18744ea --- /dev/null +++ b/other/percentage_letter_string.cpp @@ -0,0 +1,20 @@ +#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 new file mode 100644 index 0000000..677c4a0 --- /dev/null +++ b/other/perfect_squares.cpp @@ -0,0 +1,23 @@ +#include "leetcode.h" + +class Solution { +public: + int numSquares(int n) { + vector 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 new file mode 100644 index 0000000..3887e40 --- /dev/null +++ b/other/perfect_squares.rs @@ -0,0 +1,21 @@ +use std::cmp::min; +struct Solution; + +impl Solution { + pub fn num_squares(n: i32) -> i32 { + let mut dp: Vec = 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 new file mode 100644 index 0000000..f4e09f3 --- /dev/null +++ b/other/permutation_in_string.cpp @@ -0,0 +1,47 @@ +// 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 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 a, vector 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 new file mode 100644 index 0000000..a77286b --- /dev/null +++ b/other/permutation_sequence.cpp @@ -0,0 +1,25 @@ +#include "leetcode.h" +#include + +class Solution { +public: + vector fact; + string getPermutation(int n, int k) { int n = k - 1; } + +private: + void helper(int k) { + fact = vector(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 new file mode 100644 index 0000000..2e86fc0 --- /dev/null +++ b/other/permutations.cpp @@ -0,0 +1,26 @@ +#include "leetcode.h" + +class Solution { +public: + vector> permute(vector &nums) { + vector> ans; + int idx = 0; + helper(nums, ans, idx); + return ans; + } + +private: + void helper(vector &nums, vector> &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 new file mode 100644 index 0000000..16d0162 --- /dev/null +++ b/other/permutations2.cpp @@ -0,0 +1,29 @@ +#include "leetcode.h" + +class Solution { +public: + vector> permuteUnique(vector &nums) { + vector> ans; + helper(0, nums, ans); + return ans; + } + +private: + void helper(int i, vector &nums, vector> &ans) { + if (i == nums.size()) { + ans.emplace_back(nums); + return; + } + unordered_set 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 new file mode 100644 index 0000000..7455583 --- /dev/null +++ b/other/poor-pigs.cpp @@ -0,0 +1,8 @@ +#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 new file mode 100644 index 0000000..6dd4175 --- /dev/null +++ b/other/possible_bipartition.cpp @@ -0,0 +1,45 @@ +#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> dislikeTable; + unordered_map colorTable; + function 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 new file mode 100644 index 0000000..13b8cf5 --- /dev/null +++ b/other/possible_bipartition.rs @@ -0,0 +1,40 @@ +use std::collections::VecDeque; +struct Solution; + +impl Solution { + pub fn possible_bipartition(n: i32, dislikes: Vec>) -> bool { + let mut dmap: Vec> = 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> = 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 new file mode 100644 index 0000000..f92e6e3 --- /dev/null +++ b/other/power_3.cpp @@ -0,0 +1,19 @@ +#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 new file mode 100644 index 0000000..ecf6de0 --- /dev/null +++ b/other/power_of_four.cpp @@ -0,0 +1,24 @@ +#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 new file mode 100644 index 0000000..f20335f --- /dev/null +++ b/other/power_of_four.rs @@ -0,0 +1,24 @@ +//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 new file mode 100644 index 0000000..7e38aeb --- /dev/null +++ b/other/power_of_two.cpp @@ -0,0 +1,11 @@ +#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 new file mode 100644 index 0000000..edf9ee3 --- /dev/null +++ b/other/predict_winner.cpp @@ -0,0 +1,40 @@ +// 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 &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 &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 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 new file mode 100644 index 0000000..67d4d4f --- /dev/null +++ b/other/prefix_suffix_search.cpp @@ -0,0 +1,26 @@ +#include "leetcode.h" + +class WordFilter { +public: + WordFilter(vector &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 hashMap; +}; diff --git a/other/profitable_schemes.cpp b/other/profitable_schemes.cpp new file mode 100644 index 0000000..d0f353a --- /dev/null +++ b/other/profitable_schemes.cpp @@ -0,0 +1,71 @@ +// 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 group; + vector profit; +}; + +class Solution { + vector 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 &group, + vector &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 new file mode 100644 index 0000000..63b2cac --- /dev/null +++ b/other/pseudo_palindrome_binary_tree.cpp @@ -0,0 +1,29 @@ +#include "leetcode.h" + +class Solution { +public: + int pseudoPalindromicPaths(TreeNode *root) { + vector v(10, 0); + dfs(root, v); + return count; + } + +private: + int count = 0; + void dfs(TreeNode *root, vector 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 new file mode 100644 index 0000000..859dad9 --- /dev/null +++ b/other/push_dominoes.cpp @@ -0,0 +1,31 @@ +#include "leetcode.h" +#include + +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 new file mode 100644 index 0000000..17ea0ea --- /dev/null +++ b/other/queue_reconstruction.cpp @@ -0,0 +1,20 @@ +#include "leetcode.h" + +class Solution { +public: + vector> reconstructQueue(vector> &people) { + sort(people.begin(), people.end(), cmp); + vector> 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 &p1, vector &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 new file mode 100644 index 0000000..046aee2 --- /dev/null +++ b/other/range_sum_bst.cpp @@ -0,0 +1,22 @@ +#include "leetcode.h" + +class Solution { +public: + int rangeSumBST(TreeNode *root, int low, int high) { + queue 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 new file mode 100644 index 0000000..f793202 --- /dev/null +++ b/other/range_sum_bst.rs @@ -0,0 +1,38 @@ +#[derive(Debug, PartialEq, Eq)] +pub struct TreeNode { + pub val: i32, + pub left: Option>>, + pub right: Option>> +} + +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>>, 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 new file mode 100644 index 0000000..9c77900 --- /dev/null +++ b/other/range_sum_query_2d.cpp @@ -0,0 +1,40 @@ +// 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> sum; + NumMatrix(vector> &matrix) { + int m = matrix.size(), n = matrix[0].size(); + sum = vector>(m + 1, vector(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 new file mode 100644 index 0000000..cdc0230 --- /dev/null +++ b/other/range_sum_query_mutable.cpp @@ -0,0 +1,61 @@ +#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 &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 &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 new file mode 100644 index 0000000..1a78e07 --- /dev/null +++ b/other/ransom_note.cpp @@ -0,0 +1,23 @@ +#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 new file mode 100644 index 0000000..fa56d94 --- /dev/null +++ b/other/rectangle_area.cpp @@ -0,0 +1,16 @@ +#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 new file mode 100644 index 0000000..4d9c013 --- /dev/null +++ b/other/rectangle_area.rs @@ -0,0 +1,14 @@ +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 new file mode 100644 index 0000000..ef56533 --- /dev/null +++ b/other/rectangle_fewest_squares.cpp @@ -0,0 +1,51 @@ +#include "leetcode.h" + +class Solution { +public: + int maxDepth = 0; + int tilingRectangle(int n, int m) { + if (n > m) + swap(n, m); + vector 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 dp; + key hash(vector &j) { + key r = 0; + for (int n : j) + r = (r << 4LL) + n; + return r; + } + void dfs(vector 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 new file mode 100644 index 0000000..fd922dc --- /dev/null +++ b/other/reduce_array_size_half.cpp @@ -0,0 +1,30 @@ +#include "leetcode.h" + +class Solution { +public: + int minSetSize(vector &arr) { + int ans = 0, n = arr.size(), n1 = 0; + vector j; + unordered_map 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 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 new file mode 100644 index 0000000..3982095 --- /dev/null +++ b/other/reducing_dishes.cpp @@ -0,0 +1,37 @@ +// 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 &satisfaction) { + sort(satisfaction.begin(), satisfaction.end(), greater()); + 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 s1 = {-1, -8, 0, 5, -9}; + vector s2 = {4, 3, 2}; + vector 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 new file mode 100644 index 0000000..c0cc341 --- /dev/null +++ b/other/remove_adjacent_dup.cpp @@ -0,0 +1,37 @@ +#include "leetcode.h" + +class Solution { +public: + string removeDuplicates(string s, int k) { + // cout << s << endl << k << endl; + if (s.size() < k) + return s; + stack> 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 new file mode 100644 index 0000000..80b61ab --- /dev/null +++ b/other/remove_adjacent_dup_str.cpp @@ -0,0 +1,20 @@ +#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 new file mode 100644 index 0000000..063cfbb --- /dev/null +++ b/other/remove_adjacent_dup_str.rs @@ -0,0 +1,20 @@ +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 new file mode 100644 index 0000000..47f62a9 --- /dev/null +++ b/other/remove_boxes.cpp @@ -0,0 +1,40 @@ +// 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 &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 &boxes) { + int n = boxes.size(); + return dfs(boxes, 0, n - 1, 0); + } +}; + +int main() { + Solution obj; + vector 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 new file mode 100644 index 0000000..2628677 --- /dev/null +++ b/other/remove_dupplicate.cpp @@ -0,0 +1,22 @@ +#include "leetcode.h" + +class Solution { +public: + int removeDuplicates(vector &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 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 new file mode 100644 index 0000000..c192b22 --- /dev/null +++ b/other/remove_dupplicate.rs @@ -0,0 +1,24 @@ +struct Solution; + +impl Solution { + pub fn remove_duplicates(nums: &mut Vec) -> 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 new file mode 100644 index 0000000..644f239 --- /dev/null +++ b/other/remove_element.cpp @@ -0,0 +1,28 @@ +#include "leetcode.h" + +class Solution { +public: + int removeElement(vector &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 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 new file mode 100644 index 0000000..fec38b6 --- /dev/null +++ b/other/remove_element.rs @@ -0,0 +1,22 @@ +use std::convert::TryInto; +struct Solution; + +impl Solution { + pub fn remove_element(mut nums: Vec, 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 new file mode 100644 index 0000000..8cc215a --- /dev/null +++ b/other/remove_max_num_edge_traverse.cpp @@ -0,0 +1,58 @@ +// 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 &ds, int i) { + return ds[i] < 0 ? i : ds[i] = find(ds, ds[i]); + } + int maxNumEdgesToRemove(int n, vvd & edges) { + vector 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 new file mode 100644 index 0000000..38f8a72 --- /dev/null +++ b/other/remove_nth_node.cpp @@ -0,0 +1,18 @@ +#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 new file mode 100644 index 0000000..cbf7182 --- /dev/null +++ b/other/remove_palindromic_subsequence.cpp @@ -0,0 +1,19 @@ +#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 new file mode 100644 index 0000000..c7cbfb5 --- /dev/null +++ b/other/remove_star_string.cpp @@ -0,0 +1,40 @@ +// 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 stk; + string ans; + vector 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 new file mode 100644 index 0000000..f267b0c --- /dev/null +++ b/other/remove_stones.cpp @@ -0,0 +1,24 @@ +#include "leetcode.h" + +class Solution { +public: + int minStoneSum(vector &piles, int k) { + priority_queue 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 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 new file mode 100644 index 0000000..e55eade --- /dev/null +++ b/other/remove_stones.rs @@ -0,0 +1,26 @@ +use std::collections::BinaryHeap; +struct Solution; + +impl Solution { + pub fn min_stone_sum(piles: Vec, mut k: i32) -> i32 { + let mut max_heap = BinaryHeap::::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 new file mode 100644 index 0000000..5ec1813 --- /dev/null +++ b/other/remove_subfolder_filesystem.cpp @@ -0,0 +1,48 @@ +// 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 removeSubfolders(vector &folder) { + sort(folder.begin(), folder.end()); + vector 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 f1 = {"/a", "/a/b", "/c/d", "/c/d/e", "/c/f"}, + rsf1 = obj.removeSubfolders(f1); + vector f2 = {"/a", "/a/b/c", "/a/b/d"}, + rsf2 = obj.removeSubfolders(f2); + vector 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 new file mode 100644 index 0000000..a5572be --- /dev/null +++ b/other/remove_substring.cpp @@ -0,0 +1,25 @@ +// 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 new file mode 100644 index 0000000..10ae61a --- /dev/null +++ b/other/reorder_route_city_zero.cpp @@ -0,0 +1,48 @@ +// 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(n) = {}, 0); + } + +private: + int dfs(vvd & res, vector 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 new file mode 100644 index 0000000..d458052 --- /dev/null +++ b/other/reordered_power2.cpp @@ -0,0 +1,24 @@ +#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 new file mode 100644 index 0000000..7a42643 --- /dev/null +++ b/other/reorganise_string.cpp @@ -0,0 +1,41 @@ +// 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 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 new file mode 100644 index 0000000..4e2d8d8 --- /dev/null +++ b/other/repeated_substring_pattern.cpp @@ -0,0 +1,31 @@ +// 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 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 new file mode 100644 index 0000000..4f4a59a --- /dev/null +++ b/other/restore_array.cpp @@ -0,0 +1,37 @@ +// 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 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 new file mode 100644 index 0000000..eba5de2 --- /dev/null +++ b/other/restore_ip_addr.cpp @@ -0,0 +1,56 @@ +// 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 restoreIpAddresses(string s) { + vector ans; + string ip; + dfs(s, 0, 0, ip, ans); + return ans; + } + +private: + void dfs(string s, int start, int step, string ip, vector &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 new file mode 100644 index 0000000..14f55cd --- /dev/null +++ b/other/reverse_integer.cpp @@ -0,0 +1,30 @@ +// 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 new file mode 100644 index 0000000..e3a1793 --- /dev/null +++ b/other/reverse_linked_list.cpp @@ -0,0 +1,16 @@ +#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 new file mode 100644 index 0000000..dbbb261 --- /dev/null +++ b/other/reverse_linked_list2.cpp @@ -0,0 +1,26 @@ +#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 new file mode 100644 index 0000000..f5940a0 --- /dev/null +++ b/other/reverse_string.cpp @@ -0,0 +1,15 @@ +#include "leetcode.h" + +class Solution { +public: + void reverseString(vector &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 new file mode 100644 index 0000000..839a26f --- /dev/null +++ b/other/reverse_string2.cpp @@ -0,0 +1,34 @@ +#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 new file mode 100644 index 0000000..0cc2cf5 --- /dev/null +++ b/other/reverse_string3.cpp @@ -0,0 +1,21 @@ +#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 new file mode 100644 index 0000000..aa9a039 --- /dev/null +++ b/other/reverse_vowel_string.cpp @@ -0,0 +1,20 @@ +#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 new file mode 100644 index 0000000..4ae282d --- /dev/null +++ b/other/reverse_vowel_string.rs @@ -0,0 +1,33 @@ +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::>(); + 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 new file mode 100644 index 0000000..0259e04 --- /dev/null +++ b/other/reverse_word_string.cpp @@ -0,0 +1,30 @@ +#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 new file mode 100644 index 0000000..6acc9a4 --- /dev/null +++ b/other/reverse_word_string.rs @@ -0,0 +1,31 @@ +struct Solution; + +impl Solution { + pub fn reverse_words(s: String) -> String { + let mut s: Vec = 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 new file mode 100644 index 0000000..1389754 --- /dev/null +++ b/other/roman_2_int.cpp @@ -0,0 +1,43 @@ +#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 new file mode 100644 index 0000000..1bfd7f5 --- /dev/null +++ b/other/rotate_function.cpp @@ -0,0 +1,29 @@ +#include "leetcode.h" + +class Solution { +public: + int maxRotateFunction(vector &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 nums = {4, 3, 2, 6}; + cout << obj.maxRotateFunction(nums); +} diff --git a/other/rotate_image.cpp b/other/rotate_image.cpp new file mode 100644 index 0000000..10d0638 --- /dev/null +++ b/other/rotate_image.cpp @@ -0,0 +1,18 @@ +#include "leetcode.h" + +class Solution { +public: + void rotate(vector> &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 new file mode 100644 index 0000000..376545d --- /dev/null +++ b/other/rotate_image.rs @@ -0,0 +1,27 @@ +struct Solution; + +impl Solution { + pub fn rotate(mut matrix: Vec>) { + 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 new file mode 100644 index 0000000..b82e0ad --- /dev/null +++ b/other/running_sum_1d_array.cpp @@ -0,0 +1,18 @@ +#include "leetcode.h" + +class Solution { +public: + vector runningSum(vector &nums) { + vector 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 nums = {1, 2, 3, 4}; + Solution obj; + obj.runningSum(nums); +} diff --git a/other/same_tree.cpp b/other/same_tree.cpp new file mode 100644 index 0000000..71c2563 --- /dev/null +++ b/other/same_tree.cpp @@ -0,0 +1,14 @@ +#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 new file mode 100644 index 0000000..3d94ffb --- /dev/null +++ b/other/same_tree.rs @@ -0,0 +1,71 @@ +use std::rc::Rc; +use std::cell::Ref; +use std::cell::RefCell; +use std::collections::VecDeque; +type NodeRef = Option>>; +#[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) -> (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 new file mode 100644 index 0000000..b0a1f8b --- /dev/null +++ b/other/satisfiability_eqaulity.cpp @@ -0,0 +1,33 @@ +#include "leetcode.h" + +class Solution { +public: + bool equationsPossible(vector &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 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 new file mode 100644 index 0000000..da6b92d --- /dev/null +++ b/other/scramble_string.cpp @@ -0,0 +1,55 @@ +// 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 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 new file mode 100644 index 0000000..3d8ce04 --- /dev/null +++ b/other/search_2d_matrix.cpp @@ -0,0 +1,35 @@ +// 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 new file mode 100644 index 0000000..9834431 --- /dev/null +++ b/other/search_2d_matrix2.cpp @@ -0,0 +1,20 @@ +#include "leetcode.h" + +class Solution { +public: + bool searchMatrix(vector> &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 new file mode 100644 index 0000000..7001f32 --- /dev/null +++ b/other/search_rotated_array.cpp @@ -0,0 +1,37 @@ +// 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 &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 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 new file mode 100644 index 0000000..0054f04 --- /dev/null +++ b/other/search_rotated_array2.cpp @@ -0,0 +1,48 @@ +// 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 &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 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 new file mode 100644 index 0000000..404c987 --- /dev/null +++ b/other/search_suggestion_sys.cpp @@ -0,0 +1,26 @@ +#include "leetcode.h" +#include + +class Solution { +public: + vector> suggestedProducts(vector &products, + string searchWord) { + auto it = products.begin(); + sort(it, products.end()); + vector> ans; + string curr = ""; + for (char c : searchWord) { + curr += c; + vector 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 new file mode 100644 index 0000000..78c434a --- /dev/null +++ b/other/set_matrix_0.rs @@ -0,0 +1,44 @@ +// 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>) { + 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 new file mode 100644 index 0000000..8c216bc --- /dev/null +++ b/other/set_mismatch.cpp @@ -0,0 +1,19 @@ +#include "leetcode.h" + +class Solution { +public: + vector findErrorNums(vector &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 new file mode 100644 index 0000000..b490f8e --- /dev/null +++ b/other/set_mismatch.rs @@ -0,0 +1,37 @@ +struct Solution; + +impl Solution { + pub fn find_error_nums(nums: Vec) -> Vec { + 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 new file mode 100644 index 0000000..528191f --- /dev/null +++ b/other/short_encoding_words.cpp @@ -0,0 +1,21 @@ +#include "leetcode.h" + +class Solution { +public: + int minimumLengthEncoding(vector &words) { + unordered_set 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 words = {"time", "me", "bell"}; + cout << obj.minimumLengthEncoding(words); +} diff --git a/other/shortest_bridge.cpp b/other/shortest_bridge.cpp new file mode 100644 index 0000000..818d384 --- /dev/null +++ b/other/shortest_bridge.cpp @@ -0,0 +1,82 @@ +// 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> 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 new file mode 100644 index 0000000..deea04c --- /dev/null +++ b/other/shortest_dist_road_addition1.cpp @@ -0,0 +1,48 @@ +// 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 shortestDistanceAfterQueries(int n, + vector> &queries) { + vector ans; + unordered_map> 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 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 sdaq1 = obj.shortestDistanceAfterQueries(5, q1); + vector 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 new file mode 100644 index 0000000..a5cf369 --- /dev/null +++ b/other/shortest_path_alternate_color.cpp @@ -0,0 +1,56 @@ +// 1129. Shortest Path with Alternating Colors +#include "leetcode.h" + +class Solution { +public: + vector shortestAlternatingPaths(int n, vvd & redEdges, + vvd & blueEdges) { + vector ans(n, -1), v1(n, 0), v2(n, 0); + vector>> vvp(n); + queue> 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 new file mode 100644 index 0000000..fd586fe --- /dev/null +++ b/other/shortest_path_binary_matrix.cpp @@ -0,0 +1,55 @@ +// 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> &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> 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 new file mode 100644 index 0000000..daaa361 --- /dev/null +++ b/other/shortest_path_grid_obstacle.cpp @@ -0,0 +1,48 @@ +#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> togo; + togo.push_back({0, 0, k}); + vector 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 new file mode 100644 index 0000000..ba35681 --- /dev/null +++ b/other/shortest_path_grid_obstacle.rs @@ -0,0 +1,38 @@ +use std::collections::VecDeque; +struct Solution; + +impl Solution { + pub fn shortest_path(grid: Vec>, 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 new file mode 100644 index 0000000..15ffe90 --- /dev/null +++ b/other/shortest_path_keys.cpp @@ -0,0 +1,109 @@ +// 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 p; + vector keys; + int cnt; + Info(pair p, vector 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 &grid) { + pair 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 q; + vector keys_start(key_cnt, 0); + q.push(Info(start, keys_start, 0)); + int ans = -1; + vector>> vis; + for (int i = 0; i < 1 << key_cnt; i++) { + vvd tmp(m, vector(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 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 new file mode 100644 index 0000000..23d95ea --- /dev/null +++ b/other/shortest_path_vis_nodes.cpp @@ -0,0 +1,62 @@ +// 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 q; + set> 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 new file mode 100644 index 0000000..849f524 --- /dev/null +++ b/other/shortest_unsorted_subarr.cpp @@ -0,0 +1,30 @@ +#include "leetcode.h" + +class Solution { +public: + int findUnsortedSubarray(vector &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 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 new file mode 100644 index 0000000..f7dddea --- /dev/null +++ b/other/shuffle_the_array.cpp @@ -0,0 +1,39 @@ +// 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 shuffle(vector &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 nums1 = {2, 5, 1, 3, 4, 7}; + vector nums2 = {1, 2, 3, 4, 4, 3, 2, 1}; + vector 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 new file mode 100644 index 0000000..273df4f --- /dev/null +++ b/other/similar_string_group.cpp @@ -0,0 +1,63 @@ +// 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 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 &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 s1 = {"tars", "rats", "arts", "star"}; + vector 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 new file mode 100644 index 0000000..09852f3 --- /dev/null +++ b/other/simplify_path.cpp @@ -0,0 +1,33 @@ +// 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 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 new file mode 100644 index 0000000..e9bd894 --- /dev/null +++ b/other/single_element_sorted_arr.cpp @@ -0,0 +1,33 @@ +// 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 &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 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 new file mode 100644 index 0000000..e9a5878 --- /dev/null +++ b/other/single_number.cpp @@ -0,0 +1,38 @@ +#include "leetcode.h" + +class Solution { +public: + int singleNumber(vector &nums) { + int ans; + /* + * unordered_map to track frequency + * unordered_map + * both are int in this case. + */ + unordered_map 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 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 new file mode 100644 index 0000000..c724ebf --- /dev/null +++ b/other/single_number.rs @@ -0,0 +1,22 @@ +struct Solution; + +impl Solution { + pub fn single_number(nums: Vec) -> 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 new file mode 100644 index 0000000..907fee0 --- /dev/null +++ b/other/single_number2.cpp @@ -0,0 +1,29 @@ +// 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 &nums) { + unordered_map 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 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 new file mode 100644 index 0000000..262bd0e --- /dev/null +++ b/other/single_product_array.cpp @@ -0,0 +1,35 @@ +// 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 &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 n1 = {-1, -2, -3, -4, 3, 2, 1}; + vector n2 = {1, 5, 0, 2, -3}; + vector 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 new file mode 100644 index 0000000..db32185 --- /dev/null +++ b/other/single_threaded_cpu.cpp @@ -0,0 +1,31 @@ +#include "leetcode.h" + +class Solution { +public: + vector getOrder(vvd & tasks) { + vector ans, idx(tasks.size()); + priority_queue> 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 new file mode 100644 index 0000000..4defcb7 --- /dev/null +++ b/other/single_threaded_cpu.rs @@ -0,0 +1,59 @@ +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 { + 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 { + let mut tasks = tasks.into_iter().enumerate().map(|(idx, task)| { + Task { + enqueue_time: task[0], + processing_time: task[1], + initial_idx: idx + } + }).collect::>(); + let (mut output, mut current_time) = (vec![], 0); + let mut available_tasks: BinaryHeap = 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 new file mode 100644 index 0000000..b19c87a --- /dev/null +++ b/other/skyline_problem.cpp @@ -0,0 +1,28 @@ +#include "leetcode.h" + +class Solution { +public: + vvd getSkyline(vvd & buildings) { + vvd ans; + map>> mvp; + for (auto &b : buildings) { + mvp[b[0]].push_back({b[2], 0}); + mvp[b[1]].push_back({b[2], 1}); + } + multiset 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({pos, newHeight})); + } + return ans; + } +}; diff --git a/other/sliding_puzzle.cpp b/other/sliding_puzzle.cpp new file mode 100644 index 0000000..9b772f1 --- /dev/null +++ b/other/sliding_puzzle.cpp @@ -0,0 +1,53 @@ +// 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> &board) { + string begin = "", end = "123450"; + vector> 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 vis; + vis.insert(begin); + queue> 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 new file mode 100644 index 0000000..8468604 --- /dev/null +++ b/other/sliding_window_max.cpp @@ -0,0 +1,38 @@ +// 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 maxSlidingWindow(vector &nums, int k) { + deque dq; + vector 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 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 new file mode 100644 index 0000000..f05147b --- /dev/null +++ b/other/smallest_num_set.cpp @@ -0,0 +1,45 @@ +// 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 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 new file mode 100644 index 0000000..c521309 --- /dev/null +++ b/other/smallest_string_swaps.cpp @@ -0,0 +1,55 @@ +#include "leetcode.h" + +class Solution { +public: + vector parent; + string smallestStringWithSwaps(string s, vector> &pairs) { + parent.resize(s.length()); + map> obj; + set 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> 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 new file mode 100644 index 0000000..473e218 --- /dev/null +++ b/other/smallest_sufficient_team.cpp @@ -0,0 +1,61 @@ +// 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 smallestSufficientTeam(vector &req_skills, + vvd(string) & people) { + int n = req_skills.size(); + unordered_map> ans; + ans.reserve(1 << n); + ans[0] = {}; + unordered_map 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 rs1 = {"java", "nodejs", "reactjs"}; + vvd(string) p1 = {{"java"}, {"nodejs"}, {"nodejs", "reactjs"}}; + vector 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 new file mode 100644 index 0000000..160b473 --- /dev/null +++ b/other/snakes_ladders.cpp @@ -0,0 +1,47 @@ +// 909. Snakes and Ladders +#include "leetcode.h" + +typedef pair pii; +class Solution { +public: + int snakesAndLadders(vvd & board) { + int rows = board.size(), cols = board[0].size(); + int target = rows * cols, r, c, p; + vector visited(rows * cols + 1); // cells on board starting from 1 + priority_queue, greater> 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 new file mode 100644 index 0000000..42d165b --- /dev/null +++ b/other/snapshot_array.cpp @@ -0,0 +1,42 @@ +// 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>> vvp; + +public: + SnapshotArray(int length) { vvp = vector>>(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(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 new file mode 100644 index 0000000..655726d --- /dev/null +++ b/other/sort_array.cpp @@ -0,0 +1,27 @@ +// 912. Sort an Array +#include "leetcode.h" +#include + +class Solution { +public: + vector sortArray(vector &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 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 new file mode 100644 index 0000000..33f02b1 --- /dev/null +++ b/other/sort_array_parity.cpp @@ -0,0 +1,46 @@ +#include "leetcode.h" + +class Solution { +public: + vector sortArrayByParity(vector &nums) { + /* + * important to assign vector values first: + * vector... var(size, vals) + */ + vector 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 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 new file mode 100644 index 0000000..ea7d8af --- /dev/null +++ b/other/sort_char_freq.cpp @@ -0,0 +1,26 @@ +#include "leetcode.h" + +class Solution { +public: + string frequencySort(string s) { + unordered_map freq; + for (auto a : s) + freq[a]++; + priority_queue> pqp; + for (auto [a, f] : freq) + pqp.push({f, a}); + string ans; + pair 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 new file mode 100644 index 0000000..a9d0e13 --- /dev/null +++ b/other/sort_char_freq.rs @@ -0,0 +1,16 @@ +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::>(); + 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 new file mode 100644 index 0000000..1887d05 --- /dev/null +++ b/other/sort_items_dependencies.cpp @@ -0,0 +1,74 @@ +// 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> &al, int i, vector &res, + vector &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 sortItems(int n, int m, vector &group, + vvd & beforeItems) { + vector ans(n), stat(n + 2 * m), ans_tmp; + vector> 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 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 new file mode 100644 index 0000000..61f3486 --- /dev/null +++ b/other/sort_matrix_diagonal.cpp @@ -0,0 +1,21 @@ +#include "leetcode.h" + +class Solution { +public: + unordered_map> umv; + vector> diagonalSort(vector> &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 new file mode 100644 index 0000000..e859528 --- /dev/null +++ b/other/sorted_arrary_bst.cpp @@ -0,0 +1,21 @@ +#include "leetcode.h" + +class Solution { +public: + TreeNode *sortedArrayToBST(vector &nums) { + int start = 0, end = nums.size() - 1; + TreeNode *root = helper(start, end, nums); + return root; + } + +private: + TreeNode *helper(int start, int end, vector &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 new file mode 100644 index 0000000..1733c21 --- /dev/null +++ b/other/soup_servings.cpp @@ -0,0 +1,54 @@ +// 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> 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 new file mode 100644 index 0000000..d1c294b --- /dev/null +++ b/other/spiral_matrix.cpp @@ -0,0 +1,37 @@ +// 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 spiralOrder(vvd & matrix) { + vvd dirs{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int rows = matrix.size(), cols = matrix[0].size(); + vector 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 new file mode 100644 index 0000000..dc8dc11 --- /dev/null +++ b/other/spiral_matrix2.cpp @@ -0,0 +1,26 @@ +// 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(n)); + int num = 1, row = 0, col = 0, dir = 0; + vector 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 new file mode 100644 index 0000000..622e296 --- /dev/null +++ b/other/split_array_consec_subseq.cpp @@ -0,0 +1,33 @@ +#include "leetcode.h" + +class Solution { +public: + bool isPossible(vector &nums) { + unordered_map 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 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 new file mode 100644 index 0000000..61e2c88 --- /dev/null +++ b/other/stack_using_queues.cpp @@ -0,0 +1,24 @@ +#include "leetcode.h" + +class MyStack { +public: + queue 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 new file mode 100644 index 0000000..b9ba317 --- /dev/null +++ b/other/stamping_sequence.cpp @@ -0,0 +1,34 @@ +#include "leetcode.h" + +class Solution { +public: + vector movesToStamp(string stamp, string target) { + if (stamp == target) + return {0}; + int sLen = stamp.size(), tLen = target.size() - sLen + 1, i, j; + vector 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 new file mode 100644 index 0000000..2beb625 --- /dev/null +++ b/other/steps_arr_increasing.cpp @@ -0,0 +1,32 @@ +// 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 &nums) { + int n = nums.size(), ans = 0; + vector 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 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 new file mode 100644 index 0000000..7ebc520 --- /dev/null +++ b/other/stone_game2.cpp @@ -0,0 +1,39 @@ +// 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 &piles) { + int n = piles.size(); + vvd dp(n + 1, vector(n + 1, 0)); + vector 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 p1 = {2, 7, 9, 4, 4}; + vector 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 new file mode 100644 index 0000000..947d65f --- /dev/null +++ b/other/stone_game3.cpp @@ -0,0 +1,46 @@ +// 1406. Stone Game III +#include + +/* + * 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 new file mode 100644 index 0000000..2eddb18 --- /dev/null +++ b/other/stone_game4.cpp @@ -0,0 +1,16 @@ +#include "leetcode.h" +#include + +class Solution { +public: + int stoneGameVI(vector &aliceValues, vector &bobValues) { + vector> n; + int a = 0, b = 0, sz = aliceValues.size(); + } +}; + +int main() { + Solution obj; + vector aliceValues = {1, 3}, bobValues = {2, 1}; + cout << obj.stoneGameVI(aliceValues, bobValues); +} diff --git a/other/strange_printer.cpp b/other/strange_printer.cpp new file mode 100644 index 0000000..8a5dc93 --- /dev/null +++ b/other/strange_printer.cpp @@ -0,0 +1,32 @@ +// 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> dp(n + 1, vector(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 new file mode 100644 index 0000000..5f9b9c6 --- /dev/null +++ b/other/string_compression.cpp @@ -0,0 +1,31 @@ +#include "leetcode.h" + +class Solution { +public: + int compress(vector &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::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 new file mode 100644 index 0000000..1d5db7d --- /dev/null +++ b/other/string_compression.rs @@ -0,0 +1,38 @@ +struct Solution; + +impl Solution { + pub fn compress(chars: &mut Vec) -> 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 new file mode 100644 index 0000000..f4c41c8 --- /dev/null +++ b/other/string_compression2.cpp @@ -0,0 +1,37 @@ +#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 new file mode 100644 index 0000000..792a0ac --- /dev/null +++ b/other/string_compression2.rs @@ -0,0 +1,54 @@ +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 new file mode 100644 index 0000000..738d000 --- /dev/null +++ b/other/string_without_3a3b.cpp @@ -0,0 +1,38 @@ +// 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 new file mode 100644 index 0000000..658c766 --- /dev/null +++ b/other/subarr_fixed_bound.cpp @@ -0,0 +1,33 @@ +// 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 &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 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 new file mode 100644 index 0000000..64cb1b4 --- /dev/null +++ b/other/subarr_product_less_k.cpp @@ -0,0 +1,23 @@ +#include "leetcode.h" + +class Solution { +public: + int numSubarrayProductLessThanK(vector &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 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 new file mode 100644 index 0000000..3661c96 --- /dev/null +++ b/other/subarr_sum_divisible_k.cpp @@ -0,0 +1,32 @@ +// 974. Subarray Sums Divisible by K +#include "leetcode.h" +#include + +/* + * 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 &nums, int k) { + vector 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 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 new file mode 100644 index 0000000..6df445c --- /dev/null +++ b/other/substr_largest_variance.cpp @@ -0,0 +1,48 @@ +// 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 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 new file mode 100644 index 0000000..10fc449 --- /dev/null +++ b/other/sum_dist_tree.cpp @@ -0,0 +1,45 @@ +#include "leetcode.h" + +class Solution { +public: + vector 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> tree; + vector 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 new file mode 100644 index 0000000..d000d83 --- /dev/null +++ b/other/sum_dist_tree.rs @@ -0,0 +1,49 @@ +struct Solution; + +impl Solution { + pub fn sum_of_distances_in_tree(n: i32, edges: Vec>) -> Vec { + let n = n as usize; + let mut adj: Vec> = 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>) { + 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, dp: &Vec<[i32; 2]>, adj: &Vec>) { + 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 new file mode 100644 index 0000000..a58e3b2 --- /dev/null +++ b/other/sum_even_num_queries.cpp @@ -0,0 +1,22 @@ +#include "leetcode.h" + +class Solution { +public: + vector sumEvenAfterQueries(vector &nums, vvd & queries) { + int evenSum = 0; + for (auto x : nums) + if (x % 2 == 0) + evenSum += x; + vector 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 new file mode 100644 index 0000000..d1bc9c6 --- /dev/null +++ b/other/sum_root_leaf_num.cpp @@ -0,0 +1,42 @@ +// 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 new file mode 100644 index 0000000..8f90e37 --- /dev/null +++ b/other/sum_subarr_mins.cpp @@ -0,0 +1,30 @@ +#include "leetcode.h" + +class Solution { +public: + int sumSubarrayMins(vector &arr) { + vector 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 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 new file mode 100644 index 0000000..ee28cb9 --- /dev/null +++ b/other/sum_subarr_mins.rs @@ -0,0 +1,37 @@ +use std::collections::VecDeque; +struct Solution; + +impl Solution { + pub fn sum_subarray_mins(arr: Vec) -> i32 { + const MOD: i32 = 1e9 as i32 + 7; + let n: usize = arr.len(); + let mut stk: VecDeque = { + let mut stk: VecDeque = VecDeque::with_capacity(n); + stk.push_back(-1); + stk + }; + let mut ans: i32 = 0; + let mut dp: Vec = 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 new file mode 100644 index 0000000..a3048f7 --- /dev/null +++ b/other/sum_subset_xor.cpp @@ -0,0 +1,33 @@ +#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 &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 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 new file mode 100644 index 0000000..d2feb9e --- /dev/null +++ b/other/summary_ranges.cpp @@ -0,0 +1,47 @@ +// 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 summaryRanges(vector &nums) { + int n = nums.size(); + vector 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 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 new file mode 100644 index 0000000..b5ad832 --- /dev/null +++ b/other/swap_node_linked_list.cpp @@ -0,0 +1,45 @@ +#include +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 new file mode 100644 index 0000000..139c336 --- /dev/null +++ b/other/swap_nodes_pairs.cpp @@ -0,0 +1,21 @@ +// 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 new file mode 100644 index 0000000..fbd4bf3 --- /dev/null +++ b/other/symmetric_tree.cpp @@ -0,0 +1,33 @@ +// 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 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 new file mode 100644 index 0000000..1201823 --- /dev/null +++ b/other/tallest_billboard.cpp @@ -0,0 +1,26 @@ +#include "leetcode.h" + +class Solution { +public: + int tallestBillboard(vector &rods) { + unordered_map dp; + dp[0] = 0; + for (int i : rods) { + unordered_map 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 rods = {1, 2, 3, 6}; + cout << obj.tallestBillboard(rods); +} diff --git a/other/task_scheduler.cpp b/other/task_scheduler.cpp new file mode 100644 index 0000000..553dd5d --- /dev/null +++ b/other/task_scheduler.cpp @@ -0,0 +1,36 @@ +// 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 &tasks, int space) { + unordered_map 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 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 new file mode 100644 index 0000000..d45bead --- /dev/null +++ b/other/text_justification.cpp @@ -0,0 +1,56 @@ +#include "leetcode.h" + +class Solution { +public: + vector fullJustify(vector &words, int maxWidth) { + vector 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 &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 &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 new file mode 100644 index 0000000..a0493f5 --- /dev/null +++ b/other/thousand_separator.cpp @@ -0,0 +1,20 @@ +#include "leetcode.h" +#include +#include + +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 new file mode 100644 index 0000000..c23fb87 --- /dev/null +++ b/other/time_base_key_val.cpp @@ -0,0 +1,32 @@ +#include "leetcode.h" + +class TimeMap { +public: + unordered_map>> 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 new file mode 100644 index 0000000..f451196 --- /dev/null +++ b/other/toeplitz_matrix.cpp @@ -0,0 +1,30 @@ +#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 new file mode 100644 index 0000000..03a46bb --- /dev/null +++ b/other/toeplitz_matrix.rs @@ -0,0 +1,22 @@ +struct Solution; + +impl Solution { + pub fn is_toeplitz_matrix(matrix: Vec>) -> 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 new file mode 100644 index 0000000..343595f --- /dev/null +++ b/other/top_k_freq_element.cpp @@ -0,0 +1,18 @@ +#include "leetcode.h" + +class Solution { +public: + vector topKFrequent(vector &nums, int k) { + unordered_map um; + for (int n : nums) + um[n]++; + vector ans; + priority_queue> 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 new file mode 100644 index 0000000..82a2b03 --- /dev/null +++ b/other/top_k_freq_element.rs @@ -0,0 +1,32 @@ +//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, k: i32) -> Vec { + 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::>(); + 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 new file mode 100644 index 0000000..eaf31d5 --- /dev/null +++ b/other/top_k_freq_words.cpp @@ -0,0 +1,29 @@ +#include "leetcode.h" + +struct Compare { + bool operator()(pair a, pair b) { + if (a.first == b.first) + return a.second > b.second; + else + return a.first < b.first; + } +}; + +class Solution { +public: + vector topKFrequent(vector &words, int k) { + unordered_map um; + for (int i = 0; i < words.size(); i++) + um[words[i]]++; + priority_queue, vector>, Compare> + pqpvpc; + for (auto i : um) + pqpvpc.push({i.second, i.first}); + vector 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 new file mode 100644 index 0000000..606c237 --- /dev/null +++ b/other/top_k_freq_words.rs @@ -0,0 +1,26 @@ +use std::collections::BinaryHeap; +use std::collections::HashMap; + +struct Solution; + +impl Solution { + pub fn top_k_frequent(words: Vec, k: i32) -> Vec { + let mut word_to_freq = HashMap::::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 = 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 new file mode 100644 index 0000000..b6ab293 --- /dev/null +++ b/other/transpose_matrix.cpp @@ -0,0 +1,20 @@ +#include "leetcode.h" +#include + +class Solution { +public: + vector> transpose(vector> &matrix) { + int n = matrix.size(), m = matrix[0].size(); + vector> ans(m, vector(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> matrix; + obj.transpose(matrix); +} diff --git a/other/trapping_rain_water.cpp b/other/trapping_rain_water.cpp new file mode 100644 index 0000000..d2ced43 --- /dev/null +++ b/other/trapping_rain_water.cpp @@ -0,0 +1,33 @@ +#include "leetcode.h" + +class Solution { +public: + int trap(vector &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 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 new file mode 100644 index 0000000..b56e38b --- /dev/null +++ b/other/trie_prefix.cpp @@ -0,0 +1,45 @@ +// 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 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 new file mode 100644 index 0000000..e75565d --- /dev/null +++ b/other/two_sum.cpp @@ -0,0 +1,35 @@ +// 1. Two Sum +#include "leetcode.h" + +class Solution { +public: + vector twoSum(vector &nums, int target) { + vector ans; + unordered_map 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 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 new file mode 100644 index 0000000..55741ac --- /dev/null +++ b/other/two_sum_2.cpp @@ -0,0 +1,33 @@ +#include "leetcode.h" +#include + +class Solution { +public: + vector twoSum(vector &numbers, int target) { + vector 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 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 new file mode 100644 index 0000000..c25bcc9 --- /dev/null +++ b/other/two_sum_4.cpp @@ -0,0 +1,24 @@ +#include "leetcode.h" + +class Solution { +public: + bool findTarget(TreeNode *root, int k) { + vector 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 &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 new file mode 100644 index 0000000..8af53f8 --- /dev/null +++ b/other/ugly_number.cpp @@ -0,0 +1,21 @@ +#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 new file mode 100644 index 0000000..e356ff2 --- /dev/null +++ b/other/ugly_number.rs @@ -0,0 +1,19 @@ +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 new file mode 100644 index 0000000..c8156b1 --- /dev/null +++ b/other/uncrossed_lines.cpp @@ -0,0 +1,39 @@ +// 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 &nums1, vector &nums2) { + int n = nums1.size(), m = nums2.size(); + vvd dp(n + 1, vector(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 n11 = {1, 4, 2}, n21 = {1, 2, 4}; + vector n12 = {2, 5, 1, 2, 5}, n22 = {10, 5, 2, 1, 5, 2}; + vector 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 new file mode 100644 index 0000000..7aefacd --- /dev/null +++ b/other/unique_bst.cpp @@ -0,0 +1,23 @@ +#include "leetcode.h" + +class Solution { +public: + int numTrees(int n) { + if (n == 1) + return 1; + vector 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 new file mode 100644 index 0000000..438d9b7 --- /dev/null +++ b/other/unique_bst2.cpp @@ -0,0 +1,34 @@ +// 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 build(int from, int to) { + vector 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 left = build(from, i - 1); + vector 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 generateTrees(int n) { return build(1, n); } +}; diff --git a/other/unique_morse_code_words.cpp b/other/unique_morse_code_words.cpp new file mode 100644 index 0000000..2a6280e --- /dev/null +++ b/other/unique_morse_code_words.cpp @@ -0,0 +1,25 @@ +#include "leetcode.h" + +class Solution { +public: + int uniqueMorseRepresentations(vector &words) { + vector codes = { + ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", + ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", + "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; + set 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 words = {"gin", "zen", "gig", "msg"}; + cout << obj.uniqueMorseRepresentations(words); +} diff --git a/other/unique_num_occurrences.cpp b/other/unique_num_occurrences.cpp new file mode 100644 index 0000000..5c4871f --- /dev/null +++ b/other/unique_num_occurrences.cpp @@ -0,0 +1,24 @@ +#include "leetcode.h" + +class Solution { +public: + bool uniqueOccurrences(vector &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 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 new file mode 100644 index 0000000..d29c580 --- /dev/null +++ b/other/unique_num_occurrences.rs @@ -0,0 +1,20 @@ +struct Solution; + +impl Solution { + pub fn unique_occurrences(arr: Vec) -> 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 new file mode 100644 index 0000000..053a92b --- /dev/null +++ b/other/unique_paths.cpp @@ -0,0 +1,22 @@ +#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 new file mode 100644 index 0000000..fedb826 --- /dev/null +++ b/other/unique_paths2.cpp @@ -0,0 +1,39 @@ +// 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> &obstacleGrid) { + int m = obstacleGrid.size(), n = obstacleGrid[0].size(); + vvd dp(m + 1, vector(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 new file mode 100644 index 0000000..37876fa --- /dev/null +++ b/other/unique_paths3.cpp @@ -0,0 +1,38 @@ +#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 new file mode 100644 index 0000000..b83c50e --- /dev/null +++ b/other/unique_paths3.rs @@ -0,0 +1,40 @@ +struct Solution; + +impl Solution { + pub fn unique_paths_iii(mut grid: Vec>) -> 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>, 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 new file mode 100644 index 0000000..0cb96d7 --- /dev/null +++ b/other/utf8_validation.cpp @@ -0,0 +1,38 @@ +#include "leetcode.h" + +class Solution { +public: + bool validUtf8(vector &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 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 new file mode 100644 index 0000000..2c2586e --- /dev/null +++ b/other/valid_anagram.cpp @@ -0,0 +1,29 @@ +#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 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 new file mode 100644 index 0000000..0493141 --- /dev/null +++ b/other/valid_arrangement_pairs.cpp @@ -0,0 +1,73 @@ +// 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> &adj, vector> &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> validArrangement(vector> &pairs) { + int m = pairs.size(); + unordered_map> adj; + unordered_map 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> 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 new file mode 100644 index 0000000..6395fe0 --- /dev/null +++ b/other/valid_number.cpp @@ -0,0 +1,45 @@ +#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 new file mode 100644 index 0000000..9bab082 --- /dev/null +++ b/other/valid_parentheses.cpp @@ -0,0 +1,43 @@ +// 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 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 new file mode 100644 index 0000000..62250db --- /dev/null +++ b/other/valid_stack_seq.cpp @@ -0,0 +1,32 @@ +// 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 &pushed, vector &popped) { + stack 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 pushed = {1, 2, 3, 4, 5}; + vector 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 new file mode 100644 index 0000000..0843d67 --- /dev/null +++ b/other/valid_sudoku.cpp @@ -0,0 +1,38 @@ +#include "leetcode.h" +#include + +class Solution { +public: + bool isValidSudoku(vvd(char) & board) { + vector> 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 new file mode 100644 index 0000000..3c2f591 --- /dev/null +++ b/other/valid_sudoku.rs @@ -0,0 +1,27 @@ +struct Solution; + +impl Solution { + pub fn is_valid_sudoku(board: Vec>) -> 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 new file mode 100644 index 0000000..0785d47 --- /dev/null +++ b/other/validate_bst.cpp @@ -0,0 +1,24 @@ +#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 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 new file mode 100644 index 0000000..009ac52 --- /dev/null +++ b/other/verify_alien_dict.cpp @@ -0,0 +1,42 @@ +// 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 &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 words1 = {"hello", "leetcode"}; + vector words2 = {"word", "world", "row"}; + vector 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 new file mode 100644 index 0000000..a429d4d --- /dev/null +++ b/other/vertical_order_bst.cpp @@ -0,0 +1,29 @@ +#include "leetcode.h" + +class Solution { +public: + vvd verticalTraversal(TreeNode *root) { + map>> mmm; + queue>> 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 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 new file mode 100644 index 0000000..b661af8 --- /dev/null +++ b/other/ways_to_paint_nx3_grid.cpp @@ -0,0 +1,20 @@ +#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 new file mode 100644 index 0000000..4195778 --- /dev/null +++ b/other/where_will_ball_fall.cpp @@ -0,0 +1,50 @@ +#include "leetcode.h" + +class Solution { +public: + vector findBall(vvd & grid) { + int m = grid.size(), n = grid[0].size(); + vvd ugrid(m * 3, vector(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 ans; + for (auto i = 0; i < n; ++i) + ans.push_back(drop(i * 3 + 1, ugrid, m * 3, n * 3)); + return ans; + } + +private: + vector> dir{{1, 0}, {0, -1}, {0, 1}}; + int drop(int pos, vvd & ugrid, int m, int n) { + queue> 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 new file mode 100644 index 0000000..6a1bb58 --- /dev/null +++ b/other/where_will_ball_fall.rs @@ -0,0 +1,38 @@ +struct Solution; + +impl Solution { + pub fn find_ball(grid: Vec>) -> Vec { + 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>, 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 new file mode 100644 index 0000000..22376d4 --- /dev/null +++ b/other/wiggle_subsequence.cpp @@ -0,0 +1,23 @@ +#include "leetcode.h" + +class Solution { +public: + int wiggleMaxLength(vector &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 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 new file mode 100644 index 0000000..aa580c9 --- /dev/null +++ b/other/word_break.cpp @@ -0,0 +1,38 @@ +// 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 &word_dict) { + if (!word_dict.size()) + return false; + vector 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 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 new file mode 100644 index 0000000..dfe6b00 --- /dev/null +++ b/other/word_ladder.cpp @@ -0,0 +1,39 @@ +#include "leetcode.h" + +class Solution { +public: + int ladderLength(string beginWord, string endWord, vector &wordList) { + unordered_set dict(wordList.begin(), wordList.end()); + queue 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 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 new file mode 100644 index 0000000..12cff05 --- /dev/null +++ b/other/word_ladder2.cpp @@ -0,0 +1,47 @@ +#include "leetcode.h" + +class Solution { +public: + vector> findLadders(string beginWord, string endWord, + vector &wordList) { + unordered_map um; + vector> ans; + for (const auto w : wordList) + um.insert({w, INT_MAX}); + um[beginWord] = 0; + queue>> 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 wordList = {"hot", "dot", "dog", "lot", "log", "cog"}; +} diff --git a/other/word_pattern.cpp b/other/word_pattern.cpp new file mode 100644 index 0000000..26ccbfd --- /dev/null +++ b/other/word_pattern.cpp @@ -0,0 +1,25 @@ +#include "leetcode.h" + +class Solution { +public: + bool wordPattern(string pattern, string s) { + vector patMap(26, 0); + unordered_map 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 new file mode 100644 index 0000000..6161b40 --- /dev/null +++ b/other/word_pattern.rs @@ -0,0 +1,26 @@ +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 new file mode 100644 index 0000000..bbd072f --- /dev/null +++ b/other/word_search.cpp @@ -0,0 +1,53 @@ +#include "leetcode.h" + +class Solution { +public: + bool exist(vvd(char) & board, string word) { + int dirs[5] = {0, -1, 0, 1, 0}; + map 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 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 new file mode 100644 index 0000000..8163966 --- /dev/null +++ b/other/word_search2.cpp @@ -0,0 +1,70 @@ +#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 ans; + vector findWords(vvd(char) & board, vector &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 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 words = {"abcb"}; + for (auto i : obj.findWords(board, words)) + cout << i << endl; +} diff --git a/other/word_search2.rs b/other/word_search2.rs new file mode 100644 index 0000000..2c61941 --- /dev/null +++ b/other/word_search2.rs @@ -0,0 +1,59 @@ +#[derive(Default)] +struct Solution; + +struct Trie { + child: [Option>; 26], + is_end: bool +} + +impl Solution { + pub fn find_words(board: Vec>, words: Vec) -> Vec { + 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>, trie: &mut Trie, pos: (usize, usize), s: &mut String, ans: &mut Vec) { + 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 new file mode 100644 index 0000000..d053375 --- /dev/null +++ b/other/word_subsets.cpp @@ -0,0 +1,57 @@ +// 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 wordSubsets(vector &words1, vector &words2) { + vector 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 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 counter(string &word) { + vector cnt(26); + for (char c : word) + cnt[c - 'a']++; + return cnt; + } +}; + +int main() { + Solution obj; + vector w11 = {"amazon", "apple", "facebook", "google", "leetcode"}, + w21 = {"e", "o"}; + vector w12 = {"amazon", "apple", "facebook", "google", "leetcode"}, + w22 = {"l", "e"}; + vector 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 new file mode 100644 index 0000000..f7e6b74 --- /dev/null +++ b/other/zigzag_conversion.cpp @@ -0,0 +1,43 @@ +// 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/out_of_bounds_paths.cpp b/out_of_bounds_paths.cpp deleted file mode 100644 index af5ce3f..0000000 --- a/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> curr(m + 2, vector(n + 2)); - vector> last(m + 2, vector(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/pacific_atlantic_water_flow.cpp b/pacific_atlantic_water_flow.cpp deleted file mode 100644 index 8876d9f..0000000 --- a/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(m)), flag2(n, vector(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/paint_house3.cpp b/paint_house3.cpp deleted file mode 100644 index 1185109..0000000 --- a/paint_house3.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minCost(vector &houses, vector> &cost, int m, int n, - int target) { - int INF = 1000000; - vector>> dp( - m, vector>(target + 1, vector(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/painting_grid_three_colour.cpp b/painting_grid_three_colour.cpp deleted file mode 100644 index 11fb014..0000000 --- a/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 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 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 &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/painting_walls.cpp b/painting_walls.cpp deleted file mode 100644 index 5f70012..0000000 --- a/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 &cost, vector &time) { - this->n = cost.size(); - vvd memo(n, vector(n + 1)); - this->cost = cost; - this->time = time; - return dfs(0, n, memo); - } - -private: - int memo[501][501]; - vector cost; - vector 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 c1 = {1, 2, 3, 2}, c2 = {2, 3, 4, 2}; - vector 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/pairs_spells_potions.cpp b/pairs_spells_potions.cpp deleted file mode 100644 index 255b4a0..0000000 --- a/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 successfulPairs(vector &spells, vector &potions, - long long success) { - int m = potions.size(); - vector 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 s1 = {5, 1, 3}, s2 = {3, 1, 2}; - vector 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/palindrome_linked_list.cpp b/palindrome_linked_list.cpp deleted file mode 100644 index 1b08a0c..0000000 --- a/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/palindrome_number.rs b/palindrome_number.rs deleted file mode 100644 index bd3c641..0000000 --- a/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/palindrome_pairs.cpp b/palindrome_pairs.cpp deleted file mode 100644 index 8048069..0000000 --- a/palindrome_pairs.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vvd palindromePairs(vector &words) { - unordered_map 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/palindrome_partitioning.cpp b/palindrome_partitioning.cpp deleted file mode 100644 index 6a49703..0000000 --- a/palindrome_partitioning.cpp +++ /dev/null @@ -1,50 +0,0 @@ -// 131. Palindrome Partitioning -#include "leetcode.h" -#include - -/* - * 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 path; - dfs(0, s, path, ans); - return ans; - } - -private: - void dfs(int idx, string &s, vector &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/parallel_courses3.cpp b/parallel_courses3.cpp deleted file mode 100644 index 70e50e3..0000000 --- a/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 &time) { - vector 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 finish_time(n + 1); - queue 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 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/partition_array_max_sum.cpp b/partition_array_max_sum.cpp deleted file mode 100644 index 98efe07..0000000 --- a/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 &arr, int k) { - int n = arr.size(); - vector 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 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/partition_array_pivot.rs b/partition_array_pivot.rs deleted file mode 100644 index 8a126da..0000000 --- a/partition_array_pivot.rs +++ /dev/null @@ -1,32 +0,0 @@ -struct Solution; - -impl Solution { - pub fn pivot_array(nums: Vec, pivot: i32) -> Vec { - 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/partition_list.cpp b/partition_list.cpp deleted file mode 100644 index b2e44a9..0000000 --- a/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/partition_min_binary_array.cpp b/partition_min_binary_array.cpp deleted file mode 100644 index 8cec267..0000000 --- a/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/pascals_triangle.cpp b/pascals_triangle.cpp deleted file mode 100644 index 343c116..0000000 --- a/pascals_triangle.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector> generate(int numRows) { - vector> ans(numRows); - for (int i = 0; i < numRows; i++) { - vector 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/path_max_probability.cpp b/path_max_probability.cpp deleted file mode 100644 index 467829e..0000000 --- a/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 &succ_prob, - int start, int end) { - vector>> 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 seen(n, 0); - priority_queue> pqp; - pqp.push({(double)1.0, start}); - vector 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 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/path_min_effort.cpp b/path_min_effort.cpp deleted file mode 100644 index 0b93590..0000000 --- a/path_min_effort.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minimumEffortPath(vector> &heights) { - int m = heights.size(), n = heights[0].size(); - int dirs[5] = {-1, 0, 1, 0, -1}; - vector> efforts(m, vector(n, INT_MAX)); - priority_queue, vector>, - greater>> - 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/path_min_effort1.cpp b/path_min_effort1.cpp deleted file mode 100644 index d9066cd..0000000 --- a/path_min_effort1.cpp +++ /dev/null @@ -1,42 +0,0 @@ -#include "leetcode.h" -#include -#include -#include -#include -#include -#include - -class Solution { - const int d4x[4] = {-1, 0, 1, 0}, d4y[4] = {0, 1, 0, -1}; - -public: - int minimumEffortPath(vector> &heights) { - int n = heights.size(), m = heights[0].size(); - priority_queue, vector>, - greater>> - pq; - vector> dis(n, vector(m, INT_MAX)); - dis[0][0] = 0; - pq.push({0, {0, 0}}); - while (!pq.empty()) { - pair> 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/path_sum.cpp b/path_sum.cpp deleted file mode 100644 index 41498ca..0000000 --- a/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> 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/path_sum2.cpp b/path_sum2.cpp deleted file mode 100644 index 3ccfc65..0000000 --- a/path_sum2.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vvd pathSum(TreeNode *root, int targetSum) { - vvd ans; - vector d; - dfs(root, targetSum, d, ans); - return ans; - } - -private: - void dfs(TreeNode *root, int targetSum, vector 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/peak_idx_mountain_arr.cpp b/peak_idx_mountain_arr.cpp deleted file mode 100644 index 2900091..0000000 --- a/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 &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 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/peeking_iterator.cpp b/peeking_iterator.cpp deleted file mode 100644 index 1c4d0b9..0000000 --- a/peeking_iterator.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "leetcode.h" - -class Iterator { - struct Data; - Data *data; - -public: - Iterator(const vector &nums); - Iterator(const Iterator &iter); - int next(); - bool hasNext() const; -}; - -class PeekingIterator : public Iterator { -public: - int nextVal; - PeekingIterator(const vector &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/percentage_letter_string.cpp b/percentage_letter_string.cpp deleted file mode 100644 index 18744ea..0000000 --- a/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/perfect_squares.cpp b/perfect_squares.cpp deleted file mode 100644 index 677c4a0..0000000 --- a/perfect_squares.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int numSquares(int n) { - vector 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/perfect_squares.rs b/perfect_squares.rs deleted file mode 100644 index 3887e40..0000000 --- a/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 = 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/permutation_in_string.cpp b/permutation_in_string.cpp deleted file mode 100644 index f4e09f3..0000000 --- a/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 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 a, vector 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/permutation_sequence.cpp b/permutation_sequence.cpp deleted file mode 100644 index a77286b..0000000 --- a/permutation_sequence.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "leetcode.h" -#include - -class Solution { -public: - vector fact; - string getPermutation(int n, int k) { int n = k - 1; } - -private: - void helper(int k) { - fact = vector(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/permutations.cpp b/permutations.cpp deleted file mode 100644 index 2e86fc0..0000000 --- a/permutations.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector> permute(vector &nums) { - vector> ans; - int idx = 0; - helper(nums, ans, idx); - return ans; - } - -private: - void helper(vector &nums, vector> &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/permutations2.cpp b/permutations2.cpp deleted file mode 100644 index 16d0162..0000000 --- a/permutations2.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector> permuteUnique(vector &nums) { - vector> ans; - helper(0, nums, ans); - return ans; - } - -private: - void helper(int i, vector &nums, vector> &ans) { - if (i == nums.size()) { - ans.emplace_back(nums); - return; - } - unordered_set 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/poor-pigs.cpp b/poor-pigs.cpp deleted file mode 100644 index 7455583..0000000 --- a/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/possible_bipartition.cpp b/possible_bipartition.cpp deleted file mode 100644 index 6dd4175..0000000 --- a/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> dislikeTable; - unordered_map colorTable; - function 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/possible_bipartition.rs b/possible_bipartition.rs deleted file mode 100644 index 13b8cf5..0000000 --- a/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>) -> bool { - let mut dmap: Vec> = 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> = 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/power_3.cpp b/power_3.cpp deleted file mode 100644 index f92e6e3..0000000 --- a/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/power_of_four.cpp b/power_of_four.cpp deleted file mode 100644 index ecf6de0..0000000 --- a/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/power_of_four.rs b/power_of_four.rs deleted file mode 100644 index f20335f..0000000 --- a/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/power_of_two.cpp b/power_of_two.cpp deleted file mode 100644 index 7e38aeb..0000000 --- a/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/predict_winner.cpp b/predict_winner.cpp deleted file mode 100644 index edf9ee3..0000000 --- a/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 &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 &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 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/prefix_suffix_search.cpp b/prefix_suffix_search.cpp deleted file mode 100644 index 67d4d4f..0000000 --- a/prefix_suffix_search.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "leetcode.h" - -class WordFilter { -public: - WordFilter(vector &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 hashMap; -}; diff --git a/profitable_schemes.cpp b/profitable_schemes.cpp deleted file mode 100644 index d0f353a..0000000 --- a/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 group; - vector profit; -}; - -class Solution { - vector 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 &group, - vector &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/pseudo_palindrome_binary_tree.cpp b/pseudo_palindrome_binary_tree.cpp deleted file mode 100644 index 63b2cac..0000000 --- a/pseudo_palindrome_binary_tree.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int pseudoPalindromicPaths(TreeNode *root) { - vector v(10, 0); - dfs(root, v); - return count; - } - -private: - int count = 0; - void dfs(TreeNode *root, vector 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/push_dominoes.cpp b/push_dominoes.cpp deleted file mode 100644 index 859dad9..0000000 --- a/push_dominoes.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "leetcode.h" -#include - -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/queue_reconstruction.cpp b/queue_reconstruction.cpp deleted file mode 100644 index 17ea0ea..0000000 --- a/queue_reconstruction.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector> reconstructQueue(vector> &people) { - sort(people.begin(), people.end(), cmp); - vector> 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 &p1, vector &p2) { - if (p1[0] != p2[0]) - return p1[0] > p2[0]; - else - return p1[1] < p2[1]; - } -}; diff --git a/range_sum_bst.cpp b/range_sum_bst.cpp deleted file mode 100644 index 046aee2..0000000 --- a/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 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/range_sum_bst.rs b/range_sum_bst.rs deleted file mode 100644 index f793202..0000000 --- a/range_sum_bst.rs +++ /dev/null @@ -1,38 +0,0 @@ -#[derive(Debug, PartialEq, Eq)] -pub struct TreeNode { - pub val: i32, - pub left: Option>>, - pub right: Option>> -} - -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>>, 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/range_sum_query_2d.cpp b/range_sum_query_2d.cpp deleted file mode 100644 index 9c77900..0000000 --- a/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> sum; - NumMatrix(vector> &matrix) { - int m = matrix.size(), n = matrix[0].size(); - sum = vector>(m + 1, vector(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/range_sum_query_mutable.cpp b/range_sum_query_mutable.cpp deleted file mode 100644 index cdc0230..0000000 --- a/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 &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 &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/ransom_note.cpp b/ransom_note.cpp deleted file mode 100644 index 1a78e07..0000000 --- a/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/rectangle_area.cpp b/rectangle_area.cpp deleted file mode 100644 index fa56d94..0000000 --- a/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/rectangle_area.rs b/rectangle_area.rs deleted file mode 100644 index 4d9c013..0000000 --- a/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/rectangle_fewest_squares.cpp b/rectangle_fewest_squares.cpp deleted file mode 100644 index ef56533..0000000 --- a/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 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 dp; - key hash(vector &j) { - key r = 0; - for (int n : j) - r = (r << 4LL) + n; - return r; - } - void dfs(vector 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/reduce_array_size_half.cpp b/reduce_array_size_half.cpp deleted file mode 100644 index fd922dc..0000000 --- a/reduce_array_size_half.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minSetSize(vector &arr) { - int ans = 0, n = arr.size(), n1 = 0; - vector j; - unordered_map 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 arr = {3, 3, 3, 3, 5, 5, 5, 2, 2, 7}; - cout << obj.minSetSize(arr); -} diff --git a/reducing_dishes.cpp b/reducing_dishes.cpp deleted file mode 100644 index 3982095..0000000 --- a/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 &satisfaction) { - sort(satisfaction.begin(), satisfaction.end(), greater()); - 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 s1 = {-1, -8, 0, 5, -9}; - vector s2 = {4, 3, 2}; - vector 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/remove_adjacent_dup.cpp b/remove_adjacent_dup.cpp deleted file mode 100644 index c0cc341..0000000 --- a/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> 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/remove_adjacent_dup_str.cpp b/remove_adjacent_dup_str.cpp deleted file mode 100644 index 80b61ab..0000000 --- a/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/remove_adjacent_dup_str.rs b/remove_adjacent_dup_str.rs deleted file mode 100644 index 063cfbb..0000000 --- a/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/remove_boxes.cpp b/remove_boxes.cpp deleted file mode 100644 index 47f62a9..0000000 --- a/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 &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 &boxes) { - int n = boxes.size(); - return dfs(boxes, 0, n - 1, 0); - } -}; - -int main() { - Solution obj; - vector 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/remove_dupplicate.cpp b/remove_dupplicate.cpp deleted file mode 100644 index 2628677..0000000 --- a/remove_dupplicate.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int removeDuplicates(vector &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 nums = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4}; - cout << obj.removeDuplicates(nums); -} diff --git a/remove_dupplicate.rs b/remove_dupplicate.rs deleted file mode 100644 index c192b22..0000000 --- a/remove_dupplicate.rs +++ /dev/null @@ -1,24 +0,0 @@ -struct Solution; - -impl Solution { - pub fn remove_duplicates(nums: &mut Vec) -> 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/remove_element.cpp b/remove_element.cpp deleted file mode 100644 index 644f239..0000000 --- a/remove_element.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int removeElement(vector &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 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/remove_element.rs b/remove_element.rs deleted file mode 100644 index fec38b6..0000000 --- a/remove_element.rs +++ /dev/null @@ -1,22 +0,0 @@ -use std::convert::TryInto; -struct Solution; - -impl Solution { - pub fn remove_element(mut nums: Vec, 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/remove_max_num_edge_traverse.cpp b/remove_max_num_edge_traverse.cpp deleted file mode 100644 index 8cc215a..0000000 --- a/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 &ds, int i) { - return ds[i] < 0 ? i : ds[i] = find(ds, ds[i]); - } - int maxNumEdgesToRemove(int n, vvd & edges) { - vector 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/remove_nth_node.cpp b/remove_nth_node.cpp deleted file mode 100644 index 38f8a72..0000000 --- a/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/remove_palindromic_subsequence.cpp b/remove_palindromic_subsequence.cpp deleted file mode 100644 index cbf7182..0000000 --- a/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/remove_star_string.cpp b/remove_star_string.cpp deleted file mode 100644 index c7cbfb5..0000000 --- a/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 stk; - string ans; - vector 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/remove_stones.cpp b/remove_stones.cpp deleted file mode 100644 index f267b0c..0000000 --- a/remove_stones.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minStoneSum(vector &piles, int k) { - priority_queue 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 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/remove_stones.rs b/remove_stones.rs deleted file mode 100644 index e55eade..0000000 --- a/remove_stones.rs +++ /dev/null @@ -1,26 +0,0 @@ -use std::collections::BinaryHeap; -struct Solution; - -impl Solution { - pub fn min_stone_sum(piles: Vec, mut k: i32) -> i32 { - let mut max_heap = BinaryHeap::::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/remove_subfolder_filesystem.cpp b/remove_subfolder_filesystem.cpp deleted file mode 100644 index 5ec1813..0000000 --- a/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 removeSubfolders(vector &folder) { - sort(folder.begin(), folder.end()); - vector 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 f1 = {"/a", "/a/b", "/c/d", "/c/d/e", "/c/f"}, - rsf1 = obj.removeSubfolders(f1); - vector f2 = {"/a", "/a/b/c", "/a/b/d"}, - rsf2 = obj.removeSubfolders(f2); - vector 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/remove_substring.cpp b/remove_substring.cpp deleted file mode 100644 index a5572be..0000000 --- a/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/reorder_route_city_zero.cpp b/reorder_route_city_zero.cpp deleted file mode 100644 index 10ae61a..0000000 --- a/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(n) = {}, 0); - } - -private: - int dfs(vvd & res, vector 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/reordered_power2.cpp b/reordered_power2.cpp deleted file mode 100644 index d458052..0000000 --- a/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/reorganise_string.cpp b/reorganise_string.cpp deleted file mode 100644 index 7a42643..0000000 --- a/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 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/repeated_substring_pattern.cpp b/repeated_substring_pattern.cpp deleted file mode 100644 index 4e2d8d8..0000000 --- a/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 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/restore_array.cpp b/restore_array.cpp deleted file mode 100644 index 4f4a59a..0000000 --- a/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 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/restore_ip_addr.cpp b/restore_ip_addr.cpp deleted file mode 100644 index eba5de2..0000000 --- a/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 restoreIpAddresses(string s) { - vector ans; - string ip; - dfs(s, 0, 0, ip, ans); - return ans; - } - -private: - void dfs(string s, int start, int step, string ip, vector &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/reverse_integer.cpp b/reverse_integer.cpp deleted file mode 100644 index 14f55cd..0000000 --- a/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/reverse_linked_list.cpp b/reverse_linked_list.cpp deleted file mode 100644 index e3a1793..0000000 --- a/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/reverse_linked_list2.cpp b/reverse_linked_list2.cpp deleted file mode 100644 index dbbb261..0000000 --- a/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/reverse_string.cpp b/reverse_string.cpp deleted file mode 100644 index f5940a0..0000000 --- a/reverse_string.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - void reverseString(vector &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/reverse_string2.cpp b/reverse_string2.cpp deleted file mode 100644 index 839a26f..0000000 --- a/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/reverse_string3.cpp b/reverse_string3.cpp deleted file mode 100644 index 0cc2cf5..0000000 --- a/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/reverse_vowel_string.cpp b/reverse_vowel_string.cpp deleted file mode 100644 index aa9a039..0000000 --- a/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/reverse_vowel_string.rs b/reverse_vowel_string.rs deleted file mode 100644 index 4ae282d..0000000 --- a/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::>(); - 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/reverse_word_string.cpp b/reverse_word_string.cpp deleted file mode 100644 index 0259e04..0000000 --- a/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/reverse_word_string.rs b/reverse_word_string.rs deleted file mode 100644 index 6acc9a4..0000000 --- a/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 = 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/roman_2_int.cpp b/roman_2_int.cpp deleted file mode 100644 index 1389754..0000000 --- a/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/rotate_function.cpp b/rotate_function.cpp deleted file mode 100644 index 1bfd7f5..0000000 --- a/rotate_function.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int maxRotateFunction(vector &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 nums = {4, 3, 2, 6}; - cout << obj.maxRotateFunction(nums); -} diff --git a/rotate_image.cpp b/rotate_image.cpp deleted file mode 100644 index 10d0638..0000000 --- a/rotate_image.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - void rotate(vector> &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/rotate_image.rs b/rotate_image.rs deleted file mode 100644 index 376545d..0000000 --- a/rotate_image.rs +++ /dev/null @@ -1,27 +0,0 @@ -struct Solution; - -impl Solution { - pub fn rotate(mut matrix: Vec>) { - 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/running_sum_1d_array.cpp b/running_sum_1d_array.cpp deleted file mode 100644 index b82e0ad..0000000 --- a/running_sum_1d_array.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector runningSum(vector &nums) { - vector 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 nums = {1, 2, 3, 4}; - Solution obj; - obj.runningSum(nums); -} diff --git a/same_tree.cpp b/same_tree.cpp deleted file mode 100644 index 71c2563..0000000 --- a/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/same_tree.rs b/same_tree.rs deleted file mode 100644 index 3d94ffb..0000000 --- a/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>>; -#[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) -> (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/satisfiability_eqaulity.cpp b/satisfiability_eqaulity.cpp deleted file mode 100644 index b0a1f8b..0000000 --- a/satisfiability_eqaulity.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool equationsPossible(vector &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 equations = {"a==b", "b!=a"}; - if (obj.equationsPossible(equations)) - cout << "true"; - else - cout << "false"; -} diff --git a/scramble_string.cpp b/scramble_string.cpp deleted file mode 100644 index da6b92d..0000000 --- a/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 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/search_2d_matrix.cpp b/search_2d_matrix.cpp deleted file mode 100644 index 3d8ce04..0000000 --- a/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/search_2d_matrix2.cpp b/search_2d_matrix2.cpp deleted file mode 100644 index 9834431..0000000 --- a/search_2d_matrix2.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool searchMatrix(vector> &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/search_rotated_array.cpp b/search_rotated_array.cpp deleted file mode 100644 index 7001f32..0000000 --- a/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 &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 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/search_rotated_array2.cpp b/search_rotated_array2.cpp deleted file mode 100644 index 0054f04..0000000 --- a/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 &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 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/search_suggestion_sys.cpp b/search_suggestion_sys.cpp deleted file mode 100644 index 404c987..0000000 --- a/search_suggestion_sys.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "leetcode.h" -#include - -class Solution { -public: - vector> suggestedProducts(vector &products, - string searchWord) { - auto it = products.begin(); - sort(it, products.end()); - vector> ans; - string curr = ""; - for (char c : searchWord) { - curr += c; - vector 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/set_matrix_0.rs b/set_matrix_0.rs deleted file mode 100644 index 78c434a..0000000 --- a/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>) { - 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/set_mismatch.cpp b/set_mismatch.cpp deleted file mode 100644 index 8c216bc..0000000 --- a/set_mismatch.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector findErrorNums(vector &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/set_mismatch.rs b/set_mismatch.rs deleted file mode 100644 index b490f8e..0000000 --- a/set_mismatch.rs +++ /dev/null @@ -1,37 +0,0 @@ -struct Solution; - -impl Solution { - pub fn find_error_nums(nums: Vec) -> Vec { - 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/short_encoding_words.cpp b/short_encoding_words.cpp deleted file mode 100644 index 528191f..0000000 --- a/short_encoding_words.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int minimumLengthEncoding(vector &words) { - unordered_set 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 words = {"time", "me", "bell"}; - cout << obj.minimumLengthEncoding(words); -} diff --git a/shortest_bridge.cpp b/shortest_bridge.cpp deleted file mode 100644 index 818d384..0000000 --- a/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> 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/shortest_dist_road_addition1.cpp b/shortest_dist_road_addition1.cpp deleted file mode 100644 index deea04c..0000000 --- a/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 shortestDistanceAfterQueries(int n, - vector> &queries) { - vector ans; - unordered_map> 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 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 sdaq1 = obj.shortestDistanceAfterQueries(5, q1); - vector 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/shortest_path_alternate_color.cpp b/shortest_path_alternate_color.cpp deleted file mode 100644 index a5cf369..0000000 --- a/shortest_path_alternate_color.cpp +++ /dev/null @@ -1,56 +0,0 @@ -// 1129. Shortest Path with Alternating Colors -#include "leetcode.h" - -class Solution { -public: - vector shortestAlternatingPaths(int n, vvd & redEdges, - vvd & blueEdges) { - vector ans(n, -1), v1(n, 0), v2(n, 0); - vector>> vvp(n); - queue> 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/shortest_path_binary_matrix.cpp b/shortest_path_binary_matrix.cpp deleted file mode 100644 index fd586fe..0000000 --- a/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> &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> 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/shortest_path_grid_obstacle.cpp b/shortest_path_grid_obstacle.cpp deleted file mode 100644 index daaa361..0000000 --- a/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> togo; - togo.push_back({0, 0, k}); - vector 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/shortest_path_grid_obstacle.rs b/shortest_path_grid_obstacle.rs deleted file mode 100644 index ba35681..0000000 --- a/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>, 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/shortest_path_keys.cpp b/shortest_path_keys.cpp deleted file mode 100644 index 15ffe90..0000000 --- a/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 p; - vector keys; - int cnt; - Info(pair p, vector 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 &grid) { - pair 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 q; - vector keys_start(key_cnt, 0); - q.push(Info(start, keys_start, 0)); - int ans = -1; - vector>> vis; - for (int i = 0; i < 1 << key_cnt; i++) { - vvd tmp(m, vector(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 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/shortest_path_vis_nodes.cpp b/shortest_path_vis_nodes.cpp deleted file mode 100644 index 23d95ea..0000000 --- a/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 q; - set> 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/shortest_unsorted_subarr.cpp b/shortest_unsorted_subarr.cpp deleted file mode 100644 index 849f524..0000000 --- a/shortest_unsorted_subarr.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int findUnsortedSubarray(vector &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 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/shuffle_the_array.cpp b/shuffle_the_array.cpp deleted file mode 100644 index f7dddea..0000000 --- a/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 shuffle(vector &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 nums1 = {2, 5, 1, 3, 4, 7}; - vector nums2 = {1, 2, 3, 4, 4, 3, 2, 1}; - vector 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/similar_string_group.cpp b/similar_string_group.cpp deleted file mode 100644 index 273df4f..0000000 --- a/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 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 &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 s1 = {"tars", "rats", "arts", "star"}; - vector s2 = {"omv", "ovm"}; - printf("%d\n", obj.numSimilarGroups(s1)); - printf("%d\n", obj.numSimilarGroups(s2)); -} diff --git a/simplify_path.cpp b/simplify_path.cpp deleted file mode 100644 index 09852f3..0000000 --- a/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 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/single_element_sorted_arr.cpp b/single_element_sorted_arr.cpp deleted file mode 100644 index e9bd894..0000000 --- a/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 &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 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/single_number.cpp b/single_number.cpp deleted file mode 100644 index e9a5878..0000000 --- a/single_number.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int singleNumber(vector &nums) { - int ans; - /* - * unordered_map to track frequency - * unordered_map - * both are int in this case. - */ - unordered_map 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 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/single_number.rs b/single_number.rs deleted file mode 100644 index c724ebf..0000000 --- a/single_number.rs +++ /dev/null @@ -1,22 +0,0 @@ -struct Solution; - -impl Solution { - pub fn single_number(nums: Vec) -> 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/single_number2.cpp b/single_number2.cpp deleted file mode 100644 index 907fee0..0000000 --- a/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 &nums) { - unordered_map 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 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/single_product_array.cpp b/single_product_array.cpp deleted file mode 100644 index 262bd0e..0000000 --- a/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 &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 n1 = {-1, -2, -3, -4, 3, 2, 1}; - vector n2 = {1, 5, 0, 2, -3}; - vector 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/single_threaded_cpu.cpp b/single_threaded_cpu.cpp deleted file mode 100644 index db32185..0000000 --- a/single_threaded_cpu.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector getOrder(vvd & tasks) { - vector ans, idx(tasks.size()); - priority_queue> 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/single_threaded_cpu.rs b/single_threaded_cpu.rs deleted file mode 100644 index 4defcb7..0000000 --- a/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 { - 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 { - let mut tasks = tasks.into_iter().enumerate().map(|(idx, task)| { - Task { - enqueue_time: task[0], - processing_time: task[1], - initial_idx: idx - } - }).collect::>(); - let (mut output, mut current_time) = (vec![], 0); - let mut available_tasks: BinaryHeap = 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/skyline_problem.cpp b/skyline_problem.cpp deleted file mode 100644 index b19c87a..0000000 --- a/skyline_problem.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vvd getSkyline(vvd & buildings) { - vvd ans; - map>> mvp; - for (auto &b : buildings) { - mvp[b[0]].push_back({b[2], 0}); - mvp[b[1]].push_back({b[2], 1}); - } - multiset 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({pos, newHeight})); - } - return ans; - } -}; diff --git a/sliding_puzzle.cpp b/sliding_puzzle.cpp deleted file mode 100644 index 9b772f1..0000000 --- a/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> &board) { - string begin = "", end = "123450"; - vector> 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 vis; - vis.insert(begin); - queue> 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/sliding_window_max.cpp b/sliding_window_max.cpp deleted file mode 100644 index 8468604..0000000 --- a/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 maxSlidingWindow(vector &nums, int k) { - deque dq; - vector 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 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/smallest_num_set.cpp b/smallest_num_set.cpp deleted file mode 100644 index f05147b..0000000 --- a/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 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/smallest_string_swaps.cpp b/smallest_string_swaps.cpp deleted file mode 100644 index c521309..0000000 --- a/smallest_string_swaps.cpp +++ /dev/null @@ -1,55 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector parent; - string smallestStringWithSwaps(string s, vector> &pairs) { - parent.resize(s.length()); - map> obj; - set 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> 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/smallest_sufficient_team.cpp b/smallest_sufficient_team.cpp deleted file mode 100644 index 473e218..0000000 --- a/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 smallestSufficientTeam(vector &req_skills, - vvd(string) & people) { - int n = req_skills.size(); - unordered_map> ans; - ans.reserve(1 << n); - ans[0] = {}; - unordered_map 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 rs1 = {"java", "nodejs", "reactjs"}; - vvd(string) p1 = {{"java"}, {"nodejs"}, {"nodejs", "reactjs"}}; - vector 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/snakes_ladders.cpp b/snakes_ladders.cpp deleted file mode 100644 index 160b473..0000000 --- a/snakes_ladders.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// 909. Snakes and Ladders -#include "leetcode.h" - -typedef pair pii; -class Solution { -public: - int snakesAndLadders(vvd & board) { - int rows = board.size(), cols = board[0].size(); - int target = rows * cols, r, c, p; - vector visited(rows * cols + 1); // cells on board starting from 1 - priority_queue, greater> 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/snapshot_array.cpp b/snapshot_array.cpp deleted file mode 100644 index 42d165b..0000000 --- a/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>> vvp; - -public: - SnapshotArray(int length) { vvp = vector>>(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(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/sort_array.cpp b/sort_array.cpp deleted file mode 100644 index 655726d..0000000 --- a/sort_array.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// 912. Sort an Array -#include "leetcode.h" -#include - -class Solution { -public: - vector sortArray(vector &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 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/sort_array_parity.cpp b/sort_array_parity.cpp deleted file mode 100644 index 33f02b1..0000000 --- a/sort_array_parity.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector sortArrayByParity(vector &nums) { - /* - * important to assign vector values first: - * vector... var(size, vals) - */ - vector 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 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/sort_char_freq.cpp b/sort_char_freq.cpp deleted file mode 100644 index ea7d8af..0000000 --- a/sort_char_freq.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - string frequencySort(string s) { - unordered_map freq; - for (auto a : s) - freq[a]++; - priority_queue> pqp; - for (auto [a, f] : freq) - pqp.push({f, a}); - string ans; - pair 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/sort_char_freq.rs b/sort_char_freq.rs deleted file mode 100644 index a9d0e13..0000000 --- a/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::>(); - 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/sort_items_dependencies.cpp b/sort_items_dependencies.cpp deleted file mode 100644 index 1887d05..0000000 --- a/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> &al, int i, vector &res, - vector &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 sortItems(int n, int m, vector &group, - vvd & beforeItems) { - vector ans(n), stat(n + 2 * m), ans_tmp; - vector> 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 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/sort_matrix_diagonal.cpp b/sort_matrix_diagonal.cpp deleted file mode 100644 index 61f3486..0000000 --- a/sort_matrix_diagonal.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - unordered_map> umv; - vector> diagonalSort(vector> &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/sorted_arrary_bst.cpp b/sorted_arrary_bst.cpp deleted file mode 100644 index e859528..0000000 --- a/sorted_arrary_bst.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - TreeNode *sortedArrayToBST(vector &nums) { - int start = 0, end = nums.size() - 1; - TreeNode *root = helper(start, end, nums); - return root; - } - -private: - TreeNode *helper(int start, int end, vector &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/soup_servings.cpp b/soup_servings.cpp deleted file mode 100644 index 1733c21..0000000 --- a/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> 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/spiral_matrix.cpp b/spiral_matrix.cpp deleted file mode 100644 index d1c294b..0000000 --- a/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 spiralOrder(vvd & matrix) { - vvd dirs{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; - int rows = matrix.size(), cols = matrix[0].size(); - vector 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/spiral_matrix2.cpp b/spiral_matrix2.cpp deleted file mode 100644 index dc8dc11..0000000 --- a/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(n)); - int num = 1, row = 0, col = 0, dir = 0; - vector 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/split_array_consec_subseq.cpp b/split_array_consec_subseq.cpp deleted file mode 100644 index 622e296..0000000 --- a/split_array_consec_subseq.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool isPossible(vector &nums) { - unordered_map 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 nums = {1, 2, 3, 4, 5}; - if (obj.isPossible(nums)) - cout << "true"; - else - cout << "false"; -} diff --git a/stack_using_queues.cpp b/stack_using_queues.cpp deleted file mode 100644 index 61e2c88..0000000 --- a/stack_using_queues.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "leetcode.h" - -class MyStack { -public: - queue 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/stamping_sequence.cpp b/stamping_sequence.cpp deleted file mode 100644 index b9ba317..0000000 --- a/stamping_sequence.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector movesToStamp(string stamp, string target) { - if (stamp == target) - return {0}; - int sLen = stamp.size(), tLen = target.size() - sLen + 1, i, j; - vector 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/steps_arr_increasing.cpp b/steps_arr_increasing.cpp deleted file mode 100644 index 2beb625..0000000 --- a/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 &nums) { - int n = nums.size(), ans = 0; - vector 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 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/stone_game2.cpp b/stone_game2.cpp deleted file mode 100644 index 7ebc520..0000000 --- a/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 &piles) { - int n = piles.size(); - vvd dp(n + 1, vector(n + 1, 0)); - vector 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 p1 = {2, 7, 9, 4, 4}; - vector 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/stone_game3.cpp b/stone_game3.cpp deleted file mode 100644 index 947d65f..0000000 --- a/stone_game3.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// 1406. Stone Game III -#include - -/* - * 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/stone_game4.cpp b/stone_game4.cpp deleted file mode 100644 index 2eddb18..0000000 --- a/stone_game4.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "leetcode.h" -#include - -class Solution { -public: - int stoneGameVI(vector &aliceValues, vector &bobValues) { - vector> n; - int a = 0, b = 0, sz = aliceValues.size(); - } -}; - -int main() { - Solution obj; - vector aliceValues = {1, 3}, bobValues = {2, 1}; - cout << obj.stoneGameVI(aliceValues, bobValues); -} diff --git a/strange_printer.cpp b/strange_printer.cpp deleted file mode 100644 index 8a5dc93..0000000 --- a/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> dp(n + 1, vector(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/string_compression.cpp b/string_compression.cpp deleted file mode 100644 index 5f9b9c6..0000000 --- a/string_compression.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int compress(vector &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::iterator it, ty; - it = chars.begin() + ans.size(); - ty = chars.begin() + chars.size(); - chars.erase(it, ty); - return ans.size(); - } -}; diff --git a/string_compression.rs b/string_compression.rs deleted file mode 100644 index 1d5db7d..0000000 --- a/string_compression.rs +++ /dev/null @@ -1,38 +0,0 @@ -struct Solution; - -impl Solution { - pub fn compress(chars: &mut Vec) -> 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/string_compression2.cpp b/string_compression2.cpp deleted file mode 100644 index f4c41c8..0000000 --- a/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/string_compression2.rs b/string_compression2.rs deleted file mode 100644 index 792a0ac..0000000 --- a/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/string_without_3a3b.cpp b/string_without_3a3b.cpp deleted file mode 100644 index 738d000..0000000 --- a/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/subarr_fixed_bound.cpp b/subarr_fixed_bound.cpp deleted file mode 100644 index 658c766..0000000 --- a/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 &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 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/subarr_product_less_k.cpp b/subarr_product_less_k.cpp deleted file mode 100644 index 64cb1b4..0000000 --- a/subarr_product_less_k.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int numSubarrayProductLessThanK(vector &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 nums = {10, 5, 2, 6}; - cout << obj.numSubarrayProductLessThanK(nums, 100); -} diff --git a/subarr_sum_divisible_k.cpp b/subarr_sum_divisible_k.cpp deleted file mode 100644 index 3661c96..0000000 --- a/subarr_sum_divisible_k.cpp +++ /dev/null @@ -1,32 +0,0 @@ -// 974. Subarray Sums Divisible by K -#include "leetcode.h" -#include - -/* - * 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 &nums, int k) { - vector 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 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/substr_largest_variance.cpp b/substr_largest_variance.cpp deleted file mode 100644 index 6df445c..0000000 --- a/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 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/sum_dist_tree.cpp b/sum_dist_tree.cpp deleted file mode 100644 index 10fc449..0000000 --- a/sum_dist_tree.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector 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> tree; - vector 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/sum_dist_tree.rs b/sum_dist_tree.rs deleted file mode 100644 index d000d83..0000000 --- a/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 { - let n = n as usize; - let mut adj: Vec> = 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>) { - 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, dp: &Vec<[i32; 2]>, adj: &Vec>) { - 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/sum_even_num_queries.cpp b/sum_even_num_queries.cpp deleted file mode 100644 index a58e3b2..0000000 --- a/sum_even_num_queries.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector sumEvenAfterQueries(vector &nums, vvd & queries) { - int evenSum = 0; - for (auto x : nums) - if (x % 2 == 0) - evenSum += x; - vector 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/sum_root_leaf_num.cpp b/sum_root_leaf_num.cpp deleted file mode 100644 index d1bc9c6..0000000 --- a/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/sum_subarr_mins.cpp b/sum_subarr_mins.cpp deleted file mode 100644 index 8f90e37..0000000 --- a/sum_subarr_mins.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int sumSubarrayMins(vector &arr) { - vector 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 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/sum_subarr_mins.rs b/sum_subarr_mins.rs deleted file mode 100644 index ee28cb9..0000000 --- a/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 { - const MOD: i32 = 1e9 as i32 + 7; - let n: usize = arr.len(); - let mut stk: VecDeque = { - let mut stk: VecDeque = VecDeque::with_capacity(n); - stk.push_back(-1); - stk - }; - let mut ans: i32 = 0; - let mut dp: Vec = 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/sum_subset_xor.cpp b/sum_subset_xor.cpp deleted file mode 100644 index a3048f7..0000000 --- a/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 &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 nums = {3, 4, 5, 6, 7, 8}; - Solution obj; - cout << obj.subsetXORSum(nums); -} diff --git a/summary_ranges.cpp b/summary_ranges.cpp deleted file mode 100644 index d2feb9e..0000000 --- a/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 summaryRanges(vector &nums) { - int n = nums.size(); - vector 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 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/swap_node_linked_list.cpp b/swap_node_linked_list.cpp deleted file mode 100644 index b5ad832..0000000 --- a/swap_node_linked_list.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include -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/swap_nodes_pairs.cpp b/swap_nodes_pairs.cpp deleted file mode 100644 index 139c336..0000000 --- a/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/symmetric_tree.cpp b/symmetric_tree.cpp deleted file mode 100644 index fbd4bf3..0000000 --- a/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 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/tallest_billboard.cpp b/tallest_billboard.cpp deleted file mode 100644 index 1201823..0000000 --- a/tallest_billboard.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int tallestBillboard(vector &rods) { - unordered_map dp; - dp[0] = 0; - for (int i : rods) { - unordered_map 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 rods = {1, 2, 3, 6}; - cout << obj.tallestBillboard(rods); -} diff --git a/task_scheduler.cpp b/task_scheduler.cpp deleted file mode 100644 index 553dd5d..0000000 --- a/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 &tasks, int space) { - unordered_map 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 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/text_justification.cpp b/text_justification.cpp deleted file mode 100644 index d45bead..0000000 --- a/text_justification.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector fullJustify(vector &words, int maxWidth) { - vector 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 &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 &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/thousand_separator.cpp b/thousand_separator.cpp deleted file mode 100644 index a0493f5..0000000 --- a/thousand_separator.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "leetcode.h" -#include -#include - -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/time_base_key_val.cpp b/time_base_key_val.cpp deleted file mode 100644 index c23fb87..0000000 --- a/time_base_key_val.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "leetcode.h" - -class TimeMap { -public: - unordered_map>> 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/toeplitz_matrix.cpp b/toeplitz_matrix.cpp deleted file mode 100644 index f451196..0000000 --- a/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/toeplitz_matrix.rs b/toeplitz_matrix.rs deleted file mode 100644 index 03a46bb..0000000 --- a/toeplitz_matrix.rs +++ /dev/null @@ -1,22 +0,0 @@ -struct Solution; - -impl Solution { - pub fn is_toeplitz_matrix(matrix: Vec>) -> 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/top_k_freq_element.cpp b/top_k_freq_element.cpp deleted file mode 100644 index 343595f..0000000 --- a/top_k_freq_element.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector topKFrequent(vector &nums, int k) { - unordered_map um; - for (int n : nums) - um[n]++; - vector ans; - priority_queue> 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/top_k_freq_element.rs b/top_k_freq_element.rs deleted file mode 100644 index 82a2b03..0000000 --- a/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, k: i32) -> Vec { - 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::>(); - 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/top_k_freq_words.cpp b/top_k_freq_words.cpp deleted file mode 100644 index eaf31d5..0000000 --- a/top_k_freq_words.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include "leetcode.h" - -struct Compare { - bool operator()(pair a, pair b) { - if (a.first == b.first) - return a.second > b.second; - else - return a.first < b.first; - } -}; - -class Solution { -public: - vector topKFrequent(vector &words, int k) { - unordered_map um; - for (int i = 0; i < words.size(); i++) - um[words[i]]++; - priority_queue, vector>, Compare> - pqpvpc; - for (auto i : um) - pqpvpc.push({i.second, i.first}); - vector ans; - while (k--) { - ans.push_back(pqpvpc.top().second); - pqpvpc.pop(); - } - return ans; - } -}; diff --git a/top_k_freq_words.rs b/top_k_freq_words.rs deleted file mode 100644 index 606c237..0000000 --- a/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, k: i32) -> Vec { - let mut word_to_freq = HashMap::::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 = vec![]; - while let Some((_freq, word)) = heap.pop() { - ans.push(word); - } - ans.reverse(); - ans - } -} diff --git a/transpose_matrix.cpp b/transpose_matrix.cpp deleted file mode 100644 index b6ab293..0000000 --- a/transpose_matrix.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "leetcode.h" -#include - -class Solution { -public: - vector> transpose(vector> &matrix) { - int n = matrix.size(), m = matrix[0].size(); - vector> ans(m, vector(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> matrix; - obj.transpose(matrix); -} diff --git a/trapping_rain_water.cpp b/trapping_rain_water.cpp deleted file mode 100644 index d2ced43..0000000 --- a/trapping_rain_water.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int trap(vector &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 height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; - cout << obj.trap(height); -} diff --git a/trie_prefix.cpp b/trie_prefix.cpp deleted file mode 100644 index b56e38b..0000000 --- a/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 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/two_sum.cpp b/two_sum.cpp deleted file mode 100644 index e75565d..0000000 --- a/two_sum.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// 1. Two Sum -#include "leetcode.h" - -class Solution { -public: - vector twoSum(vector &nums, int target) { - vector ans; - unordered_map 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 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/two_sum_2.cpp b/two_sum_2.cpp deleted file mode 100644 index 55741ac..0000000 --- a/two_sum_2.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include "leetcode.h" -#include - -class Solution { -public: - vector twoSum(vector &numbers, int target) { - vector 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 numbers = {2, 7, 11, 15}; - int target = 9; - // expected output: 1,2 - obj.twoSum(numbers, target); -} diff --git a/two_sum_4.cpp b/two_sum_4.cpp deleted file mode 100644 index c25bcc9..0000000 --- a/two_sum_4.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool findTarget(TreeNode *root, int k) { - vector 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 &nums) { - if (root == NULL) - return; - order(root->left, nums); - nums.push_back(root->val); - order(root->right, nums); - } -}; diff --git a/ugly_number.cpp b/ugly_number.cpp deleted file mode 100644 index 8af53f8..0000000 --- a/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/ugly_number.rs b/ugly_number.rs deleted file mode 100644 index e356ff2..0000000 --- a/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/uncrossed_lines.cpp b/uncrossed_lines.cpp deleted file mode 100644 index c8156b1..0000000 --- a/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 &nums1, vector &nums2) { - int n = nums1.size(), m = nums2.size(); - vvd dp(n + 1, vector(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 n11 = {1, 4, 2}, n21 = {1, 2, 4}; - vector n12 = {2, 5, 1, 2, 5}, n22 = {10, 5, 2, 1, 5, 2}; - vector 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/unique_bst.cpp b/unique_bst.cpp deleted file mode 100644 index 7aefacd..0000000 --- a/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 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/unique_bst2.cpp b/unique_bst2.cpp deleted file mode 100644 index 438d9b7..0000000 --- a/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 build(int from, int to) { - vector 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 left = build(from, i - 1); - vector 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 generateTrees(int n) { return build(1, n); } -}; diff --git a/unique_morse_code_words.cpp b/unique_morse_code_words.cpp deleted file mode 100644 index 2a6280e..0000000 --- a/unique_morse_code_words.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int uniqueMorseRepresentations(vector &words) { - vector codes = { - ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", - ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", - "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; - set 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 words = {"gin", "zen", "gig", "msg"}; - cout << obj.uniqueMorseRepresentations(words); -} diff --git a/unique_num_occurrences.cpp b/unique_num_occurrences.cpp deleted file mode 100644 index 5c4871f..0000000 --- a/unique_num_occurrences.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool uniqueOccurrences(vector &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 arr = {1, 2, 2, 1, 1, 3}; - if (obj.uniqueOccurrences(arr)) - cout << "true"; - else - cout << "false"; -} diff --git a/unique_num_occurrences.rs b/unique_num_occurrences.rs deleted file mode 100644 index d29c580..0000000 --- a/unique_num_occurrences.rs +++ /dev/null @@ -1,20 +0,0 @@ -struct Solution; - -impl Solution { - pub fn unique_occurrences(arr: Vec) -> 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/unique_paths.cpp b/unique_paths.cpp deleted file mode 100644 index 053a92b..0000000 --- a/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/unique_paths2.cpp b/unique_paths2.cpp deleted file mode 100644 index fedb826..0000000 --- a/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> &obstacleGrid) { - int m = obstacleGrid.size(), n = obstacleGrid[0].size(); - vvd dp(m + 1, vector(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/unique_paths3.cpp b/unique_paths3.cpp deleted file mode 100644 index 37876fa..0000000 --- a/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/unique_paths3.rs b/unique_paths3.rs deleted file mode 100644 index b83c50e..0000000 --- a/unique_paths3.rs +++ /dev/null @@ -1,40 +0,0 @@ -struct Solution; - -impl Solution { - pub fn unique_paths_iii(mut grid: Vec>) -> 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>, 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/utf8_validation.cpp b/utf8_validation.cpp deleted file mode 100644 index 0cb96d7..0000000 --- a/utf8_validation.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool validUtf8(vector &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 data = {197, 130, 1}; - if (obj.validUtf8(data)) - cout << "true"; - else - cout << "false"; -} diff --git a/valid_anagram.cpp b/valid_anagram.cpp deleted file mode 100644 index 2c2586e..0000000 --- a/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 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/valid_arrangement_pairs.cpp b/valid_arrangement_pairs.cpp deleted file mode 100644 index 0493141..0000000 --- a/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> &adj, vector> &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> validArrangement(vector> &pairs) { - int m = pairs.size(); - unordered_map> adj; - unordered_map 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> 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/valid_number.cpp b/valid_number.cpp deleted file mode 100644 index 6395fe0..0000000 --- a/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/valid_parentheses.cpp b/valid_parentheses.cpp deleted file mode 100644 index 9bab082..0000000 --- a/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 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/valid_stack_seq.cpp b/valid_stack_seq.cpp deleted file mode 100644 index 62250db..0000000 --- a/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 &pushed, vector &popped) { - stack 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 pushed = {1, 2, 3, 4, 5}; - vector 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/valid_sudoku.cpp b/valid_sudoku.cpp deleted file mode 100644 index 0843d67..0000000 --- a/valid_sudoku.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include "leetcode.h" -#include - -class Solution { -public: - bool isValidSudoku(vvd(char) & board) { - vector> 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/valid_sudoku.rs b/valid_sudoku.rs deleted file mode 100644 index 3c2f591..0000000 --- a/valid_sudoku.rs +++ /dev/null @@ -1,27 +0,0 @@ -struct Solution; - -impl Solution { - pub fn is_valid_sudoku(board: Vec>) -> 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/validate_bst.cpp b/validate_bst.cpp deleted file mode 100644 index 0785d47..0000000 --- a/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 tree; - void inOrder(TreeNode *root) { - if (!root) - return; - inOrder(root->left); - tree.push_back(root->val); - inOrder(root->right); - } -}; diff --git a/verify_alien_dict.cpp b/verify_alien_dict.cpp deleted file mode 100644 index 009ac52..0000000 --- a/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 &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 words1 = {"hello", "leetcode"}; - vector words2 = {"word", "world", "row"}; - vector 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/vertical_order_bst.cpp b/vertical_order_bst.cpp deleted file mode 100644 index a429d4d..0000000 --- a/vertical_order_bst.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vvd verticalTraversal(TreeNode *root) { - map>> mmm; - queue>> 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 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/ways_to_paint_nx3_grid.cpp b/ways_to_paint_nx3_grid.cpp deleted file mode 100644 index b661af8..0000000 --- a/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/where_will_ball_fall.cpp b/where_will_ball_fall.cpp deleted file mode 100644 index 4195778..0000000 --- a/where_will_ball_fall.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector findBall(vvd & grid) { - int m = grid.size(), n = grid[0].size(); - vvd ugrid(m * 3, vector(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 ans; - for (auto i = 0; i < n; ++i) - ans.push_back(drop(i * 3 + 1, ugrid, m * 3, n * 3)); - return ans; - } - -private: - vector> dir{{1, 0}, {0, -1}, {0, 1}}; - int drop(int pos, vvd & ugrid, int m, int n) { - queue> 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/where_will_ball_fall.rs b/where_will_ball_fall.rs deleted file mode 100644 index 6a1bb58..0000000 --- a/where_will_ball_fall.rs +++ /dev/null @@ -1,38 +0,0 @@ -struct Solution; - -impl Solution { - pub fn find_ball(grid: Vec>) -> Vec { - 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>, 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/wiggle_subsequence.cpp b/wiggle_subsequence.cpp deleted file mode 100644 index 22376d4..0000000 --- a/wiggle_subsequence.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int wiggleMaxLength(vector &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 nums = {1, 17, 5, 10, 13, 15, 10, 5, 16, 8}; - cout << obj.wiggleMaxLength(nums); -} diff --git a/word_break.cpp b/word_break.cpp deleted file mode 100644 index aa580c9..0000000 --- a/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 &word_dict) { - if (!word_dict.size()) - return false; - vector 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 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/word_ladder.cpp b/word_ladder.cpp deleted file mode 100644 index dfe6b00..0000000 --- a/word_ladder.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - int ladderLength(string beginWord, string endWord, vector &wordList) { - unordered_set dict(wordList.begin(), wordList.end()); - queue 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 wordList = {"hot", "dot", "dog", "lot", "log", "cog"}; - cout << obj.ladderLength(beginWord, endWord, wordList); -} diff --git a/word_ladder2.cpp b/word_ladder2.cpp deleted file mode 100644 index 12cff05..0000000 --- a/word_ladder2.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - vector> findLadders(string beginWord, string endWord, - vector &wordList) { - unordered_map um; - vector> ans; - for (const auto w : wordList) - um.insert({w, INT_MAX}); - um[beginWord] = 0; - queue>> 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 wordList = {"hot", "dot", "dog", "lot", "log", "cog"}; -} diff --git a/word_pattern.cpp b/word_pattern.cpp deleted file mode 100644 index 26ccbfd..0000000 --- a/word_pattern.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "leetcode.h" - -class Solution { -public: - bool wordPattern(string pattern, string s) { - vector patMap(26, 0); - unordered_map 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/word_pattern.rs b/word_pattern.rs deleted file mode 100644 index 6161b40..0000000 --- a/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/word_search.cpp b/word_search.cpp deleted file mode 100644 index bbd072f..0000000 --- a/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 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 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/word_search2.cpp b/word_search2.cpp deleted file mode 100644 index 8163966..0000000 --- a/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 ans; - vector findWords(vvd(char) & board, vector &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 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 words = {"abcb"}; - for (auto i : obj.findWords(board, words)) - cout << i << endl; -} diff --git a/word_search2.rs b/word_search2.rs deleted file mode 100644 index 2c61941..0000000 --- a/word_search2.rs +++ /dev/null @@ -1,59 +0,0 @@ -#[derive(Default)] -struct Solution; - -struct Trie { - child: [Option>; 26], - is_end: bool -} - -impl Solution { - pub fn find_words(board: Vec>, words: Vec) -> Vec { - 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>, trie: &mut Trie, pos: (usize, usize), s: &mut String, ans: &mut Vec) { - 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/word_subsets.cpp b/word_subsets.cpp deleted file mode 100644 index d053375..0000000 --- a/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 wordSubsets(vector &words1, vector &words2) { - vector 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 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 counter(string &word) { - vector cnt(26); - for (char c : word) - cnt[c - 'a']++; - return cnt; - } -}; - -int main() { - Solution obj; - vector w11 = {"amazon", "apple", "facebook", "google", "leetcode"}, - w21 = {"e", "o"}; - vector w12 = {"amazon", "apple", "facebook", "google", "leetcode"}, - w22 = {"l", "e"}; - vector 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/zigzag_conversion.cpp b/zigzag_conversion.cpp deleted file mode 100644 index f7e6b74..0000000 --- a/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 -} -- cgit v1.2.3