diff --git a/README.md b/README.md index 87eb98ef..d529b99a 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) -* [Programming Skills II](#programming-skills-ii) * [Graph Theory I](#graph-theory-i) * [SQL I](#sql-i) * [Level 1](#level-1) @@ -16,149 +15,7 @@ * [Binary Search II](#binary-search-ii) * [Dynamic Programming I](#dynamic-programming-i) * [Programming Skills I](#programming-skills-i) - -### Programming Skills II - -#### Day 1 - -| | | | | | -|-|-|-|-|-|- -| 0896 |[Monotonic Array](src/main/java/g0801_0900/s0896_monotonic_array)| Easy | Array | 2 | 86.21 -| 0028 |[Implement strStr()](src/main/java/g0001_0100/s0028_find_the_index_of_the_first_occurrence_in_a_string)| Easy | Top_Interview_Questions, String, Two_Pointers, String_Matching | 0 | 100.00 - -#### Day 2 - -| | | | | | -|-|-|-|-|-|- -| 0110 |[Balanced Binary Tree](src/main/java/g0101_0200/s0110_balanced_binary_tree)| Easy | Depth_First_Search, Tree, Binary_Tree | 1 | 98.82 -| 0459 |[Repeated Substring Pattern](src/main/java/g0401_0500/s0459_repeated_substring_pattern)| Easy | String, String_Matching | 8 | 96.64 - -#### Day 3 - -| | | | | | -|-|-|-|-|-|- -| 0150 |[Evaluate Reverse Polish Notation](src/main/java/g0101_0200/s0150_evaluate_reverse_polish_notation)| Medium | Top_Interview_Questions, Array, Math, Stack | 9 | 51.23 -| 0066 |[Plus One](src/main/java/g0001_0100/s0066_plus_one)| Easy | Top_Interview_Questions, Array, Math | 0 | 100.00 - -#### Day 4 - -| | | | | | -|-|-|-|-|-|- -| 1367 |[Linked List in Binary Tree](src/main/java/g1301_1400/s1367_linked_list_in_binary_tree)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Linked_List | 2 | 61.23 -| 0043 |[Multiply Strings](src/main/java/g0001_0100/s0043_multiply_strings)| Medium | String, Math, Simulation | 1 | 100.00 - -#### Day 5 - -| | | | | | -|-|-|-|-|-|- -| 0067 |[Add Binary](src/main/java/g0001_0100/s0067_add_binary)| Easy | String, Math, Bit_Manipulation, Simulation | 1 | 100.00 -| 0989 |[Add to Array-Form of Integer](src/main/java/g0901_1000/s0989_add_to_array_form_of_integer)| Easy | Array, Math | 7 | 65.92 - -#### Day 6 - -| | | | | | -|-|-|-|-|-|- -| 0739 |[Daily Temperatures](src/main/java/g0701_0800/s0739_daily_temperatures)| Medium | Top_100_Liked_Questions, Array, Stack, Monotonic_Stack, Big_O_Time_O(n)_Space_O(n) | 10 | 94.99 -| 0058 |[Length of Last Word](src/main/java/g0001_0100/s0058_length_of_last_word)| Easy | String | 0 | 100.00 - -#### Day 7 - -| | | | | | -|-|-|-|-|-|- -| 0048 |[Rotate Image](src/main/java/g0001_0100/s0048_rotate_image)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Matrix, Big_O_Time_O(n^2)_Space_O(1) | 0 | 100.00 -| 1886 |[Determine Whether Matrix Can Be Obtained By Rotation](src/main/java/g1801_1900/s1886_determine_whether_matrix_can_be_obtained_by_rotation)| Easy | Array, Matrix | 1 | 78.38 - -#### Day 8 - -| | | | | | -|-|-|-|-|-|- -| 0054 |[Spiral Matrix](src/main/java/g0001_0100/s0054_spiral_matrix)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Matrix, Simulation | 0 | 100.00 -| 0973 |[K Closest Points to Origin](src/main/java/g0901_1000/s0973_k_closest_points_to_origin)| Medium | Array, Math, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Geometry, Quickselect | 4 | 98.26 - -#### Day 9 - -| | | | | | -|-|-|-|-|-|- -| 1630 |[Arithmetic Subarrays](src/main/java/g1601_1700/s1630_arithmetic_subarrays)| Medium | Array, Sorting | 8 | 93.62 -| 0429 |[N-ary Tree Level Order Traversal](src/main/java/g0401_0500/s0429_n_ary_tree_level_order_traversal)| Medium | Breadth_First_Search, Tree | 3 | 80.26 - -#### Day 10 - -| | | | | | -|-|-|-|-|-|- -| 0503 |[Next Greater Element II](src/main/java/g0501_0600/s0503_next_greater_element_ii)| Medium | Array, Stack, Monotonic_Stack | 7 | 97.03 -| 0556 |[Next Greater Element III](src/main/java/g0501_0600/s0556_next_greater_element_iii)| Medium | String, Math, Two_Pointers | 0 | 100.00 - -#### Day 11 - -| | | | | | -|-|-|-|-|-|- -| 1376 |[Time Needed to Inform All Employees](src/main/java/g1301_1400/s1376_time_needed_to_inform_all_employees)| Medium | Depth_First_Search, Breadth_First_Search, Tree | 8 | 99.85 -| 0049 |[Group Anagrams](src/main/java/g0001_0100/s0049_group_anagrams)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, String, Hash_Table, Sorting, Big_O_Time_O(n\*k_log_k)_Space_O(n) | 6 | 92.28 - -#### Day 12 - -| | | | | | -|-|-|-|-|-|- -| 0438 |[Find All Anagrams in a String](src/main/java/g0401_0500/s0438_find_all_anagrams_in_a_string)| Medium | Top_100_Liked_Questions, String, Hash_Table, Sliding_Window, Big_O_Time_O(n+m)_Space_O(1) | 6 | 99.03 -| 0713 |[Subarray Product Less Than K](src/main/java/g0701_0800/s0713_subarray_product_less_than_k)| Medium | Array, Sliding_Window | 8 | 39.00 - -#### Day 13 - -| | | | | | -|-|-|-|-|-|- -| 0304 |[Range Sum Query 2D - Immutable](src/main/java/g0301_0400/s0304_range_sum_query_2d_immutable)| Medium | Array, Matrix, Design, Prefix_Sum | 153 | 87.51 -| 0910 |[Smallest Range II](src/main/java/g0901_1000/s0910_smallest_range_ii)| Medium | Array, Math, Sorting, Greedy | 10 | 73.16 - -#### Day 14 - -| | | | | | -|-|-|-|-|-|- -| 0143 |[Reorder List](src/main/java/g0101_0200/s0143_reorder_list)| Medium | Two_Pointers, Stack, Linked_List, Recursion | 2 | 72.59 -| 0138 |[Copy List with Random Pointer](src/main/java/g0101_0200/s0138_copy_list_with_random_pointer)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Linked_List, Big_O_Time_O(N)_Space_O(N) | 0 | 100.00 - -#### Day 15 - -| | | | | | -|-|-|-|-|-|- -| 0002 |[Add Two Numbers](src/main/java/g0001_0100/s0002_add_two_numbers)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Math, Linked_List, Recursion, Big_O_Time_O(max(N,M))_Space_O(max(N,M)) | 1 | 100.00 -| 0445 |[Add Two Numbers II](src/main/java/g0401_0500/s0445_add_two_numbers_ii)| Medium | Math, Stack, Linked_List | 3 | 90.38 - -#### Day 16 - -| | | | | | -|-|-|-|-|-|- -| 0061 |[Rotate List](src/main/java/g0001_0100/s0061_rotate_list)| Medium | Two_Pointers, Linked_List | 0 | 100.00 -| 0173 |[Binary Search Tree Iterator](src/main/java/g0101_0200/s0173_binary_search_tree_iterator)| Medium | Tree, Binary_Tree, Stack, Design, Binary_Search_Tree, Iterator | 18 | 84.18 - -#### Day 17 - -| | | | | | -|-|-|-|-|-|- -| 1845 |[Seat Reservation Manager](src/main/java/g1801_1900/s1845_seat_reservation_manager)| Medium | Design, Heap_Priority_Queue | 47 | 87.63 -| 0860 |[Lemonade Change](src/main/java/g0801_0900/s0860_lemonade_change)| Easy | Array, Greedy | 2 | 90.84 - -#### Day 18 - -| | | | | | -|-|-|-|-|-|- -| 0155 |[Min Stack](src/main/java/g0101_0200/s0155_min_stack)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Stack, Design, Big_O_Time_O(1)_Space_O(N) | 3 | 100.00 -| 0341 |[Flatten Nested List Iterator](src/main/java/g0301_0400/s0341_flatten_nested_list_iterator)| Medium | Depth_First_Search, Tree, Stack, Design, Queue, Iterator | 2 | 99.95 - -#### Day 19 - -| | | | | | -|-|-|-|-|-|- -| 1797 |[Design Authentication Manager](src/main/java/g1701_1800/s1797_design_authentication_manager)| Medium | Hash_Table, Design | 41 | 92.67 -| 0707 |[Design Linked List](src/main/java/g0701_0800/s0707_design_linked_list)| Medium | Design, Linked_List | 10 | 70.60 - -#### Day 20 - -| | | | | | -|-|-|-|-|-|- -| 0380 |[Insert Delete GetRandom O(1)](src/main/java/g0301_0400/s0380_insert_delete_getrandom_o1)| Medium | Array, Hash_Table, Math, Design, Randomized | 27 | 93.44 -| 0622 |[Design Circular Queue](src/main/java/g0601_0700/s0622_design_circular_queue)| Medium | Array, Design, Linked_List, Queue | 3 | 100.00 -| 0729 |[My Calendar I](src/main/java/g0701_0800/s0729_my_calendar_i)| Medium | Binary_Search, Design, Ordered_Set, Segment_Tree | 17 | 97.23 +* [Programming Skills II](#programming-skills-ii) ### Graph Theory I @@ -1812,10 +1669,173 @@ | 1603 |[Design Parking System](src/main/java/g1601_1700/s1603_design_parking_system)| Easy | Design, Simulation, Counting | 8 | 76.16 | 0303 |[Range Sum Query - Immutable](src/main/java/g0301_0400/s0303_range_sum_query_immutable)| Easy | Array, Design, Prefix_Sum | 7 | 100.00 +### Programming Skills II + +#### Day 1 + +| | | | | | +|-|-|-|-|-|- +| 0896 |[Monotonic Array](src/main/java/g0801_0900/s0896_monotonic_array)| Easy | Array | 2 | 86.21 +| 0028 |[Implement strStr()](src/main/java/g0001_0100/s0028_find_the_index_of_the_first_occurrence_in_a_string)| Easy | Top_Interview_Questions, String, Two_Pointers, String_Matching | 0 | 100.00 + +#### Day 2 + +| | | | | | +|-|-|-|-|-|- +| 0110 |[Balanced Binary Tree](src/main/java/g0101_0200/s0110_balanced_binary_tree)| Easy | Depth_First_Search, Tree, Binary_Tree | 1 | 98.82 +| 0459 |[Repeated Substring Pattern](src/main/java/g0401_0500/s0459_repeated_substring_pattern)| Easy | String, String_Matching | 8 | 96.64 + +#### Day 3 + +| | | | | | +|-|-|-|-|-|- +| 0150 |[Evaluate Reverse Polish Notation](src/main/java/g0101_0200/s0150_evaluate_reverse_polish_notation)| Medium | Top_Interview_Questions, Array, Math, Stack | 9 | 51.23 +| 0066 |[Plus One](src/main/java/g0001_0100/s0066_plus_one)| Easy | Top_Interview_Questions, Array, Math | 0 | 100.00 + +#### Day 4 + +| | | | | | +|-|-|-|-|-|- +| 1367 |[Linked List in Binary Tree](src/main/java/g1301_1400/s1367_linked_list_in_binary_tree)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Linked_List | 2 | 61.23 +| 0043 |[Multiply Strings](src/main/java/g0001_0100/s0043_multiply_strings)| Medium | String, Math, Simulation | 1 | 100.00 + +#### Day 5 + +| | | | | | +|-|-|-|-|-|- +| 0067 |[Add Binary](src/main/java/g0001_0100/s0067_add_binary)| Easy | String, Math, Bit_Manipulation, Simulation | 1 | 100.00 +| 0989 |[Add to Array-Form of Integer](src/main/java/g0901_1000/s0989_add_to_array_form_of_integer)| Easy | Array, Math | 7 | 65.92 + +#### Day 6 + +| | | | | | +|-|-|-|-|-|- +| 0739 |[Daily Temperatures](src/main/java/g0701_0800/s0739_daily_temperatures)| Medium | Top_100_Liked_Questions, Array, Stack, Monotonic_Stack, Big_O_Time_O(n)_Space_O(n) | 10 | 94.99 +| 0058 |[Length of Last Word](src/main/java/g0001_0100/s0058_length_of_last_word)| Easy | String | 0 | 100.00 + +#### Day 7 + +| | | | | | +|-|-|-|-|-|- +| 0048 |[Rotate Image](src/main/java/g0001_0100/s0048_rotate_image)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Math, Matrix, Big_O_Time_O(n^2)_Space_O(1) | 0 | 100.00 +| 1886 |[Determine Whether Matrix Can Be Obtained By Rotation](src/main/java/g1801_1900/s1886_determine_whether_matrix_can_be_obtained_by_rotation)| Easy | Array, Matrix | 1 | 78.38 + +#### Day 8 + +| | | | | | +|-|-|-|-|-|- +| 0054 |[Spiral Matrix](src/main/java/g0001_0100/s0054_spiral_matrix)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Matrix, Simulation | 0 | 100.00 +| 0973 |[K Closest Points to Origin](src/main/java/g0901_1000/s0973_k_closest_points_to_origin)| Medium | Array, Math, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Geometry, Quickselect | 4 | 98.26 + +#### Day 9 + +| | | | | | +|-|-|-|-|-|- +| 1630 |[Arithmetic Subarrays](src/main/java/g1601_1700/s1630_arithmetic_subarrays)| Medium | Array, Sorting | 8 | 93.62 +| 0429 |[N-ary Tree Level Order Traversal](src/main/java/g0401_0500/s0429_n_ary_tree_level_order_traversal)| Medium | Breadth_First_Search, Tree | 3 | 80.26 + +#### Day 10 + +| | | | | | +|-|-|-|-|-|- +| 0503 |[Next Greater Element II](src/main/java/g0501_0600/s0503_next_greater_element_ii)| Medium | Array, Stack, Monotonic_Stack | 7 | 97.03 +| 0556 |[Next Greater Element III](src/main/java/g0501_0600/s0556_next_greater_element_iii)| Medium | String, Math, Two_Pointers | 0 | 100.00 + +#### Day 11 + +| | | | | | +|-|-|-|-|-|- +| 1376 |[Time Needed to Inform All Employees](src/main/java/g1301_1400/s1376_time_needed_to_inform_all_employees)| Medium | Depth_First_Search, Breadth_First_Search, Tree | 8 | 99.85 +| 0049 |[Group Anagrams](src/main/java/g0001_0100/s0049_group_anagrams)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, String, Hash_Table, Sorting, Big_O_Time_O(n\*k_log_k)_Space_O(n) | 6 | 92.28 + +#### Day 12 + +| | | | | | +|-|-|-|-|-|- +| 0438 |[Find All Anagrams in a String](src/main/java/g0401_0500/s0438_find_all_anagrams_in_a_string)| Medium | Top_100_Liked_Questions, String, Hash_Table, Sliding_Window, Big_O_Time_O(n+m)_Space_O(1) | 6 | 99.03 +| 0713 |[Subarray Product Less Than K](src/main/java/g0701_0800/s0713_subarray_product_less_than_k)| Medium | Array, Sliding_Window | 8 | 39.00 + +#### Day 13 + +| | | | | | +|-|-|-|-|-|- +| 0304 |[Range Sum Query 2D - Immutable](src/main/java/g0301_0400/s0304_range_sum_query_2d_immutable)| Medium | Array, Matrix, Design, Prefix_Sum | 153 | 87.51 +| 0910 |[Smallest Range II](src/main/java/g0901_1000/s0910_smallest_range_ii)| Medium | Array, Math, Sorting, Greedy | 10 | 73.16 + +#### Day 14 + +| | | | | | +|-|-|-|-|-|- +| 0143 |[Reorder List](src/main/java/g0101_0200/s0143_reorder_list)| Medium | Two_Pointers, Stack, Linked_List, Recursion | 2 | 72.59 +| 0138 |[Copy List with Random Pointer](src/main/java/g0101_0200/s0138_copy_list_with_random_pointer)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Hash_Table, Linked_List, Big_O_Time_O(N)_Space_O(N) | 0 | 100.00 + +#### Day 15 + +| | | | | | +|-|-|-|-|-|- +| 0002 |[Add Two Numbers](src/main/java/g0001_0100/s0002_add_two_numbers)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Math, Linked_List, Recursion, Big_O_Time_O(max(N,M))_Space_O(max(N,M)) | 1 | 100.00 +| 0445 |[Add Two Numbers II](src/main/java/g0401_0500/s0445_add_two_numbers_ii)| Medium | Math, Stack, Linked_List | 3 | 90.38 + +#### Day 16 + +| | | | | | +|-|-|-|-|-|- +| 0061 |[Rotate List](src/main/java/g0001_0100/s0061_rotate_list)| Medium | Two_Pointers, Linked_List | 0 | 100.00 +| 0173 |[Binary Search Tree Iterator](src/main/java/g0101_0200/s0173_binary_search_tree_iterator)| Medium | Tree, Binary_Tree, Stack, Design, Binary_Search_Tree, Iterator | 18 | 84.18 + +#### Day 17 + +| | | | | | +|-|-|-|-|-|- +| 1845 |[Seat Reservation Manager](src/main/java/g1801_1900/s1845_seat_reservation_manager)| Medium | Design, Heap_Priority_Queue | 47 | 87.63 +| 0860 |[Lemonade Change](src/main/java/g0801_0900/s0860_lemonade_change)| Easy | Array, Greedy | 2 | 90.84 + +#### Day 18 + +| | | | | | +|-|-|-|-|-|- +| 0155 |[Min Stack](src/main/java/g0101_0200/s0155_min_stack)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Stack, Design, Big_O_Time_O(1)_Space_O(N) | 3 | 100.00 +| 0341 |[Flatten Nested List Iterator](src/main/java/g0301_0400/s0341_flatten_nested_list_iterator)| Medium | Depth_First_Search, Tree, Stack, Design, Queue, Iterator | 2 | 99.95 + +#### Day 19 + +| | | | | | +|-|-|-|-|-|- +| 1797 |[Design Authentication Manager](src/main/java/g1701_1800/s1797_design_authentication_manager)| Medium | Hash_Table, Design | 41 | 92.67 +| 0707 |[Design Linked List](src/main/java/g0701_0800/s0707_design_linked_list)| Medium | Design, Linked_List | 10 | 70.60 + +#### Day 20 + +| | | | | | +|-|-|-|-|-|- +| 0380 |[Insert Delete GetRandom O(1)](src/main/java/g0301_0400/s0380_insert_delete_getrandom_o1)| Medium | Array, Hash_Table, Math, Design, Randomized | 27 | 93.44 +| 0622 |[Design Circular Queue](src/main/java/g0601_0700/s0622_design_circular_queue)| Medium | Array, Design, Linked_List, Queue | 3 | 100.00 +| 0729 |[My Calendar I](src/main/java/g0701_0800/s0729_my_calendar_i)| Medium | Binary_Search, Design, Ordered_Set, Segment_Tree | 17 | 97.23 + ## Algorithms | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- +| 3149 |[Find the Minimum Cost Array Permutation](src/main/java/g3101_3200/s3149_find_the_minimum_cost_array_permutation)| Hard | Array, Dynamic_Programming, Bit_Manipulation, Bitmask | 105 | 88.11 +| 3148 |[Maximum Difference Score in a Grid](src/main/java/g3101_3200/s3148_maximum_difference_score_in_a_grid)| Medium | Array, Dynamic_Programming, Matrix | 5 | 100.00 +| 3147 |[Taking Maximum Energy From the Mystic Dungeon](src/main/java/g3101_3200/s3147_taking_maximum_energy_from_the_mystic_dungeon)| Medium | Array, Prefix_Sum | 2 | 97.58 +| 3146 |[Permutation Difference between Two Strings](src/main/java/g3101_3200/s3146_permutation_difference_between_two_strings)| Easy | String, Hash_Table | 1 | 100.00 +| 3145 |[Find Products of Elements of Big Array](src/main/java/g3101_3200/s3145_find_products_of_elements_of_big_array)| Hard | Array, Binary_Search, Bit_Manipulation | 3 | 98.41 +| 3144 |[Minimum Substring Partition of Equal Character Frequency](src/main/java/g3101_3200/s3144_minimum_substring_partition_of_equal_character_frequency)| Medium | String, Hash_Table, Dynamic_Programming, Counting | 37 | 100.00 +| 3143 |[Maximum Points Inside the Square](src/main/java/g3101_3200/s3143_maximum_points_inside_the_square)| Medium | Array, String, Hash_Table, Sorting, Binary_Search | 2 | 100.00 +| 3142 |[Check if Grid Satisfies Conditions](src/main/java/g3101_3200/s3142_check_if_grid_satisfies_conditions)| Easy | Array, Matrix | 1 | 95.76 +| 3139 |[Minimum Cost to Equalize Array](src/main/java/g3101_3200/s3139_minimum_cost_to_equalize_array)| Hard | Array, Greedy, Enumeration | 1 | 100.00 +| 3138 |[Minimum Length of Anagram Concatenation](src/main/java/g3101_3200/s3138_minimum_length_of_anagram_concatenation)| Medium | String, Hash_Table, Counting | 4 | 84.18 +| 3137 |[Minimum Number of Operations to Make Word K-Periodic](src/main/java/g3101_3200/s3137_minimum_number_of_operations_to_make_word_k_periodic)| Medium | String, Hash_Table, Counting | 19 | 99.53 +| 3136 |[Valid Word](src/main/java/g3101_3200/s3136_valid_word)| Easy | String | 1 | 99.39 +| 3134 |[Find the Median of the Uniqueness Array](src/main/java/g3101_3200/s3134_find_the_median_of_the_uniqueness_array)| Hard | Array, Hash_Table, Binary_Search, Sliding_Window | 47 | 100.00 +| 3133 |[Minimum Array End](src/main/java/g3101_3200/s3133_minimum_array_end)| Medium | Bit_Manipulation | 1 | 92.38 +| 3132 |[Find the Integer Added to Array II](src/main/java/g3101_3200/s3132_find_the_integer_added_to_array_ii)| Medium | Array, Sorting, Two_Pointers, Enumeration | 2 | 100.00 +| 3131 |[Find the Integer Added to Array I](src/main/java/g3101_3200/s3131_find_the_integer_added_to_array_i)| Easy | Array | 0 | 100.00 +| 3130 |[Find All Possible Stable Binary Arrays II](src/main/java/g3101_3200/s3130_find_all_possible_stable_binary_arrays_ii)| Hard | Dynamic_Programming, Prefix_Sum | 3 | 100.00 +| 3129 |[Find All Possible Stable Binary Arrays I](src/main/java/g3101_3200/s3129_find_all_possible_stable_binary_arrays_i)| Medium | Dynamic_Programming, Prefix_Sum | 3 | 100.00 +| 3128 |[Right Triangles](src/main/java/g3101_3200/s3128_right_triangles)| Medium | Array, Hash_Table, Math, Counting, Combinatorics | 6 | 100.00 +| 3127 |[Make a Square with the Same Color](src/main/java/g3101_3200/s3127_make_a_square_with_the_same_color)| Easy | Array, Matrix, Enumeration | 0 | 100.00 | 3123 |[Find Edges in Shortest Paths](src/main/java/g3101_3200/s3123_find_edges_in_shortest_paths)| Hard | Depth_First_Search, Breadth_First_Search, Heap_Priority_Queue, Graph, Shortest_Path | 24 | 100.00 | 3122 |[Minimum Number of Operations to Satisfy Conditions](src/main/java/g3101_3200/s3122_minimum_number_of_operations_to_satisfy_conditions)| Medium | Array, Dynamic_Programming, Matrix | 6 | 100.00 | 3121 |[Count the Number of Special Characters II](src/main/java/g3101_3200/s3121_count_the_number_of_special_characters_ii)| Medium | String, Hash_Table | 6 | 100.00 @@ -2502,7 +2522,7 @@ | 2244 |[Minimum Rounds to Complete All Tasks](src/main/java/g2201_2300/s2244_minimum_rounds_to_complete_all_tasks)| Medium | Array, Hash_Table, Greedy, Counting | 13 | 94.26 | 2243 |[Calculate Digit Sum of a String](src/main/java/g2201_2300/s2243_calculate_digit_sum_of_a_string)| Easy | String, Simulation | 1 | 91.46 | 2242 |[Maximum Score of a Node Sequence](src/main/java/g2201_2300/s2242_maximum_score_of_a_node_sequence)| Hard | Array, Sorting, Graph, Enumeration | 28 | 97.57 -| 2241 |[Design an ATM Machine](src/main/java/g2201_2300/s2241_design_an_atm_machine)| Medium | Array, Greedy, Design | 192 | 24.16 +| 2241 |[Design an ATM Machine](src/main/java/g2201_2300/s2241_design_an_atm_machine)| Medium | Array, Greedy, Design | 55 | 94.44 | 2240 |[Number of Ways to Buy Pens and Pencils](src/main/java/g2201_2300/s2240_number_of_ways_to_buy_pens_and_pencils)| Medium | Math, Enumeration | 19 | 68.73 | 2239 |[Find Closest Number to Zero](src/main/java/g2201_2300/s2239_find_closest_number_to_zero)| Easy | Array | 2 | 84.21 | 2236 |[Root Equals Sum of Children](src/main/java/g2201_2300/s2236_root_equals_sum_of_children)| Easy | Tree, Binary_Tree | 0 | 100.00 @@ -2647,7 +2667,7 @@ | 2059 |[Minimum Operations to Convert Number](src/main/java/g2001_2100/s2059_minimum_operations_to_convert_number)| Medium | Array, Breadth_First_Search | 97 | 64.14 | 2058 |[Find the Minimum and Maximum Number of Nodes Between Critical Points](src/main/java/g2001_2100/s2058_find_the_minimum_and_maximum_number_of_nodes_between_critical_points)| Medium | Linked_List | 4 | 100.00 | 2057 |[Smallest Index With Equal Value](src/main/java/g2001_2100/s2057_smallest_index_with_equal_value)| Easy | Array | 1 | 94.39 -| 2056 |[Number of Valid Move Combinations On Chessboard](src/main/java/g2001_2100/s2056_number_of_valid_move_combinations_on_chessboard)| Hard | Array, String, Simulation, Backtracking | 433 | 24.83 +| 2056 |[Number of Valid Move Combinations On Chessboard](src/main/java/g2001_2100/s2056_number_of_valid_move_combinations_on_chessboard)| Hard | Array, String, Simulation, Backtracking | 195 | 41.18 | 2055 |[Plates Between Candles](src/main/java/g2001_2100/s2055_plates_between_candles)| Medium | Array, String, Binary_Search, Prefix_Sum | 10 | 92.49 | 2054 |[Two Best Non-Overlapping Events](src/main/java/g2001_2100/s2054_two_best_non_overlapping_events)| Medium | Array, Dynamic_Programming, Sorting, Binary_Search, Heap_Priority_Queue | 58 | 70.59 | 2053 |[Kth Distinct String in an Array](src/main/java/g2001_2100/s2053_kth_distinct_string_in_an_array)| Easy | Array, String, Hash_Table, Counting | 7 | 65.75 @@ -3366,7 +3386,7 @@ | 1139 |[Largest 1-Bordered Square](src/main/java/g1101_1200/s1139_largest_1_bordered_square)| Medium | Array, Dynamic_Programming, Matrix | 4 | 88.04 | 1138 |[Alphabet Board Path](src/main/java/g1101_1200/s1138_alphabet_board_path)| Medium | String, Hash_Table | 1 | 48.92 | 1137 |[N-th Tribonacci Number](src/main/java/g1101_1200/s1137_n_th_tribonacci_number)| Easy | Dynamic_Programming, Math, Memoization, Dynamic_Programming_I_Day_1 | 0 | 100.00 -| 1131 |[Maximum of Absolute Value Expression](src/main/java/g1101_1200/s1131_maximum_of_absolute_value_expression)| Medium | Array, Math | 13 | 24.81 +| 1131 |[Maximum of Absolute Value Expression](src/main/java/g1101_1200/s1131_maximum_of_absolute_value_expression)| Medium | Array, Math | 1 | 100.00 | 1130 |[Minimum Cost Tree From Leaf Values](src/main/java/g1101_1200/s1130_minimum_cost_tree_from_leaf_values)| Medium | Dynamic_Programming, Greedy, Stack, Monotonic_Stack | 1 | 98.05 | 1129 |[Shortest Path with Alternating Colors](src/main/java/g1101_1200/s1129_shortest_path_with_alternating_colors)| Medium | Breadth_First_Search, Graph, Graph_Theory_I_Day_10_Standard_Traversal | 4 | 96.63 | 1128 |[Number of Equivalent Domino Pairs](src/main/java/g1101_1200/s1128_number_of_equivalent_domino_pairs)| Easy | Array, Hash_Table, Counting | 15 | 51.49 @@ -3471,7 +3491,7 @@ | 0993 |[Cousins in Binary Tree](src/main/java/g0901_1000/s0993_cousins_in_binary_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 1 | 60.08 | 0992 |[Subarrays with K Different Integers](src/main/java/g0901_1000/s0992_subarrays_with_k_different_integers)| Hard | Array, Hash_Table, Counting, Sliding_Window | 4 | 99.36 | 0991 |[Broken Calculator](src/main/java/g0901_1000/s0991_broken_calculator)| Medium | Math, Greedy | 0 | 100.00 -| 0990 |[Satisfiability of Equality Equations](src/main/java/g0901_1000/s0990_satisfiability_of_equality_equations)| Medium | Array, String, Graph, Union_Find | 5 | 24.79 +| 0990 |[Satisfiability of Equality Equations](src/main/java/g0901_1000/s0990_satisfiability_of_equality_equations)| Medium | Array, String, Graph, Union_Find | 0 | 100.00 | 0989 |[Add to Array-Form of Integer](src/main/java/g0901_1000/s0989_add_to_array_form_of_integer)| Easy | Array, Math, Programming_Skills_II_Day_5 | 7 | 65.92 | 0988 |[Smallest String Starting From Leaf](src/main/java/g0901_1000/s0988_smallest_string_starting_from_leaf)| Medium | String, Depth_First_Search, Tree, Binary_Tree | 4 | 58.47 | 0987 |[Vertical Order Traversal of a Binary Tree](src/main/java/g0901_1000/s0987_vertical_order_traversal_of_a_binary_tree)| Hard | Hash_Table, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 4 | 71.48 @@ -4213,7 +4233,7 @@ | 0096 |[Unique Binary Search Trees](src/main/java/g0001_0100/s0096_unique_binary_search_trees)| Medium | Dynamic_Programming, Math, Tree, Binary_Tree, Binary_Search_Tree, Dynamic_Programming_I_Day_11, Big_O_Time_O(n)_Space_O(1) | 0 | 100.00 | 0095 |[Unique Binary Search Trees II](src/main/java/g0001_0100/s0095_unique_binary_search_trees_ii)| Medium | Dynamic_Programming, Tree, Binary_Tree, Backtracking, Binary_Search_Tree | 1 | 99.82 | 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, Data_Structure_I_Day_10_Tree, Udemy_Tree_Stack_Queue, Big_O_Time_O(n)_Space_O(n) | 0 | 100.00 -| 0093 |[Restore IP Addresses](src/main/java/g0001_0100/s0093_restore_ip_addresses)| Medium | String, Backtracking | 13 | 24.23 +| 0093 |[Restore IP Addresses](src/main/java/g0001_0100/s0093_restore_ip_addresses)| Medium | String, Backtracking | 1 | 99.27 | 0092 |[Reverse Linked List II](src/main/java/g0001_0100/s0092_reverse_linked_list_ii)| Medium | Linked_List | 0 | 100.00 | 0091 |[Decode Ways](src/main/java/g0001_0100/s0091_decode_ways)| Medium | Top_Interview_Questions, String, Dynamic_Programming, Algorithm_II_Day_15_Dynamic_Programming, Dynamic_Programming_I_Day_10 | 2 | 66.37 | 0090 |[Subsets II](src/main/java/g0001_0100/s0090_subsets_ii)| Medium | Array, Bit_Manipulation, Backtracking, Algorithm_II_Day_9_Recursion_Backtracking | 2 | 82.94 diff --git a/src/main/java/g0001_0100/s0002_add_two_numbers/readme.md b/src/main/java/g0001_0100/s0002_add_two_numbers/readme.md index b6840e8f..418f0ea9 100644 --- a/src/main/java/g0001_0100/s0002_add_two_numbers/readme.md +++ b/src/main/java/g0001_0100/s0002_add_two_numbers/readme.md @@ -125,7 +125,7 @@ public class Solution { solution.printList(result2); ListNode l5 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))))))); - ListNode l6 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))))); + ListNode l6 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))); ListNode result3 = solution.addTwoNumbers(l5, l6); System.out.print("Example 3 Output: "); solution.printList(result3); diff --git a/src/main/java/g0001_0100/s0093_restore_ip_addresses/readme.md b/src/main/java/g0001_0100/s0093_restore_ip_addresses/readme.md index 6fcfb54d..7e65c2c5 100644 --- a/src/main/java/g0001_0100/s0093_restore_ip_addresses/readme.md +++ b/src/main/java/g0001_0100/s0093_restore_ip_addresses/readme.md @@ -53,36 +53,48 @@ import java.util.ArrayList; import java.util.List; public class Solution { + private static final int SEG_COUNT = 4; + private List result = new ArrayList<>(); + private int[] segments = new int[SEG_COUNT]; + public List restoreIpAddresses(String s) { - List results = new ArrayList<>(); - step(s, 0, new int[4], 0, results); - return results; + dfs(s, 0, 0); + return result; } - void step(String s, int pos, int[] octets, int count, List results) { - if (count == 4 && pos == s.length()) { - results.add( - String.valueOf(octets[0]) - + '.' - + octets[1] - + '.' - + octets[2] - + '.' - + octets[3]); - } else if (count < 4 && pos < 12) { - int octet = 0; - for (int i = 0; i < 3; i++) { - if (pos + i < s.length()) { - int digit = s.charAt(pos + i) - '0'; - octet = octet * 10 + digit; - if (octet < 256) { - octets[count] = octet; - step(s, pos + i + 1, octets, count + 1, results); - } - if (i == 0 && digit == 0) { - break; + public void dfs(String s, int segId, int segStart) { + // find 4 segments and get to last index + if (segId == SEG_COUNT) { + if (segStart == s.length()) { + StringBuilder addr = new StringBuilder(); + for (int i = 0; i < SEG_COUNT; i++) { + addr.append(segments[i]); + if (i != SEG_COUNT - 1) { + addr.append('.'); } } + result.add(addr.toString()); + } + return; + } + // last index and no 4 segments + if (segStart == s.length()) { + return; + } + // start with a zero + if (s.charAt(segStart) == '0') { + segments[segId] = 0; + dfs(s, segId + 1, segStart + 1); + return; + } + int addr = 0; + for (int index = segStart; index < s.length(); index++) { + addr = addr * 10 + s.charAt(index) - '0'; + if (addr >= 0 && addr <= 255) { + segments[segId] = addr; + dfs(s, segId + 1, index + 1); + } else { + break; } } } diff --git a/src/main/java/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md b/src/main/java/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md index d1ffefd5..a8f08b97 100644 --- a/src/main/java/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md +++ b/src/main/java/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md @@ -66,7 +66,7 @@ class Solution { } // Recursive helper method to construct binary tree - private TreeNode build(int[] preorder, int[] inorder, int preStart, preEnd, int inStart, int inEnd) { + private TreeNode build(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd) { if (preStart > preEnd || inStart > inEnd) return null; // Base case int rootValue = preorder[preStart]; // Root node value diff --git a/src/main/java/g0201_0300/s0232_implement_queue_using_stacks/readme.md b/src/main/java/g0201_0300/s0232_implement_queue_using_stacks/readme.md index 2cd4f3ec..c920620b 100644 --- a/src/main/java/g0201_0300/s0232_implement_queue_using_stacks/readme.md +++ b/src/main/java/g0201_0300/s0232_implement_queue_using_stacks/readme.md @@ -56,6 +56,7 @@ import java.util.Deque; public class MyQueue { private Deque left; private Deque right; + // Initialize your data structure here. public MyQueue() { left = new ArrayDeque<>(); diff --git a/src/main/java/g0301_0400/s0315_count_of_smaller_numbers_after_self/readme.md b/src/main/java/g0301_0400/s0315_count_of_smaller_numbers_after_self/readme.md index d5d49692..70edf61a 100644 --- a/src/main/java/g0301_0400/s0315_count_of_smaller_numbers_after_self/readme.md +++ b/src/main/java/g0301_0400/s0315_count_of_smaller_numbers_after_self/readme.md @@ -72,6 +72,7 @@ public class Solution { bit[i] += v; } } + // prefix sum query private int ps(int j) { int ps = 0; diff --git a/src/main/java/g0901_1000/s0990_satisfiability_of_equality_equations/readme.md b/src/main/java/g0901_1000/s0990_satisfiability_of_equality_equations/readme.md index eb0914b4..3bf5d18c 100644 --- a/src/main/java/g0901_1000/s0990_satisfiability_of_equality_equations/readme.md +++ b/src/main/java/g0901_1000/s0990_satisfiability_of_equality_equations/readme.md @@ -39,59 +39,32 @@ There is no way to assign the variables to satisfy both equations. ## Solution ```java -import java.util.HashMap; - public class Solution { - private int[] par; + private int[] parent = new int[26]; - public boolean equationsPossible(String[] equations) { - int counter = 0; - HashMap map = new HashMap<>(); - for (String str : equations) { - char ch = str.charAt(0); - if (!map.containsKey(ch)) { - map.put(ch, counter); - counter++; - } - ch = str.charAt(3); - if (!map.containsKey(ch)) { - map.put(ch, counter); - counter++; - } + private int find(int x) { + if (parent[x] == x) { + return x; } - par = new int[counter]; - for (int i = 0; i < par.length; i++) { - par[i] = i; + parent[x] = find(parent[x]); + return parent[x]; + } + + public boolean equationsPossible(String[] equations) { + for (int i = 0; i < 26; i++) { + parent[i] = i; } - for (String str : equations) { - String oper = str.substring(1, 3); - if (oper.equals("==")) { - int px = find(map.get(str.charAt(0))); - int py = find(map.get(str.charAt(3))); - if (px != py) { - par[px] = py; - } + for (String e : equations) { + if (e.charAt(1) == '=') { + parent[find(e.charAt(0) - 'a')] = find(e.charAt(3) - 'a'); } } - for (String str : equations) { - String oper = str.substring(1, 3); - if (oper.equals("!=")) { - int px = find(map.get(str.charAt(0))); - int py = find(map.get(str.charAt(3))); - if (px == py) { - return false; - } + for (String e : equations) { + if (e.charAt(1) == '!' && find(e.charAt(0) - 'a') == find(e.charAt(3) - 'a')) { + return false; } } return true; } - - private int find(int x) { - if (par[x] == x) { - return x; - } - par[x] = find(par[x]); - return par[x]; - } } ``` \ No newline at end of file diff --git a/src/main/java/g1101_1200/s1131_maximum_of_absolute_value_expression/readme.md b/src/main/java/g1101_1200/s1131_maximum_of_absolute_value_expression/readme.md index 068fce6b..88bee8fc 100644 --- a/src/main/java/g1101_1200/s1131_maximum_of_absolute_value_expression/readme.md +++ b/src/main/java/g1101_1200/s1131_maximum_of_absolute_value_expression/readme.md @@ -32,29 +32,30 @@ where the maximum is taken over all `0 <= i, j < arr1.length`. ```java public class Solution { - public int maxAbsValExpr(int[] arr1, int[] arr2) { - if (arr1.length != arr2.length) { + private int max(int[] a1, int[] a2, int k1, int k2, int k3) { + int result = Integer.MIN_VALUE; + for (int i = 0; i < a1.length; i++) { + result = Math.max(result, a1[i] * k1 + a2[i] * k2 + i * k3); + } + return result; + } + + private int min(int[] a1, int[] a2, int k1, int k2, int k3) { + return -max(a1, a2, -k1, -k2, -k3); + } + + public int maxAbsValExpr(int[] a1, int[] a2) { + if (a1 == null || a2 == null || a1.length == 0 || a2.length == 0) { return 0; } - int max1 = Integer.MIN_VALUE; - int max2 = Integer.MIN_VALUE; - int max3 = Integer.MIN_VALUE; - int max4 = Integer.MIN_VALUE; - int min1 = Integer.MAX_VALUE; - int min2 = Integer.MAX_VALUE; - int min3 = Integer.MAX_VALUE; - int min4 = Integer.MAX_VALUE; - for (int i = 0; i < arr1.length; i++) { - max1 = Math.max(arr1[i] + arr2[i] + i, max1); - min1 = Math.min(arr1[i] + arr2[i] + i, min1); - max2 = Math.max(i - arr1[i] - arr2[i], max2); - min2 = Math.min(i - arr1[i] - arr2[i], min2); - max3 = Math.max(arr1[i] - arr2[i] + i, max3); - min3 = Math.min(arr1[i] - arr2[i] + i, min3); - max4 = Math.max(arr2[i] - arr1[i] + i, max4); - min4 = Math.min(arr2[i] - arr1[i] + i, min4); + int result = 0; + int[][] ksArray = { {1, 1, 1}, {1, 1, -1}, {1, -1, 1}, {1, -1, -1}}; + for (int[] ks : ksArray) { + int max = max(a1, a2, ks[0], ks[1], ks[2]); + int min = min(a1, a2, ks[0], ks[1], ks[2]); + result = Math.max(result, max - min); } - return Math.max(Math.max(max1 - min1, max2 - min2), Math.max(max3 - min3, max4 - min4)); + return result; } } ``` \ No newline at end of file diff --git a/src/main/java/g1301_1400/s1391_check_if_there_is_a_valid_path_in_a_grid/readme.md b/src/main/java/g1301_1400/s1391_check_if_there_is_a_valid_path_in_a_grid/readme.md index 522570a3..143cb885 100644 --- a/src/main/java/g1301_1400/s1391_check_if_there_is_a_valid_path_in_a_grid/readme.md +++ b/src/main/java/g1301_1400/s1391_check_if_there_is_a_valid_path_in_a_grid/readme.md @@ -72,6 +72,7 @@ public class Solution { { {0, -1}, {-1, 0}}, { {0, 1}, {-1, 0}} }; + // the idea is you need to check port direction match, you can go to next cell and check whether // you can come back. public boolean hasValidPath(int[][] grid) { diff --git a/src/main/java/g2301_2400/s2397_maximum_rows_covered_by_columns/readme.md b/src/main/java/g2301_2400/s2397_maximum_rows_covered_by_columns/readme.md index 62a8ec4d..186c49e5 100644 --- a/src/main/java/g2301_2400/s2397_maximum_rows_covered_by_columns/readme.md +++ b/src/main/java/g2301_2400/s2397_maximum_rows_covered_by_columns/readme.md @@ -67,7 +67,7 @@ public class Solution { private int ans = 0; public int maximumRows(int[][] matrix, int numSelect) { - dfs(matrix, /*colIndex=*/ 0, numSelect, /*mask=*/ 0); + dfs(matrix, /* colIndex= */ 0, numSelect, /* mask= */ 0); return ans; } diff --git a/src/main/java/g3101_3200/s3127_make_a_square_with_the_same_color/readme.md b/src/main/java/g3101_3200/s3127_make_a_square_with_the_same_color/readme.md new file mode 100644 index 00000000..e2cd40da --- /dev/null +++ b/src/main/java/g3101_3200/s3127_make_a_square_with_the_same_color/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) + +## 3127\. Make a Square with the Same Color + +Easy + +You are given a 2D matrix `grid` of size `3 x 3` consisting only of characters `'B'` and `'W'`. Character `'W'` represents the white color, and character `'B'` represents the black color. + +Your task is to change the color of **at most one** cell so that the matrix has a `2 x 2` square where all cells are of the same color. + +Return `true` if it is possible to create a `2 x 2` square of the same color, otherwise, return `false`. + +**Example 1:** + +**Input:** grid = \[\["B","W","B"],["B","W","W"],["B","W","B"]] + +**Output:** true + +**Explanation:** + +It can be done by changing the color of the `grid[0][2]`. + +**Example 2:** + +**Input:** grid = \[\["B","W","B"],["W","B","W"],["B","W","B"]] + +**Output:** false + +**Explanation:** + +It cannot be done by changing at most one cell. + +**Example 3:** + +**Input:** grid = \[\["B","W","B"],["B","W","W"],["B","W","W"]] + +**Output:** true + +**Explanation:** + +The `grid` already contains a `2 x 2` square of the same color. + +**Constraints:** + +* `grid.length == 3` +* `grid[i].length == 3` +* `grid[i][j]` is either `'W'` or `'B'`. + +## Solution + +```java +public class Solution { + public boolean canMakeSquare(char[][] grid) { + int n = grid.length; + int m = grid[0].length; + for (int i = 0; i < n - 1; i++) { + for (int j = 0; j < m - 1; j++) { + int countBlack = 0; + int countWhite = 0; + for (int k = i; k <= i + 1; k++) { + for (int l = j; l <= j + 1; l++) { + if (grid[k][l] == 'W') { + countWhite++; + } else { + countBlack++; + } + } + } + if (countBlack >= 3 || countWhite >= 3) { + return true; + } + } + } + return false; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3128_right_triangles/readme.md b/src/main/java/g3101_3200/s3128_right_triangles/readme.md new file mode 100644 index 00000000..ddab82b2 --- /dev/null +++ b/src/main/java/g3101_3200/s3128_right_triangles/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) + +## 3128\. Right Triangles + +Medium + +You are given a 2D boolean matrix `grid`. + +Return an integer that is the number of **right triangles** that can be made with the 3 elements of `grid` such that **all** of them have a value of 1. + +**Note:** + +* A collection of 3 elements of `grid` is a **right triangle** if one of its elements is in the **same row** with another element and in the **same column** with the third element. The 3 elements do not have to be next to each other. + +**Example 1:** + +0 **1** 0 + +0 **1 1** + +0 1 0 + +0 1 0 + +0 **1 1** + +0 **1** 0 + +**Input:** grid = \[\[0,1,0],[0,1,1],[0,1,0]] + +**Output:** 2 + +**Explanation:** + +There are two right triangles. + +**Example 2:** + +1 0 0 0 + +0 1 0 1 + +1 0 0 0 + +**Input:** grid = \[\[1,0,0,0],[0,1,0,1],[1,0,0,0]] + +**Output:** 0 + +**Explanation:** + +There are no right triangles. + +**Example 3:** + +**1** 0 **1** + +**1** 0 0 + +1 0 0 + +**1** 0 **1** + +1 0 0 + +**1** 0 0 + +**Input:** grid = \[\[1,0,1],[1,0,0],[1,0,0]] + +**Output: **2 + +**Explanation:** + +There are two right triangles. + +**Constraints:** + +* `1 <= grid.length <= 1000` +* `1 <= grid[i].length <= 1000` +* `0 <= grid[i][j] <= 1` + +## Solution + +```java +public class Solution { + public long numberOfRightTriangles(int[][] grid) { + int n = grid.length; + int m = grid[0].length; + int[] columns = new int[n]; + int[] rows = new int[m]; + long sum = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + columns[i] += grid[i][j]; + rows[j] += grid[i][j]; + } + } + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + sum += (long) grid[i][j] * (rows[j] - 1) * (columns[i] - 1); + } + } + return sum; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3129_find_all_possible_stable_binary_arrays_i/readme.md b/src/main/java/g3101_3200/s3129_find_all_possible_stable_binary_arrays_i/readme.md new file mode 100644 index 00000000..c33c5f57 --- /dev/null +++ b/src/main/java/g3101_3200/s3129_find_all_possible_stable_binary_arrays_i/readme.md @@ -0,0 +1,108 @@ +[![](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) + +## 3129\. Find All Possible Stable Binary Arrays I + +Medium + +You are given 3 positive integers `zero`, `one`, and `limit`. + +A binary array `arr` is called **stable** if: + +* The number of occurrences of 0 in `arr` is **exactly** `zero`. +* The number of occurrences of 1 in `arr` is **exactly** `one`. +* Each subarray of `arr` with a size greater than `limit` must contain **both** 0 and 1. + +Return the _total_ number of **stable** binary arrays. + +Since the answer may be very large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** zero = 1, one = 1, limit = 2 + +**Output:** 2 + +**Explanation:** + +The two possible stable binary arrays are `[1,0]` and `[0,1]`, as both arrays have a single 0 and a single 1, and no subarray has a length greater than 2. + +**Example 2:** + +**Input:** zero = 1, one = 2, limit = 1 + +**Output:** 1 + +**Explanation:** + +The only possible stable binary array is `[1,0,1]`. + +Note that the binary arrays `[1,1,0]` and `[0,1,1]` have subarrays of length 2 with identical elements, hence, they are not stable. + +**Example 3:** + +**Input:** zero = 3, one = 3, limit = 2 + +**Output:** 14 + +**Explanation:** + +All the possible stable binary arrays are `[0,0,1,0,1,1]`, `[0,0,1,1,0,1]`, `[0,1,0,0,1,1]`, `[0,1,0,1,0,1]`, `[0,1,0,1,1,0]`, `[0,1,1,0,0,1]`, `[0,1,1,0,1,0]`, `[1,0,0,1,0,1]`, `[1,0,0,1,1,0]`, `[1,0,1,0,0,1]`, `[1,0,1,0,1,0]`, `[1,0,1,1,0,0]`, `[1,1,0,0,1,0]`, and `[1,1,0,1,0,0]`. + +**Constraints:** + +* `1 <= zero, one, limit <= 200` + +## Solution + +```java +public class Solution { + private static final int MODULUS = (int) 1e9 + 7; + + private int add(int x, int y) { + return (x + y) % MODULUS; + } + + private int subtract(int x, int y) { + return (x + MODULUS - y) % MODULUS; + } + + private int multiply(int x, int y) { + return (int) ((long) x * y % MODULUS); + } + + public int numberOfStableArrays(int zero, int one, int limit) { + if (limit == 1) { + return Math.max(2 - Math.abs(zero - one), 0); + } + int max = Math.max(zero, one); + int min = Math.min(zero, one); + int[][] lcn = new int[max + 1][max + 1]; + int[] row0 = lcn[0]; + int[] row1; + int[] row2; + row0[0] = 1; + for (int s = 1, sLim = s - limit; s <= max; s++, sLim++) { + row2 = sLim > 0 ? lcn[sLim - 1] : new int[] {}; + row1 = row0; + row0 = lcn[s]; + int c; + for (c = (s - 1) / limit + 1; c <= sLim; c++) { + row0[c] = subtract(add(row1[c], row1[c - 1]), row2[c - 1]); + } + for (; c <= s; c++) { + row0[c] = add(row1[c], row1[c - 1]); + } + } + row1 = lcn[min]; + int result = 0; + int s0 = add(min < max ? row0[min + 1] : 0, row0[min]); + for (int c = min; c > 0; c--) { + int s1 = s0; + s0 = add(row0[c], row0[c - 1]); + result = add(result, multiply(row1[c], add(s0, s1))); + } + return result; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3130_find_all_possible_stable_binary_arrays_ii/readme.md b/src/main/java/g3101_3200/s3130_find_all_possible_stable_binary_arrays_ii/readme.md new file mode 100644 index 00000000..e358428c --- /dev/null +++ b/src/main/java/g3101_3200/s3130_find_all_possible_stable_binary_arrays_ii/readme.md @@ -0,0 +1,138 @@ +[![](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) + +## 3130\. Find All Possible Stable Binary Arrays II + +Hard + +You are given 3 positive integers `zero`, `one`, and `limit`. + +A binary array `arr` is called **stable** if: + +* The number of occurrences of 0 in `arr` is **exactly** `zero`. +* The number of occurrences of 1 in `arr` is **exactly** `one`. +* Each subarray of `arr` with a size greater than `limit` must contain **both** 0 and 1. + +Return the _total_ number of **stable** binary arrays. + +Since the answer may be very large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** zero = 1, one = 1, limit = 2 + +**Output:** 2 + +**Explanation:** + +The two possible stable binary arrays are `[1,0]` and `[0,1]`. + +**Example 2:** + +**Input:** zero = 1, one = 2, limit = 1 + +**Output:** 1 + +**Explanation:** + +The only possible stable binary array is `[1,0,1]`. + +**Example 3:** + +**Input:** zero = 3, one = 3, limit = 2 + +**Output:** 14 + +**Explanation:** + +All the possible stable binary arrays are `[0,0,1,0,1,1]`, `[0,0,1,1,0,1]`, `[0,1,0,0,1,1]`, `[0,1,0,1,0,1]`, `[0,1,0,1,1,0]`, `[0,1,1,0,0,1]`, `[0,1,1,0,1,0]`, `[1,0,0,1,0,1]`, `[1,0,0,1,1,0]`, `[1,0,1,0,0,1]`, `[1,0,1,0,1,0]`, `[1,0,1,1,0,0]`, `[1,1,0,0,1,0]`, and `[1,1,0,1,0,0]`. + +**Constraints:** + +* `1 <= zero, one, limit <= 1000` + +## Solution + +```java +public class Solution { + private static final int MOD = (int) 1e9 + 7; + private static final int N = 1000; + private long[] factorial; + private long[] reverse; + + public int numberOfStableArrays(int zero, int one, int limit) { + if (factorial == null) { + factorial = new long[N + 1]; + reverse = new long[N + 1]; + factorial[0] = 1; + reverse[0] = 1; + long x = 1; + for (int i = 1; i <= N; ++i) { + x = (x * i) % MOD; + factorial[i] = (int) x; + reverse[i] = getInverse(x, MOD); + } + } + long ans = 0; + long[] s = new long[one + 1]; + int n = Math.min(zero, one) + 1; + for (int groups0 = (zero + limit - 1) / limit; groups0 <= Math.min(zero, n); ++groups0) { + long s0 = calc(groups0, zero, limit); + for (int groups1 = Math.max(groups0 - 1, (one + limit - 1) / limit); + groups1 <= Math.min(groups0 + 1, one); + ++groups1) { + long s1; + if (s[groups1] != 0) { + s1 = s[groups1]; + } else { + s1 = s[groups1] = calc(groups1, one, limit); + } + ans = (ans + s0 * s1 * (groups1 == groups0 ? 2 : 1)) % MOD; + } + } + return (int) ((ans + MOD) % MOD); + } + + long calc(int groups, int x, int limit) { + long s = 0; + int sign = 1; + for (int k = 0; k * limit <= x - groups && k <= groups; k++) { + s = (s + sign * comb(groups, k) * comb(x - k * limit - 1, groups - 1)) % MOD; + sign *= -1; + } + return s; + } + + public long comb(int n, int k) { + return (factorial[n] * reverse[k] % MOD) * reverse[n - k] % MOD; + } + + public long getInverse(long n, long mod) { + long p = mod; + long x = 1; + long y = 0; + while (p > 0) { + long quotient = n / p; + long remainder = n % p; + long tempY = x - quotient * y; + x = y; + y = tempY; + n = p; + p = remainder; + } + return ((x % mod) + mod) % mod; + } + + public long quickPower(long base, long power, long p) { + long result = 1; + while (power > 0) { + if ((power & 1) == 1) { + result = result * base % p; + } + power >>= 1; + base = base * base % p; + } + return result; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3131_find_the_integer_added_to_array_i/readme.md b/src/main/java/g3101_3200/s3131_find_the_integer_added_to_array_i/readme.md new file mode 100644 index 00000000..9b9f428c --- /dev/null +++ b/src/main/java/g3101_3200/s3131_find_the_integer_added_to_array_i/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) + +## 3131\. Find the Integer Added to Array I + +Easy + +You are given two arrays of equal length, `nums1` and `nums2`. + +Each element in `nums1` has been increased (or decreased in the case of negative) by an integer, represented by the variable `x`. + +As a result, `nums1` becomes **equal** to `nums2`. Two arrays are considered **equal** when they contain the same integers with the same frequencies. + +Return the integer `x`. + +**Example 1:** + +**Input:** nums1 = [2,6,4], nums2 = [9,7,5] + +**Output:** 3 + +**Explanation:** + +The integer added to each element of `nums1` is 3. + +**Example 2:** + +**Input:** nums1 = [10], nums2 = [5] + +**Output:** \-5 + +**Explanation:** + +The integer added to each element of `nums1` is -5. + +**Example 3:** + +**Input:** nums1 = [1,1,1,1], nums2 = [1,1,1,1] + +**Output:** 0 + +**Explanation:** + +The integer added to each element of `nums1` is 0. + +**Constraints:** + +* `1 <= nums1.length == nums2.length <= 100` +* `0 <= nums1[i], nums2[i] <= 1000` +* The test cases are generated in a way that there is an integer `x` such that `nums1` can become equal to `nums2` by adding `x` to each element of `nums1`. + +## Solution + +```java +public class Solution { + public int addedInteger(int[] nums1, int[] nums2) { + int n1 = nums1.length; + int s1 = 0; + int s2 = 0; + for (int i : nums1) { + s1 += i; + } + for (int i : nums2) { + s2 += i; + } + return (s2 - s1) / n1; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3132_find_the_integer_added_to_array_ii/readme.md b/src/main/java/g3101_3200/s3132_find_the_integer_added_to_array_ii/readme.md new file mode 100644 index 00000000..6b032f96 --- /dev/null +++ b/src/main/java/g3101_3200/s3132_find_the_integer_added_to_array_ii/readme.md @@ -0,0 +1,76 @@ +[![](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) + +## 3132\. Find the Integer Added to Array II + +Medium + +You are given two integer arrays `nums1` and `nums2`. + +From `nums1` two elements have been removed, and all other elements have been increased (or decreased in the case of negative) by an integer, represented by the variable `x`. + +As a result, `nums1` becomes **equal** to `nums2`. Two arrays are considered **equal** when they contain the same integers with the same frequencies. + +Return the **minimum** possible integer `x` that achieves this equivalence. + +**Example 1:** + +**Input:** nums1 = [4,20,16,12,8], nums2 = [14,18,10] + +**Output:** \-2 + +**Explanation:** + +After removing elements at indices `[0,4]` and adding -2, `nums1` becomes `[18,14,10]`. + +**Example 2:** + +**Input:** nums1 = [3,5,5,3], nums2 = [7,7] + +**Output:** 2 + +**Explanation:** + +After removing elements at indices `[0,3]` and adding 2, `nums1` becomes `[7,7]`. + +**Constraints:** + +* `3 <= nums1.length <= 200` +* `nums2.length == nums1.length - 2` +* `0 <= nums1[i], nums2[i] <= 1000` +* The test cases are generated in a way that there is an integer `x` such that `nums1` can become equal to `nums2` by removing two elements and adding `x` to each element of `nums1`. + +## Solution + +```java +import java.util.Arrays; + +public class Solution { + public int minimumAddedInteger(int[] nums1, int[] nums2) { + Arrays.sort(nums1); + Arrays.sort(nums2); + if (checkOk(nums1, nums2, 2)) { + return nums2[0] - nums1[2]; + } else if (checkOk(nums1, nums2, 1)) { + return nums2[0] - nums1[1]; + } else { + return nums2[0] - nums1[0]; + } + } + + private boolean checkOk(int[] nums1, int[] nums2, int start) { + int i = 0; + int diff = nums2[i] - nums1[start]; + while (i < nums2.length) { + if (start - i > 2) { + return false; + } + if (nums2[i] == nums1[start] + diff) { + i++; + } + start++; + } + return i == nums2.length; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3133_minimum_array_end/readme.md b/src/main/java/g3101_3200/s3133_minimum_array_end/readme.md new file mode 100644 index 00000000..4324b58b --- /dev/null +++ b/src/main/java/g3101_3200/s3133_minimum_array_end/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) + +## 3133\. Minimum Array End + +Medium + +You are given two integers `n` and `x`. You have to construct an array of **positive** integers `nums` of size `n` where for every `0 <= i < n - 1`, `nums[i + 1]` is **greater than** `nums[i]`, and the result of the bitwise `AND` operation between all elements of `nums` is `x`. + +Return the **minimum** possible value of `nums[n - 1]`. + +**Example 1:** + +**Input:** n = 3, x = 4 + +**Output:** 6 + +**Explanation:** + +`nums` can be `[4,5,6]` and its last element is 6. + +**Example 2:** + +**Input:** n = 2, x = 7 + +**Output:** 15 + +**Explanation:** + +`nums` can be `[7,15]` and its last element is 15. + +**Constraints:** + +* 1 <= n, x <= 108 + +## Solution + +```java +public class Solution { + public long minEnd(int n, int x) { + n = n - 1; + int[] xb = new int[64]; + int[] nb = new int[64]; + for (int i = 0; i < 32; i++) { + xb[i] = (x >> i) & 1; + nb[i] = (n >> i) & 1; + } + int i = 0; + int j = 0; + while (i < 64) { + if (xb[i] != 1) { + xb[i] = nb[j++]; + } + i++; + } + long ans = 0; + long p = 1; + for (i = 0; i < 64; i++) { + ans += (xb[i]) * p; + p *= 2; + } + return ans; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3134_find_the_median_of_the_uniqueness_array/readme.md b/src/main/java/g3101_3200/s3134_find_the_median_of_the_uniqueness_array/readme.md new file mode 100644 index 00000000..f89cfb31 --- /dev/null +++ b/src/main/java/g3101_3200/s3134_find_the_median_of_the_uniqueness_array/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) + +## 3134\. Find the Median of the Uniqueness Array + +Hard + +You are given an integer array `nums`. The **uniqueness array** of `nums` is the sorted array that contains the number of distinct elements of all the subarrays of `nums`. In other words, it is a sorted array consisting of `distinct(nums[i..j])`, for all `0 <= i <= j < nums.length`. + +Here, `distinct(nums[i..j])` denotes the number of distinct elements in the subarray that starts at index `i` and ends at index `j`. + +Return the **median** of the **uniqueness array** of `nums`. + +**Note** that the **median** of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the **smaller** of the two values is taken. + +**Example 1:** + +**Input:** nums = [1,2,3] + +**Output:** 1 + +**Explanation:** + +The uniqueness array of `nums` is `[distinct(nums[0..0]), distinct(nums[1..1]), distinct(nums[2..2]), distinct(nums[0..1]), distinct(nums[1..2]), distinct(nums[0..2])]` which is equal to `[1, 1, 1, 2, 2, 3]`. The uniqueness array has a median of 1. Therefore, the answer is 1. + +**Example 2:** + +**Input:** nums = [3,4,3,4,5] + +**Output:** 2 + +**Explanation:** + +The uniqueness array of `nums` is `[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3]`. The uniqueness array has a median of 2. Therefore, the answer is 2. + +**Example 3:** + +**Input:** nums = [4,3,5,4] + +**Output:** 2 + +**Explanation:** + +The uniqueness array of `nums` is `[1, 1, 1, 1, 2, 2, 2, 3, 3, 3]`. The uniqueness array has a median of 2. Therefore, the answer is 2. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 105 + +## Solution + +```java +public class Solution { + public int medianOfUniquenessArray(int[] nums) { + int max = 0; + for (int x : nums) { + max = Math.max(max, x); + } + int n = nums.length; + long k = ((long) n * (n + 1) / 2 + 1) / 2; + int left = 0; + int right = n / 2; + while (left <= right) { + int mid = left + right >> 1; + if (check(nums, max, mid, k)) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return left; + } + + private boolean check(int[] nums, int max, int target, long k) { + long count = 0; + int distinct = 0; + int n = nums.length; + int left = 0; + int right = 0; + int[] freq = new int[max + 1]; + while (right < n) { + int x = nums[right++]; + if (++freq[x] == 1) { + distinct++; + } + while (distinct > target) { + x = nums[left++]; + if (--freq[x] == 0) { + distinct--; + } + } + count += right - left; + if (count >= k) { + return true; + } + } + return false; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3136_valid_word/readme.md b/src/main/java/g3101_3200/s3136_valid_word/readme.md new file mode 100644 index 00000000..0953f27e --- /dev/null +++ b/src/main/java/g3101_3200/s3136_valid_word/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) + +## 3136\. Valid Word + +Easy + +A word is considered **valid** if: + +* It contains a **minimum** of 3 characters. +* It contains only digits (0-9), and English letters (uppercase and lowercase). +* It includes **at least** one **vowel**. +* It includes **at least** one **consonant**. + +You are given a string `word`. + +Return `true` if `word` is valid, otherwise, return `false`. + +**Notes:** + +* `'a'`, `'e'`, `'i'`, `'o'`, `'u'`, and their uppercases are **vowels**. +* A **consonant** is an English letter that is not a vowel. + +**Example 1:** + +**Input:** word = "234Adas" + +**Output:** true + +**Explanation:** + +This word satisfies the conditions. + +**Example 2:** + +**Input:** word = "b3" + +**Output:** false + +**Explanation:** + +The length of this word is fewer than 3, and does not have a vowel. + +**Example 3:** + +**Input:** word = "a3$e" + +**Output:** false + +**Explanation:** + +This word contains a `'$'` character and does not have a consonant. + +**Constraints:** + +* `1 <= word.length <= 20` +* `word` consists of English uppercase and lowercase letters, digits, `'@'`, `'#'`, and `'$'`. + +## Solution + +```java +public class Solution { + public boolean isValid(String word) { + if (word.length() < 3) { + return false; + } + if (word.contains("@") || word.contains("#") || word.contains("$")) { + return false; + } + char[] vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; + char[] consonants = { + 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', + 'w', 'x', 'y', 'z', 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', + 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z' + }; + boolean flag1 = false; + boolean flag2 = false; + for (char c : vowels) { + if (word.indexOf(c) != -1) { + flag1 = true; + break; + } + } + for (char c : consonants) { + if (word.indexOf(c) != -1) { + flag2 = true; + break; + } + } + return flag1 && flag2; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3137_minimum_number_of_operations_to_make_word_k_periodic/readme.md b/src/main/java/g3101_3200/s3137_minimum_number_of_operations_to_make_word_k_periodic/readme.md new file mode 100644 index 00000000..a84b5c59 --- /dev/null +++ b/src/main/java/g3101_3200/s3137_minimum_number_of_operations_to_make_word_k_periodic/readme.md @@ -0,0 +1,73 @@ +[![](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) + +## 3137\. Minimum Number of Operations to Make Word K-Periodic + +Medium + +You are given a string `word` of size `n`, and an integer `k` such that `k` divides `n`. + +In one operation, you can pick any two indices `i` and `j`, that are divisible by `k`, then replace the substring of length `k` starting at `i` with the substring of length `k` starting at `j`. That is, replace the substring `word[i..i + k - 1]` with the substring `word[j..j + k - 1]`. + +Return _the **minimum** number of operations required to make_ `word` _**k-periodic**_. + +We say that `word` is **k-periodic** if there is some string `s` of length `k` such that `word` can be obtained by concatenating `s` an arbitrary number of times. For example, if `word == “ababab”`, then `word` is 2-periodic for `s = "ab"`. + +**Example 1:** + +**Input:** word = "leetcodeleet", k = 4 + +**Output:** 1 + +**Explanation:** + +We can obtain a 4-periodic string by picking i = 4 and j = 0. After this operation, word becomes equal to "leetleetleet". + +**Example 2:** + +**Input:** word = "leetcoleet", k = 2 + +**Output:** 3 + +**Explanation:** + +We can obtain a 2-periodic string by applying the operations in the table below. + + i j word + 0 2 etetcoleet + 4 0 etetetleet + 6 0 etetetetet + +**Constraints:** + +* 1 <= n == word.length <= 105 +* `1 <= k <= word.length` +* `k` divides `word.length`. +* `word` consists only of lowercase English letters. + +## Solution + +```java +import java.util.HashMap; +import java.util.Map; + +public class Solution { + public int minimumOperationsToMakeKPeriodic(String word, int k) { + Map map = new HashMap<>(); + int n = word.length(); + int max = 0; + for (int i = 0; i < n; i += k) { + int hash = 0; + for (int j = i; j < i + k; j++) { + int idx = word.charAt(j) - 'a'; + hash = hash * 26 + idx; + } + int count = map.getOrDefault(hash, 0); + count++; + map.put(hash, count); + max = Math.max(max, count); + } + return n / k - max; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3138_minimum_length_of_anagram_concatenation/readme.md b/src/main/java/g3101_3200/s3138_minimum_length_of_anagram_concatenation/readme.md new file mode 100644 index 00000000..96501ba4 --- /dev/null +++ b/src/main/java/g3101_3200/s3138_minimum_length_of_anagram_concatenation/readme.md @@ -0,0 +1,94 @@ +[![](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) + +## 3138\. Minimum Length of Anagram Concatenation + +Medium + +You are given a string `s`, which is known to be a concatenation of **anagrams** of some string `t`. + +Return the **minimum** possible length of the string `t`. + +An **anagram** is formed by rearranging the letters of a string. For example, "aab", "aba", and, "baa" are anagrams of "aab". + +**Example 1:** + +**Input:** s = "abba" + +**Output:** 2 + +**Explanation:** + +One possible string `t` could be `"ba"`. + +**Example 2:** + +**Input:** s = "cdef" + +**Output:** 4 + +**Explanation:** + +One possible string `t` could be `"cdef"`, notice that `t` can be equal to `s`. + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` consist only of lowercase English letters. + +## Solution + +```java +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class Solution { + public int minAnagramLength(String s) { + int n = s.length(); + int[] sq = new int[n]; + for (int i = 0; i < s.length(); i++) { + int ch = s.charAt(i); + if (i == 0) { + sq[i] = ch * ch; + } else { + sq[i] = sq[i - 1] + ch * ch; + } + } + List factors = getAllFactorsVer2(n); + Collections.sort(factors); + for (int j = 0; j < factors.size(); j++) { + int factor = factors.get(j); + if (factor == 1) { + if (sq[0] * n == sq[n - 1]) { + return 1; + } + } else { + int sum = sq[factor - 1]; + int start = 0; + for (int i = factor - 1; i < n; i += factor) { + if (start + sum != sq[i]) { + break; + } + start += sum; + if (i == n - 1) { + return factor; + } + } + } + } + return n - 1; + } + + private List getAllFactorsVer2(int n) { + List factors = new ArrayList<>(); + for (int i = 1; i <= Math.sqrt(n); i++) { + if (n % i == 0) { + factors.add(i); + factors.add(n / i); + } + } + return factors; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3139_minimum_cost_to_equalize_array/readme.md b/src/main/java/g3101_3200/s3139_minimum_cost_to_equalize_array/readme.md new file mode 100644 index 00000000..c9787084 --- /dev/null +++ b/src/main/java/g3101_3200/s3139_minimum_cost_to_equalize_array/readme.md @@ -0,0 +1,118 @@ +[![](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) + +## 3139\. Minimum Cost to Equalize Array + +Hard + +You are given an integer array `nums` and two integers `cost1` and `cost2`. You are allowed to perform **either** of the following operations **any** number of times: + +* Choose an index `i` from `nums` and **increase** `nums[i]` by `1` for a cost of `cost1`. +* Choose two **different** indices `i`, `j`, from `nums` and **increase** `nums[i]` and `nums[j]` by `1` for a cost of `cost2`. + +Return the **minimum** **cost** required to make all elements in the array **equal**_._ + +Since the answer may be very large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** nums = [4,1], cost1 = 5, cost2 = 2 + +**Output:** 15 + +**Explanation:** + +The following operations can be performed to make the values equal: + +* Increase `nums[1]` by 1 for a cost of 5. `nums` becomes `[4,2]`. +* Increase `nums[1]` by 1 for a cost of 5. `nums` becomes `[4,3]`. +* Increase `nums[1]` by 1 for a cost of 5. `nums` becomes `[4,4]`. + +The total cost is 15. + +**Example 2:** + +**Input:** nums = [2,3,3,3,5], cost1 = 2, cost2 = 1 + +**Output:** 6 + +**Explanation:** + +The following operations can be performed to make the values equal: + +* Increase `nums[0]` and `nums[1]` by 1 for a cost of 1. `nums` becomes `[3,4,3,3,5]`. +* Increase `nums[0]` and `nums[2]` by 1 for a cost of 1. `nums` becomes `[4,4,4,3,5]`. +* Increase `nums[0]` and `nums[3]` by 1 for a cost of 1. `nums` becomes `[5,4,4,4,5]`. +* Increase `nums[1]` and `nums[2]` by 1 for a cost of 1. `nums` becomes `[5,5,5,4,5]`. +* Increase `nums[3]` by 1 for a cost of 2. `nums` becomes `[5,5,5,5,5]`. + +The total cost is 6. + +**Example 3:** + +**Input:** nums = [3,5,3], cost1 = 1, cost2 = 3 + +**Output:** 4 + +**Explanation:** + +The following operations can be performed to make the values equal: + +* Increase `nums[0]` by 1 for a cost of 1. `nums` becomes `[4,5,3]`. +* Increase `nums[0]` by 1 for a cost of 1. `nums` becomes `[5,5,3]`. +* Increase `nums[2]` by 1 for a cost of 1. `nums` becomes `[5,5,4]`. +* Increase `nums[2]` by 1 for a cost of 1. `nums` becomes `[5,5,5]`. + +The total cost is 4. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 106 +* 1 <= cost1 <= 106 +* 1 <= cost2 <= 106 + +## Solution + +```java +public class Solution { + private static final int MOD = 1_000_000_007; + private static final long LMOD = MOD; + + public int minCostToEqualizeArray(int[] nums, int cost1, int cost2) { + long max = 0L; + long min = Long.MAX_VALUE; + long sum = 0L; + for (long num : nums) { + if (num > max) { + max = num; + } + if (num < min) { + min = num; + } + sum += num; + } + final int n = nums.length; + long total = max * n - sum; + // When operation one is always better: + if ((cost1 << 1) <= cost2 || n <= 2) { + return (int) (total * cost1 % LMOD); + } + // When operation two is moderately better: + long op1 = Math.max(0L, ((max - min) << 1L) - total); + long op2 = total - op1; + long result = (op1 + (op2 & 1L)) * cost1 + (op2 >> 1L) * cost2; + // When operation two is significantly better: + total += op1 / (n - 2L) * n; + op1 %= n - 2L; + op2 = total - op1; + result = Math.min(result, (op1 + (op2 & 1L)) * cost1 + (op2 >> 1L) * cost2); + // When operation two is always better: + for (int i = 0; i < 2; ++i) { + total += n; + result = Math.min(result, (total & 1L) * cost1 + (total >> 1L) * cost2); + } + return (int) (result % LMOD); + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3142_check_if_grid_satisfies_conditions/readme.md b/src/main/java/g3101_3200/s3142_check_if_grid_satisfies_conditions/readme.md new file mode 100644 index 00000000..799944ed --- /dev/null +++ b/src/main/java/g3101_3200/s3142_check_if_grid_satisfies_conditions/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) + +## 3142\. Check if Grid Satisfies Conditions + +Easy + +You are given a 2D matrix `grid` of size `m x n`. You need to check if each cell `grid[i][j]` is: + +* Equal to the cell below it, i.e. `grid[i][j] == grid[i + 1][j]` (if it exists). +* Different from the cell to its right, i.e. `grid[i][j] != grid[i][j + 1]` (if it exists). + +Return `true` if **all** the cells satisfy these conditions, otherwise, return `false`. + +**Example 1:** + +**Input:** grid = \[\[1,0,2],[1,0,2]] + +**Output:** true + +**Explanation:** + +**![](https://assets.leetcode.com/uploads/2024/04/15/examplechanged.png)** + +All the cells in the grid satisfy the conditions. + +**Example 2:** + +**Input:** grid = \[\[1,1,1],[0,0,0]] + +**Output:** false + +**Explanation:** + +**![](https://assets.leetcode.com/uploads/2024/03/27/example21.png)** + +All cells in the first row are equal. + +**Example 3:** + +**Input:** grid = \[\[1],[2],[3]] + +**Output:** false + +**Explanation:** + +![](https://assets.leetcode.com/uploads/2024/03/31/changed.png) + +Cells in the first column have different values. + +**Constraints:** + +* `1 <= n, m <= 10` +* `0 <= grid[i][j] <= 9` + +## Solution + +```java +public class Solution { + public boolean satisfiesConditions(int[][] grid) { + int m = grid.length; + int n = grid[0].length; + for (int i = 0; i < m - 1; i++) { + if (n > 1) { + for (int j = 0; j < n - 1; j++) { + if ((grid[i][j] != grid[i + 1][j]) || (grid[i][j] == grid[i][j + 1])) { + return false; + } + } + } else { + if (grid[i][0] != grid[i + 1][0]) { + return false; + } + } + } + for (int j = 0; j < n - 1; j++) { + if (grid[m - 1][j] == grid[m - 1][j + 1]) { + return false; + } + } + return true; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3143_maximum_points_inside_the_square/readme.md b/src/main/java/g3101_3200/s3143_maximum_points_inside_the_square/readme.md new file mode 100644 index 00000000..9180773d --- /dev/null +++ b/src/main/java/g3101_3200/s3143_maximum_points_inside_the_square/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) + +## 3143\. Maximum Points Inside the Square + +Medium + +You are given a 2D array `points` and a string `s` where, `points[i]` represents the coordinates of point `i`, and `s[i]` represents the **tag** of point `i`. + +A **valid** square is a square centered at the origin `(0, 0)`, has edges parallel to the axes, and **does not** contain two points with the same tag. + +Return the **maximum** number of points contained in a **valid** square. + +Note: + +* A point is considered to be inside the square if it lies on or within the square's boundaries. +* The side length of the square can be zero. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2024/03/29/3708-tc1.png) + +**Input:** points = \[\[2,2],[-1,-2],[-4,4],[-3,1],[3,-3]], s = "abdca" + +**Output:** 2 + +**Explanation:** + +The square of side length 4 covers two points `points[0]` and `points[1]`. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2024/03/29/3708-tc2.png) + +**Input:** points = \[\[1,1],[-2,-2],[-2,2]], s = "abb" + +**Output:** 1 + +**Explanation:** + +The square of side length 2 covers one point, which is `points[0]`. + +**Example 3:** + +**Input:** points = \[\[1,1],[-1,-1],[2,-2]], s = "ccd" + +**Output:** 0 + +**Explanation:** + +It's impossible to make any valid squares centered at the origin such that it covers only one point among `points[0]` and `points[1]`. + +**Constraints:** + +* 1 <= s.length, points.length <= 105 +* `points[i].length == 2` +* -109 <= points[i][0], points[i][1] <= 109 +* `s.length == points.length` +* `points` consists of distinct coordinates. +* `s` consists only of lowercase English letters. + +## Solution + +```java +import java.util.Arrays; + +public class Solution { + public int maxPointsInsideSquare(int[][] points, String s) { + int[] tags = new int[26]; + Arrays.fill(tags, Integer.MAX_VALUE); + int secondMin = Integer.MAX_VALUE; + for (int i = 0; i < s.length(); i++) { + int dist = Math.max(Math.abs(points[i][0]), Math.abs(points[i][1])); + char c = s.charAt(i); + if (tags[c - 'a'] == Integer.MAX_VALUE) { + tags[c - 'a'] = dist; + } else if (dist < tags[c - 'a']) { + secondMin = Math.min(secondMin, tags[c - 'a']); + tags[c - 'a'] = dist; + } else { + secondMin = Math.min(secondMin, dist); + } + } + int count = 0; + for (int dist : tags) { + if (dist < secondMin) { + count++; + } + } + return count; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3144_minimum_substring_partition_of_equal_character_frequency/readme.md b/src/main/java/g3101_3200/s3144_minimum_substring_partition_of_equal_character_frequency/readme.md new file mode 100644 index 00000000..b6f27c63 --- /dev/null +++ b/src/main/java/g3101_3200/s3144_minimum_substring_partition_of_equal_character_frequency/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) + +## 3144\. Minimum Substring Partition of Equal Character Frequency + +Medium + +Given a string `s`, you need to partition it into one or more **balanced** substrings. For example, if `s == "ababcc"` then `("abab", "c", "c")`, `("ab", "abc", "c")`, and `("ababcc")` are all valid partitions, but ("a", **"bab"**, "cc"), (**"aba"**, "bc", "c"), and ("ab", **"abcc"**) are not. The unbalanced substrings are bolded. + +Return the **minimum** number of substrings that you can partition `s` into. + +**Note:** A **balanced** string is a string where each character in the string occurs the same number of times. + +**Example 1:** + +**Input:** s = "fabccddg" + +**Output:** 3 + +**Explanation:** + +We can partition the string `s` into 3 substrings in one of the following ways: `("fab, "ccdd", "g")`, or `("fabc", "cd", "dg")`. + +**Example 2:** + +**Input:** s = "abababaccddb" + +**Output:** 2 + +**Explanation:** + +We can partition the string `s` into 2 substrings like so: `("abab", "abaccddb")`. + +**Constraints:** + +* `1 <= s.length <= 1000` +* `s` consists only of English lowercase letters. + +## Solution + +```java +import java.util.Arrays; + +public class Solution { + public int minimumSubstringsInPartition(String s) { + char[] cs = s.toCharArray(); + int n = cs.length; + int[] dp = new int[n + 1]; + Arrays.fill(dp, n); + dp[0] = 0; + for (int i = 1; i <= n; ++i) { + int[] count = new int[26]; + int distinct = 0; + int maxCount = 0; + for (int j = i - 1; j >= 0; --j) { + int index = cs[j] - 'a'; + if (++count[index] == 1) { + distinct++; + } + if (count[index] > maxCount) { + maxCount = count[index]; + } + if (maxCount * distinct == i - j) { + dp[i] = Math.min(dp[i], dp[j] + 1); + } + } + } + return dp[n]; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3145_find_products_of_elements_of_big_array/readme.md b/src/main/java/g3101_3200/s3145_find_products_of_elements_of_big_array/readme.md new file mode 100644 index 00000000..eb4f2fc9 --- /dev/null +++ b/src/main/java/g3101_3200/s3145_find_products_of_elements_of_big_array/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) + +## 3145\. Find Products of Elements of Big Array + +Hard + +A **powerful array** for an integer `x` is the shortest sorted array of powers of two that sum up to `x`. For example, the powerful array for 11 is `[1, 2, 8]`. + +The array `big_nums` is created by concatenating the **powerful** arrays for every positive integer `i` in ascending order: 1, 2, 3, and so forth. Thus, `big_nums` starts as [1, 2, 1, 2, 4, 1, 4, 2, 4, 1, 2, 4, 8, ...]. + +You are given a 2D integer matrix `queries`, where for queries[i] = [fromi, toi, modi] you should calculate (big_nums[fromi] * big_nums[fromi + 1] * ... * big_nums[toi]) % modi. + +Return an integer array `answer` such that `answer[i]` is the answer to the ith query. + +**Example 1:** + +**Input:** queries = \[\[1,3,7]] + +**Output:** [4] + +**Explanation:** + +There is one query. + +`big_nums[1..3] = [2,1,2]`. The product of them is 4. The remainder of 4 under 7 is 4. + +**Example 2:** + +**Input:** queries = \[\[2,5,3],[7,7,4]] + +**Output:** [2,2] + +**Explanation:** + +There are two queries. + +First query: `big_nums[2..5] = [1,2,4,1]`. The product of them is 8. The remainder of 8 under 3 is 2. + +Second query: `big_nums[7] = 2`. The remainder of 2 under 4 is 2. + +**Constraints:** + +* `1 <= queries.length <= 500` +* `queries[i].length == 3` +* 0 <= queries[i][0] <= queries[i][1] <= 1015 +* 1 <= queries[i][2] <= 105 + +## Solution + +```java +public class Solution { + public int[] findProductsOfElements(long[][] queries) { + int[] ans = new int[queries.length]; + for (int i = 0; i < queries.length; i++) { + long[] q = queries[i]; + long er = sumE(q[1] + 1); + long el = sumE(q[0]); + ans[i] = pow(2, er - el, q[2]); + } + return ans; + } + + private long sumE(long k) { + long res = 0; + long n = 0; + long cnt1 = 0; + long sumI = 0; + for (long i = 63L - Long.numberOfLeadingZeros(k + 1); i > 0; i--) { + long c = (cnt1 << i) + (i << (i - 1)); + if (c <= k) { + k -= c; + res += (sumI << i) + ((i * (i - 1) / 2) << (i - 1)); + sumI += i; + cnt1++; + n |= 1L << i; + } + } + if (cnt1 <= k) { + k -= cnt1; + res += sumI; + n++; + } + while (k-- > 0) { + res += Long.numberOfTrailingZeros(n); + n &= n - 1; + } + return res; + } + + private int pow(long x, long n, long mod) { + long res = 1 % mod; + for (; n > 0; n /= 2) { + if (n % 2 == 1) { + res = (res * x) % mod; + } + x = (x * x) % mod; + } + return (int) res; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3146_permutation_difference_between_two_strings/readme.md b/src/main/java/g3101_3200/s3146_permutation_difference_between_two_strings/readme.md new file mode 100644 index 00000000..eb118632 --- /dev/null +++ b/src/main/java/g3101_3200/s3146_permutation_difference_between_two_strings/readme.md @@ -0,0 +1,64 @@ +[![](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) + +## 3146\. Permutation Difference between Two Strings + +Easy + +You are given two strings `s` and `t` such that every character occurs at most once in `s` and `t` is a permutation of `s`. + +The **permutation difference** between `s` and `t` is defined as the **sum** of the absolute difference between the index of the occurrence of each character in `s` and the index of the occurrence of the same character in `t`. + +Return the **permutation difference** between `s` and `t`. + +**Example 1:** + +**Input:** s = "abc", t = "bac" + +**Output:** 2 + +**Explanation:** + +For `s = "abc"` and `t = "bac"`, the permutation difference of `s` and `t` is equal to the sum of: + +* The absolute difference between the index of the occurrence of `"a"` in `s` and the index of the occurrence of `"a"` in `t`. +* The absolute difference between the index of the occurrence of `"b"` in `s` and the index of the occurrence of `"b"` in `t`. +* The absolute difference between the index of the occurrence of `"c"` in `s` and the index of the occurrence of `"c"` in `t`. + +That is, the permutation difference between `s` and `t` is equal to `|0 - 1| + |2 - 2| + |1 - 0| = 2`. + +**Example 2:** + +**Input:** s = "abcde", t = "edbac" + +**Output:** 12 + +**Explanation:** The permutation difference between `s` and `t` is equal to `|0 - 3| + |1 - 2| + |2 - 4| + |3 - 1| + |4 - 0| = 12`. + +**Constraints:** + +* `1 <= s.length <= 26` +* Each character occurs at most once in `s`. +* `t` is a permutation of `s`. +* `s` consists only of lowercase English letters. + +## Solution + +```java +import java.util.Arrays; + +public class Solution { + public int findPermutationDifference(String s, String t) { + int[] res = new int[26]; + Arrays.fill(res, -1); + int sum = 0; + for (int i = 0; i < s.length(); ++i) { + res[s.charAt(i) - 'a'] = i; + } + for (int i = 0; i < t.length(); ++i) { + sum += Math.abs(res[t.charAt(i) - 'a'] - i); + } + return sum; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3147_taking_maximum_energy_from_the_mystic_dungeon/readme.md b/src/main/java/g3101_3200/s3147_taking_maximum_energy_from_the_mystic_dungeon/readme.md new file mode 100644 index 00000000..85966779 --- /dev/null +++ b/src/main/java/g3101_3200/s3147_taking_maximum_energy_from_the_mystic_dungeon/readme.md @@ -0,0 +1,55 @@ +[![](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) + +## 3147\. Taking Maximum Energy From the Mystic Dungeon + +Medium + +In a mystic dungeon, `n` magicians are standing in a line. Each magician has an attribute that gives you energy. Some magicians can give you negative energy, which means taking energy from you. + +You have been cursed in such a way that after absorbing energy from magician `i`, you will be instantly transported to magician `(i + k)`. This process will be repeated until you reach the magician where `(i + k)` does not exist. + +In other words, you will choose a starting point and then teleport with `k` jumps until you reach the end of the magicians' sequence, **absorbing all the energy** during the journey. + +You are given an array `energy` and an integer `k`. Return the **maximum** possible energy you can gain. + +**Example 1:** + +**Input:** energy = [5,2,-10,-5,1], k = 3 + +**Output:** 3 + +**Explanation:** We can gain a total energy of 3 by starting from magician 1 absorbing 2 + 1 = 3. + +**Example 2:** + +**Input:** energy = [-2,-3,-1], k = 2 + +**Output:** -1 + +**Explanation:** We can gain a total energy of -1 by starting from magician 2. + +**Constraints:** + +* 1 <= energy.length <= 105 +* `-1000 <= energy[i] <= 1000` +* `1 <= k <= energy.length - 1` + +## Solution + +```java +public class Solution { + public int maximumEnergy(int[] energy, int k) { + int max = Integer.MIN_VALUE; + int n = energy.length; + for (int i = n - 1; i >= n - k; i--) { + int en = 0; + for (int j = i; j >= 0; j -= k) { + en += energy[j]; + max = Math.max(en, max); + } + } + return max; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3148_maximum_difference_score_in_a_grid/readme.md b/src/main/java/g3101_3200/s3148_maximum_difference_score_in_a_grid/readme.md new file mode 100644 index 00000000..cccdad1c --- /dev/null +++ b/src/main/java/g3101_3200/s3148_maximum_difference_score_in_a_grid/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) + +## 3148\. Maximum Difference Score in a Grid + +Medium + +You are given an `m x n` matrix `grid` consisting of **positive** integers. You can move from a cell in the matrix to **any** other cell that is either to the bottom or to the right (not necessarily adjacent). The score of a move from a cell with the value `c1` to a cell with the value `c2` is `c2 - c1`. + +You can start at **any** cell, and you have to make **at least** one move. + +Return the **maximum** total score you can achieve. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2024/03/14/grid1.png) + +**Input:** grid = \[\[9,5,7,3],[8,9,6,1],[6,7,14,3],[2,5,3,1]] + +**Output:** 9 + +**Explanation:** We start at the cell `(0, 1)`, and we perform the following moves: + +- Move from the cell `(0, 1)` to `(2, 1)` with a score of `7 - 5 = 2`. + +- Move from the cell `(2, 1)` to `(2, 2)` with a score of `14 - 7 = 7`. + +The total score is `2 + 7 = 9`. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2024/04/08/moregridsdrawio-1.png) + +**Input:** grid = \[\[4,3,2],[3,2,1]] + +**Output:** \-1 + +**Explanation:** We start at the cell `(0, 0)`, and we perform one move: `(0, 0)` to `(0, 1)`. The score is `3 - 4 = -1`. + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `2 <= m, n <= 1000` +* 4 <= m * n <= 105 +* 1 <= grid[i][j] <= 105 + +## Solution + +```java +import java.util.List; + +public class Solution { + public int maxScore(List> grid) { + int m = grid.size() - 1; + List row = grid.get(m); + int n = row.size(); + int[] maxRB = new int[n--]; + int mx = maxRB[n] = row.get(n); + int result = Integer.MIN_VALUE; + for (int i = n - 1; i >= 0; i--) { + int x = row.get(i); + result = Math.max(result, mx - x); + maxRB[i] = mx = Math.max(mx, x); + } + for (int i = m - 1; i >= 0; i--) { + row = grid.get(i); + mx = 0; + for (int j = n; j >= 0; j--) { + mx = Math.max(mx, maxRB[j]); + int x = row.get(j); + result = Math.max(result, mx - x); + maxRB[j] = mx = Math.max(mx, x); + } + } + return result; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g3101_3200/s3149_find_the_minimum_cost_array_permutation/readme.md b/src/main/java/g3101_3200/s3149_find_the_minimum_cost_array_permutation/readme.md new file mode 100644 index 00000000..82575c91 --- /dev/null +++ b/src/main/java/g3101_3200/s3149_find_the_minimum_cost_array_permutation/readme.md @@ -0,0 +1,103 @@ +[![](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) + +## 3149\. Find the Minimum Cost Array Permutation + +Hard + +You are given an array `nums` which is a permutation of `[0, 1, 2, ..., n - 1]`. The **score** of any permutation of `[0, 1, 2, ..., n - 1]` named `perm` is defined as: + +`score(perm) = |perm[0] - nums[perm[1]]| + |perm[1] - nums[perm[2]]| + ... + |perm[n - 1] - nums[perm[0]]|` + +Return the permutation `perm` which has the **minimum** possible score. If _multiple_ permutations exist with this score, return the one that is lexicographically smallest among them. + +**Example 1:** + +**Input:** nums = [1,0,2] + +**Output:** [0,1,2] + +**Explanation:** + +**![](https://assets.leetcode.com/uploads/2024/04/04/example0gif.gif)** + +The lexicographically smallest permutation with minimum cost is `[0,1,2]`. The cost of this permutation is `|0 - 0| + |1 - 2| + |2 - 1| = 2`. + +**Example 2:** + +**Input:** nums = [0,2,1] + +**Output:** [0,2,1] + +**Explanation:** + +**![](https://assets.leetcode.com/uploads/2024/04/04/example1gif.gif)** + +The lexicographically smallest permutation with minimum cost is `[0,2,1]`. The cost of this permutation is `|0 - 1| + |2 - 2| + |1 - 0| = 2`. + +**Constraints:** + +* `2 <= n == nums.length <= 14` +* `nums` is a permutation of `[0, 1, 2, ..., n - 1]`. + +## Solution + +```java +import java.util.Arrays; + +public class Solution { + private int findMinScore(int mask, int prevNum, int[] nums, int[][] dp) { + int n = nums.length; + if (Integer.bitCount(mask) == n) { + dp[mask][prevNum] = Math.abs(prevNum - nums[0]); + return dp[mask][prevNum]; + } + if (dp[mask][prevNum] != -1) { + return dp[mask][prevNum]; + } + int minScore = Integer.MAX_VALUE; + for (int currNum = 0; currNum < n; currNum++) { + if ((mask >> currNum & 1 ^ 1) == 1) { + int currScore = + Math.abs(prevNum - nums[currNum]) + + findMinScore(mask | 1 << currNum, currNum, nums, dp); + minScore = Math.min(minScore, currScore); + } + } + dp[mask][prevNum] = minScore; + return dp[mask][prevNum]; + } + + private int[] constructMinScorePermutation(int n, int[] nums, int[][] dp) { + int[] permutation = new int[n]; + int i = 0; + permutation[i++] = 0; + int prevNum = 0; + for (int mask = 1; i < n; mask |= 1 << prevNum) { + for (int currNum = 0; currNum < n; currNum++) { + if ((mask >> currNum & 1 ^ 1) == 1) { + int currScore = + Math.abs(prevNum - nums[currNum]) + dp[mask | 1 << currNum][currNum]; + int minScore = dp[mask][prevNum]; + if (currScore == minScore) { + permutation[i++] = currNum; + prevNum = currNum; + break; + } + } + } + } + return permutation; + } + + public int[] findPermutation(int[] nums) { + int n = nums.length; + int[][] dp = new int[1 << n][n]; + for (int[] row : dp) { + Arrays.fill(row, -1); + } + findMinScore(1, 0, nums, dp); + return constructMinScorePermutation(n, nums, dp); + } +} +``` \ No newline at end of file