From cfb08a4a088fbc30dd09208e976cc54707074294 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Wed, 19 Jul 2023 03:38:48 +0300 Subject: [PATCH] Added tasks 2600-2643 --- README.md | 55 ++++++-- .../readme.md | 1 + .../g1801_1900/s1847_closest_room/readme.md | 1 - .../readme.md | 57 ++++++++ .../readme.md | 90 +++++++++++++ .../readme.md | 93 +++++++++++++ .../s2603_collect_coins_in_a_tree/readme.md | 97 ++++++++++++++ .../readme.md | 51 +++++++ .../readme.md | 65 +++++++++ .../readme.md | 78 +++++++++++ .../s2608_shortest_cycle_in_a_graph/readme.md | 88 ++++++++++++ .../readme.md | 70 ++++++++++ .../readme.md | 68 ++++++++++ .../s2611_mice_and_cheese/readme.md | 61 +++++++++ .../readme.md | 107 +++++++++++++++ .../s2614_prime_in_diagonal/readme.md | 83 ++++++++++++ .../s2615_sum_of_distances/readme.md | 69 ++++++++++ .../readme.md | 77 +++++++++++ .../readme.md | 113 ++++++++++++++++ .../readme.md | 71 ++++++++++ .../s2619_array_prototype_last/readme.md | 51 +++++++ .../kotlin/g2601_2700/s2620_counter/readme.md | 56 ++++++++ .../kotlin/g2601_2700/s2621_sleep/readme.md | 45 +++++++ .../s2622_cache_with_time_limit/readme.md | 105 +++++++++++++++ .../kotlin/g2601_2700/s2623_memoize/readme.md | 111 +++++++++++++++ .../s2624_snail_traversal/readme.md | 77 +++++++++++ .../readme.md | 71 ++++++++++ .../readme.md | 81 +++++++++++ .../g2601_2700/s2627_debounce/readme.md | 106 +++++++++++++++ .../s2629_function_composition/readme.md | 88 ++++++++++++ .../g2601_2700/s2630_memoize_ii/readme.md | 126 ++++++++++++++++++ .../g2601_2700/s2631_group_by/readme.md | 124 +++++++++++++++++ .../readme.md | 70 ++++++++++ .../readme.md | 60 +++++++++ .../s2637_promise_time_limit/readme.md | 125 +++++++++++++++++ .../readme.md | 75 +++++++++++ .../readme.md | 76 +++++++++++ .../s2641_cousins_in_binary_tree_ii/readme.md | 118 ++++++++++++++++ .../readme.md | 95 +++++++++++++ .../s2643_row_with_maximum_ones/readme.md | 62 +++++++++ 40 files changed, 3107 insertions(+), 10 deletions(-) create mode 100644 src/main/kotlin/g2501_2600/s2600_k_items_with_the_maximum_sum/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2601_prime_subtraction_operation/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2602_minimum_operations_to_make_all_array_elements_equal/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2603_collect_coins_in_a_tree/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2605_form_smallest_number_from_two_digit_arrays/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2606_find_the_substring_with_maximum_cost/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2607_make_k_subarray_sums_equal/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2608_shortest_cycle_in_a_graph/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2609_find_the_longest_balanced_substring_of_a_binary_string/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2610_convert_an_array_into_a_2d_array_with_conditions/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2611_mice_and_cheese/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2612_minimum_reverse_operations/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2614_prime_in_diagonal/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2615_sum_of_distances/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2616_minimize_the_maximum_difference_of_pairs/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2617_minimum_number_of_visited_cells_in_a_grid/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2618_check_if_object_instance_of_class/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2619_array_prototype_last/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2620_counter/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2621_sleep/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2622_cache_with_time_limit/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2623_memoize/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2624_snail_traversal/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2625_flatten_deeply_nested_array/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2626_array_reduce_transformation/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2627_debounce/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2629_function_composition/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2630_memoize_ii/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2631_group_by/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2634_filter_elements_from_array/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2635_apply_transform_over_each_element_in_array/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2637_promise_time_limit/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2639_find_the_width_of_columns_of_a_grid/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2640_find_the_score_of_all_prefixes_of_an_array/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2641_cousins_in_binary_tree_ii/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2642_design_graph_with_shortest_path_calculator/readme.md create mode 100644 src/main/kotlin/g2601_2700/s2643_row_with_maximum_ones/readme.md diff --git a/README.md b/README.md index fe00cfc5..e69412d5 100644 --- a/README.md +++ b/README.md @@ -1816,11 +1816,48 @@ | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- -| 2598 |[Smallest Missing Non-negative Integer After Operations](src/main/kotlin/g2501_2600/s2598_smallest_missing_non_negative_integer_after_operations)| ||| +| 2643 |[Row With Maximum Ones](src/main/kotlin/g2601_2700/s2643_row_with_maximum_ones)| Easy | Array, Matrix | 530 | 100.00 +| 2642 |[Design Graph With Shortest Path Calculator](src/main/kotlin/g2601_2700/s2642_design_graph_with_shortest_path_calculator)| Hard | Design, Heap_Priority_Queue, Graph, Shortest_Path | 789 | 100.00 +| 2641 |[Cousins in Binary Tree II](src/main/kotlin/g2601_2700/s2641_cousins_in_binary_tree_ii)| Medium | Hash_Table, Tree, Binary_Tree, Depth_First_Search, Breadth_First_Search | 922 | 90.91 +| 2640 |[Find the Score of All Prefixes of an Array](src/main/kotlin/g2601_2700/s2640_find_the_score_of_all_prefixes_of_an_array)| Medium | Array, Prefix_Sum | 587 | 100.00 +| 2639 |[Find the Width of Columns of a Grid](src/main/kotlin/g2601_2700/s2639_find_the_width_of_columns_of_a_grid)| Easy | Array, Matrix | 222 | 100.00 +| 2637 |[Promise Time Limit](src/main/kotlin/g2601_2700/s2637_promise_time_limit)| Easy || 64 | 75.36 +| 2635 |[Apply Transform Over Each Element in Array](src/main/kotlin/g2601_2700/s2635_apply_transform_over_each_element_in_array)| Easy || 47 | 99.33 +| 2634 |[Filter Elements from Array](src/main/kotlin/g2601_2700/s2634_filter_elements_from_array)| Easy || 55 | 90.38 +| 2631 |[Group By](src/main/kotlin/g2601_2700/s2631_group_by)| Medium || 131 | 95.95 +| 2630 |[Memoize II](src/main/kotlin/g2601_2700/s2630_memoize_ii)| Hard || 314 | 99.39 +| 2629 |[Function Composition](src/main/kotlin/g2601_2700/s2629_function_composition)| Easy || 68 | 92.25 +| 2627 |[Debounce](src/main/kotlin/g2601_2700/s2627_debounce)| Medium || 64 | 73.92 +| 2626 |[Array Reduce Transformation](src/main/kotlin/g2601_2700/s2626_array_reduce_transformation)| Easy || 54 | 95.99 +| 2625 |[Flatten Deeply Nested Array](src/main/kotlin/g2601_2700/s2625_flatten_deeply_nested_array)| Medium || 107 | 88.76 +| 2624 |[Snail Traversal](src/main/kotlin/g2601_2700/s2624_snail_traversal)| Medium || 215 | 83.48 +| 2623 |[Memoize](src/main/kotlin/g2601_2700/s2623_memoize)| Medium || 326 | 92.92 +| 2622 |[Cache With Time Limit](src/main/kotlin/g2601_2700/s2622_cache_with_time_limit)| Medium || 59 | 86.77 +| 2621 |[Sleep](src/main/kotlin/g2601_2700/s2621_sleep)| Easy || 49 | 97.92 +| 2620 |[Counter](src/main/kotlin/g2601_2700/s2620_counter)| Easy || 53 | 91.77 +| 2619 |[Array Prototype Last](src/main/kotlin/g2601_2700/s2619_array_prototype_last)| Easy || 51 | 94.69 +| 2618 |[Check if Object Instance of Class](src/main/kotlin/g2601_2700/s2618_check_if_object_instance_of_class)| Medium || 100 | 91.86 +| 2617 |[Minimum Number of Visited Cells in a Grid](src/main/kotlin/g2601_2700/s2617_minimum_number_of_visited_cells_in_a_grid)| Hard | Array, Dynamic_Programming, Binary_Search, Stack, Union_Find, Segment_Tree, Binary_Indexed_Tree | 1255 | 100.00 +| 2616 |[Minimize the Maximum Difference of Pairs](src/main/kotlin/g2601_2700/s2616_minimize_the_maximum_difference_of_pairs)| Medium | Array, Greedy, Binary_Search | 556 | 100.00 +| 2615 |[Sum of Distances](src/main/kotlin/g2601_2700/s2615_sum_of_distances)| Medium | Array, Hash_Table, Prefix_Sum | 902 | 100.00 +| 2614 |[Prime In Diagonal](src/main/kotlin/g2601_2700/s2614_prime_in_diagonal)| Easy | Array, Math, Matrix, Number_Theory | 465 | 100.00 +| 2612 |[Minimum Reverse Operations](src/main/kotlin/g2601_2700/s2612_minimum_reverse_operations)| Hard | Array, Ordered_Set, Breadth_First_Search | 923 | 100.00 +| 2611 |[Mice and Cheese](src/main/kotlin/g2601_2700/s2611_mice_and_cheese)| Medium | Array, Sorting, Greedy, Heap_Priority_Queue | 554 | 100.00 +| 2610 |[Convert an Array Into a 2D Array With Conditions](src/main/kotlin/g2601_2700/s2610_convert_an_array_into_a_2d_array_with_conditions)| Medium | Array, Hash_Table | 240 | 88.24 +| 2609 |[Find the Longest Balanced Substring of a Binary String](src/main/kotlin/g2601_2700/s2609_find_the_longest_balanced_substring_of_a_binary_string)| Easy | String | 174 | 100.00 +| 2608 |[Shortest Cycle in a Graph](src/main/kotlin/g2601_2700/s2608_shortest_cycle_in_a_graph)| Hard | Graph, Breadth_First_Search | 1061 | 100.00 +| 2607 |[Make K-Subarray Sums Equal](src/main/kotlin/g2601_2700/s2607_make_k_subarray_sums_equal)| Medium | Array, Math, Sorting, Number_Theory | 1062 | 100.00 +| 2606 |[Find the Substring With Maximum Cost](src/main/kotlin/g2601_2700/s2606_find_the_substring_with_maximum_cost)| Medium | Array, String, Hash_Table, Dynamic_Programming | 238 | 100.00 +| 2605 |[Form Smallest Number From Two Digit Arrays](src/main/kotlin/g2601_2700/s2605_form_smallest_number_from_two_digit_arrays)| Easy | Array, Hash_Table, Enumeration | 161 | 100.00 +| 2603 |[Collect Coins in a Tree](src/main/kotlin/g2601_2700/s2603_collect_coins_in_a_tree)| Hard | Array, Tree, Graph, Topological_Sort | 986 | 100.00 +| 2602 |[Minimum Operations to Make All Array Elements Equal](src/main/kotlin/g2601_2700/s2602_minimum_operations_to_make_all_array_elements_equal)| Medium | Array, Sorting, Binary_Search, Prefix_Sum | 790 | 100.00 +| 2601 |[Prime Subtraction Operation](src/main/kotlin/g2601_2700/s2601_prime_subtraction_operation)| Medium | Array, Math, Greedy, Binary_Search, Number_Theory | 233 | 100.00 +| 2600 |[K Items With the Maximum Sum](src/main/kotlin/g2501_2600/s2600_k_items_with_the_maximum_sum)| Easy | Math, Greedy | 145 | 100.00 +| 2598 |[Smallest Missing Non-negative Integer After Operations](src/main/kotlin/g2501_2600/s2598_smallest_missing_non_negative_integer_after_operations)| Medium | Array, Hash_Table, Math, Greedy | 594 | 100.00 | 2597 |[The Number of Beautiful Subsets](src/main/kotlin/g2501_2600/s2597_the_number_of_beautiful_subsets)| Medium | Array, Dynamic_Programming, Backtracking | 194 | 100.00 -| 2596 |[Check Knight Tour Configuration](src/main/kotlin/g2501_2600/s2596_check_knight_tour_configuration)| Medium | Array, Matrix, Simulation, Depth_First_Search, Breadth_First_Search | 179 | 100.00 +| 2596 |[Check Knight Tour Configuration](src/main/kotlin/g2501_2600/s2596_check_knight_tour_configuration)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Simulation | 179 | 100.00 | 2595 |[Number of Even and Odd Bits](src/main/kotlin/g2501_2600/s2595_number_of_even_and_odd_bits)| Easy | Bit_Manipulation | 177 | 100.00 -| 2594 |[Minimum Time to Repair Cars](src/main/kotlin/g2501_2600/s2594_minimum_time_to_repair_cars)| ||| +| 2594 |[Minimum Time to Repair Cars](src/main/kotlin/g2501_2600/s2594_minimum_time_to_repair_cars)| Medium | Array, Binary_Search | 416 | 100.00 | 2593 |[Find Score of an Array After Marking All Elements](src/main/kotlin/g2501_2600/s2593_find_score_of_an_array_after_marking_all_elements)| Medium | Array, Sorting, Heap_Priority_Queue, Simulation | 738 | 100.00 | 2592 |[Maximize Greatness of an Array](src/main/kotlin/g2501_2600/s2592_maximize_greatness_of_an_array)| Medium | Array, Sorting, Greedy, Two_Pointers | 748 | 100.00 | 2591 |[Distribute Money to Maximum Children](src/main/kotlin/g2501_2600/s2591_distribute_money_to_maximum_children)| Easy | Math, Greedy | 155 | 100.00 @@ -1830,13 +1867,13 @@ | 2586 |[Count the Number of Vowel Strings in Range](src/main/kotlin/g2501_2600/s2586_count_the_number_of_vowel_strings_in_range)| Easy | Array, String | 195 | 100.00 | 2585 |[Number of Ways to Earn Points](src/main/kotlin/g2501_2600/s2585_number_of_ways_to_earn_points)| Hard | Array, Dynamic_Programming | 263 | 100.00 | 2584 |[Split the Array to Make Coprime Products](src/main/kotlin/g2501_2600/s2584_split_the_array_to_make_coprime_products)| Hard | Array, Hash_Table, Math, Number_Theory | 341 | 100.00 -| 2583 |[Kth Largest Sum in a Binary Tree](src/main/kotlin/g2501_2600/s2583_kth_largest_sum_in_a_binary_tree)| Medium | Tree, Binary_Search, Breadth_First_Search | 557 | 83.33 +| 2583 |[Kth Largest Sum in a Binary Tree](src/main/kotlin/g2501_2600/s2583_kth_largest_sum_in_a_binary_tree)| Medium | Breadth_First_Search, Tree, Binary_Search | 557 | 83.33 | 2582 |[Pass the Pillow](src/main/kotlin/g2501_2600/s2582_pass_the_pillow)| Easy | Math, Simulation | 122 | 85.71 -| 2581 |[Count Number of Possible Root Nodes](src/main/kotlin/g2501_2600/s2581_count_number_of_possible_root_nodes)| Hard | Hash_Table, Dynamic_Programming, Tree, Depth_First_Search | 1352 | 100.00 +| 2581 |[Count Number of Possible Root Nodes](src/main/kotlin/g2501_2600/s2581_count_number_of_possible_root_nodes)| Hard | Hash_Table, Dynamic_Programming, Depth_First_Search, Tree | 1352 | 100.00 | 2580 |[Count Ways to Group Overlapping Ranges](src/main/kotlin/g2501_2600/s2580_count_ways_to_group_overlapping_ranges)| Medium | Array, Sorting | 669 | 100.00 | 2579 |[Count Total Number of Colored Cells](src/main/kotlin/g2501_2600/s2579_count_total_number_of_colored_cells)| Medium | Math | 109 | 100.00 | 2578 |[Split With Minimum Sum](src/main/kotlin/g2501_2600/s2578_split_with_minimum_sum)| Easy | Math, Sorting, Greedy | 121 | 75.00 -| 2577 |[Minimum Time to Visit a Cell In a Grid](src/main/kotlin/g2501_2600/s2577_minimum_time_to_visit_a_cell_in_a_grid)| Hard | Array, Matrix, Heap_Priority_Queue, Graph, Shortest_Path, Breadth_First_Search | 1446 | 100.00 +| 2577 |[Minimum Time to Visit a Cell In a Grid](src/main/kotlin/g2501_2600/s2577_minimum_time_to_visit_a_cell_in_a_grid)| Hard | Array, Breadth_First_Search, Matrix, Heap_Priority_Queue, Graph, Shortest_Path | 1446 | 100.00 | 2576 |[Find the Maximum Number of Marked Indices](src/main/kotlin/g2501_2600/s2576_find_the_maximum_number_of_marked_indices)| Medium | Array, Sorting, Greedy, Binary_Search, Two_Pointers | 610 | 100.00 | 2575 |[Find the Divisibility Array of a String](src/main/kotlin/g2501_2600/s2575_find_the_divisibility_array_of_a_string)| Medium | Array, String, Math | 507 | 100.00 | 2574 |[Left and Right Sum Differences](src/main/kotlin/g2501_2600/s2574_left_and_right_sum_differences)| Easy | Array, Prefix_Sum | 203 | 100.00 @@ -1856,7 +1893,7 @@ | 2560 |[House Robber IV](src/main/kotlin/g2501_2600/s2560_house_robber_iv)| Medium | Array, Binary_Search | 467 | 100.00 | 2559 |[Count Vowel Strings in Ranges](src/main/kotlin/g2501_2600/s2559_count_vowel_strings_in_ranges)| Medium | Array, String, Prefix_Sum | 638 | 100.00 | 2558 |[Take Gifts From the Richest Pile](src/main/kotlin/g2501_2600/s2558_take_gifts_from_the_richest_pile)| Easy | Array, Heap_Priority_Queue, Simulation | 169 | 100.00 -| 2556 |[Disconnect Path in a Binary Matrix by at Most One Flip](src/main/kotlin/g2501_2600/s2556_disconnect_path_in_a_binary_matrix_by_at_most_one_flip)| Medium | Array, Dynamic_Programming, Matrix, Depth_First_Search, Breadth_First_Search | 571 | 100.00 +| 2556 |[Disconnect Path in a Binary Matrix by at Most One Flip](src/main/kotlin/g2501_2600/s2556_disconnect_path_in_a_binary_matrix_by_at_most_one_flip)| Medium | Array, Dynamic_Programming, Depth_First_Search, Breadth_First_Search, Matrix | 571 | 100.00 | 2555 |[Maximize Win From Two Segments](src/main/kotlin/g2501_2600/s2555_maximize_win_from_two_segments)| Medium | Array, Binary_Search, Sliding_Window | 388 | 100.00 | 2554 |[Maximum Number of Integers to Choose From a Range I](src/main/kotlin/g2501_2600/s2554_maximum_number_of_integers_to_choose_from_a_range_i)| Medium | Array, Hash_Table, Sorting, Greedy, Binary_Search | 543 | 100.00 | 2553 |[Separate the Digits in an Array](src/main/kotlin/g2501_2600/s2553_separate_the_digits_in_an_array)| Easy | Array, Simulation | 210 | 100.00 @@ -1869,7 +1906,7 @@ | 2545 |[Sort the Students by Their Kth Score](src/main/kotlin/g2501_2600/s2545_sort_the_students_by_their_kth_score)| Medium | Array, Sorting, Matrix | 442 | 100.00 | 2544 |[Alternating Digit Sum](src/main/kotlin/g2501_2600/s2544_alternating_digit_sum)| Easy | Math | 122 | 60.00 | 2543 |[Check if Point Is Reachable](src/main/kotlin/g2501_2600/s2543_check_if_point_is_reachable)| Hard | Math, Number_Theory | 134 | 100.00 -| 2542 |[Maximum Subsequence Score](src/main/kotlin/g2501_2600/s2542_maximum_subsequence_score)| Medium | Array, Sorting, Greedy, Heap_(Priority_Queue) | 780 | 81.97 +| 2542 |[Maximum Subsequence Score](src/main/kotlin/g2501_2600/s2542_maximum_subsequence_score)| Medium | Array, Sorting, Greedy, Heap_Priority_Queue | 780 | 81.97 | 2541 |[Minimum Operations to Make Array Equal II](src/main/kotlin/g2501_2600/s2541_minimum_operations_to_make_array_equal_ii)| Medium | Array, Math, Greedy | 521 | 100.00 | 2540 |[Minimum Common Value](src/main/kotlin/g2501_2600/s2540_minimum_common_value)| Easy | Array, Hash_Table, Binary_Search, Two_Pointers | 412 | 100.00 | 2538 |[Difference Between Maximum and Minimum Price Sum](src/main/kotlin/g2501_2600/s2538_difference_between_maximum_and_minimum_price_sum)| Hard | Array, Dynamic_Programming, Depth_First_Search, Tree | 1054 | 100.00 @@ -2725,7 +2762,7 @@ | 1465 |[Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts](src/main/kotlin/g1401_1500/s1465_maximum_area_of_a_piece_of_cake_after_horizontal_and_vertical_cuts)| Medium | Array, Sorting, Greedy | 418 | 50.00 | 1464 |[Maximum Product of Two Elements in an Array](src/main/kotlin/g1401_1500/s1464_maximum_product_of_two_elements_in_an_array)| Easy | Array, Sorting, Heap_Priority_Queue | 190 | 64.71 | 1463 |[Cherry Pickup II](src/main/kotlin/g1401_1500/s1463_cherry_pickup_ii)| Hard | Array, Dynamic_Programming, Matrix | 198 | 100.00 -| 1462 |[Course Schedule IV](src/main/kotlin/g1401_1500/s1462_course_schedule_iv)| Medium | Depth_First_Search, Breadth_First_Search, Graph | Sort | Sort +| 1462 |[Course Schedule IV](src/main/kotlin/g1401_1500/s1462_course_schedule_iv)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Topological_Sort | 512 | 100.00 | 1461 |[Check If a String Contains All Binary Codes of Size K](src/main/kotlin/g1401_1500/s1461_check_if_a_string_contains_all_binary_codes_of_size_k)| Medium | String, Hash_Table, Bit_Manipulation, Hash_Function, Rolling_Hash | 578 | 20.00 | 1460 |[Make Two Arrays Equal by Reversing Sub-arrays](src/main/kotlin/g1401_1500/s1460_make_two_arrays_equal_by_reversing_subarrays)| Easy | Array, Hash_Table, Sorting | 231 | 66.67 | 1458 |[Max Dot Product of Two Subsequences](src/main/kotlin/g1401_1500/s1458_max_dot_product_of_two_subsequences)| Hard | Array, Dynamic_Programming | 215 | 100.00 diff --git a/src/main/kotlin/g0901_1000/s0947_most_stones_removed_with_same_row_or_column/readme.md b/src/main/kotlin/g0901_1000/s0947_most_stones_removed_with_same_row_or_column/readme.md index 643a1a93..00b03dc7 100644 --- a/src/main/kotlin/g0901_1000/s0947_most_stones_removed_with_same_row_or_column/readme.md +++ b/src/main/kotlin/g0901_1000/s0947_most_stones_removed_with_same_row_or_column/readme.md @@ -62,6 +62,7 @@ Stones [0,0] and [1,1] cannot be removed since they do not share a row/column wi ```kotlin class Solution { private val roots = IntArray(20002) + fun removeStones(stones: Array): Int { for (stone in stones) { init(stone[0] + 1, roots) diff --git a/src/main/kotlin/g1801_1900/s1847_closest_room/readme.md b/src/main/kotlin/g1801_1900/s1847_closest_room/readme.md index a91cc963..2c0253d2 100644 --- a/src/main/kotlin/g1801_1900/s1847_closest_room/readme.md +++ b/src/main/kotlin/g1801_1900/s1847_closest_room/readme.md @@ -59,7 +59,6 @@ Query = [2,5]: Room number 3 is the only room with a size of at least 5. The ans import java.util.Arrays import java.util.TreeSet - class Solution { fun closestRoom(rooms: Array, queries: Array): IntArray { val numRoom = rooms.size diff --git a/src/main/kotlin/g2501_2600/s2600_k_items_with_the_maximum_sum/readme.md b/src/main/kotlin/g2501_2600/s2600_k_items_with_the_maximum_sum/readme.md new file mode 100644 index 00000000..f4c1ffaf --- /dev/null +++ b/src/main/kotlin/g2501_2600/s2600_k_items_with_the_maximum_sum/readme.md @@ -0,0 +1,57 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2600\. K Items With the Maximum Sum + +Easy + +There is a bag that consists of items, each item has a number `1`, `0`, or `-1` written on it. + +You are given four **non-negative** integers `numOnes`, `numZeros`, `numNegOnes`, and `k`. + +The bag initially contains: + +* `numOnes` items with `1`s written on them. +* `numZeroes` items with `0`s written on them. +* `numNegOnes` items with `-1`s written on them. + +We want to pick exactly `k` items among the available items. Return _the **maximum** possible sum of numbers written on the items_. + +**Example 1:** + +**Input:** numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2 + +**Output:** 2 + +**Explanation:** We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 2 items with 1 written on them and get a sum in a total of 2. It can be proven that 2 is the maximum possible sum. + +**Example 2:** + +**Input:** numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4 + +**Output:** 3 + +**Explanation:** We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 3 items with 1 written on them, and 1 item with 0 written on it, and get a sum in a total of 3. It can be proven that 3 is the maximum possible sum. + +**Constraints:** + +* `0 <= numOnes, numZeros, numNegOnes <= 50` +* `0 <= k <= numOnes + numZeros + numNegOnes` + +## Solution + +```kotlin +@Suppress("UNUSED_PARAMETER") +class Solution { + fun kItemsWithMaximumSum(numOnes: Int, numZeros: Int, numNegOnes: Int, k: Int): Int { + if (k <= numOnes) { + return k + } + if (k <= numOnes + numZeros) { + return numOnes + } + val remainingSum = k - (numOnes + numZeros) + return numOnes - remainingSum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2601_prime_subtraction_operation/readme.md b/src/main/kotlin/g2601_2700/s2601_prime_subtraction_operation/readme.md new file mode 100644 index 00000000..3fd379db --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2601_prime_subtraction_operation/readme.md @@ -0,0 +1,90 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2601\. Prime Subtraction Operation + +Medium + +You are given a **0-indexed** integer array `nums` of length `n`. + +You can perform the following operation as many times as you want: + +* Pick an index `i` that you haven’t picked before, and pick a prime `p` **strictly less than** `nums[i]`, then subtract `p` from `nums[i]`. + +Return _true if you can make `nums` a strictly increasing array using the above operation and false otherwise._ + +A **strictly increasing array** is an array whose each element is strictly greater than its preceding element. + +**Example 1:** + +**Input:** nums = [4,9,6,10] + +**Output:** true + +**Explanation:** In the first operation: Pick i = 0 and p = 3, and then subtract 3 from nums[0], so that nums becomes [1,9,6,10]. In the second operation: i = 1, p = 7, subtract 7 from nums[1], so nums becomes equal to [1,2,6,10]. After the second operation, nums is sorted in strictly increasing order, so the answer is true. + +**Example 2:** + +**Input:** nums = [6,8,11,12] + +**Output:** true + +**Explanation:** Initially nums is sorted in strictly increasing order, so we don't need to make any operations. + +**Example 3:** + +**Input:** nums = [5,8,3] + +**Output:** false + +**Explanation:** It can be proven that there is no way to perform operations to make nums sorted in strictly increasing order, so the answer is false. + +**Constraints:** + +* `1 <= nums.length <= 1000` +* `1 <= nums[i] <= 1000` +* `nums.length == n` + +## Solution + +```kotlin +class Solution { + private fun primesUntil(n: Int): IntArray { + if (n < 2) return intArrayOf() + val primes = IntArray(200) + val composite = BooleanArray(n + 1) + primes[0] = 2 + var added = 1 + var i = 3 + while (i <= n) { + if (composite[i]) { + i += 2 + continue + } + primes[added++] = i + var j = i * i + while (j <= n) { + composite[j] = true + j += i + } + i += 2 + } + return primes.copyOf(added) + } + + fun primeSubOperation(nums: IntArray): Boolean { + var max = 0 + for (n in nums) { + max = max.coerceAtLeast(n) + } + val primes = primesUntil(max) + var prev = 0 + for (n in nums) { + val pos = primes.binarySearch(n - prev - 1) + if (pos == -1 && n <= prev) return false + prev = n - if (pos == -1) 0 else if (pos < 0) primes[-pos - 2] else primes[pos] + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2602_minimum_operations_to_make_all_array_elements_equal/readme.md b/src/main/kotlin/g2601_2700/s2602_minimum_operations_to_make_all_array_elements_equal/readme.md new file mode 100644 index 00000000..e6f879b3 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2602_minimum_operations_to_make_all_array_elements_equal/readme.md @@ -0,0 +1,93 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2602\. Minimum Operations to Make All Array Elements Equal + +Medium + +You are given an array `nums` consisting of positive integers. + +You are also given an integer array `queries` of size `m`. For the ith query, you want to make all of the elements of `nums` equal to `queries[i]`. You can perform the following operation on the array **any** number of times: + +* **Increase** or **decrease** an element of the array by `1`. + +Return _an array_ `answer` _of size_ `m` _where_ `answer[i]` _is the **minimum** number of operations to make all elements of_ `nums` _equal to_ `queries[i]`. + +**Note** that after each query the array is reset to its original state. + +**Example 1:** + +**Input:** nums = [3,1,6,8], queries = [1,5] + +**Output:** [14,10] + +**Explanation:** For the first query we can do the following operations: +- Decrease nums[0] 2 times, so that nums = [1,1,6,8]. +- Decrease nums[2] 5 times, so that nums = [1,1,1,8]. +- Decrease nums[3] 7 times, so that nums = [1,1,1,1]. + +So the total number of operations for the first query is 2 + 5 + 7 = 14. + +For the second query we can do the following operations: +- Increase nums[0] 2 times, so that nums = [5,1,6,8]. +- Increase nums[1] 4 times, so that nums = [5,5,6,8]. +- Decrease nums[2] 1 time, so that nums = [5,5,5,8]. +- Decrease nums[3] 3 times, so that nums = [5,5,5,5]. + +So the total number of operations for the second query is 2 + 4 + 1 + 3 = 10. + +**Example 2:** + +**Input:** nums = [2,9,6,3], queries = [10] + +**Output:** [20] + +**Explanation:** We can increase each value in the array to 10. The total number of operations will be 8 + 1 + 4 + 7 = 20. + +**Constraints:** + +* `n == nums.length` +* `m == queries.length` +* 1 <= n, m <= 105 +* 1 <= nums[i], queries[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun minOperations(nums: IntArray, queries: IntArray): List { + nums.sort() + val sum = LongArray(nums.size) + sum[0] = nums[0].toLong() + for (i in 1 until nums.size) { + sum[i] = sum[i - 1] + nums[i].toLong() + } + val res: MutableList = ArrayList() + for (query in queries) { + res.add(getOperations(sum, nums, query)) + } + return res + } + + private fun getOperations(sum: LongArray, nums: IntArray, target: Int): Long { + var res: Long = 0 + val index = getIndex(nums, target) + val rightCounts = nums.size - 1 - index + if (index > 0) { + res += index.toLong() * target - sum[index - 1] + } + if (rightCounts > 0) { + res += sum[nums.size - 1] - sum[index] - rightCounts.toLong() * target + } + res += kotlin.math.abs(target - nums[index]).toLong() + return res + } + + private fun getIndex(nums: IntArray, target: Int): Int { + var index = nums.binarySearch(target) + if (index < 0) index = -(index + 1) + if (index == nums.size) --index + return index + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2603_collect_coins_in_a_tree/readme.md b/src/main/kotlin/g2601_2700/s2603_collect_coins_in_a_tree/readme.md new file mode 100644 index 00000000..b172f15f --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2603_collect_coins_in_a_tree/readme.md @@ -0,0 +1,97 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2603\. Collect Coins in a Tree + +Hard + +There exists an undirected and unrooted tree with `n` nodes indexed from `0` to `n - 1`. You are given an integer `n` and a 2D integer array edges of length `n - 1`, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given an array `coins` of size `n` where `coins[i]` can be either `0` or `1`, where `1` indicates the presence of a coin in the vertex `i`. + +Initially, you choose to start at any vertex in the tree. Then, you can perform the following operations any number of times: + +* Collect all the coins that are at a distance of at most `2` from the current vertex, or +* Move to any adjacent vertex in the tree. + +Find _the minimum number of edges you need to go through to collect all the coins and go back to the initial vertex_. + +Note that if you pass an edge several times, you need to count it into the answer several times. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/03/01/graph-2.png) + +**Input:** coins = [1,0,0,0,0,1], edges = \[\[0,1],[1,2],[2,3],[3,4],[4,5]] + +**Output:** 2 + +**Explanation:** Start at vertex 2, collect the coin at vertex 0, move to vertex 3, collect the coin at vertex 5 then move back to vertex 2. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/03/02/graph-4.png) + +**Input:** coins = [0,0,0,1,1,0,0,1], edges = \[\[0,1],[0,2],[1,3],[1,4],[2,5],[5,6],[5,7]] + +**Output:** 2 + +**Explanation:** Start at vertex 0, collect the coins at vertices 4 and 3, move to vertex 2, collect the coin at vertex 7, then move back to vertex 0. + +**Constraints:** + +* `n == coins.length` +* 1 <= n <= 3 * 104 +* `0 <= coins[i] <= 1` +* `edges.length == n - 1` +* `edges[i].length == 2` +* 0 <= ai, bi < n +* ai != bi +* `edges` represents a valid tree. + +## Solution + +```kotlin +class Solution { + private lateinit var coins: IntArray + private var n = 0 + private lateinit var graph: Array?> + private var sum = 0 + private var ret = 0 + + fun collectTheCoins(coins: IntArray, edges: Array): Int { + n = coins.size + this.coins = coins + graph = arrayOfNulls(n) + for (i in 0 until n) { + graph[i] = ArrayList() + } + for (edge in edges) { + graph[edge[0]]!!.add(edge[1]) + graph[edge[1]]!!.add(edge[0]) + } + for (coin in coins) { + sum += coin + } + dfs(0, -1) + return (2 * (ret - 1)).coerceAtLeast(0) + } + + private fun dfs(node: Int, pre: Int): Int { + var cnt = 0 + var s = 0 + for (nn in graph[node]!!) { + if (nn != pre) { + val r = dfs(nn, node) + if (r - coins[nn] > 0) cnt++ + s += r + } + } + if (pre != -1 && sum - s - coins[node] - coins[pre] > 0) { + cnt++ + } + if (cnt >= 2) { + ret++ + } + return s + coins[node] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2605_form_smallest_number_from_two_digit_arrays/readme.md b/src/main/kotlin/g2601_2700/s2605_form_smallest_number_from_two_digit_arrays/readme.md new file mode 100644 index 00000000..7b62e1c6 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2605_form_smallest_number_from_two_digit_arrays/readme.md @@ -0,0 +1,51 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2605\. Form Smallest Number From Two Digit Arrays + +Easy + +Given two arrays of **unique** digits `nums1` and `nums2`, return _the **smallest** number that contains **at least** one digit from each array_. + +**Example 1:** + +**Input:** nums1 = [4,1,3], nums2 = [5,7] + +**Output:** 15 + +**Explanation:** The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It can be proven that 15 is the smallest number we can have. + +**Example 2:** + +**Input:** nums1 = [3,5,2,6], nums2 = [3,1,7] + +**Output:** 3 + +**Explanation:** The number 3 contains the digit 3 which exists in both arrays. + +**Constraints:** + +* `1 <= nums1.length, nums2.length <= 9` +* `1 <= nums1[i], nums2[i] <= 9` +* All digits in each array are **unique**. + +## Solution + +```kotlin +class Solution { + fun minNumber(nums1: IntArray, nums2: IntArray): Int { + val set = HashSet() + var (min, min1, min2) = arrayOf(10, 10, 10) + for (num in nums1) { + min1 = minOf(min1, num) + set.add(num) + } + for (num in nums2) { + min2 = minOf(min2, num) + if (set.contains(num)) min = minOf(min, num) + } + if (min != 10) return min + return minOf(min1, min2) * 10 + maxOf(min1, min2) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2606_find_the_substring_with_maximum_cost/readme.md b/src/main/kotlin/g2601_2700/s2606_find_the_substring_with_maximum_cost/readme.md new file mode 100644 index 00000000..d1a2048b --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2606_find_the_substring_with_maximum_cost/readme.md @@ -0,0 +1,65 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2606\. Find the Substring With Maximum Cost + +Medium + +You are given a string `s`, a string `chars` of **distinct** characters and an integer array `vals` of the same length as `chars`. + +The **cost of the substring** is the sum of the values of each character in the substring. The cost of an empty string is considered `0`. + +The **value of the character** is defined in the following way: + +* If the character is not in the string `chars`, then its value is its corresponding position **(1-indexed)** in the alphabet. + * For example, the value of `'a'` is `1`, the value of `'b'` is `2`, and so on. The value of `'z'` is `26`. +* Otherwise, assuming `i` is the index where the character occurs in the string `chars`, then its value is `vals[i]`. + +Return _the maximum cost among all substrings of the string_ `s`. + +**Example 1:** + +**Input:** s = "adaa", chars = "d", vals = [-1000] + +**Output:** 2 + +**Explanation:** The value of the characters "a" and "d" is 1 and -1000 respectively. The substring with the maximum cost is "aa" and its cost is 1 + 1 = 2. It can be proven that 2 is the maximum cost. + +**Example 2:** + +**Input:** s = "abc", chars = "abc", vals = [-1,-1,-1] + +**Output:** 0 + +**Explanation:** The value of the characters "a", "b" and "c" is -1, -1, and -1 respectively. The substring with the maximum cost is the empty substring "" and its cost is 0. It can be proven that 0 is the maximum cost. + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` consist of lowercase English letters. +* `1 <= chars.length <= 26` +* `chars` consist of **distinct** lowercase English letters. +* `vals.length == chars.length` +* `-1000 <= vals[i] <= 1000` + +## Solution + +```kotlin +class Solution { + fun maximumCostSubstring(s: String, chars: String, vals: IntArray): Int { + val cost = IntArray('z' - 'a' + 1) { i -> i + 1 } + for (i in chars.indices) { + cost[chars[i] - 'a'] = vals[i] + } + + var max = 0 + var currentMax = 0 + + for (c in s) { + currentMax = maxOf(0, currentMax + cost[c - 'a']) + max = maxOf(max, currentMax) + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2607_make_k_subarray_sums_equal/readme.md b/src/main/kotlin/g2601_2700/s2607_make_k_subarray_sums_equal/readme.md new file mode 100644 index 00000000..0d8af989 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2607_make_k_subarray_sums_equal/readme.md @@ -0,0 +1,78 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2607\. Make K-Subarray Sums Equal + +Medium + +You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element. + +You can do the following operation any number of times: + +* Pick any element from `arr` and increase or decrease it by `1`. + +Return _the minimum number of operations such that the sum of each **subarray** of length_ `k` _is equal_. + +A **subarray** is a contiguous part of the array. + +**Example 1:** + +**Input:** arr = [1,4,1,3], k = 2 + +**Output:** 1 + +**Explanation:** we can do one operation on index 1 to make its value equal to 3. The array after the operation is [1,3,1,3] +- Subarray starts at index 0 is [1, 3], and its sum is 4 +- Subarray starts at index 1 is [3, 1], and its sum is 4 +- Subarray starts at index 2 is [1, 3], and its sum is 4 +- Subarray starts at index 3 is [3, 1], and its sum is 4 + +**Example 2:** + +**Input:** arr = [2,5,5,7], k = 3 + +**Output:** 5 + +**Explanation:** we can do three operations on index 0 to make its value equal to 5 and two operations on index 3 to make its value equal to 5. The array after the operations is [5,5,5,5] +- Subarray starts at index 0 is [5, 5, 5], and its sum is 15 +- Subarray starts at index 1 is [5, 5, 5], and its sum is 15 +- Subarray starts at index 2 is [5, 5, 5], and its sum is 15 +- Subarray starts at index 3 is [5, 5, 5], and its sum is 15 + +**Constraints:** + +* 1 <= k <= arr.length <= 105 +* 1 <= arr[i] <= 109 + +## Solution + +```kotlin +import java.util.ArrayList + +internal class Solution { + fun makeSubKSumEqual(arr: IntArray, k: Int): Long { + val n = arr.size + var ans: Long = 0 + val vis = IntArray(n) + var i = 0 + while (i < n) { + val list: MutableList = ArrayList() + if (vis[i] == 1) { + i++ + continue + } + while (vis[i] == 0) { + vis[i] = 1 + list.add(arr[i]) + i = (i + k) % n + } + list.sort() + for (j in list) { + ans += kotlin.math.abs(j - list[list.size / 2]).toLong() + } + i++ + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2608_shortest_cycle_in_a_graph/readme.md b/src/main/kotlin/g2601_2700/s2608_shortest_cycle_in_a_graph/readme.md new file mode 100644 index 00000000..ea71e53b --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2608_shortest_cycle_in_a_graph/readme.md @@ -0,0 +1,88 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2608\. Shortest Cycle in a Graph + +Hard + +There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1`. The edges in the graph are represented by a given 2D integer array `edges`, where edges[i] = [ui, vi] denotes an edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. + +Return _the length of the **shortest** cycle in the graph_. If no cycle exists, return `-1`. + +A cycle is a path that starts and ends at the same node, and each edge in the path is used only once. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/01/04/cropped.png) + +**Input:** n = 7, edges = \[\[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]] + +**Output:** 3 + +**Explanation:** The cycle with the smallest length is : 0 -> 1 -> 2 -> 0 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/01/04/croppedagin.png) + +**Input:** n = 4, edges = \[\[0,1],[0,2]] + +**Output:** -1 + +**Explanation:** There are no cycles in this graph. + +**Constraints:** + +* `2 <= n <= 1000` +* `1 <= edges.length <= 1000` +* `edges[i].length == 2` +* 0 <= ui, vi < n +* ui != vi +* There are no repeated edges. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + private var min = Int.MAX_VALUE + fun findShortestCycle(n: Int, edges: Array): Int { + val adj: MutableList> = ArrayList() + for (i in 0 until n) adj.add(ArrayList()) + for (edge in edges) { + adj[edge[0]].add(edge[1]) + adj[edge[1]].add(edge[0]) + } + for (i in 0 until n) { + dfs(adj, HashSet(), i) + } + return if (min == Int.MAX_VALUE) -1 else min + } + + private fun dfs(adj: List>, set: HashSet, node: Int) { + val queue: Queue = LinkedList() + set.add(node) + queue.add(intArrayOf(node, node)) + val distance = IntArray(adj.size) + distance.fill(-1) + distance[node] = 0 + while (queue.isNotEmpty()) { + val arr: IntArray = queue.poll() + val topNode = arr[0] + val from = arr[1] + for (i in adj[topNode]) { + if (i == from) continue + if (set.contains(i)) { + min = min.coerceAtMost(distance[topNode] + distance[i] + 1) + continue + } + set.add(i) + distance[i] = distance[topNode] + 1 + queue.add(intArrayOf(i, topNode)) + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2609_find_the_longest_balanced_substring_of_a_binary_string/readme.md b/src/main/kotlin/g2601_2700/s2609_find_the_longest_balanced_substring_of_a_binary_string/readme.md new file mode 100644 index 00000000..4669723b --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2609_find_the_longest_balanced_substring_of_a_binary_string/readme.md @@ -0,0 +1,70 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2609\. Find the Longest Balanced Substring of a Binary String + +Easy + +You are given a binary string `s` consisting only of zeroes and ones. + +A substring of `s` is considered balanced if **all zeroes are before ones** and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring. + +Return _the length of the longest balanced substring of_ `s`. + +A **substring** is a contiguous sequence of characters within a string. + +**Example 1:** + +**Input:** s = "01000111" + +**Output:** 6 + +**Explanation:** The longest balanced substring is "000111", which has length 6. + +**Example 2:** + +**Input:** s = "00111" + +**Output:** 4 + +**Explanation:** The longest balanced substring is "0011", which has length 4. + +**Example 3:** + +**Input:** s = "111" + +**Output:** 0 + +**Explanation:** There is no balanced substring except the empty substring, so the answer is 0. + +**Constraints:** + +* `1 <= s.length <= 50` +* `'0' <= s[i] <= '1'` + +## Solution + +```kotlin +class Solution { + fun findTheLongestBalancedSubstring(s: String): Int { + val n = s.length + var max = 0 + var countZeros = 0 + var countOnes = 0 + var temp = 0 + for (i in 0 until n) { + if (s[i] == '0') { + countOnes = 0 + countZeros++ + } + if (s[i] == '1') { + countOnes++ + temp = countZeros + if (i < n - 1 && s[i + 1] == '0') countZeros = 0 + } + if (countOnes <= temp) max = max.coerceAtLeast(countOnes) + } + return 2 * max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2610_convert_an_array_into_a_2d_array_with_conditions/readme.md b/src/main/kotlin/g2601_2700/s2610_convert_an_array_into_a_2d_array_with_conditions/readme.md new file mode 100644 index 00000000..d1912a52 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2610_convert_an_array_into_a_2d_array_with_conditions/readme.md @@ -0,0 +1,68 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2610\. Convert an Array Into a 2D Array With Conditions + +Medium + +You are given an integer array `nums`. You need to create a 2D array from `nums` satisfying the following conditions: + +* The 2D array should contain **only** the elements of the array `nums`. +* Each row in the 2D array contains **distinct** integers. +* The number of rows in the 2D array should be **minimal**. + +Return _the resulting array_. If there are multiple answers, return any of them. + +**Note** that the 2D array can have a different number of elements on each row. + +**Example 1:** + +**Input:** nums = [1,3,4,1,2,3,1] + +**Output:** [[1,3,4,2],[1,3],[1]] + +**Explanation:** We can create a 2D array that contains the following rows: - 1,3,4,2 - 1,3 - 1 All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer. It can be shown that we cannot have less than 3 rows in a valid array. + +**Example 2:** + +**Input:** nums = [1,2,3,4] + +**Output:** [[4,3,2,1]] + +**Explanation:** All elements of the array are distinct, so we can keep all of them in the first row of the 2D array. + +**Constraints:** + +* `1 <= nums.length <= 200` +* `1 <= nums[i] <= nums.length` + +## Solution + +```kotlin +class Solution { + fun findMatrix(nums: IntArray): List> { + val ans = mutableListOf>() + val map = mutableMapOf() + var max = 0 + + for (n in nums) { + val count = map.getOrDefault(n, 0) + 1 + map[n] = count + max = max.coerceAtLeast(count) + } + + repeat(max) { + val new = mutableListOf() + for (e in map) { + if (e.value != 0) { + new.add(e.key) + map[e.key] = e.value - 1 + } + } + ans.add(new) + } + + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2611_mice_and_cheese/readme.md b/src/main/kotlin/g2601_2700/s2611_mice_and_cheese/readme.md new file mode 100644 index 00000000..3aacf059 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2611_mice_and_cheese/readme.md @@ -0,0 +1,61 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2611\. Mice and Cheese + +Medium + +There are two mice and `n` different types of cheese, each type of cheese should be eaten by exactly one mouse. + +A point of the cheese with index `i` (**0-indexed**) is: + +* `reward1[i]` if the first mouse eats it. +* `reward2[i]` if the second mouse eats it. + +You are given a positive integer array `reward1`, a positive integer array `reward2`, and a non-negative integer `k`. + +Return _**the maximum** points the mice can achieve if the first mouse eats exactly_ `k` _types of cheese._ + +**Example 1:** + +**Input:** reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2 + +**Output:** 15 + +**Explanation:** In this example, the first mouse eats the 2nd (0-indexed) and the 3rd types of cheese, and the second mouse eats the 0th and the 1st types of cheese. The total points are 4 + 4 + 3 + 4 = 15. It can be proven that 15 is the maximum total points that the mice can achieve. + +**Example 2:** + +**Input:** reward1 = [1,1], reward2 = [1,1], k = 2 + +**Output:** 2 + +**Explanation:** In this example, the first mouse eats the 0th (0-indexed) and 1st types of cheese, and the second mouse does not eat any cheese. The total points are 1 + 1 = 2. It can be proven that 2 is the maximum total points that the mice can achieve. + +**Constraints:** + +* 1 <= n == reward1.length == reward2.length <= 105 +* `1 <= reward1[i], reward2[i] <= 1000` +* `0 <= k <= n` + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + fun miceAndCheese(firstReward: IntArray, seondReward: IntArray, numberOfTypesOfCheeseForFirstMouse: Int): Int { + var maximumPoints = 0 + val totalTypesOfCheese = firstReward.size + val minHeapDifferenceInRewards = PriorityQueue() + for (i in 0 until totalTypesOfCheese) { + maximumPoints += firstReward[i] + minHeapDifferenceInRewards.add(firstReward[i] - seondReward[i]) + if (minHeapDifferenceInRewards.size > numberOfTypesOfCheeseForFirstMouse) { + maximumPoints -= minHeapDifferenceInRewards.poll() + } + } + return maximumPoints + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2612_minimum_reverse_operations/readme.md b/src/main/kotlin/g2601_2700/s2612_minimum_reverse_operations/readme.md new file mode 100644 index 00000000..f7f9d5d7 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2612_minimum_reverse_operations/readme.md @@ -0,0 +1,107 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2612\. Minimum Reverse Operations + +Hard + +You are given an integer `n` and an integer `p` in the range `[0, n - 1]`. Representing a **0-indexed** array `arr` of length `n` where all positions are set to `0`'s, except position `p` which is set to `1`. + +You are also given an integer array `banned` containing some positions from the array. For the **i****th** position in `banned`, `arr[banned[i]] = 0`, and `banned[i] != p`. + +You can perform **multiple** operations on `arr`. In an operation, you can choose a **subarray** with size `k` and **reverse** the subarray. However, the `1` in `arr` should never go to any of the positions in `banned`. In other words, after each operation `arr[banned[i]]` **remains** `0`. + +_Return an array_ `ans` _where_ _for each_ `i` _from_ `[0, n - 1]`, `ans[i]` _is the **minimum** number of reverse operations needed to bring the_ `1` _to position_ `i` _in arr_, _or_ `-1` _if it is impossible_. + +* A **subarray** is a contiguous **non-empty** sequence of elements within an array. +* The values of `ans[i]` are independent for all `i`'s. +* The **reverse** of an array is an array containing the values in **reverse order**. + +**Example 1:** + +**Input:** n = 4, p = 0, banned = [1,2], k = 4 + +**Output:** [0,-1,-1,1] + +**Explanation:** + +In this case `k = 4` so there is only one possible reverse operation we can perform, which is reversing the whole array. Initially, 1 is placed at position 0 so the amount of operations we need for position 0 is `0`. We can never place a 1 on the banned positions, so the answer for positions 1 and 2 is `-1`. Finally, with one reverse operation we can bring the 1 to index 3, so the answer for position 3 is `1`. + +**Example 2:** + +**Input:** n = 5, p = 0, banned = [2,4], k = 3 + +**Output:** [0,-1,-1,-1,-1] + +**Explanation:** + +In this case the 1 is initially at position 0, so the answer for that position is `0`. We can perform reverse operations of size 3. The 1 is currently located at position 0, so we need to reverse the subarray `[0, 2]` for it to leave that position, but reversing that subarray makes position 2 have a 1, which shouldn't happen. So, we can't move the 1 from position 0, making the result for all the other positions `-1`. + +**Example 3:** + +**Input:** n = 4, p = 2, banned = [0,1,3], k = 1 + +**Output:** [-1,-1,0,-1] + +**Explanation:** In this case we can only perform reverse operations of size 1.So the 1 never changes its position. + +**Constraints:** + +* 1 <= n <= 105 +* `0 <= p <= n - 1` +* `0 <= banned.length <= n - 1` +* `0 <= banned[i] <= n - 1` +* `1 <= k <= n` +* `banned[i] != p` +* all values in `banned` are **unique** + +## Solution + +```kotlin +class Solution { + fun minReverseOperations(n: Int, p: Int, banned: IntArray, k: Int): IntArray { + val out = IntArray(n) + out.fill(-1) + for (node in banned) { + out[node] = -2 + } + var nodes: MutableList = ArrayList() + nodes.add(p) + var depth = 0 + out[p] = depth + val step = k - 1 + val nextNode2s = IntArray(n + 1) + for (i in 0 until n + 1) { + nextNode2s[i] = i + 2 + } + while (nodes.isNotEmpty()) { + depth++ + val newNodes: MutableList = ArrayList() + for (node1 in nodes) { + val loReverseStart = Math.max(node1 - step, 0) + val hiReverseStart = Math.min(node1, n - k) + val loNode2 = 2 * loReverseStart + k - 1 - node1 + val hiNode2 = 2 * hiReverseStart + k - 1 - node1 + val postHiNode2 = hiNode2 + 2 + var node2 = loNode2 + while (node2 <= hiNode2) { + val nextNode2 = nextNode2s[node2] + nextNode2s[node2] = postHiNode2 + if (node2 >= 0 && node2 < n && out[node2] == -1) { + newNodes.add(node2) + out[node2] = depth + } + node2 = nextNode2 + } + } + nodes = newNodes + } + for (i in 0 until n) { + if (out[i] == -2) { + out[i] = -1 + } + } + return out + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2614_prime_in_diagonal/readme.md b/src/main/kotlin/g2601_2700/s2614_prime_in_diagonal/readme.md new file mode 100644 index 00000000..809f5952 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2614_prime_in_diagonal/readme.md @@ -0,0 +1,83 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2614\. Prime In Diagonal + +Easy + +You are given a 0-indexed two-dimensional integer array `nums`. + +Return _the largest **prime** number that lies on at least one of the **diagonals** of_ `nums`. In case, no prime is present on any of the diagonals, return _0._ + +Note that: + +* An integer is **prime** if it is greater than `1` and has no positive integer divisors other than `1` and itself. +* An integer `val` is on one of the **diagonals** of `nums` if there exists an integer `i` for which `nums[i][i] = val` or an `i` for which `nums[i][nums.length - i - 1] = val`. + +![](https://assets.leetcode.com/uploads/2023/03/06/screenshot-2023-03-06-at-45648-pm.png) + +In the above diagram, one diagonal is **[1,5,9]** and another diagonal is **[3,5,7]**. + +**Example 1:** + +**Input:** nums = \[\[1,2,3],[5,6,7],[9,10,11]] + +**Output:** 11 + +**Explanation:** The numbers 1, 3, 6, 9, and 11 are the only numbers present on at least one of the diagonals. Since 11 is the largest prime, we return 11. + +**Example 2:** + +**Input:** nums = \[\[1,2,3],[5,17,7],[9,11,10]] + +**Output:** 17 + +**Explanation:** The numbers 1, 3, 9, 10, and 17 are all present on at least one of the diagonals. 17 is the largest prime, so we return 17. + +**Constraints:** + +* `1 <= nums.length <= 300` +* nums.length == numsi.length +* 1 <= nums[i][j] <= 4*106 + +## Solution + +```kotlin +class Solution { + fun diagonalPrime(nums: Array): Int { + var i = 0 + var j = nums[0].size - 1 + var lp = 0 + while (i < nums.size) { + val n1 = nums[i][i] + if (n1 > lp && isPrime(n1)) { + lp = n1 + } + val n2 = nums[i][j] + if (n2 > lp && isPrime(n2)) { + lp = n2 + } + i++ + j-- + } + return lp + } + + private fun isPrime(n: Int): Boolean { + if (n == 1) { + return false + } + if (n == 2 || n == 3) { + return true + } + var i = 2 + while (i <= Math.sqrt(n.toDouble())) { + if (n % i == 0) { + return false + } + i++ + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2615_sum_of_distances/readme.md b/src/main/kotlin/g2601_2700/s2615_sum_of_distances/readme.md new file mode 100644 index 00000000..b69df03c --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2615_sum_of_distances/readme.md @@ -0,0 +1,69 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2615\. Sum of Distances + +Medium + +You are given a **0-indexed** integer array `nums`. There exists an array `arr` of length `nums.length`, where `arr[i]` is the sum of `|i - j|` over all `j` such that `nums[j] == nums[i]` and `j != i`. If there is no such `j`, set `arr[i]` to be `0`. + +Return _the array_ `arr`_._ + +**Example 1:** + +**Input:** nums = [1,3,1,1,2] + +**Output:** [5,0,3,4,0] + +**Explanation:** + +When i = 0, nums[0] == nums[2] and nums[0] == nums[3]. Therefore, arr[0] = \|0 - 2\| + \|0 - 3\| = 5. + +When i = 1, arr[1] = 0 because there is no other index with value 3. + +When i = 2, nums[2] == nums[0] and nums[2] == nums[3]. Therefore, arr[2] = \|2 - 0\| + \|2 - 3\| = 3. + +When i = 3, nums[3] == nums[0] and nums[3] == nums[2]. Therefore, arr[3] = \|3 - 0\| + \|3 - 2\| = 4. + +When i = 4, arr[4] = 0 because there is no other index with value 2. + +**Example 2:** + +**Input:** nums = [0,5,3] + +**Output:** [0,0,0] + +**Explanation:** Since each element in nums is distinct, arr[i] = 0 for all i. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 0 <= nums[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun distance(nums: IntArray): LongArray { + val map = HashMap() + for (i in nums.indices) { + var temp = map[nums[i]] + if (temp == null) { + temp = LongArray(4) + map[nums[i]] = temp + } + temp[0] += i.toLong() + temp[2] += 1L + } + val ans = LongArray(nums.size) + for (i in nums.indices) { + val temp = map[nums[i]] + ans[i] += i * temp!![3] - temp[1] + temp[1] += i.toLong() + temp[3] += 1L + ans[i] += temp[0] - temp[1] - i * (temp[2] - temp[3]) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2616_minimize_the_maximum_difference_of_pairs/readme.md b/src/main/kotlin/g2601_2700/s2616_minimize_the_maximum_difference_of_pairs/readme.md new file mode 100644 index 00000000..ee36a7c6 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2616_minimize_the_maximum_difference_of_pairs/readme.md @@ -0,0 +1,77 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2616\. Minimize the Maximum Difference of Pairs + +Medium + +You are 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 **minimized**. Also, ensure no index appears more than once amongst the `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. + +**Example 1:** + +**Input:** nums = [10,1,2,7,1,3], p = 2 + +**Output:** 1 + +**Explanation:** + +The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. + +The maximum difference is max(\|nums[1] - nums[4]\|, \|nums[2] - nums[5]\|) = max(0, 1) = 1. Therefore, we return 1. + +**Example 2:** + +**Input:** nums = [4,2,1,2], p = 1 + +**Output:** 0 + +**Explanation:** + +Let the indices 1 and 3 form a pair. The difference of that pair is \|2 - 2\| = 0, which is the minimum we can attain. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 0 <= nums[i] <= 109 +* `0 <= p <= (nums.length)/2` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + private fun ispossible(nums: IntArray, p: Int, diff: Int): Boolean { + var p = p + val n = nums.size + var i = 1 + while (i < n) { + if (nums[i] - nums[i - 1] <= diff) { + p-- + i++ + } + i++ + } + return p <= 0 + } + + fun minimizeMax(nums: IntArray, p: Int): Int { + val n = nums.size + nums.sort() + var left = 0 + var right = nums[n - 1] - nums[0] + var ans = right + while (left <= right) { + val mid = left + (right - left) / 2 + if (ispossible(nums, p, mid)) { + ans = mid + right = mid - 1 + } else left = mid + 1 + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2617_minimum_number_of_visited_cells_in_a_grid/readme.md b/src/main/kotlin/g2601_2700/s2617_minimum_number_of_visited_cells_in_a_grid/readme.md new file mode 100644 index 00000000..0f5b901a --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2617_minimum_number_of_visited_cells_in_a_grid/readme.md @@ -0,0 +1,113 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2617\. Minimum Number of Visited Cells in a Grid + +Hard + +You are given a **0-indexed** `m x n` integer matrix `grid`. Your initial position is at the **top-left** cell `(0, 0)`. + +Starting from the cell `(i, j)`, you can move to one of the following cells: + +* Cells `(i, k)` with `j < k <= grid[i][j] + j` (rightward movement), or +* Cells `(k, j)` with `i < k <= grid[i][j] + i` (downward movement). + +Return _the minimum number of cells you need to visit to reach the **bottom-right** cell_ `(m - 1, n - 1)`. If there is no valid path, return `-1`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/01/25/ex1.png) + +**Input:** grid = \[\[3,4,2,1],[4,2,3,1],[2,1,0,0],[2,4,0,0]] + +**Output:** 4 + +**Explanation:** The image above shows one of the paths that visits exactly 4 cells. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/01/25/ex2.png) + +**Input:** grid = \[\[3,4,2,1],[4,2,1,1],[2,1,1,0],[3,4,1,0]] + +**Output:** 3 + +**Explanation:** The image above shows one of the paths that visits exactly 3 cells. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2023/01/26/ex3.png) + +**Input:** grid = \[\[2,1,0],[1,0,0]] + +**Output:** -1 + +**Explanation:** It can be proven that no path exists. + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* 1 <= m, n <= 105 +* 1 <= m * n <= 105 +* `0 <= grid[i][j] < m * n` +* `grid[m - 1][n - 1] == 0` + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + fun minimumVisitedCells(grid: Array): Int { + val len = Array(grid.size) { IntArray(grid[0].size) } + for (ints in len) { + ints.fill(-1) + } + val q: Queue = LinkedList() + q.add(intArrayOf(0, 0)) + len[0][0] = 1 + while (q.isNotEmpty()) { + val tmp = q.poll() + val i = tmp[0] + val j = tmp[1] + var c = 0 + for (k in Math.min(grid[0].size - 1, grid[i][j] + j) downTo j + 1) { + if (len[i][k] != -1) { + c++ + if (c > LIMIT) { + break + } + } else { + len[i][k] = len[i][j] + 1 + q.add(intArrayOf(i, k)) + } + } + if (len[grid.size - 1][grid[0].size - 1] != -1) { + return len[grid.size - 1][grid[0].size - 1] + } + c = 0 + for (k in Math.min(grid.size - 1, grid[i][j] + i) downTo i + 1) { + if (len[k][j] != -1) { + c++ + if (c > LIMIT) { + break + } + } else { + len[k][j] = len[i][j] + 1 + q.add(intArrayOf(k, j)) + } + } + if (len[grid.size - 1][grid[0].size - 1] != -1) { + return len[grid.size - 1][grid[0].size - 1] + } + } + return -1 + } + + companion object { + private const val LIMIT = 2 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2618_check_if_object_instance_of_class/readme.md b/src/main/kotlin/g2601_2700/s2618_check_if_object_instance_of_class/readme.md new file mode 100644 index 00000000..b5d128fb --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2618_check_if_object_instance_of_class/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2618\. Check if Object Instance of Class + +Medium + +Write a function that checks if a given value is an instance of a given class or superclass. For this problem, an object is considered an instance of a given class if that object has access to that class's methods. + +There are no constraints on the data types that can be passed to the function. For example, the value or the class could be `undefined`. + +**Example 1:** + +**Input:** func = () => checkIfInstanceOf(new Date(), Date) + +**Output:** true + +**Explanation:** The object returned by the Date constructor is, by definition, an instance of Date. + +**Example 2:** + +**Input:** func = () => { class Animal {}; class Dog extends Animal {}; return checkIfInstanceOf(new Dog(), Animal); } + +**Output:** true + +**Explanation:** + +class Animal {}; + +class Dog extends Animal {}; + +checkIfInstanceOf(new Dog(), Animal); // true + +Dog is a subclass of Animal. Therefore, a Dog object is an instance of both Dog and Animal. + +**Example 3:** + +**Input:** func = () => checkIfInstanceOf(Date, Date) + +**Output:** false + +**Explanation:** A date constructor cannot logically be an instance of itself. + +**Example 4:** + +**Input:** func = () => checkIfInstanceOf(5, Number) + +**Output:** true + +**Explanation:** 5 is a Number. Note that the "instanceof" keyword would return false. However, it is still considered an instance of Number because it accesses the Number methods. For example "toFixed()". + +## Solution + +```typescript +function checkIfInstanceOf(obj: any, classFunction: any): boolean { + if (obj === null || obj === undefined || typeof classFunction !== 'function') return false + + let proto = Object.getPrototypeOf(obj) + while (proto !== null) { + if (proto === classFunction.prototype) return true + proto = Object.getPrototypeOf(proto) + } + return false +} + +/** + * checkIfInstanceOf(new Date(), Date); // true + */ + +export { checkIfInstanceOf } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2619_array_prototype_last/readme.md b/src/main/kotlin/g2601_2700/s2619_array_prototype_last/readme.md new file mode 100644 index 00000000..c646e742 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2619_array_prototype_last/readme.md @@ -0,0 +1,51 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2619\. Array Prototype Last + +Easy + +Write code that enhances all arrays such that you can call the `array.last()` method on any array and it will return the last element. If there are no elements in the array, it should return `-1`. + +You may assume the array is the output of `JSON.parse`. + +**Example 1:** + +**Input:** nums = [null, {}, 3] + +**Output:** 3 + +**Explanation:** Calling nums.last() should return the last element: 3. + +**Example 2:** + +**Input:** nums = [] + +**Output:** -1 + +**Explanation:** Because there are no elements, return -1. + +**Constraints:** + +* `0 <= arr.length <= 1000` + +## Solution + +```typescript +declare global { + interface Array { + last(): T | -1 + } +} + +Array.prototype.last = function (): T | -1 { //NOSONAR + return this.length ? this.at(-1) : -1 +} + +/** + * const arr = [1, 2, 3]; + * arr.last(); // 3 + */ + +export {} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2620_counter/readme.md b/src/main/kotlin/g2601_2700/s2620_counter/readme.md new file mode 100644 index 00000000..f353ac1e --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2620_counter/readme.md @@ -0,0 +1,56 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2620\. Counter + +Easy + +Given an integer `n`, return a `counter` function. This `counter` function initially returns `n` and then returns 1 more than the previous value every subsequent time it is called (`n`, `n + 1`, `n + 2`, etc). + +**Example 1:** + +**Input:** n = 10 ["call","call","call"] + +**Output:** [10,11,12] + +**Explanation:** + +counter() = 10 // The first time counter() is called, it returns n. + +counter() = 11 // Returns 1 more than the previous time. + +counter() = 12 // Returns 1 more than the previous time. + +**Example 2:** + +**Input:** n = -2 ["call","call","call","call","call"] + +**Output:** [-2,-1,0,1,2] + +**Explanation:** counter() initially returns -2. Then increases after each sebsequent call. + +**Constraints:** + +* `-1000<= n <= 1000` +* `At most 1000 calls to counter() will be made` + +## Solution + +```typescript +function createCounter(n: number): () => number { + const fun = function () { + n++ + return n - 1 + } + return fun +} + +/** + * const counter = createCounter(10) + * counter() // 10 + * counter() // 11 + * counter() // 12 + */ + +export { createCounter } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2621_sleep/readme.md b/src/main/kotlin/g2601_2700/s2621_sleep/readme.md new file mode 100644 index 00000000..0420bd24 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2621_sleep/readme.md @@ -0,0 +1,45 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2621\. Sleep + +Easy + +Given a positive integer `millis`, write an asynchronous function that sleeps for `millis` milliseconds. It can resolve any value. + +**Example 1:** + +**Input:** millis = 100 + +**Output:** 100 + +**Explanation:** It should return a promise that resolves after 100ms. let t = Date.now(); sleep(100).then(() => { console.log(Date.now() - t); // 100 }); + +**Example 2:** + +**Input:** millis = 200 + +**Output:** 200 + +**Explanation:** It should return a promise that resolves after 200ms. + +**Constraints:** + +* `1 <= millis <= 1000` + +## Solution + +```typescript +async function sleep(millis: number): Promise { + return new Promise((resolve, reject) => { + setTimeout(resolve, millis) + }) +} + +/** + * let t = Date.now() + * sleep(100).then(() => console.log(Date.now() - t)) // 100 + */ + +export { sleep } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2622_cache_with_time_limit/readme.md b/src/main/kotlin/g2601_2700/s2622_cache_with_time_limit/readme.md new file mode 100644 index 00000000..a4621b74 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2622_cache_with_time_limit/readme.md @@ -0,0 +1,105 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2622\. Cache With Time Limit + +Medium + +Write a class that allows getting and setting key-value pairs, however a **time until expiration** is associated with each key. + +The class has three public methods: + +`set(key, value, duration)`: accepts an integer `key`, an integer `value`, and a `duration` in milliseconds. Once the `duration` has elapsed, the key should be inaccessible. The method should return `true` if the same un-expired key already exists and `false` otherwise. Both the value and duration should be overwritten if the key already exists. + +`get(key)`: if an un-expired key exists, it should return the associated value. Otherwise it should return `-1`. + +`count()`: returns the count of un-expired keys. + +**Example 1:** + +**Input:** ["TimeLimitedCache", "set", "get", "count", "get"] [[], [1, 42, 100], [1], [], [1]] [0, 0, 50, 50, 150] + +**Output:** [null, false, 42, 1, -1] + +**Explanation:** + +At t=0, the cache is constructed. + +At t=0, a key-value pair (1: 42) is added with a time limit of 100ms. The value doesn't exist so false is returned. + +At t=50, key=1 is requested and the value of 42 is returned. + +At t=50, count() is called and there is one active key in the cache. + +At t=100, key=1 expires. + +At t=150, get(1) is called but -1 is returned because the cache is empty. + +**Example 2:** + +**Input:** ["TimeLimitedCache", "set", "set", "get", "get", "get", "count"] [[], [1, 42, 50], [1, 50, 100], [1], [1], [1], []] [0, 0, 40, 50, 120, 200, 250] + +**Output:** [null, false, true, 50, 50, -1] + +**Explanation:** + +At t=0, the cache is constructed. + +At t=0, a key-value pair (1: 42) is added with a time limit of 50ms. The value doesn't exist so false is returned. + +At t=40, a key-value pair (1: 50) is added with a time limit of 100ms. A non-expired value already existed so true is returned and the old value was overwritten. + +At t=50, get(1) is called which returned 50. At t=120, get(1) is called which returned 50. + +At t=140, key=1 expires. At t=200, get(1) is called but the cache is empty so -1 is returned. + +At t=250, count() returns 0 because the cache is empty. + +**Constraints:** + +* 0 <= key <= 109 +* 0 <= value <= 109 +* `0 <= duration <= 1000` +* `total method calls will not exceed 100` + +## Solution + +```typescript +class TimeLimitedCache { + private keyMap: Map + constructor() { + this.keyMap = new Map() + } + + set(key: number, value: number, duration: number): boolean { + let existed: boolean = this.keyMap.has(key) + if (existed) clearTimeout(this.keyMap.get(key).clearRef) + + this.keyMap.set(key, { + value, + clearRef: setTimeout(() => { + this.keyMap.delete(key) + }, duration), + }) + return existed + } + + get(key: number): number { + return this.keyMap.has(key) ? this.keyMap.get(key).value : -1 + } + + count(): number { + return this.keyMap.size + } +} + +/** + * Your TimeLimitedCache object will be instantiated and called as such: + * var obj = new TimeLimitedCache() + * obj.set(1, 42, 1000); // false + * obj.get(1) // 42 + * obj.count() // 1 + */ + +export { TimeLimitedCache } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2623_memoize/readme.md b/src/main/kotlin/g2601_2700/s2623_memoize/readme.md new file mode 100644 index 00000000..984a981c --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2623_memoize/readme.md @@ -0,0 +1,111 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2623\. Memoize + +Medium + +Given a function `fn`, return a **memoized** version of that function. + +A **memoized **function is a function that will never be called twice with the same inputs. Instead it will return a cached value. + +You can assume there are **3 **possible input functions: `sum`**,** `fib`**, **and `factorial`**.** + +* `sum`accepts two integers `a` and `b` and returns `a + b`. +* `fib`accepts a single integer `n` and returns `1` if `n <= 1` or `fib(n - 1) + fib(n - 2)` otherwise. +* `factorial` accepts a single integer `n` and returns `1` if `n <= 1` or `factorial(n - 1) * n` otherwise. + +**Example 1:** + +**Input** "sum" ["call","call","getCallCount","call","getCallCount"] [[2,2],[2,2],[],[1,2],[]] + +**Output:** [4,4,1,3,2] + +**Explanation:** + +const sum = (a, b) => a + b; + +const memoizedSum = memoize(sum); + +memoizedSum(2, 2); // Returns 4. sum() was called as (2, 2) was not seen before. + +memoizedSum(2, 2); // Returns 4. However sum() was not called because the same inputs were seen before. + +// Total call count: 1 + +memoizedSum(1, 2); // Returns 3. sum() was called as (1, 2) was not seen before. + +// Total call count: 2 + +**Example 2:** + +**Input** "factorial" ["call","call","call","getCallCount","call","getCallCount"] [[2],[3],[2],[],[3],[]] + +**Output:** [2,6,2,2,6,2] + +**Explanation:** + +const factorial = (n) => (n <= 1) ? 1 : (n \* factorial(n - 1)); + +const memoFactorial = memoize(factorial); + +memoFactorial(2); // Returns 2. + +memoFactorial(3); // Returns 6. + +memoFactorial(2); // Returns 2. However factorial was not called because 2 was seen before. + +// Total call count: 2 + +memoFactorial(3); // Returns 6. However factorial was not called because 3 was seen before. + +// Total call count: 2 + +**Example 3:** + +**Input** "fib" ["call","getCallCount"] [[5],[]] + +**Output:** [8,1] + +**Explanation:** fib(5) = 8 // Total call count: 1 + +**Constraints:** + +* 0 <= a, b <= 105 +* `1 <= n <= 10` +* at most 105 function calls +* at most 105 attempts to access callCount +* `input function is sum, fib, or factorial` + +## Solution + +```typescript +type Fn = (...params: any) => any + +function memoize(fn: Fn): Fn { + const mem_args: Map = new Map() + return function (...args) { + const args_str = args.toString() + if (mem_args.has(args_str)) { + return mem_args.get(args_str) + } + + const result = fn(...args) + mem_args.set(args_str, result) + return result + } +} + +/** + * let callCount = 0; + * const memoizedFn = memoize(function (a, b) { + * callCount += 1; + * return a + b; + * }) + * memoizedFn(2, 3) // 5 + * memoizedFn(2, 3) // 5 + * console.log(callCount) // 1 + */ + +export { memoize } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2624_snail_traversal/readme.md b/src/main/kotlin/g2601_2700/s2624_snail_traversal/readme.md new file mode 100644 index 00000000..36d025cf --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2624_snail_traversal/readme.md @@ -0,0 +1,77 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2624\. Snail Traversal + +Medium + +Write code that enhances all arrays such that you can call the `snail(rowsCount, colsCount)` method that transforms the 1D array into a 2D array organised in the pattern known as **snail traversal order**. Invalid input values should output an empty array. If `rowsCount * colsCount !== nums.length`, the input is considered invalid. + +**Snail traversal order**starts at the top left cell with the first value of the current array. It then moves through the entire first column from top to bottom, followed by moving to the next column on the right and traversing it from bottom to top. This pattern continues, alternating the direction of traversal with each column, until the entire current array is covered. For example, when given the input array `[19, 10, 3, 7, 9, 8, 5, 2, 1, 17, 16, 14, 12, 18, 6, 13, 11, 20, 4, 15]` with `rowsCount = 5` and `colsCount = 4`, the desired output matrix is shown below. Note that iterating the matrix following the arrows corresponds to the order of numbers in the original array. + +![Traversal Diagram](https://assets.leetcode.com/uploads/2023/04/10/screen-shot-2023-04-10-at-100006-pm.png) + +**Example 1:** + +**Input:** nums = [19, 10, 3, 7, 9, 8, 5, 2, 1, 17, 16, 14, 12, 18, 6, 13, 11, 20, 4, 15] rowsCount = 5 colsCount = 4 + +**Output:** + +[ + [19,17,16,15], + [10,1,14,4], + [3,2,12,20], + [7,5,18,11], + [9,8,6,13] +] + +**Example 2:** + +**Input:** nums = [1,2,3,4] rowsCount = 1 colsCount = 4 + +**Output:** [[1, 2, 3, 4]] + +**Example 3:** + +**Input:** nums = [1,3] rowsCount = 2 colsCount = 2 + +**Output:** [] + +**Explanation:** 2 multiplied by 2 is 4, and the original array [1,3] has a length of 2; therefore, the input is invalid. + +**Constraints:** + +* `0 <= nums.length <= 250` +* `1 <= nums[i] <= 1000` +* `1 <= rowsCount <= 250` +* `1 <= colsCount <= 250` + +## Solution + +```typescript +declare global { + interface Array { + snail(rowsCount: number, colsCount: number): number[][] + } +} + +Array.prototype.snail = function (rowsCount: number, colsCount: number): number[][] { //NOSONAR + if (rowsCount * colsCount !== this.length) return [] + let res: number[][] = [] + for (let i = 0; i < this.length; i++) { + let col = Math.floor(i / rowsCount) + let row = i % rowsCount + row = col % 2 === 0 ? row : rowsCount - row - 1 + if (res[row] === undefined) res[row] = [] + res[row].push(this[i]) + } + return res +} + +/** + * const arr = [1,2,3,4]; + * arr.snail(1,4); // [[1,2,3,4]] + */ + +export {} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2625_flatten_deeply_nested_array/readme.md b/src/main/kotlin/g2601_2700/s2625_flatten_deeply_nested_array/readme.md new file mode 100644 index 00000000..cae7a25f --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2625_flatten_deeply_nested_array/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2625\. Flatten Deeply Nested Array + +Medium + +Given a **multi-dimensional** array `arr` and a depth `n`, return a **flattened** version of that array. + +A **multi-dimensional** array is a recursive data structure that contains integers or other **multi-dimensional** arrays. + +A **flattened** array is a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array. This flattening operation should only be done if the current depth of nesting is less than `n`. The depth of the elements in the first array are considered to be `0`. + +Please solve it without the built-in `Array.flat` method. + +**Example 1:** + +**Input** arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] n = 0 + +**Output:** [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] + +**Explanation:** Passing a depth of n=0 will always result in the original array. This is because the smallest possible depth of a subarray (0) is not less than n=0. Thus, no subarray should be flattened. + +**Example 2:** + +**Input** arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] n = 1 + +**Output:** [1, 2, 3, 4, 5, 6, 7, 8, [9, 10, 11], 12, 13, 14, 15] + +**Explanation:** The subarrays starting with 4, 7, and 13 are all flattened. This is because their depth of 0 is less than 1. However [9, 10, 11] remains unflattened because its depth is 1. + +**Example 3:** + +**Input** arr = \[\[1, 2, 3], [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] n = 2 + +**Output:** [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + +**Explanation:** The maximum depth of any subarray is 1. Thus, all of them are flattened. + +**Constraints:** + +* 0 <= count of numbers in arr <= 105 +* 0 <= count of subarrays in arr <= 105 +* `maxDepth <= 1000` +* `-1000 <= each number <= 1000` +* `0 <= n <= 1000` + +## Solution + +```typescript +type MultiDimensionalArray = (number | MultiDimensionalArray)[] + +const flat = (arr: MultiDimensionalArray, depth: number): MultiDimensionalArray => { + const result: MultiDimensionalArray = [] + + const flatten = (nestedArray: MultiDimensionalArray, currentDepth: number) => { + for (const element of nestedArray) { + if (Array.isArray(element) && currentDepth > 0 && currentDepth <= depth) { + flatten(element, currentDepth - 1) + } else { + result.push(element) + } + } + } + + flatten(arr, depth) + return result +} + +export { flat } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2626_array_reduce_transformation/readme.md b/src/main/kotlin/g2601_2700/s2626_array_reduce_transformation/readme.md new file mode 100644 index 00000000..bc0e44fb --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2626_array_reduce_transformation/readme.md @@ -0,0 +1,81 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2626\. Array Reduce Transformation + +Easy + +Given an integer array `nums`, a reducer function `fn`, and an initial value `init`, return a **reduced** array. + +A **reduced** array is created by applying the following operation: `val = fn(init, nums[0])`, `val = fn(val, nums[1])`, `val = fn(val, nums[2])`, `...` until every element in the array has been processed. The final value of `val` is returned. + +If the length of the array is 0, it should return `init`. + +Please solve it without using the built-in `Array.reduce` method. + +**Example 1:** + +**Input:** nums = [1,2,3,4] fn = function sum(accum, curr) { return accum + curr; } init = 0 + +**Output:** 10 + +**Explanation:** initially, the value is init=0. + +(0) + nums[0] = 1 + +(1) + nums[1] = 3 + +(3) + nums[2] = 6 + +(6) + nums[3] = 10 + +The final answer is 10. + +**Example 2:** + +**Input:** nums = [1,2,3,4] fn = function sum(accum, curr) { return accum + curr \* curr; } init = 100 + +**Output:** 130 + +**Explanation:** initially, the value is init=100. + +(100) + nums[0]^2 = 101 + +(101) + nums[1]^2 = 105 + +(105) + nums[2]^2 = 114 + +(114) + nums[3]^2 = 130 + +The final answer is 130. + +**Example 3:** + +**Input:** nums = [] fn = function sum(accum, curr) { return 0; } init = 25 + +**Output:** 25 + +**Explanation:** For empty arrays, the answer is always init. + +**Constraints:** + +* `0 <= nums.length <= 1000` +* `0 <= nums[i] <= 1000` +* `0 <= init <= 1000` + +## Solution + +```typescript +type Fn = (accum: number, curr: number) => number + +function reduce(nums: number[], fn: Fn, init: number): number { + let accumulator = init + nums.forEach((num) => { + accumulator = fn(accumulator, num) + }) + + return accumulator +} + +export { reduce } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2627_debounce/readme.md b/src/main/kotlin/g2601_2700/s2627_debounce/readme.md new file mode 100644 index 00000000..be864a86 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2627_debounce/readme.md @@ -0,0 +1,106 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2627\. Debounce + +Medium + +Given a function `fn` and a time in milliseconds `t`, return a **debounced** version of that function. + +A **debounced** function is a function whose execution is delayed by `t` milliseconds and whose execution is cancelled if it is called again within that window of time. The debounced function should also receive the passed parameters. + +For example, let's say `t = 50ms`, and the function was called at `30ms`, `60ms`, and `100ms`. The first 2 function calls would be cancelled, and the 3rd function call would be executed at `150ms`. If instead `t = 35ms`, The 1st call would be cancelled, the 2nd would be executed at `95ms`, and the 3rd would be executed at `135ms`. + +![Debounce Schematic](https://assets.leetcode.com/uploads/2023/04/08/screen-shot-2023-04-08-at-11048-pm.png) + +The above diagram shows how debounce will transform events. Each rectangle represents 100ms and the debounce time is 400ms. Each color represents a different set of inputs. + +Please solve it without using lodash's `_.debounce()` function. + +**Example 1:** + +**Input:** t = 50 calls = [ {"t": 50, inputs: [1]}, {"t": 75, inputs: [2]} ] + +**Output:** [{"t": 125, inputs: [2]}] + +**Explanation:** + + let start = Date.now(); + + function log(...inputs) { + console.log([Date.now() - start, inputs ]) + } + const dlog = debounce(log, 50); + setTimeout(() => dlog(1), 50); + setTimeout(() => dlog(2), 75); + +The 1st call is cancelled by the 2nd call because the 2nd call occurred before 100ms + +The 2nd call is delayed by 50ms and executed at 125ms. The inputs were (2). + +**Example 2:** + +**Input:** + + t = 20 + calls = [ + {"t": 50, inputs: [1]}, + {"t": 100, inputs: [2]} + ] + +**Output:** [{"t": 70, inputs: [1]}, {"t": 120, inputs: [2]}] + +**Explanation:** The 1st call is delayed until 70ms. The inputs were (1). The 2nd call is delayed until 120ms. The inputs were (2). + +**Example 3:** + +**Input:** + + t = 150 + calls = [ + {"t": 50, inputs: [1, 2]}, + {"t": 300, inputs: [3, 4]}, + {"t": 300, inputs: [5, 6]} + ] + +**Output:** [{"t": 200, inputs: [1,2]}, {"t": 450, inputs: [5, 6]}] + +**Explanation:** + +The 1st call is delayed by 150ms and ran at 200ms. The inputs were (1, 2). + +The 2nd call is cancelled by the 3rd call + +The 3rd call is delayed by 150ms and ran at 450ms. The inputs were (5, 6). + +**Constraints:** + +* `0 <= t <= 1000` +* `1 <= calls.length <= 10` +* `0 <= calls[i].t <= 1000` +* `0 <= calls[i].inputs.length <= 10` + +## Solution + +```typescript +type F = (...p: any[]) => any + +function debounce(fn: F, t: number): F { + let ref = null + return function (...args) { + if (ref !== null) { + clearTimeout(ref) + } + ref = setTimeout(() => fn(...args), t) + } +} + +/** + * const log = debounce(console.log, 100); + * log('Hello'); // cancelled + * log('Hello'); // cancelled + * log('Hello'); // Logged at t=100ms + */ + +export { debounce } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2629_function_composition/readme.md b/src/main/kotlin/g2601_2700/s2629_function_composition/readme.md new file mode 100644 index 00000000..0723a25f --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2629_function_composition/readme.md @@ -0,0 +1,88 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2629\. Function Composition + +Easy + +Given an array of functions [f1, f2, f3, ..., fn], return a new function `fn` that is the **function composition** of the array of functions. + +The **function composition** of `[f(x), g(x), h(x)]` is `fn(x) = f(g(h(x)))`. + +The **function composition** of an empty list of functions is the **identity function** `f(x) = x`. + +You may assume each function in the array accepts one integer as input and returns one integer as output. + +**Example 1:** + +**Input:** functions = [x => x + 1, x => x * x, x => 2 * x], x = 4 + +**Output:** 65 + +**Explanation:** + +Evaluating from right to left ... + +Starting with x = 4. + +2 * (4) = 8 + +(8) * (8) = 64 + +(64) + 1 = 65 + +**Example 2:** + +**Input:** functions = [x => 10 * x, x => 10 * x, x => 10 * x], x = 1 + +**Output:** 1000 + +**Explanation:** + +Evaluating from right to left ... + +10 * (1) = 10 + +10 * (10) = 100 + +10 * (100) = 1000 + +**Example 3:** + +**Input:** functions = [], x = 42 + +**Output:** 42 + +**Explanation:** The composition of zero functions is the identity function + +**Constraints:** + +* `-1000 <= x <= 1000` +* `0 <= functions.length <= 1000` +* `all functions accept and return a single integer` + +## Solution + +```typescript +type F = (x: number) => number + +function compose(functions: F[]): F { + const n = functions.length + + return function (x) { + for (let i = n - 1; i >= 0; i--) { + const fn = functions[i] + x = fn(x) + } + + return x + } +} + +/** + * const fn = compose([x => x + 1, x => 2 * x]) + * fn(4) // 9 + */ + +export { compose } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2630_memoize_ii/readme.md b/src/main/kotlin/g2601_2700/s2630_memoize_ii/readme.md new file mode 100644 index 00000000..c28899ab --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2630_memoize_ii/readme.md @@ -0,0 +1,126 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2630\. Memoize II + +Hard + +Given a function `fn`, return a **memoized** version of that function. + +A **memoized **function is a function that will never be called twice with the same inputs. Instead it will return a cached value. + +`fn` can be any function and there are no constraints on what type of values it accepts. Inputs are considered identical if they are `===` to each other. + +**Example 1:** + +**Input:** + +getInputs = () => [[2,2],[2,2],[1,2]] + +fn = function (a, b) { return a + b; } + +**Output:** [{"val":4,"calls":1},{"val":4,"calls":1},{"val":3,"calls":2}] + +**Explanation:** + + const inputs = getInputs(); + const memoized = memoize(fn); + for (const arr of inputs) { + memoized(...arr); + } + +For the inputs of (2, 2): 2 + 2 = 4, and it required a call to fn(). + +For the inputs of (2, 2): 2 + 2 = 4, but those inputs were seen before so no call to fn() was required. + +For the inputs of (1, 2): 1 + 2 = 3, and it required another call to fn() for a total of 2. + +**Example 2:** + +**Input:** + +getInputs = () => [[{},{}],[{},{}],[{},{}]] + +fn = function (a, b) { return ({...a, ...b}); } + +**Output:** [{"val":{},"calls":1},{"val":{},"calls":2},{"val":{},"calls":3}] + +**Explanation:** Merging two empty objects will always result in an empty object. It may seem like there should only be 1 call to fn() because of cache-hits, however none of those objects are === to each other. + +**Example 3:** + +**Input:** + +getInputs = () => { const o = {}; return [[o,o],[o,o],[o,o]]; } + +fn = function (a, b) { return ({...a, ...b}); } + +**Output:** [{"val":{},"calls":1},{"val":{},"calls":1},{"val":{},"calls":1}] + +**Explanation:** Merging two empty objects will always result in an empty object. The 2nd and 3rd third function calls result in a cache-hit. This is because every object passed in is identical. + +**Constraints:** + +* 1 <= inputs.length <= 105 +* 0 <= inputs.flat().length <= 105 +* `inputs[i][j] != NaN` + +## Solution + +```typescript +type Fn = (...params: any) => any + +function memoize(fn: Fn): Fn { + const cache = new Map() + + return function (...args) { + let currentCache + if (cache.has(args.length)) { + currentCache = cache.get(args.length) + } else { + currentCache = new Map() + cache.set(args.length, currentCache) + } + + for (let i = 0, len = args.length; i <= len; i++) { + const arg = args[i] + const isEnd = i >= len - 1 + + if (currentCache.has(arg)) { + if (isEnd) { + return currentCache.get(arg) + } else { + currentCache = currentCache.get(arg) + } + } else { + if (isEnd) { + break + } else { + const newSubCache = new Map() + + currentCache.set(arg, newSubCache) + currentCache = newSubCache + } + } + } + + let value = fn.apply(null, args) + + currentCache.set(args[args.length - 1], value) + return value + } +} + +/** + * let callCount = 0; + * const memoizedFn = memoize(function (a, b) { + * callCount += 1; + * return a + b; + * }) + * memoizedFn(2, 3) // 5 + * memoizedFn(2, 3) // 5 + * console.log(callCount) // 1 + */ + +export { memoize } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2631_group_by/readme.md b/src/main/kotlin/g2601_2700/s2631_group_by/readme.md new file mode 100644 index 00000000..a01b1859 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2631_group_by/readme.md @@ -0,0 +1,124 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2631\. Group By + +Medium + +Write code that enhances all arrays such that you can call the `array.groupBy(fn)` method on any array and it will return a **grouped** version of the array. + +A **grouped** array is an object where each key is the output of `fn(arr[i])` and each value is an array containing all items in the original array with that key. + +The provided callback `fn` will accept an item in the array and return a string key. + +The order of each value list should be the order the items appear in the array. Any order of keys is acceptable. + +Please solve it without lodash's `_.groupBy` function. + +**Example 1:** + +**Input:** + + array = [ + {"id":"1"}, + {"id":"1"}, + {"id":"2"} + ], + fn = function (item) { + return item.id; + } + +**Output:** + + { + "1": [{"id": "1"}, {"id": "1"}], + "2": [{"id": "2"}] + } + +**Explanation:** + + Output is from array.groupBy(fn). + The selector function gets the "id" out of each item in the array. + There are two objects with an "id" of 1. Both of those objects are put in the first array. + There is one object with an "id" of 2. That object is put in the second array. + +**Example 2:** + +**Input:** + + array = [ + [1, 2, 3], + [1, 3, 5], + [1, 5, 9] + ] + fn = function (list) { + return String(list[0]); + } + +**Output:** + + { + "1": [[1, 2, 3], [1, 3, 5], [1, 5, 9]] + } + +**Explanation:** + +The array can be of any type. In this case, the selector function defines the key as being the first element in the array. + +All the arrays have 1 as their first element so they are grouped together. + + { + "1": [[1, 2, 3], [1, 3, 5], [1, 5, 9]] + } + +**Example 3:** + +**Input:** + + array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + fn = function (n) { + return String(n > 5); + } + +**Output:** + + { + "true": [6, 7, 8, 9, 10], + "false": [1, 2, 3, 4, 5] + } + +**Explanation:** The selector function splits the array by whether each number is greater than 5. + +**Constraints:** + +* 0 <= array.length <= 105 +* `fn returns a string` + +## Solution + +```typescript +declare global { + interface Array { + groupBy(fn: (item: T) => string): Record + } +} + +Array.prototype.groupBy = function (fn: (item: T) => string) { //NOSONAR + const returnObject: Record = {} + for (const item of this) { + const key = fn(item) + if (key in returnObject) { + returnObject[key].push(item) + } else { + returnObject[key] = [item] + } + } + return returnObject +} + +/** + * [1,2,3].groupBy(String) // {"1":[1],"2":[2],"3":[3]} + */ + +export {} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2634_filter_elements_from_array/readme.md b/src/main/kotlin/g2601_2700/s2634_filter_elements_from_array/readme.md new file mode 100644 index 00000000..a1664cd1 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2634_filter_elements_from_array/readme.md @@ -0,0 +1,70 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2634\. Filter Elements from Array + +Easy + +Given an integer array `arr` and a filtering function `fn`, return a filtered array `filteredArr`. + +The `fn` function takes one or two arguments: + +* `arr[i]` - number from the `arr` +* `i` - index of `arr[i]` + +`filteredArr` should only contain the elements from the `arr` for which the expression `fn(arr[i], i)` evaluates to a **truthy** value. A **truthy** value is a value where `Boolean(value)` returns `true`. + +Please solve it without the built-in Array.filter method. + +**Example 1:** + +**Input:** arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; } + +**Output:** [20,30] + +**Explanation:** + +const newArray = filter(arr, fn); // [20, 30] + +The function filters out values that are not greater than 10 + +**Example 2:** + +**Input:** arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; } + +**Output:** [1] + +**Explanation:** + +fn can also accept the index of each element + +In this case, the function removes elements not at index 0 + +**Example 3:** + +**Input:** arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 } + +**Output:** [-2,0,1,2] + +**Explanation:** Falsey values such as 0 should be filtered out + +**Constraints:** + +* `0 <= arr.length <= 1000` +* -109 <= arr[i] <= 109 + +## Solution + +```typescript +function filter(arr: number[], fn: (n: number, i: number) => boolean): number[] { + const filteredArr: number[] = [] + + for (let i = 0; i < arr.length; i++) { + if (fn(arr[i], i)) filteredArr.push(arr[i]) + } + + return filteredArr +} + +export { filter } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2635_apply_transform_over_each_element_in_array/readme.md b/src/main/kotlin/g2601_2700/s2635_apply_transform_over_each_element_in_array/readme.md new file mode 100644 index 00000000..54f81cd6 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2635_apply_transform_over_each_element_in_array/readme.md @@ -0,0 +1,60 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2635\. Apply Transform Over Each Element in Array + +Easy + +Given an integer array `arr` and a mapping function `fn`, return a new array with a transformation applied to each element. + +The returned array should be created such that `returnedArray[i] = fn(arr[i], i)`. + +Please solve it without the built-in `Array.map` method. + +**Example 1:** + +**Input:** arr = [1,2,3], fn = function plusone(n) { return n + 1; } + +**Output:** [2,3,4] + +**Explanation:** + +const newArray = map(arr, plusone); // [2,3,4] + +The function increases each value in the array by one. + +**Example 2:** + +**Input:** arr = [1,2,3], fn = function plusI(n, i) { return n + i; } + +**Output:** [1,3,5] + +**Explanation:** The function increases each value by the index it resides in. + +**Example 3:** + +**Input:** arr = [10,20,30], fn = function constant() { return 42; } + +**Output:** [42,42,42] + +**Explanation:** The function always returns 42. + +**Constraints:** + +* `0 <= arr.length <= 1000` +* -109 <= arr[i] <= 109 +* `fn returns a number` + +## Solution + +```typescript +function map(arr: number[], fn: (n: number, i: number) => number): number[] { + const res: number[] = [] + for (let i = 0; i < arr.length; i++) { + res.push(fn(arr[i], i)) + } + return res +} + +export { map } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2637_promise_time_limit/readme.md b/src/main/kotlin/g2601_2700/s2637_promise_time_limit/readme.md new file mode 100644 index 00000000..e230f532 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2637_promise_time_limit/readme.md @@ -0,0 +1,125 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2637\. Promise Time Limit + +Easy + +Given an asynchronous function `fn` and a time `t` in milliseconds, return a new **time limited** version of the input function. `fn` takes arguments provided to the **time limited **function. + +The **time limited** function should follow these rules: + +* If the `fn` completes within the time limit of `t` milliseconds, the **time limited** function should resolve with the result. +* If the execution of the `fn` exceeds the time limit, the **time limited** function should reject with the string `"Time Limit Exceeded"`. + +**Example 1:** + +**Input:** + + fn = async (n) => { + await new Promise(res => setTimeout(res, 100)); + return n * n; + } + +inputs = [5] + +t = 50 + +**Output:** {"rejected":"Time Limit Exceeded","time":50} + +**Explanation:** + + const limited = timeLimit(fn, t) + const start = performance.now() + let result; + try { + const res = await limited(...inputs) + result = {"resolved": res, "time": Math.floor(performance.now() - start)}; + } catch (err) { + result = {"rejected": err, "time": Math.floor(performance.now() - start)}; + } + console.log(result) // Output + +The provided function is set to resolve after 100ms. However, the time limit is set to 50ms. It rejects at t=50ms because the time limit was reached. + +**Example 2:** + +**Input:** + + fn = async (n) => { + await new Promise(res => setTimeout(res, 100)); + return n * n; + } + +inputs = [5] + +t = 150 + +**Output:** {"resolved":25,"time":100} + +**Explanation:** The function resolved 5 * 5 = 25 at t=100ms. The time limit is never reached. + +**Example 3:** + +**Input:** + + fn = async (a, b) => { + await new Promise(res => setTimeout(res, 120)); + return a + b; + } + +inputs = [5,10] + +t = 150 + +**Output:** {"resolved":15,"time":120} + +**Explanation:** The function resolved 5 + 10 = 15 at t=120ms. The time limit is never reached. + +**Example 4:** + +**Input:** + + fn = async () => { + throw "Error"; + } + +inputs = [] + +t = 1000 + +**Output:** {"rejected":"Error","time":0} + +**Explanation:** The function immediately throws an error. + +**Constraints:** + +* `0 <= inputs.length <= 10` +* `0 <= t <= 1000` +* `fn returns a promise` + +## Solution + +```typescript +type Fn = (...params: any[]) => Promise + +function timeLimit(fn: Fn, t: number): Fn { + return async function (...args: any[]): Promise { + const fns = fn(...args) + const timeLimitPromise = new Promise((_, reject) => { + setTimeout(() => { + reject('Time Limit Exceeded') + }, t) + }) + + return Promise.race([fns, timeLimitPromise]) + } +} + +/** + * const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100); + * limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms + */ + +export { timeLimit } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2639_find_the_width_of_columns_of_a_grid/readme.md b/src/main/kotlin/g2601_2700/s2639_find_the_width_of_columns_of_a_grid/readme.md new file mode 100644 index 00000000..2059bff8 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2639_find_the_width_of_columns_of_a_grid/readme.md @@ -0,0 +1,75 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2639\. Find the Width of Columns of a Grid + +Easy + +You are given a **0-indexed** `m x n` integer matrix `grid`. The width of a column is the maximum **length** of its integers. + +* For example, if `grid = \[\[-10], [3], [12]]`, the width of the only column is `3` since `-10` is of length `3`. + +Return _an integer array_ `ans` _of size_ `n` _where_ `ans[i]` _is the width of the_ ith _column_. + +The **length** of an integer `x` with `len` digits is equal to `len` if `x` is non-negative, and `len + 1` otherwise. + +**Example 1:** + +**Input:** grid = \[\[1],[22],[333]] + +**Output:** [3] + +**Explanation:** In the 0th column, 333 is of length 3. + +**Example 2:** + +**Input:** grid = \[\[-15,1,3],[15,7,12],[5,6,-2]] + +**Output:** [3,1,2] + +**Explanation:** + +In the 0th column, only -15 is of length 3. + +In the 1st column, all integers are of length 1. + +In the 2nd column, both 12 and -2 are of length 2. + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `1 <= m, n <= 100` +* -109 <= grid[r][c] <= 109 + +## Solution + +```kotlin +class Solution { + fun findColumnWidth(grid: Array): IntArray { + val ans = IntArray(grid[0].size) { 1 } + for (j in 0 until grid[0].size) { + var max = 1 + for (i in 0 until grid.size) { + var num = grid[i][j] + var neg = false + if (num < 0) { + neg = true + num *= -1 + } + var size = 0 + while (num > 0) { + num /= 10 + size++ + } + if (neg) { + size += 1 + } + max = maxOf(max, size) + } + ans[j] = max + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2640_find_the_score_of_all_prefixes_of_an_array/readme.md b/src/main/kotlin/g2601_2700/s2640_find_the_score_of_all_prefixes_of_an_array/readme.md new file mode 100644 index 00000000..f5f654aa --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2640_find_the_score_of_all_prefixes_of_an_array/readme.md @@ -0,0 +1,76 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2640\. Find the Score of All Prefixes of an Array + +Medium + +We define the **conversion array** `conver` of an array `arr` as follows: + +* `conver[i] = arr[i] + max(arr[0..i])` where `max(arr[0..i])` is the maximum value of `arr[j]` over `0 <= j <= i`. + +We also define the **score** of an array `arr` as the sum of the values of the conversion array of `arr`. + +Given a **0-indexed** integer array `nums` of length `n`, return _an array_ `ans` _of length_ `n` _where_ `ans[i]` _is the score of the prefix_ `nums[0..i]`. + +**Example 1:** + +**Input:** nums = [2,3,7,5,10] + +**Output:** [4,10,24,36,56] + +**Explanation:** + +For the prefix [2], the conversion array is [4] hence the score is 4 + +For the prefix [2, 3], the conversion array is [4, 6] hence the score is 10 + +For the prefix [2, 3, 7], the conversion array is [4, 6, 14] hence the score is 24 + +For the prefix [2, 3, 7, 5], the conversion array is [4, 6, 14, 12] hence the score is 36 + +For the prefix [2, 3, 7, 5, 10], the conversion array is [4, 6, 14, 12, 20] hence the score is 56 + +**Example 2:** + +**Input:** nums = [1,1,2,4,8,16] + +**Output:** [2,4,8,16,32,64] + +**Explanation:** + +For the prefix [1], the conversion array is [2] hence the score is 2 + +For the prefix [1, 1], the conversion array is [2, 2] hence the score is 4 + +For the prefix [1, 1, 2], the conversion array is [2, 2, 4] hence the score is 8 + +For the prefix [1, 1, 2, 4], the conversion array is [2, 2, 4, 8] hence the score is 16 + +For the prefix [1, 1, 2, 4, 8], the conversion array is [2, 2, 4, 8, 16] hence the score is 32 + +For the prefix [1, 1, 2, 4, 8, 16], the conversion array is [2, 2, 4, 8, 16, 32] hence the score is 64 + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun findPrefixScore(nums: IntArray): LongArray { + var max = Integer.MIN_VALUE + var sum = 0L + val res = LongArray(nums.size) + for (i in 0 until nums.size) { + val curr = nums[i] + max = maxOf(max, curr) + sum += max + curr + res[i] = sum + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2641_cousins_in_binary_tree_ii/readme.md b/src/main/kotlin/g2601_2700/s2641_cousins_in_binary_tree_ii/readme.md new file mode 100644 index 00000000..bd79d570 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2641_cousins_in_binary_tree_ii/readme.md @@ -0,0 +1,118 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2641\. Cousins in Binary Tree II + +Medium + +Given the `root` of a binary tree, replace the value of each node in the tree with the **sum of all its cousins' values**. + +Two nodes of a binary tree are **cousins** if they have the same depth with different parents. + +Return _the_ `root` _of the modified tree_. + +**Note** that the depth of a node is the number of edges in the path from the root node to it. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/01/11/example11.png) + +**Input:** root = [5,4,9,1,10,null,7] + +**Output:** [0,0,0,7,7,null,11] + +**Explanation:** The diagram above shows the initial binary tree and the binary tree after changing the value of each node. +- Node with value 5 does not have any cousins so its sum is 0. +- Node with value 4 does not have any cousins so its sum is 0. +- Node with value 9 does not have any cousins so its sum is 0. +- Node with value 1 has a cousin with value 7 so its sum is 7. +- Node with value 10 has a cousin with value 7 so its sum is 7. +- Node with value 7 has cousins with values 1 and 10 so its sum is 11. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/01/11/diagram33.png) + +**Input:** root = [3,1,2] + +**Output:** [0,0,0] + +**Explanation:** The diagram above shows the initial binary tree and the binary tree after changing the value of each node. +- Node with value 3 does not have any cousins so its sum is 0. +- Node with value 1 does not have any cousins so its sum is 0. +- Node with value 2 does not have any cousins so its sum is 0. + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 105]. +* 1 <= Node.val <= 104 + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private var horizontalSum: MutableList? = null + + private fun traverse(root: TreeNode?, depth: Int) { + if (root == null) { + return + } + if (depth < horizontalSum!!.size) { + horizontalSum!![depth] = horizontalSum!![depth]!! + root.`val` + } else { + horizontalSum!!.add(root.`val`) + } + traverse(root.left, depth + 1) + traverse(root.right, depth + 1) + } + + private fun traverse1(root: TreeNode?, depth: Int) { + if (root == null) { + return + } + if (depth > 0) { + var sum = 0 + if (root.left != null) { + sum += root.left!!.`val` + } + if (root.right != null) { + sum += root.right!!.`val` + } + if (root.left != null) { + root.left!!.`val` = horizontalSum!![depth + 1]!! - sum + } + if (root.right != null) { + root.right!!.`val` = horizontalSum!![depth + 1]!! - sum + } + } + traverse1(root.left, depth + 1) + traverse1(root.right, depth + 1) + } + + fun replaceValueInTree(root: TreeNode?): TreeNode { + horizontalSum = ArrayList() + root!!.`val` = 0 + if (root.left != null) { + root.left!!.`val` = 0 + } + if (root.right != null) { + root.right!!.`val` = 0 + } + traverse(root, 0) + traverse1(root, 0) + return root + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2642_design_graph_with_shortest_path_calculator/readme.md b/src/main/kotlin/g2601_2700/s2642_design_graph_with_shortest_path_calculator/readme.md new file mode 100644 index 00000000..f1f4b598 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2642_design_graph_with_shortest_path_calculator/readme.md @@ -0,0 +1,95 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2642\. Design Graph With Shortest Path Calculator + +Hard + +There is a **directed weighted** graph that consists of `n` nodes numbered from `0` to `n - 1`. The edges of the graph are initially represented by the given array `edges` where edges[i] = [fromi, toi, edgeCosti] meaning that there is an edge from fromi to toi with the cost edgeCosti. + +Implement the `Graph` class: + +* `Graph(int n, int[][] edges)` initializes the object with `n` nodes and the given edges. +* `addEdge(int[] edge)` adds an edge to the list of edges where `edge = [from, to, edgeCost]`. It is guaranteed that there is no edge between the two nodes before adding this one. +* `int shortestPath(int node1, int node2)` returns the **minimum** cost of a path from `node1` to `node2`. If no path exists, return `-1`. The cost of a path is the sum of the costs of the edges in the path. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/01/11/graph3drawio-2.png) + +**Input** ["Graph", "shortestPath", "shortestPath", "addEdge", "shortestPath"] [[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]] + +**Output:** [null, 6, -1, null, 6] + +**Explanation:** + +Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]); + +g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -> 0 -> 1 -> 2 with a total cost of 3 + 2 + 1 = 6. + +g.shortestPath(0, 3); // return -1. There is no path from 0 to 3. + +g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above. + +g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -> 1 -> 3 with a total cost of 2 + 4 = 6. + +**Constraints:** + +* `1 <= n <= 100` +* `0 <= edges.length <= n * (n - 1)` +* `edges[i].length == edge.length == 3` +* 0 <= fromi, toi, from, to, node1, node2 <= n - 1 +* 1 <= edgeCosti, edgeCost <= 106 +* There are no repeated edges and no self-loops in the graph at any point. +* At most `100` calls will be made for `addEdge`. +* At most `100` calls will be made for `shortestPath`. + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Graph(n: Int, edges: Array) { + private val adj = HashMap>>().apply { + for (i in 0 until n) + this[i] = ArrayList>() + + for ((u, v, cost) in edges) { + this[u] = getOrDefault(u, ArrayList>()).apply { this.add(v to cost) } + } + } + + fun addEdge(edge: IntArray) { + val (u, v, cost) = edge + adj[u] = adj.getOrDefault(u, ArrayList>()).apply { this.add(v to cost) } + } + + fun shortestPath(node1: Int, node2: Int): Int { + val minHeap = PriorityQueue> { a, b -> a.second - b.second } + val distance = IntArray(adj.size) { Integer.MAX_VALUE } + minHeap.add(node1 to 0) + distance[node1] = 0 + while (minHeap.isNotEmpty()) { + val (node, cost) = minHeap.poll() + if (node == node2) return cost + if (cost > distance[node]) continue + adj[node]?.let { + for ((next, nextCost) in adj[node]!!) { + if (cost + nextCost < distance[next]) { + distance[next] = cost + nextCost + minHeap.add(next to cost + nextCost) + } + } + } + } + return -1 + } +} + +/* + * Your Graph object will be instantiated and called as such: + * var obj = Graph(n, edges) + * obj.addEdge(edge) + * var param_2 = obj.shortestPath(node1,node2) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2643_row_with_maximum_ones/readme.md b/src/main/kotlin/g2601_2700/s2643_row_with_maximum_ones/readme.md new file mode 100644 index 00000000..25fff4b4 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2643_row_with_maximum_ones/readme.md @@ -0,0 +1,62 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2643\. Row With Maximum Ones + +Easy + +Given a `m x n` binary matrix `mat`, find the **0-indexed** position of the row that contains the **maximum** count of **ones,** and the number of ones in that row. + +In case there are multiple rows that have the maximum count of ones, the row with the **smallest row number** should be selected. + +Return _an array containing the index of the row, and the number of ones in it._ + +**Example 1:** + +**Input:** mat = \[\[0,1],[1,0]] + +**Output:** [0,1] + +**Explanation:** Both rows have the same number of 1's. So we return the index of the smaller row, 0, and the maximum count of ones (1`)`. So, the answer is [0,1]. + +**Example 2:** + +**Input:** mat = \[\[0,0,0],[0,1,1]] + +**Output:** [1,2] + +**Explanation:** The row indexed 1 has the maximum count of ones `(2)`. So we return its index, `1`, and the count. So, the answer is [1,2]. + +**Example 3:** + +**Input:** mat = \[\[0,0],[1,1],[0,0]] + +**Output:** [1,2] + +**Explanation:** The row indexed 1 has the maximum count of ones (2). So the answer is [1,2]. + +**Constraints:** + +* `m == mat.length` +* `n == mat[i].length` +* `1 <= m, n <= 100` +* `mat[i][j]` is either `0` or `1`. + +## Solution + +```kotlin +class Solution { + fun rowAndMaximumOnes(mat: Array): IntArray { + var row = -1 + var best = -1 + for ((i, arr) in mat.withIndex()) { + val sum = arr.sum() + if (sum > best) { + best = sum + row = i + } + } + return intArrayOf(row, best) + } +} +``` \ No newline at end of file