From 635a5cc446f082d12c710ba4cf12ab98d632b80a Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 25 Dec 2023 16:42:11 +0200 Subject: [PATCH] Added tasks 2857-2900 --- README.md | 47 ++++++- .../s2815_max_pair_sum_in_an_array/readme.md | 1 + .../readme.md | 1 + .../readme.md | 1 + .../readme.md | 2 +- .../readme.md | 1 + .../readme.md | 1 + .../readme.md | 1 + .../readme.md | 67 +++++++++ .../readme.md | 130 +++++++++++++++++ .../readme.md | 87 ++++++++++++ .../g2801_2900/s2860_happy_students/readme.md | 80 +++++++++++ .../s2861_maximum_number_of_alloys/readme.md | 131 ++++++++++++++++++ .../readme.md | 86 ++++++++++++ .../s2864_maximum_odd_binary_number/readme.md | 67 +++++++++ .../s2865_beautiful_towers_i/readme.md | 102 ++++++++++++++ .../s2866_beautiful_towers_ii/readme.md | 129 +++++++++++++++++ .../readme.md | 127 +++++++++++++++++ .../readme.md | 72 ++++++++++ .../readme.md | 59 ++++++++ .../readme.md | 80 +++++++++++ .../readme.md | 103 ++++++++++++++ .../readme.md | 75 ++++++++++ .../readme.md | 65 +++++++++ .../readme.md | 79 +++++++++++ .../readme.md | 90 ++++++++++++ .../readme.md | 40 ++++++ .../readme.md | 58 ++++++++ .../readme.md | 55 ++++++++ .../g2801_2900/s2880_select_data/readme.md | 50 +++++++ .../s2881_create_a_new_column/readme.md | 61 ++++++++ .../s2882_drop_duplicate_rows/readme.md | 61 ++++++++ .../s2883_drop_missing_data/readme.md | 58 ++++++++ .../g2801_2900/s2884_modify_columns/readme.md | 57 ++++++++ .../g2801_2900/s2885_rename_columns/readme.md | 62 +++++++++ .../s2886_change_data_type/readme.md | 53 +++++++ .../s2887_fill_missing_data/readme.md | 56 ++++++++ .../s2888_reshape_data_concatenate/readme.md | 76 ++++++++++ .../s2889_reshape_data_pivot/readme.md | 60 ++++++++ .../s2890_reshape_data_melt/readme.md | 59 ++++++++ .../s2891_method_chaining/readme.md | 72 ++++++++++ .../readme.md | 68 +++++++++ .../s2895_minimum_processing_time/readme.md | 86 ++++++++++++ .../readme.md | 84 +++++++++++ .../readme.md | 78 +++++++++++ .../s2899_last_visited_integers/readme.md | 74 ++++++++++ .../readme.md | 79 +++++++++++ 47 files changed, 3026 insertions(+), 5 deletions(-) create mode 100644 src/main/kotlin/g2801_2900/s2857_count_pairs_of_points_with_distance_k/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2858_minimum_edge_reversals_so_every_node_is_reachable/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2859_sum_of_values_at_indices_with_k_set_bits/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2860_happy_students/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2861_maximum_number_of_alloys/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2862_maximum_element_sum_of_a_complete_subset_of_indices/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2864_maximum_odd_binary_number/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2865_beautiful_towers_i/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2866_beautiful_towers_ii/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2867_count_valid_paths_in_a_tree/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2869_minimum_operations_to_collect_elements/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2870_minimum_number_of_operations_to_make_array_empty/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2871_split_array_into_maximum_number_of_subarrays/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2872_maximum_number_of_k_divisible_components/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2873_maximum_value_of_an_ordered_triplet_i/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2874_maximum_value_of_an_ordered_triplet_ii/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2875_minimum_size_subarray_in_infinite_array/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2876_count_visited_nodes_in_a_directed_graph/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2877_create_a_dataframe_from_list/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2878_get_the_size_of_a_dataframe/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2879_display_the_first_three_rows/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2880_select_data/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2881_create_a_new_column/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2882_drop_duplicate_rows/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2883_drop_missing_data/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2884_modify_columns/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2885_rename_columns/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2886_change_data_type/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2887_fill_missing_data/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2888_reshape_data_concatenate/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2889_reshape_data_pivot/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2890_reshape_data_melt/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2891_method_chaining/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2894_divisible_and_non_divisible_sums_difference/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2895_minimum_processing_time/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2896_apply_operations_to_make_two_strings_equal/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2897_apply_operations_on_array_to_maximize_sum_of_squares/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2899_last_visited_integers/readme.md create mode 100644 src/main/kotlin/g2801_2900/s2900_longest_unequal_adjacent_groups_subsequence_i/readme.md diff --git a/README.md b/README.md index f2eb5c48..c9370e2d 100644 --- a/README.md +++ b/README.md @@ -1154,7 +1154,7 @@ | 0977 |[Squares of a Sorted Array](src/main/kotlin/g0901_1000/s0977_squares_of_a_sorted_array)| Easy | Array, Sorting, Two_Pointers | 271 | 77.17 | 0026 |[Remove Duplicates from Sorted Array](src/main/kotlin/g0001_0100/s0026_remove_duplicates_from_sorted_array)| Easy | Top_Interview_Questions, Array, Two_Pointers | 249 | 67.38 | 0042 |[Trapping Rain Water](src/main/kotlin/g0001_0100/s0042_trapping_rain_water)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Two_Pointers, Stack, Monotonic_Stack, Big_O_Time_O(n)_Space_O(1) | 189 | 99.37 -| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Big_O_Time_O(n^2)_Space_O(1) | 493 | 93.45 +| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Big_O_Time_O(n\*log(n))_Space_O(n^2) | 493 | 93.45 #### Udemy Famous Algorithm @@ -1406,7 +1406,7 @@ |-|-|-|-|-|- | 0136 |[Single Number](src/main/kotlin/g0101_0200/s0136_single_number)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Bit_Manipulation, Big_O_Time_O(N)_Space_O(1) | 344 | 83.63 | 0169 |[Majority Element](src/main/kotlin/g0101_0200/s0169_majority_element)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table, Sorting, Counting, Divide_and_Conquer, Big_O_Time_O(n)_Space_O(1) | 460 | 51.25 -| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Big_O_Time_O(n^2)_Space_O(1) | 493 | 93.45 +| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Big_O_Time_O(n\*log(n))_Space_O(n^2) | 493 | 93.45 #### Day 2 Array @@ -1680,7 +1680,7 @@ | | | | | | |-|-|-|-|-|- | 0082 |[Remove Duplicates from Sorted List II](src/main/kotlin/g0001_0100/s0082_remove_duplicates_from_sorted_list_ii)| Medium | Two_Pointers, Linked_List | 166 | 89.47 -| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Big_O_Time_O(n^2)_Space_O(1) | 493 | 93.45 +| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Big_O_Time_O(n\*log(n))_Space_O(n^2) | 493 | 93.45 #### Day 4 Two Pointers @@ -1816,6 +1816,45 @@ | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- +| 2900 |[Longest Unequal Adjacent Groups Subsequence I](src/main/kotlin/g2801_2900/s2900_longest_unequal_adjacent_groups_subsequence_i)| Medium | Array, String, Dynamic_Programming, Greedy | 294 | 100.00 +| 2899 |[Last Visited Integers](src/main/kotlin/g2801_2900/s2899_last_visited_integers)| Easy | Array, String, Simulation | 209 | 72.73 +| 2897 |[Apply Operations on Array to Maximize Sum of Squares](src/main/kotlin/g2801_2900/s2897_apply_operations_on_array_to_maximize_sum_of_squares)| Hard | Array, Hash_Table, Greedy, Bit_Manipulation | 572 | 100.00 +| 2896 |[Apply Operations to Make Two Strings Equal](src/main/kotlin/g2801_2900/s2896_apply_operations_to_make_two_strings_equal)| Medium | String, Dynamic_Programming | 181 | 66.67 +| 2895 |[Minimum Processing Time](src/main/kotlin/g2801_2900/s2895_minimum_processing_time)| Medium | Array, Sorting, Greedy | 662 | 80.00 +| 2894 |[Divisible and Non-divisible Sums Difference](src/main/kotlin/g2801_2900/s2894_divisible_and_non_divisible_sums_difference)| Easy | Math | 135 | 76.92 +| 2891 |[Method Chaining](src/main/kotlin/g2801_2900/s2891_method_chaining)| Easy || 412 | 99.23 +| 2890 |[Reshape Data: Melt](src/main/kotlin/g2801_2900/s2890_reshape_data_melt)| Easy || 446 | 97.89 +| 2889 |[Reshape Data: Pivot](src/main/kotlin/g2801_2900/s2889_reshape_data_pivot)| Easy || 416 | 99.87 +| 2888 |[Reshape Data: Concatenate](src/main/kotlin/g2801_2900/s2888_reshape_data_concatenate)| Easy || 441 | 96.26 +| 2887 |[Fill Missing Data](src/main/kotlin/g2801_2900/s2887_fill_missing_data)| Easy || 404 | 97.11 +| 2886 |[Change Data Type](src/main/kotlin/g2801_2900/s2886_change_data_type)| Easy || 421 | 94.57 +| 2885 |[Rename Columns](src/main/kotlin/g2801_2900/s2885_rename_columns)| Easy || 467 | 68.13 +| 2884 |[Modify Columns](src/main/kotlin/g2801_2900/s2884_modify_columns)| Easy || 401 | 96.35 +| 2883 |[Drop Missing Data](src/main/kotlin/g2801_2900/s2883_drop_missing_data)| Easy || 429 | 94.97 +| 2882 |[Drop Duplicate Rows](src/main/kotlin/g2801_2900/s2882_drop_duplicate_rows)| Easy || 405 | 97.36 +| 2881 |[Create a New Column](src/main/kotlin/g2801_2900/s2881_create_a_new_column)| Easy || 437 | 81.98 +| 2880 |[Select Data](src/main/kotlin/g2801_2900/s2880_select_data)| Easy || 428 | 94.99 +| 2879 |[Display the First Three Rows](src/main/kotlin/g2801_2900/s2879_display_the_first_three_rows)| Easy || 406 | 96.44 +| 2878 |[Get the Size of a DataFrame](src/main/kotlin/g2801_2900/s2878_get_the_size_of_a_dataframe)| Easy || 413 | 94.68 +| 2877 |[Create a DataFrame from List](src/main/kotlin/g2801_2900/s2877_create_a_dataframe_from_list)| Easy || 406 | 82.57 +| 2876 |[Count Visited Nodes in a Directed Graph](src/main/kotlin/g2801_2900/s2876_count_visited_nodes_in_a_directed_graph)| Hard | Dynamic_Programming, Graph, Memoization | 922 | 100.00 +| 2875 |[Minimum Size Subarray in Infinite Array](src/main/kotlin/g2801_2900/s2875_minimum_size_subarray_in_infinite_array)| Medium | Array, Hash_Table, Prefix_Sum, Sliding_Window | 372 | 100.00 +| 2874 |[Maximum Value of an Ordered Triplet II](src/main/kotlin/g2801_2900/s2874_maximum_value_of_an_ordered_triplet_ii)| Medium | Array | 508 | 100.00 +| 2873 |[Maximum Value of an Ordered Triplet I](src/main/kotlin/g2801_2900/s2873_maximum_value_of_an_ordered_triplet_i)| Easy | Array | 157 | 94.12 +| 2872 |[Maximum Number of K-Divisible Components](src/main/kotlin/g2801_2900/s2872_maximum_number_of_k_divisible_components)| Hard | Dynamic_Programming, Depth_First_Search, Tree | 780 | 100.00 +| 2871 |[Split Array Into Maximum Number of Subarrays](src/main/kotlin/g2801_2900/s2871_split_array_into_maximum_number_of_subarrays)| Medium | Array, Greedy, Bit_Manipulation | 490 | 100.00 +| 2870 |[Minimum Number of Operations to Make Array Empty](src/main/kotlin/g2801_2900/s2870_minimum_number_of_operations_to_make_array_empty)| Medium | Array, Hash_Table, Greedy, Counting | 503 | 80.00 +| 2869 |[Minimum Operations to Collect Elements](src/main/kotlin/g2801_2900/s2869_minimum_operations_to_collect_elements)| Easy | Array, Hash_Table | 156 | 100.00 +| 2867 |[Count Valid Paths in a Tree](src/main/kotlin/g2801_2900/s2867_count_valid_paths_in_a_tree)| Hard | Dynamic_Programming, Math, Depth_First_Search, Tree, Number_Theory | 793 | 100.00 +| 2866 |[Beautiful Towers II](src/main/kotlin/g2801_2900/s2866_beautiful_towers_ii)| Medium | Array, Stack, Monotonic_Stack | 676 | 85.71 +| 2865 |[Beautiful Towers I](src/main/kotlin/g2801_2900/s2865_beautiful_towers_i)| Medium | Array, Stack, Monotonic_Stack | 232 | 75.00 +| 2864 |[Maximum Odd Binary Number](src/main/kotlin/g2801_2900/s2864_maximum_odd_binary_number)| Easy | String, Math, Greedy | 176 | 90.91 +| 2862 |[Maximum Element-Sum of a Complete Subset of Indices](src/main/kotlin/g2801_2900/s2862_maximum_element_sum_of_a_complete_subset_of_indices)| Hard | Array, Math, Number_Theory | 259 | 100.00 +| 2861 |[Maximum Number of Alloys](src/main/kotlin/g2801_2900/s2861_maximum_number_of_alloys)| Medium | Array, Binary_Search | 289 | 100.00 +| 2860 |[Happy Students](src/main/kotlin/g2801_2900/s2860_happy_students)| Medium | Array, Sorting, Enumeration | 512 | 100.00 +| 2859 |[Sum of Values at Indices With K Set Bits](src/main/kotlin/g2801_2900/s2859_sum_of_values_at_indices_with_k_set_bits)| Easy | Array, Bit_Manipulation | 177 | 100.00 +| 2858 |[Minimum Edge Reversals So Every Node Is Reachable](src/main/kotlin/g2801_2900/s2858_minimum_edge_reversals_so_every_node_is_reachable)| Hard | Dynamic_Programming, Depth_First_Search, Breadth_First_Search, Graph | 1161 | 100.00 +| 2857 |[Count Pairs of Points With Distance k](src/main/kotlin/g2801_2900/s2857_count_pairs_of_points_with_distance_k)| Medium | Array, Hash_Table, Bit_Manipulation | 1212 | 100.00 | 2856 |[Minimum Array Length After Pair Removals](src/main/kotlin/g2801_2900/s2856_minimum_array_length_after_pair_removals)| Medium | Array, Hash_Table, Greedy, Binary_Search, Two_Pointers, Counting | 647 | 100.00 | 2855 |[Minimum Right Shifts to Sort the Array](src/main/kotlin/g2801_2900/s2855_minimum_right_shifts_to_sort_the_array)| Easy | Array | 169 | 75.00 | 2851 |[String Transformation](src/main/kotlin/g2801_2900/s2851_string_transformation)| Hard | String, Dynamic_Programming, Math, String_Matching | 377 | 100.00 @@ -4085,7 +4124,7 @@ | 0018 |[4Sum](src/main/kotlin/g0001_0100/s0018_4sum)| Medium | Array, Sorting, Two_Pointers | 229 | 98.59 | 0017 |[Letter Combinations of a Phone Number](src/main/kotlin/g0001_0100/s0017_letter_combinations_of_a_phone_number)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Backtracking, Algorithm_II_Day_11_Recursion_Backtracking, Udemy_Backtracking/Recursion, Big_O_Time_O(4^n)_Space_O(n) | 155 | 95.24 | 0016 |[3Sum Closest](src/main/kotlin/g0001_0100/s0016_3sum_closest)| Medium | Array, Sorting, Two_Pointers, Level_2_Day_14_Sliding_Window/Two_Pointer | 163 | 100.00 -| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Data_Structure_II_Day_1_Array, Algorithm_II_Day_3_Two_Pointers, Udemy_Two_Pointers, Big_O_Time_O(n^2)_Space_O(1) | 493 | 93.45 +| 0015 |[3Sum](src/main/kotlin/g0001_0100/s0015_3sum)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Sorting, Two_Pointers, Data_Structure_II_Day_1_Array, Algorithm_II_Day_3_Two_Pointers, Udemy_Two_Pointers, Big_O_Time_O(n\*log(n))_Space_O(n^2) | 493 | 93.45 | 0014 |[Longest Common Prefix](src/main/kotlin/g0001_0100/s0014_longest_common_prefix)| Easy | Top_Interview_Questions, String, Level_2_Day_2_String, Udemy_Strings | 154 | 89.70 | 0013 |[Roman to Integer](src/main/kotlin/g0001_0100/s0013_roman_to_integer)| Easy | Top_Interview_Questions, String, Hash_Table, Math | 211 | 83.47 | 0012 |[Integer to Roman](src/main/kotlin/g0001_0100/s0012_integer_to_roman)| Medium | String, Hash_Table, Math | 180 | 98.25 diff --git a/src/main/kotlin/g2801_2900/s2815_max_pair_sum_in_an_array/readme.md b/src/main/kotlin/g2801_2900/s2815_max_pair_sum_in_an_array/readme.md index b1b2c85c..fd384e13 100644 --- a/src/main/kotlin/g2801_2900/s2815_max_pair_sum_in_an_array/readme.md +++ b/src/main/kotlin/g2801_2900/s2815_max_pair_sum_in_an_array/readme.md @@ -43,6 +43,7 @@ import java.util.PriorityQueue import kotlin.collections.HashMap import kotlin.math.max +@Suppress("NAME_SHADOWING") class Solution { fun maxSum(nums: IntArray): Int { // what we'll return diff --git a/src/main/kotlin/g2801_2900/s2827_number_of_beautiful_integers_in_the_range/readme.md b/src/main/kotlin/g2801_2900/s2827_number_of_beautiful_integers_in_the_range/readme.md index 11eee41e..f954abf2 100644 --- a/src/main/kotlin/g2801_2900/s2827_number_of_beautiful_integers_in_the_range/readme.md +++ b/src/main/kotlin/g2801_2900/s2827_number_of_beautiful_integers_in_the_range/readme.md @@ -54,6 +54,7 @@ Return _the number of beautiful integers in the range_ `[low, high]`. ```kotlin import kotlin.math.max +@Suppress("kotlin:S107") class Solution { private lateinit var dp: Array>>> private var maxLength = 0 diff --git a/src/main/kotlin/g2801_2900/s2829_determine_the_minimum_sum_of_a_k_avoiding_array/readme.md b/src/main/kotlin/g2801_2900/s2829_determine_the_minimum_sum_of_a_k_avoiding_array/readme.md index 1265de8e..3b98bafc 100644 --- a/src/main/kotlin/g2801_2900/s2829_determine_the_minimum_sum_of_a_k_avoiding_array/readme.md +++ b/src/main/kotlin/g2801_2900/s2829_determine_the_minimum_sum_of_a_k_avoiding_array/readme.md @@ -34,6 +34,7 @@ Return _the **minimum** possible sum of a k-avoiding array of length_ `n`. ## Solution ```kotlin +@Suppress("NAME_SHADOWING") class Solution { fun minimumSum(n: Int, k: Int): Int { var k = k diff --git a/src/main/kotlin/g2801_2900/s2835_minimum_operations_to_form_subsequence_with_target_sum/readme.md b/src/main/kotlin/g2801_2900/s2835_minimum_operations_to_form_subsequence_with_target_sum/readme.md index eaea4ed5..ee0da63b 100644 --- a/src/main/kotlin/g2801_2900/s2835_minimum_operations_to_form_subsequence_with_target_sum/readme.md +++ b/src/main/kotlin/g2801_2900/s2835_minimum_operations_to_form_subsequence_with_target_sum/readme.md @@ -77,7 +77,7 @@ class Solution { if (sum < target) { return -1 } - while (!pq.isEmpty()) { + while (pq.isNotEmpty()) { val `val` = pq.poll() sum -= `val`.toLong() if (`val` <= target) { diff --git a/src/main/kotlin/g2801_2900/s2842_count_k_subsequences_of_a_string_with_maximum_beauty/readme.md b/src/main/kotlin/g2801_2900/s2842_count_k_subsequences_of_a_string_with_maximum_beauty/readme.md index 1df41922..963f484d 100644 --- a/src/main/kotlin/g2801_2900/s2842_count_k_subsequences_of_a_string_with_maximum_beauty/readme.md +++ b/src/main/kotlin/g2801_2900/s2842_count_k_subsequences_of_a_string_with_maximum_beauty/readme.md @@ -73,6 +73,7 @@ There are 2 k-subsequences that have the maximum beauty, 5. Hence, the answer is ## Solution ```kotlin +@Suppress("NAME_SHADOWING") class Solution { fun countKSubsequencesWithMaxBeauty(s: String, k: Int): Int { var k = k diff --git a/src/main/kotlin/g2801_2900/s2846_minimum_edge_weight_equilibrium_queries_in_a_tree/readme.md b/src/main/kotlin/g2801_2900/s2846_minimum_edge_weight_equilibrium_queries_in_a_tree/readme.md index 3654d1a3..3c6a8d91 100644 --- a/src/main/kotlin/g2801_2900/s2846_minimum_edge_weight_equilibrium_queries_in_a_tree/readme.md +++ b/src/main/kotlin/g2801_2900/s2846_minimum_edge_weight_equilibrium_queries_in_a_tree/readme.md @@ -64,6 +64,7 @@ In the fourth query, we change the weights of edges [0,7], [0,3] and [1,3] to 6. import kotlin.math.ln import kotlin.math.max +@Suppress("kotlin:S107") class Solution { private class Node(var v: Int, var w: Int) diff --git a/src/main/kotlin/g2801_2900/s2855_minimum_right_shifts_to_sort_the_array/readme.md b/src/main/kotlin/g2801_2900/s2855_minimum_right_shifts_to_sort_the_array/readme.md index c749769c..aaad349c 100644 --- a/src/main/kotlin/g2801_2900/s2855_minimum_right_shifts_to_sort_the_array/readme.md +++ b/src/main/kotlin/g2801_2900/s2855_minimum_right_shifts_to_sort_the_array/readme.md @@ -48,6 +48,7 @@ Now nums is sorted; therefore the answer is 2. ## Solution ```kotlin +@Suppress("kotlin:S6510") class Solution { fun minimumRightShifts(nums: List): Int { var i = 1 diff --git a/src/main/kotlin/g2801_2900/s2857_count_pairs_of_points_with_distance_k/readme.md b/src/main/kotlin/g2801_2900/s2857_count_pairs_of_points_with_distance_k/readme.md new file mode 100644 index 00000000..b20a52bc --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2857_count_pairs_of_points_with_distance_k/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2857\. Count Pairs of Points With Distance k + +Medium + +You are given a **2D** integer array `coordinates` and an integer `k`, where coordinates[i] = [xi, yi] are the coordinates of the ith point in a 2D plane. + +We define the **distance** between two points (x1, y1) and (x2, y2) as `(x1 XOR x2) + (y1 XOR y2)` where `XOR` is the bitwise `XOR` operation. + +Return _the number of pairs_ `(i, j)` _such that_ `i < j` _and the distance between points_ `i` _and_ `j` _is equal to_ `k`. + +**Example 1:** + +**Input:** coordinates = \[\[1,2],[4,2],[1,3],[5,2]], k = 5 + +**Output:** 2 + +**Explanation:** We can choose the following pairs: +- (0,1): Because we have (1 XOR 4) + (2 XOR 2) = 5. +- (2,3): Because we have (1 XOR 5) + (3 XOR 2) = 5. + +**Example 2:** + +**Input:** coordinates = \[\[1,3],[1,3],[1,3],[1,3],[1,3]], k = 0 + +**Output:** 10 + +**Explanation:** Any two chosen pairs will have a distance of 0. There are 10 ways to choose two pairs. + +**Constraints:** + +* `2 <= coordinates.length <= 50000` +* 0 <= xi, yi <= 106 +* `0 <= k <= 100` + +## Solution + +```kotlin +class Solution { + fun countPairs(coordinates: List>, k: Int): Int { + var ans = 0 + val map: MutableMap = HashMap() + for (p in coordinates) { + val p0 = p[0] + val p1 = p[1] + for (i in 0..k) { + val x1 = i xor p0 + val y1 = (k - i) xor p1 + val key2 = hash(x1, y1) + if (map.containsKey(key2)) { + ans += map[key2]!! + } + } + val key = hash(p0, p1) + map[key] = map.getOrDefault(key, 0) + 1 + } + return ans + } + + private fun hash(x1: Int, y1: Int): Long { + val r = 1e8.toLong() + return x1 * r + y1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2858_minimum_edge_reversals_so_every_node_is_reachable/readme.md b/src/main/kotlin/g2801_2900/s2858_minimum_edge_reversals_so_every_node_is_reachable/readme.md new file mode 100644 index 00000000..fe38a882 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2858_minimum_edge_reversals_so_every_node_is_reachable/readme.md @@ -0,0 +1,130 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2858\. Minimum Edge Reversals So Every Node Is Reachable + +Hard + +There is a **simple directed graph** with `n` nodes labeled from `0` to `n - 1`. The graph would form a **tree** if its edges were bi-directional. + +You are given an integer `n` and a **2D** integer array `edges`, where edges[i] = [ui, vi] represents a **directed edge** going from node ui to node vi. + +An **edge reversal** changes the direction of an edge, i.e., a directed edge going from node ui to node vi becomes a directed edge going from node vi to node ui. + +For every node `i` in the range `[0, n - 1]`, your task is to **independently** calculate the **minimum** number of **edge reversals** required so it is possible to reach any other node starting from node `i` through a **sequence** of **directed edges**. + +Return _an integer array_ `answer`_, where_ `answer[i]` _is the_ _**minimum** number of **edge reversals** required so it is possible to reach any other node starting from node_ `i` _through a **sequence** of **directed edges**._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/08/26/image-20230826221104-3.png) + +**Input:** n = 4, edges = \[\[2,0],[2,1],[1,3]] + +**Output:** [1,1,0,2] + +**Explanation:** The image above shows the graph formed by the edges. + +For node 0: after reversing the edge [2,0], it is possible to reach any other node starting from node 0. + +So, answer[0] = 1. + +For node 1: after reversing the edge [2,1], it is possible to reach any other node starting from node 1. + +So, answer[1] = 1. + +For node 2: it is already possible to reach any other node starting from node 2. + +So, answer[2] = 0. + +For node 3: after reversing the edges [1,3] and [2,1], it is possible to reach any other node starting from node 3. + +So, answer[3] = 2. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/08/26/image-20230826225541-2.png) + +**Input:** n = 3, edges = \[\[1,2],[2,0]] + +**Output:** [2,0,1] + +**Explanation:** The image above shows the graph formed by the edges. + +For node 0: after reversing the edges [2,0] and [1,2], it is possible to reach any other node starting from node 0. + +So, answer[0] = 2. + +For node 1: it is already possible to reach any other node starting from node 1. + +So, answer[1] = 0. + +For node 2: after reversing the edge [1, 2], it is possible to reach any other node starting from node 2. + +So, answer[2] = 1. + +**Constraints:** + +* 2 <= n <= 105 +* `edges.length == n - 1` +* `edges[i].length == 2` +* 0 <= ui == edges[i][0] < n +* 0 <= vi == edges[i][1] < n +* ui != vi +* The input is generated such that if the edges were bi-directional, the graph would be a tree. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + fun minEdgeReversals(n: Int, edges: Array): IntArray { + val nexts: Array> = Array(n) { ArrayList() } + for (edge in edges) { + val u = edge[0] + val v = edge[1] + nexts[u].add(intArrayOf(1, v)) + nexts[v].add(intArrayOf(-1, u)) + } + val res = IntArray(n) + for (i in 0 until n) { + res[i] = -1 + } + res[0] = dfs(nexts, 0, -1) + val queue: Queue = LinkedList() + queue.add(0) + while (queue.isNotEmpty()) { + val index = queue.remove() + val `val` = res[index] + val next: List = nexts[index] + for (node in next) { + if (res[node[1]] == -1) { + if (node[0] == 1) { + res[node[1]] = `val` + 1 + } else { + res[node[1]] = `val` - 1 + } + queue.add(node[1]) + } + } + } + return res + } + + private fun dfs(nexts: Array>, index: Int, pre: Int): Int { + var res = 0 + val next: List = nexts[index] + for (node in next) { + if (node[1] != pre) { + if (node[0] == -1) { + res++ + } + res += dfs(nexts, node[1], index) + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2859_sum_of_values_at_indices_with_k_set_bits/readme.md b/src/main/kotlin/g2801_2900/s2859_sum_of_values_at_indices_with_k_set_bits/readme.md new file mode 100644 index 00000000..080be749 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2859_sum_of_values_at_indices_with_k_set_bits/readme.md @@ -0,0 +1,87 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2859\. Sum of Values at Indices With K Set Bits + +Easy + +You are given a **0-indexed** integer array `nums` and an integer `k`. + +Return _an integer that denotes the **sum** of elements in_ `nums` _whose corresponding **indices** have **exactly**_ `k` _set bits in their binary representation._ + +The **set bits** in an integer are the `1`'s present when it is written in binary. + +* For example, the binary representation of `21` is `10101`, which has `3` set bits. + +**Example 1:** + +**Input:** nums = [5,10,1,5,2], k = 1 + +**Output:** 13 + +**Explanation:** The binary representation of the indices are: + +0 = 0002 + +1 = 0012 + +2 = 0102 + +3 = 0112 + +4 = 1002 + +Indices 1, 2, and 4 have k = 1 set bits in their binary representation. Hence, the answer is nums[1] + nums[2] + nums[4] = 13. + +**Example 2:** + +**Input:** nums = [4,3,2,1], k = 2 + +**Output:** 1 + +**Explanation:** The binary representation of the indices are: + +0 = 002 + +1 = 012 + +2 = 102 + +3 = 112 + +Only index 3 has k = 2 set bits in its binary representation. Hence, the answer is nums[3] = 1. + +**Constraints:** + +* `1 <= nums.length <= 1000` +* 1 <= nums[i] <= 105 +* `0 <= k <= 10` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun sumIndicesWithKSetBits(nums: List, k: Int): Int { + var sum = 0 + for (i in nums.indices) { + if (countSetBits(i) == k) { + sum += nums[i] + } + } + return sum + } + + companion object { + fun countSetBits(num: Int): Int { + var num = num + var count = 0 + while (num > 0) { + num = num and (num - 1) + count++ + } + return count + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2860_happy_students/readme.md b/src/main/kotlin/g2801_2900/s2860_happy_students/readme.md new file mode 100644 index 00000000..88f915b0 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2860_happy_students/readme.md @@ -0,0 +1,80 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2860\. Happy Students + +Medium + +You are given a **0-indexed** integer array `nums` of length `n` where `n` is the total number of students in the class. The class teacher tries to select a group of students so that all the students remain happy. + +The ith student will become happy if one of these two conditions is met: + +* The student is selected and the total number of selected students is **strictly greater than** `nums[i]`. +* The student is not selected and the total number of selected students is **strictly** **less than** `nums[i]`. + +Return _the number of ways to select a group of students so that everyone remains happy._ + +**Example 1:** + +**Input:** nums = [1,1] + +**Output:** 2 + +**Explanation:** + +The two possible ways are: + +The class teacher selects no student. + +The class teacher selects both students to form the group. + +If the class teacher selects just one student to form a group then the both students will not be happy. + +Therefore, there are only two possible ways. + +**Example 2:** + +**Input:** nums = [6,0,3,3,6,7,2,7] + +**Output:** 3 + +**Explanation:** + +The three possible ways are: + +The class teacher selects the student with index = 1 to form the group. + +The class teacher selects the students with index = 1, 2, 3, 6 to form the group. + +The class teacher selects all the students to form the group. + +**Constraints:** + +* 1 <= nums.length <= 105 +* `0 <= nums[i] < nums.length` + +## Solution + +```kotlin +import java.util.Collections + +class Solution { + fun countWays(nums: List): Int { + Collections.sort(nums) + var cnt = 0 + val n = nums.size + if (nums[0] != 0) { + cnt++ + } + for (i in 0 until n - 1) { + if (nums[i] < (i + 1) && (nums[i + 1] > (i + 1))) { + cnt++ + } + } + if (n > nums[n - 1]) { + cnt++ + } + return cnt + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2861_maximum_number_of_alloys/readme.md b/src/main/kotlin/g2801_2900/s2861_maximum_number_of_alloys/readme.md new file mode 100644 index 00000000..ba2a1e07 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2861_maximum_number_of_alloys/readme.md @@ -0,0 +1,131 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2861\. Maximum Number of Alloys + +Medium + +You are the owner of a company that creates alloys using various types of metals. There are `n` different types of metals available, and you have access to `k` machines that can be used to create alloys. Each machine requires a specific amount of each metal type to create an alloy. + +For the ith machine to create an alloy, it needs `composition[i][j]` units of metal of type `j`. Initially, you have `stock[i]` units of metal type `i`, and purchasing one unit of metal type `i` costs `cost[i]` coins. + +Given integers `n`, `k`, `budget`, a **1-indexed** 2D array `composition`, and **1-indexed** arrays `stock` and `cost`, your goal is to **maximize** the number of alloys the company can create while staying within the budget of `budget` coins. + +**All alloys must be created with the same machine.** + +Return _the maximum number of alloys that the company can create_. + +**Example 1:** + +**Input:** n = 3, k = 2, budget = 15, composition = \[\[1,1,1],[1,1,10]], stock = [0,0,0], cost = [1,2,3] + +**Output:** 2 + +**Explanation:** It is optimal to use the 1st machine to create alloys. + +To create 2 alloys we need to buy the: +- 2 units of metal of the 1st type. +- 2 units of metal of the 2nd type. +- 2 units of metal of the 3rd type. + +In total, we need 2 \* 1 + 2 \* 2 + 2 \* 3 = 12 coins, which is smaller than or equal to budget = 15. Notice that we have 0 units of metal of each type and we have to buy all the required units of metal. It can be proven that we can create at most 2 alloys. + +**Example 2:** + +**Input:** n = 3, k = 2, budget = 15, composition = \[\[1,1,1],[1,1,10]], stock = [0,0,100], cost = [1,2,3] + +**Output:** 5 + +**Explanation:** It is optimal to use the 2nd machine to create alloys. To create 5 alloys we need to buy: +- 5 units of metal of the 1st type. +- 5 units of metal of the 2nd type. +- 0 units of metal of the 3rd type. + +In total, we need 5 \* 1 + 5 \* 2 + 0 \* 3 = 15 coins, which is smaller than or equal to budget = 15. It can be proven that we can create at most 5 alloys. + +**Example 3:** + +**Input:** n = 2, k = 3, budget = 10, composition = \[\[2,1],[1,2],[1,1]], stock = [1,1], cost = [5,5] + +**Output:** 2 + +**Explanation:** It is optimal to use the 3rd machine to create alloys. To create 2 alloys we need to buy the: +- 1 unit of metal of the 1st type. +- 1 unit of metal of the 2nd type. + +In total, we need 1 \* 5 + 1 \* 5 = 10 coins, which is smaller than or equal to budget = 10. It can be proven that we can create at most 2 alloys. + +**Constraints:** + +* `1 <= n, k <= 100` +* 0 <= budget <= 108 +* `composition.length == k` +* `composition[i].length == n` +* `1 <= composition[i][j] <= 100` +* `stock.length == cost.length == n` +* 0 <= stock[i] <= 108 +* `1 <= cost[i] <= 100` + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun maxNumberOfAlloys( + n: Int, + k: Int, + budget: Int, + composition: List>, + stock: List, + cost: List + ): Int { + var ans = 0 + var max = 0 + for (i in 0 until n) { + max = max(stock[i].toDouble(), max.toDouble()).toInt() + } + for (i in 0 until k) { + var temp = 0 + var low = 0 + var high = max + budget + var mid: Int + while (low <= high) { + mid = low + (high - low) / 2 + if (isPos(i, mid, n, budget, composition, stock, cost)) { + low = mid + 1 + temp = mid + } else { + high = mid - 1 + } + } + ans = max(ans.toDouble(), temp.toDouble()).toInt() + } + return ans + } + + private fun isPos( + idx: Int, + mid: Int, + n: Int, + budget: Int, + composition: List>, + stock: List, + cost: List + ): Boolean { + var paiSa = 0L + for (i in 0 until n) { + val require = (composition[idx][i].toLong()) * (mid) + val have = stock[i].toLong() + val diff = require - have + if (diff > 0) { + paiSa += diff * (cost[i].toLong()) + } + if (budget < paiSa) { + return false + } + } + return budget >= paiSa + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2862_maximum_element_sum_of_a_complete_subset_of_indices/readme.md b/src/main/kotlin/g2801_2900/s2862_maximum_element_sum_of_a_complete_subset_of_indices/readme.md new file mode 100644 index 00000000..0ebac0fe --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2862_maximum_element_sum_of_a_complete_subset_of_indices/readme.md @@ -0,0 +1,86 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2862\. Maximum Element-Sum of a Complete Subset of Indices + +Hard + +You are given a **1****\-indexed** array `nums` of `n` integers. + +A set of numbers is **complete** if the product of every pair of its elements is a perfect square. + +For a subset of the indices set `{1, 2, ..., n}` represented as {i1, i2, ..., ik}, we define its **element-sum** as: nums[i1] + nums[i2] + ... + nums[ik]. + +Return _the **maximum element-sum** of a **complete** subset of the indices set_ `{1, 2, ..., n}`. + +A perfect square is a number that can be expressed as the product of an integer by itself. + +**Example 1:** + +**Input:** nums = [8,7,3,5,7,2,4,9] + +**Output:** 16 + +**Explanation:** Apart from the subsets consisting of a single index, there are two other complete subsets of indices: {1,4} and {2,8}. + +The sum of the elements corresponding to indices 1 and 4 is equal to nums[1] + nums[4] = 8 + 5 = 13. + +The sum of the elements corresponding to indices 2 and 8 is equal to nums[2] + nums[8] = 7 + 9 = 16. + +Hence, the maximum element-sum of a complete subset of indices is 16. + +**Example 2:** + +**Input:** nums = [5,10,3,10,1,13,7,9,4] + +**Output:** 19 + +**Explanation:** Apart from the subsets consisting of a single index, there are four other complete subsets of indices: {1,4}, {1,9}, {2,8}, {4,9}, and {1,4,9}. + +The sum of the elements corresponding to indices 1 and 4 is equal to nums[1] + nums[4] = 5 + 10 = 15. + +The sum of the elements corresponding to indices 1 and 9 is equal to nums[1] + nums[9] = 5 + 4 = 9. + +The sum of the elements corresponding to indices 2 and 8 is equal to nums[2] + nums[8] = 10 + 9 = 19. + +The sum of the elements corresponding to indices 4 and 9 is equal to nums[4] + nums[9] = 10 + 4 = 14. + +The sum of the elements corresponding to indices 1, 4, and 9 is equal to nums[1] + nums[4] + nums[9] = 5 + 10 + 4 = 19. + +Hence, the maximum element-sum of a complete subset of indices is 19. + +**Constraints:** + +* 1 <= n == nums.length <= 104 +* 1 <= nums[i] <= 109 + +## Solution + +```kotlin +import kotlin.math.floor +import kotlin.math.max +import kotlin.math.sqrt + +class Solution { + fun maximumSum(nums: List): Long { + var ans: Long = 0 + val n = nums.size + val bound = floor(sqrt(n.toDouble())).toInt() + val squares = IntArray(bound + 1) + for (i in 1..bound + 1) { + squares[i - 1] = i * i + } + for (i in 1..n) { + var res: Long = 0 + var idx = 0 + var curr = i * squares[idx] + while (curr <= n) { + res += nums[curr - 1].toLong() + curr = i * squares[++idx] + } + ans = max(ans.toDouble(), res.toDouble()).toLong() + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2864_maximum_odd_binary_number/readme.md b/src/main/kotlin/g2801_2900/s2864_maximum_odd_binary_number/readme.md new file mode 100644 index 00000000..01218b02 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2864_maximum_odd_binary_number/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2864\. Maximum Odd Binary Number + +Easy + +You are given a **binary** string `s` that contains at least one `'1'`. + +You have to **rearrange** the bits in such a way that the resulting binary number is the **maximum odd binary number** that can be created from this combination. + +Return _a string representing the maximum odd binary number that can be created from the given combination._ + +**Note** that the resulting string **can** have leading zeros. + +**Example 1:** + +**Input:** s = "010" + +**Output:** "001" + +**Explanation:** Because there is just one '1', it must be in the last position. So the answer is "001". + +**Example 2:** + +**Input:** s = "0101" + +**Output:** "1001" + +**Explanation:** One of the '1's must be in the last position. The maximum number that can be made with the remaining digits is "100". So the answer is "1001". + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` consists only of `'0'` and `'1'`. +* `s` contains at least one `'1'`. + +## Solution + +```kotlin +class Solution { + fun maximumOddBinaryNumber(s: String): String { + var len = s.length + var count = 0 + val sb = StringBuilder() + for (i in 0 until len) { + if (s[i] == '1') { + count++ + } + } + if (count == len) { + return s + } + len -= count + while (count > 1) { + sb.append('1') + count-- + } + while (len > 0) { + sb.append('0') + len-- + } + sb.append('1') + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2865_beautiful_towers_i/readme.md b/src/main/kotlin/g2801_2900/s2865_beautiful_towers_i/readme.md new file mode 100644 index 00000000..be56c40b --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2865_beautiful_towers_i/readme.md @@ -0,0 +1,102 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2865\. Beautiful Towers I + +Medium + +You are given a **0-indexed** array `maxHeights` of `n` integers. + +You are tasked with building `n` towers in the coordinate line. The ith tower is built at coordinate `i` and has a height of `heights[i]`. + +A configuration of towers is **beautiful** if the following conditions hold: + +1. `1 <= heights[i] <= maxHeights[i]` +2. `heights` is a **mountain** array. + +Array `heights` is a **mountain** if there exists an index `i` such that: + +* For all `0 < j <= i`, `heights[j - 1] <= heights[j]` +* For all `i <= k < n - 1`, `heights[k + 1] <= heights[k]` + +Return _the **maximum possible sum of heights** of a beautiful configuration of towers_. + +**Example 1:** + +**Input:** maxHeights = [5,3,4,1,1] + +**Output:** 13 + +**Explanation:** One beautiful configuration with a maximum sum is heights = [5,3,3,1,1]. This configuration is beautiful since: +- 1 <= heights[i] <= maxHeights[i] +- heights is a mountain of peak i = 0. + +It can be shown that there exists no other beautiful configuration with a sum of heights greater than 13. + +**Example 2:** + +**Input:** maxHeights = [6,5,3,9,2,7] + +**Output:** 22 + +**Explanation:** One beautiful configuration with a maximum sum is heights = [3,3,3,9,2,2]. This configuration is beautiful since: +- 1 <= heights[i] <= maxHeights[i] +- heights is a mountain of peak i = 3. + +It can be shown that there exists no other beautiful configuration with a sum of heights greater than 22. + +**Example 3:** + +**Input:** maxHeights = [3,2,5,5,2,3] + +**Output:** 18 + +**Explanation:** One beautiful configuration with a maximum sum is heights = [2,2,5,5,2,2]. This configuration is beautiful since: +- 1 <= heights[i] <= maxHeights[i] +- heights is a mountain of peak i = 2. + +Note that, for this configuration, i = 3 can also be considered a peak. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 18. + +**Constraints:** + +* 1 <= n == maxHeights <= 103 +* 1 <= maxHeights[i] <= 109 + +## Solution + +```kotlin +import kotlin.math.max +import kotlin.math.min + +class Solution { + private fun `fun`(maxHeights: List, pickId: Int): Long { + var ans = maxHeights[pickId].toLong() + var min = maxHeights[pickId].toLong() + for (i in pickId - 1 downTo 0) { + min = min(min.toDouble(), maxHeights[i].toDouble()).toLong() + ans += min + } + min = maxHeights[pickId].toLong() + for (i in pickId + 1 until maxHeights.size) { + min = min(min.toDouble(), maxHeights[i].toDouble()).toLong() + ans += min + } + return ans + } + + fun maximumSumOfHeights(maxHeights: List): Long { + val n = maxHeights.size + var ans: Long = 0 + for (i in 0 until n) { + if (i == 0 || i == n - 1 || ( + maxHeights[i] >= maxHeights[i - 1] && + maxHeights[i] >= maxHeights[i + 1] + ) + ) { + ans = max(ans.toDouble(), `fun`(maxHeights, i).toDouble()).toLong() + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2866_beautiful_towers_ii/readme.md b/src/main/kotlin/g2801_2900/s2866_beautiful_towers_ii/readme.md new file mode 100644 index 00000000..8aa4ff4d --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2866_beautiful_towers_ii/readme.md @@ -0,0 +1,129 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2866\. Beautiful Towers II + +Medium + +You are given a **0-indexed** array `maxHeights` of `n` integers. + +You are tasked with building `n` towers in the coordinate line. The ith tower is built at coordinate `i` and has a height of `heights[i]`. + +A configuration of towers is **beautiful** if the following conditions hold: + +1. `1 <= heights[i] <= maxHeights[i]` +2. `heights` is a **mountain** array. + +Array `heights` is a **mountain** if there exists an index `i` such that: + +* For all `0 < j <= i`, `heights[j - 1] <= heights[j]` +* For all `i <= k < n - 1`, `heights[k + 1] <= heights[k]` + +Return _the **maximum possible sum of heights** of a beautiful configuration of towers_. + +**Example 1:** + +**Input:** maxHeights = [5,3,4,1,1] + +**Output:** 13 + +**Explanation:** One beautiful configuration with a maximum sum is heights = [5,3,3,1,1]. This configuration is beautiful since: +- 1 <= heights[i] <= maxHeights[i] +- heights is a mountain of peak i = 0. + +It can be shown that there exists no other beautiful configuration with a sum of heights greater than 13. + +**Example 2:** + +**Input:** maxHeights = [6,5,3,9,2,7] + +**Output:** 22 + +**Explanation:** One beautiful configuration with a maximum sum is heights = [3,3,3,9,2,2]. This configuration is beautiful since: +- 1 <= heights[i] <= maxHeights[i] +- heights is a mountain of peak i = 3. + +It can be shown that there exists no other beautiful configuration with a sum of heights greater than 22. + +**Example 3:** + +**Input:** maxHeights = [3,2,5,5,2,3] + +**Output:** 18 + +**Explanation:** One beautiful configuration with a maximum sum is heights = [2,2,5,5,2,2]. This configuration is beautiful since: +- 1 <= heights[i] <= maxHeights[i] +- heights is a mountain of peak i = 2. + +Note that, for this configuration, i = 3 can also be considered a peak. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 18. + +**Constraints:** + +* 1 <= n == maxHeights <= 105 +* 1 <= maxHeights[i] <= 109 + +## Solution + +```kotlin +import java.util.Deque +import java.util.LinkedList +import kotlin.math.max + +class Solution { + fun maximumSumOfHeights(mH: List): Long { + val n = mH.size + val st: Deque = LinkedList() + val prevSmaller = IntArray(n + 1) + for (i in 0 until n) { + while (st.isNotEmpty() && mH[st.peek()] >= mH[i]) { + st.pop() + } + if (st.isEmpty()) { + prevSmaller[i] = -1 + } else { + prevSmaller[i] = st.peek() + } + st.push(i) + } + st.clear() + val nextSmaller = IntArray(n + 1) + for (i in n - 1 downTo 0) { + while (st.isNotEmpty() && mH[st.peek()] >= mH[i]) { + st.pop() + } + if (st.isEmpty()) { + nextSmaller[i] = n + } else { + nextSmaller[i] = st.peek() + } + st.push(i) + } + val leftSum = LongArray(n) + leftSum[0] = mH[0].toLong() + for (i in 1 until n) { + val prevSmallerIdx = prevSmaller[i] + val equalCount = i - prevSmallerIdx + leftSum[i] = (equalCount.toLong() * mH[i]) + if (prevSmallerIdx != -1) { + leftSum[i] += leftSum[prevSmallerIdx] + } + } + val rightSum = LongArray(n) + rightSum[n - 1] = mH[n - 1].toLong() + for (i in n - 2 downTo 0) { + val nextSmallerIdx = nextSmaller[i] + val equalCount = nextSmallerIdx - i + rightSum[i] = (equalCount.toLong() * mH[i]) + if (nextSmallerIdx != n) { + rightSum[i] += rightSum[nextSmallerIdx] + } + } + var ans: Long = 0 + for (i in 0 until n) { + val totalSum = leftSum[i] + rightSum[i] - mH[i] + ans = max(ans, totalSum) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2867_count_valid_paths_in_a_tree/readme.md b/src/main/kotlin/g2801_2900/s2867_count_valid_paths_in_a_tree/readme.md new file mode 100644 index 00000000..2a118aa6 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2867_count_valid_paths_in_a_tree/readme.md @@ -0,0 +1,127 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2867\. Count Valid Paths in a Tree + +Hard + +There is an undirected tree with `n` nodes labeled from `1` to `n`. You are given the integer `n` and a 2D integer array `edges` of length `n - 1`, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the tree. + +Return _the **number of valid paths** in the tree_. + +A path `(a, b)` is **valid** if there exists **exactly one** prime number among the node labels in the path from `a` to `b`. + +**Note** that: + +* The path `(a, b)` is a sequence of **distinct** nodes starting with node `a` and ending with node `b` such that every two adjacent nodes in the sequence share an edge in the tree. +* Path `(a, b)` and path `(b, a)` are considered the **same** and counted only **once**. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/08/27/example1.png) + +**Input:** n = 5, edges = \[\[1,2],[1,3],[2,4],[2,5]] + +**Output:** 4 + +**Explanation:** The pairs with exactly one prime number on the path between them are: +- (1, 2) since the path from 1 to 2 contains prime number 2. +- (1, 3) since the path from 1 to 3 contains prime number 3. +- (1, 4) since the path from 1 to 4 contains prime number 2. +- (2, 4) since the path from 2 to 4 contains prime number 2. + +It can be shown that there are only 4 valid paths. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/08/27/example2.png) + +**Input:** n = 6, edges = \[\[1,2],[1,3],[2,4],[3,5],[3,6]] + +**Output:** 6 + +**Explanation:** The pairs with exactly one prime number on the path between them are: +- (1, 2) since the path from 1 to 2 contains prime number 2. +- (1, 3) since the path from 1 to 3 contains prime number 3. +- (1, 4) since the path from 1 to 4 contains prime number 2. +- (1, 6) since the path from 1 to 6 contains prime number 3. +- (2, 4) since the path from 2 to 4 contains prime number 2. +- (3, 6) since the path from 3 to 6 contains prime number 3. + +It can be shown that there are only 6 valid paths. + +**Constraints:** + +* 1 <= n <= 105 +* `edges.length == n - 1` +* `edges[i].length == 2` +* 1 <= ui, vi <= n +* The input is generated such that `edges` represent a valid tree. + +## Solution + +```kotlin +class Solution { + private lateinit var isPrime: BooleanArray + private lateinit var treeEdges: Array?> + private var r: Long = 0 + + private fun preparePrime(n: Int): BooleanArray { + // Sieve of Eratosthenes < 3 + val isPrimeLocal = BooleanArray(n + 1) + for (i in 2 until n + 1) { + isPrimeLocal[i] = true + } + for (i in 2..n / 2) { + var j = 2 * i + while (j < n + 1) { + isPrimeLocal[j] = false + j += i + } + } + return isPrimeLocal + } + + private fun prepareTree(n: Int, edges: Array): Array?> { + val treeEdgesLocal: Array?> = arrayOfNulls(n + 1) + for (edge in edges) { + if (treeEdgesLocal[edge[0]] == null) { + treeEdgesLocal[edge[0]] = ArrayList() + } + treeEdgesLocal[edge[0]]!!.add(edge[1]) + if (treeEdgesLocal[edge[1]] == null) { + treeEdgesLocal[edge[1]] = ArrayList() + } + treeEdgesLocal[edge[1]]!!.add(edge[0]) + } + return treeEdgesLocal + } + + private fun countPathDfs(node: Int, parent: Int): LongArray { + val v = longArrayOf((if (isPrime[node]) 0 else 1).toLong(), (if (isPrime[node]) 1 else 0).toLong()) + val edges = treeEdges[node] ?: return v + for (neigh in edges) { + if (neigh == parent) { + continue + } + val ce = countPathDfs(neigh, node) + r += v[0] * ce[1] + v[1] * ce[0] + if (isPrime[node]) { + v[1] += ce[0] + } else { + v[0] += ce[0] + v[1] += ce[1] + } + } + return v + } + + fun countPaths(n: Int, edges: Array): Long { + isPrime = preparePrime(n) + treeEdges = prepareTree(n, edges) + r = 0 + countPathDfs(1, 0) + return r + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2869_minimum_operations_to_collect_elements/readme.md b/src/main/kotlin/g2801_2900/s2869_minimum_operations_to_collect_elements/readme.md new file mode 100644 index 00000000..2e0d5aa8 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2869_minimum_operations_to_collect_elements/readme.md @@ -0,0 +1,72 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2869\. Minimum Operations to Collect Elements + +Easy + +You are given an array `nums` of positive integers and an integer `k`. + +In one operation, you can remove the last element of the array and add it to your collection. + +Return _the **minimum number of operations** needed to collect elements_ `1, 2, ..., k`. + +**Example 1:** + +**Input:** nums = [3,1,5,4,2], k = 2 + +**Output:** 4 + +**Explanation:** After 4 operations, we collect elements 2, 4, 5, and 1, in this order. Our collection contains elements 1 and 2. Hence, the answer is 4. + +**Example 2:** + +**Input:** nums = [3,1,5,4,2], k = 5 + +**Output:** 5 + +**Explanation:** After 5 operations, we collect elements 2, 4, 5, 1, and 3, in this order. Our collection contains elements 1 through 5. Hence, the answer is 5. + +**Example 3:** + +**Input:** nums = [3,2,5,3,1], k = 3 + +**Output:** 4 + +**Explanation:** After 4 operations, we collect elements 1, 3, 5, and 2, in this order. Our collection contains elements 1 through 3. Hence, the answer is 4. + +**Constraints:** + +* `1 <= nums.length <= 50` +* `1 <= nums[i] <= nums.length` +* `1 <= k <= nums.length` +* The input is generated such that you can collect elements `1, 2, ..., k`. + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun minOperations(nums: List, k: Int): Int { + val visited = arrayOfNulls(k + 1) + visited[0] = Pair(0) + var count = 0 + for (i in nums.indices.reversed()) { + count++ + if (nums[i] <= k && visited[nums[i]] == null) { + visited[nums[i]] = Pair(count) + } + } + var fin = -1 + for (pair in visited) { + if (pair != null) { + fin = max(fin, pair.totalVisitedTillNow) + } + } + return fin + } + + private class Pair(var totalVisitedTillNow: Int) +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2870_minimum_number_of_operations_to_make_array_empty/readme.md b/src/main/kotlin/g2801_2900/s2870_minimum_number_of_operations_to_make_array_empty/readme.md new file mode 100644 index 00000000..48f6fb7e --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2870_minimum_number_of_operations_to_make_array_empty/readme.md @@ -0,0 +1,59 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2870\. Minimum Number of Operations to Make Array Empty + +Medium + +You are given a **0-indexed** array `nums` consisting of positive integers. + +There are two types of operations that you can apply on the array **any** number of times: + +* Choose **two** elements with **equal** values and **delete** them from the array. +* Choose **three** elements with **equal** values and **delete** them from the array. + +Return _the **minimum** number of operations required to make the array empty, or_ `-1` _if it is not possible_. + +**Example 1:** + +**Input:** nums = [2,3,3,2,2,4,2,3,4] + +**Output:** 4 + +**Explanation:** We can apply the following operations to make the array empty: +- Apply the first operation on the elements at indices 0 and 3. The resulting array is nums = [3,3,2,4,2,3,4]. +- Apply the first operation on the elements at indices 2 and 4. The resulting array is nums = [3,3,4,3,4]. +- Apply the second operation on the elements at indices 0, 1, and 3. The resulting array is nums = [4,4]. +- Apply the first operation on the elements at indices 0 and 1. The resulting array is nums = []. + +It can be shown that we cannot make the array empty in less than 4 operations. + +**Example 2:** + +**Input:** nums = [2,1,2,2,3,3] + +**Output:** -1 + +**Explanation:** It is impossible to empty the array. + +**Constraints:** + +* 2 <= nums.length <= 105 +* 1 <= nums[i] <= 106 + +## Solution + +```kotlin +class Solution { + fun minOperations(nums: IntArray): Int { + var count = 0 + val map = hashMapOf() + for (num in nums) map[num] = map[num]?.plus(1) ?: 1 + for ((_, v) in map) { + if (v == 1) return -1 + count += (v / 3) + (if (v % 3 == 0) 0 else 1) + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2871_split_array_into_maximum_number_of_subarrays/readme.md b/src/main/kotlin/g2801_2900/s2871_split_array_into_maximum_number_of_subarrays/readme.md new file mode 100644 index 00000000..cc6b50d9 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2871_split_array_into_maximum_number_of_subarrays/readme.md @@ -0,0 +1,80 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2871\. Split Array Into Maximum Number of Subarrays + +Medium + +You are given an array `nums` consisting of **non-negative** integers. + +We define the score of subarray `nums[l..r]` such that `l <= r` as `nums[l] AND nums[l + 1] AND ... AND nums[r]` where **AND** is the bitwise `AND` operation. + +Consider splitting the array into one or more subarrays such that the following conditions are satisfied: + +* **E****ach** element of the array belongs to **exactly** one subarray. +* The sum of scores of the subarrays is the **minimum** possible. + +Return _the **maximum** number of subarrays in a split that satisfies the conditions above._ + +A **subarray** is a contiguous part of an array. + +**Example 1:** + +**Input:** nums = [1,0,2,0,1,2] + +**Output:** 3 + +**Explanation:** We can split the array into the following subarrays: +- \[1,0]. The score of this subarray is 1 AND 0 = 0. +- \[2,0]. The score of this subarray is 2 AND 0 = 0. +- \[1,2]. The score of this subarray is 1 AND 2 = 0. + +The sum of scores is 0 + 0 + 0 = 0, which is the minimum possible score that we can obtain. + +It can be shown that we cannot split the array into more than 3 subarrays with a total score of 0. So we return 3. + +**Example 2:** + +**Input:** nums = [5,7,1,3] + +**Output:** 1 + +**Explanation:** We can split the array into one subarray: [5,7,1,3] with a score of 1, which is the minimum possible score that we can obtain. It can be shown that we cannot split the array into more than 1 subarray with a total score of 1. So we return 1. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 0 <= nums[i] <= 106 + +## Solution + +```kotlin +class Solution { + fun maxSubarrays(nums: IntArray): Int { + if (nums.size == 1) { + return 1 + } + var andMax = nums[0] + var count = 0 + var currAnd = nums[0] + var sum = 0 + for (n in nums) { + andMax = andMax and n + } + for (i in 1 until nums.size) { + val n = nums[i] + if (currAnd <= andMax) { + count++ + sum += currAnd + currAnd = n + } + currAnd = currAnd and n + } + if (currAnd <= andMax) { + count++ + sum += currAnd + } + return if (sum <= andMax) count else 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2872_maximum_number_of_k_divisible_components/readme.md b/src/main/kotlin/g2801_2900/s2872_maximum_number_of_k_divisible_components/readme.md new file mode 100644 index 00000000..e79abee5 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2872_maximum_number_of_k_divisible_components/readme.md @@ -0,0 +1,103 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2872\. Maximum Number of K-Divisible Components + +Hard + +There is an undirected tree with `n` nodes labeled from `0` to `n - 1`. You are given the integer `n` and a 2D integer array `edges` of length `n - 1`, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. + +You are also given a **0-indexed** integer array `values` of length `n`, where `values[i]` is the **value** associated with the ith node, and an integer `k`. + +A **valid split** of the tree is obtained by removing any set of edges, possibly empty, from the tree such that the resulting components all have values that are divisible by `k`, where the **value of a connected component** is the sum of the values of its nodes. + +Return _the **maximum number of components** in any valid split_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/08/07/example12-cropped2svg.jpg) + +**Input:** n = 5, edges = \[\[0,2],[1,2],[1,3],[2,4]], values = [1,8,1,4,4], k = 6 + +**Output:** 2 + +**Explanation:** We remove the edge connecting node 1 with 2. The resulting split is valid because: +- The value of the component containing nodes 1 and 3 is values[1] + values[3] = 12. +- The value of the component containing nodes 0, 2, and 4 is values[0] + values[2] + values[4] = 6. + +It can be shown that no other valid split has more than 2 connected components. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/08/07/example21svg-1.jpg) + +**Input:** n = 7, edges = \[\[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [3,0,6,1,5,2,1], k = 3 + +**Output:** 3 + +**Explanation:** We remove the edge connecting node 0 with 2, and the edge connecting node 0 with 1. The resulting split is valid because: +- The value of the component containing node 0 is values[0] = 3. +- The value of the component containing nodes 2, 5, and 6 is values[2] + values[5] + values[6] = 9. +- The value of the component containing nodes 1, 3, and 4 is values[1] + values[3] + values[4] = 6. + +It can be shown that no other valid split has more than 3 connected components. + +**Constraints:** + +* 1 <= n <= 3 * 104 +* `edges.length == n - 1` +* `edges[i].length == 2` +* 0 <= ai, bi < n +* `values.length == n` +* 0 <= values[i] <= 109 +* 1 <= k <= 109 +* Sum of `values` is divisible by `k`. +* The input is generated such that `edges` represents a valid tree. + +## Solution + +```kotlin +class Solution { + private var ans = 0 + + fun maxKDivisibleComponents(n: Int, edges: Array, values: IntArray, k: Int): Int { + val adj: MutableList> = ArrayList() + for (i in 0 until n) { + adj.add(ArrayList()) + } + for (edge in edges) { + val start = edge[0] + val end = edge[1] + adj[start].add(end) + adj[end].add(start) + } + val isVis = BooleanArray(n) + isVis[0] = true + get(0, -1, adj, isVis, values, k.toLong()) + return ans + } + + private fun get( + curNode: Int, + parent: Int, + adj: List>, + isVis: BooleanArray, + values: IntArray, + k: Long + ): Long { + var sum = values[curNode].toLong() + for (ele in adj[curNode]) { + if (ele != parent && !isVis[ele]) { + isVis[ele] = true + sum += get(ele, curNode, adj, isVis, values, k) + } + } + return if (sum % k == 0L) { + ans++ + 0 + } else { + sum + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2873_maximum_value_of_an_ordered_triplet_i/readme.md b/src/main/kotlin/g2801_2900/s2873_maximum_value_of_an_ordered_triplet_i/readme.md new file mode 100644 index 00000000..162efe7a --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2873_maximum_value_of_an_ordered_triplet_i/readme.md @@ -0,0 +1,75 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2873\. Maximum Value of an Ordered Triplet I + +Easy + +You are given a **0-indexed** integer array `nums`. + +Return _**the maximum value over all triplets of indices**_ `(i, j, k)` _such that_ `i < j < k`. If all such triplets have a negative value, return `0`. + +The **value of a triplet of indices** `(i, j, k)` is equal to `(nums[i] - nums[j]) * nums[k]`. + +**Example 1:** + +**Input:** nums = [12,6,1,2,7] + +**Output:** 77 + +**Explanation:** The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) \* nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77. + +**Example 2:** + +**Input:** nums = [1,10,3,4,19] + +**Output:** 133 + +**Explanation:** The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) \* nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133. + +**Example 3:** + +**Input:** nums = [1,2,3] + +**Output:** 0 + +**Explanation:** The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) \* nums[2] = -3. Hence, the answer would be 0. + +**Constraints:** + +* `3 <= nums.length <= 100` +* 1 <= nums[i] <= 106 + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun maximumTripletValue(nums: IntArray): Long { + val n = nums.size + val iNumMaxs = IntArray(n) + var prev = 0 + for (i in 0 until n) { + if (nums[i] <= prev) { + iNumMaxs[i] = prev + } else { + iNumMaxs[i] = nums[i] + prev = iNumMaxs[i] + } + } + var result: Long = 0 + var kNumMax = nums[n - 1] + for (j in n - 2 downTo 1) { + result = max( + result.toDouble(), + ((iNumMaxs[j - 1] - nums[j]).toLong() * kNumMax).toDouble() + ).toLong() + if (nums[j] > kNumMax) { + kNumMax = nums[j] + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2874_maximum_value_of_an_ordered_triplet_ii/readme.md b/src/main/kotlin/g2801_2900/s2874_maximum_value_of_an_ordered_triplet_ii/readme.md new file mode 100644 index 00000000..ff85ab1d --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2874_maximum_value_of_an_ordered_triplet_ii/readme.md @@ -0,0 +1,65 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2874\. Maximum Value of an Ordered Triplet II + +Medium + +You are given a **0-indexed** integer array `nums`. + +Return _**the maximum value over all triplets of indices**_ `(i, j, k)` _such that_ `i < j < k`_._ If all such triplets have a negative value, return `0`. + +The **value of a triplet of indices** `(i, j, k)` is equal to `(nums[i] - nums[j]) * nums[k]`. + +**Example 1:** + +**Input:** nums = [12,6,1,2,7] + +**Output:** 77 + +**Explanation:** The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) \* nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77. + +**Example 2:** + +**Input:** nums = [1,10,3,4,19] + +**Output:** 133 + +**Explanation:** The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) \* nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133. + +**Example 3:** + +**Input:** nums = [1,2,3] + +**Output:** 0 + +**Explanation:** The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) \* nums[2] = -3. Hence, the answer would be 0. + +**Constraints:** + +* 3 <= nums.length <= 105 +* 1 <= nums[i] <= 106 + +## Solution + +```kotlin +import kotlin.math.max + +class Solution { + fun maximumTripletValue(nums: IntArray): Long { + val diff = IntArray(nums.size) + var tempMax = nums[0] + for (i in 1 until diff.size - 1) { + diff[i] = tempMax - nums[i] + tempMax = max(tempMax.toDouble(), nums[i].toDouble()).toInt() + } + var max = Long.MIN_VALUE + tempMax = nums[nums.size - 1] + for (i in nums.size - 2 downTo 1) { + max = max(max.toDouble(), (tempMax.toLong() * diff[i]).toDouble()).toLong() + tempMax = max(tempMax.toDouble(), nums[i].toDouble()).toInt() + } + return max(max.toDouble(), 0.0).toLong() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2875_minimum_size_subarray_in_infinite_array/readme.md b/src/main/kotlin/g2801_2900/s2875_minimum_size_subarray_in_infinite_array/readme.md new file mode 100644 index 00000000..aebed300 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2875_minimum_size_subarray_in_infinite_array/readme.md @@ -0,0 +1,79 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2875\. Minimum Size Subarray in Infinite Array + +Medium + +You are given a **0-indexed** array `nums` and an integer `target`. + +A **0-indexed** array `infinite_nums` is generated by infinitely appending the elements of `nums` to itself. + +Return _the length of the **shortest** subarray of the array_ `infinite_nums` _with a sum equal to_ `target`_._ If there is no such subarray return `-1`. + +**Example 1:** + +**Input:** nums = [1,2,3], target = 5 + +**Output:** 2 + +**Explanation:** In this example infinite\_nums = [1,2,3,1,2,3,1,2,...]. The subarray in the range [1,2], has the sum equal to target = 5 and length = 2. It can be proven that 2 is the shortest length of a subarray with sum equal to target = 5. + +**Example 2:** + +**Input:** nums = [1,1,1,2,3], target = 4 + +**Output:** 2 + +**Explanation:** In this example infinite\_nums = [1,1,1,2,3,1,1,1,2,3,1,1,...]. The subarray in the range [4,5], has the sum equal to target = 4 and length = 2. It can be proven that 2 is the shortest length of a subarray with sum equal to target = 4. + +**Example 3:** + +**Input:** nums = [2,4,6,8], target = 3 + +**Output:** -1 + +**Explanation:** In this example infinite\_nums = [2,4,6,8,2,4,6,8,...]. It can be proven that there is no subarray with sum equal to target = 3. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 105 +* 1 <= target <= 109 + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + fun minSizeSubarray(nums: IntArray, target: Int): Int { + var sum = 0 + for (num in nums) { + sum += num + } + if (sum == 0) { + return -1 + } + val result = (target / sum) * nums.size + sum = target % sum + var currentSum = 0 + var min = nums.size + var start = 0 + for (i in 0 until nums.size * 2) { + currentSum += nums[i % nums.size] + while (currentSum > sum) { + currentSum -= nums[start % nums.size] + start++ + } + if (currentSum == sum) { + min = min(min, i - start + 1) + } + } + if (min == nums.size) { + return -1 + } + return result + min + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2876_count_visited_nodes_in_a_directed_graph/readme.md b/src/main/kotlin/g2801_2900/s2876_count_visited_nodes_in_a_directed_graph/readme.md new file mode 100644 index 00000000..1dcd4503 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2876_count_visited_nodes_in_a_directed_graph/readme.md @@ -0,0 +1,90 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2876\. Count Visited Nodes in a Directed Graph + +Hard + +There is a **directed** graph consisting of `n` nodes numbered from `0` to `n - 1` and `n` directed edges. + +You are given a **0-indexed** array `edges` where `edges[i]` indicates that there is an edge from node `i` to node `edges[i]`. + +Consider the following process on the graph: + +* You start from a node `x` and keep visiting other nodes through edges until you reach a node that you have already visited before on this **same** process. + +Return _an array_ `answer` _where_ `answer[i]` _is the number of **different** nodes that you will visit if you perform the process starting from node_ `i`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/08/31/graaphdrawio-1.png) + +**Input:** edges = [1,2,0,0] + +**Output:** [3,3,3,4] + +**Explanation:** We perform the process starting from each node in the following way: +- Starting from node 0, we visit the nodes 0 -> 1 -> 2 -> 0. The number of different nodes we visit is 3. +- Starting from node 1, we visit the nodes 1 -> 2 -> 0 -> 1. The number of different nodes we visit is 3. +- Starting from node 2, we visit the nodes 2 -> 0 -> 1 -> 2. The number of different nodes we visit is 3. +- Starting from node 3, we visit the nodes 3 -> 0 -> 1 -> 2 -> 0. The number of different nodes we visit is 4. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/08/31/graaph2drawio.png) + +**Input:** edges = [1,2,3,4,0] + +**Output:** [5,5,5,5,5] + +**Explanation:** Starting from any node we can visit every node in the graph in the process. + +**Constraints:** + +* `n == edges.length` +* 2 <= n <= 105 +* `0 <= edges[i] <= n - 1` +* `edges[i] != i` + +## Solution + +```kotlin +class Solution { + fun countVisitedNodes(edges: List): IntArray { + val n = edges.size + val visited = BooleanArray(n) + val ans = IntArray(n) + val level = IntArray(n) + for (i in 0 until n) { + if (!visited[i]) { + visit(edges, 0, i, ans, visited, level) + } + } + return ans + } + + private fun visit( + edges: List, + count: Int, + curr: Int, + ans: IntArray, + visited: BooleanArray, + level: IntArray + ): IntArray { + if (ans[curr] != 0) { + return intArrayOf(-1, ans[curr]) + } + if (visited[curr]) { + return intArrayOf(level[curr], count - level[curr]) + } + level[curr] = count + visited[curr] = true + val ret = visit(edges, count + 1, edges[curr], ans, visited, level) + if (ret[0] == -1 || count < ret[0]) { + ret[1]++ + } + ans[curr] = ret[1] + return ret + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2877_create_a_dataframe_from_list/readme.md b/src/main/kotlin/g2801_2900/s2877_create_a_dataframe_from_list/readme.md new file mode 100644 index 00000000..4ba40ed6 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2877_create_a_dataframe_from_list/readme.md @@ -0,0 +1,40 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2877\. Create a DataFrame from List + +Easy + +Write a solution to **create** a DataFrame from a 2D list called `student_data`. This 2D list contains the IDs and ages of some students. + +The DataFrame should have two columns, `student_id` and `age`, and be in the same order as the original 2D list. + +The result format is in the following example. + +**Example 1:** + +**Input:** student\_data: `[ [1, 15], [2, 11], [3, 11], [4, 20] ]` + +**Output:** + + +------------+-----+ + | student_id | age | + +------------+-----+ + | 1 | 15 | + | 2 | 11 | + | 3 | 11 | + | 4 | 20 | + +------------+-----+ + +**Explanation:** A DataFrame was created on top of student\_data, with two columns named `student_id` and `age`. + +## Solution + +```python +import pandas as pd + +def createDataframe(student_data: List[List[int]]) -> pd.DataFrame: + column_name = ['student_id','age'] + result = pd.DataFrame(student_data, columns=column_name) + return result +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2878_get_the_size_of_a_dataframe/readme.md b/src/main/kotlin/g2801_2900/s2878_get_the_size_of_a_dataframe/readme.md new file mode 100644 index 00000000..cf918887 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2878_get_the_size_of_a_dataframe/readme.md @@ -0,0 +1,58 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2878\. Get the Size of a DataFrame + +Easy + +DataFrame `players:` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | player_id | int | + | name | object | + | age | int | + | position | object | + | ... | ... | + +-------------+--------+ + +Write a solution to calculate and display the **number of rows and columns** of `players`. + +Return the result as an array: + +`[number of rows, number of columns]` + +The result format is in the following example. + +**Example 1:** + +**Input:** + + +-----------+----------+-----+-------------+--------------------+ + | player_id | name | age | position | team | + +-----------+----------+-----+-------------+--------------------+ + | 846 | Mason | 21 | Forward | RealMadrid | + | 749 | Riley | 30 | Winger | Barcelona | + | 155 | Bob | 28 | Striker | ManchesterUnited | + | 583 | Isabella | 32 | Goalkeeper | Liverpool | + | 388 | Zachary | 24 | Midfielder | BayernMunich | + | 883 | Ava | 23 | Defender | Chelsea | + | 355 | Violet | 18 | Striker | Juventus | + | 247 | Thomas | 27 | Striker | ParisSaint-Germain | + | 761 | Jack | 33 | Midfielder | ManchesterCity | + | 642 | Charlie | 36 | Center-back | Arsenal | + +-----------+----------+-----+-------------+--------------------+ + +**Output:** [10, 5] + +**Explanation:** This DataFrame contains 10 rows and 5 columns. + +## Solution + +```python +import pandas as pd + +def getDataframeSize(players: pd.DataFrame) -> List[int]: + return[players.shape[0], players.shape[1]] +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2879_display_the_first_three_rows/readme.md b/src/main/kotlin/g2801_2900/s2879_display_the_first_three_rows/readme.md new file mode 100644 index 00000000..69be73e9 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2879_display_the_first_three_rows/readme.md @@ -0,0 +1,55 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2879\. Display the First Three Rows + +Easy + +DataFrame: `employees` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | employee_id | int | + | name | object | + | department | object | + | salary | int | + +-------------+--------+ + +Write a solution to display the **first `3`** rows of this DataFrame. + +**Example 1:** + +**Input:** DataFrame employees + + +-------------+-----------+-----------------------+--------+ + | employee_id | name | department | salary | + +-------------+-----------+-----------------------+--------+ + | 3 | Bob | Operations | 48675 | + | 90 | Alice | Sales | 11096 | + | 9 | Tatiana | Engineering | 33805 | + | 60 | Annabelle | InformationTechnology | 37678 | + | 49 | Jonathan | HumanResources | 23793 | + | 43 | Khaled | Administration | 40454 | + +-------------+-----------+-----------------------+--------+ + +**Output:** + + +-------------+---------+-------------+--------+ + | employee_id | name | department | salary | + +-------------+---------+-------------+--------+ + | 3 | Bob | Operations | 48675 | + | 90 | Alice | Sales | 11096 | + | 9 | Tatiana | Engineering | 33805 | + +-------------+---------+-------------+--------+ + +**Explanation:** Only the first 3 rows are displayed. + +## Solution + +```python +import pandas as pd + +def selectFirstRows(zs: pd.DataFrame) -> pd.DataFrame: + return zs.head(3) +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2880_select_data/readme.md b/src/main/kotlin/g2801_2900/s2880_select_data/readme.md new file mode 100644 index 00000000..77676836 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2880_select_data/readme.md @@ -0,0 +1,50 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2880\. Select Data + +Easy + +DataFrame students + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | student_id | int | + | name | object | + | age | int | + +-------------+--------+ + +Write a solution to select the name and age of the student with `student_id = 101`. + +The result format is in the following example. + +**Example 1: Input:** + + +------------+---------+-----+ + | student_id | name | age | + +------------+---------+-----+ + | 101 | Ulysses | 13 | + | 53 | William | 10 | + | 128 | Henry | 6 | + | 3 | Henry | 11 | + +------------+---------+-----+ + +**Output:** + + +---------+-----+ + | name | age | + +---------+-----+ + | Ulysses | 13 | + +---------+-----+ + +**Explanation:** Student Ulysses has student_id = 101, we select the name and age. + +## Solution + +```python +import pandas as pd + +def selectData(students: pd.DataFrame) -> pd.DataFrame: + return students[students.student_id == 101][['name','age']] +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2881_create_a_new_column/readme.md b/src/main/kotlin/g2801_2900/s2881_create_a_new_column/readme.md new file mode 100644 index 00000000..2ae37058 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2881_create_a_new_column/readme.md @@ -0,0 +1,61 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2881\. Create a New Column + +Easy + +DataFrame `employees` + + +-------------+--------+ + | Column Name | Type. | + +-------------+--------+ + | name | object | + | salary | int. | + +-------------+--------+ + +A company plans to provide its employees with a bonus. + +Write a solution to create a new column name `bonus` that contains the **doubled values** of the `salary` column. + +The result format is in the following example. + +**Example 1:** + +**Input:** DataFrame employees + + +---------+--------+ + | name | salary | + +---------+--------+ + | Piper | 4548 | + | Grace | 28150 | + | Georgia | 1103 | + | Willow | 6593 | + | Finn | 74576 | + | Thomas | 24433 | + +---------+--------+ + +**Output:** + + +---------+--------+--------+ + | name | salary | bonus | + +---------+--------+--------+ + | Piper | 4548 | 9096 | + | Grace | 28150 | 56300 | + | Georgia | 1103 | 2206 | + | Willow | 6593 | 13186 | + | Finn | 74576 | 149152 | + | Thomas | 24433 | 48866 | + +---------+--------+--------+ + +**Explanation:** A new column bonus is created by doubling the value in the column salary. + +## Solution + +```python +import pandas as pd + +def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame: + employees["bonus"] = employees["salary"] * 2 + return employees +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2882_drop_duplicate_rows/readme.md b/src/main/kotlin/g2801_2900/s2882_drop_duplicate_rows/readme.md new file mode 100644 index 00000000..b856af5e --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2882_drop_duplicate_rows/readme.md @@ -0,0 +1,61 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2882\. Drop Duplicate Rows + +Easy + +DataFrame customers + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | customer_id | int | + | name | object | + | email | object | + +-------------+--------+ + +There are some duplicate rows in the DataFrame based on the `email` column. + +Write a solution to remove these duplicate rows and keep only the **first** occurrence. + +The result format is in the following example. + +**Example 1:** + +**Input:** + + +-------------+---------+---------------------+ + | customer_id | name | email | + +-------------+---------+---------------------+ + | 1 | Ella | emily@example.com | + | 2 | David | michael@example.com | + | 3 | Zachary | sarah@example.com | + | 4 | Alice | john@example.com | + | 5 | Finn | john@example.com | + | 6 | Violet | alice@example.com | + +-------------+---------+---------------------+ + +**Output:** + + +-------------+---------+---------------------+ + | customer_id | name | email | + +-------------+---------+---------------------+ + | 1 | Ella | emily@example.com | + | 2 | David | michael@example.com | + | 3 | Zachary | sarah@example.com | + | 4 | Alice | john@example.com | + | 6 | Violet | alice@example.com | + +-------------+---------+---------------------+ + +**Explanation:** Alic (customer_id = 4) and Finn (customer_id = 5) both use john@example.com, so only the first occurrence of this email is retained. + +## Solution + +```python +import pandas as pd + +def dropDuplicateEmails(customers: pd.DataFrame) -> pd.DataFrame: + customers.drop_duplicates(subset='email', keep='first', inplace=True) + return customers +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2883_drop_missing_data/readme.md b/src/main/kotlin/g2801_2900/s2883_drop_missing_data/readme.md new file mode 100644 index 00000000..28152ee2 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2883_drop_missing_data/readme.md @@ -0,0 +1,58 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2883\. Drop Missing Data + +Easy + +DataFrame students + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | student_id | int | + | name | object | + | age | int | + +-------------+--------+ + +There are some rows having missing values in the `name` column. + +Write a solution to remove the rows with missing values. + +The result format is in the following example. + +**Example 1:** + +**Input:** + + +------------+---------+-----+ + | student_id | name | age | + +------------+---------+-----+ + | 32 | Piper | 5 | + | 217 | None | 19 | + | 779 | Georgia | 20 | + | 849 | Willow | 14 | + +------------+---------+-----+ + +**Output:** + + +------------+---------+-----+ + | student_id | name | age | + +------------+---------+-----+ + | 32 | Piper | 5 | + | 779 | Georgia | 20 | + | 849 | Willow | 14 | + +------------+---------+-----+ + +**Explanation:** Student with id 217 havs empty value in the name column, so it will be removed. + +## Solution + +```python +import pandas as pd + +def dropMissingData(students: pd.DataFrame) -> pd.DataFrame: + r = pd.DataFrame(students) + r.dropna(subset='name', inplace=True) + return r +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2884_modify_columns/readme.md b/src/main/kotlin/g2801_2900/s2884_modify_columns/readme.md new file mode 100644 index 00000000..30a3449b --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2884_modify_columns/readme.md @@ -0,0 +1,57 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2884\. Modify Columns + +Easy + +DataFrame `employees` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | name | object | + | salary | int | + +-------------+--------+ + +A company intends to give its employees a pay rise. + +Write a solution to **modify** the `salary` column by multiplying each salary by 2. + +The result format is in the following example. + +**Example 1:** + +**Input:** DataFrame employees + + +---------+--------+ + | name | salary | + +---------+--------+ + | Jack | 19666 | + | Piper | 74754 | + | Mia | 62509 | + | Ulysses | 54866 | + +---------+--------+ + +**Output:** + + +---------+--------+ + | name | salary | + +---------+--------+ + | Jack | 39332 | + | Piper | 149508 | + | Mia | 125018 | + | Ulysses | 109732 | + +---------+--------+ + +**Explanation:** Every salary has been doubled. + +## Solution + +```python +import pandas as pd + +def modifySalaryColumn(employees: pd.DataFrame) -> pd.DataFrame: + employees['salary'] = employees['salary'] * 2 + return employees +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2885_rename_columns/readme.md b/src/main/kotlin/g2801_2900/s2885_rename_columns/readme.md new file mode 100644 index 00000000..5dfd16d2 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2885_rename_columns/readme.md @@ -0,0 +1,62 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2885\. Rename Columns + +Easy + +DataFrame `students` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | id | int | + | first | object | + | last | object | + | age | int | + +-------------+--------+ + +Write a solution to rename the columns as follows: + +* `id` to `student_id` +* `first` to `first_name` +* `last` to `last_name` +* `age` to `age_in_years` + +The result format is in the following example. + +**Example 1:** **Input:** + + +----+---------+----------+-----+ + | id | first | last | age | + +----+---------+----------+-----+ + | 1 | Mason | King | 6 | + | 2 | Ava | Wright | 7 | + | 3 | Taylor | Hall | 16 | + | 4 | Georgia | Thompson | 18 | + | 5 | Thomas | Moore | 10 | + +----+---------+----------+-----+ + +**Output:** + + +------------+------------+-----------+--------------+ + | student_id | first_name | last_name | age_in_years | + +------------+------------+-----------+--------------+ + | 1 | Mason | King | 6 | + | 2 | Ava | Wright | 7 | + | 3 | Taylor | Hall | 16 | + | 4 | Georgia | Thompson | 18 | + | 5 | Thomas | Moore | 10 | + +------------+------------+-----------+--------------+ + +**Explanation:** The column names are changed accordingly. + +## Solution + +```python +import pandas as pd + +def renameColumns(students: pd.DataFrame) -> pd.DataFrame: + students.rename(columns={'id': 'student_id', 'first': 'first_name', 'last': 'last_name', 'age': 'age_in_years'}, inplace=True) + return students +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2886_change_data_type/readme.md b/src/main/kotlin/g2801_2900/s2886_change_data_type/readme.md new file mode 100644 index 00000000..1a803719 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2886_change_data_type/readme.md @@ -0,0 +1,53 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2886\. Change Data Type + +Easy + +DataFrame `students` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | student_id | int | + | name | object | + | age | int | + | grade | float | + +-------------+--------+ + +Write a solution to correct the errors: + +The `grade` column is stored as floats, convert it to integers. + +The result format is in the following example. + +**Example 1:** **Input:** DataFrame students: + + +------------+------+-----+-------+ + | student_id | name | age | grade | + +------------+------+-----+-------+ + | 1 | Ava | 6 | 73.0 | + | 2 | Kate | 15 | 87.0 | + +------------+------+-----+-------+ + +**Output:** + + +------------+------+-----+-------+ + | student_id | name | age | grade | + +------------+------+-----+-------+ + | 1 | Ava | 6 | 73 | + | 2 | Kate | 15 | 87 | + +------------+------+-----+-------+ + +**Explanation:** The data types of the column grade is converted to int. + +## Solution + +```python +import pandas as pd + +def changeDatatype(students: pd.DataFrame) -> pd.DataFrame: + students['grade'] = students['grade'].astype(int) + return students +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2887_fill_missing_data/readme.md b/src/main/kotlin/g2801_2900/s2887_fill_missing_data/readme.md new file mode 100644 index 00000000..66bdfa5c --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2887_fill_missing_data/readme.md @@ -0,0 +1,56 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2887\. Fill Missing Data + +Easy + +DataFrame `products` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | name | object | + | quantity | int | + | price | int | + +-------------+--------+ + +Write a solution to fill in the missing value as **0** in the `quantity` column. + +The result format is in the following example. + +**Example 1:** + +**Input:** + + +-----------------+----------+-------+ + | name | quantity | price | + +-----------------+----------+-------+ + | Wristwatch | None | 135 | + | WirelessEarbuds | None | 821 | + | GolfClubs | 779 | 9319 | + | Printer | 849 | 3051 | + +-----------------+----------+-------+ + +**Output:** + + +-----------------+----------+-------+ + | name | quantity | price | + +-----------------+----------+-------+ + | Wristwatch | 0 | 135 | + | WirelessEarbuds | 0 | 821 | + | GolfClubs | 779 | 9319 | + | Printer | 849 | 3051 | + +-----------------+----------+-------+ + +**Explanation:** The quantity for Wristwatch and WirelessEarbuds are filled by 0. + +## Solution + +```python +import pandas as pd + +def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame: + products['quantity'].fillna(0, inplace=True) + return products +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2888_reshape_data_concatenate/readme.md b/src/main/kotlin/g2801_2900/s2888_reshape_data_concatenate/readme.md new file mode 100644 index 00000000..0b385b01 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2888_reshape_data_concatenate/readme.md @@ -0,0 +1,76 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2888\. Reshape Data: Concatenate + +Easy + +DataFrame `df1` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | student_id | int | + | name | object | + | age | int | + +-------------+--------+ + +DataFrame `df2` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | student_id | int | + | name | object | + | age | int | + +-------------+--------+ + +Write a solution to concatenate these two DataFrames **vertically** into one DataFrame. + +The result format is in the following example. + +**Example 1:** + +**Input: df1** + + +------------+---------+-----+ + | student_id | name | age | + +------------+---------+-----+ + | 1 | Mason | 8 | + | 2 | Ava | 6 | + | 3 | Taylor | 15 | + | 4 | Georgia | 17 | + +------------+---------+-----+ + +**df2** + + +------------+------+-----+ + | student_id | name | age | + +------------+------+-----+ + | 5 | Leo | 7 | + | 6 | Alex | 7 | + +------------+------+-----+ + +**Output:** + + +------------+---------+-----+ + | student_id | name | age | + +------------+---------+-----+ + | 1 | Mason | 8 | + | 2 | Ava | 6 | + | 3 | Taylor | 15 | + | 4 | Georgia | 17 | + | 5 | Leo | 7 | + | 6 | Alex | 7 | + +------------+---------+-----+ + +**Explanation:** The two DataFramess are stacked vertically, and their rows are combined. + +## Solution + +```python +import pandas as pd + +def concatenateTables(df1: pd.DataFrame, df2: pd.DataFrame) -> pd.DataFrame: + return pd.concat([df1, df2], ignore_index=True) +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2889_reshape_data_pivot/readme.md b/src/main/kotlin/g2801_2900/s2889_reshape_data_pivot/readme.md new file mode 100644 index 00000000..9c13fb09 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2889_reshape_data_pivot/readme.md @@ -0,0 +1,60 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2889\. Reshape Data: Pivot + +Easy + +DataFrame `weather` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | city | object | + | month | object | + | temperature | int | + +-------------+--------+ + +Write a solution to **pivot** the data so that each row represents temperatures for a specific month, and each city is a separate column. + +The result format is in the following example. + +**Example 1:** **Input:** + + +--------------+----------+-------------+ + | city | month | temperature | + +--------------+----------+-------------+ + | Jacksonville | January | 13 | + | Jacksonville | February | 23 | + | Jacksonville | March | 38 | + | Jacksonville | April | 5 | + | Jacksonville | May | 34 | + | ElPaso | January | 20 | + | ElPaso | February | 6 | + | ElPaso | March | 26 | + | ElPaso | April | 2 | + | ElPaso | May | 43 | + +--------------+----------+-------------+ + +**Output:**` + + +----------+--------+--------------+ + | month | ElPaso | Jacksonville | + +----------+--------+--------------+ + | April | 2 | 5 | + | February | 6 | 23 | + | January | 20 | 13 | + | March | 26 | 38 | + | May | 43 | 34 | + +----------+--------+--------------+` + +**Explanation:** The table is pivoted, each column represents a city, and each row represents a specific month. + +## Solution + +```python +import pandas as pd + +def pivotTable(weather: pd.DataFrame) -> pd.DataFrame: + return weather.pivot(index='month', columns='city', values='temperature') +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2890_reshape_data_melt/readme.md b/src/main/kotlin/g2801_2900/s2890_reshape_data_melt/readme.md new file mode 100644 index 00000000..88ad7a5d --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2890_reshape_data_melt/readme.md @@ -0,0 +1,59 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2890\. Reshape Data: Melt + +Easy + +DataFrame `report` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | product | object | + | quarter_1 | int | + | quarter_2 | int | + | quarter_3 | int | + | quarter_4 | int | + +-------------+--------+ + +Write a solution to **reshape** the data so that each row represents sales data for a product in a specific quarter. + +The result format is in the following example. + +**Example 1:** + +**Input:** + + +-------------+-----------+-----------+-----------+-----------+ + | product | quarter_1 | quarter_2 | quarter_3 | quarter_4 | + +-------------+-----------+-----------+-----------+-----------+ + | Umbrella | 417 | 224 | 379 | 611 | + | SleepingBag | 800 | 936 | 93 | 875 | + +-------------+-----------+-----------+-----------+-----------+ + +**Output:** + + +-------------+-----------+-------+ + | product | quarter | sales | + +-------------+-----------+-------+ + | Umbrella | quarter_1 | 417 | + | SleepingBag | quarter_1 | 800 | + | Umbrella | quarter_2 | 224 | + | SleepingBag | quarter_2 | 936 | + | Umbrella | quarter_3 | 379 | + | SleepingBag | quarter_3 | 93 | + | Umbrella | quarter_4 | 611 | + | SleepingBag | quarter_4 | 875 | + +-------------+-----------+-------+ + +**Explanation:** The DataFrame is reshaped from wide to long format. Each row represents the sales of a product in a quarter. + +## Solution + +```python +import pandas as pd + +def meltTable(report: pd.DataFrame) -> pd.DataFrame: + return report.melt(id_vars='product', var_name='quarter', value_name='sales') +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2891_method_chaining/readme.md b/src/main/kotlin/g2801_2900/s2891_method_chaining/readme.md new file mode 100644 index 00000000..4a562df5 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2891_method_chaining/readme.md @@ -0,0 +1,72 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2891\. Method Chaining + +Easy + +DataFrame `animals` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | name | object | + | species | object | + | age | int | + | weight | int | + +-------------+--------+ + +Write a solution to list the names of animals that weigh **strictly more than** `100` kilograms. + +Return the animals sorted by weight in **descending order**. + +The result format is in the following example. + +**Example 1:** + +**Input:** DataFrame animals: + + +----------+---------+-----+--------+ + | name | species | age | weight | + +----------+---------+-----+--------+ + | Tatiana | Snake | 98 | 464 | + | Khaled | Giraffe | 50 | 41 | + | Alex | Leopard | 6 | 328 | + | Jonathan | Monkey | 45 | 463 | + | Stefan | Bear | 100 | 50 | + | Tommy | Panda | 26 | 349 | + +----------+---------+-----+--------+ + +**Output:** + + +----------+ + | name | + +----------+ + | Tatiana | + | Jonathan | + | Tommy | + | Alex | + +----------+ + +**Explanation:** All animals weighing more than 100 should be included in the results table. Tatiana's weight is 464, Jonathan's weight is 463, Tommy's weight is 349, and Alex's weight is 328. The results should be sorted in descending order of weight. + +In Pandas, **method chaining** enables us to perform operations on a DataFrame without breaking up each operation into a separate line or creating multiple temporary variables. + +Can you complete this task in just **one line** of code using method chaining? + +## Solution + +```python +import pandas as pd + +def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame: + animal_data = {} + for index in animals.index: + animal = animals.iloc[index] + if animal['weight'] > 100: + animal_data[animal['name']] = animal['weight'] + + animal_data = dict(sorted(animal_data.items() , key = lambda x : x[1] , reverse = True)) + result = pd.DataFrame(animal_data.keys() , columns = ['name']) + return result +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2894_divisible_and_non_divisible_sums_difference/readme.md b/src/main/kotlin/g2801_2900/s2894_divisible_and_non_divisible_sums_difference/readme.md new file mode 100644 index 00000000..e35d400c --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2894_divisible_and_non_divisible_sums_difference/readme.md @@ -0,0 +1,68 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2894\. Divisible and Non-divisible Sums Difference + +Easy + +You are given positive integers `n` and `m`. + +Define two integers, `num1` and `num2`, as follows: + +* `num1`: The sum of all integers in the range `[1, n]` that are **not divisible** by `m`. +* `num2`: The sum of all integers in the range `[1, n]` that are **divisible** by `m`. + +Return _the integer_ `num1 - num2`. + +**Example 1:** + +**Input:** n = 10, m = 3 + +**Output:** 19 + +**Explanation:** In the given example: +- Integers in the range [1, 10] that are not divisible by 3 are [1,2,4,5,7,8,10], num1 is the sum of those integers = 37. +- Integers in the range [1, 10] that are divisible by 3 are [3,6,9], num2 is the sum of those integers = 18. We return 37 - 18 = 19 as the answer. + +**Example 2:** + +**Input:** n = 5, m = 6 + +**Output:** 15 + +**Explanation:** In the given example: +- Integers in the range [1, 5] that are not divisible by 6 are [1,2,3,4,5], num1 is the sum of those integers = 15. +- Integers in the range [1, 5] that are divisible by 6 are [], num2 is the sum of those integers = 0. We return 15 - 0 = 15 as the answer. + +**Example 3:** + +**Input:** n = 5, m = 1 + +**Output:** -15 + +**Explanation:** In the given example: +- Integers in the range [1, 5] that are not divisible by 1 are [], num1 is the sum of those integers = 0. +- Integers in the range [1, 5] that are divisible by 1 are [1,2,3,4,5], num2 is the sum of those integers = 15. We return 0 - 15 = -15 as the answer. + +**Constraints:** + +* `1 <= n, m <= 1000` + +## Solution + +```kotlin +class Solution { + fun differenceOfSums(n: Int, m: Int): Int { + var sum1 = 0 + var sum2 = 0 + for (i in 1..n) { + if (i % m == 0) { + sum1 += i + } else { + sum2 += i + } + } + return sum2 - sum1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2895_minimum_processing_time/readme.md b/src/main/kotlin/g2801_2900/s2895_minimum_processing_time/readme.md new file mode 100644 index 00000000..156b82dd --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2895_minimum_processing_time/readme.md @@ -0,0 +1,86 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2895\. Minimum Processing Time + +Medium + +You have `n` processors each having `4` cores and `n * 4` tasks that need to be executed such that each core should perform only **one** task. + +Given a **0-indexed** integer array `processorTime` representing the time at which each processor becomes available for the first time and a **0-indexed** integer array `tasks` representing the time it takes to execute each task, return _the **minimum** time when all of the tasks have been executed by the processors._ + +**Note:** Each core executes the task independently of the others. + +**Example 1:** + +**Input:** processorTime = [8,10], tasks = [2,2,3,1,8,7,4,5] + +**Output:** 16 + +**Explanation:** + +It's optimal to assign the tasks at indexes 4, 5, 6, 7 to the first processor which becomes available at time = 8, and the tasks at indexes 0, 1, 2, 3 to the second processor which becomes available at time = 10. + +Time taken by the first processor to finish execution of all tasks = max(8 + 8, 8 + 7, 8 + 4, 8 + 5) = 16. + +Time taken by the second processor to finish execution of all tasks = max(10 + 2, 10 + 2, 10 + 3, 10 + 1) = 13. + +Hence, it can be shown that the minimum time taken to execute all the tasks is 16. + +**Example 2:** + +**Input:** processorTime = [10,20], tasks = [2,3,1,2,5,8,4,3] + +**Output:** 23 + +**Explanation:** + +It's optimal to assign the tasks at indexes 1, 4, 5, 6 to the first processor which becomes available at time = 10, and the tasks at indexes 0, 2, 3, 7 to the second processor which becomes available at time = 20. Time taken by the first processor to finish execution of all tasks = max(10 + 3, 10 + 5, 10 + 8, 10 + 4) = 18. Time taken by the second processor to finish execution of all tasks = max(20 + 2, 20 + 1, 20 + 2, 20 + 3) = 23. Hence, it can be shown that the minimum time taken to execute all the tasks is 23. + +**Constraints:** + +* `1 <= n == processorTime.length <= 25000` +* 1 <= tasks.length <= 105 +* 0 <= processorTime[i] <= 109 +* 1 <= tasks[i] <= 109 +* `tasks.length == 4 * n` + +## Solution + +```kotlin +class Solution { + fun minProcessingTime(processorTime: List, tasks: List): Int { + val proc = IntArray(processorTime.size) + run { + var i = 0 + val n = processorTime.size + while (i < n) { + proc[i] = processorTime[i] + i++ + } + } + val jobs = IntArray(tasks.size) + run { + var i = 0 + val n = tasks.size + while (i < n) { + jobs[i] = tasks[i] + i++ + } + } + proc.sort() + jobs.sort() + var maxTime = 0 + var i = 0 + val n = proc.size + while (i < n) { + val procTime = proc[i] + jobs[jobs.size - 1 - i * 4] + if (procTime > maxTime) { + maxTime = procTime + } + i++ + } + return maxTime + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2896_apply_operations_to_make_two_strings_equal/readme.md b/src/main/kotlin/g2801_2900/s2896_apply_operations_to_make_two_strings_equal/readme.md new file mode 100644 index 00000000..1e5b14dd --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2896_apply_operations_to_make_two_strings_equal/readme.md @@ -0,0 +1,84 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2896\. Apply Operations to Make Two Strings Equal + +Medium + +You are given two **0-indexed** binary strings `s1` and `s2`, both of length `n`, and a positive integer `x`. + +You can perform any of the following operations on the string `s1` **any** number of times: + +* Choose two indices `i` and `j`, and flip both `s1[i]` and `s1[j]`. The cost of this operation is `x`. +* Choose an index `i` such that `i < n - 1` and flip both `s1[i]` and `s1[i + 1]`. The cost of this operation is `1`. + +Return _the **minimum** cost needed to make the strings_ `s1` _and_ `s2` _equal, or return_ `-1` _if it is impossible._ + +**Note** that flipping a character means changing it from `0` to `1` or vice-versa. + +**Example 1:** + +**Input:** s1 = "1100011000", s2 = "0101001010", x = 2 + +**Output:** 4 + +**Explanation:** We can do the following operations: + +- Choose i = 3 and apply the second operation. The resulting string is s1 = "110**11**11000". + +- Choose i = 4 and apply the second operation. The resulting string is s1 = "1101**00**1000". + +- Choose i = 0 and j = 8 and apply the first operation. The resulting string is s1 = "**0**1010010**1**0" = s2. + +The total cost is 1 + 1 + 2 = 4. It can be shown that it is the minimum cost possible. + +**Example 2:** + +**Input:** s1 = "10110", s2 = "00011", x = 4 + +**Output:** -1 + +**Explanation:** It is not possible to make the two strings equal. + +**Constraints:** + +* `n == s1.length == s2.length` +* `1 <= n, x <= 500` +* `s1` and `s2` consist only of the characters `'0'` and `'1'`. + +## Solution + +```kotlin +import kotlin.math.min + +class Solution { + fun minOperations(s1: String, s2: String, x: Int): Int { + val n = s1.length + val diffs = ArrayList() + for (i in 0 until n) { + if (s1[i] != s2[i]) { + diffs.add(i) + } + } + val m = diffs.size + if ((m and 1) == 1) { + return -1 + } else if (m == 0) { + return 0 + } + val dp = IntArray(m) + dp[0] = 0 + dp[1] = min(x.toDouble(), (diffs[1] - diffs[0]).toDouble()).toInt() + for (i in 2 until m) { + if ((i and 1) == 1) { + dp[i] = min((dp[i - 1] + x).toDouble(), (dp[i - 2] + diffs[i] - diffs[i - 1]).toDouble()) + .toInt() + } else { + dp[i] = min(dp[i - 1].toDouble(), (dp[i - 2] + diffs[i] - diffs[i - 1]).toDouble()) + .toInt() + } + } + return dp[m - 1] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2897_apply_operations_on_array_to_maximize_sum_of_squares/readme.md b/src/main/kotlin/g2801_2900/s2897_apply_operations_on_array_to_maximize_sum_of_squares/readme.md new file mode 100644 index 00000000..b7c4e033 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2897_apply_operations_on_array_to_maximize_sum_of_squares/readme.md @@ -0,0 +1,78 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2897\. Apply Operations on Array to Maximize Sum of Squares + +Hard + +You are given a **0-indexed** integer array `nums` and a **positive** integer `k`. + +You can do the following operation on the array **any** number of times: + +* Choose any two distinct indices `i` and `j` and **simultaneously** update the values of `nums[i]` to `(nums[i] AND nums[j])` and `nums[j]` to `(nums[i] OR nums[j])`. Here, `OR` denotes the bitwise `OR` operation, and `AND` denotes the bitwise `AND` operation. + +You have to choose `k` elements from the final array and calculate the sum of their **squares**. + +Return _the **maximum** sum of squares you can achieve_. + +Since the answer can be very large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** nums = [2,6,5,8], k = 2 + +**Output:** 261 + +**Explanation:** We can do the following operations on the array: + +- Choose i = 0 and j = 3, then change nums[0] to (2 AND 8) = 0 and nums[3] to (2 OR 8) = 10. The resulting array is nums = [0,6,5,10]. + +- Choose i = 2 and j = 3, then change nums[2] to (5 AND 10) = 0 and nums[3] to (5 OR 10) = 15. The resulting array is nums = [0,6,0,15]. + +We can choose the elements 15 and 6 from the final array. The sum of squares is 152 + 62 = 261. + +It can be shown that this is the maximum value we can get. + +**Example 2:** + +**Input:** nums = [4,5,4,7], k = 3 + +**Output:** 90 + +**Explanation:** We do not need to apply any operations. + +We can choose the elements 7, 5, and 4 with a sum of squares: 72 + 52 + 42 = 90. + +It can be shown that this is the maximum value we can get. + +**Constraints:** + +* 1 <= k <= nums.length <= 105 +* 1 <= nums[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun maxSum(nums: List, k: Int): Int { + val bits = IntArray(32) + for (n in nums) { + for (i in 0..31) { + bits[i] += (n shr i) and 1 + } + } + val mod = 1000000007 + var sum: Long = 0 + for (i in 0 until k) { + var n: Long = 0 + for (j in 0..31) { + if (bits[j] > i) { + n = n or (1 shl j).toLong() + } + } + sum = (sum + n * n % mod) % mod + } + return sum.toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2899_last_visited_integers/readme.md b/src/main/kotlin/g2801_2900/s2899_last_visited_integers/readme.md new file mode 100644 index 00000000..6b997d5f --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2899_last_visited_integers/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2899\. Last Visited Integers + +Easy + +Given a **0-indexed** array of strings `words` where `words[i]` is either a positive integer represented as a string or the string `"prev"`. + +Start iterating from the beginning of the array; for every `"prev"` string seen in `words`, find the **last visited integer** in `words` which is defined as follows: + +* Let `k` be the number of consecutive `"prev"` strings seen so far (containing the current string). Let `nums` be the **0-indexed** array of **integers** seen so far and `nums_reverse` be the reverse of `nums`, then the integer at (k - 1)th index of `nums_reverse` will be the **last visited integer** for this `"prev"`. +* If `k` is **greater** than the total visited integers, then the last visited integer will be `-1`. + +Return _an integer array containing the last visited integers._ + +**Example 1:** + +**Input:** words = ["1","2","prev","prev","prev"] + +**Output:** [2,1,-1] + +**Explanation:** + +For "prev" at index = 2, last visited integer will be 2 as here the number of consecutive "prev" strings is 1, and in the array reverse\_nums, 2 will be the first element. + +For "prev" at index = 3, last visited integer will be 1 as there are a total of two consecutive "prev" strings including this "prev" which are visited, and 1 is the second last visited integer. + +For "prev" at index = 4, last visited integer will be -1 as there are a total of three consecutive "prev" strings including this "prev" which are visited, but the total number of integers visited is two. + +**Example 2:** + +**Input:** words = ["1","prev","2","prev","prev"] + +**Output:** [1,2,1] + +**Explanation:** + +For "prev" at index = 1, last visited integer will be 1. + +For "prev" at index = 3, last visited integer will be 2. + +For "prev" at index = 4, last visited integer will be 1 as there are a total of two consecutive "prev" strings including this "prev" which are visited, and 1 is the second last visited integer. + +**Constraints:** + +* `1 <= words.length <= 100` +* `words[i] == "prev"` or `1 <= int(words[i]) <= 100` + +## Solution + +```kotlin +class Solution { + fun lastVisitedIntegers(words: List): List { + val prevEle: MutableList = ArrayList() + val res: MutableList = ArrayList() + var count = 0 + for (i in words.indices) { + if (words[i] != "prev") { + count = 0 + prevEle.add(words[i]) + continue + } + if (count >= prevEle.size) { + res.add(-1) + } else { + res.add(prevEle[prevEle.size - count - 1].toInt()) + } + count++ + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2801_2900/s2900_longest_unequal_adjacent_groups_subsequence_i/readme.md b/src/main/kotlin/g2801_2900/s2900_longest_unequal_adjacent_groups_subsequence_i/readme.md new file mode 100644 index 00000000..d6b23747 --- /dev/null +++ b/src/main/kotlin/g2801_2900/s2900_longest_unequal_adjacent_groups_subsequence_i/readme.md @@ -0,0 +1,79 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2900\. Longest Unequal Adjacent Groups Subsequence I + +Medium + +You are given an integer `n`, a **0-indexed** string array `words`, and a **0-indexed** **binary** array `groups`, both arrays having length `n`. + +You need to select the **longest** **subsequence** from an array of indices `[0, 1, ..., n - 1]`, such that for the subsequence denoted as [i0, i1, ..., ik - 1] having length `k`, groups[ij] != groups[ij + 1], for each `j` where `0 < j + 1 < k`. + +Return _a string array containing the words corresponding to the indices **(in order)** in the selected subsequence_. If there are multiple answers, return _any of them_. + +A **subsequence** of an array is a new array that is formed from the original array by deleting some (possibly none) of the elements without disturbing the relative positions of the remaining elements. + +**Note:** strings in `words` may be **unequal** in length. + +**Example 1:** + +**Input:** n = 3, words = ["e","a","b"], groups = [0,0,1] + +**Output:** ["e","b"] + +**Explanation:** A subsequence that can be selected is [0,2] because groups[0] != groups[2]. + +So, a valid answer is [words[0],words[2]] = ["e","b"]. + +Another subsequence that can be selected is [1,2] because groups[1] != groups[2]. + +This results in [words[1],words[2]] = ["a","b"]. + +It is also a valid answer. + +It can be shown that the length of the longest subsequence of indices that satisfies the condition is 2. + +**Example 2:** + +**Input:** n = 4, words = ["a","b","c","d"], groups = [1,0,1,1] + +**Output:** ["a","b","c"] + +**Explanation:** A subsequence that can be selected is [0,1,2] because groups[0] != groups[1] and groups[1] != groups[2]. + +So, a valid answer is [words[0],words[1],words[2]] = ["a","b","c"]. + +Another subsequence that can be selected is [0,1,3] because groups[0] != groups[1] and groups[1] != groups[3]. + +This results in [words[0],words[1],words[3]] = ["a","b","d"]. + +It is also a valid answer. + +It can be shown that the length of the longest subsequence of indices that satisfies the condition is 3. + +**Constraints:** + +* `1 <= n == words.length == groups.length <= 100` +* `1 <= words[i].length <= 10` +* `0 <= groups[i] < 2` +* `words` consists of **distinct** strings. +* `words[i]` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun getWordsInLongestSubsequence(n: Int, words: Array, groups: IntArray): List { + val ans: MutableList = ArrayList() + ans.add(words[0]) + var prev = groups[0] + for (i in 1 until n) { + if (prev != groups[i]) { + ans.add(words[i]) + prev = groups[i] + } + } + return ans + } +} +``` \ No newline at end of file