From a4cf90c274b8152cfeb975d3fa015a9dce32c003 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Fri, 1 Sep 2023 00:59:03 +0300 Subject: [PATCH] Added tasks 2596-2637 --- README.md | 249 ++++++++++-------- .../readme.md | 80 ++++++ .../readme.md | 99 +++++++ .../readme.md | 93 +++++++ .../readme.md | 57 ++++ .../readme.md | 102 +++++++ .../readme.md | 101 +++++++ .../s2603_collect_coins_in_a_tree/readme.md | 101 +++++++ .../readme.md | 57 ++++ .../readme.md | 69 +++++ .../readme.md | 81 ++++++ .../s2608_shortest_cycle_in_a_graph/readme.md | 84 ++++++ .../readme.md | 78 ++++++ .../readme.md | 62 +++++ .../s2611_mice_and_cheese/readme.md | 65 +++++ .../readme.md | 112 ++++++++ .../s2614_prime_in_diagonal/readme.md | 83 ++++++ .../s2615_sum_of_distances/readme.md | 67 +++++ .../readme.md | 79 ++++++ .../readme.md | 112 ++++++++ .../readme.md | 67 +++++ .../s2619_array_prototype_last/readme.md | 51 ++++ .../java/g2601_2700/s2620_counter/readme.md | 56 ++++ .../java/g2601_2700/s2621_sleep/readme.md | 43 +++ .../s2622_cache_with_time_limit/readme.md | 105 ++++++++ .../java/g2601_2700/s2623_memoize/readme.md | 111 ++++++++ .../s2624_snail_traversal/readme.md | 77 ++++++ .../readme.md | 71 +++++ .../readme.md | 80 ++++++ .../java/g2601_2700/s2627_debounce/readme.md | 106 ++++++++ .../s2629_function_composition/readme.md | 85 ++++++ .../g2601_2700/s2630_memoize_ii/readme.md | 124 +++++++++ .../java/g2601_2700/s2631_group_by/readme.md | 124 +++++++++ .../readme.md | 70 +++++ .../readme.md | 60 +++++ .../s2637_promise_time_limit/readme.md | 124 +++++++++ 36 files changed, 3078 insertions(+), 107 deletions(-) create mode 100644 src/main/java/g2501_2600/s2596_check_knight_tour_configuration/readme.md create mode 100644 src/main/java/g2501_2600/s2597_the_number_of_beautiful_subsets/readme.md create mode 100644 src/main/java/g2501_2600/s2598_smallest_missing_non_negative_integer_after_operations/readme.md create mode 100644 src/main/java/g2501_2600/s2600_k_items_with_the_maximum_sum/readme.md create mode 100644 src/main/java/g2601_2700/s2601_prime_subtraction_operation/readme.md create mode 100644 src/main/java/g2601_2700/s2602_minimum_operations_to_make_all_array_elements_equal/readme.md create mode 100644 src/main/java/g2601_2700/s2603_collect_coins_in_a_tree/readme.md create mode 100644 src/main/java/g2601_2700/s2605_form_smallest_number_from_two_digit_arrays/readme.md create mode 100644 src/main/java/g2601_2700/s2606_find_the_substring_with_maximum_cost/readme.md create mode 100644 src/main/java/g2601_2700/s2607_make_k_subarray_sums_equal/readme.md create mode 100644 src/main/java/g2601_2700/s2608_shortest_cycle_in_a_graph/readme.md create mode 100644 src/main/java/g2601_2700/s2609_find_the_longest_balanced_substring_of_a_binary_string/readme.md create mode 100644 src/main/java/g2601_2700/s2610_convert_an_array_into_a_2d_array_with_conditions/readme.md create mode 100644 src/main/java/g2601_2700/s2611_mice_and_cheese/readme.md create mode 100644 src/main/java/g2601_2700/s2612_minimum_reverse_operations/readme.md create mode 100644 src/main/java/g2601_2700/s2614_prime_in_diagonal/readme.md create mode 100644 src/main/java/g2601_2700/s2615_sum_of_distances/readme.md create mode 100644 src/main/java/g2601_2700/s2616_minimize_the_maximum_difference_of_pairs/readme.md create mode 100644 src/main/java/g2601_2700/s2617_minimum_number_of_visited_cells_in_a_grid/readme.md create mode 100644 src/main/java/g2601_2700/s2618_check_if_object_instance_of_class/readme.md create mode 100644 src/main/java/g2601_2700/s2619_array_prototype_last/readme.md create mode 100644 src/main/java/g2601_2700/s2620_counter/readme.md create mode 100644 src/main/java/g2601_2700/s2621_sleep/readme.md create mode 100644 src/main/java/g2601_2700/s2622_cache_with_time_limit/readme.md create mode 100644 src/main/java/g2601_2700/s2623_memoize/readme.md create mode 100644 src/main/java/g2601_2700/s2624_snail_traversal/readme.md create mode 100644 src/main/java/g2601_2700/s2625_flatten_deeply_nested_array/readme.md create mode 100644 src/main/java/g2601_2700/s2626_array_reduce_transformation/readme.md create mode 100644 src/main/java/g2601_2700/s2627_debounce/readme.md create mode 100644 src/main/java/g2601_2700/s2629_function_composition/readme.md create mode 100644 src/main/java/g2601_2700/s2630_memoize_ii/readme.md create mode 100644 src/main/java/g2601_2700/s2631_group_by/readme.md create mode 100644 src/main/java/g2601_2700/s2634_filter_elements_from_array/readme.md create mode 100644 src/main/java/g2601_2700/s2635_apply_transform_over_each_element_in_array/readme.md create mode 100644 src/main/java/g2601_2700/s2637_promise_time_limit/readme.md diff --git a/README.md b/README.md index 8675e8ba..f84825bf 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,6 @@ [![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) > ["For coding interview preparation, LeetCode is one of the best online resource providing a rich library of more than 300 real coding interview questions for you to practice from using one of the 7 supported languages - C, C++, Java, Python, C#, JavaScript, Ruby."](https://www.quora.com/How-effective-is-Leetcode-for-preparing-for-technical-interviews) -* [Data Structure I](#data-structure-i) * [Data Structure II](#data-structure-ii) * [Algorithm I](#algorithm-i) * [Algorithm II](#algorithm-ii) @@ -16,111 +15,7 @@ * [Level 1](#level-1) * [Level 2](#level-2) * [Udemy](#udemy) - -### Data Structure I - -#### Day 1 Array - -| | | | | | -|-|-|-|-|-|- -| 0217 |[Contains Duplicate](src/main/java/g0201_0300/s0217_contains_duplicate)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting | 6 | 96.68 -| 0053 |[Maximum Subarray](src/main/java/g0001_0100/s0053_maximum_subarray)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer | 1 | 100.00 - -#### Day 2 Array - -| | | | | | -|-|-|-|-|-|- -| 0001 |[Two Sum](src/main/java/g0001_0100/s0001_two_sum)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table | 1 | 99.37 -| 0088 |[Merge Sorted Array](src/main/java/g0001_0100/s0088_merge_sorted_array)| Easy | Top_Interview_Questions, Array, Sorting, Two_Pointers | 0 | 100.00 - -#### Day 3 Array - -| | | | | | -|-|-|-|-|-|- -| 0350 |[Intersection of Two Arrays II](src/main/java/g0301_0400/s0350_intersection_of_two_arrays_ii)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting, Binary_Search, Two_Pointers | 4 | 69.62 -| 0121 |[Best Time to Buy and Sell Stock](src/main/java/g0101_0200/s0121_best_time_to_buy_and_sell_stock)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 1 | 100.00 - -#### Day 4 Array - -| | | | | | -|-|-|-|-|-|- -| 0566 |[Reshape the Matrix](src/main/java/g0501_0600/s0566_reshape_the_matrix)| Easy | Array, Matrix, Simulation | 1 | 90.08 -| 0118 |[Pascal's Triangle](src/main/java/g0101_0200/s0118_pascals_triangle)| Easy | Top_Interview_Questions, Array, Dynamic_Programming | 1 | 67.08 - -#### Day 5 Array - -| | | | | | -|-|-|-|-|-|- -| 0036 |[Valid Sudoku](src/main/java/g0001_0100/s0036_valid_sudoku)| Medium | Top_Interview_Questions, Array, Hash_Table, Matrix | 1 | 100.00 -| 0074 |[Search a 2D Matrix](src/main/java/g0001_0100/s0074_search_a_2d_matrix)| Medium | Top_100_Liked_Questions, Array, Binary_Search, Matrix | 0 | 100.00 - -#### Day 6 String - -| | | | | | -|-|-|-|-|-|- -| 0387 |[First Unique Character in a String](src/main/java/g0301_0400/s0387_first_unique_character_in_a_string)| Easy | Top_Interview_Questions, String, Hash_Table, Counting, Queue | 1 | 100.00 -| 0383 |[Ransom Note](src/main/java/g0301_0400/s0383_ransom_note)| Easy | String, Hash_Table, Counting | 1 | 99.97 -| 0242 |[Valid Anagram](src/main/java/g0201_0300/s0242_valid_anagram)| Easy | Top_Interview_Questions, String, Hash_Table, Sorting | 2 | 99.01 - -#### Day 7 Linked List - -| | | | | | -|-|-|-|-|-|- -| 0141 |[Linked List Cycle](src/main/java/g0101_0200/s0141_linked_list_cycle)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Two_Pointers, Linked_List | 0 | 100.00 -| 0021 |[Merge Two Sorted Lists](src/main/java/g0001_0100/s0021_merge_two_sorted_lists)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 0 | 100.00 -| 0203 |[Remove Linked List Elements](src/main/java/g0201_0300/s0203_remove_linked_list_elements)| Easy | Linked_List, Recursion | 1 | 98.82 - -#### Day 8 Linked List - -| | | | | | -|-|-|-|-|-|- -| 0206 |[Reverse Linked List](src/main/java/g0201_0300/s0206_reverse_linked_list)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 0 | 100.00 -| 0083 |[Remove Duplicates from Sorted List](src/main/java/g0001_0100/s0083_remove_duplicates_from_sorted_list)| Easy | Linked_List | 0 | 100.00 - -#### Day 9 Stack Queue - -| | | | | | -|-|-|-|-|-|- -| 0020 |[Valid Parentheses](src/main/java/g0001_0100/s0020_valid_parentheses)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, String, Stack | 2 | 90.49 -| 0232 |[Implement Queue using Stacks](src/main/java/g0201_0300/s0232_implement_queue_using_stacks)| Easy | Stack, Design, Queue | 1 | 67.21 - -#### Day 10 Tree - -| | | | | | -|-|-|-|-|-|- -| 0144 |[Binary Tree Preorder Traversal](src/main/java/g0101_0200/s0144_binary_tree_preorder_traversal)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack | 1 | 48.38 -| 0094 |[Binary Tree Inorder Traversal](src/main/java/g0001_0100/s0094_binary_tree_inorder_traversal)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Stack | 0 | 100.00 -| 0145 |[Binary Tree Postorder Traversal](src/main/java/g0101_0200/s0145_binary_tree_postorder_traversal)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack | 1 | 49.11 - -#### Day 11 Tree - -| | | | | | -|-|-|-|-|-|- -| 0102 |[Binary Tree Level Order Traversal](src/main/java/g0101_0200/s0102_binary_tree_level_order_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 1 | 91.09 -| 0104 |[Maximum Depth of Binary Tree](src/main/java/g0101_0200/s0104_maximum_depth_of_binary_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 0 | 100.00 -| 0101 |[Symmetric Tree](src/main/java/g0101_0200/s0101_symmetric_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 0 | 100.00 - -#### Day 12 Tree - -| | | | | | -|-|-|-|-|-|- -| 0226 |[Invert Binary Tree](src/main/java/g0201_0300/s0226_invert_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 0 | 100.00 -| 0112 |[Path Sum](src/main/java/g0101_0200/s0112_path_sum)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 0 | 100.00 - -#### Day 13 Tree - -| | | | | | -|-|-|-|-|-|- -| 0700 |[Search in a Binary Search Tree](src/main/java/g0601_0700/s0700_search_in_a_binary_search_tree)| Easy | Tree, Binary_Tree, Binary_Search_Tree | 0 | 100.00 -| 0701 |[Insert into a Binary Search Tree](src/main/java/g0701_0800/s0701_insert_into_a_binary_search_tree)| Medium | Tree, Binary_Tree, Binary_Search_Tree | 0 | 100.00 - -#### Day 14 Tree - -| | | | | | -|-|-|-|-|-|- -| 0098 |[Validate Binary Search Tree](src/main/java/g0001_0100/s0098_validate_binary_search_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 0 | 100.00 -| 0653 |[Two Sum IV - Input is a BST](src/main/java/g0601_0700/s0653_two_sum_iv_input_is_a_bst)| Easy | Hash_Table, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Two_Pointers, Binary_Search_Tree | 5 | 74.23 -| 0235 |[Lowest Common Ancestor of a Binary Search Tree](src/main/java/g0201_0300/s0235_lowest_common_ancestor_of_a_binary_search_tree)| Easy | Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 4 | 100.00 +* [Data Structure I](#data-structure-i) ### Data Structure II @@ -1812,10 +1707,150 @@ |-|-|-|-|-|- | 0155 |[Min Stack](src/main/java/g0101_0200/s0155_min_stack)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Stack, Design | 3 | 100.00 +### Data Structure I + +#### Day 1 Array + +| | | | | | +|-|-|-|-|-|- +| 0217 |[Contains Duplicate](src/main/java/g0201_0300/s0217_contains_duplicate)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting | 6 | 96.68 +| 0053 |[Maximum Subarray](src/main/java/g0001_0100/s0053_maximum_subarray)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer | 1 | 100.00 + +#### Day 2 Array + +| | | | | | +|-|-|-|-|-|- +| 0001 |[Two Sum](src/main/java/g0001_0100/s0001_two_sum)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table | 1 | 99.37 +| 0088 |[Merge Sorted Array](src/main/java/g0001_0100/s0088_merge_sorted_array)| Easy | Top_Interview_Questions, Array, Sorting, Two_Pointers | 0 | 100.00 + +#### Day 3 Array + +| | | | | | +|-|-|-|-|-|- +| 0350 |[Intersection of Two Arrays II](src/main/java/g0301_0400/s0350_intersection_of_two_arrays_ii)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting, Binary_Search, Two_Pointers | 4 | 69.62 +| 0121 |[Best Time to Buy and Sell Stock](src/main/java/g0101_0200/s0121_best_time_to_buy_and_sell_stock)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 1 | 100.00 + +#### Day 4 Array + +| | | | | | +|-|-|-|-|-|- +| 0566 |[Reshape the Matrix](src/main/java/g0501_0600/s0566_reshape_the_matrix)| Easy | Array, Matrix, Simulation | 1 | 90.08 +| 0118 |[Pascal's Triangle](src/main/java/g0101_0200/s0118_pascals_triangle)| Easy | Top_Interview_Questions, Array, Dynamic_Programming | 1 | 67.08 + +#### Day 5 Array + +| | | | | | +|-|-|-|-|-|- +| 0036 |[Valid Sudoku](src/main/java/g0001_0100/s0036_valid_sudoku)| Medium | Top_Interview_Questions, Array, Hash_Table, Matrix | 1 | 100.00 +| 0074 |[Search a 2D Matrix](src/main/java/g0001_0100/s0074_search_a_2d_matrix)| Medium | Top_100_Liked_Questions, Array, Binary_Search, Matrix | 0 | 100.00 + +#### Day 6 String + +| | | | | | +|-|-|-|-|-|- +| 0387 |[First Unique Character in a String](src/main/java/g0301_0400/s0387_first_unique_character_in_a_string)| Easy | Top_Interview_Questions, String, Hash_Table, Counting, Queue | 1 | 100.00 +| 0383 |[Ransom Note](src/main/java/g0301_0400/s0383_ransom_note)| Easy | String, Hash_Table, Counting | 1 | 99.97 +| 0242 |[Valid Anagram](src/main/java/g0201_0300/s0242_valid_anagram)| Easy | Top_Interview_Questions, String, Hash_Table, Sorting | 2 | 99.01 + +#### Day 7 Linked List + +| | | | | | +|-|-|-|-|-|- +| 0141 |[Linked List Cycle](src/main/java/g0101_0200/s0141_linked_list_cycle)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Two_Pointers, Linked_List | 0 | 100.00 +| 0021 |[Merge Two Sorted Lists](src/main/java/g0001_0100/s0021_merge_two_sorted_lists)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 0 | 100.00 +| 0203 |[Remove Linked List Elements](src/main/java/g0201_0300/s0203_remove_linked_list_elements)| Easy | Linked_List, Recursion | 1 | 98.82 + +#### Day 8 Linked List + +| | | | | | +|-|-|-|-|-|- +| 0206 |[Reverse Linked List](src/main/java/g0201_0300/s0206_reverse_linked_list)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Linked_List, Recursion | 0 | 100.00 +| 0083 |[Remove Duplicates from Sorted List](src/main/java/g0001_0100/s0083_remove_duplicates_from_sorted_list)| Easy | Linked_List | 0 | 100.00 + +#### Day 9 Stack Queue + +| | | | | | +|-|-|-|-|-|- +| 0020 |[Valid Parentheses](src/main/java/g0001_0100/s0020_valid_parentheses)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, String, Stack | 2 | 90.49 +| 0232 |[Implement Queue using Stacks](src/main/java/g0201_0300/s0232_implement_queue_using_stacks)| Easy | Stack, Design, Queue | 1 | 67.21 + +#### Day 10 Tree + +| | | | | | +|-|-|-|-|-|- +| 0144 |[Binary Tree Preorder Traversal](src/main/java/g0101_0200/s0144_binary_tree_preorder_traversal)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack | 1 | 48.38 +| 0094 |[Binary Tree Inorder Traversal](src/main/java/g0001_0100/s0094_binary_tree_inorder_traversal)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Stack | 0 | 100.00 +| 0145 |[Binary Tree Postorder Traversal](src/main/java/g0101_0200/s0145_binary_tree_postorder_traversal)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack | 1 | 49.11 + +#### Day 11 Tree + +| | | | | | +|-|-|-|-|-|- +| 0102 |[Binary Tree Level Order Traversal](src/main/java/g0101_0200/s0102_binary_tree_level_order_traversal)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Breadth_First_Search, Tree, Binary_Tree | 1 | 91.09 +| 0104 |[Maximum Depth of Binary Tree](src/main/java/g0101_0200/s0104_maximum_depth_of_binary_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 0 | 100.00 +| 0101 |[Symmetric Tree](src/main/java/g0101_0200/s0101_symmetric_tree)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 0 | 100.00 + +#### Day 12 Tree + +| | | | | | +|-|-|-|-|-|- +| 0226 |[Invert Binary Tree](src/main/java/g0201_0300/s0226_invert_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 0 | 100.00 +| 0112 |[Path Sum](src/main/java/g0101_0200/s0112_path_sum)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 0 | 100.00 + +#### Day 13 Tree + +| | | | | | +|-|-|-|-|-|- +| 0700 |[Search in a Binary Search Tree](src/main/java/g0601_0700/s0700_search_in_a_binary_search_tree)| Easy | Tree, Binary_Tree, Binary_Search_Tree | 0 | 100.00 +| 0701 |[Insert into a Binary Search Tree](src/main/java/g0701_0800/s0701_insert_into_a_binary_search_tree)| Medium | Tree, Binary_Tree, Binary_Search_Tree | 0 | 100.00 + +#### Day 14 Tree + +| | | | | | +|-|-|-|-|-|- +| 0098 |[Validate Binary Search Tree](src/main/java/g0001_0100/s0098_validate_binary_search_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 0 | 100.00 +| 0653 |[Two Sum IV - Input is a BST](src/main/java/g0601_0700/s0653_two_sum_iv_input_is_a_bst)| Easy | Hash_Table, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Two_Pointers, Binary_Search_Tree | 5 | 74.23 +| 0235 |[Lowest Common Ancestor of a Binary Search Tree](src/main/java/g0201_0300/s0235_lowest_common_ancestor_of_a_binary_search_tree)| Easy | Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 4 | 100.00 + ## Algorithms | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- +| 2637 |[Promise Time Limit](src/main/java/g2601_2700/s2637_promise_time_limit)| Easy | Medium | 53 | 93.41 +| 2635 |[Apply Transform Over Each Element in Array](src/main/java/g2601_2700/s2635_apply_transform_over_each_element_in_array)| Easy || 43 | 98.46 +| 2634 |[Filter Elements from Array](src/main/java/g2601_2700/s2634_filter_elements_from_array)| Easy || 44 | 98.04 +| 2631 |[Group By](src/main/java/g2601_2700/s2631_group_by)| Medium || 101 | 99.50 +| 2630 |[Memoize II](src/main/java/g2601_2700/s2630_memoize_ii)| Hard || 264 | 98.86 +| 2629 |[Function Composition](src/main/java/g2601_2700/s2629_function_composition)| Easy || 58 | 95.63 +| 2627 |[Debounce](src/main/java/g2601_2700/s2627_debounce)| Medium || 50 | 98.23 +| 2626 |[Array Reduce Transformation](src/main/java/g2601_2700/s2626_array_reduce_transformation)| Easy || 52 | 91.40 +| 2625 |[Flatten Deeply Nested Array](src/main/java/g2601_2700/s2625_flatten_deeply_nested_array)| Medium || 84 | 98.71 +| 2624 |[Snail Traversal](src/main/java/g2601_2700/s2624_snail_traversal)| Medium || 175 | 92.96 +| 2623 |[Memoize](src/main/java/g2601_2700/s2623_memoize)| Medium || 264 | 97.20 +| 2622 |[Cache With Time Limit](src/main/java/g2601_2700/s2622_cache_with_time_limit)| Medium || 51 | 94.82 +| 2621 |[Sleep](src/main/java/g2601_2700/s2621_sleep)| Easy || 40 | 99.59 +| 2620 |[Counter](src/main/java/g2601_2700/s2620_counter)| Easy || 43 | 98.60 +| 2619 |[Array Prototype Last](src/main/java/g2601_2700/s2619_array_prototype_last)| Easy || 41 | 98.99 +| 2618 |[Check if Object Instance of Class](src/main/java/g2601_2700/s2618_check_if_object_instance_of_class)| Medium || 82 | 99.55 +| 2617 |[Minimum Number of Visited Cells in a Grid](src/main/java/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 | 34 | 100.00 +| 2616 |[Minimize the Maximum Difference of Pairs](src/main/java/g2601_2700/s2616_minimize_the_maximum_difference_of_pairs)| Medium | Array, Greedy, Binary_Search | 16 | 91.77 +| 2615 |[Sum of Distances](src/main/java/g2601_2700/s2615_sum_of_distances)| Medium | Array, Hash_Table, Prefix_Sum | 13 | 100.00 +| 2614 |[Prime In Diagonal](src/main/java/g2601_2700/s2614_prime_in_diagonal)| Easy | Array, Math, Matrix, Number_Theory | 0 | 100.00 +| 2612 |[Minimum Reverse Operations](src/main/java/g2601_2700/s2612_minimum_reverse_operations)| Hard | Array, Breadth_First_Search, Ordered_Set | 19 | 100.00 +| 2611 |[Mice and Cheese](src/main/java/g2601_2700/s2611_mice_and_cheese)| Medium | Array, Sorting, Greedy, Heap_Priority_Queue | 11 | 99.56 +| 2610 |[Convert an Array Into a 2D Array With Conditions](src/main/java/g2601_2700/s2610_convert_an_array_into_a_2d_array_with_conditions)| Medium | Array, Hash_Table | 2 | 97.24 +| 2609 |[Find the Longest Balanced Substring of a Binary String](src/main/java/g2601_2700/s2609_find_the_longest_balanced_substring_of_a_binary_string)| Easy | String | 1 | 100.00 +| 2608 |[Shortest Cycle in a Graph](src/main/java/g2601_2700/s2608_shortest_cycle_in_a_graph)| Hard | Breadth_First_Search, Graph | 11 | 100.00 +| 2607 |[Make K-Subarray Sums Equal](src/main/java/g2601_2700/s2607_make_k_subarray_sums_equal)| Medium | Array, Math, Sorting, Number_Theory | 24 | 99.15 +| 2606 |[Find the Substring With Maximum Cost](src/main/java/g2601_2700/s2606_find_the_substring_with_maximum_cost)| Medium | Array, String, Hash_Table, Dynamic_Programming | 3 | 100.00 +| 2605 |[Form Smallest Number From Two Digit Arrays](src/main/java/g2601_2700/s2605_form_smallest_number_from_two_digit_arrays)| Easy | Array, Hash_Table, Enumeration | 1 | 95.34 +| 2603 |[Collect Coins in a Tree](src/main/java/g2601_2700/s2603_collect_coins_in_a_tree)| Hard | Array, Tree, Graph, Topological_Sort | 26 | 100.00 +| 2602 |[Minimum Operations to Make All Array Elements Equal](src/main/java/g2601_2700/s2602_minimum_operations_to_make_all_array_elements_equal)| Medium | Array, Sorting, Binary_Search, Prefix_Sum | 41 | 97.39 +| 2601 |[Prime Subtraction Operation](src/main/java/g2601_2700/s2601_prime_subtraction_operation)| Medium | Array, Math, Greedy, Binary_Search, Number_Theory | 2 | 100.00 +| 2600 |[K Items With the Maximum Sum](src/main/java/g2501_2600/s2600_k_items_with_the_maximum_sum)| Easy | Math, Greedy | 1 | 100.00 +| 2598 |[Smallest Missing Non-negative Integer After Operations](src/main/java/g2501_2600/s2598_smallest_missing_non_negative_integer_after_operations)| Medium | Array, Hash_Table, Math, Greedy | 4 | 99.19 +| 2597 |[The Number of Beautiful Subsets](src/main/java/g2501_2600/s2597_the_number_of_beautiful_subsets)| Medium | Array, Dynamic_Programming, Backtracking | 4 | 100.00 +| 2596 |[Check Knight Tour Configuration](src/main/java/g2501_2600/s2596_check_knight_tour_configuration)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Simulation | 1 | 100.00 | 2595 |[Number of Even and Odd Bits](src/main/java/g2501_2600/s2595_number_of_even_and_odd_bits)| Easy | Bit_Manipulation | 1 | 100.00 | 2594 |[Minimum Time to Repair Cars](src/main/java/g2501_2600/s2594_minimum_time_to_repair_cars)| Medium | Array, Binary_Search | 15 | 97.28 | 2593 |[Find Score of an Array After Marking All Elements](src/main/java/g2501_2600/s2593_find_score_of_an_array_after_marking_all_elements)| Medium | Array, Sorting, Heap_Priority_Queue, Simulation | 159 | 96.76 @@ -1826,7 +1861,7 @@ | 2587 |[Rearrange Array to Maximize Prefix Score](src/main/java/g2501_2600/s2587_rearrange_array_to_maximize_prefix_score)| Medium | Array, Sorting, Greedy, Prefix_Sum | 28 | 92.55 | 2586 |[Count the Number of Vowel Strings in Range](src/main/java/g2501_2600/s2586_count_the_number_of_vowel_strings_in_range)| Easy | Array, String | 1 | 100.00 | 2585 |[Number of Ways to Earn Points](src/main/java/g2501_2600/s2585_number_of_ways_to_earn_points)| Hard | Array, Dynamic_Programming | 56 | 76.40 -| 2584 |[Split the Array to Make Coprime Products](src/main/java/g2501_2600/s2584_split_the_array_to_make_coprime_products)| Medium | Breadth_First_Search, Tree, Binary_Search | 13 | 99.83 +| 2584 |[Split the Array to Make Coprime Products](src/main/java/g2501_2600/s2584_split_the_array_to_make_coprime_products)| Hard | Array, Hash_Table, Math, Number_Theory | 236 | 58.73 | 2583 |[Kth Largest Sum in a Binary Tree](src/main/java/g2501_2600/s2583_kth_largest_sum_in_a_binary_tree)| Medium | Breadth_First_Search, Tree, Binary_Search | 13 | 99.83 | 2582 |[Pass the Pillow](src/main/java/g2501_2600/s2582_pass_the_pillow)| Easy | Math, Simulation | 0 | 100.00 | 2581 |[Count Number of Possible Root Nodes](src/main/java/g2501_2600/s2581_count_number_of_possible_root_nodes)| Hard | Hash_Table, Dynamic_Programming, Depth_First_Search, Tree | 38 | 100.00 diff --git a/src/main/java/g2501_2600/s2596_check_knight_tour_configuration/readme.md b/src/main/java/g2501_2600/s2596_check_knight_tour_configuration/readme.md new file mode 100644 index 00000000..8da7f4c1 --- /dev/null +++ b/src/main/java/g2501_2600/s2596_check_knight_tour_configuration/readme.md @@ -0,0 +1,80 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2596\. Check Knight Tour Configuration + +Medium + +There is a knight on an `n x n` chessboard. In a valid configuration, the knight starts **at the top-left cell** of the board and visits every cell on the board **exactly once**. + +You are given an `n x n` integer matrix `grid` consisting of distinct integers from the range `[0, n * n - 1]` where `grid[row][col]` indicates that the cell `(row, col)` is the grid[row][col]th cell that the knight visited. The moves are **0-indexed**. + +Return `true` _if_ `grid` _represents a valid configuration of the knight's movements or_ `false` _otherwise_. + +**Note** that a valid knight move consists of moving two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The figure below illustrates all the possible eight moves of a knight from some cell. + +![](https://assets.leetcode.com/uploads/2018/10/12/knight.png) + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2022/12/28/yetgriddrawio-5.png) + +**Input:** grid = \[\[0,11,16,5,20],[17,4,19,10,15],[12,1,8,21,6],[3,18,23,14,9],[24,13,2,7,22]] + +**Output:** true + +**Explanation:** The above diagram represents the grid. It can be shown that it is a valid configuration. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2022/12/28/yetgriddrawio-6.png) + +**Input:** grid = \[\[0,3,6],[5,8,1],[2,7,4]] + +**Output:** false + +**Explanation:** The above diagram represents the grid. The 8th move of the knight is not valid considering its position after the 7th move. + +**Constraints:** + +* `n == grid.length == grid[i].length` +* `3 <= n <= 7` +* `0 <= grid[row][col] < n * n` +* All integers in `grid` are **unique**. + +## Solution + +```java +public class Solution { + public boolean checkValidGrid(int[][] grid) { + if (grid[0][0] != 0) { + return false; + } + int n = grid.length; + int m = grid[0].length; + int[] rmove = {2, 2, -2, -2, 1, 1, -1, -1}; + int[] cmove = {1, -1, 1, -1, 2, -2, 2, -2}; + int cnt = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + int val = grid[i][j]; + boolean isPoss = false; + for (int d = 0; d < 8; d++) { + int r = i + rmove[d]; + int c = j + cmove[d]; + if (r >= 0 && c >= 0 && r < n && c < m && grid[r][c] == val + 1) { + isPoss = true; + } + } + if (!isPoss) { + cnt++; + } + if (cnt > 1) { + return false; + } + } + } + return true; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2501_2600/s2597_the_number_of_beautiful_subsets/readme.md b/src/main/java/g2501_2600/s2597_the_number_of_beautiful_subsets/readme.md new file mode 100644 index 00000000..8b7f1d14 --- /dev/null +++ b/src/main/java/g2501_2600/s2597_the_number_of_beautiful_subsets/readme.md @@ -0,0 +1,99 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2597\. The Number of Beautiful Subsets + +Medium + +You are given an array `nums` of positive integers and a **positive** integer `k`. + +A subset of `nums` is **beautiful** if it does not contain two integers with an absolute difference equal to `k`. + +Return _the number of **non-empty beautiful** subsets of the array_ `nums`. + +A **subset** of `nums` is an array that can be obtained by deleting some (possibly none) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different. + +**Example 1:** + +**Input:** nums = [2,4,6], k = 2 + +**Output:** 4 + +**Explanation:** + +The beautiful subsets of the array nums are: [2], [4], [6], [2, 6]. + +It can be proved that there are only 4 beautiful subsets in the array [2,4,6]. + +**Example 2:** + +**Input:** nums = [1], k = 1 + +**Output:** 1 + +**Explanation:** + +The beautiful subset of the array nums is [1]. + +It can be proved that there is only 1 beautiful subset in the array [1]. + +**Constraints:** + +* `1 <= nums.length <= 20` +* `1 <= nums[i], k <= 1000` + +## Solution + +```java +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Solution { + public int beautifulSubsets(int[] nums, int k) { + Map map = new HashMap<>(); + for (int n : nums) { + map.put(n, map.getOrDefault(n, 0) + 1); + } + int res = 1; + for (Map.Entry entry : map.entrySet()) { + if (!map.containsKey(entry.getKey() - k)) { + if (map.containsKey(entry.getKey() + k)) { + List freq = new ArrayList<>(); + int localKey = entry.getKey(); + while (map.containsKey(localKey)) { + freq.add(map.get(localKey)); + localKey += k; + } + res *= helper(freq); + } else { + res *= 1 << entry.getValue(); + } + } + } + return res - 1; + } + + private int helper(List freq) { + int n = freq.size(); + if (n == 1) { + return 1 << freq.get(0); + } + int[] dp = new int[n]; + dp[0] = (1 << freq.get(0)) - 1; + dp[1] = (1 << freq.get(1)) - 1; + if (n == 2) { + return dp[0] + dp[1] + 1; + } + for (int i = 2; i < n; i++) { + if (i > 2) { + dp[i - 2] += dp[i - 3]; + } + + dp[i] = (dp[i - 2] + 1) * ((1 << freq.get(i)) - 1); + } + return dp[n - 1] + dp[n - 2] + dp[n - 3] + 1; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2501_2600/s2598_smallest_missing_non_negative_integer_after_operations/readme.md b/src/main/java/g2501_2600/s2598_smallest_missing_non_negative_integer_after_operations/readme.md new file mode 100644 index 00000000..3b5daa9d --- /dev/null +++ b/src/main/java/g2501_2600/s2598_smallest_missing_non_negative_integer_after_operations/readme.md @@ -0,0 +1,93 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2598\. Smallest Missing Non-negative Integer After Operations + +Medium + +You are given a **0-indexed** integer array `nums` and an integer `value`. + +In one operation, you can add or subtract `value` from any element of `nums`. + +* For example, if `nums = [1,2,3]` and `value = 2`, you can choose to subtract `value` from `nums[0]` to make `nums = [-1,2,3]`. + +The MEX (minimum excluded) of an array is the smallest missing **non-negative** integer in it. + +* For example, the MEX of `[-1,2,3]` is `0` while the MEX of `[1,0,3]` is `2`. + +Return _the maximum MEX of_ `nums` _after applying the mentioned operation **any number of times**_. + +**Example 1:** + +**Input:** nums = [1,-10,7,13,6,8], value = 5 + +**Output:** 4 + +**Explanation:** + +One can achieve this result by applying the following operations: + +- Add value to nums[1] twice to make nums = [1,**0**,7,13,6,8] + +- Subtract value from nums[2] once to make nums = [1,0,**2**,13,6,8] + +- Subtract value from nums[3] twice to make nums = [1,0,2,**3**,6,8] + +The MEX of nums is 4. It can be shown that 4 is the maximum MEX we can achieve. + +**Example 2:** + +**Input:** nums = [1,-10,7,13,6,8], value = 7 + +**Output:** 2 + +**Explanation:** + +One can achieve this result by applying the following operation: + +- subtract value from nums[2] once to make nums = [1,-10,**0**,13,6,8] + +The MEX of nums is 2. It can be shown that 2 is the maximum MEX we can achieve. + +**Constraints:** + +* 1 <= nums.length, value <= 105 +* -109 <= nums[i] <= 109 + +## Solution + +```java +public class Solution { + public int findSmallestInteger(int[] nums, int value) { + int n = nums.length; + if (value == 1) { + return n; + } + int[] a = new int[value]; + for (int i = 0; i < n; i++) { + int k = nums[i] % value; + if (k < 0) { + k = (value + k) % value; + } + a[k]++; + } + int[] minsResult = mins(a); + int min = minsResult[0]; + int minIndex = minsResult[1]; + return min * value + minIndex; + } + + private int[] mins(int[] a) { + int n = a.length; + int min = 100001; + int minIndex = -1; + for (int i = 0; i < n; i++) { + if (a[i] < min) { + min = a[i]; + minIndex = i; + } + } + return new int[] {min, minIndex}; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2501_2600/s2600_k_items_with_the_maximum_sum/readme.md b/src/main/java/g2501_2600/s2600_k_items_with_the_maximum_sum/readme.md new file mode 100644 index 00000000..30d79687 --- /dev/null +++ b/src/main/java/g2501_2600/s2600_k_items_with_the_maximum_sum/readme.md @@ -0,0 +1,57 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +@SuppressWarnings("java:S1172") +public class Solution { + public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { + if (k <= numOnes) { + return k; + } + if (k <= numOnes + numZeros) { + return numOnes; + } + int remainingSum = k - (numOnes + numZeros); + return numOnes - remainingSum; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2601_prime_subtraction_operation/readme.md b/src/main/java/g2601_2700/s2601_prime_subtraction_operation/readme.md new file mode 100644 index 00000000..187cccb1 --- /dev/null +++ b/src/main/java/g2601_2700/s2601_prime_subtraction_operation/readme.md @@ -0,0 +1,102 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +import java.util.Arrays; + +public class Solution { + private int[] primesUntil(int n) { + if (n < 2) { + return new int[0]; + } + int[] primes = new int[200]; + boolean[] composite = new boolean[n + 1]; + primes[0] = 2; + int added = 1; + int i = 3; + while (i <= n) { + if (composite[i]) { + i += 2; + continue; + } + primes[added++] = i; + int j = i * i; + while (j <= n) { + composite[j] = true; + j += i; + } + i += 2; + } + return Arrays.copyOf(primes, added); + } + + public boolean primeSubOperation(int[] nums) { + int max = 0; + for (int n : nums) { + max = Math.max(max, n); + } + int[] primes = primesUntil(max); + int prev = 0; + for (int n : nums) { + int pos = Arrays.binarySearch(primes, n - prev - 1); + if (pos == -1 && n <= prev) { + return false; + } + final int index; + if (pos == -1) { + index = 0; + } else { + index = pos < 0 ? primes[-pos - 2] : primes[pos]; + } + prev = n - index; + } + return true; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2602_minimum_operations_to_make_all_array_elements_equal/readme.md b/src/main/java/g2601_2700/s2602_minimum_operations_to_make_all_array_elements_equal/readme.md new file mode 100644 index 00000000..94959fa5 --- /dev/null +++ b/src/main/java/g2601_2700/s2602_minimum_operations_to_make_all_array_elements_equal/readme.md @@ -0,0 +1,101 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Solution { + public List minOperations(int[] nums, int[] queries) { + Arrays.sort(nums); + long[] sum = new long[nums.length]; + sum[0] = nums[0]; + for (int i = 1; i < nums.length; ++i) { + sum[i] = sum[i - 1] + nums[i]; + } + List res = new ArrayList<>(); + for (int query : queries) { + res.add(getOperations(sum, nums, query)); + } + return res; + } + + private long getOperations(long[] sum, int[] nums, int target) { + long res = 0; + int index = getIndex(nums, target); + int rightCounts = nums.length - 1 - index; + if (index > 0) { + res += (long) index * target - sum[index - 1]; + } + if (rightCounts > 0) { + res += sum[nums.length - 1] - sum[index] - (long) rightCounts * target; + } + res += Math.abs(target - nums[index]); + return res; + } + + private int getIndex(int[] nums, int target) { + int index = Arrays.binarySearch(nums, target); + if (index < 0) { + index = -(index + 1); + } + if (index == nums.length) { + --index; + } + return index; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2603_collect_coins_in_a_tree/readme.md b/src/main/java/g2601_2700/s2603_collect_coins_in_a_tree/readme.md new file mode 100644 index 00000000..cf62a722 --- /dev/null +++ b/src/main/java/g2601_2700/s2603_collect_coins_in_a_tree/readme.md @@ -0,0 +1,101 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +import java.util.ArrayList; +import java.util.List; + +public class Solution { + private int[] coins; + private List[] graph; + private int sum; + private int ret; + + public int collectTheCoins(int[] coins, int[][] edges) { + int n = coins.length; + this.coins = coins; + graph = new ArrayList[n]; + for (int i = 0; i < n; i++) { + graph[i] = new ArrayList<>(); + } + for (int[] edge : edges) { + graph[edge[0]].add(edge[1]); + graph[edge[1]].add(edge[0]); + } + for (int coin : coins) { + sum += coin; + } + dfs(0, -1); + return Math.max(2 * (ret - 1), 0); + } + + private int dfs(int node, int pre) { + int cnt = 0; + int s = 0; + for (int nn : graph[node]) { + if (nn != pre) { + int 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/java/g2601_2700/s2605_form_smallest_number_from_two_digit_arrays/readme.md b/src/main/java/g2601_2700/s2605_form_smallest_number_from_two_digit_arrays/readme.md new file mode 100644 index 00000000..eb239ead --- /dev/null +++ b/src/main/java/g2601_2700/s2605_form_smallest_number_from_two_digit_arrays/readme.md @@ -0,0 +1,57 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +import java.util.Arrays; + +public class Solution { + public int minNumber(int[] nums1, int[] nums2) { + Arrays.sort(nums1); + Arrays.sort(nums2); + int[] temp = new int[Math.max(nums1[nums1.length - 1], nums2[nums2.length - 1]) + 1]; + int n1 = nums1[0]; + int n2 = nums2[0]; + int k = Math.min(n1 * 10 + n2, n2 * 10 + n1); + for (int value : nums1) { + temp[value]++; + } + for (int i : nums2) { + if (temp[i] > 0) { + k = Math.min(k, i); + return k; + } + } + return k; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2606_find_the_substring_with_maximum_cost/readme.md b/src/main/java/g2601_2700/s2606_find_the_substring_with_maximum_cost/readme.md new file mode 100644 index 00000000..e813a983 --- /dev/null +++ b/src/main/java/g2601_2700/s2606_find_the_substring_with_maximum_cost/readme.md @@ -0,0 +1,69 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +public class Solution { + public int maximumCostSubstring(String s, String chars, int[] vals) { + int[] alphabetCost = new int[26]; + for (char ch = 'a'; ch <= 'z'; ch++) { + alphabetCost[ch - 'a'] = ((ch - 'a') + 1); + } + for (int i = 0; i < chars.length(); i++) { + char chr = chars.charAt(i); + int chrCost = vals[i]; + alphabetCost[chr - 'a'] = chrCost; + } + int currCost = 0; + int maxCost = Integer.MIN_VALUE; + for (char ch : s.toCharArray()) { + int cost = alphabetCost[ch - 'a']; + currCost = Math.max(currCost + cost, cost); + maxCost = Math.max(maxCost, currCost); + } + return Math.max(maxCost, "".length()); + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2607_make_k_subarray_sums_equal/readme.md b/src/main/java/g2601_2700/s2607_make_k_subarray_sums_equal/readme.md new file mode 100644 index 00000000..2375b34b --- /dev/null +++ b/src/main/java/g2601_2700/s2607_make_k_subarray_sums_equal/readme.md @@ -0,0 +1,81 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +import java.util.Arrays; + +public class Solution { + public long makeSubKSumEqual(int[] arr, int k) { + int n = arr.length; + int h = gcd(n, k); + int q = n / h; + long ans = 0; + for (int i = 0; i < h; i++) { + int[] x = new int[q]; + for (int j = 0; j < q; j++) { + x[j] = arr[(h * j) + i]; + } + Arrays.sort(x); + int v = q / 2; + int u = q % 2 == 0 ? (x[v] + x[v - 1]) / 2 : x[v]; + for (int o = 0; o < q; o++) { + ans += Math.abs(u - x[o]); + } + } + return ans; + } + + private int gcd(int a, int b) { + if (b == 0) { + return a; + } else { + return gcd(b, Math.abs(a - b)); + } + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2608_shortest_cycle_in_a_graph/readme.md b/src/main/java/g2601_2700/s2608_shortest_cycle_in_a_graph/readme.md new file mode 100644 index 00000000..a9d17ebf --- /dev/null +++ b/src/main/java/g2601_2700/s2608_shortest_cycle_in_a_graph/readme.md @@ -0,0 +1,84 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +import java.util.ArrayList; +import java.util.List; + +public class Solution { + private int output = 1001; + + public int findShortestCycle(int n, int[][] edges) { + List[] nexts = new ArrayList[n]; + int[] ranks = new int[n]; + for (int i = 0; i < n; i++) { + nexts[i] = new ArrayList<>(); + } + for (int[] edge : edges) { + for (int i = 0; i < 2; i++) { + nexts[edge[i]].add(edge[1 - i]); + } + } + for (int i = 0; i < n; i++) { + if (ranks[i] == 0) { + findShortestCycle(nexts, i, -1, -1001, ranks); + } + } + return output == 1001 ? -1 : output; + } + + private void findShortestCycle(List[] nexts, int c, int p, int r, int[] ranks) { + ranks[c] = r; + for (int n : nexts[c]) { + if (n != p) { + if (ranks[n] > r + 1) { + findShortestCycle(nexts, n, c, r + 1, ranks); + } else if (ranks[c] > ranks[n]) { + output = Math.min(output, ranks[c] - ranks[n] + 1); + } + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2609_find_the_longest_balanced_substring_of_a_binary_string/readme.md b/src/main/java/g2601_2700/s2609_find_the_longest_balanced_substring_of_a_binary_string/readme.md new file mode 100644 index 00000000..7f835e68 --- /dev/null +++ b/src/main/java/g2601_2700/s2609_find_the_longest_balanced_substring_of_a_binary_string/readme.md @@ -0,0 +1,78 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +public class Solution { + public int findTheLongestBalancedSubstring(String s) { + char[] chars = s.toCharArray(); + int max = 0; + int n = chars.length; + int zero = 0; + int one = 0; + int i = 0; + while (i < n) { + if (chars[i] == '0') { + zero++; + } else { + while (i < n) { + if (chars[i++] == '1') { + one++; + } else { + i--; + break; + } + } + max = Math.max(max, 2 * Math.min(one, zero)); + zero = 1; + one = 0; + } + i++; + } + + return max; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2610_convert_an_array_into_a_2d_array_with_conditions/readme.md b/src/main/java/g2601_2700/s2610_convert_an_array_into_a_2d_array_with_conditions/readme.md new file mode 100644 index 00000000..d2fc8358 --- /dev/null +++ b/src/main/java/g2601_2700/s2610_convert_an_array_into_a_2d_array_with_conditions/readme.md @@ -0,0 +1,62 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Solution { + public List> findMatrix(int[] nums) { + List> res = new ArrayList<>(); + Map map = new HashMap<>(); + for (int x : nums) { + map.put(x, map.getOrDefault(x, 0) + 1); + int idx = map.get(x); + if (res.size() < idx) { + res.add(new ArrayList<>()); + } + res.get(idx - 1).add(x); + } + return res; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2611_mice_and_cheese/readme.md b/src/main/java/g2601_2700/s2611_mice_and_cheese/readme.md new file mode 100644 index 00000000..15b152e7 --- /dev/null +++ b/src/main/java/g2601_2700/s2611_mice_and_cheese/readme.md @@ -0,0 +1,65 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +import java.util.Arrays; + +public class Solution { + public int miceAndCheese( + int[] firstReward, int[] seondReward, int numberOfTypesOfCheeseForFirstMouse) { + int maximumPoints = 0; + final int totalTypesOfCheese = firstReward.length; + int[] differenceInRewards = new int[totalTypesOfCheese]; + for (int i = 0; i < totalTypesOfCheese; ++i) { + differenceInRewards[i] = firstReward[i] - seondReward[i]; + maximumPoints += seondReward[i]; + } + Arrays.sort(differenceInRewards); + for (int i = totalTypesOfCheese - 1; + i > totalTypesOfCheese - numberOfTypesOfCheeseForFirstMouse - 1; + --i) { + maximumPoints += differenceInRewards[i]; + } + return maximumPoints; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2612_minimum_reverse_operations/readme.md b/src/main/java/g2601_2700/s2612_minimum_reverse_operations/readme.md new file mode 100644 index 00000000..728e01de --- /dev/null +++ b/src/main/java/g2601_2700/s2612_minimum_reverse_operations/readme.md @@ -0,0 +1,112 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +import java.util.ArrayList; +import java.util.List; + +public class Solution { + public int[] minReverseOperations(int n, int p, int[] banned, int k) { + int[] out = new int[n]; + for (int i = 0; i < n; i++) { + out[i] = -1; + } + for (int node : banned) { + out[node] = -2; + } + List nodes = new ArrayList<>(); + nodes.add(p); + int depth = 0; + out[p] = depth; + int step = k - 1; + int[] nextNode2s = new int[n + 1]; + for (int i = 0; i < n + 1; i++) { + nextNode2s[i] = i + 2; + } + while (!nodes.isEmpty()) { + depth++; + List newNodes = new ArrayList<>(); + for (int node1 : nodes) { + int loReverseStart = Math.max(node1 - step, 0); + int hiReverseStart = Math.min(node1, n - k); + int loNode2 = 2 * loReverseStart + k - 1 - node1; + int hiNode2 = 2 * hiReverseStart + k - 1 - node1; + int postHiNode2 = hiNode2 + 2; + int node2 = loNode2; + while (node2 <= hiNode2) { + int nextNode2 = nextNode2s[node2]; + nextNode2s[node2] = postHiNode2; + if (node2 < n && out[node2] == -1) { + newNodes.add(node2); + out[node2] = depth; + } + node2 = nextNode2; + } + } + nodes = newNodes; + } + for (int i = 0; i < n; i++) { + if (out[i] == -2) { + out[i] = -1; + } + } + return out; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2614_prime_in_diagonal/readme.md b/src/main/java/g2601_2700/s2614_prime_in_diagonal/readme.md new file mode 100644 index 00000000..6e78af8a --- /dev/null +++ b/src/main/java/g2601_2700/s2614_prime_in_diagonal/readme.md @@ -0,0 +1,83 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +public class Solution { + public int diagonalPrime(int[][] nums) { + int i = 0; + int j = nums[0].length - 1; + int lp = 0; + while (i < nums.length) { + int n1 = nums[i][i]; + if (n1 > lp && isPrime(n1)) { + lp = n1; + } + int n2 = nums[i][j]; + if (n2 > lp && isPrime(n2)) { + lp = n2; + } + i++; + j--; + } + return lp; + } + + private boolean isPrime(int n) { + if (n == 1) { + return false; + } + if (n == 2 || n == 3) { + return true; + } + int i = 2; + while (i <= Math.sqrt(n)) { + if (n % i == 0) { + return false; + } + i++; + } + return true; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2615_sum_of_distances/readme.md b/src/main/java/g2601_2700/s2615_sum_of_distances/readme.md new file mode 100644 index 00000000..7a89279e --- /dev/null +++ b/src/main/java/g2601_2700/s2615_sum_of_distances/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +import java.util.HashMap; + +public class Solution { + public long[] distance(int[] nums) { + HashMap map = new HashMap<>(); + for (int i = 0; i < nums.length; i++) { + long[] temp = map.computeIfAbsent(nums[i], k -> new long[4]); + temp[0] += i; + temp[2]++; + } + long[] ans = new long[nums.length]; + for (int i = 0; i < nums.length; i++) { + long[] temp = map.get(nums[i]); + ans[i] += i * temp[3] - temp[1]; + temp[1] += i; + temp[3]++; + ans[i] += temp[0] - temp[1] - i * (temp[2] - temp[3]); + } + return ans; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2616_minimize_the_maximum_difference_of_pairs/readme.md b/src/main/java/g2601_2700/s2616_minimize_the_maximum_difference_of_pairs/readme.md new file mode 100644 index 00000000..365a3afb --- /dev/null +++ b/src/main/java/g2601_2700/s2616_minimize_the_maximum_difference_of_pairs/readme.md @@ -0,0 +1,79 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +import java.util.Arrays; + +public class Solution { + private boolean isPossible(int[] nums, int p, int diff) { + int n = nums.length; + int i = 1; + while (i < n) { + if (nums[i] - nums[i - 1] <= diff) { + p--; + i++; + } + i++; + } + return p <= 0; + } + + public int minimizeMax(int[] nums, int p) { + int n = nums.length; + Arrays.sort(nums); + int left = 0; + int right = nums[n - 1] - nums[0]; + int ans = right; + while (left <= right) { + int 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/java/g2601_2700/s2617_minimum_number_of_visited_cells_in_a_grid/readme.md b/src/main/java/g2601_2700/s2617_minimum_number_of_visited_cells_in_a_grid/readme.md new file mode 100644 index 00000000..df46b7f3 --- /dev/null +++ b/src/main/java/g2601_2700/s2617_minimum_number_of_visited_cells_in_a_grid/readme.md @@ -0,0 +1,112 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 + +```java +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.Queue; + +public class Solution { + private static final int LIMIT = 2; + + public int minimumVisitedCells(int[][] grid) { + int[][] len = new int[grid.length][grid[0].length]; + for (int[] ints : len) { + Arrays.fill(ints, -1); + } + Queue q = new ArrayDeque<>(); + q.add(new int[] {0, 0}); + len[0][0] = 1; + while (!q.isEmpty()) { + int[] tmp = q.poll(); + int i = tmp[0]; + int j = tmp[1]; + int c = 0; + for (int k = Math.min(grid[0].length - 1, grid[i][j] + j); k > j; k--) { + if (len[i][k] != -1) { + c++; + if (c > LIMIT) { + break; + } + } else { + len[i][k] = len[i][j] + 1; + q.add(new int[] {i, k}); + } + } + if (len[grid.length - 1][grid[0].length - 1] != -1) { + return len[grid.length - 1][grid[0].length - 1]; + } + c = 0; + for (int k = Math.min(grid.length - 1, grid[i][j] + i); k > i; k--) { + if (len[k][j] != -1) { + c++; + if (c > LIMIT) { + break; + } + } else { + len[k][j] = len[i][j] + 1; + q.add(new int[] {k, j}); + } + } + if (len[grid.length - 1][grid[0].length - 1] != -1) { + return len[grid.length - 1][grid[0].length - 1]; + } + } + return -1; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2618_check_if_object_instance_of_class/readme.md b/src/main/java/g2601_2700/s2618_check_if_object_instance_of_class/readme.md new file mode 100644 index 00000000..7c16ed2c --- /dev/null +++ b/src/main/java/g2601_2700/s2618_check_if_object_instance_of_class/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 +} + +export { checkIfInstanceOf } +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2619_array_prototype_last/readme.md b/src/main/java/g2601_2700/s2619_array_prototype_last/readme.md new file mode 100644 index 00000000..9ee31597 --- /dev/null +++ b/src/main/java/g2601_2700/s2619_array_prototype_last/readme.md @@ -0,0 +1,51 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 () { //NOSONAR + return this.length !== 0 ? this[this.length - 1] : -1 +} + +/* + * const arr = [1, 2, 3]; + * arr.last(); // 3 + */ + +export {} +``` \ No newline at end of file diff --git a/src/main/java/g2601_2700/s2620_counter/readme.md b/src/main/java/g2601_2700/s2620_counter/readme.md new file mode 100644 index 00000000..3ebd8c90 --- /dev/null +++ b/src/main/java/g2601_2700/s2620_counter/readme.md @@ -0,0 +1,56 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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/java/g2601_2700/s2621_sleep/readme.md b/src/main/java/g2601_2700/s2621_sleep/readme.md new file mode 100644 index 00000000..165ae93e --- /dev/null +++ b/src/main/java/g2601_2700/s2621_sleep/readme.md @@ -0,0 +1,43 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 { + await new Promise((resolve) => 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/java/g2601_2700/s2622_cache_with_time_limit/readme.md b/src/main/java/g2601_2700/s2622_cache_with_time_limit/readme.md new file mode 100644 index 00000000..9e6f7f3b --- /dev/null +++ b/src/main/java/g2601_2700/s2622_cache_with_time_limit/readme.md @@ -0,0 +1,105 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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/java/g2601_2700/s2623_memoize/readme.md b/src/main/java/g2601_2700/s2623_memoize/readme.md new file mode 100644 index 00000000..790d72f8 --- /dev/null +++ b/src/main/java/g2601_2700/s2623_memoize/readme.md @@ -0,0 +1,111 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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/java/g2601_2700/s2624_snail_traversal/readme.md b/src/main/java/g2601_2700/s2624_snail_traversal/readme.md new file mode 100644 index 00000000..a06254e3 --- /dev/null +++ b/src/main/java/g2601_2700/s2624_snail_traversal/readme.md @@ -0,0 +1,77 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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/java/g2601_2700/s2625_flatten_deeply_nested_array/readme.md b/src/main/java/g2601_2700/s2625_flatten_deeply_nested_array/readme.md new file mode 100644 index 00000000..24fd7eff --- /dev/null +++ b/src/main/java/g2601_2700/s2625_flatten_deeply_nested_array/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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/java/g2601_2700/s2626_array_reduce_transformation/readme.md b/src/main/java/g2601_2700/s2626_array_reduce_transformation/readme.md new file mode 100644 index 00000000..bd7069c1 --- /dev/null +++ b/src/main/java/g2601_2700/s2626_array_reduce_transformation/readme.md @@ -0,0 +1,80 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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/java/g2601_2700/s2627_debounce/readme.md b/src/main/java/g2601_2700/s2627_debounce/readme.md new file mode 100644 index 00000000..4bae9dab --- /dev/null +++ b/src/main/java/g2601_2700/s2627_debounce/readme.md @@ -0,0 +1,106 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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/java/g2601_2700/s2629_function_composition/readme.md b/src/main/java/g2601_2700/s2629_function_composition/readme.md new file mode 100644 index 00000000..ec11e5c2 --- /dev/null +++ b/src/main/java/g2601_2700/s2629_function_composition/readme.md @@ -0,0 +1,85 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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 { + return function (x) { + if (functions.length == 0) return x + for (let ind = functions.length - 1; ind >= 0; ind--) { + x = functions[ind](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/java/g2601_2700/s2630_memoize_ii/readme.md b/src/main/java/g2601_2700/s2630_memoize_ii/readme.md new file mode 100644 index 00000000..ac4f2173 --- /dev/null +++ b/src/main/java/g2601_2700/s2630_memoize_ii/readme.md @@ -0,0 +1,124 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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(...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/java/g2601_2700/s2631_group_by/readme.md b/src/main/java/g2601_2700/s2631_group_by/readme.md new file mode 100644 index 00000000..fb578149 --- /dev/null +++ b/src/main/java/g2601_2700/s2631_group_by/readme.md @@ -0,0 +1,124 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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/java/g2601_2700/s2634_filter_elements_from_array/readme.md b/src/main/java/g2601_2700/s2634_filter_elements_from_array/readme.md new file mode 100644 index 00000000..d882bcb2 --- /dev/null +++ b/src/main/java/g2601_2700/s2634_filter_elements_from_array/readme.md @@ -0,0 +1,70 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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/java/g2601_2700/s2635_apply_transform_over_each_element_in_array/readme.md b/src/main/java/g2601_2700/s2635_apply_transform_over_each_element_in_array/readme.md new file mode 100644 index 00000000..fa419d69 --- /dev/null +++ b/src/main/java/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-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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/java/g2601_2700/s2637_promise_time_limit/readme.md b/src/main/java/g2601_2700/s2637_promise_time_limit/readme.md new file mode 100644 index 00000000..7d84684f --- /dev/null +++ b/src/main/java/g2601_2700/s2637_promise_time_limit/readme.md @@ -0,0 +1,124 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/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(new Error('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