diff --git a/README.md b/README.md index 35b584b9..5038e292 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,7 @@ | | | | | | |-|-|-|-|-|- +| 1046 |[Last Stone Weight](src/main/kotlin/g1001_1100/s1046_last_stone_weight)| Easy | Array, Heap_Priority_Queue | 123 | 100.00 | 0692 |[Top K Frequent Words](src/main/kotlin/g0601_0700/s0692_top_k_frequent_words)| Medium | String, Hash_Table, Sorting, Heap_Priority_Queue, Counting, Trie, Bucket_Sort | 239 | 81.10 ### Level 2 @@ -191,7 +192,7 @@ | | | | | | |-|-|-|-|-|- -| 0994 |[Rotting Oranges](src/main/kotlin/g0901_1000/s0994_rotting_oranges)| Medium | Array, Breadth_First_Search, Matrix | 308 | 57.93 +| 0994 |[Rotting Oranges](src/main/kotlin/g0901_1000/s0994_rotting_oranges)| Medium | Array, Breadth_First_Search, Matrix | 164 | 82.95 | 0417 |[Pacific Atlantic Water Flow](src/main/kotlin/g0401_0500/s0417_pacific_atlantic_water_flow)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix | 319 | 100.00 #### Day 11 Graph/BFS/DFS @@ -801,7 +802,7 @@ | | | | | | |-|-|-|-|-|- | 0542 |[01 Matrix](src/main/kotlin/g0501_0600/s0542_01_matrix)| Medium | Array, Dynamic_Programming, Breadth_First_Search, Matrix | 441 | 94.06 -| 0994 |[Rotting Oranges](src/main/kotlin/g0901_1000/s0994_rotting_oranges)| Medium | Array, Breadth_First_Search, Matrix | 308 | 57.93 +| 0994 |[Rotting Oranges](src/main/kotlin/g0901_1000/s0994_rotting_oranges)| Medium | Array, Breadth_First_Search, Matrix | 164 | 82.95 #### Day 10 Recursion Backtracking @@ -1238,6 +1239,7 @@ | | | | | | |-|-|-|-|-|- +| 1014 |[Best Sightseeing Pair](src/main/kotlin/g1001_1100/s1014_best_sightseeing_pair)| Medium | Array, Dynamic_Programming | 336 | 66.67 | 0121 |[Best Time to Buy and Sell Stock](src/main/kotlin/g0101_0200/s0121_best_time_to_buy_and_sell_stock)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 609 | 94.06 | 0122 |[Best Time to Buy and Sell Stock II](src/main/kotlin/g0101_0200/s0122_best_time_to_buy_and_sell_stock_ii)| Medium | Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 197 | 95.10 @@ -1575,11 +1577,13 @@ | | | | | | |-|-|-|-|-|- +| 1020 |[Number of Enclaves](src/main/kotlin/g1001_1100/s1020_number_of_enclaves)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 369 | 76.26 #### Day 4 Matrix Related Problems | | | | | | |-|-|-|-|-|- +| 1162 |[As Far from Land as Possible](src/main/kotlin/g1101_1200/s1162_as_far_from_land_as_possible)| Medium | Array, Dynamic_Programming, Breadth_First_Search, Matrix | 362 | 81.25 | 0417 |[Pacific Atlantic Water Flow](src/main/kotlin/g0401_0500/s0417_pacific_atlantic_water_flow)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix | 319 | 100.00 #### Day 5 Matrix Related Problems @@ -1704,18 +1708,91 @@ | | | | | | |-|-|-|-|-|- +| 1158 |[Market Analysis I](src/main/kotlin/g1101_1200/s1158_market_analysis_i)| Medium | Database | 2470 | 44.76 #### Day 10 Where | | | | | | |-|-|-|-|-|- | 0182 |[Duplicate Emails](src/main/kotlin/g0101_0200/s0182_duplicate_emails)| Easy | Database | 396 | 68.40 +| 1050 |[Actors and Directors Who Cooperated At Least Three Times](src/main/kotlin/g1001_1100/s1050_actors_and_directors_who_cooperated_at_least_three_times)| Easy | LeetCode_Curated_SQL_70, Database | 629 | 81.02 ## Algorithms | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- +| 1200 |[Minimum Absolute Difference](src/main/kotlin/g1101_1200/s1200_minimum_absolute_difference)| Easy | Array, Sorting | 507 | 75.00 +| 1195 |[Fizz Buzz Multithreaded](src/main/kotlin/g1101_1200/s1195_fizz_buzz_multithreaded)| Medium || | +| 1192 |[Critical Connections in a Network](src/main/kotlin/g1101_1200/s1192_critical_connections_in_a_network)| Hard | Depth_First_Search, Graph, Biconnected_Component | 1696 | 60.00 +| 1191 |[K-Concatenation Maximum Sum](src/main/kotlin/g1101_1200/s1191_k_concatenation_maximum_sum)| Medium | Array, Dynamic_Programming | 389 | 100.00 +| 1190 |[Reverse Substrings Between Each Pair of Parentheses](src/main/kotlin/g1101_1200/s1190_reverse_substrings_between_each_pair_of_parentheses)| Medium | String, Stack | 153 | 42.86 +| 1189 |[Maximum Number of Balloons](src/main/kotlin/g1101_1200/s1189_maximum_number_of_balloons)| Easy | String, Hash_Table, Counting | 136 | 98.31 +| 1187 |[Make Array Strictly Increasing](src/main/kotlin/g1101_1200/s1187_make_array_strictly_increasing)| Hard | Array, Dynamic_Programming, Binary_Search | 308 | 100.00 +| 1186 |[Maximum Subarray Sum with One Deletion](src/main/kotlin/g1101_1200/s1186_maximum_subarray_sum_with_one_deletion)| Medium | Array, Dynamic_Programming | 304 | 50.00 +| 1185 |[Day of the Week](src/main/kotlin/g1101_1200/s1185_day_of_the_week)| Easy | Math | 127 | 50.00 +| 1184 |[Distance Between Bus Stops](src/main/kotlin/g1101_1200/s1184_distance_between_bus_stops)| Easy | Array | 164 | 57.14 +| 1179 |[Reformat Department Table](src/main/kotlin/g1101_1200/s1179_reformat_department_table)| Easy | Database | 815 | 90.95 +| 1178 |[Number of Valid Words for Each Puzzle](src/main/kotlin/g1101_1200/s1178_number_of_valid_words_for_each_puzzle)| Hard | Array, String, Hash_Table, Bit_Manipulation, Trie | 675 | 100.00 +| 1177 |[Can Make Palindrome from Substring](src/main/kotlin/g1101_1200/s1177_can_make_palindrome_from_substring)| Medium | String, Hash_Table, Bit_Manipulation, Prefix_Sum | 937 | 100.00 +| 1175 |[Prime Arrangements](src/main/kotlin/g1101_1200/s1175_prime_arrangements)| Easy | Math | 129 | 50.00 +| 1172 |[Dinner Plate Stacks](src/main/kotlin/g1101_1200/s1172_dinner_plate_stacks)| Hard | Hash_Table, Stack, Design, Heap_Priority_Queue | 1160 | 50.00 +| 1171 |[Remove Zero Sum Consecutive Nodes from Linked List](src/main/kotlin/g1101_1200/s1171_remove_zero_sum_consecutive_nodes_from_linked_list)| Medium | Hash_Table, Linked_List | 194 | 50.00 +| 1170 |[Compare Strings by Frequency of the Smallest Character](src/main/kotlin/g1101_1200/s1170_compare_strings_by_frequency_of_the_smallest_character)| Medium | Array, String, Hash_Table, Sorting, Binary_Search | 221 | 50.00 +| 1169 |[Invalid Transactions](src/main/kotlin/g1101_1200/s1169_invalid_transactions)| Medium | Array, String, Hash_Table, Sorting | 362 | 57.14 +| 1163 |[Last Substring in Lexicographical Order](src/main/kotlin/g1101_1200/s1163_last_substring_in_lexicographical_order)| Hard | String, Two_Pointers | 254 | 100.00 +| 1162 |[As Far from Land as Possible](src/main/kotlin/g1101_1200/s1162_as_far_from_land_as_possible)| Medium | Array, Dynamic_Programming, Breadth_First_Search, Matrix, Graph_Theory_I_Day_4_Matrix_Related_Problems | 362 | 81.25 +| 1161 |[Maximum Level Sum of a Binary Tree](src/main/kotlin/g1101_1200/s1161_maximum_level_sum_of_a_binary_tree)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 445 | 87.50 +| 1160 |[Find Words That Can Be Formed by Characters](src/main/kotlin/g1101_1200/s1160_find_words_that_can_be_formed_by_characters)| Easy | Array, String, Hash_Table | 288 | 72.22 +| 1158 |[Market Analysis I](src/main/kotlin/g1101_1200/s1158_market_analysis_i)| Medium | Database, SQL_I_Day_9_Control_of_Flow | 2470 | 44.76 +| 1157 |[Online Majority Element In Subarray](src/main/kotlin/g1101_1200/s1157_online_majority_element_in_subarray)| Hard | Array, Binary_Search, Design, Segment_Tree, Binary_Indexed_Tree | 953 | 100.00 +| 1156 |[Swap For Longest Repeated Character Substring](src/main/kotlin/g1101_1200/s1156_swap_for_longest_repeated_character_substring)| Medium | String, Sliding_Window | 195 | 20.00 +| 1155 |[Number of Dice Rolls With Target Sum](src/main/kotlin/g1101_1200/s1155_number_of_dice_rolls_with_target_sum)| Medium | Dynamic_Programming | 158 | 80.95 +| 1154 |[Day of the Year](src/main/kotlin/g1101_1200/s1154_day_of_the_year)| Easy | String, Math | 317 | 70.00 | 1143 |[Longest Common Subsequence](src/main/kotlin/g1101_1200/s1143_longest_common_subsequence)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming, Algorithm_II_Day_17_Dynamic_Programming, Dynamic_Programming_I_Day_19, Udemy_Dynamic_Programming | 307 | 38.36 +| 1068 |[Product Sales Analysis I](src/main/kotlin/g1001_1100/s1068_product_sales_analysis_i)| Easy | Database | 1897 | 79.88 +| 1061 |[Lexicographically Smallest Equivalent String](src/main/kotlin/g1001_1100/s1061_lexicographically_smallest_equivalent_string)| Medium | String, Union_Find | 166 | 100.00 +| 1054 |[Distant Barcodes](src/main/kotlin/g1001_1100/s1054_distant_barcodes)| Medium | Array, Hash_Table, Sorting, Greedy, Heap_Priority_Queue, Counting | 622 | 75.00 +| 1053 |[Previous Permutation With One Swap](src/main/kotlin/g1001_1100/s1053_previous_permutation_with_one_swap)| Medium | Array, Greedy | 338 | 25.00 +| 1052 |[Grumpy Bookstore Owner](src/main/kotlin/g1001_1100/s1052_grumpy_bookstore_owner)| Medium | Array, Sliding_Window | 268 | 80.00 +| 1051 |[Height Checker](src/main/kotlin/g1001_1100/s1051_height_checker)| Easy | Array, Sorting, Counting_Sort | 140 | 94.37 +| 1050 |[Actors and Directors Who Cooperated At Least Three Times](src/main/kotlin/g1001_1100/s1050_actors_and_directors_who_cooperated_at_least_three_times)| Easy | LeetCode_Curated_SQL_70, Database, SQL_I_Day_10_Where | 629 | 81.02 +| 1049 |[Last Stone Weight II](src/main/kotlin/g1001_1100/s1049_last_stone_weight_ii)| Medium | Array, Dynamic_Programming | 150 | 100.00 +| 1048 |[Longest String Chain](src/main/kotlin/g1001_1100/s1048_longest_string_chain)| Medium | Array, String, Hash_Table, Dynamic_Programming, Two_Pointers | 273 | 75.00 +| 1047 |[Remove All Adjacent Duplicates In String](src/main/kotlin/g1001_1100/s1047_remove_all_adjacent_duplicates_in_string)| Easy | String, Stack | 228 | 94.52 +| 1046 |[Last Stone Weight](src/main/kotlin/g1001_1100/s1046_last_stone_weight)| Easy | Array, Heap_Priority_Queue, Level_1_Day_15_Heap | 123 | 100.00 +| 1045 |[Customers Who Bought All Products](src/main/kotlin/g1001_1100/s1045_customers_who_bought_all_products)| Medium | Database | 881 | 90.47 +| 1044 |[Longest Duplicate Substring](src/main/kotlin/g1001_1100/s1044_longest_duplicate_substring)| Hard | String, Binary_Search, Sliding_Window, Hash_Function, Rolling_Hash, Suffix_Array | 592 | 100.00 +| 1043 |[Partition Array for Maximum Sum](src/main/kotlin/g1001_1100/s1043_partition_array_for_maximum_sum)| Medium | Array, Dynamic_Programming | 194 | 71.43 +| 1042 |[Flower Planting With No Adjacent](src/main/kotlin/g1001_1100/s1042_flower_planting_with_no_adjacent)| Medium | Depth_First_Search, Breadth_First_Search, Graph | 396 | 85.71 +| 1041 |[Robot Bounded In Circle](src/main/kotlin/g1001_1100/s1041_robot_bounded_in_circle)| Medium | String, Math, Simulation | 121 | 100.00 +| 1040 |[Moving Stones Until Consecutive II](src/main/kotlin/g1001_1100/s1040_moving_stones_until_consecutive_ii)| Medium | Array, Math, Sorting, Two_Pointers | 287 | 50.00 +| 1039 |[Minimum Score Triangulation of Polygon](src/main/kotlin/g1001_1100/s1039_minimum_score_triangulation_of_polygon)| Medium | Array, Dynamic_Programming | 147 | 100.00 +| 1038 |[Binary Search Tree to Greater Sum Tree](src/main/kotlin/g1001_1100/s1038_binary_search_tree_to_greater_sum_tree)| Medium | Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 123 | 91.67 +| 1037 |[Valid Boomerang](src/main/kotlin/g1001_1100/s1037_valid_boomerang)| Easy | Array, Math, Geometry | 126 | 100.00 +| 1036 |[Escape a Large Maze](src/main/kotlin/g1001_1100/s1036_escape_a_large_maze)| Hard | Array, Hash_Table, Depth_First_Search, Breadth_First_Search | 387 | 100.00 +| 1035 |[Uncrossed Lines](src/main/kotlin/g1001_1100/s1035_uncrossed_lines)| Medium | Array, Dynamic_Programming | 162 | 93.33 +| 1034 |[Coloring A Border](src/main/kotlin/g1001_1100/s1034_coloring_a_border)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix | 332 | 100.00 +| 1033 |[Moving Stones Until Consecutive](src/main/kotlin/g1001_1100/s1033_moving_stones_until_consecutive)| Medium | Math, Brainteaser | 139 | 100.00 +| 1032 |[Stream of Characters](src/main/kotlin/g1001_1100/s1032_stream_of_characters)| Hard | Array, String, Design, Trie, Data_Stream | 733 | 100.00 +| 1031 |[Maximum Sum of Two Non-Overlapping Subarrays](src/main/kotlin/g1001_1100/s1031_maximum_sum_of_two_non_overlapping_subarrays)| Medium | Array, Dynamic_Programming, Sliding_Window | 172 | 100.00 +| 1030 |[Matrix Cells in Distance Order](src/main/kotlin/g1001_1100/s1030_matrix_cells_in_distance_order)| Easy | Array, Math, Sorting, Matrix, Geometry | 426 | 100.00 +| 1029 |[Two City Scheduling](src/main/kotlin/g1001_1100/s1029_two_city_scheduling)| Medium | Array, Sorting, Greedy | 148 | 100.00 +| 1028 |[Recover a Tree From Preorder Traversal](src/main/kotlin/g1001_1100/s1028_recover_a_tree_from_preorder_traversal)| Hard | String, Depth_First_Search, Tree, Binary_Tree | 246 | 100.00 +| 1027 |[Longest Arithmetic Subsequence](src/main/kotlin/g1001_1100/s1027_longest_arithmetic_subsequence)| Medium | Array, Hash_Table, Dynamic_Programming, Binary_Search | 330 | 100.00 +| 1026 |[Maximum Difference Between Node and Ancestor](src/main/kotlin/g1001_1100/s1026_maximum_difference_between_node_and_ancestor)| Medium | Depth_First_Search, Tree, Binary_Tree | 155 | 77.78 +| 1025 |[Divisor Game](src/main/kotlin/g1001_1100/s1025_divisor_game)| Easy | Dynamic_Programming, Math, Game_Theory, Brainteaser | 114 | 93.33 +| 1024 |[Video Stitching](src/main/kotlin/g1001_1100/s1024_video_stitching)| Medium | Array, Dynamic_Programming, Greedy | 141 | 100.00 +| 1023 |[Camelcase Matching](src/main/kotlin/g1001_1100/s1023_camelcase_matching)| Medium | String, Two_Pointers, Trie, String_Matching | 149 | 60.00 +| 1022 |[Sum of Root To Leaf Binary Numbers](src/main/kotlin/g1001_1100/s1022_sum_of_root_to_leaf_binary_numbers)| Easy | Depth_First_Search, Tree, Binary_Tree | 158 | 88.89 +| 1021 |[Remove Outermost Parentheses](src/main/kotlin/g1001_1100/s1021_remove_outermost_parentheses)| Easy | String, Stack | 156 | 60.00 +| 1020 |[Number of Enclaves](src/main/kotlin/g1001_1100/s1020_number_of_enclaves)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find, Graph_Theory_I_Day_3_Matrix_Related_Problems | 369 | 76.26 +| 1019 |[Next Greater Node In Linked List](src/main/kotlin/g1001_1100/s1019_next_greater_node_in_linked_list)| Medium | Array, Stack, Linked_List, Monotonic_Stack | 472 | 75.00 +| 1018 |[Binary Prefix Divisible By 5](src/main/kotlin/g1001_1100/s1018_binary_prefix_divisible_by_5)| Easy | Array | 297 | 100.00 +| 1017 |[Convert to Base -2](src/main/kotlin/g1001_1100/s1017_convert_to_base_2)| Medium | Math | 138 | 100.00 +| 1016 |[Binary String With Substrings Representing 1 To N](src/main/kotlin/g1001_1100/s1016_binary_string_with_substrings_representing_1_to_n)| Medium | String | 134 | 75.00 +| 1015 |[Smallest Integer Divisible by K](src/main/kotlin/g1001_1100/s1015_smallest_integer_divisible_by_k)| Medium | Hash_Table, Math | 123 | 100.00 +| 1014 |[Best Sightseeing Pair](src/main/kotlin/g1001_1100/s1014_best_sightseeing_pair)| Medium | Array, Dynamic_Programming, Dynamic_Programming_I_Day_7 | 336 | 66.67 +| 1013 |[Partition Array Into Three Parts With Equal Sum](src/main/kotlin/g1001_1100/s1013_partition_array_into_three_parts_with_equal_sum)| Easy | Array, Greedy | 328 | 100.00 | 1012 |[Numbers With Repeated Digits](src/main/kotlin/g1001_1100/s1012_numbers_with_repeated_digits)| Hard | Dynamic_Programming, Math | 123 | 100.00 | 1011 |[Capacity To Ship Packages Within D Days](src/main/kotlin/g1001_1100/s1011_capacity_to_ship_packages_within_d_days)| Medium | Array, Binary_Search | 325 | 66.67 | 1010 |[Pairs of Songs With Total Durations Divisible by 60](src/main/kotlin/g1001_1100/s1010_pairs_of_songs_with_total_durations_divisible_by_60)| Medium | Array, Hash_Table, Counting | 287 | 77.78 @@ -1734,7 +1811,7 @@ | 0997 |[Find the Town Judge](src/main/kotlin/g0901_1000/s0997_find_the_town_judge)| Easy | Array, Hash_Table, Graph, Data_Structure_II_Day_19_Graph, Graph_Theory_I_Day_13_Graph_Theory | 475 | 58.62 | 0996 |[Number of Squareful Arrays](src/main/kotlin/g0901_1000/s0996_number_of_squareful_arrays)| Hard | Array, Dynamic_Programming, Math, Bit_Manipulation, Backtracking, Bitmask | 139 | 100.00 | 0995 |[Minimum Number of K Consecutive Bit Flips](src/main/kotlin/g0901_1000/s0995_minimum_number_of_k_consecutive_bit_flips)| Hard | Array, Bit_Manipulation, Prefix_Sum, Sliding_Window | 480 | 100.00 -| 0994 |[Rotting Oranges](src/main/kotlin/g0901_1000/s0994_rotting_oranges)| Medium | Array, Breadth_First_Search, Matrix, Algorithm_I_Day_9_Breadth_First_Search_Depth_First_Search, Level_2_Day_10_Graph/BFS/DFS | 308 | 57.93 +| 0994 |[Rotting Oranges](src/main/kotlin/g0901_1000/s0994_rotting_oranges)| Medium | Array, Breadth_First_Search, Matrix, Algorithm_I_Day_9_Breadth_First_Search_Depth_First_Search, Level_2_Day_10_Graph/BFS/DFS | 164 | 82.95 | 0993 |[Cousins in Binary Tree](src/main/kotlin/g0901_1000/s0993_cousins_in_binary_tree)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 152 | 71.43 | 0992 |[Subarrays with K Different Integers](src/main/kotlin/g0901_1000/s0992_subarrays_with_k_different_integers)| Hard | Array, Hash_Table, Counting, Sliding_Window | 341 | 87.50 | 0991 |[Broken Calculator](src/main/kotlin/g0901_1000/s0991_broken_calculator)| Medium | Math, Greedy | 127 | 100.00 @@ -2075,13 +2152,16 @@ | 0622 |[Design Circular Queue](src/main/kotlin/g0601_0700/s0622_design_circular_queue)| Medium | Array, Design, Linked_List, Queue, Programming_Skills_II_Day_20 | 234 | 92.68 | 0621 |[Task Scheduler](src/main/kotlin/g0601_0700/s0621_task_scheduler)| Medium | Array, Hash_Table, Sorting, Greedy, Heap_Priority_Queue, Counting, Level_2_Day_5_Greedy | 266 | 98.36 | 0620 |[Not Boring Movies](src/main/kotlin/g0601_0700/s0620_not_boring_movies)| Easy | Database | 305 | 59.80 +| 0619 |[Biggest Single Number](src/main/kotlin/g0601_0700/s0619_biggest_single_number)| Easy | Database | 656 | 90.69 | 0617 |[Merge Two Binary Trees](src/main/kotlin/g0601_0700/s0617_merge_two_binary_trees)| Easy | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Algorithm_I_Day_8_Breadth_First_Search_Depth_First_Search | 243 | 72.83 | 0611 |[Valid Triangle Number](src/main/kotlin/g0601_0700/s0611_valid_triangle_number)| Medium | Array, Sorting, Greedy, Binary_Search, Two_Pointers, Binary_Search_II_Day_1 | 203 | 100.00 +| 0610 |[Triangle Judgement](src/main/kotlin/g0601_0700/s0610_triangle_judgement)| Easy | Database | 464 | 72.35 | 0609 |[Find Duplicate File in System](src/main/kotlin/g0601_0700/s0609_find_duplicate_file_in_system)| Medium | Array, String, Hash_Table | 426 | 100.00 | 0608 |[Tree Node](src/main/kotlin/g0601_0700/s0608_tree_node)| Medium | LeetCode_Curated_SQL_70, Database, SQL_I_Day_4_Union_and_Select | 794 | 48.38 | 0607 |[Sales Person](src/main/kotlin/g0601_0700/s0607_sales_person)| Easy | LeetCode_Curated_SQL_70, Database, SQL_I_Day_6_Union | 2142 | 44.56 | 0606 |[Construct String from Binary Tree](src/main/kotlin/g0601_0700/s0606_construct_string_from_binary_tree)| Easy | String, Depth_First_Search, Tree, Binary_Tree | 187 | 100.00 | 0605 |[Can Place Flowers](src/main/kotlin/g0601_0700/s0605_can_place_flowers)| Easy | Array, Greedy, Udemy_Arrays | 209 | 85.71 +| 0602 |[Friend Requests II: Who Has the Most Friends](src/main/kotlin/g0601_0700/s0602_friend_requests_ii_who_has_the_most_friends)| Medium | Database | 398 | 97.39 | 0601 |[Human Traffic of Stadium](src/main/kotlin/g0601_0700/s0601_human_traffic_of_stadium)| Hard | Database | 529 | 51.80 | 0600 |[Non-negative Integers without Consecutive Ones](src/main/kotlin/g0501_0600/s0600_non_negative_integers_without_consecutive_ones)| Hard | Dynamic_Programming | 142 | 100.00 | 0599 |[Minimum Index Sum of Two Lists](src/main/kotlin/g0501_0600/s0599_minimum_index_sum_of_two_lists)| Easy | Array, String, Hash_Table | 293 | 100.00 @@ -2096,12 +2176,15 @@ | 0589 |[N-ary Tree Preorder Traversal](src/main/kotlin/g0501_0600/s0589_n_ary_tree_preorder_traversal)| Easy | Depth_First_Search, Tree, Stack, Programming_Skills_I_Day_5_Function, Level_1_Day_6_Tree | 233 | 84.02 | 0587 |[Erect the Fence](src/main/kotlin/g0501_0600/s0587_erect_the_fence)| Hard | Array, Math, Geometry | 470 | 100.00 | 0586 |[Customer Placing the Largest Number of Orders](src/main/kotlin/g0501_0600/s0586_customer_placing_the_largest_number_of_orders)| Easy | LeetCode_Curated_SQL_70, Database, SQL_I_Day_8_Function | 768 | 44.85 +| 0585 |[Investments in 2016](src/main/kotlin/g0501_0600/s0585_investments_in_2016)| Medium | Database | 729 | 99.22 | 0584 |[Find Customer Referee](src/main/kotlin/g0501_0600/s0584_find_customer_referee)| Easy | Database, SQL_I_Day_1_Select | 779 | 43.48 | 0583 |[Delete Operation for Two Strings](src/main/kotlin/g0501_0600/s0583_delete_operation_for_two_strings)| Medium | String, Dynamic_Programming, Algorithm_II_Day_17_Dynamic_Programming | 197 | 100.00 | 0581 |[Shortest Unsorted Continuous Subarray](src/main/kotlin/g0501_0600/s0581_shortest_unsorted_continuous_subarray)| Medium | Array, Sorting, Greedy, Two_Pointers, Stack, Monotonic_Stack | 246 | 100.00 +| 0577 |[Employee Bonus](src/main/kotlin/g0501_0600/s0577_employee_bonus)| Easy | Database | 1473 | 95.83 | 0576 |[Out of Boundary Paths](src/main/kotlin/g0501_0600/s0576_out_of_boundary_paths)| Medium | Dynamic_Programming | 153 | 100.00 | 0575 |[Distribute Candies](src/main/kotlin/g0501_0600/s0575_distribute_candies)| Easy | Array, Hash_Table | 538 | 76.92 | 0572 |[Subtree of Another Tree](src/main/kotlin/g0501_0600/s0572_subtree_of_another_tree)| Easy | Depth_First_Search, Tree, Binary_Tree, Hash_Function, String_Matching, Algorithm_II_Day_7_Breadth_First_Search_Depth_First_Search | 214 | 92.39 +| 0570 |[Managers with at Least 5 Direct Reports](src/main/kotlin/g0501_0600/s0570_managers_with_at_least_5_direct_reports)| Medium | Database | 454 | 90.82 | 0567 |[Permutation in String](src/main/kotlin/g0501_0600/s0567_permutation_in_string)| Medium | String, Hash_Table, Two_Pointers, Sliding_Window, Algorithm_I_Day_6_Sliding_Window | 169 | 100.00 | 0566 |[Reshape the Matrix](src/main/kotlin/g0501_0600/s0566_reshape_the_matrix)| Easy | Array, Matrix, Simulation, Data_Structure_I_Day_4_Array, Programming_Skills_I_Day_7_Array | 239 | 99.05 | 0565 |[Array Nesting](src/main/kotlin/g0501_0600/s0565_array_nesting)| Medium | Array, Depth_First_Search | 553 | 100.00 @@ -2117,6 +2200,7 @@ | 0553 |[Optimal Division](src/main/kotlin/g0501_0600/s0553_optimal_division)| Medium | Array, Dynamic_Programming, Math | 154 | 100.00 | 0552 |[Student Attendance Record II](src/main/kotlin/g0501_0600/s0552_student_attendance_record_ii)| Hard | Dynamic_Programming | 151 | 100.00 | 0551 |[Student Attendance Record I](src/main/kotlin/g0501_0600/s0551_student_attendance_record_i)| Easy | String | 151 | 95.00 +| 0550 |[Game Play Analysis IV](src/main/kotlin/g0501_0600/s0550_game_play_analysis_iv)| Medium | Database | 762 | 97.74 | 0547 |[Number of Provinces](src/main/kotlin/g0501_0600/s0547_number_of_provinces)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find, Algorithm_II_Day_6_Breadth_First_Search_Depth_First_Search, Graph_Theory_I_Day_8_Standard_Traversal, Level_2_Day_19_Union_Find | 229 | 79.73 | 0546 |[Remove Boxes](src/main/kotlin/g0501_0600/s0546_remove_boxes)| Hard | Array, Dynamic_Programming, Memoization | 283 | 100.00 | 0543 |[Diameter of Binary Tree](src/main/kotlin/g0501_0600/s0543_diameter_of_binary_tree)| Easy | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree, Level_2_Day_7_Tree, Udemy_Tree_Stack_Queue | 307 | 43.93 diff --git a/src/main/kotlin/g0001_0100/s0001_two_sum/readme.md b/src/main/kotlin/g0001_0100/s0001_two_sum/readme.md index 0d6afa88..d005de30 100644 --- a/src/main/kotlin/g0001_0100/s0001_two_sum/readme.md +++ b/src/main/kotlin/g0001_0100/s0001_two_sum/readme.md @@ -49,7 +49,7 @@ class Solution { for (i in numbers.indices) { val requiredNum = target - numbers[i] if (indexMap.containsKey(requiredNum)) { - return intArrayOf(indexMap[requiredNum]!!, i) + return intArrayOf(indexMap.getValue(requiredNum), i) } indexMap[numbers[i]] = i } diff --git a/src/main/kotlin/g0001_0100/s0014_longest_common_prefix/readme.md b/src/main/kotlin/g0001_0100/s0014_longest_common_prefix/readme.md index e11612ad..366b0a37 100644 --- a/src/main/kotlin/g0001_0100/s0014_longest_common_prefix/readme.md +++ b/src/main/kotlin/g0001_0100/s0014_longest_common_prefix/readme.md @@ -43,7 +43,7 @@ class Solution { var temp = strs[0] var i = 1 var cur: String - while (temp.length > 0 && i < strs.size) { + while (temp.isNotEmpty() && i < strs.size) { if (temp.length > strs[i].length) { temp = temp.substring(0, strs[i].length) } diff --git a/src/main/kotlin/g0001_0100/s0020_valid_parentheses/readme.md b/src/main/kotlin/g0001_0100/s0020_valid_parentheses/readme.md index e85d23b1..a2d4f77e 100644 --- a/src/main/kotlin/g0001_0100/s0020_valid_parentheses/readme.md +++ b/src/main/kotlin/g0001_0100/s0020_valid_parentheses/readme.md @@ -59,11 +59,11 @@ class Solution { val c = element if (c == '(' || c == '[' || c == '{') { stack.push(c) - } else if (c == ')' && !stack.isEmpty() && stack.peek() == '(') { + } else if (c == ')' && stack.isNotEmpty() && stack.peek() == '(') { stack.pop() - } else if (c == '}' && !stack.isEmpty() && stack.peek() == '{') { + } else if (c == '}' && stack.isNotEmpty() && stack.peek() == '{') { stack.pop() - } else if (c == ']' && !stack.isEmpty() && stack.peek() == '[') { + } else if (c == ']' && stack.isNotEmpty() && stack.peek() == '[') { stack.pop() } else { return false diff --git a/src/main/kotlin/g0001_0100/s0049_group_anagrams/readme.md b/src/main/kotlin/g0001_0100/s0049_group_anagrams/readme.md index 03852ca0..4ff07c9a 100644 --- a/src/main/kotlin/g0001_0100/s0049_group_anagrams/readme.md +++ b/src/main/kotlin/g0001_0100/s0049_group_anagrams/readme.md @@ -46,7 +46,7 @@ class Solution { hm.computeIfAbsent( temp ) { _: String? -> ArrayList() } - hm[temp]!!.add(s) + hm.getValue(temp).add(s) } return ArrayList>(hm.values) } diff --git a/src/main/kotlin/g0001_0100/s0071_simplify_path/readme.md b/src/main/kotlin/g0001_0100/s0071_simplify_path/readme.md index 643e2143..93c575fc 100644 --- a/src/main/kotlin/g0001_0100/s0071_simplify_path/readme.md +++ b/src/main/kotlin/g0001_0100/s0071_simplify_path/readme.md @@ -68,7 +68,7 @@ class Solution { } val s = path.substring(start, end) if (s == "..") { - if (!stk.isEmpty()) { + if (stk.isNotEmpty()) { stk.pop() } } else if (s != "." && s != "") { @@ -77,7 +77,7 @@ class Solution { start = end + 1 } val ans = StringBuilder() - while (!stk.isEmpty()) { + while (stk.isNotEmpty()) { ans.insert(0, stk.pop()) ans.insert(0, "/") } diff --git a/src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal/readme.md b/src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal/readme.md index 23ae6671..257fe77a 100644 --- a/src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal/readme.md +++ b/src/main/kotlin/g0101_0200/s0102_binary_tree_level_order_traversal/readme.md @@ -61,9 +61,9 @@ class Solution { queue.add(localRoot) queue.add(null) var level: MutableList = ArrayList() - while (!queue.isEmpty()) { + while (queue.isNotEmpty()) { localRoot = queue.remove() - while (!queue.isEmpty() && localRoot != null) { + while (queue.isNotEmpty() && localRoot != null) { level.add(localRoot.`val`) if (localRoot.left != null) { queue.add(localRoot.left) @@ -75,7 +75,7 @@ class Solution { } result.add(level) level = ArrayList() - if (!queue.isEmpty()) { + if (queue.isNotEmpty()) { queue.add(null) } } diff --git a/src/main/kotlin/g0101_0200/s0103_binary_tree_zigzag_level_order_traversal/readme.md b/src/main/kotlin/g0101_0200/s0103_binary_tree_zigzag_level_order_traversal/readme.md index f3a0e7d8..426907d0 100644 --- a/src/main/kotlin/g0101_0200/s0103_binary_tree_zigzag_level_order_traversal/readme.md +++ b/src/main/kotlin/g0101_0200/s0103_binary_tree_zigzag_level_order_traversal/readme.md @@ -60,9 +60,9 @@ class Solution { q.add(null) var zig = true var level = LinkedList() - while (!q.isEmpty()) { + while (q.isNotEmpty()) { var node: TreeNode? = q.remove() - while (!q.isEmpty() && node != null) { + while (q.isNotEmpty() && node != null) { if (zig) { level.add(node.`val`) } else { @@ -79,7 +79,7 @@ class Solution { result.add(level) zig = !zig level = LinkedList() - if (!q.isEmpty()) { + if (q.isNotEmpty()) { q.add(null) } } diff --git a/src/main/kotlin/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md b/src/main/kotlin/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md index 9da626b9..7c50b5d2 100644 --- a/src/main/kotlin/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md +++ b/src/main/kotlin/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md @@ -50,8 +50,9 @@ import java.util.HashMap class Solution { private var j = 0 private val map: MutableMap = HashMap() + fun get(key: Int): Int { - return map[key]!! + return map.getValue(key) } private fun answer(preorder: IntArray, inorder: IntArray, start: Int, end: Int): TreeNode? { diff --git a/src/main/kotlin/g0101_0200/s0111_minimum_depth_of_binary_tree/readme.md b/src/main/kotlin/g0101_0200/s0111_minimum_depth_of_binary_tree/readme.md index 57c2d46b..a0727679 100644 --- a/src/main/kotlin/g0101_0200/s0111_minimum_depth_of_binary_tree/readme.md +++ b/src/main/kotlin/g0101_0200/s0111_minimum_depth_of_binary_tree/readme.md @@ -55,7 +55,7 @@ class Solution { val queue: Queue = LinkedList() queue.add(root) var d = 0 - while (!queue.isEmpty()) { + while (queue.isNotEmpty()) { val size: Int = queue.size for (i in 0 until size) { val current: TreeNode = queue.poll() diff --git a/src/main/kotlin/g0101_0200/s0117_populating_next_right_pointers_in_each_node_ii/readme.md b/src/main/kotlin/g0101_0200/s0117_populating_next_right_pointers_in_each_node_ii/readme.md index 2247fa2e..93cd14f7 100644 --- a/src/main/kotlin/g0101_0200/s0117_populating_next_right_pointers_in_each_node_ii/readme.md +++ b/src/main/kotlin/g0101_0200/s0117_populating_next_right_pointers_in_each_node_ii/readme.md @@ -62,7 +62,7 @@ class Solution { root.next = null var temp: Node? var prev: Node? - while (!bfsQueue.isEmpty()) { + while (bfsQueue.isNotEmpty()) { val size = bfsQueue.size prev = null for (j in 0 until size) { diff --git a/src/main/kotlin/g0101_0200/s0126_word_ladder_ii/readme.md b/src/main/kotlin/g0101_0200/s0126_word_ladder_ii/readme.md index 5418ed11..0e84f5d4 100644 --- a/src/main/kotlin/g0101_0200/s0126_word_ladder_ii/readme.md +++ b/src/main/kotlin/g0101_0200/s0126_word_ladder_ii/readme.md @@ -69,7 +69,7 @@ class Solution { // find endWord flag var findEnd = false // traverse current layer nodes - while (!queue.isEmpty()) { + while (queue.isNotEmpty()) { val word = queue.remove() for (next in wordSet) { // is ladder words diff --git a/src/main/kotlin/g0101_0200/s0127_word_ladder/readme.md b/src/main/kotlin/g0101_0200/s0127_word_ladder/readme.md index ecd3a0fd..a2de5253 100644 --- a/src/main/kotlin/g0101_0200/s0127_word_ladder/readme.md +++ b/src/main/kotlin/g0101_0200/s0127_word_ladder/readme.md @@ -55,7 +55,7 @@ class Solution { val strLen = beginWord.length beginSet.add(beginWord) endSet.add(endWord) - while (!beginSet.isEmpty() && !endSet.isEmpty()) { + while (beginSet.isNotEmpty() && endSet.isNotEmpty()) { if (beginSet.size > endSet.size) { val temp = beginSet beginSet = endSet diff --git a/src/main/kotlin/g0101_0200/s0128_longest_consecutive_sequence/readme.md b/src/main/kotlin/g0101_0200/s0128_longest_consecutive_sequence/readme.md index 56c26795..2b988dcb 100644 --- a/src/main/kotlin/g0101_0200/s0128_longest_consecutive_sequence/readme.md +++ b/src/main/kotlin/g0101_0200/s0128_longest_consecutive_sequence/readme.md @@ -45,7 +45,7 @@ class Solution { var lastNum = Integer.MIN_VALUE var length = 0 var maxLength = 1 - while (!queue.isEmpty()) { + while (queue.isNotEmpty()) { val num = queue.poll() if (num == lastNum) { continue diff --git a/src/main/kotlin/g0101_0200/s0144_binary_tree_preorder_traversal/readme.md b/src/main/kotlin/g0101_0200/s0144_binary_tree_preorder_traversal/readme.md index b70d6558..62a87097 100644 --- a/src/main/kotlin/g0101_0200/s0144_binary_tree_preorder_traversal/readme.md +++ b/src/main/kotlin/g0101_0200/s0144_binary_tree_preorder_traversal/readme.md @@ -58,7 +58,7 @@ class Solution { } val stack: Stack = Stack() var current: TreeNode? = root - while (current != null || !stack.isEmpty()) { + while (current != null || stack.isNotEmpty()) { while (current != null) { result.add(current.`val`) stack.push(current.right) diff --git a/src/main/kotlin/g0101_0200/s0150_evaluate_reverse_polish_notation/readme.md b/src/main/kotlin/g0101_0200/s0150_evaluate_reverse_polish_notation/readme.md index a605c819..575e31f3 100644 --- a/src/main/kotlin/g0101_0200/s0150_evaluate_reverse_polish_notation/readme.md +++ b/src/main/kotlin/g0101_0200/s0150_evaluate_reverse_polish_notation/readme.md @@ -72,7 +72,7 @@ class Solution { if (op.contains(t)) { val b = stack.removeFirst().toInt() val a = stack.removeFirst().toInt() - val c = op[t]!!.apply(a, b) + val c = op.getValue(t).apply(a, b) stack.addFirst(c.toString()) } else { stack.addFirst(t) diff --git a/src/main/kotlin/g0101_0200/s0166_fraction_to_recurring_decimal/readme.md b/src/main/kotlin/g0101_0200/s0166_fraction_to_recurring_decimal/readme.md index 2a41cafa..e66e1175 100644 --- a/src/main/kotlin/g0101_0200/s0166_fraction_to_recurring_decimal/readme.md +++ b/src/main/kotlin/g0101_0200/s0166_fraction_to_recurring_decimal/readme.md @@ -63,7 +63,7 @@ class Solution { val map: MutableMap = HashMap() while (remainder != 0L) { if (map.containsKey(remainder)) { - sb.insert(map[remainder]!!, "(") + sb.insert(map.getValue(remainder), "(") sb.append(")") break } diff --git a/src/main/kotlin/g0201_0300/s0216_combination_sum_iii/readme.md b/src/main/kotlin/g0201_0300/s0216_combination_sum_iii/readme.md index b661260d..e35b29cc 100644 --- a/src/main/kotlin/g0201_0300/s0216_combination_sum_iii/readme.md +++ b/src/main/kotlin/g0201_0300/s0216_combination_sum_iii/readme.md @@ -67,7 +67,7 @@ class Solution { return } if (n == 0 && tmp.size == k) { - a.add(tmp.map { it -> it }.toMutableList()) + a.add(tmp.map { it }.toMutableList()) return } for (i in index until 10) { diff --git a/src/main/kotlin/g0201_0300/s0220_contains_duplicate_iii/readme.md b/src/main/kotlin/g0201_0300/s0220_contains_duplicate_iii/readme.md index 38cda020..61150559 100644 --- a/src/main/kotlin/g0201_0300/s0220_contains_duplicate_iii/readme.md +++ b/src/main/kotlin/g0201_0300/s0220_contains_duplicate_iii/readme.md @@ -67,10 +67,10 @@ class Solution { if (d.containsKey(m)) { return true } - if (d.containsKey(m - 1) && Math.abs(nums[i] - d[m - 1]!!) < w) { + if (d.containsKey(m - 1) && Math.abs(nums[i] - d.getValue(m - 1)) < w) { return true } - if (d.containsKey(m + 1) && Math.abs(nums[i] - d[m + 1]!!) < w) { + if (d.containsKey(m + 1) && Math.abs(nums[i] - d.getValue(m + 1)) < w) { return true } d[m] = nums[i].toLong() diff --git a/src/main/kotlin/g0201_0300/s0239_sliding_window_maximum/readme.md b/src/main/kotlin/g0201_0300/s0239_sliding_window_maximum/readme.md index f5405846..d99f614d 100644 --- a/src/main/kotlin/g0201_0300/s0239_sliding_window_maximum/readme.md +++ b/src/main/kotlin/g0201_0300/s0239_sliding_window_maximum/readme.md @@ -59,7 +59,7 @@ class Solution { var i = 0 var j = 0 while (j < nums.size) { - while (!dq.isEmpty() && dq.peekLast() < nums[j]) { + while (dq.isNotEmpty() && dq.peekLast() < nums[j]) { dq.pollLast() } dq.addLast(nums[j]) diff --git a/src/main/kotlin/g0201_0300/s0241_different_ways_to_add_parentheses/readme.md b/src/main/kotlin/g0201_0300/s0241_different_ways_to_add_parentheses/readme.md index c82066a8..c30d6aed 100644 --- a/src/main/kotlin/g0201_0300/s0241_different_ways_to_add_parentheses/readme.md +++ b/src/main/kotlin/g0201_0300/s0241_different_ways_to_add_parentheses/readme.md @@ -45,7 +45,7 @@ class Solution { private fun diffWayToCompute(expression: String, hashMap: HashMap>): List { if (hashMap.containsKey(expression)) { - return hashMap[expression]!! + return hashMap.getValue(expression) } val newList = arrayListOf() if (!hasOperatorInBetween(expression)) { diff --git a/src/main/kotlin/g0201_0300/s0282_expression_add_operators/readme.md b/src/main/kotlin/g0201_0300/s0282_expression_add_operators/readme.md index 77eaa6b7..02d52967 100644 --- a/src/main/kotlin/g0201_0300/s0282_expression_add_operators/readme.md +++ b/src/main/kotlin/g0201_0300/s0282_expression_add_operators/readme.md @@ -46,7 +46,7 @@ Note that operands in the returned expressions **should not** contain leading ze class Solution { fun addOperators(num: String, target: Int): List { val res: MutableList = ArrayList() - if (num.length == 0 || java.lang.Long.valueOf(num) > Int.MAX_VALUE) { + if (num.isEmpty() || java.lang.Long.valueOf(num) > Int.MAX_VALUE) { return res } val list = num.toCharArray() diff --git a/src/main/kotlin/g0301_0400/s0332_reconstruct_itinerary/readme.md b/src/main/kotlin/g0301_0400/s0332_reconstruct_itinerary/readme.md index 15bf936d..25eac3bf 100644 --- a/src/main/kotlin/g0301_0400/s0332_reconstruct_itinerary/readme.md +++ b/src/main/kotlin/g0301_0400/s0332_reconstruct_itinerary/readme.md @@ -69,7 +69,7 @@ class Solution { private fun dfs(map: Map>, src: String, ans: LinkedList) { val temp = map[src] - while (temp != null && !temp.isEmpty()) { + while (!temp.isNullOrEmpty()) { val nbr = temp.remove() dfs(map, nbr, ans) } diff --git a/src/main/kotlin/g0301_0400/s0350_intersection_of_two_arrays_ii/readme.md b/src/main/kotlin/g0301_0400/s0350_intersection_of_two_arrays_ii/readme.md index b95c3163..01a806ed 100644 --- a/src/main/kotlin/g0301_0400/s0350_intersection_of_two_arrays_ii/readme.md +++ b/src/main/kotlin/g0301_0400/s0350_intersection_of_two_arrays_ii/readme.md @@ -45,7 +45,7 @@ class Solution { for (i in 0 until nums2.size) { if (a.getOrDefault(nums2[i], 0)> 0) { s.add(nums2[i]) - a[nums2[i]] = a[nums2[i]]!! - 1 + a[nums2[i]] = a.getValue(nums2[i]) - 1 } } return s.toIntArray() diff --git a/src/main/kotlin/g0301_0400/s0355_design_twitter/readme.md b/src/main/kotlin/g0301_0400/s0355_design_twitter/readme.md index 7dea0999..2aed54e3 100644 --- a/src/main/kotlin/g0301_0400/s0355_design_twitter/readme.md +++ b/src/main/kotlin/g0301_0400/s0355_design_twitter/readme.md @@ -75,7 +75,7 @@ class Twitter { fun getNewsFeed(userId: Int): List { checkNewUser(userId) val res: MutableList = ArrayList() - val followers = twitterData[userId]!! + val followers = twitterData.getValue(userId) var t = head.next while (t != null && res.size < 10) { if (followers.contains(t.userId)) { @@ -89,7 +89,7 @@ class Twitter { fun follow(followerId: Int, followeeId: Int) { checkNewUser(followeeId) checkNewUser(followerId) - twitterData[followerId]!!.add(followeeId) + twitterData.getValue(followerId).add(followeeId) } fun unfollow(followerId: Int, followeeId: Int) { @@ -99,7 +99,7 @@ class Twitter { return } checkNewUser(followerId) - twitterData[followerId]!!.remove(followeeId) + twitterData.getValue(followerId).remove(followeeId) } fun checkNewUser(userId: Int) { @@ -108,7 +108,7 @@ class Twitter { } twitterData[userId] = HashSet() // follow yourself - twitterData[userId]!!.add(userId) + twitterData.getValue(userId).add(userId) } } diff --git a/src/main/kotlin/g0301_0400/s0373_find_k_pairs_with_smallest_sums/readme.md b/src/main/kotlin/g0301_0400/s0373_find_k_pairs_with_smallest_sums/readme.md index 7692f233..711d2ab1 100644 --- a/src/main/kotlin/g0301_0400/s0373_find_k_pairs_with_smallest_sums/readme.md +++ b/src/main/kotlin/g0301_0400/s0373_find_k_pairs_with_smallest_sums/readme.md @@ -74,7 +74,7 @@ class Solution { } } var i = 1 - while (i <= k && !queue.isEmpty()) { + while (i <= k && queue.isNotEmpty()) { val cur = queue.poll() res.add(cur.al) val next = cur.index diff --git a/src/main/kotlin/g0301_0400/s0388_longest_absolute_file_path/readme.md b/src/main/kotlin/g0301_0400/s0388_longest_absolute_file_path/readme.md index e0825c15..c30bbb98 100644 --- a/src/main/kotlin/g0301_0400/s0388_longest_absolute_file_path/readme.md +++ b/src/main/kotlin/g0301_0400/s0388_longest_absolute_file_path/readme.md @@ -117,17 +117,17 @@ class Solution { if (nextLevel < currLevel) { var j = 0 if (isFile) { - while (!stack.isEmpty() && j < currLevel - nextLevel) { + while (stack.isNotEmpty() && j < currLevel - nextLevel) { currDirLen -= stack.pop() j++ } } else { - while (!stack.isEmpty() && j <= currLevel - nextLevel) { + while (stack.isNotEmpty() && j <= currLevel - nextLevel) { currDirLen -= stack.pop() j++ } } - } else if (nextLevel == currLevel && !isFile && !stack.isEmpty()) { + } else if (nextLevel == currLevel && !isFile && stack.isNotEmpty()) { currDirLen -= stack.pop() } if (nextLevel == 0) { diff --git a/src/main/kotlin/g0401_0500/s0407_trapping_rain_water_ii/readme.md b/src/main/kotlin/g0401_0500/s0407_trapping_rain_water_ii/readme.md index d72a0750..60ce3f3e 100644 --- a/src/main/kotlin/g0401_0500/s0407_trapping_rain_water_ii/readme.md +++ b/src/main/kotlin/g0401_0500/s0407_trapping_rain_water_ii/readme.md @@ -69,7 +69,7 @@ class Solution { visited1[r][cols - 1] = true } // end build wall - while (!walls.isEmpty()) { + while (walls.isNotEmpty()) { val min = walls.poll() visit(heightMap, min, walls) } diff --git a/src/main/kotlin/g0401_0500/s0429_n_ary_tree_level_order_traversal/readme.md b/src/main/kotlin/g0401_0500/s0429_n_ary_tree_level_order_traversal/readme.md index 4d2e051e..d81afbf1 100644 --- a/src/main/kotlin/g0401_0500/s0429_n_ary_tree_level_order_traversal/readme.md +++ b/src/main/kotlin/g0401_0500/s0429_n_ary_tree_level_order_traversal/readme.md @@ -51,7 +51,7 @@ class Solution { } val queue: Queue = LinkedList() queue.offer(root) - while (!queue.isEmpty()) { + while (queue.isNotEmpty()) { val size: Int = queue.size val level: MutableList = ArrayList() for (i in 0 until size) { diff --git a/src/main/kotlin/g0401_0500/s0433_minimum_genetic_mutation/readme.md b/src/main/kotlin/g0401_0500/s0433_minimum_genetic_mutation/readme.md index cb073d7e..38a61c71 100644 --- a/src/main/kotlin/g0401_0500/s0433_minimum_genetic_mutation/readme.md +++ b/src/main/kotlin/g0401_0500/s0433_minimum_genetic_mutation/readme.md @@ -69,7 +69,7 @@ class Solution { val queue: Queue = LinkedList() queue.offer(start) var step = 0 - while (!queue.isEmpty()) { + while (queue.isNotEmpty()) { var curSize = queue.size while (curSize-- > 0) { val cur = queue.poll() diff --git a/src/main/kotlin/g0401_0500/s0434_number_of_segments_in_a_string/readme.md b/src/main/kotlin/g0401_0500/s0434_number_of_segments_in_a_string/readme.md index b90a3352..ed0b0921 100644 --- a/src/main/kotlin/g0401_0500/s0434_number_of_segments_in_a_string/readme.md +++ b/src/main/kotlin/g0401_0500/s0434_number_of_segments_in_a_string/readme.md @@ -37,13 +37,13 @@ class Solution { fun countSegments(s: String): Int { var s = s s = s.trim { it <= ' ' } - if (s.length == 0) { + if (s.isEmpty()) { return 0 } val splitted = s.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() var result = 0 for (value in splitted) { - if (value.length > 0) { + if (value.isNotEmpty()) { result++ } } diff --git a/src/main/kotlin/g0401_0500/s0456_132_pattern/readme.md b/src/main/kotlin/g0401_0500/s0456_132_pattern/readme.md index 746721a3..79ce4fd9 100644 --- a/src/main/kotlin/g0401_0500/s0456_132_pattern/readme.md +++ b/src/main/kotlin/g0401_0500/s0456_132_pattern/readme.md @@ -59,7 +59,7 @@ class Solution { if (nums[i] < s3) { return true } else { - while (!stack.isEmpty() && nums[i] > stack.peek()) { + while (stack.isNotEmpty() && nums[i] > stack.peek()) { s3 = Math.max(s3, stack.pop()) } } diff --git a/src/main/kotlin/g0401_0500/s0468_validate_ip_address/readme.md b/src/main/kotlin/g0401_0500/s0468_validate_ip_address/readme.md index 737411e8..175205d1 100644 --- a/src/main/kotlin/g0401_0500/s0468_validate_ip_address/readme.md +++ b/src/main/kotlin/g0401_0500/s0468_validate_ip_address/readme.md @@ -50,7 +50,7 @@ For example, "`2001:0db8:85a3:0000:0000:8a2e:0370:7334"` and "`2001:db8:85a3:0:0 ```kotlin class Solution { fun validIPAddress(ip: String): String { - if (ip.length == 0) { + if (ip.isEmpty()) { return NEITHER } val arr = ip.split("\\.".toRegex()).toTypedArray() diff --git a/src/main/kotlin/g0401_0500/s0488_zuma_game/readme.md b/src/main/kotlin/g0401_0500/s0488_zuma_game/readme.md index 4db742cc..a2039f25 100644 --- a/src/main/kotlin/g0401_0500/s0488_zuma_game/readme.md +++ b/src/main/kotlin/g0401_0500/s0488_zuma_game/readme.md @@ -63,10 +63,10 @@ class Solution { } private fun findMinStepDp(board: String, hand: String, dp: MutableMap?>): Int { - if (board.length == 0) { + if (board.isEmpty()) { return 0 } - if (hand.length == 0) { + if (hand.isEmpty()) { return -1 } if (dp[board] != null && dp[board]!![hand] != null) { diff --git a/src/main/kotlin/g0501_0600/s0502_ipo/readme.md b/src/main/kotlin/g0501_0600/s0502_ipo/readme.md index 892b788c..59240bf9 100644 --- a/src/main/kotlin/g0501_0600/s0502_ipo/readme.md +++ b/src/main/kotlin/g0501_0600/s0502_ipo/readme.md @@ -64,7 +64,7 @@ class Solution { for (i in 0 until k) { // first fetch all tasks you can do with current capital and add those in profit max heap - while (!capitalMinHeap.isEmpty() && currentCapital >= capitalMinHeap.peek().capital) { + while (capitalMinHeap.isNotEmpty() && currentCapital >= capitalMinHeap.peek().capital) { profitMaxHeap.add(capitalMinHeap.poll()) } diff --git a/src/main/kotlin/g0501_0600/s0503_next_greater_element_ii/readme.md b/src/main/kotlin/g0501_0600/s0503_next_greater_element_ii/readme.md index 648e6190..080adb2d 100644 --- a/src/main/kotlin/g0501_0600/s0503_next_greater_element_ii/readme.md +++ b/src/main/kotlin/g0501_0600/s0503_next_greater_element_ii/readme.md @@ -37,7 +37,7 @@ class Solution { val result = IntArray(nums.size) val stack: Deque = ArrayDeque() for (i in nums.size * 2 - 1 downTo 0) { - while (!stack.isEmpty() && nums[stack.peek()] <= nums[i % nums.size]) { + while (stack.isNotEmpty() && nums[stack.peek()] <= nums[i % nums.size]) { stack.pop() } result[i % nums.size] = if (stack.isEmpty()) -1 else nums[stack.peek()] diff --git a/src/main/kotlin/g0501_0600/s0515_find_largest_value_in_each_tree_row/readme.md b/src/main/kotlin/g0501_0600/s0515_find_largest_value_in_each_tree_row/readme.md index 1023438e..41b9a50a 100644 --- a/src/main/kotlin/g0501_0600/s0515_find_largest_value_in_each_tree_row/readme.md +++ b/src/main/kotlin/g0501_0600/s0515_find_largest_value_in_each_tree_row/readme.md @@ -49,7 +49,7 @@ class Solution { val queue: Queue = LinkedList() if (root != null) { queue.offer(root) - while (!queue.isEmpty()) { + while (queue.isNotEmpty()) { var max = Int.MIN_VALUE val size = queue.size for (i in 0 until size) { diff --git a/src/main/kotlin/g0501_0600/s0524_longest_word_in_dictionary_through_deleting/readme.md b/src/main/kotlin/g0501_0600/s0524_longest_word_in_dictionary_through_deleting/readme.md index d1077faa..70d502f5 100644 --- a/src/main/kotlin/g0501_0600/s0524_longest_word_in_dictionary_through_deleting/readme.md +++ b/src/main/kotlin/g0501_0600/s0524_longest_word_in_dictionary_through_deleting/readme.md @@ -48,7 +48,7 @@ class Solution { var maxLen = 0 var res = "" for (i in 0 until s.length) { - if (!map[s[i]]!!.isEmpty()) { + if (map[s[i]]!!.isNotEmpty()) { val deque = map[s[i]]!! val size = deque.size for (j in 0 until size) { diff --git a/src/main/kotlin/g0501_0600/s0550_game_play_analysis_iv/readme.md b/src/main/kotlin/g0501_0600/s0550_game_play_analysis_iv/readme.md new file mode 100644 index 00000000..457b3989 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0550_game_play_analysis_iv/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) + +## 550\. Game Play Analysis IV + +Medium + +SQL Schema + +Table: `Activity` + + +--------------+---------+ + | Column Name | Type | + +--------------+---------+ + | player_id | int | + | device_id | int | + | event_date | date | + | games_played | int | + +--------------+---------+ + (player_id, event_date) is the primary key of this table. + This table shows the activity of players of some games. + Each row is a record of a player who logged in and played a number of games + (possibly 0) before logging out on someday using some device. + +Write an SQL query to report the **fraction** of players that logged in again on the day after the day they first logged in, **rounded to 2 decimal places**. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + +Activity table: + + +-----------+-----------+------------+--------------+ + | player_id | device_id | event_date | games_played | + +-----------+-----------+------------+--------------+ + | 1 | 2 | 2016-03-01 | 5 | + | 1 | 2 | 2016-03-02 | 6 | + | 2 | 3 | 2017-06-25 | 1 | + | 3 | 1 | 2016-03-02 | 0 | + | 3 | 4 | 2018-07-03 | 5 | + +-----------+-----------+------------+--------------+ + +**Output:** + + +-----------+ + | fraction | + +-----------+ + | 0.33 | + +-----------+ + +**Explanation:** + +Only the player with id 1 logged back in after the first day he had logged in so the answer is 1/3 = 0.33 + +## Solution + +```sql +# Write your MySQL query statement below +SELECT ROUND(COUNT(t2.player_id)/CAST(COUNT(t1.player_id) AS DECIMAL),2) AS fraction +FROM +(SELECT player_id, MIN(event_date) AS first_login FROM Activity GROUP BY player_id) t1 LEFT JOIN Activity t2 +ON t1.player_id = t2.player_id AND t1.first_login = t2.event_date - 1 +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0554_brick_wall/readme.md b/src/main/kotlin/g0501_0600/s0554_brick_wall/readme.md index cbb335d6..289601c3 100644 --- a/src/main/kotlin/g0501_0600/s0554_brick_wall/readme.md +++ b/src/main/kotlin/g0501_0600/s0554_brick_wall/readme.md @@ -49,7 +49,7 @@ class Solution { } } var value = 0 - if (gapMap.size > 0) { + if (gapMap.isNotEmpty()) { value = gapMap.values.max() } return wall.size - value diff --git a/src/main/kotlin/g0501_0600/s0559_maximum_depth_of_n_ary_tree/readme.md b/src/main/kotlin/g0501_0600/s0559_maximum_depth_of_n_ary_tree/readme.md index 0577e61b..4aa40be2 100644 --- a/src/main/kotlin/g0501_0600/s0559_maximum_depth_of_n_ary_tree/readme.md +++ b/src/main/kotlin/g0501_0600/s0559_maximum_depth_of_n_ary_tree/readme.md @@ -60,7 +60,7 @@ class Solution { } private fun findDepth(n: Node?, d: Int) { - if (!n!!.neighbors.isEmpty()) { + if (n!!.neighbors.isNotEmpty()) { for (no in n.neighbors) { findDepth(no, d + 1) } diff --git a/src/main/kotlin/g0501_0600/s0570_managers_with_at_least_5_direct_reports/readme.md b/src/main/kotlin/g0501_0600/s0570_managers_with_at_least_5_direct_reports/readme.md new file mode 100644 index 00000000..23c762a8 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0570_managers_with_at_least_5_direct_reports/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) + +## 570\. Managers with at Least 5 Direct Reports + +Medium + +SQL Schema + +Table: `Employee` + + +-------------+---------+ + | Column Name | Type | + +-------------+---------+ + | id | int | + | name | varchar | + | department | varchar | + | managerId | int | + +-------------+---------+ + id is the primary key column for this table. + Each row of this table indicates the name of an employee, their department, and the id of their manager. + If managerId is null, then the employee does not have a manager. + No employee will be the manager of themself. + +Write an SQL query to report the managers with at least **five direct reports**. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + +Employee table: + + +-----+-------+------------+-----------+ + | id | name | department | managerId | + +-----+-------+------------+-----------+ + | 101 | John | A | None | + | 102 | Dan | A | 101 | + | 103 | James | A | 101 | + | 104 | Amy | A | 101 | + | 105 | Anne | A | 101 | + | 106 | Ron | B | 101 | + +-----+-------+------------+-----------+ + +**Output:** + + +------+ + | name | + +------+ + | John | + +------+ + +## Solution + +```sql +# Write your MySQL query statement below +select e.name +from employee m left join employee e +on m.managerid = e.id +group by e.name +having count(e.name) > 4; +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0577_employee_bonus/readme.md b/src/main/kotlin/g0501_0600/s0577_employee_bonus/readme.md new file mode 100644 index 00000000..4683e1e6 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0577_employee_bonus/readme.md @@ -0,0 +1,88 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 577\. Employee Bonus + +Easy + +SQL Schema + +Table: `Employee` + + +-------------+---------+ + | Column Name | Type | + +-------------+---------+ + | empId | int | + | name | varchar | + | supervisor | int | + | salary | int | + +-------------+---------+ + +empId is the primary key column for this table. + +Each row of this table indicates the name and the ID of an employee in addition to their salary and the id of their manager. + +Table: `Bonus` + + +-------------+------+ + | Column Name | Type | + +-------------+------+ + | empId | int | + | bonus | int | + +-------------+------+ + +empId is the primary key column for this table. + +empId is a foreign key to empId from the Employee table. + +Each row of this table contains the id of an employee and their respective bonus. + +Write an SQL query to report the name and bonus amount of each employee with a bonus **less than** `1000`. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + +Employee table: + + +-------+--------+------------+--------+ + | empId | name | supervisor | salary | + +-------+--------+------------+--------+ + | 3 | Brad | null | 4000 | + | 1 | John | 3 | 1000 | + | 2 | Dan | 3 | 2000 | + | 4 | Thomas | 3 | 4000 | + +-------+--------+------------+--------+ + +Bonus table: + + +-------+-------+ + | empId | bonus | + +-------+-------+ + | 2 | 500 | + | 4 | 2000 | + +-------+-------+ + +**Output:** + + +------+-------+ + | name | bonus | + +------+-------+ + | Brad | null | + | John | null | + | Dan | 500 | + +------+-------+ + +## Solution + +```sql +# Write your MySQL query statement below +SELECT name, bonus +FROM Employee e +LEFT JOIN Bonus b ON e.empId = b.empId +WHERE bonus < 1000 or b.empId is null; +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0585_investments_in_2016/readme.md b/src/main/kotlin/g0501_0600/s0585_investments_in_2016/readme.md new file mode 100644 index 00000000..10c2114d --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0585_investments_in_2016/readme.md @@ -0,0 +1,81 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 585\. Investments in 2016 + +Medium + +SQL Schema + +Table: `Insurance` + + +-------------+-------+ + | Column Name | Type | + +-------------+-------+ + | pid | int | + | tiv_2015 | float | + | tiv_2016 | float | + | lat | float | + | lon | float | + +-------------+-------+ + +pid is the primary key column for this table. + +Each row of this table contains information about one policy where: + +pid is the policyholder's policy ID. + +tiv\_2015 is the total investment value in 2015 and tiv\_2016 is the total investment value in 2016. + +lat is the latitude of the policy holder's city. It's guaranteed that lat is not NULL. + +lon is the longitude of the policy holder's city. It's guaranteed that lon is not NULL. + +Write an SQL query to report the sum of all total investment values in 2016 `tiv_2016`, for all policyholders who: + +* have the same `tiv_2015` value as one or more other policyholders, and +* are not located in the same city like any other policyholder (i.e., the (`lat, lon`) attribute pairs must be unique). + +Round `tiv_2016` to **two decimal places**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** Insurance table: + + +-----+----------+----------+-----+-----+ + | pid | tiv_2015 | tiv_2016 | lat | lon | + +-----+----------+----------+-----+-----+ + | 1 | 10 | 5 | 10 | 10 | + | 2 | 20 | 20 | 20 | 20 | + | 3 | 10 | 30 | 20 | 20 | + | 4 | 10 | 40 | 40 | 40 | + +-----+----------+----------+-----+-----+ + +**Output:** + + +----------+ + | tiv_2016 | + +----------+ + | 45.00 | + +----------+ + +**Explanation:** + +The first record in the table, like the last record, meets both of the two criteria. +The tiv\_2015 value 10 is the same as the third and fourth records, and its location is unique. + +The second record does not meet any of the two criteria. Its tiv\_2015 is not like any other policyholders and its location is the same as the third record, which makes the third record fail, too. +So, the result is the sum of tiv\_2016 of the first and last record, which is 45. + +## Solution + +```sql +# Write your MySQL query statement below +select round(sum(tiv_2016),2) tiv_2016 from insurance i1 +where tiv_2015 in (select tiv_2015 from insurance i2 + where i1.pid != i2.pid) +and (lat, lon) not in (select lat, lon from insurance i3 + where i3.pid != i1.pid) +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0602_friend_requests_ii_who_has_the_most_friends/readme.md b/src/main/kotlin/g0601_0700/s0602_friend_requests_ii_who_has_the_most_friends/readme.md new file mode 100644 index 00000000..94e7efa4 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0602_friend_requests_ii_who_has_the_most_friends/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) + +## 602\. Friend Requests II: Who Has the Most Friends + +Medium + +SQL Schema + +Table: `RequestAccepted` + + +----------------+---------+ + | Column Name | Type | + +----------------+---------+ + | requester_id | int | + | accepter_id | int | + | accept_date | date | + +----------------+---------+ + +(requester_id, accepter_id) is the primary key for this table. This table contains the ID of the user who sent the request, the ID of the user who received the request, and the date when the request was accepted. + +Write an SQL query to find the people who have the most friends and the most friends number. + +The test cases are generated so that only one person has the most friends. + +The query result format is in the following example. + +**Example 1:** + +**Input:** RequestAccepted table: + + +--------------+-------------+-------------+ + | requester_id | accepter_id | accept_date | + +--------------+-------------+-------------+ + | 1 | 2 | 2016/06/03 | + | 1 | 3 | 2016/06/08 | + | 2 | 3 | 2016/06/08 | + | 3 | 4 | 2016/06/09 | + +--------------+-------------+-------------+ + +**Output:** + + +----+-----+ + | id | num | + +----+-----+ + | 3 | 3 | + +----+-----+ + +**Explanation:** The person with id 3 is a friend of people 1, 2, and 4, so he has three friends in total, which is the most number than any others. + +**Follow up:** In the real world, multiple people could have the same most number of friends. Could you find all these people in this case? + +## Solution + +```sql +# Write your MySQL query statement below +SELECT req AS id, COUNT(acc) AS num +FROM +((SELECT requester_id AS req, accepter_id AS acc +FROM requestaccepted) +UNION +(SELECT accepter_id AS req, requester_id AS acc +FROM requestaccepted)) t +GROUP BY req +ORDER BY num DESC +LIMIT 1 +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0610_triangle_judgement/readme.md b/src/main/kotlin/g0601_0700/s0610_triangle_judgement/readme.md new file mode 100644 index 00000000..670bb0f2 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0610_triangle_judgement/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) + +## 610\. Triangle Judgement + +Easy + +SQL Schema + +Table: `Triangle` + + +-------------+------+ + | Column Name | Type | + +-------------+------+ + | x | int | + | y | int | + | z | int | + +-------------+------+ + +(x, y, z) is the primary key column for this table. + +Each row of this table contains the lengths of three line segments. + +Write an SQL query to report for every three line segments whether they can form a triangle. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** Triangle table: + + +----+----+----+ + | x | y | z | + +----+----+----+ + | 13 | 15 | 30 | + | 10 | 20 | 15 | + +----+----+----+ + +**Output:** + + +----+----+----+----------+ + | x | y | z | triangle | + +----+----+----+----------+ + | 13 | 15 | 30 | No | + | 10 | 20 | 15 | Yes | + +----+----+----+----------+ + +## Solution + +```sql +# Write your MySQL query statement below +SELECT *, + CASE WHEN x+y>z AND y+z>x AND z+x>y THEN 'Yes' ELSE 'No' END AS triangle +FROM Triangle +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0619_biggest_single_number/readme.md b/src/main/kotlin/g0601_0700/s0619_biggest_single_number/readme.md new file mode 100644 index 00000000..7797fc2f --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0619_biggest_single_number/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) + +## 619\. Biggest Single Number + +Easy + +SQL Schema + +Table: `MyNumbers` + + +-------------+------+ + | Column Name | Type | + +-------------+------+ + | num | int | + +-------------+------+ + +There is no primary key for this table. It may contain duplicates. + +Each row of this table contains an integer. + +A **single number** is a number that appeared only once in the `MyNumbers` table. + +Write an SQL query to report the largest **single number**. If there is no **single number**, report `null`. + +The query result format is in the following example. + +**Example 1:** + +**Input:** MyNumbers table: + + +-----+ + | num | + +-----+ + | 8 | + | 8 | + | 3 | + | 3 | + | 1 | + | 4 | + | 5 | + | 6 | + +-----+ + +**Output:** + + +-----+ + | num | + +-----+ + | 6 | + +-----+ + +**Explanation:** The single numbers are 1, 4, 5, and 6. Since 6 is the largest single number, we return it. + +**Example 2:** + +**Input:** MyNumbers table: + + +-----+ + | num | + +-----+ + | 8 | + | 8 | + | 7 | + | 7 | + | 3 | + | 3 | + | 3 | + +-----+ + +**Output:** + + +------+ + | num | + +------+ + | null | + +------+ + +**Explanation:** There are no single numbers in the input table so we return null. + +## Solution + +```sql +# Write your MySQL query statement below +SELECT MAX(num) AS num +FROM (SELECT num, COUNT(num) + FROM MyNumbers + GROUP BY num + HAVING COUNT(num) = 1) t +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0630_course_schedule_iii/readme.md b/src/main/kotlin/g0601_0700/s0630_course_schedule_iii/readme.md index b26f1e42..8774216b 100644 --- a/src/main/kotlin/g0601_0700/s0630_course_schedule_iii/readme.md +++ b/src/main/kotlin/g0601_0700/s0630_course_schedule_iii/readme.md @@ -73,7 +73,7 @@ class Solution { // Remove any course that is longer than current course // will work, but we remove the longest one with the help // of heap (pq). - if (!pq.isEmpty() && pq.peek() > course[0]) { + if (pq.isNotEmpty() && pq.peek() > course[0]) { time -= pq.poll() time += course[0] pq.offer(course[0]) diff --git a/src/main/kotlin/g0601_0700/s0636_exclusive_time_of_functions/readme.md b/src/main/kotlin/g0601_0700/s0636_exclusive_time_of_functions/readme.md index 85cde8ec..5cd9b17d 100644 --- a/src/main/kotlin/g0601_0700/s0636_exclusive_time_of_functions/readme.md +++ b/src/main/kotlin/g0601_0700/s0636_exclusive_time_of_functions/readme.md @@ -101,7 +101,7 @@ class Solution { val top = stack.pop() val executionTime = log.time - top.time + 1 result[top.id] += executionTime - top.waitingTime - if (!stack.isEmpty()) { + if (stack.isNotEmpty()) { stack.peek().waitingTime += executionTime } } diff --git a/src/main/kotlin/g0601_0700/s0662_maximum_width_of_binary_tree/readme.md b/src/main/kotlin/g0601_0700/s0662_maximum_width_of_binary_tree/readme.md index aa35a2f7..0b482dbb 100644 --- a/src/main/kotlin/g0601_0700/s0662_maximum_width_of_binary_tree/readme.md +++ b/src/main/kotlin/g0601_0700/s0662_maximum_width_of_binary_tree/readme.md @@ -81,7 +81,7 @@ class Solution { val q: Queue = LinkedList() q.add(Pair(root, 0)) var res = 1 - while (!q.isEmpty()) { + while (q.isNotEmpty()) { val qSize = q.size var lastIdx = 0 var firstIdx = 0 diff --git a/src/main/kotlin/g0601_0700/s0675_cut_off_trees_for_golf_event/readme.md b/src/main/kotlin/g0601_0700/s0675_cut_off_trees_for_golf_event/readme.md index dd7aab92..1a63def6 100644 --- a/src/main/kotlin/g0601_0700/s0675_cut_off_trees_for_golf_event/readme.md +++ b/src/main/kotlin/g0601_0700/s0675_cut_off_trees_for_golf_event/readme.md @@ -76,7 +76,7 @@ class Solution { } } var steps = 0 - while (!pq.isEmpty()) { + while (pq.isNotEmpty()) { val count = minSteps(forest, pq.poll()) if (count == -1) { return -1 @@ -97,7 +97,7 @@ class Solution { val q: Queue = LinkedList() q.add(intArrayOf(r, c)) visited[r][c] = true - while (!q.isEmpty()) { + while (q.isNotEmpty()) { val qSize = q.size for (i in 0 until qSize) { val curr = q.poll() diff --git a/src/main/kotlin/g0701_0800/s0735_asteroid_collision/readme.md b/src/main/kotlin/g0701_0800/s0735_asteroid_collision/readme.md index 02613d33..f8829bb9 100644 --- a/src/main/kotlin/g0701_0800/s0735_asteroid_collision/readme.md +++ b/src/main/kotlin/g0701_0800/s0735_asteroid_collision/readme.md @@ -54,14 +54,14 @@ class Solution { if (a > 0) { stack.addLast(a) } else { - if (!stack.isEmpty() && stack.peekLast() > 0) { + if (stack.isNotEmpty() && stack.peekLast() > 0) { if (stack.peekLast() == Math.abs(a)) { stack.pollLast() } else { - while (!stack.isEmpty() && stack.peekLast() > 0 && stack.peekLast() < Math.abs(a)) { + while (stack.isNotEmpty() && stack.peekLast() > 0 && stack.peekLast() < Math.abs(a)) { stack.pollLast() } - if (!stack.isEmpty() && stack.peekLast() > 0 && stack.peekLast() == Math.abs(a)) { + if (stack.isNotEmpty() && stack.peekLast() > 0 && stack.peekLast() == Math.abs(a)) { stack.pollLast() } else if (stack.isEmpty() || stack.peekLast() < 0) { stack.addLast(a) diff --git a/src/main/kotlin/g0701_0800/s0743_network_delay_time/readme.md b/src/main/kotlin/g0701_0800/s0743_network_delay_time/readme.md index 50c16d4e..a5c06917 100644 --- a/src/main/kotlin/g0701_0800/s0743_network_delay_time/readme.md +++ b/src/main/kotlin/g0701_0800/s0743_network_delay_time/readme.md @@ -61,7 +61,7 @@ class Solution { val spf: Queue = LinkedList() spf.add(k) visited[k] = true - while (!spf.isEmpty()) { + while (spf.isNotEmpty()) { val curr = spf.poll() visited[curr] = false for (i in 1..n) { diff --git a/src/main/kotlin/g0701_0800/s0752_open_the_lock/readme.md b/src/main/kotlin/g0701_0800/s0752_open_the_lock/readme.md index bb0e7ff6..7d9c9ff0 100644 --- a/src/main/kotlin/g0701_0800/s0752_open_the_lock/readme.md +++ b/src/main/kotlin/g0701_0800/s0752_open_the_lock/readme.md @@ -64,7 +64,7 @@ class Solution { queue.add(intArrayOf(0, 0)) visited.add(0) val numTarget = target.toInt() - while (!queue.isEmpty()) { + while (queue.isNotEmpty()) { val node = queue.poll() val number = node[0] val dist = node[1] diff --git a/src/main/kotlin/g0701_0800/s0761_special_binary_string/readme.md b/src/main/kotlin/g0701_0800/s0761_special_binary_string/readme.md index ef6f8752..c11d752e 100644 --- a/src/main/kotlin/g0701_0800/s0761_special_binary_string/readme.md +++ b/src/main/kotlin/g0701_0800/s0761_special_binary_string/readme.md @@ -70,7 +70,7 @@ class Solution { } } val ans = StringBuilder() - while (!pq.isEmpty()) { + while (pq.isNotEmpty()) { ans.append(pq.poll()) } if (ans.isEmpty()) { diff --git a/src/main/kotlin/g0701_0800/s0770_basic_calculator_iv/readme.md b/src/main/kotlin/g0701_0800/s0770_basic_calculator_iv/readme.md index ea8e4795..077ea9b6 100644 --- a/src/main/kotlin/g0701_0800/s0770_basic_calculator_iv/readme.md +++ b/src/main/kotlin/g0701_0800/s0770_basic_calculator_iv/readme.md @@ -225,14 +225,14 @@ internal class Solution { } ops.pop() } else if (a == '+' || a == '-' || a == '*') { - while (ops.size > 0 && getPriority(ops.peek()) >= getPriority(a)) { + while (ops.isNotEmpty() && getPriority(ops.peek()) >= getPriority(a)) { numS.add(helper(numS, ops)) } ops.add(a) } i++ } - while (ops.size > 0) { + while (ops.isNotEmpty()) { numS.add(helper(numS, ops)) } return numS.peek().evaluate(vars).toList() diff --git a/src/main/kotlin/g0701_0800/s0773_sliding_puzzle/readme.md b/src/main/kotlin/g0701_0800/s0773_sliding_puzzle/readme.md index 4451f715..1452b630 100644 --- a/src/main/kotlin/g0701_0800/s0773_sliding_puzzle/readme.md +++ b/src/main/kotlin/g0701_0800/s0773_sliding_puzzle/readme.md @@ -74,7 +74,7 @@ class Solution { val q: Queue = LinkedList() q.add(Node(sb.toString(), 0, y, x)) val dir = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1)) - while (!q.isEmpty()) { + while (q.isNotEmpty()) { val next = q.poll() val s = next.board if (!seen.contains(s)) { diff --git a/src/main/kotlin/g0701_0800/s0778_swim_in_rising_water/readme.md b/src/main/kotlin/g0701_0800/s0778_swim_in_rising_water/readme.md index f147784e..992b8565 100644 --- a/src/main/kotlin/g0701_0800/s0778_swim_in_rising_water/readme.md +++ b/src/main/kotlin/g0701_0800/s0778_swim_in_rising_water/readme.md @@ -94,7 +94,7 @@ class Solution { // we start from top left corner que.add(intArrayOf(0, 0)) visited[0][0] = true - while (!que.isEmpty()) { + while (que.isNotEmpty()) { // get current cell val cur = que.poll() val x = cur[0] diff --git a/src/main/kotlin/g0801_0900/s0815_bus_routes/readme.md b/src/main/kotlin/g0801_0900/s0815_bus_routes/readme.md index ab0749de..68aee966 100644 --- a/src/main/kotlin/g0801_0900/s0815_bus_routes/readme.md +++ b/src/main/kotlin/g0801_0900/s0815_bus_routes/readme.md @@ -55,7 +55,7 @@ class Solution { return -1 } var bus = 1 - while (!queue.isEmpty()) { + while (queue.isNotEmpty()) { val size = queue.size for (i in 0 until size) { val route = queue.poll() diff --git a/src/main/kotlin/g0801_0900/s0818_race_car/readme.md b/src/main/kotlin/g0801_0900/s0818_race_car/readme.md index 15d430b7..655d2b52 100644 --- a/src/main/kotlin/g0801_0900/s0818_race_car/readme.md +++ b/src/main/kotlin/g0801_0900/s0818_race_car/readme.md @@ -56,7 +56,7 @@ class Solution { fun racecar(target: Int): Int { val queue: Queue = LinkedList() queue.add(intArrayOf(0, 1, 0)) - while (!queue.isEmpty()) { + while (queue.isNotEmpty()) { val arr = queue.poll() if (arr[0] == target) { return arr[2] diff --git a/src/main/kotlin/g0801_0900/s0839_similar_string_groups/readme.md b/src/main/kotlin/g0801_0900/s0839_similar_string_groups/readme.md index ef90b893..1187ed6a 100644 --- a/src/main/kotlin/g0801_0900/s0839_similar_string_groups/readme.md +++ b/src/main/kotlin/g0801_0900/s0839_similar_string_groups/readme.md @@ -55,7 +55,7 @@ class Solution { val qu: Queue = LinkedList() qu.add(strs[i]) visited[i] = true - while (!qu.isEmpty()) { + while (qu.isNotEmpty()) { val s = qu.poll() for (j in strs.indices) { if (visited[j]) { diff --git a/src/main/kotlin/g0801_0900/s0841_keys_and_rooms/readme.md b/src/main/kotlin/g0801_0900/s0841_keys_and_rooms/readme.md index 4f0e378d..c0f81fa5 100644 --- a/src/main/kotlin/g0801_0900/s0841_keys_and_rooms/readme.md +++ b/src/main/kotlin/g0801_0900/s0841_keys_and_rooms/readme.md @@ -56,7 +56,7 @@ class Solution { val visited: MutableSet = HashSet() visited.add(0) val treeSet = TreeSet(rooms[0]) - while (!treeSet.isEmpty()) { + while (treeSet.isNotEmpty()) { val key = treeSet.pollFirst() if (!visited.add(key)) { continue diff --git a/src/main/kotlin/g0801_0900/s0847_shortest_path_visiting_all_nodes/readme.md b/src/main/kotlin/g0801_0900/s0847_shortest_path_visiting_all_nodes/readme.md index 6468a747..ccde864d 100644 --- a/src/main/kotlin/g0801_0900/s0847_shortest_path_visiting_all_nodes/readme.md +++ b/src/main/kotlin/g0801_0900/s0847_shortest_path_visiting_all_nodes/readme.md @@ -58,7 +58,7 @@ class Solution { target + 1 ) } - while (!q.isEmpty()) { + while (q.isNotEmpty()) { val size = q.size for (i in 0 until size) { val curr = q.poll() diff --git a/src/main/kotlin/g0801_0900/s0856_score_of_parentheses/readme.md b/src/main/kotlin/g0801_0900/s0856_score_of_parentheses/readme.md index a7ca3fa4..b5166836 100644 --- a/src/main/kotlin/g0801_0900/s0856_score_of_parentheses/readme.md +++ b/src/main/kotlin/g0801_0900/s0856_score_of_parentheses/readme.md @@ -59,7 +59,7 @@ class Solution { } } var score = 0 - while (!stack.isEmpty()) { + while (stack.isNotEmpty()) { score += stack.pop() } return score diff --git a/src/main/kotlin/g0801_0900/s0862_shortest_subarray_with_sum_at_least_k/readme.md b/src/main/kotlin/g0801_0900/s0862_shortest_subarray_with_sum_at_least_k/readme.md index 5a7cf95c..2d82df90 100644 --- a/src/main/kotlin/g0801_0900/s0862_shortest_subarray_with_sum_at_least_k/readme.md +++ b/src/main/kotlin/g0801_0900/s0862_shortest_subarray_with_sum_at_least_k/readme.md @@ -50,14 +50,14 @@ class Solution { for (i in 0 until n) { sum += nums[i].toLong() // Keep dq in incrementing order - while (!dq.isEmpty() && sum <= dq.peekLast().value) dq.removeLast() + while (dq.isNotEmpty() && sum <= dq.peekLast().value) dq.removeLast() // Add current sum and index dq.add(Pair(i, sum)) // Calculate your answer here if (sum >= k) ans = Math.min(ans, i + 1) // Check if Contraction is possible or not - while (!dq.isEmpty() && sum - dq.peekFirst().value >= k) { + while (dq.isNotEmpty() && sum - dq.peekFirst().value >= k) { ans = ans.coerceAtMost(i - dq.peekFirst().index) dq.removeFirst() } diff --git a/src/main/kotlin/g0801_0900/s0864_shortest_path_to_get_all_keys/readme.md b/src/main/kotlin/g0801_0900/s0864_shortest_path_to_get_all_keys/readme.md index da6c0098..725d6fa3 100644 --- a/src/main/kotlin/g0801_0900/s0864_shortest_path_to_get_all_keys/readme.md +++ b/src/main/kotlin/g0801_0900/s0864_shortest_path_to_get_all_keys/readme.md @@ -104,7 +104,7 @@ class Solution { // set initial position and state to true visited[q.peek()[0]][q.peek()[1]][0] = true var steps = 0 - while (!q.isEmpty()) { + while (q.isNotEmpty()) { // use size to make sure everything is on one level var size = q.size while (--size >= 0) { diff --git a/src/main/kotlin/g0801_0900/s0870_advantage_shuffle/readme.md b/src/main/kotlin/g0801_0900/s0870_advantage_shuffle/readme.md index 11e3092c..5b5f754a 100644 --- a/src/main/kotlin/g0801_0900/s0870_advantage_shuffle/readme.md +++ b/src/main/kotlin/g0801_0900/s0870_advantage_shuffle/readme.md @@ -45,7 +45,7 @@ class Solution { var left = 0 var right = n - 1 val res = IntArray(n) - while (!maxpq.isEmpty()) { + while (maxpq.isNotEmpty()) { val pair = maxpq.poll() val i = pair[0] val `val` = pair[1] diff --git a/src/main/kotlin/g0801_0900/s0882_reachable_nodes_in_subdivided_graph/readme.md b/src/main/kotlin/g0801_0900/s0882_reachable_nodes_in_subdivided_graph/readme.md index c25e15f3..3f95fdfd 100644 --- a/src/main/kotlin/g0801_0900/s0882_reachable_nodes_in_subdivided_graph/readme.md +++ b/src/main/kotlin/g0801_0900/s0882_reachable_nodes_in_subdivided_graph/readme.md @@ -63,7 +63,7 @@ class Solution { val minDis = IntArray(n) var res = 0 pQueue.add(intArrayOf(0, 0)) - while (pQueue.size > 0) { + while (pQueue.isNotEmpty()) { val poll = pQueue.poll() val node = poll[0] val dist = poll[1] diff --git a/src/main/kotlin/g0901_1000/s0994_rotting_oranges/readme.md b/src/main/kotlin/g0901_1000/s0994_rotting_oranges/readme.md index 6b745f4c..bc2bf000 100644 --- a/src/main/kotlin/g0901_1000/s0994_rotting_oranges/readme.md +++ b/src/main/kotlin/g0901_1000/s0994_rotting_oranges/readme.md @@ -49,12 +49,9 @@ Return _the minimum number of minutes that must elapse until no cell has a fresh ## Solution ```kotlin -import java.util.LinkedList -import java.util.Queue - class Solution { fun orangesRotting(grid: Array): Int { - val queue: Queue = LinkedList() + val queue = ArrayDeque() val row = grid.size val col: Int = grid[0].size var countActive = 0 @@ -79,7 +76,7 @@ class Solution { val size: Int = queue.size count += size for (i in 0 until size) { - val arr: IntArray = queue.poll() + val arr: IntArray = queue.removeFirst() for (j in 0..3) { val x = arr[0] + dx[j] val y = arr[1] + dy[j] diff --git a/src/main/kotlin/g1001_1100/s1013_partition_array_into_three_parts_with_equal_sum/readme.md b/src/main/kotlin/g1001_1100/s1013_partition_array_into_three_parts_with_equal_sum/readme.md new file mode 100644 index 00000000..46efbbfe --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1013_partition_array_into_three_parts_with_equal_sum/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) + +## 1013\. Partition Array Into Three Parts With Equal Sum + +Easy + +Given an array of integers `arr`, return `true` if we can partition the array into three **non-empty** parts with equal sums. + +Formally, we can partition the array if we can find indexes `i + 1 < j` with `(arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])` + +**Example 1:** + +**Input:** arr = [0,2,1,-6,6,-7,9,1,2,0,1] + +**Output:** true + +**Explanation:** 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1 + +**Example 2:** + +**Input:** arr = [0,2,1,-6,6,7,9,-1,2,0,1] + +**Output:** false + +**Example 3:** + +**Input:** arr = [3,3,6,5,-2,2,5,1,-9,4] + +**Output:** true + +**Explanation:** 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4 + +**Constraints:** + +* 3 <= arr.length <= 5 * 104 +* -104 <= arr[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun canThreePartsEqualSum(arr: IntArray): Boolean { + var sum = 0 + for (j in arr) { + sum += j + } + // 1. Base condition , the sum should be equally divided into 3 parts + if (sum % 3 != 0) { + return false + } + val eq = sum / 3 + // to keep track of occurences of sum in the sub array + var count = 0 + var temp = 0 + for (j in arr) { + // 2. Base / Break condition for loop , i.e. if the count is 2, + // i.e. sum has been achieved twice ( and there is more indices + // to go through since we are in the loop again ) then return true + if (count == 2) { + return true + } + // 3. Adding to temp array + temp += j + // 4. If sum is achieved , increase the count + if (temp == eq) { + count++ + // put temp=0 to start summing up from the next indices + temp = 0 + } + } + // 5. If the above conditoin fails , result is false + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1014_best_sightseeing_pair/readme.md b/src/main/kotlin/g1001_1100/s1014_best_sightseeing_pair/readme.md new file mode 100644 index 00000000..3816a254 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1014_best_sightseeing_pair/readme.md @@ -0,0 +1,47 @@ +[![](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) + +## 1014\. Best Sightseeing Pair + +Medium + +You are given an integer array `values` where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots `i` and `j` have a **distance** `j - i` between them. + +The score of a pair (`i < j`) of sightseeing spots is `values[i] + values[j] + i - j`: the sum of the values of the sightseeing spots, minus the distance between them. + +Return _the maximum score of a pair of sightseeing spots_. + +**Example 1:** + +**Input:** values = [8,1,5,2,6] + +**Output:** 11 + +**Explanation:** i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11 + +**Example 2:** + +**Input:** values = [1,2] + +**Output:** 2 + +**Constraints:** + +* 2 <= values.length <= 5 * 104 +* `1 <= values[i] <= 1000` + +## Solution + +```kotlin +class Solution { + fun maxScoreSightseeingPair(values: IntArray): Int { + var bestPrevious = values[0] + var maxSum = 0 + for (i in 1 until values.size) { + maxSum = maxSum.coerceAtLeast(bestPrevious + values[i] - i) + bestPrevious = bestPrevious.coerceAtLeast(values[i] + i) + } + return maxSum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1015_smallest_integer_divisible_by_k/readme.md b/src/main/kotlin/g1001_1100/s1015_smallest_integer_divisible_by_k/readme.md new file mode 100644 index 00000000..edb466e3 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1015_smallest_integer_divisible_by_k/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) + +## 1015\. Smallest Integer Divisible by K + +Medium + +Given a positive integer `k`, you need to find the **length** of the **smallest** positive integer `n` such that `n` is divisible by `k`, and `n` only contains the digit `1`. + +Return _the **length** of_ `n`. If there is no such `n`, return -1. + +**Note:** `n` may not fit in a 64-bit signed integer. + +**Example 1:** + +**Input:** k = 1 + +**Output:** 1 + +**Explanation:** The smallest answer is n = 1, which has length 1. + +**Example 2:** + +**Input:** k = 2 + +**Output:** -1 + +**Explanation:** There is no such positive integer n divisible by 2. + +**Example 3:** + +**Input:** k = 3 + +**Output:** 3 + +**Explanation:** The smallest answer is n = 111, which has length 3. + +**Constraints:** + +* 1 <= k <= 105 + +## Solution + +```kotlin +class Solution { + fun smallestRepunitDivByK(k: Int): Int { + var n = 0 + if (k % 2 == 0 || k % 5 == 0) { + return -1 + } + var i = 1 + while (i <= k) { + n = (n * 10 + 1) % k + if (n == 0) { + return i + } + i++ + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1016_binary_string_with_substrings_representing_1_to_n/readme.md b/src/main/kotlin/g1001_1100/s1016_binary_string_with_substrings_representing_1_to_n/readme.md new file mode 100644 index 00000000..d80b5cdf --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1016_binary_string_with_substrings_representing_1_to_n/readme.md @@ -0,0 +1,44 @@ +[![](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) + +## 1016\. Binary String With Substrings Representing 1 To N + +Medium + +Given a binary string `s` and a positive integer `n`, return `true` _if the binary representation of all the integers in the range_ `[1, n]` _are **substrings** of_ `s`_, or_ `false` _otherwise_. + +A **substring** is a contiguous sequence of characters within a string. + +**Example 1:** + +**Input:** s = "0110", n = 3 + +**Output:** true + +**Example 2:** + +**Input:** s = "0110", n = 4 + +**Output:** false + +**Constraints:** + +* `1 <= s.length <= 1000` +* `s[i]` is either `'0'` or `'1'`. +* 1 <= n <= 109 + +## Solution + +```kotlin +class Solution { + fun queryString(s: String, n: Int): Boolean { + for (i in 1..n) { + val str = Integer.toBinaryString(i) + if (!s.contains(str)) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1017_convert_to_base_2/readme.md b/src/main/kotlin/g1001_1100/s1017_convert_to_base_2/readme.md new file mode 100644 index 00000000..c64556fa --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1017_convert_to_base_2/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) + +## 1017\. Convert to Base -2 + +Medium + +Given an integer `n`, return _a binary string representing its representation in base_ `-2`. + +**Note** that the returned string should not have leading zeros unless the string is `"0"`. + +**Example 1:** + +**Input:** n = 2 + +**Output:** "110" **Explantion:** (-2)2 + (-2)1 = 2 + +**Example 2:** + +**Input:** n = 3 + +**Output:** "111" **Explantion:** (-2)2 + (-2)1 + (-2)0 = 3 + +**Example 3:** + +**Input:** n = 4 + +**Output:** "100" **Explantion:** (-2)2 = 4 + +**Constraints:** + +* 0 <= n <= 109 + +## Solution + +```kotlin +class Solution { + fun baseNeg2(n: Int): String { + val sb = StringBuilder(Integer.toBinaryString(n)) + sb.reverse() + var carry = 0 + var sum: Int + var pos = 0 + while (pos < sb.length) { + sum = carry + sb[pos].code - '0'.code + sb.setCharAt(pos, if (sum % 2 == 0) '0' else '1') + carry = sum / 2 + if (pos % 2 == 1 && sb[pos] == '1') { + carry += 1 + } + pos++ + if (pos >= sb.length && carry > 0) { + sb.append(Integer.toBinaryString(carry)) + carry = 0 + } + } + return sb.reverse().toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1018_binary_prefix_divisible_by_5/readme.md b/src/main/kotlin/g1001_1100/s1018_binary_prefix_divisible_by_5/readme.md new file mode 100644 index 00000000..7cb93527 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1018_binary_prefix_divisible_by_5/readme.md @@ -0,0 +1,49 @@ +[![](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) + +## 1018\. Binary Prefix Divisible By 5 + +Easy + +You are given a binary array `nums` (**0-indexed**). + +We define xi as the number whose binary representation is the subarray `nums[0..i]` (from most-significant-bit to least-significant-bit). + +* For example, if `nums = [1,0,1]`, then x0 = 1, x1 = 2, and x2 = 5. + +Return _an array of booleans_ `answer` _where_ `answer[i]` _is_ `true` _if_ xi _is divisible by_ `5`. + +**Example 1:** + +**Input:** nums = [0,1,1] + +**Output:** [true,false,false] + +**Explanation:** The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. Only the first number is divisible by 5, so answer[0] is true. + +**Example 2:** + +**Input:** nums = [1,1,1] + +**Output:** [false,false,false] + +**Constraints:** + +* 1 <= nums.length <= 105 +* `nums[i]` is either `0` or `1`. + +## Solution + +```kotlin +class Solution { + fun prefixesDivBy5(nums: IntArray): List { + val result: MutableList = ArrayList(nums.size) + var remainder = 0 + for (j in nums) { + remainder = (j + (remainder shl 1)) % 5 + result.add(remainder == 0) + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1019_next_greater_node_in_linked_list/readme.md b/src/main/kotlin/g1001_1100/s1019_next_greater_node_in_linked_list/readme.md new file mode 100644 index 00000000..c2cd7628 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1019_next_greater_node_in_linked_list/readme.md @@ -0,0 +1,105 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1019\. Next Greater Node In Linked List + +Medium + +You are given the `head` of a linked list with `n` nodes. + +For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it. + +Return an integer array `answer` where `answer[i]` is the value of the next greater node of the ith node (**1-indexed**). If the ith node does not have a next greater node, set `answer[i] = 0`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/08/05/linkedlistnext1.jpg) + +**Input:** head = [2,1,5] + +**Output:** [5,5,0] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/08/05/linkedlistnext2.jpg) + +**Input:** head = [2,7,4,3,5] + +**Output:** [7,0,5,5,0] + +**Constraints:** + +* The number of nodes in the list is `n`. +* 1 <= n <= 104 +* 1 <= Node.val <= 109 + +## Solution + +```kotlin +import com_github_leetcode.ListNode + +/* + * Example: + * var li = ListNode(5) + * var v = li.`val` + * Definition for singly-linked list. + * class ListNode(var `val`: Int) { + * var next: ListNode? = null + * } + */ +@Suppress("NAME_SHADOWING") +class Solution { + fun nextLargerNodes(head: ListNode?): IntArray { + var head = head + val len = length(head) + var i = 0 + val arr = IntArray(len) + val idx = IntArray(len) + while (head != null) { + arr[i] = head.`val` + head = head.next + i++ + } + hlp(arr, idx, 0) + i = 0 + while (i < idx.size) { + val j = idx[i] + if (j != -1) { + arr[i] = arr[j] + } else { + arr[i] = 0 + } + i++ + } + arr[i - 1] = 0 + return arr + } + + private fun hlp(arr: IntArray, idx: IntArray, i: Int) { + if (i == arr.size - 1) { + idx[i] = -1 + return + } + hlp(arr, idx, i + 1) + var j = i + 1 + while (j != -1 && arr[i] >= arr[j]) { + j = idx[j] + } + if (j != -1 && arr[i] >= arr[j]) { + idx[i] = -1 + } else { + idx[i] = j + } + } + + private fun length(head: ListNode?): Int { + var head = head + var len = 0 + while (head != null) { + head = head.next + len++ + } + return len + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1020_number_of_enclaves/readme.md b/src/main/kotlin/g1001_1100/s1020_number_of_enclaves/readme.md new file mode 100644 index 00000000..bdc18953 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1020_number_of_enclaves/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) + +## 1020\. Number of Enclaves + +Medium + +You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell. + +A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`. + +Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/18/enclaves1.jpg) + +**Input:** grid = \[\[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]] + +**Output:** 3 + +**Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/02/18/enclaves2.jpg) + +**Input:** grid = \[\[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]] + +**Output:** 0 + +**Explanation:** All 1s are either on the boundary or can reach the boundary. + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `1 <= m, n <= 500` +* `grid[i][j]` is either `0` or `1`. + +## Solution + +```kotlin +class Solution { + fun numEnclaves(grid: Array): Int { + val visited = Array(grid.size) { + BooleanArray( + grid[0].size + ) + } + for (i in grid.indices) { + for (j in grid[0].indices) { + if (grid[i][j] == 1 && (i == 0 || j == 0 || i == grid.size - 1 || j == grid[0].size - 1)) { + move(grid, i, j, visited) + } + } + } + var count = 0 + for (i in 1 until visited.size - 1) { + for (j in 1 until visited[0].size - 1) { + if (!visited[i][j] && grid[i][j] == 1) count++ + } + } + return count + } + + companion object { + fun move(g: Array, i: Int, j: Int, b: Array) { + if (i < 0 || j < 0 || i == g.size || j == g[0].size || g[i][j] == 0 || b[i][j]) return + b[i][j] = true + move(g, i + 1, j, b) + move(g, i - 1, j, b) + move(g, i, j - 1, b) + move(g, i, j + 1, b) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1021_remove_outermost_parentheses/readme.md b/src/main/kotlin/g1001_1100/s1021_remove_outermost_parentheses/readme.md new file mode 100644 index 00000000..79b5f04d --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1021_remove_outermost_parentheses/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) + +## 1021\. Remove Outermost Parentheses + +Easy + +A valid parentheses string is either empty `""`, `"(" + A + ")"`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation. + +* For example, `""`, `"()"`, `"(())()"`, and `"(()(()))"` are all valid parentheses strings. + +A valid parentheses string `s` is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`, with `A` and `B` nonempty valid parentheses strings. + +Given a valid parentheses string `s`, consider its primitive decomposition: s = P1 + P2 + ... + Pk, where Pi are primitive valid parentheses strings. + +Return `s` _after removing the outermost parentheses of every primitive string in the primitive decomposition of_ `s`. + +**Example 1:** + +**Input:** s = "(()())(())" + +**Output:** "()()()" + +**Explanation:** The input string is "(()())(())", with primitive decomposition "(()())" + "(())". After removing outer parentheses of each part, this is "()()" + "()" = "()()()". + +**Example 2:** + +**Input:** s = "(()())(())(()(()))" + +**Output:** "()()()()(())" + +**Explanation:** The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))". After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())". + +**Example 3:** + +**Input:** s = "()()" + +**Output:** "" + +**Explanation:** The input string is "()()", with primitive decomposition "()" + "()". After removing outer parentheses of each part, this is "" + "" = "". + +**Constraints:** + +* 1 <= s.length <= 105 +* `s[i]` is either `'('` or `')'`. +* `s` is a valid parentheses string. + +## Solution + +```kotlin +class Solution { + fun removeOuterParentheses(s: String): String { + val primitives: MutableList = ArrayList() + var i = 1 + while (i < s.length) { + val initialI = i - 1 + var left = 1 + while (i < s.length && left > 0) { + if (s[i] == '(') { + left++ + } else { + left-- + } + i++ + } + primitives.add(s.substring(initialI, i)) + i++ + } + val sb = StringBuilder() + for (primitive in primitives) { + sb.append(primitive, 1, primitive.length - 1) + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1022_sum_of_root_to_leaf_binary_numbers/readme.md b/src/main/kotlin/g1001_1100/s1022_sum_of_root_to_leaf_binary_numbers/readme.md new file mode 100644 index 00000000..dde09363 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1022_sum_of_root_to_leaf_binary_numbers/readme.md @@ -0,0 +1,82 @@ +[![](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) + +## 1022\. Sum of Root To Leaf Binary Numbers + +Easy + +You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit. + +* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`. + +For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_. + +The test cases are generated so that the answer fits in a **32-bits** integer. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/04/04/sum-of-root-to-leaf-binary-numbers.png) + +**Input:** root = [1,0,1,0,1,0,1] + +**Output:** 22 + +**Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 + +**Example 2:** + +**Input:** root = [0] + +**Output:** 0 + +**Constraints:** + +* The number of nodes in the tree is in the range `[1, 1000]`. +* `Node.val` is `0` or `1`. + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun sumRootToLeaf(root: TreeNode?): Int { + val paths: MutableList> = ArrayList() + dfs(root, paths, ArrayList()) + var sum = 0 + for (list in paths) { + var num = 0 + for (i in list) { + num = (num shl 1) + i + } + sum += num + } + return sum + } + + private fun dfs(root: TreeNode?, paths: MutableList>, path: MutableList) { + path.add(root!!.`val`) + if (root.left != null) { + dfs(root.left!!, paths, path) + path.removeAt(path.size - 1) + } + if (root.right != null) { + dfs(root.right!!, paths, path) + path.removeAt(path.size - 1) + } + if (root.left == null && root.right == null) { + paths.add(ArrayList(path)) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1023_camelcase_matching/readme.md b/src/main/kotlin/g1001_1100/s1023_camelcase_matching/readme.md new file mode 100644 index 00000000..6ef381f8 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1023_camelcase_matching/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) + +## 1023\. Camelcase Matching + +Medium + +Given an array of strings `queries` and a string `pattern`, return a boolean array `answer` where `answer[i]` is `true` if `queries[i]` matches `pattern`, and `false` otherwise. + +A query word `queries[i]` matches `pattern` if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters. + +**Example 1:** + +**Input:** queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB" + +**Output:** [true,false,true,true,false] + +**Explanation:** "FooBar" can be generated like this "F" + "oo" + "B" + "ar". "FootBall" can be generated like this "F" + "oot" + "B" + "all". "FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer". + +**Example 2:** + +**Input:** queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa" + +**Output:** [true,false,true,false,false] + +**Explanation:** "FooBar" can be generated like this "Fo" + "o" + "Ba" + "r". "FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll". + +**Example 3:** + +**Input:** queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT" + +**Output:** [false,true,false,false,false] + +**Explanation:** "FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est". + +**Constraints:** + +* `1 <= pattern.length, queries.length <= 100` +* `1 <= queries[i].length <= 100` +* `queries[i]` and `pattern` consist of English letters. + +## Solution + +```kotlin +import java.util.LinkedList + +class Solution { + fun camelMatch(queries: Array, pattern: String): List { + val ret: MutableList = LinkedList() + for (query in queries) { + ret.add(check(query, pattern)) + } + return ret + } + + private fun check(query: String, pattern: String): Boolean { + val patternLen = pattern.length + var patternPos = 0 + var uppercaseCount = 0 + for (element in query) { + val c = element + if (Character.isUpperCase(c)) { + if (patternPos < patternLen && c != pattern[patternPos]) { + return false + } + uppercaseCount++ + if (uppercaseCount > patternLen) { + return false + } + patternPos++ + } else { + if (patternPos < patternLen && c == pattern[patternPos]) { + patternPos++ + } + } + } + return patternPos == patternLen + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1024_video_stitching/readme.md b/src/main/kotlin/g1001_1100/s1024_video_stitching/readme.md new file mode 100644 index 00000000..7eed100b --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1024_video_stitching/readme.md @@ -0,0 +1,83 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1024\. Video Stitching + +Medium + +You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths. + +Each video clip is described by an array `clips` where clips[i] = [starti, endi] indicates that the ith clip started at starti and ended at endi. + +We can cut these clips into segments freely. + +* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`. + +Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`. + +**Example 1:** + +**Input:** clips = \[\[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10 + +**Output:** 3 + +**Explanation:** We take the clips [0,2], [8,10], [1,9]; a total of 3 clips. + +Then, we can reconstruct the sporting event as follows: + +We cut [1,9] into segments [1,2] + [2,8] + [8,9]. + +Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10]. + +**Example 2:** + +**Input:** clips = \[\[0,1],[1,2]], time = 5 + +**Output:** -1 + +**Explanation:** We cannot cover [0,5] with only [0,1] and [1,2]. + +**Example 3:** + +**Input:** clips = \[\[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9 + +**Output:** 3 + +**Explanation:** We can take clips [0,4], [4,7], and [6,9]. + +**Constraints:** + +* `1 <= clips.length <= 100` +* 0 <= starti <= endi <= 100 +* `1 <= time <= 100` + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun videoStitching(clips: Array, time: Int): Int { + Arrays.sort(clips) { a: IntArray, b: IntArray -> + if (a[0] == b[0] + ) a[1] - b[1] else a[0] - b[0] + } + var count = 0 + var covered = 0 + var i = 0 + var start = 0 + while (start < time) { + while (i < clips.size && clips[i][0] <= start) { + covered = covered.coerceAtLeast(clips[i][1]) + i++ + } + if (start == covered) { + return -1 + } + count++ + start = covered + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1025_divisor_game/readme.md b/src/main/kotlin/g1001_1100/s1025_divisor_game/readme.md new file mode 100644 index 00000000..08da01eb --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1025_divisor_game/readme.md @@ -0,0 +1,47 @@ +[![](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) + +## 1025\. Divisor Game + +Easy + +Alice and Bob take turns playing a game, with Alice starting first. + +Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of: + +* Choosing any `x` with `0 < x < n` and `n % x == 0`. +* Replacing the number `n` on the chalkboard with `n - x`. + +Also, if a player cannot make a move, they lose the game. + +Return `true` _if and only if Alice wins the game, assuming both players play optimally_. + +**Example 1:** + +**Input:** n = 2 + +**Output:** true + +**Explanation:** Alice chooses 1, and Bob has no more moves. + +**Example 2:** + +**Input:** n = 3 + +**Output:** false + +**Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves. + +**Constraints:** + +* `1 <= n <= 1000` + +## Solution + +```kotlin +class Solution { + fun divisorGame(n: Int): Boolean { + return n % 2 == 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1026_maximum_difference_between_node_and_ancestor/readme.md b/src/main/kotlin/g1001_1100/s1026_maximum_difference_between_node_and_ancestor/readme.md new file mode 100644 index 00000000..a3422e0f --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1026_maximum_difference_between_node_and_ancestor/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) + +## 1026\. Maximum Difference Between Node and Ancestor + +Medium + +Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`. + +A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/09/tmp-tree.jpg) + +**Input:** root = [8,3,10,1,6,null,14,null,null,4,7,13] + +**Output:** 7 + +**Explanation:** We have various ancestor-node differences, some of which are given below : + +\|8 - 3\| = 5 + +\|3 - 7\| = 4 + +\|8 - 1\| = 7 + +\|10 - 13\| = 3 + +Among all possible differences, the maximum value of 7 is obtained by \|8 - 1\| = 7. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/11/09/tmp-tree-1.jpg) + +**Input:** root = [1,null,2,null,0,3] + +**Output:** 3 + +**Constraints:** + +* The number of nodes in the tree is in the range `[2, 5000]`. +* 0 <= Node.val <= 105 + +## Solution + +```kotlin +import com_github_leetcode.TreeNode +import kotlin.math.abs + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private var max = 0 + fun maxAncestorDiff(root: TreeNode?): Int { + traverse(root, -1, -1) + return max + } + + private fun traverse(root: TreeNode?, maxAncestor: Int, minAncestor: Int) { + if (root == null) { + return + } + if (maxAncestor == -1) { + traverse(root.left, root.`val`, root.`val`) + traverse(root.right, root.`val`, root.`val`) + } + if (maxAncestor != -1) { + max = max.coerceAtLeast(abs(maxAncestor - root.`val`)) + max = max.coerceAtLeast(abs(minAncestor - root.`val`)) + traverse(root.left, root.`val`.coerceAtLeast(maxAncestor), root.`val`.coerceAtMost(minAncestor)) + traverse(root.right, root.`val`.coerceAtLeast(maxAncestor), root.`val`.coerceAtMost(minAncestor)) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1027_longest_arithmetic_subsequence/readme.md b/src/main/kotlin/g1001_1100/s1027_longest_arithmetic_subsequence/readme.md new file mode 100644 index 00000000..104ed748 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1027_longest_arithmetic_subsequence/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) + +## 1027\. Longest Arithmetic Subsequence + +Medium + +Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`. + +**Note** that: + +* A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. +* A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`). + +**Example 1:** + +**Input:** nums = [3,6,9,12] + +**Output:** 4 **Explanation: ** The whole array is an arithmetic sequence with steps of length = 3. + +**Example 2:** + +**Input:** nums = [9,4,7,2,10] + +**Output:** 3 **Explanation: ** The longest arithmetic subsequence is [4,7,10]. + +**Example 3:** + +**Input:** nums = [20,1,15,3,10,5,8] + +**Output:** 4 **Explanation: ** The longest arithmetic subsequence is [20,15,10,5]. + +**Constraints:** + +* `2 <= nums.length <= 1000` +* `0 <= nums[i] <= 500` + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun longestArithSeqLength(nums: IntArray): Int { + val max = maxElement(nums) + val min = minElement(nums) + val diff = max - min + val n = nums.size + val dp = Array(n) { IntArray(2 * diff + 2) } + for (d in dp) { + Arrays.fill(d, 1) + } + var ans = 0 + for (i in 0 until n) { + for (j in i - 1 downTo 0) { + val difference = nums[i] - nums[j] + diff + val temp = dp[j][difference] + dp[i][difference] = Math.max(dp[i][difference], temp + 1) + if (ans < dp[i][difference]) { + ans = dp[i][difference] + } + } + } + return ans + } + + private fun maxElement(arr: IntArray): Int { + var max = Int.MIN_VALUE + for (e in arr) { + if (max < e) { + max = e + } + } + return max + } + + private fun minElement(arr: IntArray): Int { + var min = Int.MAX_VALUE + for (e in arr) { + if (min > e) { + min = e + } + } + return min + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1028_recover_a_tree_from_preorder_traversal/readme.md b/src/main/kotlin/g1001_1100/s1028_recover_a_tree_from_preorder_traversal/readme.md new file mode 100644 index 00000000..4760b794 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1028_recover_a_tree_from_preorder_traversal/readme.md @@ -0,0 +1,93 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1028\. Recover a Tree From Preorder Traversal + +Hard + +We run a preorder depth-first search (DFS) on the `root` of a binary tree. + +At each node in this traversal, we output `D` dashes (where `D` is the depth of this node), then we output the value of this node. If the depth of a node is `D`, the depth of its immediate child is `D + 1`. The depth of the `root` node is `0`. + +If a node has only one child, that child is guaranteed to be **the left child**. + +Given the output `traversal` of this traversal, recover the tree and return _its_ `root`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/04/08/recover-a-tree-from-preorder-traversal.png) + +**Input:** traversal = "1-2--3--4-5--6--7" + +**Output:** [1,2,5,3,4,6,7] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2019/04/11/screen-shot-2019-04-10-at-114101-pm.png) + +**Input:** traversal = "1-2--3---4-5--6---7" + +**Output:** [1,2,5,3,null,6,null,4,null,7] + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2019/04/11/screen-shot-2019-04-10-at-114955-pm.png) + +**Input:** traversal = "1-401--349---90--88" + +**Output:** [1,401,null,349,88,90] + +**Constraints:** + +* The number of nodes in the original tree is in the range `[1, 1000]`. +* 1 <= Node.val <= 109 + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private var ptr = 0 + + fun recoverFromPreorder(traversal: String): TreeNode? { + return find(traversal, 0) + } + + private fun find(traversal: String, level: Int): TreeNode? { + if (ptr == traversal.length) { + return null + } + var i = ptr + var count = 0 + while (traversal[i] == '-') { + count++ + i++ + } + return if (count == level) { + val start = i + while (i < traversal.length && traversal[i] != '-') { + i++ + } + val `val` = traversal.substring(start, i).toInt() + ptr = i + val root = TreeNode(`val`) + root.left = find(traversal, level + 1) + root.right = find(traversal, level + 1) + root + } else { + null + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1029_two_city_scheduling/readme.md b/src/main/kotlin/g1001_1100/s1029_two_city_scheduling/readme.md new file mode 100644 index 00000000..cc22f8e7 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1029_two_city_scheduling/readme.md @@ -0,0 +1,70 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1029\. Two City Scheduling + +Medium + +A company is planning to interview `2n` people. Given the array `costs` where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city `a` is aCosti, and the cost of flying the ith person to city `b` is bCosti. + +Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city. + +**Example 1:** + +**Input:** costs = \[\[10,20],[30,200],[400,50],[30,20]] + +**Output:** 110 + +**Explanation:** + +The first person goes to city A for a cost of 10. + +The second person goes to city A for a cost of 30. + +The third person goes to city B for a cost of 50. + +The fourth person goes to city B for a cost of 20. + +The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. + +**Example 2:** + +**Input:** costs = \[\[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]] + +**Output:** 1859 + +**Example 3:** + +**Input:** costs = \[\[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]] + +**Output:** 3086 + +**Constraints:** + +* `2 * n == costs.length` +* `2 <= costs.length <= 100` +* `costs.length` is even. +* 1 <= aCosti, bCosti <= 1000 + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun twoCitySchedCost(costs: Array): Int { + Arrays.sort(costs) { a: IntArray, b: IntArray -> + a[0] - a[1] - (b[0] - b[1]) + } + var cost = 0 + for (i in costs.indices) { + cost += if (i < costs.size / 2) { + costs[i][0] + } else { + costs[i][1] + } + } + return cost + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1030_matrix_cells_in_distance_order/readme.md b/src/main/kotlin/g1001_1100/s1030_matrix_cells_in_distance_order/readme.md new file mode 100644 index 00000000..06c44e8a --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1030_matrix_cells_in_distance_order/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1030\. Matrix Cells in Distance Order + +Easy + +You are given four integers `row`, `cols`, `rCenter`, and `cCenter`. There is a `rows x cols` matrix and you are on the cell with the coordinates `(rCenter, cCenter)`. + +Return _the coordinates of all cells in the matrix, sorted by their **distance** from_ `(rCenter, cCenter)` _from the smallest distance to the largest distance_. You may return the answer in **any order** that satisfies this condition. + +The **distance** between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|. + +**Example 1:** + +**Input:** rows = 1, cols = 2, rCenter = 0, cCenter = 0 + +**Output:** [[0,0],[0,1]] + +**Explanation:** The distances from (0, 0) to other cells are: [0,1] + +**Example 2:** + +**Input:** rows = 2, cols = 2, rCenter = 0, cCenter = 1 + +**Output:** [[0,1],[0,0],[1,1],[1,0]] + +**Explanation:** The distances from (0, 1) to other cells are: [0,1,1,2] The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct. + +**Example 3:** + +**Input:** rows = 2, cols = 3, rCenter = 1, cCenter = 2 + +**Output:** [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]] + +**Explanation:** The distances from (1, 2) to other cells are: [0,1,1,2,2,3] There are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]]. + +**Constraints:** + +* `1 <= rows, cols <= 100` +* `0 <= rCenter < rows` +* `0 <= cCenter < cols` + +## Solution + +```kotlin +import java.util.TreeMap +import kotlin.math.abs + +class Solution { + fun allCellsDistOrder(rows: Int, cols: Int, rCenter: Int, cCenter: Int): Array { + val map: MutableMap> = TreeMap() + for (i in 0 until rows) { + for (j in 0 until cols) { + map.computeIfAbsent( + abs(i - rCenter) + abs(j - cCenter) + ) { ArrayList() } + .add(intArrayOf(i, j)) + } + } + val res = arrayOfNulls(rows * cols) + var i = 0 + for (list in map.values) { + for (each in list) { + res[i++] = each + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1031_maximum_sum_of_two_non_overlapping_subarrays/readme.md b/src/main/kotlin/g1001_1100/s1031_maximum_sum_of_two_non_overlapping_subarrays/readme.md new file mode 100644 index 00000000..3ff561ec --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1031_maximum_sum_of_two_non_overlapping_subarrays/readme.md @@ -0,0 +1,105 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1031\. Maximum Sum of Two Non-Overlapping Subarrays + +Medium + +Given an integer array `nums` and two integers `firstLen` and `secondLen`, return _the maximum sum of elements in two non-overlapping **subarrays** with lengths_ `firstLen` _and_ `secondLen`. + +The array with length `firstLen` could occur before or after the array with length `secondLen`, but they have to be non-overlapping. + +A **subarray** is a **contiguous** part of an array. + +**Example 1:** + +**Input:** nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2 + +**Output:** 20 + +**Explanation:** One choice of subarrays is [9] with length 1, and [6,5] with length 2. + +**Example 2:** + +**Input:** nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2 + +**Output:** 29 + +**Explanation:** One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2. + +**Example 3:** + +**Input:** nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3 + +**Output:** 31 + +**Explanation:** One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3. + +**Constraints:** + +* `1 <= firstLen, secondLen <= 1000` +* `2 <= firstLen + secondLen <= 1000` +* `firstLen + secondLen <= nums.length <= 1000` +* `0 <= nums[i] <= 1000` + +## Solution + +```kotlin +class Solution { + fun maxSumTwoNoOverlap(nums: IntArray, firstLen: Int, secondLen: Int): Int { + val firstLenSum = getFirstLenSums(nums, firstLen) + return getMaxLenSum(nums, secondLen, firstLenSum) + } + + private fun getMaxLenSum(nums: IntArray, secondLen: Int, firstLenSum: Array): Int { + var maxSum = 0 + var currentSum = 0 + var onRight: Int + for (i in 0 until secondLen) { + currentSum += nums[i] + } + onRight = firstLenSum[1][secondLen] + maxSum = maxSum.coerceAtLeast(currentSum + onRight) + var i = 1 + var j = secondLen + while (j < nums.size) { + currentSum = currentSum - nums[i - 1] + nums[j] + onRight = if (j < nums.size - 1) firstLenSum[1][j + 1] else 0 + maxSum = maxSum.coerceAtLeast(currentSum + firstLenSum[0][i - 1].coerceAtLeast(onRight)) + i++ + j++ + } + return maxSum + } + + private fun getFirstLenSums(nums: IntArray, windowSize: Int): Array { + // sum[0] - maximum from left to right, sum[1] - max from right to left. + val sum = Array(2) { IntArray(nums.size) } + var currentLeftSum = 0 + var currentRightSum = 0 + run { + var i = 0 + var j = nums.size - 1 + while (i < windowSize) { + currentLeftSum += nums[i] + currentRightSum += nums[j] + i++ + j-- + } + } + sum[0][windowSize - 1] = currentLeftSum + sum[1][nums.size - windowSize] = currentRightSum + var i = windowSize + var j = nums.size - windowSize - 1 + while (i < nums.size) { + currentLeftSum = currentLeftSum - nums[i - windowSize] + nums[i] + currentRightSum = currentRightSum - nums[j + windowSize] + nums[j] + sum[0][i] = sum[0][i - 1].coerceAtLeast(currentLeftSum) + sum[1][j] = sum[1][j + 1].coerceAtLeast(currentRightSum) + i++ + j-- + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1032_stream_of_characters/readme.md b/src/main/kotlin/g1001_1100/s1032_stream_of_characters/readme.md new file mode 100644 index 00000000..1366b80e --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1032_stream_of_characters/readme.md @@ -0,0 +1,98 @@ +[![](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) + +## 1032\. Stream of Characters + +Hard + +Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings `words`. + +For example, if `words = ["abc", "xyz"]` and the stream added the four characters (one by one) `'a'`, `'x'`, `'y'`, and `'z'`, your algorithm should detect that the suffix `"xyz"` of the characters `"axyz"` matches `"xyz"` from `words`. + +Implement the `StreamChecker` class: + +* `StreamChecker(String[] words)` Initializes the object with the strings array `words`. +* `boolean query(char letter)` Accepts a new character from the stream and returns `true` if any non-empty suffix from the stream forms a word that is in `words`. + +**Example 1:** + +**Input** ["StreamChecker", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query"] [[["cd", "f", "kl"]], ["a"], ["b"], ["c"], ["d"], ["e"], ["f"], ["g"], ["h"], ["i"], ["j"], ["k"], ["l"]] + +**Output:** [null, false, false, false, true, false, true, false, false, false, false, false, true] + +**Explanation:** + + StreamChecker streamChecker = new StreamChecker(["cd", "f", "kl"]); + streamChecker.query("a"); // return False + streamChecker.query("b"); // return False + streamChecker.query("c"); // return False + streamChecker.query("d"); // return True, because 'cd' is in the wordlist + streamChecker.query("e"); // return False + streamChecker.query("f"); // return True, because 'f' is in the wordlist + streamChecker.query("g"); // return False + streamChecker.query("h"); // return False + streamChecker.query("i"); // return False + streamChecker.query("j"); // return False + streamChecker.query("k"); // return False + streamChecker.query("l"); // return True, because 'kl' is in the wordlist + +**Constraints:** + +* `1 <= words.length <= 2000` +* `1 <= words[i].length <= 2000` +* `words[i]` consists of lowercase English letters. +* `letter` is a lowercase English letter. +* At most 4 * 104 calls will be made to query. + +## Solution + +```kotlin +class StreamChecker(words: Array) { + internal class Node { + var child: Array = arrayOfNulls(26) + var isEnd = false + } + + private val sb: StringBuilder = StringBuilder() + private val root: Node = Node() + fun insert(s: String) { + var curr: Node? = root + for (i in s.length - 1 downTo 0) { + val c = s[i] + if (curr!!.child[c.code - 'a'.code] == null) { + curr.child[c.code - 'a'.code] = Node() + } + curr = curr.child[c.code - 'a'.code] + } + curr!!.isEnd = true + } + + init { + for (s in words) { + insert(s) + } + } + + fun query(letter: Char): Boolean { + sb.append(letter) + var curr: Node? = root + for (i in sb.length - 1 downTo 0) { + val c = sb[i] + if (curr!!.child[c.code - 'a'.code] == null) { + return false + } + if (curr.child[c.code - 'a'.code]!!.isEnd) { + return true + } + curr = curr.child[c.code - 'a'.code] + } + return false + } +} + +/* + * Your StreamChecker object will be instantiated and called as such: + * var obj = StreamChecker(words) + * var param_1 = obj.query(letter) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1033_moving_stones_until_consecutive/readme.md b/src/main/kotlin/g1001_1100/s1033_moving_stones_until_consecutive/readme.md new file mode 100644 index 00000000..6d4c67a5 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1033_moving_stones_until_consecutive/readme.md @@ -0,0 +1,73 @@ +[![](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) + +## 1033\. Moving Stones Until Consecutive + +Medium + +There are three stones in different positions on the X-axis. You are given three integers `a`, `b`, and `c`, the positions of the stones. + +In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions `x`, `y`, and `z` with `x < y < z`. You pick up the stone at either position `x` or position `z`, and move that stone to an integer position `k`, with `x < k < z` and `k != y`. + +The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). + +Return _an integer array_ `answer` _of length_ `2` _where_: + +* `answer[0]` _is the minimum number of moves you can play, and_ +* `answer[1]` _is the maximum number of moves you can play_. + +**Example 1:** + +**Input:** a = 1, b = 2, c = 5 + +**Output:** [1,2] + +**Explanation:** Move the stone from 5 to 3, or move the stone from 5 to 4 to 3. + +**Example 2:** + +**Input:** a = 4, b = 3, c = 2 + +**Output:** [0,0] + +**Explanation:** We cannot make any moves. + +**Example 3:** + +**Input:** a = 3, b = 5, c = 1 + +**Output:** [1,2] + +**Explanation:** Move the stone from 1 to 4; or move the stone from 1 to 2 to 4. + +**Constraints:** + +* `1 <= a, b, c <= 100` +* `a`, `b`, and `c` have different values. + +## Solution + +```kotlin +class Solution { + private fun minMoves(x: Int, y: Int, z: Int): Int { + if (x + 1 == y && y + 1 == z) { + return 0 + } + return if (y - x <= 2 || z - y <= 2) { + 1 + } else 2 + } + + private fun maxMoves(x: Int, z: Int): Int { + return z - x - 2 + } + + fun numMovesStones(a: Int, b: Int, c: Int): IntArray { + val t = intArrayOf(a, b, c) + t.sort() + val min = minMoves(t[0], t[1], t[2]) + val max = maxMoves(t[0], t[2]) + return intArrayOf(min, max) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1034_coloring_a_border/readme.md b/src/main/kotlin/g1001_1100/s1034_coloring_a_border/readme.md new file mode 100644 index 00000000..d0418b48 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1034_coloring_a_border/readme.md @@ -0,0 +1,82 @@ +[![](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) + +## 1034\. Coloring A Border + +Medium + +You are given an `m x n` integer matrix `grid`, and three integers `row`, `col`, and `color`. Each value in the grid represents the color of the grid square at that location. + +Two squares belong to the same **connected component** if they have the same color and are next to each other in any of the 4 directions. + +The **border of a connected component** is all the squares in the connected component that are either **4-directionally** adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column). + +You should color the **border** of the **connected component** that contains the square `grid[row][col]` with `color`. + +Return _the final grid_. + +**Example 1:** + +**Input:** grid = \[\[1,1],[1,2]], row = 0, col = 0, color = 3 + +**Output:** [[3,3],[3,2]] + +**Example 2:** + +**Input:** grid = \[\[1,2,2],[2,3,2]], row = 0, col = 1, color = 3 + +**Output:** [[1,3,3],[2,3,3]] + +**Example 3:** + +**Input:** grid = \[\[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2 + +**Output:** [[2,2,2],[2,1,2],[2,2,2]] + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `1 <= m, n <= 50` +* `1 <= grid[i][j], color <= 1000` +* `0 <= row < m` +* `0 <= col < n` + +## Solution + +```kotlin +import kotlin.math.abs + +class Solution { + fun colorBorder(grid: Array, row: Int, col: Int, color: Int): Array { + getComp(grid, row, col, color, grid[row][col]) + for (i in grid.indices) { + for (j in grid[0].indices) { + if (grid[i][j] < 0) { + grid[i][j] = color + } + } + } + return grid + } + + private fun getComp(grid: Array, r: Int, c: Int, color: Int, stColor: Int): Int { + if (r < 0 || c < 0 || r >= grid.size || c >= grid[0].size || abs(grid[r][c]) != stColor) { + return 0 + } + if (grid[r][c] == -stColor) { + return 1 + } + grid[r][c] = -grid[r][c] + var count = 0 + count += getComp(grid, r - 1, c, color, stColor) + count += getComp(grid, r + 1, c, color, stColor) + count += getComp(grid, r, c - 1, color, stColor) + count += getComp(grid, r, c + 1, color, stColor) + if (count == 4) { + grid[r][c] = -grid[r][c] + } + return 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1035_uncrossed_lines/readme.md b/src/main/kotlin/g1001_1100/s1035_uncrossed_lines/readme.md new file mode 100644 index 00000000..bf2c0ee7 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1035_uncrossed_lines/readme.md @@ -0,0 +1,66 @@ +[![](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) + +## 1035\. Uncrossed Lines + +Medium + +You are given two integer arrays `nums1` and `nums2`. We write the integers of `nums1` and `nums2` (in the order they are given) on two separate horizontal lines. + +We may draw connecting lines: a straight line connecting two numbers `nums1[i]` and `nums2[j]` such that: + +* `nums1[i] == nums2[j]`, and +* the line we draw does not intersect any other connecting (non-horizontal) line. + +Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line). + +Return _the maximum number of connecting lines we can draw in this way_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/04/26/142.png) + +**Input:** nums1 = [1,4,2], nums2 = [1,2,4] + +**Output:** 2 + +**Explanation:** We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2. + +**Example 2:** + +**Input:** nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2] + +**Output:** 3 + +**Example 3:** + +**Input:** nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1] + +**Output:** 2 + +**Constraints:** + +* `1 <= nums1.length, nums2.length <= 500` +* `1 <= nums1[i], nums2[j] <= 2000` + +## Solution + +```kotlin +class Solution { + fun maxUncrossedLines(nums1: IntArray, nums2: IntArray): Int { + var dp = IntArray(nums2.size + 1) + for (i in 1..nums1.size) { + val dpRow = IntArray(nums2.size + 1) + for (j in 1..nums2.size) { + if (nums1[i - 1] == nums2[j - 1]) { + dpRow[j] = dp[j - 1] + 1 + } else { + dpRow[j] = dp[j].coerceAtLeast(dpRow[j - 1]) + } + } + dp = dpRow + } + return dp[nums2.size] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1036_escape_a_large_maze/readme.md b/src/main/kotlin/g1001_1100/s1036_escape_a_large_maze/readme.md new file mode 100644 index 00000000..31b3c1b2 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1036_escape_a_large_maze/readme.md @@ -0,0 +1,91 @@ +[![](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) + +## 1036\. Escape a Large Maze + +Hard + +There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are `(x, y)`. + +We start at the source = [sx, sy] square and want to reach the target = [tx, ty] square. There is also an array of `blocked` squares, where each blocked[i] = [xi, yi] represents a blocked square with coordinates (xi, yi). + +Each move, we can walk one square north, east, south, or west if the square is **not** in the array of `blocked` squares. We are also not allowed to walk outside of the grid. + +Return `true` _if and only if it is possible to reach the_ `target` _square from the_ `source` _square through a sequence of valid moves_. + +**Example 1:** + +**Input:** blocked = \[\[0,1],[1,0]], source = [0,0], target = [0,2] + +**Output:** false + +**Explanation:** The target square is inaccessible starting from the source square because we cannot move. + +We cannot move north or east because those squares are blocked. + +We cannot move south or west because we cannot go outside of the grid. + +**Example 2:** + +**Input:** blocked = [], source = [0,0], target = [999999,999999] + +**Output:** true + +**Explanation:** Because there are no blocked cells, it is possible to reach the target square. + +**Constraints:** + +* `0 <= blocked.length <= 200` +* `blocked[i].length == 2` +* 0 <= xi, yi < 106 +* `source.length == target.length == 2` +* 0 <= sx, sy, tx, ty < 106 +* `source != target` +* It is guaranteed that `source` and `target` are not blocked. + +## Solution + +```kotlin +class Solution { + fun isEscapePossible(blocked: Array, source: IntArray, target: IntArray): Boolean { + if (blocked.isEmpty()) { + return true + } + val blocks: MutableSet = HashSet() + for (b in blocked) { + if (target[0] * 1000000 + target[1] != b[0] * 1000000 + b[1]) { + blocks.add(b[0] * 1000000 + b[1]) + } + } + return ( + dfs(blocks, source, source[0], source[1], HashSet(), target) && + dfs(blocks, target, target[0], target[1], HashSet(), source) + ) + } + + private fun dfs( + blocks: Set, + start: IntArray, + i: Int, + j: Int, + visited: MutableSet, + target: IntArray + ): Boolean { + if (i < 0 || j < 0 || i > 999999 || j > 999999 || blocks.contains(i * 1000000 + j) || + visited.contains(i * 1000000 + j) + ) { + return false + } + if (i == target[0] && j == target[1]) { + return true + } + visited.add(i * 1000000 + j) + return if (visited.size > blocks.size * (blocks.size + 1)) { + true + } else dfs(blocks, start, i + 1, j, visited, target) || + dfs(blocks, start, i - 1, j, visited, target) || + dfs(blocks, start, i, j + 1, visited, target) || + dfs(blocks, start, i, j - 1, visited, target) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1037_valid_boomerang/readme.md b/src/main/kotlin/g1001_1100/s1037_valid_boomerang/readme.md new file mode 100644 index 00000000..8fdca3aa --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1037_valid_boomerang/readme.md @@ -0,0 +1,41 @@ +[![](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) + +## 1037\. Valid Boomerang + +Easy + +Given an array `points` where points[i] = [xi, yi] represents a point on the **X-Y** plane, return `true` _if these points are a **boomerang**_. + +A **boomerang** is a set of three points that are **all distinct** and **not in a straight line**. + +**Example 1:** + +**Input:** points = \[\[1,1],[2,3],[3,2]] + +**Output:** true + +**Example 2:** + +**Input:** points = \[\[1,1],[2,2],[3,3]] + +**Output:** false + +**Constraints:** + +* `points.length == 3` +* `points[i].length == 2` +* 0 <= xi, yi <= 100 + +## Solution + +```kotlin +class Solution { + fun isBoomerang(points: Array): Boolean { + return ( + (points[1][1] - points[0][1]) * (points[2][0] - points[0][0]) + != (points[2][1] - points[0][1]) * (points[1][0] - points[0][0]) + ) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1038_binary_search_tree_to_greater_sum_tree/readme.md b/src/main/kotlin/g1001_1100/s1038_binary_search_tree_to_greater_sum_tree/readme.md new file mode 100644 index 00000000..08e172a6 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1038_binary_search_tree_to_greater_sum_tree/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) + +## 1038\. Binary Search Tree to Greater Sum Tree + +Medium + +Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. + +As a reminder, a _binary search tree_ is a tree that satisfies these constraints: + +* The left subtree of a node contains only nodes with keys **less than** the node's key. +* The right subtree of a node contains only nodes with keys **greater than** the node's key. +* Both the left and right subtrees must also be binary search trees. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/05/02/tree.png) + +**Input:** root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] + +**Output:** [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] + +**Example 2:** + +**Input:** root = [0,null,1] + +**Output:** [1,null,1] + +**Constraints:** + +* The number of nodes in the tree is in the range `[1, 100]`. +* `0 <= Node.val <= 100` +* All the values in the tree are **unique**. + +**Note:** This question is the same as 538: [https://leetcode.com/problems/convert-bst-to-greater-tree/](https://leetcode.com/problems/convert-bst-to-greater-tree/) + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private var greaterSum = 0 + fun bstToGst(root: TreeNode?): TreeNode { + if (root!!.right != null) { + bstToGst(root.right!!) + } + root.`val` = greaterSum + root.`val` + greaterSum = root.`val` + if (root.left != null) { + bstToGst(root.left!!) + } + return root + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1039_minimum_score_triangulation_of_polygon/readme.md b/src/main/kotlin/g1001_1100/s1039_minimum_score_triangulation_of_polygon/readme.md new file mode 100644 index 00000000..957f43c4 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1039_minimum_score_triangulation_of_polygon/readme.md @@ -0,0 +1,83 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1039\. Minimum Score Triangulation of Polygon + +Medium + +You have a convex `n`\-sided polygon where each vertex has an integer value. You are given an integer array `values` where `values[i]` is the value of the ith vertex (i.e., **clockwise order**). + +You will **triangulate** the polygon into `n - 2` triangles. For each triangle, the value of that triangle is the product of the values of its vertices, and the total score of the triangulation is the sum of these values over all `n - 2` triangles in the triangulation. + +Return _the smallest possible total score that you can achieve with some triangulation of the polygon_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/25/shape1.jpg) + +**Input:** values = [1,2,3] + +**Output:** 6 + +**Explanation:** The polygon is already triangulated, and the score of the only triangle is 6. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/02/25/shape2.jpg) + +**Input:** values = [3,7,4,5] + +**Output:** 144 + +**Explanation:** There are two triangulations, with possible scores: 3\*7\*5 + 4\*5\*7 = 245, or 3\*4\*5 + 3\*4\*7 = 144. The minimum score is 144. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/02/25/shape3.jpg) + +**Input:** values = [1,3,1,4,1,5] + +**Output:** 13 + +**Explanation:** The minimum score triangulation has score 1\*1\*3 + 1\*1\*4 + 1\*1\*5 + 1\*1\*1 = 13. + +**Constraints:** + +* `n == values.length` +* `3 <= n <= 50` +* `1 <= values[i] <= 100` + +## Solution + +```kotlin +class Solution() { + private val dp = Array(101) { IntArray(101) } + fun minScoreTriangulation(values: IntArray): Int { + val n = values.size + for (row: IntArray? in dp) { + row!!.fill(-1) + } + return util(values, 1, n - 1) + } + + private fun util(values: IntArray, i: Int, j: Int): Int { + if (i >= j) { + return 0 + } + if (dp[i][j] != -1) { + return dp[i][j] + } + var ans = Int.MAX_VALUE + for (k in i until j) { + val temp = ( + util(values, i, k) + + util(values, k + 1, j) + + (values[i - 1] * values[k] * values[j]) + ) + ans = ans.coerceAtMost(temp) + dp[i][j] = ans + } + return dp[i][j] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1040_moving_stones_until_consecutive_ii/readme.md b/src/main/kotlin/g1001_1100/s1040_moving_stones_until_consecutive_ii/readme.md new file mode 100644 index 00000000..27fdb9be --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1040_moving_stones_until_consecutive_ii/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) + +## 1040\. Moving Stones Until Consecutive II + +Medium + +There are some stones in different positions on the X-axis. You are given an integer array `stones`, the positions of the stones. + +Call a stone an **endpoint stone** if it has the smallest or largest position. In one move, you pick up an **endpoint stone** and move it to an unoccupied position so that it is no longer an **endpoint stone**. + +* In particular, if the stones are at say, `stones = [1,2,5]`, you cannot move the endpoint stone at position `5`, since moving it to any position (such as `0`, or `3`) will still keep that stone as an endpoint stone. + +The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). + +Return _an integer array_ `answer` _of length_ `2` _where_: + +* `answer[0]` _is the minimum number of moves you can play, and_ +* `answer[1]` _is the maximum number of moves you can play_. + +**Example 1:** + +**Input:** stones = [7,4,9] + +**Output:** [1,2] + +**Explanation:** We can move 4 -> 8 for one move to finish the game. Or, we can move 9 -> 5, 4 -> 6 for two moves to finish the game. + +**Example 2:** + +**Input:** stones = [6,5,4,3,10] + +**Output:** [2,3] + +**Explanation:** We can move 3 -> 8 then 10 -> 7 to finish the game. Or, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game. Notice we cannot move 10 -> 2 to finish the game, because that would be an illegal move. + +**Constraints:** + +* 3 <= stones.length <= 104 +* 1 <= stones[i] <= 109 +* All the values of `stones` are **unique**. + +## Solution + +```kotlin +class Solution { + fun numMovesStonesII(a: IntArray): IntArray? { + a.sort() + var i = 0 + val n = a.size + var low = n + val high = (a[n - 1] - n + 2 - a[1]).coerceAtLeast(a[n - 2] - a[0] - n + 2) + for (j in 0 until n) { + while (a[j] - a[i] >= n) ++i + low = if (j - i + 1 == n - 1 && a[j] - a[i] == n - 2) low.coerceAtMost(2) + else low.coerceAtMost(n - (j - i + 1)) + } + return intArrayOf(low, high) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1041_robot_bounded_in_circle/readme.md b/src/main/kotlin/g1001_1100/s1041_robot_bounded_in_circle/readme.md new file mode 100644 index 00000000..38b703e0 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1041_robot_bounded_in_circle/readme.md @@ -0,0 +1,120 @@ +[![](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) + +## 1041\. Robot Bounded In Circle + +Medium + +On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that: + +* The **north direction** is the positive direction of the y-axis. +* The **south direction** is the negative direction of the y-axis. +* The **east direction** is the positive direction of the x-axis. +* The **west direction** is the negative direction of the x-axis. + +The robot can receive one of three instructions: + +* `"G"`: go straight 1 unit. +* `"L"`: turn 90 degrees to the left (i.e., anti-clockwise direction). +* `"R"`: turn 90 degrees to the right (i.e., clockwise direction). + +The robot performs the `instructions` given in order, and repeats them forever. + +Return `true` if and only if there exists a circle in the plane such that the robot never leaves the circle. + +**Example 1:** + +**Input:** instructions = "GGLLGG" + +**Output:** true + +**Explanation:** The robot is initially at (0, 0) facing the north direction. + +"G": move one step. Position: (0, 1). Direction: North. + +"G": move one step. Position: (0, 2). Direction: North. + +"L": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West. + +"L": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South. + +"G": move one step. Position: (0, 1). Direction: South. + +"G": move one step. Position: (0, 0). Direction: South. + +Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0). + +Based on that, we return true. + +**Example 2:** + +**Input:** instructions = "GG" + +**Output:** false + +**Explanation:** The robot is initially at (0, 0) facing the north direction. + +"G": move one step. Position: (0, 1). Direction: North. + +"G": move one step. Position: (0, 2). Direction: North. + +Repeating the instructions, keeps advancing in the north direction and does not go into cycles. + +Based on that, we return false. + +**Example 3:** + +**Input:** instructions = "GL" + +**Output:** true + +**Explanation:** The robot is initially at (0, 0) facing the north direction. + +"G": move one step. Position: (0, 1). Direction: North. + +"L": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West. + +"G": move one step. Position: (-1, 1). Direction: West. + +"L": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South. + +"G": move one step. Position: (-1, 0). Direction: South. + +"L": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East. + +"G": move one step. Position: (0, 0). Direction: East. + +"L": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North. + +Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0). + +Based on that, we return true. + +**Constraints:** + +* `1 <= instructions.length <= 100` +* `instructions[i]` is `'G'`, `'L'` or, `'R'`. + +## Solution + +```kotlin +class Solution { + fun isRobotBounded(instructions: String): Boolean { + val dir = arrayOf(intArrayOf(0, 1), intArrayOf(-1, 0), intArrayOf(0, -1), intArrayOf(1, 0)) + var i = 0 + var x = 0 + var y = 0 + for (s in instructions.indices) { + if (instructions[s] == 'L') { + i = (i + 1) % 4 + } else if (instructions[s] == 'R') { + i = (i + 3) % 4 + } else { + x += dir[i][0] + y += dir[i][1] + } + } + return x == 0 && y == 0 || i != 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1042_flower_planting_with_no_adjacent/readme.md b/src/main/kotlin/g1001_1100/s1042_flower_planting_with_no_adjacent/readme.md new file mode 100644 index 00000000..2fa57b4e --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1042_flower_planting_with_no_adjacent/readme.md @@ -0,0 +1,104 @@ +[![](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) + +## 1042\. Flower Planting With No Adjacent + +Medium + +You have `n` gardens, labeled from `1` to `n`, and an array `paths` where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers. + +All gardens have **at most 3** paths coming into or leaving it. + +Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. + +Return _**any** such a choice as an array_ `answer`_, where_ `answer[i]` _is the type of flower planted in the_ (i+1)th _garden. The flower types are denoted_ `1`_,_ `2`_,_ `3`_, or_ `4`_. It is guaranteed an answer exists._ + +**Example 1:** + +**Input:** n = 3, paths = \[\[1,2],[2,3],[3,1]] + +**Output:** [1,2,3] + +**Explanation:** + +Gardens 1 and 2 have different types. + +Gardens 2 and 3 have different types. + +Gardens 3 and 1 have different types. + +Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1]. + +**Example 2:** + +**Input:** n = 4, paths = \[\[1,2],[3,4]] + +**Output:** [1,2,1,2] + +**Example 3:** + +**Input:** n = 4, paths = \[\[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]] + +**Output:** [1,2,3,4] + +**Constraints:** + +* 1 <= n <= 104 +* 0 <= paths.length <= 2 * 104 +* `paths[i].length == 2` +* 1 <= xi, yi <= n +* xi != yi +* Every garden has **at most 3** paths coming into or leaving it. + +## Solution + +```kotlin +class Solution { + private lateinit var graph: Array?> + private lateinit var color: IntArray + private lateinit var visited: BooleanArray + + fun gardenNoAdj(n: Int, paths: Array): IntArray { + buildGraph(n, paths) + color = IntArray(n) + visited = BooleanArray(n) + for (i in 0 until n) { + if (!visited[i]) { + dfs(i) + } + } + return color + } + + private fun dfs(at: Int) { + visited[at] = true + var used = 0 + for (to in graph[at]!!) { + if (color[to] != 0) { + used = used or (1 shl color[to] - 1) + } + } + + // use available color + for (i in 0..3) { + if (used and (1 shl i) == 0) { + color[at] = i + 1 + break + } + } + } + + private fun buildGraph(n: Int, paths: Array) { + graph = arrayOfNulls(n) + for (i in 0 until n) { + graph[i] = ArrayList() + } + for (path in paths) { + val u = path[0] - 1 + val v = path[1] - 1 + graph[u]!!.add(v) + graph[v]!!.add(u) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1043_partition_array_for_maximum_sum/readme.md b/src/main/kotlin/g1001_1100/s1043_partition_array_for_maximum_sum/readme.md new file mode 100644 index 00000000..38529c45 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1043_partition_array_for_maximum_sum/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) + +## 1043\. Partition Array for Maximum Sum + +Medium + +Given an integer array `arr`, partition the array into (contiguous) subarrays of length **at most** `k`. After partitioning, each subarray has their values changed to become the maximum value of that subarray. + +Return _the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a **32-bit** integer._ + +**Example 1:** + +**Input:** arr = [1,15,7,9,2,5,10], k = 3 + +**Output:** 84 + +**Explanation:** arr becomes [15,15,15,9,10,10,10] + +**Example 2:** + +**Input:** arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4 + +**Output:** 83 + +**Example 3:** + +**Input:** arr = [1], k = 1 + +**Output:** 1 + +**Constraints:** + +* `1 <= arr.length <= 500` +* 0 <= arr[i] <= 109 +* `1 <= k <= arr.length` + +## Solution + +```kotlin +class Solution { + fun maxSumAfterPartitioning(arr: IntArray, k: Int): Int { + val n = arr.size + val dp = IntArray(n) + for (right in 0 until n) { + var localMax = arr[right] + for (left in right downTo (-1).coerceAtLeast(right - k) + 1) { + localMax = localMax.coerceAtLeast(arr[left]) + if (left == 0) { + dp[right] = dp[right].coerceAtLeast((right + 1) * localMax) + } else { + dp[right] = dp[right].coerceAtLeast(dp[left - 1] + (right - left + 1) * localMax) + } + } + } + return dp[n - 1] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1044_longest_duplicate_substring/readme.md b/src/main/kotlin/g1001_1100/s1044_longest_duplicate_substring/readme.md new file mode 100644 index 00000000..c0ce0903 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1044_longest_duplicate_substring/readme.md @@ -0,0 +1,95 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1044\. Longest Duplicate Substring + +Hard + +Given a string `s`, consider all _duplicated substrings_: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap. + +Return **any** duplicated substring that has the longest possible length. If `s` does not have a duplicated substring, the answer is `""`. + +**Example 1:** + +**Input:** s = "banana" + +**Output:** "ana" + +**Example 2:** + +**Input:** s = "abcd" + +**Output:** "" + +**Constraints:** + +* 2 <= s.length <= 3 * 104 +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + private lateinit var hsh: LongArray + private lateinit var pw: LongArray + private val cnt: Array?> = arrayOfNulls(26) + + fun longestDupSubstring(s: String): String { + val n = s.length + val base = 131 + for (i in 0..25) { + cnt[i] = ArrayList() + } + hsh = LongArray(n + 1) + pw = LongArray(n + 1) + pw[0] = 1 + for (j in 1..n) { + hsh[j] = (hsh[j - 1] * base + s[j - 1].code.toLong()) % MOD + pw[j] = pw[j - 1] * base % MOD + cnt[s[j - 1].code - 'a'.code]!!.add(j - 1) + } + var ans = "" + for (i in 0..25) { + if (cnt[i]!!.isEmpty()) { + continue + } + val idx: MutableList? = cnt[i] + var set: MutableSet + var lo = 1 + var hi = n - idx!![0] + while (lo <= hi) { + val len = (lo + hi) / 2 + set = HashSet() + var found = false + for (nxt in idx) { + if (nxt + len <= n) { + val substrHash = getSubstrHash(nxt, nxt + len) + if (set.contains(substrHash)) { + found = true + if (len + 1 > ans.length) { + ans = s.substring(nxt, nxt + len) + } + break + } + set.add(substrHash) + } + } + if (found) { + lo = len + 1 + } else { + hi = len - 1 + } + } + } + return ans + } + + private fun getSubstrHash(l: Int, r: Int): Long { + return (hsh[r] - hsh[l] * pw[r - l] % MOD + MOD) % MOD + } + + companion object { + private const val MOD = 1e9.toInt() + 7 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1045_customers_who_bought_all_products/readme.md b/src/main/kotlin/g1001_1100/s1045_customers_who_bought_all_products/readme.md new file mode 100644 index 00000000..2669ca17 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1045_customers_who_bought_all_products/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) + +## 1045\. Customers Who Bought All Products + +Medium + +SQL Schema + +Table: `Customer` + + +-------------+---------+ + | Column Name | Type | + +-------------+---------+ + | customer_id | int | + | product_key | int | + +-------------+---------+ + +There is no primary key for this table. It may contain duplicates. `customer_id` is not NULL`.` product\_key is a foreign key to `Product` table. + +Table: `Product` + + +-------------+---------+ + | Column Name | Type | + +-------------+---------+ + | product_key | int | + +-------------+---------+ + + product_key is the primary key column for this table. + +Write an SQL query to report the customer ids from the `Customer` table that bought all the products in the `Product` table. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** Customer table: + + +-------------+-------------+ + | customer_id | product_key | + +-------------+-------------+ + | 1 | 5 | + | 2 | 6 | + | 3 | 5 | + | 3 | 6 | + | 1 | 6 | + +-------------+-------------+ + +Product table: + + +-------------+ + | product_key | + +-------------+ + | 5 | + | 6 | + +-------------+ + +**Output:** + + +-------------+ + | customer_id | + +-------------+ + | 1 | + | 3 | + +-------------+ + +**Explanation:** The customers who bought all the products (5 and 6) are customers with IDs 1 and 3. + +## Solution + +```sql +# Write your MySQL query statement below +select customer_id +from customer +group by customer_id +having count(distinct product_key)=(select count(*) from product); +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1046_last_stone_weight/readme.md b/src/main/kotlin/g1001_1100/s1046_last_stone_weight/readme.md new file mode 100644 index 00000000..246b05d1 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1046_last_stone_weight/readme.md @@ -0,0 +1,70 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1046\. Last Stone Weight + +Easy + +You are given an array of integers `stones` where `stones[i]` is the weight of the ith stone. + +We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is: + +* If `x == y`, both stones are destroyed, and +* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`. + +At the end of the game, there is **at most one** stone left. + +Return _the weight of the last remaining stone_. If there are no stones left, return `0`. + +**Example 1:** + +**Input:** stones = [2,7,4,1,8,1] + +**Output:** 1 + +**Explanation:** + +We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, + +we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, + +we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, + +we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone. + +**Example 2:** + +**Input:** stones = [1] + +**Output:** 1 + +**Constraints:** + +* `1 <= stones.length <= 30` +* `1 <= stones[i] <= 1000` + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + fun lastStoneWeight(stones: IntArray): Int { + val heap = PriorityQueue { a: Int, b: Int -> b - a } + for (stone in stones) { + heap.offer(stone) + } + while (heap.isNotEmpty()) { + if (heap.size >= 2) { + val one = heap.poll() + val two = heap.poll() + val diff = one - two + heap.offer(diff) + } else { + return heap.poll() + } + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1047_remove_all_adjacent_duplicates_in_string/readme.md b/src/main/kotlin/g1001_1100/s1047_remove_all_adjacent_duplicates_in_string/readme.md new file mode 100644 index 00000000..871868ca --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1047_remove_all_adjacent_duplicates_in_string/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) + +## 1047\. Remove All Adjacent Duplicates In String + +Easy + +You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them. + +We repeatedly make **duplicate removals** on `s` until we no longer can. + +Return _the final string after all such duplicate removals have been made_. It can be proven that the answer is **unique**. + +**Example 1:** + +**Input:** s = "abbaca" + +**Output:** "ca" + +**Explanation:** For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca". + +**Example 2:** + +**Input:** s = "azxxzy" + +**Output:** "ay" + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun removeDuplicates(s: String): String { + if (s.length == 1) { + return s + } + val array = s.toCharArray() + val length = array.size + var fast = 0 + var slow = 0 + while (fast < length) { + if (slow == 0 || array[fast] != array[slow - 1]) { + array[slow++] = array[fast++] + } else { + if (array[fast] == array[slow - 1]) { + fast++ + } + slow-- + } + } + return String(array, 0, slow) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1048_longest_string_chain/readme.md b/src/main/kotlin/g1001_1100/s1048_longest_string_chain/readme.md new file mode 100644 index 00000000..2459d998 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1048_longest_string_chain/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) + +## 1048\. Longest String Chain + +Medium + +You are given an array of `words` where each word consists of lowercase English letters. + +wordA is a **predecessor** of wordB if and only if we can insert **exactly one** letter anywhere in wordA **without changing the order of the other characters** to make it equal to wordB. + +* For example, `"abc"` is a **predecessor** of "abac", while `"cba"` is not a **predecessor** of `"bcad"`. + +A **word chain** is a sequence of words [word1, word2, ..., wordk] with `k >= 1`, where word1 is a **predecessor** of word2, word2 is a **predecessor** of word3, and so on. A single word is trivially a **word chain** with `k == 1`. + +Return _the **length** of the **longest possible word chain** with words chosen from the given list of_ `words`. + +**Example 1:** + +**Input:** words = ["a","b","ba","bca","bda","bdca"] + +**Output:** 4 + +**Explanation:**: One of the longest word chains is ["a","ba","bda","bdca"]. + +**Example 2:** + +**Input:** words = ["xbc","pcxbcf","xb","cxbc","pcxbc"] + +**Output:** 5 + +**Explanation:** All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"]. + +**Example 3:** + +**Input:** words = ["abcd","dbqca"] + +**Output:** 1 + +**Explanation:** The trivial word chain ["abcd"] is one of the longest word chains. ["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed. + +**Constraints:** + +* `1 <= words.length <= 1000` +* `1 <= words[i].length <= 16` +* `words[i]` only consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun longestStrChain(words: Array): Int { + val lenStr = arrayOfNulls?>(20) + for (word in words) { + val len = word.length + if (lenStr[len] == null) { + lenStr[len] = ArrayList() + } + lenStr[len]!!.add(word) + } + val longest: MutableMap = HashMap() + var max = 0 + for (s in words) { + max = findLongest(s, lenStr, longest).coerceAtLeast(max) + } + return max + } + + private fun findLongest( + word: String, + lenStr: Array?>, + longest: MutableMap + ): Int { + if (longest.containsKey(word)) { + return longest[word]!! + } + val len = word.length + val words: List? = lenStr[len + 1] + if (words == null) { + longest[word] = 1 + return 1 + } + var max = 0 + var i: Int + var j: Int + for (w in words) { + i = 0 + j = 0 + while (i < len && j - i <= 1) { + if (word[i] == w[j++]) { + ++i + } + } + if (j - i <= 1) { + max = findLongest(w, lenStr, longest).coerceAtLeast(max) + } + } + ++max + longest[word] = max + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1049_last_stone_weight_ii/readme.md b/src/main/kotlin/g1001_1100/s1049_last_stone_weight_ii/readme.md new file mode 100644 index 00000000..56f3efef --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1049_last_stone_weight_ii/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) + +## 1049\. Last Stone Weight II + +Medium + +You are given an array of integers `stones` where `stones[i]` is the weight of the ith stone. + +We are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights `x` and `y` with `x <= y`. The result of this smash is: + +* If `x == y`, both stones are destroyed, and +* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`. + +At the end of the game, there is **at most one** stone left. + +Return _the smallest possible weight of the left stone_. If there are no stones left, return `0`. + +**Example 1:** + +**Input:** stones = [2,7,4,1,8,1] + +**Output:** 1 + +**Explanation:** + +We can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then, + +we can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then, + +we can combine 2 and 1 to get 1, so the array converts to [1,1,1] then, + +we can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value. + +**Example 2:** + +**Input:** stones = [31,26,33,21,40] + +**Output:** 5 + +**Constraints:** + +* `1 <= stones.length <= 30` +* `1 <= stones[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun lastStoneWeightII(stones: IntArray): Int { + // dp[i][j] i is the index of stones, j is the current weight + // goal is to find max closest to half and use it to get the diff + // 0-1 knapsack problem + var sum = 0 + for (stone in stones) { + sum += stone + } + val half = sum / 2 + val dp = IntArray(half + 1) + for (cur in stones) { + for (j in half downTo cur) { + dp[j] = dp[j].coerceAtLeast(dp[j - cur] + cur) + } + } + return sum - dp[half] * 2 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1050_actors_and_directors_who_cooperated_at_least_three_times/readme.md b/src/main/kotlin/g1001_1100/s1050_actors_and_directors_who_cooperated_at_least_three_times/readme.md new file mode 100644 index 00000000..d634eb35 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1050_actors_and_directors_who_cooperated_at_least_three_times/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) + +## 1050\. Actors and Directors Who Cooperated At Least Three Times + +Easy + +SQL Schema + +Table: `ActorDirector` + + +-------------+---------+ + | Column Name | Type | + +-------------+---------+ + | actor_id | int | + | director_id | int | + | timestamp | int | + +-------------+---------+ + timestamp is the primary key column for this table. + +Write a SQL query for a report that provides the pairs `(actor_id, director_id)` where the actor has cooperated with the director at least three times. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + ActorDirector table: + +-------------+-------------+-------------+ + | actor_id | director_id | timestamp | + +-------------+-------------+-------------+ + | 1 | 1 | 0 | + | 1 | 1 | 1 | + | 1 | 1 | 2 | + | 1 | 2 | 3 | + | 1 | 2 | 4 | + | 2 | 1 | 5 | + | 2 | 1 | 6 | + +-------------+-------------+-------------+ + +**Output:** + + +-------------+-------------+ + | actor_id | director_id | + +-------------+-------------+ + | 1 | 1 | + +-------------+-------------+ + +**Explanation:** The only pair is (1, 1) where they cooperated exactly 3 times. + +## Solution + +```sql +# Write your MySQL query statement below +SELECT actor_id, director_id +FROM ActorDirector +GROUP BY actor_id, director_id +HAVING COUNT(*) > 2 +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1051_height_checker/readme.md b/src/main/kotlin/g1001_1100/s1051_height_checker/readme.md new file mode 100644 index 00000000..35fa3971 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1051_height_checker/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) + +## 1051\. Height Checker + +Easy + +A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in **non-decreasing order** by height. Let this ordering be represented by the integer array `expected` where `expected[i]` is the expected height of the ith student in line. + +You are given an integer array `heights` representing the **current order** that the students are standing in. Each `heights[i]` is the height of the ith student in line (**0-indexed**). + +Return _the **number of indices** where_ `heights[i] != expected[i]`. + +**Example 1:** + +**Input:** heights = [1,1,4,2,1,3] + +**Output:** 3 + +**Explanation:** + +heights: [1,1,4,2,1,3] + +expected: [1,1,1,2,3,4] + +Indices 2, 4, and 5 do not match. + +**Example 2:** + +**Input:** heights = [5,1,2,3,4] + +**Output:** 5 + +**Explanation:** + +heights: [5,1,2,3,4] + +expected: [1,2,3,4,5] + +All indices do not match. + +**Example 3:** + +**Input:** heights = [1,2,3,4,5] + +**Output:** 0 + +**Explanation:** + +heights: [1,2,3,4,5] + +expected: [1,2,3,4,5] + +All indices match. + +**Constraints:** + +* `1 <= heights.length <= 100` +* `1 <= heights[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun heightChecker(heights: IntArray): Int { + var heightDiff = 0 + val count = IntArray(101) + val actualLine = IntArray(heights.size) + for (height in heights) { + count[height]++ + } + var heightLength = 0 + for (i in count.indices) { + if (count[i] > 0) { + for (j in 0 until count[i]) { + actualLine[heightLength] = i + heightLength++ + } + count[i] = 0 + } + } + for (i in heights.indices) { + if (actualLine[i] != heights[i]) { + heightDiff++ + } + } + return heightDiff + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1052_grumpy_bookstore_owner/readme.md b/src/main/kotlin/g1001_1100/s1052_grumpy_bookstore_owner/readme.md new file mode 100644 index 00000000..9dd7e0f0 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1052_grumpy_bookstore_owner/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) + +## 1052\. Grumpy Bookstore Owner + +Medium + +There is a bookstore owner that has a store open for `n` minutes. Every minute, some number of customers enter the store. You are given an integer array `customers` of length `n` where `customers[i]` is the number of the customer that enters the store at the start of the ith minute and all those customers leave after the end of that minute. + +On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where `grumpy[i]` is `1` if the bookstore owner is grumpy during the ith minute, and is `0` otherwise. + +When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied. + +The bookstore owner knows a secret technique to keep themselves not grumpy for `minutes` consecutive minutes, but can only use it once. + +Return _the maximum number of customers that can be satisfied throughout the day_. + +**Example 1:** + +**Input:** customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3 + +**Output:** 16 + +**Explanation:** The bookstore owner keeps themselves not grumpy for the last 3 minutes. The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16. + +**Example 2:** + +**Input:** customers = [1], grumpy = [0], minutes = 1 + +**Output:** 1 + +**Constraints:** + +* `n == customers.length == grumpy.length` +* 1 <= minutes <= n <= 2 * 104 +* `0 <= customers[i] <= 1000` +* `grumpy[i]` is either `0` or `1`. + +## Solution + +```kotlin +class Solution { + fun maxSatisfied(customers: IntArray, grumpy: IntArray, minutes: Int): Int { + // storing numbers of customers who faced grumpy owner till ith minute. + val grumpySum = IntArray(grumpy.size) + var ans = 0 + if (grumpy[0] == 1) { + grumpySum[0] = customers[0] + } else { + ans += customers[0] + } + for (i in 1 until grumpy.size) { + if (grumpy[i] == 1) { + grumpySum[i] = grumpySum[i - 1] + customers[i] + } else { + grumpySum[i] = grumpySum[i - 1] + ans += customers[i] + } + } + // calculating max number of customers who faced grumpy owner in a window of size 'minutes'. + var max = 0 + for (i in 0..customers.size - minutes) { + max = if (i == 0) { + max.coerceAtLeast(grumpySum[i + minutes - 1]) + } else { + max.coerceAtLeast(grumpySum[i + minutes - 1] - grumpySum[i - 1]) + } + } + // making the owner non-grumpy in that max window and adding the number of customers who do + // not face the grumpy customers. + ans += max + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1053_previous_permutation_with_one_swap/readme.md b/src/main/kotlin/g1001_1100/s1053_previous_permutation_with_one_swap/readme.md new file mode 100644 index 00000000..a4db52be --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1053_previous_permutation_with_one_swap/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) + +## 1053\. Previous Permutation With One Swap + +Medium + +Given an array of positive integers `arr` (not necessarily distinct), return _the_ _lexicographically_ _largest permutation that is smaller than_ `arr`, that can be **made with exactly one swap**. If it cannot be done, then return the same array. + +**Note** that a _swap_ exchanges the positions of two numbers `arr[i]` and `arr[j]` + +**Example 1:** + +**Input:** arr = [3,2,1] + +**Output:** [3,1,2] + +**Explanation:** Swapping 2 and 1. + +**Example 2:** + +**Input:** arr = [1,1,5] + +**Output:** [1,1,5] + +**Explanation:** This is already the smallest permutation. + +**Example 3:** + +**Input:** arr = [1,9,4,6,7] + +**Output:** [1,7,4,6,9] + +**Explanation:** Swapping 9 and 7. + +**Constraints:** + +* 1 <= arr.length <= 104 +* 1 <= arr[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun prevPermOpt1(arr: IntArray): IntArray { + for (i in arr.indices.reversed()) { + var diff = Int.MAX_VALUE + var index = i + for (j in i + 1 until arr.size) { + if (arr[i] - arr[j] in 1 until diff) { + diff = arr[i] - arr[j] + index = j + } + } + if (diff != Int.MAX_VALUE) { + val temp = arr[i] + arr[i] = arr[index] + arr[index] = temp + break + } + } + return arr + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1054_distant_barcodes/readme.md b/src/main/kotlin/g1001_1100/s1054_distant_barcodes/readme.md new file mode 100644 index 00000000..f191abbf --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1054_distant_barcodes/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) + +## 1054\. Distant Barcodes + +Medium + +In a warehouse, there is a row of barcodes, where the ith barcode is `barcodes[i]`. + +Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists. + +**Example 1:** + +**Input:** barcodes = [1,1,1,2,2,2] + +**Output:** [2,1,2,1,2,1] + +**Example 2:** + +**Input:** barcodes = [1,1,1,1,2,2,3,3] + +**Output:** [1,3,1,3,1,2,1,2] + +**Constraints:** + +* `1 <= barcodes.length <= 10000` +* `1 <= barcodes[i] <= 10000` + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + fun rearrangeBarcodes(barcodes: IntArray): IntArray { + val map = barcodes.groupBy { it }.mapValues { it.value.size } + val pq = PriorityQueue> { a, b -> b.second - a.second } + map.forEach { kv -> pq.offer(kv.toPair()) } + val result = IntArray(barcodes.size) + var ind = 0 + while (pq.isNotEmpty()) { + val remainingBcs = mutableListOf>() + for (i in 0 until 2) { + if (pq.isNotEmpty()) { + val max = pq.poll() + result[ind++] = max.first + if (max.second - 1 != 0) { + remainingBcs.add(Pair(max.first, max.second - 1)) + } + } + } + remainingBcs.forEach { bc -> pq.offer(bc) } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1061_lexicographically_smallest_equivalent_string/readme.md b/src/main/kotlin/g1001_1100/s1061_lexicographically_smallest_equivalent_string/readme.md new file mode 100644 index 00000000..53a84414 --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1061_lexicographically_smallest_equivalent_string/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) + +## 1061\. Lexicographically Smallest Equivalent String + +Medium + +You are given two strings of the same length `s1` and `s2` and a string `baseStr`. + +We say `s1[i]` and `s2[i]` are equivalent characters. + +* For example, if `s1 = "abc"` and `s2 = "cde"`, then we have `'a' == 'c'`, `'b' == 'd'`, and `'c' == 'e'`. + +Equivalent characters follow the usual rules of any equivalence relation: + +* **Reflexivity:** `'a' == 'a'`. +* **Symmetry:** `'a' == 'b'` implies `'b' == 'a'`. +* **Transitivity:** `'a' == 'b'` and `'b' == 'c'` implies `'a' == 'c'`. + +For example, given the equivalency information from `s1 = "abc"` and `s2 = "cde"`, `"acd"` and `"aab"` are equivalent strings of `baseStr = "eed"`, and `"aab"` is the lexicographically smallest equivalent string of `baseStr`. + +Return _the lexicographically smallest equivalent string of_ `baseStr` _by using the equivalency information from_ `s1` _and_ `s2`. + +**Example 1:** + +**Input:** s1 = "parker", s2 = "morris", baseStr = "parser" + +**Output:** "makkek" + +**Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as [m,p], [a,o], [k,r,s], [e,i]. + +The characters in each group are equivalent and sorted in lexicographical order. + +So the answer is "makkek". + +**Example 2:** + +**Input:** s1 = "hello", s2 = "world", baseStr = "hold" + +**Output:** "hdld" + +**Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as [h,w], [d,e,o], [l,r]. + +So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld". + +**Example 3:** + +**Input:** s1 = "leetcode", s2 = "programs", baseStr = "sourcecode" + +**Output:** "aauaaaaada" + +**Explanation:** We group the equivalent characters in s1 and s2 as [a,o,e,r,s,c], [l,p], [g,t] and [d,m], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada". + +**Constraints:** + +* `1 <= s1.length, s2.length, baseStr <= 1000` +* `s1.length == s2.length` +* `s1`, `s2`, and `baseStr` consist of lowercase English letters. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + lateinit var parent: IntArray + + fun smallestEquivalentString(s1: String, s2: String, baseStr: String): String? { + parent = IntArray(26) + val n = s1.length + var result = "" + for (i in 0..25) parent[i] = i + for (i in 0 until n) { + union(s1[i].code - 'a'.code, s2[i].code - 'a'.code) + } + val base = 'a'.code + for (element in baseStr) { + result += (base + find(element.code - 'a'.code)).toChar() + } + return result + } + + private fun union(a: Int, b: Int) { + val parentA = find(a) + val parentB = find(b) + if (parentA != parentB) { + if (parentA < parentB) { + parent[parentB] = parentA + } else { + parent[parentA] = parentB + } + } + } + + private fun find(x: Int): Int { + var x = x + while (parent[x] != x) { + x = parent[x] + } + return x + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1001_1100/s1068_product_sales_analysis_i/readme.md b/src/main/kotlin/g1001_1100/s1068_product_sales_analysis_i/readme.md new file mode 100644 index 00000000..fca0a8ba --- /dev/null +++ b/src/main/kotlin/g1001_1100/s1068_product_sales_analysis_i/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) + +## 1068\. Product Sales Analysis I + +Easy + +SQL Schema + +Table: `Sales` + + +-------------+-------+ + | Column Name | Type | + +-------------+-------+ + | sale_id | int | + | product_id | int | + | year | int | + | quantity | int | + | price | int | + +-------------+-------+ + +(sale_id, year) is the primary key of this table. + +product_id is a foreign key to `Product` table. + +Each row of this table shows a sale on the product product_id in a certain year. + +Note that the price is per unit. + +Table: `Product` + + +--------------+---------+ + | Column Name | Type | + +--------------+---------+ + | product_id | int | + | product_name | varchar | + +--------------+---------+ + +product_id is the primary key of this table. + +Each row of this table indicates the product name of each product. + +Write an SQL query that reports the `product_name`, `year`, and `price` for each `sale_id` in the `Sales` table. + +Return the resulting table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** Sales table: + + +---------+------------+------+----------+-------+ + | sale_id | product_id | year | quantity | price | + +---------+------------+------+----------+-------+ + | 1 | 100 | 2008 | 10 | 5000 | + | 2 | 100 | 2009 | 12 | 5000 | + | 7 | 200 | 2011 | 15 | 9000 | + +---------+------------+------+----------+-------+ + +Product table: + + +------------+--------------+ + | product_id | product_name | + +------------+--------------+ + | 100 | Nokia | + | 200 | Apple | + | 300 | Samsung | + +------------+--------------+ + +**Output:** + + +--------------+-------+-------+ + | product_name | year | price | + +--------------+-------+-------+ + | Nokia | 2008 | 5000 | + | Nokia | 2009 | 5000 | + | Apple | 2011 | 9000 | + +--------------+-------+-------+ + +**Explanation:** From sale\_id = 1, we can conclude that Nokia was sold for 5000 in the year 2008. From sale\_id = 2, we can conclude that Nokia was sold for 5000 in the year 2009. From sale\_id = 7, we can conclude that Apple was sold for 9000 in the year 2011. + +## Solution + +```sql +# Write your MySQL query statement below +Select Product.product_name, Sales.sale_year, Sales.price +from Sales +Inner Join Product On Product.product_id = Sales.product_id +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1154_day_of_the_year/readme.md b/src/main/kotlin/g1101_1200/s1154_day_of_the_year/readme.md new file mode 100644 index 00000000..d3df7920 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1154_day_of_the_year/readme.md @@ -0,0 +1,52 @@ +[![](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) + +## 1154\. Day of the Year + +Easy + +Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_. + +**Example 1:** + +**Input:** date = "2019-01-09" + +**Output:** 9 + +**Explanation:** Given date is the 9th day of the year in 2019. + +**Example 2:** + +**Input:** date = "2019-02-10" + +**Output:** 41 + +**Constraints:** + +* `date.length == 10` +* `date[4] == date[7] == '-'`, and all other `date[i]`'s are digits +* `date` represents a calendar date between Jan 1st, 1900 and Dec 31th, 2019. + +## Solution + +```kotlin +class Solution { + fun dayOfYear(date: String): Int { + val monthDays = intArrayOf(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) + val dateArr = date.split("-".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + val year = dateArr[0].toInt() + val month = dateArr[1].toInt() + val day = dateArr[2].toInt() + var dayCount = 0 + val leapYear = year % 4 == 0 && year % 100 != 0 || year % 400 == 0 + for (i in 1 until month) { + dayCount += monthDays[i] + } + dayCount += day + if (leapYear && month > 2) { + dayCount++ + } + return dayCount + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1155_number_of_dice_rolls_with_target_sum/readme.md b/src/main/kotlin/g1101_1200/s1155_number_of_dice_rolls_with_target_sum/readme.md new file mode 100644 index 00000000..e54d42e6 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1155_number_of_dice_rolls_with_target_sum/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) + +## 1155\. Number of Dice Rolls With Target Sum + +Medium + +You have `n` dice and each die has `k` faces numbered from `1` to `k`. + +Given three integers `n`, `k`, and `target`, return _the number of possible ways (out of the_ kn _total ways)_ _to roll the dice so the sum of the face-up numbers equals_ `target`. Since the answer may be too large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** n = 1, k = 6, target = 3 + +**Output:** 1 + +**Explanation:** You throw one die with 6 faces. + +There is only one way to get a sum of 3. + +**Example 2:** + +**Input:** n = 2, k = 6, target = 7 + +**Output:** 6 + +**Explanation:** You throw two dice, each with 6 faces. + +There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1. + +**Example 3:** + +**Input:** n = 30, k = 30, target = 500 + +**Output:** 222616187 + +**Explanation:** The answer must be returned modulo 109 + 7. + +**Constraints:** + +* `1 <= n, k <= 30` +* `1 <= target <= 1000` + +## Solution + +```kotlin +class Solution { + private var memo: Array = arrayOf() + + private var k = 0 + private fun dp(diceLeft: Int, targetLeft: Int): Int { + if (diceLeft == 0) { + return if (targetLeft == 0) { + 1 + } else 0 + } + if (memo[diceLeft][targetLeft] == -1) { + var res = 0 + for (i in 1..Math.min(k, targetLeft)) { + res += dp(diceLeft - 1, targetLeft - i) + val modulo = 1000000007 + res %= modulo + } + memo[diceLeft][targetLeft] = res + } + return memo[diceLeft][targetLeft] + } + + fun numRollsToTarget(n: Int, k: Int, target: Int): Int { + this.k = k + memo = Array(n + 1) { IntArray(target + 1) } + for (i in memo) { + i.fill(-1) + } + return dp(n, target) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1156_swap_for_longest_repeated_character_substring/readme.md b/src/main/kotlin/g1101_1200/s1156_swap_for_longest_repeated_character_substring/readme.md new file mode 100644 index 00000000..d0b85117 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1156_swap_for_longest_repeated_character_substring/readme.md @@ -0,0 +1,92 @@ +[![](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) + +## 1156\. Swap For Longest Repeated Character Substring + +Medium + +You are given a string `text`. You can swap two of the characters in the `text`. + +Return _the length of the longest substring with repeated characters_. + +**Example 1:** + +**Input:** text = "ababa" + +**Output:** 3 + +**Explanation:** We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa" with length 3. + +**Example 2:** + +**Input:** text = "aaabaaa" + +**Output:** 6 + +**Explanation:** Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa" with length 6. + +**Example 3:** + +**Input:** text = "aaaaa" + +**Output:** 5 + +**Explanation:** No need to swap, longest repeated character substring is "aaaaa" with length is 5. + +**Constraints:** + +* 1 <= text.length <= 2 * 104 +* `text` consist of lowercase English characters only. + +## Solution + +```kotlin +class Solution { + private class Pair(var character: Char, var count: Int) + + fun maxRepOpt1(text: String): Int { + val pairs: MutableList = ArrayList() + val map: MutableMap = HashMap() + // collect counts for each char-block + var i = 0 + while (i < text.length) { + val c = text[i] + var count = 0 + while (i < text.length && text[i] == c) { + count++ + i++ + } + pairs.add(Pair(c, count)) + map[c] = map.getOrDefault(c, 0) + count + } + var max = 0 + // case 1, swap 1 item to the boundary of a consecutive cha-block to achieve possible max + // length + // we need total count to make sure whether a swap is possible! + for (p in pairs) { + val totalCount = map.getValue(p.character) + max = if (totalCount > p.count) { + Math.max(max, p.count + 1) + } else { + Math.max(max, p.count) + } + } + // case 2, find xxxxYxxxxx pattern + // we need total count to make sure whether a swap is possible! + for (j in 1 until pairs.size - 1) { + if (pairs[j - 1].character == pairs[j + 1].character && + pairs[j].count == 1 + ) { + val totalCount = map.getValue(pairs[j - 1].character) + val groupSum = pairs[j - 1].count + pairs[j + 1].count + max = if (totalCount > groupSum) { + Math.max(max, groupSum + 1) + } else { + Math.max(max, groupSum) + } + } + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1157_online_majority_element_in_subarray/readme.md b/src/main/kotlin/g1101_1200/s1157_online_majority_element_in_subarray/readme.md new file mode 100644 index 00000000..6fba52d7 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1157_online_majority_element_in_subarray/readme.md @@ -0,0 +1,89 @@ +[![](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) + +## 1157\. Online Majority Element In Subarray + +Hard + +Design a data structure that efficiently finds the **majority element** of a given subarray. + +The **majority element** of a subarray is an element that occurs `threshold` times or more in the subarray. + +Implementing the `MajorityChecker` class: + +* `MajorityChecker(int[] arr)` Initializes the instance of the class with the given array `arr`. +* `int query(int left, int right, int threshold)` returns the element in the subarray `arr[left...right]` that occurs at least `threshold` times, or `-1` if no such element exists. + +**Example 1:** + +**Input** ["MajorityChecker", "query", "query", "query"] [[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]] + +**Output:** [null, 1, -1, 2] + +**Explanation:** + +MajorityChecker majorityChecker = new MajorityChecker([1, 1, 2, 2, 1, 1]); +majorityChecker.query(0, 5, 4); // return 1 +majorityChecker.query(0, 3, 3); // return -1 +majorityChecker.query(2, 3, 2); // return 2 + +**Constraints:** + +* 1 <= arr.length <= 2 * 104 +* 1 <= arr[i] <= 2 * 104 +* `0 <= left <= right < arr.length` +* `threshold <= right - left + 1` +* `2 * threshold > right - left + 1` +* At most 104 calls will be made to `query`. + +## Solution + +```kotlin +class MajorityChecker(arr: IntArray) { + private val valToInd: MutableMap> + private val bitCount: Array + + init { + valToInd = HashMap() + bitCount = Array(arr.size + 1) { IntArray(NUM_OF_BITS) } + for (i in arr.indices) { + var `val` = arr[i] + val indList = valToInd.computeIfAbsent(`val`) { _: Int? -> ArrayList() } + indList.add(i) + for (j in 0 until NUM_OF_BITS) { + bitCount[i + 1][j] = bitCount[i][j] + (`val` and 1) + `val` = `val` shr 1 + } + } + } + + fun query(left: Int, right: Int, threshold: Int): Int { + var candidateVal = 0 + for (i in NUM_OF_BITS - 1 downTo 0) { + val curBit = if (bitCount[right + 1][i] - bitCount[left][i] >= threshold) 1 else 0 + candidateVal = (candidateVal shl 1) + curBit + } + val indList: List? = valToInd[candidateVal] + if (indList == null || indList.size < threshold) { + return -1 + } + var indOfLeft = indList.binarySearch(left) + if (indOfLeft < 0) { + indOfLeft = -indOfLeft - 1 + } + var indOfRight = indList.binarySearch(right) + if (indOfRight < 0) { + indOfRight = -indOfRight - 2 + } + return if (indOfRight - indOfLeft + 1 >= threshold) { + candidateVal + } else { + -1 + } + } + + companion object { + private const val NUM_OF_BITS = 15 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1158_market_analysis_i/readme.md b/src/main/kotlin/g1101_1200/s1158_market_analysis_i/readme.md new file mode 100644 index 00000000..0dc54509 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1158_market_analysis_i/readme.md @@ -0,0 +1,110 @@ +[![](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) + +## 1158\. Market Analysis I + +Medium + +SQL Schema + +Table: `Users` + + +----------------+---------+ + | Column Name | Type | + +----------------+---------+ + | user_id | int | + | join_date | date | + | favorite_brand | varchar | + +----------------+---------+ + user_id is the primary key of this table. + This table has the info of the users of an online shopping website where users can sell and buy items. + +Table: `Orders` + + +---------------+---------+ + | Column Name | Type | + +---------------+---------+ + | order_id | int | + | order_date | date | + | item_id | int | + | buyer_id | int | + | seller_id | int | + +---------------+---------+ + order_id is the primary key of this table. + item_id is a foreign key to the Items table. + buyer_id and seller_id are foreign keys to the Users table. + +Table: `Items` + + +---------------+---------+ + | Column Name | Type | + +---------------+---------+ + | item_id | int | + | item_brand | varchar | + +---------------+---------+ + item_id is the primary key of this table. + +Write an SQL query to find for each user, the join date and the number of orders they made as a buyer in `2019`. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Users table: + +---------+------------+----------------+ + | user_id | join_date | favorite_brand | + +---------+------------+----------------+ + | 1 | 2018-01-01 | Lenovo | + | 2 | 2018-02-09 | Samsung | + | 3 | 2018-01-19 | LG | + | 4 | 2018-05-21 | HP | + +---------+------------+----------------+ + + Orders table: + +----------+------------+---------+----------+-----------+ + | order_id | order_date | item_id | buyer_id | seller_id | + +----------+------------+---------+----------+-----------+ + | 1 | 2019-08-01 | 4 | 1 | 2 | + | 2 | 2018-08-02 | 2 | 1 | 3 | + | 3 | 2019-08-03 | 3 | 2 | 3 | + | 4 | 2018-08-04 | 1 | 4 | 2 | + | 5 | 2018-08-04 | 1 | 3 | 4 | + | 6 | 2019-08-05 | 2 | 2 | 4 | + +----------+------------+---------+----------+-----------+ + + Items table: + +---------+------------+ + | item_id | item_brand | + +---------+------------+ + | 1 | Samsung | + | 2 | Lenovo | + | 3 | LG | + | 4 | HP | + +---------+------------+ + +**Output:** + + +-----------+------------+----------------+ + | buyer_id | join_date | orders_in_2019 | + +-----------+------------+----------------+ + | 1 | 2018-01-01 | 1 | + | 2 | 2018-02-09 | 2 | + | 3 | 2018-01-19 | 0 | + | 4 | 2018-05-21 | 0 | + +-----------+------------+----------------+ + +## Solution + +```sql +# Write your MySQL query statement below +SELECT U.user_id AS buyer_id, U.join_date, IFNULL(USERS_ORDERED_IN_2019.orders_in_2019, 0) AS orders_in_2019 FROM Users U +LEFT JOIN (SELECT U.user_id AS user_id, COUNT(O.item_id) AS orders_in_2019 FROM Users U +LEFT JOIN Orders O ON O.buyer_id = U.user_id +WHERE YEAR(O.order_date) = 2019 +GROUP BY U.user_id) AS USERS_ORDERED_IN_2019 +ON U.user_id = USERS_ORDERED_IN_2019.user_id; +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1160_find_words_that_can_be_formed_by_characters/readme.md b/src/main/kotlin/g1101_1200/s1160_find_words_that_can_be_formed_by_characters/readme.md new file mode 100644 index 00000000..a71f5066 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1160_find_words_that_can_be_formed_by_characters/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) + +## 1160\. Find Words That Can Be Formed by Characters + +Easy + +You are given an array of strings `words` and a string `chars`. + +A string is **good** if it can be formed by characters from chars (each character can only be used once). + +Return _the sum of lengths of all good strings in words_. + +**Example 1:** + +**Input:** words = ["cat","bt","hat","tree"], chars = "atach" + +**Output:** 6 + +**Explanation:** The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6. + +**Example 2:** + +**Input:** words = ["hello","world","leetcode"], chars = "welldonehoneyr" + +**Output:** 10 + +**Explanation:** The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10. + +**Constraints:** + +* `1 <= words.length <= 1000` +* `1 <= words[i].length, chars.length <= 100` +* `words[i]` and `chars` consist of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun countCharacters(words: Array, chars: String): Int { + var length = 0 + val map: MutableMap = HashMap() + for (c in chars.toCharArray()) { + val count = map.getOrDefault(c, 0) + map[c] = count + 1 + } + for (word in words) { + if (canForm(word, map)) { + length += word.length + } + } + return length + } + + private fun canForm(word: String, map: Map): Boolean { + val tmp: MutableMap = HashMap(map) + for (c in word.toCharArray()) { + if (tmp.containsKey(c) && tmp.getValue(c) > 0) { + val count = tmp.getValue(c) + tmp[c] = count - 1 + } else { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1161_maximum_level_sum_of_a_binary_tree/readme.md b/src/main/kotlin/g1101_1200/s1161_maximum_level_sum_of_a_binary_tree/readme.md new file mode 100644 index 00000000..6b0ec40c --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1161_maximum_level_sum_of_a_binary_tree/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) + +## 1161\. Maximum Level Sum of a Binary Tree + +Medium + +Given the `root` of a binary tree, the level of its root is `1`, the level of its children is `2`, and so on. + +Return the **smallest** level `x` such that the sum of all the values of nodes at level `x` is **maximal**. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/05/03/capture.JPG) + +**Input:** root = [1,7,0,7,-8,null,null] + +**Output:** 2 + +**Explanation:** + +Level 1 sum = 1. + +Level 2 sum = 7 + 0 = 7. + +Level 3 sum = 7 + -8 = -1. + +So we return the level with the maximum sum which is level 2. + +**Example 2:** + +**Input:** root = [989,null,10250,98693,-89388,null,null,null,-32127] + +**Output:** 2 + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 104]. +* -105 <= Node.val <= 105 + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private var sums: MutableList = ArrayList() + + fun maxLevelSum(root: TreeNode?): Int { + sums = ArrayList() + find(root, 1) + var ans = 1 + var maxv = Int.MIN_VALUE + for (i in sums.indices) { + if (sums[i] > maxv) { + maxv = sums[i] + ans = i + 1 + } + } + return ans + } + + private fun find(root: TreeNode?, height: Int) { + if (root == null) { + return + } + if (sums.size < height) { + sums.add(root.`val`) + } else { + sums[height - 1] = sums[height - 1] + root.`val` + } + find(root.left, height + 1) + find(root.right, height + 1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1162_as_far_from_land_as_possible/readme.md b/src/main/kotlin/g1101_1200/s1162_as_far_from_land_as_possible/readme.md new file mode 100644 index 00000000..ceb4dd32 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1162_as_far_from_land_as_possible/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) + +## 1162\. As Far from Land as Possible + +Medium + +Given an `n x n` `grid` containing only values `0` and `1`, where `0` represents water and `1` represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return `-1`. + +The distance used in this problem is the Manhattan distance: the distance between two cells `(x0, y0)` and `(x1, y1)` is `|x0 - x1| + |y0 - y1|`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/05/03/1336_ex1.JPG) + +**Input:** grid = \[\[1,0,1],[0,0,0],[1,0,1]] + +**Output:** 2 + +**Explanation:** The cell (1, 1) is as far as possible from all the land with distance 2. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2019/05/03/1336_ex2.JPG) + +**Input:** grid = \[\[1,0,0],[0,0,0],[0,0,0]] + +**Output:** 4 + +**Explanation:** The cell (2, 2) is as far as possible from all the land with distance 4. + +**Constraints:** + +* `n == grid.length` +* `n == grid[i].length` +* `1 <= n <= 100` +* `grid[i][j]` is `0` or `1` + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Objects +import java.util.Queue + +class Solution { + fun maxDistance(grid: Array): Int { + val q: Queue = LinkedList() + val n = grid.size + val m = grid[0].size + val vis = Array(n) { BooleanArray(m) } + for (i in 0 until n) { + for (j in 0 until m) { + if (grid[i][j] == 1) { + q.add(intArrayOf(i, j)) + vis[i][j] = true + } + } + } + if (q.isEmpty() || q.size == n * m) { + return -1 + } + val dir = intArrayOf(-1, 0, 1, 0, -1) + var maxDistance = 0 + var level = 1 + while (q.isNotEmpty()) { + val size = q.size + for (i in 0 until size) { + val top = q.poll() + val currX = Objects.requireNonNull(top)[0] + val currY = top[1] + for (j in 0 until dir.size - 1) { + val x = currX + dir[j] + val y = currY + dir[j + 1] + if (x >= 0 && x != n && y >= 0 && y != n && !vis[x][y]) { + maxDistance = Math.max(maxDistance, level) + vis[x][y] = true + q.add(intArrayOf(x, y)) + } + } + } + level++ + } + return maxDistance + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1163_last_substring_in_lexicographical_order/readme.md b/src/main/kotlin/g1101_1200/s1163_last_substring_in_lexicographical_order/readme.md new file mode 100644 index 00000000..400c84b0 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1163_last_substring_in_lexicographical_order/readme.md @@ -0,0 +1,54 @@ +[![](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) + +## 1163\. Last Substring in Lexicographical Order + +Hard + +Given a string `s`, return _the last substring of_ `s` _in lexicographical order_. + +**Example 1:** + +**Input:** s = "abab" + +**Output:** "bab" + +**Explanation:** The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab". + +**Example 2:** + +**Input:** s = "leetcode" + +**Output:** "tcode" + +**Constraints:** + +* 1 <= s.length <= 4 * 105 +* `s` contains only lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun lastSubstring(s: String): String { + var i = 0 + var j = 1 + var k = 0 + val n = s.length + val ca = s.toCharArray() + while (j + k < n) { + if (ca[i + k] == ca[j + k]) { + k++ + } else if (ca[i + k] > ca[j + k]) { + j += k + 1 + k = 0 + } else { + i = Math.max(i + k + 1, j) + j = i + 1 + k = 0 + } + } + return s.substring(i) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1169_invalid_transactions/readme.md b/src/main/kotlin/g1101_1200/s1169_invalid_transactions/readme.md new file mode 100644 index 00000000..e883a8e9 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1169_invalid_transactions/readme.md @@ -0,0 +1,98 @@ +[![](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) + +## 1169\. Invalid Transactions + +Medium + +A transaction is possibly invalid if: + +* the amount exceeds `$1000`, or; +* if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**. + +You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. + +Return a list of `transactions` that are possibly invalid. You may return the answer in **any order**. + +**Example 1:** + +**Input:** transactions = ["alice,20,800,mtv","alice,50,100,beijing"] + +**Output:** ["alice,20,800,mtv","alice,50,100,beijing"] + +**Explanation:** The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too. + +**Example 2:** + +**Input:** transactions = ["alice,20,800,mtv","alice,50,1200,mtv"] + +**Output:** ["alice,50,1200,mtv"] + +**Example 3:** + +**Input:** transactions = ["alice,20,800,mtv","bob,50,1200,mtv"] + +**Output:** ["bob,50,1200,mtv"] + +**Constraints:** + +* `transactions.length <= 1000` +* Each `transactions[i]` takes the form `"{name},{time},{amount},{city}"` +* Each `{name}` and `{city}` consist of lowercase English letters, and have lengths between `1` and `10`. +* Each `{time}` consist of digits, and represent an integer between `0` and `1000`. +* Each `{amount}` consist of digits, and represent an integer between `0` and `2000`. + +## Solution + +```kotlin +class Solution { + internal class Transaction(trans: String) { + var name: String + var time: Int + var amount: Int + var city: String + + init { + val s = trans.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + name = s[0] + time = s[1].toInt() + amount = s[2].toInt() + city = s[3] + } + } + + fun invalidTransactions(input: Array?): List { + val res: MutableList = ArrayList() + if (input == null || input.size == 0) { + return res + } + val map: MutableMap> = HashMap() + for (s in input) { + val trans = Transaction(s) + if (!map.containsKey(trans.name)) { + map[trans.name] = ArrayList() + } + map.getValue(trans.name).add(trans) + } + for (s in input) { + val trans = Transaction(s) + if (!isValid(trans, map)) { + res.add(s) + } + } + return res + } + + private fun isValid(transaction: Transaction, map: Map>): Boolean { + if (transaction.amount > 1000) { + return false + } + for (s in map.getValue(transaction.name)) { + if (Math.abs(s.time - transaction.time) <= 60 && s.city != transaction.city) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1170_compare_strings_by_frequency_of_the_smallest_character/readme.md b/src/main/kotlin/g1101_1200/s1170_compare_strings_by_frequency_of_the_smallest_character/readme.md new file mode 100644 index 00000000..1ef4b440 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1170_compare_strings_by_frequency_of_the_smallest_character/readme.md @@ -0,0 +1,85 @@ +[![](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) + +## 1170\. Compare Strings by Frequency of the Smallest Character + +Medium + +Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce"` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2. + +You are given an array of strings `words` and another array of query strings `queries`. For each query `queries[i]`, count the **number of words** in `words` such that `f(queries[i])` < `f(W)` for each `W` in `words`. + +Return _an integer array_ `answer`_, where each_ `answer[i]` _is the answer to the_ ith _query_. + +**Example 1:** + +**Input:** queries = ["cbd"], words = ["zaaaz"] + +**Output:** [1] + +**Explanation:** On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz"). + +**Example 2:** + +**Input:** queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"] + +**Output:** [1,2] + +**Explanation:** On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc"). + +**Constraints:** + +* `1 <= queries.length <= 2000` +* `1 <= words.length <= 2000` +* `1 <= queries[i].length, words[i].length <= 10` +* `queries[i][j]`, `words[i][j]` consist of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun numSmallerByFrequency(queries: Array, words: Array): IntArray { + val queriesMinFrequecies = IntArray(queries.size) + for (i in queries.indices) { + queriesMinFrequecies[i] = computeLowestFrequency(queries[i]) + } + val wordsMinFrequecies = IntArray(words.size) + for (i in words.indices) { + wordsMinFrequecies[i] = computeLowestFrequency(words[i]) + } + wordsMinFrequecies.sort() + val result = IntArray(queries.size) + for (i in result.indices) { + result[i] = search(wordsMinFrequecies, queriesMinFrequecies[i]) + } + return result + } + + private fun search(nums: IntArray, target: Int): Int { + var count = 0 + for (i in nums.indices.reversed()) { + if (nums[i] > target) { + count++ + } else { + break + } + } + return count + } + + private fun computeLowestFrequency(string: String): Int { + val str = string.toCharArray() + str.sort() + val sortedString = String(str) + var frequency = 1 + for (i in 1 until sortedString.length) { + if (sortedString[i] == sortedString[0]) { + frequency++ + } else { + break + } + } + return frequency + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1171_remove_zero_sum_consecutive_nodes_from_linked_list/readme.md b/src/main/kotlin/g1101_1200/s1171_remove_zero_sum_consecutive_nodes_from_linked_list/readme.md new file mode 100644 index 00000000..9e0274c2 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1171_remove_zero_sum_consecutive_nodes_from_linked_list/readme.md @@ -0,0 +1,77 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1171\. Remove Zero Sum Consecutive Nodes from Linked List + +Medium + +Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. + +After doing so, return the head of the final linked list. You may return any such answer. + +(Note that in the examples below, all sequences are serializations of `ListNode` objects.) + +**Example 1:** + +**Input:** head = [1,2,-3,3,1] + +**Output:** [3,1] **Note:** The answer [1,2,1] would also be accepted. + +**Example 2:** + +**Input:** head = [1,2,3,-3,4] + +**Output:** [1,2,4] + +**Example 3:** + +**Input:** head = [1,2,3,-3,-2] + +**Output:** [1] + +**Constraints:** + +* The given linked list will contain between `1` and `1000` nodes. +* Each node in the linked list has `-1000 <= node.val <= 1000`. + +## Solution + +```kotlin +import com_github_leetcode.ListNode + +/* + * Example: + * var li = ListNode(5) + * var v = li.`val` + * Definition for singly-linked list. + * class ListNode(var `val`: Int) { + * var next: ListNode? = null + * } + */ +class Solution { + fun removeZeroSumSublists(head: ListNode?): ListNode? { + val pre = ListNode(-1) + var curr: ListNode? = pre + pre.next = head + val map: MutableMap = HashMap() + var preSum = 0 + while (curr != null) { + preSum += curr.`val` + if (map.containsKey(preSum)) { + curr = map.getValue(preSum).next + var key = preSum + curr!!.`val` + while (key != preSum) { + map.remove(key) + curr = curr!!.next + key += curr!!.`val` + } + map.getValue(preSum).next = curr!!.next + } else { + map[preSum] = curr + } + curr = curr.next + } + return pre.next + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1172_dinner_plate_stacks/readme.md b/src/main/kotlin/g1101_1200/s1172_dinner_plate_stacks/readme.md new file mode 100644 index 00000000..25c96e3d --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1172_dinner_plate_stacks/readme.md @@ -0,0 +1,133 @@ +[![](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) + +## 1172\. Dinner Plate Stacks + +Hard + +You have an infinite number of stacks arranged in a row and numbered (left to right) from `0`, each of the stacks has the same maximum capacity. + +Implement the `DinnerPlates` class: + +* `DinnerPlates(int capacity)` Initializes the object with the maximum capacity of the stacks `capacity`. +* `void push(int val)` Pushes the given integer `val` into the leftmost stack with a size less than `capacity`. +* `int pop()` Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns `-1` if all the stacks are empty. +* `int popAtStack(int index)` Returns the value at the top of the stack with the given index `index` and removes it from that stack or returns `-1` if the stack with that given index is empty. + +**Example 1:** + +**Input** + +["DinnerPlates", "push", "push", "push", "push", "push", "popAtStack", "push", "push", "popAtStack", "popAtStack", "pop", "pop", "pop", "pop", "pop"] + +[[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []] + +**Output:** [null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1] + +**Explanation:** + + DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2 + D.push(1); + D.push(2); + D.push(3); + D.push(4); + D.push(5); // The stacks are now: 2 4 + 1 3 5 + ﹈ ﹈ ﹈ + D.popAtStack(0); // Returns 2. The stacks are now: 4 + 1 3 5 + ﹈ ﹈ ﹈ + D.push(20); // The stacks are now: 20 4 + 1 3 5 + ﹈ ﹈ ﹈ + D.push(21); // The stacks are now: 20 4 21 + 1 3 5 + ﹈ ﹈ ﹈ + D.popAtStack(0); // Returns 20. The stacks are now: 4 21 + 1 3 5 + ﹈ ﹈ ﹈ + D.popAtStack(2); // Returns 21. The stacks are now: 4 + 1 3 5 + ﹈ ﹈ ﹈ + D.pop() // Returns 5. The stacks are now: 4 + 1 3 + ﹈ ﹈ + D.pop() // Returns 4. The stacks are now: 1 3 + ﹈ ﹈ + D.pop() // Returns 3. The stacks are now: 1 + ﹈ + D.pop() // Returns 1. There are no stacks. + D.pop() // Returns -1. There are still no stacks. + +**Constraints:** + +* 1 <= capacity <= 2 * 104 +* 1 <= val <= 2 * 104 +* 0 <= index <= 105 +* At most 2 * 105 calls will be made to `push`, `pop`, and `popAtStack`. + +## Solution + +```kotlin +import java.util.Stack +import java.util.TreeSet + +class DinnerPlates(private val stackCap: Int) { + private val stacks: MutableList> + private val leftIndex: TreeSet + + init { + stacks = ArrayList() + leftIndex = TreeSet() + } + + fun push(`val`: Int) { + if (leftIndex.isNotEmpty()) { + val i = leftIndex.first() + stacks[i].push(`val`) + if (stacks[i].size == stackCap) { + leftIndex.remove(i) + } + return + } + if (stacks.isEmpty() || stacks[stacks.size - 1].size == stackCap) { + val newStack = Stack() + stacks.add(newStack) + } + stacks[stacks.size - 1].push(`val`) + } + + fun pop(): Int { + if (stacks.isEmpty()) { + return -1 + } + while (stacks[stacks.size - 1].isEmpty()) { + leftIndex.remove(stacks.size - 1) + stacks.removeAt(stacks.size - 1) + } + val `val` = stacks[stacks.size - 1].pop() + if (stacks[stacks.size - 1].isEmpty()) { + leftIndex.remove(stacks.size - 1) + stacks.removeAt(stacks.size - 1) + } + return `val` + } + + fun popAtStack(index: Int): Int { + if (stacks.size - 1 >= index) { + var `val` = -1 + if (stacks[index].isNotEmpty()) { + `val` = stacks[index].pop() + } + if (stacks[index].isEmpty() && index == stacks.size - 1) { + leftIndex.remove(stacks.size - 1) + stacks.removeAt(index) + return `val` + } + leftIndex.add(index) + return `val` + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1175_prime_arrangements/readme.md b/src/main/kotlin/g1101_1200/s1175_prime_arrangements/readme.md new file mode 100644 index 00000000..a1fbb53b --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1175_prime_arrangements/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) + +## 1175\. Prime Arrangements + +Easy + +Return the number of permutations of 1 to `n` so that prime numbers are at prime indices (1-indexed.) + +_(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)_ + +Since the answer may be large, return the answer **modulo `10^9 + 7`**. + +**Example 1:** + +**Input:** n = 5 + +**Output:** 12 + +**Explanation:** For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1. + +**Example 2:** + +**Input:** n = 100 + +**Output:** 682289015 + +**Constraints:** + +* `1 <= n <= 100` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun numPrimeArrangements(n: Int): Int { + var n = n + val a = intArrayOf( + 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, + 89, 97 + ) + var c = 0 + while (c < 25 && n >= a[c]) { + c++ + } + val m = 1000000007 + var res = 1L + while (n - c > 0) { + res *= (n - c).toLong() + res %= m.toLong() + n-- + } + while (c > 0) { + res *= c.toLong() + res %= m.toLong() + c-- + } + return res.toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1177_can_make_palindrome_from_substring/readme.md b/src/main/kotlin/g1101_1200/s1177_can_make_palindrome_from_substring/readme.md new file mode 100644 index 00000000..49e335e2 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1177_can_make_palindrome_from_substring/readme.md @@ -0,0 +1,83 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1177\. Can Make Palindrome from Substring + +Medium + +You are given a string `s` and array `queries` where queries[i] = [lefti, righti, ki]. We may rearrange the substring s[lefti...righti] for each query and then choose up to ki of them to replace with any lowercase English letter. + +If the substring is possible to be a palindrome string after the operations above, the result of the query is `true`. Otherwise, the result is `false`. + +Return a boolean array `answer` where `answer[i]` is the result of the ith query `queries[i]`. + +Note that each letter is counted individually for replacement, so if, for example s[lefti...righti] = "aaa", and ki = 2, we can only replace two of the letters. Also, note that no query modifies the initial string `s`. + +**Example :** + +**Input:** s = "abcda", queries = \[\[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]] + +**Output:** [true,false,false,true,true] + +**Explanation:** + +queries[0]: substring = "d", is palidrome. + +queries[1]: substring = "bc", is not palidrome. + +queries[2]: substring = "abcd", is not palidrome after replacing only 1 character. q + +ueries[3]: substring = "abcd", could be changed to "abba" which is palidrome. Also this can be changed to "baab" first rearrange it "bacd" then replace "cd" with "ab". + +queries[4]: substring = "abcda", could be changed to "abcba" which is palidrome. + +**Example 2:** + +**Input:** s = "lyb", queries = \[\[0,1,0],[2,2,1]] + +**Output:** [false,true] + +**Constraints:** + +* 1 <= s.length, queries.length <= 105 +* 0 <= lefti <= righti < s.length +* 0 <= ki <= s.length +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun canMakePaliQueries(s: String, queries: Array): List { + return canMakeP(s, queries) + } + + private fun canMakeP(s: String, qs: Array): List { + val n = s.length + val counts = IntArray(n) + for (i in 0 until n) { + var m = 0 + if (i > 0) { + m = counts[i - 1] + } + val c = s[i] + m = m xor (1 shl c.code - 'a'.code) + counts[i] = m + } + val ans: MutableList = ArrayList() + for (q in qs) { + ans.add(check(q, counts)) + } + return ans + } + + private fun check(q: IntArray, counts: IntArray): Boolean { + val l = q[0] + val r = q[1] + val k = q[2] + val prev = if (l > 0) counts[l - 1] else 0 + val kk = Integer.bitCount(prev xor counts[r]) + return kk / 2 <= k + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1178_number_of_valid_words_for_each_puzzle/readme.md b/src/main/kotlin/g1101_1200/s1178_number_of_valid_words_for_each_puzzle/readme.md new file mode 100644 index 00000000..7b45fa9f --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1178_number_of_valid_words_for_each_puzzle/readme.md @@ -0,0 +1,97 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1178\. Number of Valid Words for Each Puzzle + +Hard + +With respect to a given `puzzle` string, a `word` is _valid_ if both the following conditions are satisfied: + +* `word` contains the first letter of `puzzle`. +* For each letter in `word`, that letter is in `puzzle`. + * For example, if the puzzle is `"abcdefg"`, then valid words are `"faced"`, `"cabbage"`, and `"baggage"`, while + * invalid words are `"beefed"` (does not include `'a'`) and `"based"` (includes `'s'` which is not in the puzzle). + +Return _an array_ `answer`_, where_ `answer[i]` _is the number of words in the given word list_ `words` _that is valid with respect to the puzzle_ `puzzles[i]`. + +**Example 1:** + +**Input:** words = ["aaaa","asas","able","ability","actt","actor","access"], puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"] + +**Output:** [1,1,3,2,4,0] + +**Explanation:** + +1 valid word for "aboveyz" : "aaaa" + +1 valid word for "abrodyz" : "aaaa" + +3 valid words for "abslute" : "aaaa", "asas", "able" + +2 valid words for "absoryz" : "aaaa", "asas" + +4 valid words for "actresz" : "aaaa", "asas", "actt", "access" + +There are no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'. + +**Example 2:** + +**Input:** words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"] + +**Output:** [0,1,3,2,0] + +**Constraints:** + +* 1 <= words.length <= 105 +* `4 <= words[i].length <= 50` +* 1 <= puzzles.length <= 104 +* `puzzles[i].length == 7` +* `words[i]` and `puzzles[i]` consist of lowercase English letters. +* Each `puzzles[i]` does not contain repeated characters. + +## Solution + +```kotlin +class Solution { + fun findNumOfValidWords(words: Array, puzzles: Array): List { + val ans: MutableList = ArrayList() + val map = HashMap() + for (word in words) { + val wordmask = createMask(word) + if (map.containsKey(wordmask)) { + val oldfreq = map.getValue(wordmask) + val newfreq = oldfreq + 1 + map[wordmask] = newfreq + } else { + map[wordmask] = 1 + } + } + for (puzzle in puzzles) { + val puzzlemask = createMask(puzzle) + val firstChar = puzzle[0] + val first = 1 shl firstChar.code - 'a'.code + var sub = puzzlemask + var count = 0 + while (sub != 0) { + val firstCharPresent = sub and first == first + val wordvalid = map.containsKey(sub) + if (firstCharPresent && wordvalid) { + count += map.getValue(sub) + } + sub = sub - 1 and puzzlemask + } + ans.add(count) + } + return ans + } + + private fun createMask(str: String): Int { + var mask = 0 + for (i in 0 until str.length) { + val bit = str[i].code - 'a'.code + mask = mask or (1 shl bit) + } + return mask + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1179_reformat_department_table/readme.md b/src/main/kotlin/g1101_1200/s1179_reformat_department_table/readme.md new file mode 100644 index 00000000..8bd212dd --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1179_reformat_department_table/readme.md @@ -0,0 +1,81 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1179\. Reformat Department Table + +Easy + +SQL Schema + +Table: `Department` + + +-------------+---------+ + | Column Name | Type | + +-------------+---------+ + | id | int | + | revenue | int | + | month | varchar | + +-------------+---------+ + +(id, month) is the primary key of this table. + +The table has information about the revenue of each department per month. + +The month has values in ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]. + +Write an SQL query to reformat the table such that there is a department id column and a revenue column **for each month**. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + +Department table: + + +------+---------+-------+ + | id | revenue | month | + +------+---------+-------+ + | 1 | 8000 | Jan | + | 2 | 9000 | Jan | + | 3 | 10000 | Feb | + | 1 | 7000 | Feb | + | 1 | 6000 | Mar | + +------+---------+-------+ + +**Output:** + + +------+-------------+-------------+-------------+-----+-------------+ + | id | Jan_Revenue | Feb_Revenue | Mar_Revenue | ... | Dec_Revenue | + +------+-------------+-------------+-------------+-----+-------------+ + | 1 | 8000 | 7000 | 6000 | ... | null | + | 2 | 9000 | null | null | ... | null | + | 3 | null | 10000 | null | ... | null | + +------+-------------+-------------+-------------+-----+-------------+ + +**Explanation:** The revenue from Apr to Dec is null. + +Note that the result table has 13 columns (1 for the department id + 12 for the months). + +## Solution + +```sql +# Write your MySQL query statement below +SELECT DISTINCT id + , SUM(CASE WHEN "month" = 'Jan' THEN revenue END) AS Jan_Revenue + , SUM(CASE WHEN "month" = 'Feb' THEN revenue END) AS Feb_Revenue + , SUM(CASE WHEN "month" = 'Mar' THEN revenue END) AS Mar_Revenue + , SUM(CASE WHEN "month" = 'Apr' THEN revenue END) AS Apr_Revenue + , SUM(CASE WHEN "month" = 'May' THEN revenue END) AS May_Revenue + , SUM(CASE WHEN "month" = 'Jun' THEN revenue END) AS Jun_Revenue + , SUM(CASE WHEN "month" = 'Jul' THEN revenue END) AS Jul_Revenue + , SUM(CASE WHEN "month" = 'Aug' THEN revenue END) AS Aug_Revenue + , SUM(CASE WHEN "month" = 'Sep' THEN revenue END) AS Sep_Revenue + , SUM(CASE WHEN "month" = 'Oct' THEN revenue END) AS Oct_Revenue + , SUM(CASE WHEN "month" = 'Nov' THEN revenue END) AS Nov_Revenue + , SUM(CASE WHEN "month" = 'Dec' THEN revenue END) AS Dec_Revenue +FROM Department +GROUP BY id +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1184_distance_between_bus_stops/readme.md b/src/main/kotlin/g1101_1200/s1184_distance_between_bus_stops/readme.md new file mode 100644 index 00000000..372bef9d --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1184_distance_between_bus_stops/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) + +## 1184\. Distance Between Bus Stops + +Easy + +A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`. + +The bus goes along both directions i.e. clockwise and counterclockwise. + +Return the shortest distance between the given `start` and `destination` stops. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1.jpg) + +**Input:** distance = [1,2,3,4], start = 0, destination = 1 + +**Output:** 1 + +**Explanation:** Distance between 0 and 1 is 1 or 9, minimum is 1. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1-1.jpg) + +**Input:** distance = [1,2,3,4], start = 0, destination = 2 + +**Output:** 3 + +**Explanation:** Distance between 0 and 2 is 3 or 7, minimum is 3. + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1-2.jpg) + +**Input:** distance = [1,2,3,4], start = 0, destination = 3 + +**Output:** 4 + +**Explanation:** Distance between 0 and 3 is 6 or 4, minimum is 4. + +**Constraints:** + +* `1 <= n <= 10^4` +* `distance.length == n` +* `0 <= start, destination < n` +* `0 <= distance[i] <= 10^4` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun distanceBetweenBusStops(distance: IntArray, start: Int, destination: Int): Int { + var start = start + var destination = destination + if (start > destination) { + val tmp = start + start = destination + destination = tmp + } + var clockwise = 0 + for (i in start until destination) { + clockwise += distance[i] + } + var counterClockwise = 0 + for (i in destination until distance.size) { + counterClockwise += distance[i] + } + for (i in 0 until start) { + counterClockwise += distance[i] + } + return Math.min(clockwise, counterClockwise) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1185_day_of_the_week/readme.md b/src/main/kotlin/g1101_1200/s1185_day_of_the_week/readme.md new file mode 100644 index 00000000..90500f93 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1185_day_of_the_week/readme.md @@ -0,0 +1,81 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1185\. Day of the Week + +Easy + +Given a date, return the corresponding day of the week for that date. + +The input is given as three integers representing the `day`, `month` and `year` respectively. + +Return the answer as one of the following values `{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}`. + +**Example 1:** + +**Input:** day = 31, month = 8, year = 2019 + +**Output:** "Saturday" + +**Example 2:** + +**Input:** day = 18, month = 7, year = 1999 + +**Output:** "Sunday" + +**Example 3:** + +**Input:** day = 15, month = 8, year = 1993 + +**Output:** "Sunday" + +**Constraints:** + +* The given dates are valid dates between the years `1971` and `2100`. + +## Solution + +```kotlin +class Solution { + fun dayOfTheWeek(day: Int, month: Int, year: Int): String { + var counter = 0 + for (i in 1971 until year) { + counter += if (isLeapYear(i)) { + 366 + } else { + 365 + } + } + for (i in 1 until month) { + counter += dayOfMonth(i) + } + for (i in 1..day) { + counter += 1 + } + if (isLeapYear(year) && month > 2) { + counter++ + } + return when (counter % 7) { + 1 -> "Friday" + 2 -> "Saturday" + 3 -> "Sunday" + 4 -> "Monday" + 5 -> "Tuesday" + 6 -> "Wednesday" + else -> "Thursday" + } + } + + private fun isLeapYear(year: Int): Boolean { + return year % 4 == 0 && year % 100 != 0 || year % 400 == 0 + } + + private fun dayOfMonth(month: Int): Int { + return when (month) { + 1, 3, 5, 7, 8, 10, 12 -> 31 + 4, 6, 9, 11 -> 30 + else -> 28 + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1186_maximum_subarray_sum_with_one_deletion/readme.md b/src/main/kotlin/g1101_1200/s1186_maximum_subarray_sum_with_one_deletion/readme.md new file mode 100644 index 00000000..237eacc3 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1186_maximum_subarray_sum_with_one_deletion/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) + +## 1186\. Maximum Subarray Sum with One Deletion + +Medium + +Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible. + +Note that the subarray needs to be **non-empty** after deleting one element. + +**Example 1:** + +**Input:** arr = [1,-2,0,3] + +**Output:** 4 + +**Explanation:** Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value. + +**Example 2:** + +**Input:** arr = [1,-2,-2,3] + +**Output:** 3 + +**Explanation:** We just choose [3] and it's the maximum sum. + +**Example 3:** + +**Input:** arr = [-1,-1,-1,-1] + +**Output:** -1 + +**Explanation:** The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0. + +**Constraints:** + +* 1 <= arr.length <= 105 +* -104 <= arr[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun maximumSum(arr: IntArray): Int { + var maxWithNoDeletions = arr[0] + var maxWithOneDeletion = arr[0] + var maxOverall = arr[0] + for (i in 1 until arr.size) { + val numToProcess = arr[i] + val nextMaxWithNoDeletions = Math.max(maxWithNoDeletions + numToProcess, numToProcess) + val nextMaxWithOneDeletion = Math.max(maxWithOneDeletion + numToProcess, maxWithNoDeletions) + maxOverall = Math.max(maxOverall, Math.max(nextMaxWithNoDeletions, nextMaxWithOneDeletion)) + maxWithNoDeletions = nextMaxWithNoDeletions + maxWithOneDeletion = nextMaxWithOneDeletion + } + return maxOverall + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1187_make_array_strictly_increasing/readme.md b/src/main/kotlin/g1101_1200/s1187_make_array_strictly_increasing/readme.md new file mode 100644 index 00000000..3662613e --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1187_make_array_strictly_increasing/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) + +## 1187\. Make Array Strictly Increasing + +Hard + +Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing. + +In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`. + +If there is no way to make `arr1` strictly increasing, return `-1`. + +**Example 1:** + +**Input:** arr1 = [1,5,3,6,7], arr2 = [1,3,2,4] + +**Output:** 1 + +**Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`. + +**Example 2:** + +**Input:** arr1 = [1,5,3,6,7], arr2 = [4,3,1] + +**Output:** 2 + +**Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`. + +**Example 3:** + +**Input:** arr1 = [1,5,3,6,7], arr2 = [1,6,3,3] + +**Output:** -1 + +**Explanation:** You can't make `arr1` strictly increasing. + +**Constraints:** + +* `1 <= arr1.length, arr2.length <= 2000` +* `0 <= arr1[i], arr2[i] <= 10^9` + +## Solution + +```kotlin +class Solution { + fun makeArrayIncreasing(arr1: IntArray, arr2: IntArray): Int { + arr2.sort() + var start = 0 + for (i in arr2.indices) { + if (arr2[i] != arr2[start]) { + arr2[++start] = arr2[i] + } + } + val l2 = start + 1 + val dp = IntArray(l2 + 2) + for (i in arr1.indices) { + var noChange = dp[dp.size - 1] + if (i > 0 && arr1[i - 1] >= arr1[i]) { + noChange = -1 + } + for (j in dp.size - 2 downTo 1) { + if (arr2[j - 1] < arr1[i] && dp[j] != -1) { + noChange = if (noChange == -1) dp[j] else Math.min(noChange, dp[j]) + } + if (dp[j - 1] != -1) { + dp[j] = 1 + dp[j - 1] + } else { + dp[j] = -1 + } + if (i > 0 && arr1[i - 1] < arr2[j - 1] && dp[dp.size - 1] >= 0) { + dp[j] = if (dp[j] == -1) dp[dp.size - 1] + 1 else Math.min(dp[j], dp[dp.size - 1] + 1) + } + } + dp[0] = -1 + dp[dp.size - 1] = noChange + } + var res = -1 + for (num in dp) { + if (num != -1) { + res = if (res == -1) num else Math.min(res, num) + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1189_maximum_number_of_balloons/readme.md b/src/main/kotlin/g1101_1200/s1189_maximum_number_of_balloons/readme.md new file mode 100644 index 00000000..f45c0951 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1189_maximum_number_of_balloons/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) + +## 1189\. Maximum Number of Balloons + +Easy + +Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon"** as possible. + +You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed. + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2019/09/05/1536_ex1_upd.JPG)** + +**Input:** text = "nlaebolko" + +**Output:** 1 + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2019/09/05/1536_ex2_upd.JPG)** + +**Input:** text = "loonbalxballpoon" + +**Output:** 2 + +**Example 3:** + +**Input:** text = "leetcode" + +**Output:** 0 + +**Constraints:** + +* 1 <= text.length <= 104 +* `text` consists of lower case English letters only. + +## Solution + +```kotlin +class Solution { + fun maxNumberOfBalloons(text: String): Int { + val counts = IntArray(26) + for (c in text.toCharArray()) { + counts[c.code - 'a'.code]++ + } + return Math.min( + counts[0], + Math.min( + counts[1], Math.min(counts[11] / 2, Math.min(counts[14] / 2, counts[13])) + ) + ) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1190_reverse_substrings_between_each_pair_of_parentheses/readme.md b/src/main/kotlin/g1101_1200/s1190_reverse_substrings_between_each_pair_of_parentheses/readme.md new file mode 100644 index 00000000..c569ca11 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1190_reverse_substrings_between_each_pair_of_parentheses/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) + +## 1190\. Reverse Substrings Between Each Pair of Parentheses + +Medium + +You are given a string `s` that consists of lower case English letters and brackets. + +Reverse the strings in each pair of matching parentheses, starting from the innermost one. + +Your result should **not** contain any brackets. + +**Example 1:** + +**Input:** s = "(abcd)" + +**Output:** "dcba" + +**Example 2:** + +**Input:** s = "(u(love)i)" + +**Output:** "iloveu" + +**Explanation:** The substring "love" is reversed first, then the whole string is reversed. + +**Example 3:** + +**Input:** s = "(ed(et(oc))el)" + +**Output:** "leetcode" + +**Explanation:** First, we reverse the substring "oc", then "etco", and finally, the whole string. + +**Constraints:** + +* `1 <= s.length <= 2000` +* `s` only contains lower case English characters and parentheses. +* It is guaranteed that all parentheses are balanced. + +## Solution + +```kotlin +class Solution { + fun reverseParentheses(s: String): String { + val n = s.length + val sb = StringBuilder() + var i = 0 + while (i < n) { + if (s[i] == '(') { + var l = 1 + var r = 0 + val idx = i + while (l != r) { + i++ + if (s[i] == '(') { + l++ + } else if (s[i] == ')') { + r++ + } + } + val reversed = reverseParentheses(s.substring(idx + 1, i)) + val temp = StringBuilder().append(reversed) + sb.append(temp.reverse()) + } else { + sb.append(s[i]) + } + i++ + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1191_k_concatenation_maximum_sum/readme.md b/src/main/kotlin/g1101_1200/s1191_k_concatenation_maximum_sum/readme.md new file mode 100644 index 00000000..c104d9b1 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1191_k_concatenation_maximum_sum/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) + +## 1191\. K-Concatenation Maximum Sum + +Medium + +Given an integer array `arr` and an integer `k`, modify the array by repeating it `k` times. + +For example, if `arr = [1, 2]` and `k = 3` then the modified array will be `[1, 2, 1, 2, 1, 2]`. + +Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be `0` and its sum in that case is `0`. + +As the answer can be very large, return the answer **modulo** 109 + 7. + +**Example 1:** + +**Input:** arr = [1,2], k = 3 + +**Output:** 9 + +**Example 2:** + +**Input:** arr = [1,-2,1], k = 5 + +**Output:** 2 + +**Example 3:** + +**Input:** arr = [-1,-2], k = 7 + +**Output:** 0 + +**Constraints:** + +* 1 <= arr.length <= 105 +* 1 <= k <= 105 +* -104 <= arr[i] <= 104 + +## Solution + +```kotlin +class Solution { + private var mod = (1e9 + 7).toInt() + + fun kConcatenationMaxSum(arr: IntArray, k: Int): Int { + var sum: Long = 0 + for (i in arr.indices) { + sum += arr[i].toLong() + } + return if (sum <= 0 || k == 1) { + var cb: Long = 0 + var ob: Long = 0 + for (i in arr.indices) { + cb = if (arr[i] + cb > arr[i]) { + arr[i] + cb + } else { + arr[i].toLong() + } + if (ob < cb) { + ob = cb + } + } + if (k == 1) { + return (ob % mod).toInt() + } + for (i in arr.indices) { + cb = if (arr[i] + cb > arr[i]) { + arr[i] + cb + } else { + arr[i].toLong() + } + if (ob < cb) { + ob = cb + } + } + (ob % mod).toInt() + } else { + var max1: Long = 0 + var smax: Long = 0 + for (i in arr.indices.reversed()) { + smax += arr[i].toLong() + if (smax > max1) { + max1 = smax + } + } + max1 %= mod.toLong() + var max2: Long = 0 + smax = 0 + for (i in arr.indices) { + smax += arr[i].toLong() + if (smax > max2) { + max2 = smax + } + } + max2 %= mod.toLong() + val ans = max1 + (k - 2) * sum + max2 + (ans % mod).toInt() + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1192_critical_connections_in_a_network/readme.md b/src/main/kotlin/g1101_1200/s1192_critical_connections_in_a_network/readme.md new file mode 100644 index 00000000..10ca1e31 --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1192_critical_connections_in_a_network/readme.md @@ -0,0 +1,97 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1192\. Critical Connections in a Network + +Hard + +There are `n` servers numbered from `0` to `n - 1` connected by undirected server-to-server `connections` forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network. + +A _critical connection_ is a connection that, if removed, will make some servers unable to reach some other server. + +Return all critical connections in the network in any order. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/09/03/1537_ex1_2.png) + +**Input:** n = 4, connections = \[\[0,1],[1,2],[2,0],[1,3]] + +**Output:** [[1,3]] + +**Explanation:** [[3,1]] is also accepted. + +**Example 2:** + +**Input:** n = 2, connections = \[\[0,1]] + +**Output:** [[0,1]] + +**Constraints:** + +* 2 <= n <= 105 +* n - 1 <= connections.length <= 105 +* 0 <= ai, bi <= n - 1 +* ai != bi +* There are no repeated connections. + +## Solution + +```kotlin +class Solution { + fun criticalConnections(n: Int, connections: List>): List> { + val graph: MutableList> = ArrayList() + for (i in 0 until n) { + graph.add(ArrayList()) + } + // build graph + for (conn in connections) { + val x = conn[0] + val y = conn[1] + graph[x].add(y) + graph[y].add(x) + } + // record rank + val rank = IntArray(n) + // store result + val res: MutableList> = ArrayList() + dfs(graph, 0, 1, -1, rank, res) + return res + } + + // rank[] records the each node's smallest rank(min (it's natural rank, neighbors's smallest + // rank)) + private fun dfs( + graph: List>, + node: Int, + time: Int, + parent: Int, + rank: IntArray, + res: MutableList> + ): Int { + if (rank[node] > 0) { + return rank[node] + } + // record the current natural rank for current node + rank[node] = time + for (nei in graph[node]) { + // skip the parent, since this is undirected graph + if (nei == parent) { + continue + } + // step1 : run dfs to get the rank of this nei, if it is visited before, it will reach + // base case immediately + val neiTime = dfs(graph, nei, time + 1, node, rank, res) + // if neiTime is strictly larger than current node's rank, there is no cycle, + // connections between node and nei is a critically connection. + if (neiTime > time) { + res.add(listOf(nei, node)) + } + // keep updating current node's rank with nei's smaller ranks + rank[node] = Math.min(rank[node], neiTime) + } + // return current node's rank to caller + return rank[node] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1195_fizz_buzz_multithreaded/readme.md b/src/main/kotlin/g1101_1200/s1195_fizz_buzz_multithreaded/readme.md new file mode 100644 index 00000000..9085bc1f --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1195_fizz_buzz_multithreaded/readme.md @@ -0,0 +1,111 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 1195\. Fizz Buzz Multithreaded + +Medium + +You have the four functions: + +* `printFizz` that prints the word `"Fizz"` to the console, +* `printBuzz` that prints the word `"Buzz"` to the console, +* `printFizzBuzz` that prints the word `"FizzBuzz"` to the console, and +* `printNumber` that prints a given integer to the console. + +You are given an instance of the class `FizzBuzz` that has four functions: `fizz`, `buzz`, `fizzbuzz` and `number`. The same instance of `FizzBuzz` will be passed to four different threads: + +* **Thread A:** calls `fizz()` that should output the word `"Fizz"`. +* **Thread B:** calls `buzz()` that should output the word `"Buzz"`. +* **Thread C:** calls `fizzbuzz()` that should output the word `"FizzBuzz"`. +* **Thread D:** calls `number()` that should only output the integers. + +Modify the given class to output the series `[1, 2, "Fizz", 4, "Buzz", ...]` where the ith token (**1-indexed**) of the series is: + +* `"FizzBuzz"` if `i` is divisible by `3` and `5`, +* `"Fizz"` if `i` is divisible by `3` and not `5`, +* `"Buzz"` if `i` is divisible by `5` and not `3`, or +* `i` if `i` is not divisible by `3` or `5`. + +Implement the `FizzBuzz` class: + +* `FizzBuzz(int n)` Initializes the object with the number `n` that represents the length of the sequence that should be printed. +* `void fizz(printFizz)` Calls `printFizz` to output `"Fizz"`. +* `void buzz(printBuzz)` Calls `printBuzz` to output `"Buzz"`. +* `void fizzbuzz(printFizzBuzz)` Calls `printFizzBuzz` to output `"FizzBuzz"`. +* `void number(printNumber)` Calls `printnumber` to output the numbers. + +**Example 1:** + +**Input:** n = 15 + +**Output:** [1,2,"fizz",4,"buzz","fizz",7,8,"fizz","buzz",11,"fizz",13,14,"fizzbuzz"] + +**Example 2:** + +**Input:** n = 5 + +**Output:** [1,2,"fizz",4,"buzz"] + +**Constraints:** + +* `1 <= n <= 50` + +## Solution + +```kotlin +import java.util.concurrent.atomic.AtomicInteger +import java.util.function.IntConsumer + +class FizzBuzz(private val n: Int) { + private val count = AtomicInteger(1) + + // printFizz.run() outputs "fizz". + @Throws(InterruptedException::class) + fun fizz(printFizz: Runnable) { + var i: Int + while (count.get().also { i = it } <= n) { + if (i % 3 == 0 && i % 5 != 0) { + printFizz.run() + count.compareAndSet(i, i + 1) + } + } + } + + // printBuzz.run() outputs "buzz". + @Throws(InterruptedException::class) + fun buzz(printBuzz: Runnable) { + var i: Int + while (count.get().also { i = it } <= n) { + count.get() + if (i % 5 == 0 && i % 3 != 0) { + printBuzz.run() + count.compareAndSet(i, i + 1) + } + } + } + + // printFizzBuzz.run() outputs "fizzbuzz". + @Throws(InterruptedException::class) + fun fizzbuzz(printFizzBuzz: Runnable) { + var i: Int + while (count.get().also { i = it } <= n) { + if (i % 15 == 0) { + printFizzBuzz.run() + count.compareAndSet(i, i + 1) + } + } + } + + // printNumber.accept(x) outputs "x", where x is an integer. + @Throws(InterruptedException::class) + fun number(printNumber: IntConsumer) { + var i: Int + while (count.get().also { i = it } <= n) { + if (i % 5 != 0 && i % 3 != 0) { + printNumber.accept(i) + count.compareAndSet(i, i + 1) + } + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1200_minimum_absolute_difference/readme.md b/src/main/kotlin/g1101_1200/s1200_minimum_absolute_difference/readme.md new file mode 100644 index 00000000..3ca5d95d --- /dev/null +++ b/src/main/kotlin/g1101_1200/s1200_minimum_absolute_difference/readme.md @@ -0,0 +1,64 @@ +[![](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) + +## 1200\. Minimum Absolute Difference + +Easy + +Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements. + +Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows + +* `a, b` are from `arr` +* `a < b` +* `b - a` equals to the minimum absolute difference of any two elements in `arr` + +**Example 1:** + +**Input:** arr = [4,2,1,3] + +**Output:** [[1,2],[2,3],[3,4]] + +**Explanation:** The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. + +**Example 2:** + +**Input:** arr = [1,3,6,10,15] + +**Output:** [[1,3]] + +**Example 3:** + +**Input:** arr = [3,8,-10,23,19,-4,-14,27] + +**Output:** [[-14,-10],[19,23],[23,27]] + +**Constraints:** + +* 2 <= arr.length <= 105 +* -106 <= arr[i] <= 106 + +## Solution + +```kotlin +class Solution { + fun minimumAbsDifference(arr: IntArray): List> { + val result: MutableList> = ArrayList() + var min = 10000000 + arr.sort() + var i = 0 + while (i + 1 < arr.size) { + val diff = arr[i + 1] - arr[i] + if (diff <= min) { + if (diff < min) { + min = diff + result.clear() + } + result.add(listOf(arr[i], arr[i + 1])) + } + i++ + } + return result + } +} +``` \ No newline at end of file