From 45931aad046032593f5cc0d389de4879feef94f4 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 2 Jan 2023 07:00:35 +0200 Subject: [PATCH] Added tasks 454-480. --- README.md | 311 ++++++++++-------- .../kotlin/g0401_0500/s0454_4sum_ii/readme.md | 62 ++++ .../g0401_0500/s0455_assign_cookies/readme.md | 54 +++ .../g0401_0500/s0456_132_pattern/readme.md | 71 ++++ .../s0457_circular_array_loop/readme.md | 100 ++++++ .../g0401_0500/s0458_poor_pigs/readme.md | 62 ++++ .../readme.md | 73 ++++ .../g0401_0500/s0460_lfu_cache/readme.md | 174 ++++++++++ .../s0461_hamming_distance/readme.md | 38 +++ .../readme.md | 52 +++ .../s0463_island_perimeter/readme.md | 67 ++++ .../g0401_0500/s0464_can_i_win/readme.md | 89 +++++ .../s0466_count_the_repetitions/readme.md | 73 ++++ .../readme.md | 69 ++++ .../s0468_validate_ip_address/readme.md | 95 ++++++ .../readme.md | 66 ++++ .../s0472_concatenated_words/readme.md | 99 ++++++ .../s0473_matchsticks_to_square/readme.md | 73 ++++ .../s0474_ones_and_zeroes/readme.md | 77 +++++ .../kotlin/g0401_0500/s0475_heaters/readme.md | 78 +++++ .../s0476_number_complement/readme.md | 44 +++ .../s0477_total_hamming_distance/readme.md | 53 +++ .../readme.md | 66 ++++ .../readme.md | 60 ++++ .../s0480_sliding_window_median/readme.md | 98 ++++++ 25 files changed, 1962 insertions(+), 142 deletions(-) create mode 100644 src/main/kotlin/g0401_0500/s0454_4sum_ii/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0455_assign_cookies/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0456_132_pattern/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0457_circular_array_loop/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0458_poor_pigs/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0459_repeated_substring_pattern/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0460_lfu_cache/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0461_hamming_distance/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0462_minimum_moves_to_equal_array_elements_ii/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0463_island_perimeter/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0464_can_i_win/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0466_count_the_repetitions/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0467_unique_substrings_in_wraparound_string/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0468_validate_ip_address/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0470_implement_rand10_using_rand7/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0472_concatenated_words/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0473_matchsticks_to_square/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0474_ones_and_zeroes/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0475_heaters/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0476_number_complement/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0477_total_hamming_distance/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0478_generate_random_point_in_a_circle/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0479_largest_palindrome_product/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0480_sliding_window_median/readme.md diff --git a/README.md b/README.md index 7f7d2759..490d4ae4 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,6 @@ [![](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) > ["For coding interview preparation, LeetCode is one of the best online resource providing a rich library of more than 300 real coding interview questions for you to practice from using one of the 7 supported languages - C, C++, Java, Python, C#, JavaScript, Ruby."](https://www.quora.com/How-effective-is-Leetcode-for-preparing-for-technical-interviews) -* [Dynamic Programming I](#dynamic-programming-i) * [Programming Skills I](#programming-skills-i) * [Programming Skills II](#programming-skills-ii) * [Graph Theory I](#graph-theory-i) @@ -16,147 +15,7 @@ * [Algorithm II](#algorithm-ii) * [Binary Search I](#binary-search-i) * [Binary Search II](#binary-search-ii) - -### Dynamic Programming I - -#### Day 1 - -| | | | | | -|-|-|-|-|-|- - -#### Day 2 - -| | | | | | -|-|-|-|-|-|- -| 0070 |[Climbing Stairs](src/main/kotlin/g0001_0100/s0070_climbing_stairs)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Memoization | 127 | 97.06 - -#### Day 3 - -| | | | | | -|-|-|-|-|-|- -| 0198 |[House Robber](src/main/kotlin/g0101_0200/s0198_house_robber)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 156 | 92.24 -| 0213 |[House Robber II](src/main/kotlin/g0201_0300/s0213_house_robber_ii)| Medium | Array, Dynamic_Programming | 257 | 59.62 - -#### Day 4 - -| | | | | | -|-|-|-|-|-|- -| 0055 |[Jump Game](src/main/kotlin/g0001_0100/s0055_jump_game)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 670 | 66.67 -| 0045 |[Jump Game II](src/main/kotlin/g0001_0100/s0045_jump_game_ii)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Greedy | 227 | 98.14 - -#### Day 5 - -| | | | | | -|-|-|-|-|-|- -| 0053 |[Maximum Subarray](src/main/kotlin/g0001_0100/s0053_maximum_subarray)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer | 662 | 82.48 - -#### Day 6 - -| | | | | | -|-|-|-|-|-|- -| 0152 |[Maximum Product Subarray](src/main/kotlin/g0101_0200/s0152_maximum_product_subarray)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 253 | 88.42 - -#### Day 7 - -| | | | | | -|-|-|-|-|-|- -| 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 - -#### Day 8 - -| | | | | | -|-|-|-|-|-|- -| 0309 |[Best Time to Buy and Sell Stock with Cooldown](src/main/kotlin/g0301_0400/s0309_best_time_to_buy_and_sell_stock_with_cooldown)| Medium | Array, Dynamic_Programming | 272 | 73.33 - -#### Day 9 - -| | | | | | -|-|-|-|-|-|- -| 0139 |[Word Break](src/main/kotlin/g0101_0200/s0139_word_break)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Dynamic_Programming, Trie, Memoization | 197 | 87.17 -| 0042 |[Trapping Rain Water](src/main/kotlin/g0001_0100/s0042_trapping_rain_water)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Two_Pointers, Stack, Monotonic_Stack | 196 | 100.00 - -#### Day 10 - -| | | | | | -|-|-|-|-|-|- -| 0413 |[Arithmetic Slices](src/main/kotlin/g0401_0500/s0413_arithmetic_slices)| Medium | Array, Dynamic_Programming | 156 | 100.00 -| 0091 |[Decode Ways](src/main/kotlin/g0001_0100/s0091_decode_ways)| Medium | Top_Interview_Questions, String, Dynamic_Programming | 237 | 76.88 - -#### Day 11 - -| | | | | | -|-|-|-|-|-|- -| 0264 |[Ugly Number II](src/main/kotlin/g0201_0300/s0264_ugly_number_ii)| Medium | Hash_Table, Dynamic_Programming, Math, Heap_Priority_Queue | 182 | 95.45 -| 0096 |[Unique Binary Search Trees](src/main/kotlin/g0001_0100/s0096_unique_binary_search_trees)| Medium | Top_100_Liked_Questions, Dynamic_Programming, Math, Tree, Binary_Tree, Binary_Search_Tree | 147 | 88.52 - -#### Day 12 - -| | | | | | -|-|-|-|-|-|- -| 0118 |[Pascal's Triangle](src/main/kotlin/g0101_0200/s0118_pascals_triangle)| Easy | Top_Interview_Questions, Array, Dynamic_Programming | 277 | 33.22 -| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming | 157 | 97.27 - -#### Day 13 - -| | | | | | -|-|-|-|-|-|- -| 0120 |[Triangle](src/main/kotlin/g0101_0200/s0120_triangle)| Medium | Array, Dynamic_Programming | 194 | 97.87 - -#### Day 14 - -| | | | | | -|-|-|-|-|-|- -| 0304 |[Range Sum Query 2D - Immutable](src/main/kotlin/g0301_0400/s0304_range_sum_query_2d_immutable)| Medium | Array, Matrix, Design, Prefix_Sum | 1373 | 85.71 - -#### Day 15 - -| | | | | | -|-|-|-|-|-|- -| 0062 |[Unique Paths](src/main/kotlin/g0001_0100/s0062_unique_paths)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Combinatorics | 209 | 49.18 -| 0063 |[Unique Paths II](src/main/kotlin/g0001_0100/s0063_unique_paths_ii)| Medium | Array, Dynamic_Programming, Matrix | 187 | 84.62 - -#### Day 16 - -| | | | | | -|-|-|-|-|-|- -| 0064 |[Minimum Path Sum](src/main/kotlin/g0001_0100/s0064_minimum_path_sum)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Matrix | 222 | 95.70 -| 0221 |[Maximal Square](src/main/kotlin/g0201_0300/s0221_maximal_square)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Matrix | 614 | 44.00 - -#### Day 17 - -| | | | | | -|-|-|-|-|-|- -| 0005 |[Longest Palindromic Substring](src/main/kotlin/g0001_0100/s0005_longest_palindromic_substring)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming | 323 | 75.48 - -#### Day 18 - -| | | | | | -|-|-|-|-|-|- -| 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search | 318 | 82.28 -| 0376 |[Wiggle Subsequence](src/main/kotlin/g0301_0400/s0376_wiggle_subsequence)| Medium | Array, Dynamic_Programming, Greedy | 162 | 88.89 - -#### Day 19 - -| | | | | | -|-|-|-|-|-|- -| 0392 |[Is Subsequence](src/main/kotlin/g0301_0400/s0392_is_subsequence)| Easy | String, Dynamic_Programming, Two_Pointers | 156 | 87.74 -| 1143 |[Longest Common Subsequence](src/main/kotlin/g1101_1200/s1143_longest_common_subsequence)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming | 307 | 38.36 -| 0072 |[Edit Distance](src/main/kotlin/g0001_0100/s0072_edit_distance)| Hard | Top_100_Liked_Questions, String, Dynamic_Programming | 320 | 63.53 - -#### Day 20 - -| | | | | | -|-|-|-|-|-|- -| 0322 |[Coin Change](src/main/kotlin/g0301_0400/s0322_coin_change)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Breadth_First_Search | 332 | 50.68 - -#### Day 21 - -| | | | | | -|-|-|-|-|-|- -| 0377 |[Combination Sum IV](src/main/kotlin/g0301_0400/s0377_combination_sum_iv)| Medium | Array, Dynamic_Programming | 217 | 72.41 -| 0343 |[Integer Break](src/main/kotlin/g0301_0400/s0343_integer_break)| Medium | Dynamic_Programming, Math | 218 | 63.89 -| 0279 |[Perfect Squares](src/main/kotlin/g0201_0300/s0279_perfect_squares)| Medium | Top_Interview_Questions, Dynamic_Programming, Math, Breadth_First_Search | 176 | 98.80 +* [Dynamic Programming I](#dynamic-programming-i) ### Programming Skills I @@ -243,6 +102,7 @@ | | | | | | |-|-|-|-|-|- | 0110 |[Balanced Binary Tree](src/main/kotlin/g0101_0200/s0110_balanced_binary_tree)| Easy | Depth_First_Search, Tree, Binary_Tree | 310 | 63.63 +| 0459 |[Repeated Substring Pattern](src/main/kotlin/g0401_0500/s0459_repeated_substring_pattern)| Easy | String, String_Matching | 201 | 100.00 #### Day 3 @@ -781,6 +641,7 @@ | 0448 |[Find All Numbers Disappeared in an Array](src/main/kotlin/g0401_0500/s0448_find_all_numbers_disappeared_in_an_array)| Easy | Array, Hash_Table | 394 | 100.00 | 0442 |[Find All Duplicates in an Array](src/main/kotlin/g0401_0500/s0442_find_all_duplicates_in_an_array)| Medium | Array, Hash_Table | 480 | 73.81 | 0041 |[First Missing Positive](src/main/kotlin/g0001_0100/s0041_first_missing_positive)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table | 345 | 100.00 +| 0456 |[132 Pattern](src/main/kotlin/g0401_0500/s0456_132_pattern)| Medium | Array, Binary_Search, Stack, Ordered_Set, Monotonic_Stack | 434 | 100.00 | 0239 |[Sliding Window Maximum](src/main/kotlin/g0201_0300/s0239_sliding_window_maximum)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Heap_Priority_Queue, Sliding_Window, Queue, Monotonic_Queue | 1059 | 86.14 #### Udemy Two Pointers @@ -908,6 +769,7 @@ | 0191 |[Number of 1 Bits](src/main/kotlin/g0101_0200/s0191_number_of_1_bits)| Easy | Top_Interview_Questions, Bit_Manipulation | 237 | 68.44 | 0389 |[Find the Difference](src/main/kotlin/g0301_0400/s0389_find_the_difference)| Easy | String, Hash_Table, Sorting, Bit_Manipulation | 256 | 64.81 | 0190 |[Reverse Bits](src/main/kotlin/g0101_0200/s0190_reverse_bits)| Easy | Top_Interview_Questions, Bit_Manipulation, Divide_and_Conquer | 198 | 81.82 +| 0461 |[Hamming Distance](src/main/kotlin/g0401_0500/s0461_hamming_distance)| Easy | Bit_Manipulation | 150 | 96.15 | 0338 |[Counting Bits](src/main/kotlin/g0301_0400/s0338_counting_bits)| Easy | Top_100_Liked_Questions, Dynamic_Programming, Bit_Manipulation | 186 | 99.26 | 0371 |[Sum of Two Integers](src/main/kotlin/g0301_0400/s0371_sum_of_two_integers)| Medium | Top_Interview_Questions, Math, Bit_Manipulation | 129 | 95.45 | 0029 |[Divide Two Integers](src/main/kotlin/g0001_0100/s0029_divide_two_integers)| Medium | Top_Interview_Questions, Math, Bit_Manipulation | 281 | 31.67 @@ -1592,6 +1454,147 @@ | | | | | | |-|-|-|-|-|- +### Dynamic Programming I + +#### Day 1 + +| | | | | | +|-|-|-|-|-|- + +#### Day 2 + +| | | | | | +|-|-|-|-|-|- +| 0070 |[Climbing Stairs](src/main/kotlin/g0001_0100/s0070_climbing_stairs)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Memoization | 127 | 97.06 + +#### Day 3 + +| | | | | | +|-|-|-|-|-|- +| 0198 |[House Robber](src/main/kotlin/g0101_0200/s0198_house_robber)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 156 | 92.24 +| 0213 |[House Robber II](src/main/kotlin/g0201_0300/s0213_house_robber_ii)| Medium | Array, Dynamic_Programming | 257 | 59.62 + +#### Day 4 + +| | | | | | +|-|-|-|-|-|- +| 0055 |[Jump Game](src/main/kotlin/g0001_0100/s0055_jump_game)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Greedy | 670 | 66.67 +| 0045 |[Jump Game II](src/main/kotlin/g0001_0100/s0045_jump_game_ii)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Greedy | 227 | 98.14 + +#### Day 5 + +| | | | | | +|-|-|-|-|-|- +| 0053 |[Maximum Subarray](src/main/kotlin/g0001_0100/s0053_maximum_subarray)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer | 662 | 82.48 + +#### Day 6 + +| | | | | | +|-|-|-|-|-|- +| 0152 |[Maximum Product Subarray](src/main/kotlin/g0101_0200/s0152_maximum_product_subarray)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming | 253 | 88.42 + +#### Day 7 + +| | | | | | +|-|-|-|-|-|- +| 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 + +#### Day 8 + +| | | | | | +|-|-|-|-|-|- +| 0309 |[Best Time to Buy and Sell Stock with Cooldown](src/main/kotlin/g0301_0400/s0309_best_time_to_buy_and_sell_stock_with_cooldown)| Medium | Array, Dynamic_Programming | 272 | 73.33 + +#### Day 9 + +| | | | | | +|-|-|-|-|-|- +| 0139 |[Word Break](src/main/kotlin/g0101_0200/s0139_word_break)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Dynamic_Programming, Trie, Memoization | 197 | 87.17 +| 0042 |[Trapping Rain Water](src/main/kotlin/g0001_0100/s0042_trapping_rain_water)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Two_Pointers, Stack, Monotonic_Stack | 196 | 100.00 + +#### Day 10 + +| | | | | | +|-|-|-|-|-|- +| 0413 |[Arithmetic Slices](src/main/kotlin/g0401_0500/s0413_arithmetic_slices)| Medium | Array, Dynamic_Programming | 156 | 100.00 +| 0091 |[Decode Ways](src/main/kotlin/g0001_0100/s0091_decode_ways)| Medium | Top_Interview_Questions, String, Dynamic_Programming | 237 | 76.88 + +#### Day 11 + +| | | | | | +|-|-|-|-|-|- +| 0264 |[Ugly Number II](src/main/kotlin/g0201_0300/s0264_ugly_number_ii)| Medium | Hash_Table, Dynamic_Programming, Math, Heap_Priority_Queue | 182 | 95.45 +| 0096 |[Unique Binary Search Trees](src/main/kotlin/g0001_0100/s0096_unique_binary_search_trees)| Medium | Top_100_Liked_Questions, Dynamic_Programming, Math, Tree, Binary_Tree, Binary_Search_Tree | 147 | 88.52 + +#### Day 12 + +| | | | | | +|-|-|-|-|-|- +| 0118 |[Pascal's Triangle](src/main/kotlin/g0101_0200/s0118_pascals_triangle)| Easy | Top_Interview_Questions, Array, Dynamic_Programming | 277 | 33.22 +| 0119 |[Pascal's Triangle II](src/main/kotlin/g0101_0200/s0119_pascals_triangle_ii)| Easy | Array, Dynamic_Programming | 157 | 97.27 + +#### Day 13 + +| | | | | | +|-|-|-|-|-|- +| 0120 |[Triangle](src/main/kotlin/g0101_0200/s0120_triangle)| Medium | Array, Dynamic_Programming | 194 | 97.87 + +#### Day 14 + +| | | | | | +|-|-|-|-|-|- +| 0304 |[Range Sum Query 2D - Immutable](src/main/kotlin/g0301_0400/s0304_range_sum_query_2d_immutable)| Medium | Array, Matrix, Design, Prefix_Sum | 1373 | 85.71 + +#### Day 15 + +| | | | | | +|-|-|-|-|-|- +| 0062 |[Unique Paths](src/main/kotlin/g0001_0100/s0062_unique_paths)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Math, Combinatorics | 209 | 49.18 +| 0063 |[Unique Paths II](src/main/kotlin/g0001_0100/s0063_unique_paths_ii)| Medium | Array, Dynamic_Programming, Matrix | 187 | 84.62 + +#### Day 16 + +| | | | | | +|-|-|-|-|-|- +| 0064 |[Minimum Path Sum](src/main/kotlin/g0001_0100/s0064_minimum_path_sum)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Matrix | 222 | 95.70 +| 0221 |[Maximal Square](src/main/kotlin/g0201_0300/s0221_maximal_square)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Matrix | 614 | 44.00 + +#### Day 17 + +| | | | | | +|-|-|-|-|-|- +| 0005 |[Longest Palindromic Substring](src/main/kotlin/g0001_0100/s0005_longest_palindromic_substring)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Dynamic_Programming | 323 | 75.48 + +#### Day 18 + +| | | | | | +|-|-|-|-|-|- +| 0300 |[Longest Increasing Subsequence](src/main/kotlin/g0201_0300/s0300_longest_increasing_subsequence)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Binary_Search | 318 | 82.28 +| 0376 |[Wiggle Subsequence](src/main/kotlin/g0301_0400/s0376_wiggle_subsequence)| Medium | Array, Dynamic_Programming, Greedy | 162 | 88.89 + +#### Day 19 + +| | | | | | +|-|-|-|-|-|- +| 0392 |[Is Subsequence](src/main/kotlin/g0301_0400/s0392_is_subsequence)| Easy | String, Dynamic_Programming, Two_Pointers | 156 | 87.74 +| 1143 |[Longest Common Subsequence](src/main/kotlin/g1101_1200/s1143_longest_common_subsequence)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming | 307 | 38.36 +| 0072 |[Edit Distance](src/main/kotlin/g0001_0100/s0072_edit_distance)| Hard | Top_100_Liked_Questions, String, Dynamic_Programming | 320 | 63.53 + +#### Day 20 + +| | | | | | +|-|-|-|-|-|- +| 0322 |[Coin Change](src/main/kotlin/g0301_0400/s0322_coin_change)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Breadth_First_Search | 332 | 50.68 + +#### Day 21 + +| | | | | | +|-|-|-|-|-|- +| 0377 |[Combination Sum IV](src/main/kotlin/g0301_0400/s0377_combination_sum_iv)| Medium | Array, Dynamic_Programming | 217 | 72.41 +| 0343 |[Integer Break](src/main/kotlin/g0301_0400/s0343_integer_break)| Medium | Dynamic_Programming, Math | 218 | 63.89 +| 0279 |[Perfect Squares](src/main/kotlin/g0201_0300/s0279_perfect_squares)| Medium | Top_Interview_Questions, Dynamic_Programming, Math, Breadth_First_Search | 176 | 98.80 + ## Algorithms | # | Title | Difficulty | Tag | Time, ms | Time, % @@ -1605,6 +1608,30 @@ | 0560 |[Subarray Sum Equals K](src/main/kotlin/g0501_0600/s0560_subarray_sum_equals_k)| Medium | Top_100_Liked_Questions, Array, Hash_Table, Prefix_Sum, Data_Structure_II_Day_5_Array | 692 | 53.27 | 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 | 0494 |[Target Sum](src/main/kotlin/g0401_0500/s0494_target_sum)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Backtracking | 308 | 89.61 +| 0480 |[Sliding Window Median](src/main/kotlin/g0401_0500/s0480_sliding_window_median)| Hard | Array, Hash_Table, Heap_Priority_Queue, Sliding_Window | 409 | 100.00 +| 0479 |[Largest Palindrome Product](src/main/kotlin/g0401_0500/s0479_largest_palindrome_product)| Hard | Math | 147 | 100.00 +| 0478 |[Generate Random Point in a Circle](src/main/kotlin/g0401_0500/s0478_generate_random_point_in_a_circle)| Medium | Math, Geometry, Randomized, Rejection_Sampling | 862 | 100.00 +| 0477 |[Total Hamming Distance](src/main/kotlin/g0401_0500/s0477_total_hamming_distance)| Medium | Array, Math, Bit_Manipulation | 298 | 100.00 +| 0476 |[Number Complement](src/main/kotlin/g0401_0500/s0476_number_complement)| Easy | Bit_Manipulation | 133 | 100.00 +| 0475 |[Heaters](src/main/kotlin/g0401_0500/s0475_heaters)| Medium | Array, Sorting, Binary_Search, Two_Pointers | 356 | 87.50 +| 0474 |[Ones and Zeroes](src/main/kotlin/g0401_0500/s0474_ones_and_zeroes)| Medium | Array, String, Dynamic_Programming | 204 | 100.00 +| 0473 |[Matchsticks to Square](src/main/kotlin/g0401_0500/s0473_matchsticks_to_square)| Medium | Array, Dynamic_Programming, Bit_Manipulation, Backtracking, Bitmask | 255 | 100.00 +| 0472 |[Concatenated Words](src/main/kotlin/g0401_0500/s0472_concatenated_words)| Hard | Array, String, Dynamic_Programming, Depth_First_Search, Trie | 484 | 100.00 +| 0470 |[Implement Rand10() Using Rand7()](src/main/kotlin/g0401_0500/s0470_implement_rand10_using_rand7)| Medium | Math, Randomized, Probability_and_Statistics, Rejection_Sampling | 220 | 100.00 +| 0468 |[Validate IP Address](src/main/kotlin/g0401_0500/s0468_validate_ip_address)| Medium | String | 192 | 62.50 +| 0467 |[Unique Substrings in Wraparound String](src/main/kotlin/g0401_0500/s0467_unique_substrings_in_wraparound_string)| Medium | String, Dynamic_Programming | 197 | 100.00 +| 0466 |[Count The Repetitions](src/main/kotlin/g0401_0500/s0466_count_the_repetitions)| Hard | String, Dynamic_Programming | 147 | 100.00 +| 0464 |[Can I Win](src/main/kotlin/g0401_0500/s0464_can_i_win)| Medium | Dynamic_Programming, Math, Bit_Manipulation, Bitmask, Memoization, Game_Theory | 213 | 100.00 +| 0463 |[Island Perimeter](src/main/kotlin/g0401_0500/s0463_island_perimeter)| Easy | Array, Depth_First_Search, Breadth_First_Search, Matrix | 381 | 98.04 +| 0462 |[Minimum Moves to Equal Array Elements II](src/main/kotlin/g0401_0500/s0462_minimum_moves_to_equal_array_elements_ii)| Medium | Array, Math, Sorting | 210 | 100.00 +| 0461 |[Hamming Distance](src/main/kotlin/g0401_0500/s0461_hamming_distance)| Easy | Bit_Manipulation, Udemy_Bit_Manipulation | 150 | 96.15 +| 0460 |[LFU Cache](src/main/kotlin/g0401_0500/s0460_lfu_cache)| Hard | Hash_Table, Design, Linked_List, Doubly_Linked_List | 1143 | 100.00 +| 0459 |[Repeated Substring Pattern](src/main/kotlin/g0401_0500/s0459_repeated_substring_pattern)| Easy | String, String_Matching, Programming_Skills_II_Day_2 | 201 | 100.00 +| 0458 |[Poor Pigs](src/main/kotlin/g0401_0500/s0458_poor_pigs)| Hard | Dynamic_Programming, Math, Combinatorics | 133 | 80.00 +| 0457 |[Circular Array Loop](src/main/kotlin/g0401_0500/s0457_circular_array_loop)| Medium | Array, Hash_Table, Two_Pointers | 143 | 100.00 +| 0456 |[132 Pattern](src/main/kotlin/g0401_0500/s0456_132_pattern)| Medium | Array, Binary_Search, Stack, Ordered_Set, Monotonic_Stack, Udemy_Arrays | 434 | 100.00 +| 0455 |[Assign Cookies](src/main/kotlin/g0401_0500/s0455_assign_cookies)| Easy | Array, Sorting, Greedy | 260 | 96.67 +| 0454 |[4Sum II](src/main/kotlin/g0401_0500/s0454_4sum_ii)| Medium | Top_Interview_Questions, Array, Hash_Table | 660 | 85.71 | 0453 |[Minimum Moves to Equal Array Elements](src/main/kotlin/g0401_0500/s0453_minimum_moves_to_equal_array_elements)| Medium | Array, Math | 282 | 100.00 | 0452 |[Minimum Number of Arrows to Burst Balloons](src/main/kotlin/g0401_0500/s0452_minimum_number_of_arrows_to_burst_balloons)| Medium | Array, Sorting, Greedy | 934 | 100.00 | 0451 |[Sort Characters By Frequency](src/main/kotlin/g0401_0500/s0451_sort_characters_by_frequency)| Medium | String, Hash_Table, Sorting, Heap_Priority_Queue, Counting, Bucket_Sort, Data_Structure_II_Day_21_Heap_Priority_Queue | 288 | 81.72 diff --git a/src/main/kotlin/g0401_0500/s0454_4sum_ii/readme.md b/src/main/kotlin/g0401_0500/s0454_4sum_ii/readme.md new file mode 100644 index 00000000..33ddcc28 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0454_4sum_ii/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) + +## 454\. 4Sum II + +Medium + +Given four integer arrays `nums1`, `nums2`, `nums3`, and `nums4` all of length `n`, return the number of tuples `(i, j, k, l)` such that: + +* `0 <= i, j, k, l < n` +* `nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0` + +**Example 1:** + +**Input:** nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] + +**Output:** 2 + +**Explanation:** The two tuples are: + +1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0 + +2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0 + +**Example 2:** + +**Input:** nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] + +**Output:** 1 + +**Constraints:** + +* `n == nums1.length` +* `n == nums2.length` +* `n == nums3.length` +* `n == nums4.length` +* `1 <= n <= 200` +* -228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228 + +## Solution + +```kotlin +class Solution { + fun fourSumCount(nums1: IntArray, nums2: IntArray, nums3: IntArray, nums4: IntArray): Int { + var count = 0 + val map: MutableMap = HashMap() + for (k in nums3) { + for (i in nums4) { + val sum = k + i + map[sum] = map.getOrDefault(sum, 0) + 1 + } + } + for (k in nums1) { + for (i in nums2) { + val m = -(k + i) + count += map.getOrDefault(m, 0) + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0455_assign_cookies/readme.md b/src/main/kotlin/g0401_0500/s0455_assign_cookies/readme.md new file mode 100644 index 00000000..9e1c3f61 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0455_assign_cookies/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) + +## 455\. Assign Cookies + +Easy + +Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. + +Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number. + +**Example 1:** + +**Input:** g = [1,2,3], s = [1,1] + +**Output:** 1 + +**Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. + +**Example 2:** + +**Input:** g = [1,2], s = [1,2,3] + +**Output:** 2 + +**Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. + +**Constraints:** + +* 1 <= g.length <= 3 * 104 +* 0 <= s.length <= 3 * 104 +* 1 <= g[i], s[j] <= 231 - 1 + +## Solution + +```kotlin +class Solution { + fun findContentChildren(g: IntArray, s: IntArray): Int { + g.sort() + s.sort() + var result = 0 + var i = 0 + var j = 0 + while (i < g.size && j < s.size) { + if (s[j] >= g[i]) { + result++ + i++ + } + j++ + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0456_132_pattern/readme.md b/src/main/kotlin/g0401_0500/s0456_132_pattern/readme.md new file mode 100644 index 00000000..746721a3 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0456_132_pattern/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) + +## 456\. 132 Pattern + +Medium + +Given an array of `n` integers `nums`, a **132 pattern** is a subsequence of three integers `nums[i]`, `nums[j]` and `nums[k]` such that `i < j < k` and `nums[i] < nums[k] < nums[j]`. + +Return `true` _if there is a **132 pattern** in_ `nums`_, otherwise, return_ `false`_._ + +**Example 1:** + +**Input:** nums = [1,2,3,4] + +**Output:** false + +**Explanation:** There is no 132 pattern in the sequence. + +**Example 2:** + +**Input:** nums = [3,1,4,2] + +**Output:** true + +**Explanation:** There is a 132 pattern in the sequence: [1, 4, 2]. + +**Example 3:** + +**Input:** nums = [-1,3,2,0] + +**Output:** true + +**Explanation:** There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. + +**Constraints:** + +* `n == nums.length` +* 1 <= n <= 2 * 105 +* -109 <= nums[i] <= 109 + +## Solution + +```kotlin +import java.util.Deque +import java.util.LinkedList + +class Solution { + /* + * It scans only once, this is the power of using correct data structure. + * It goes from the right to the left. + * It keeps pushing elements into the stack, + * but it also keeps poping elements out of the stack as long as the current element is bigger than this number. + */ + fun find132pattern(nums: IntArray): Boolean { + val stack: Deque = LinkedList() + var s3 = Int.MIN_VALUE + for (i in nums.indices.reversed()) { + if (nums[i] < s3) { + return true + } else { + while (!stack.isEmpty() && nums[i] > stack.peek()) { + s3 = Math.max(s3, stack.pop()) + } + } + stack.push(nums[i]) + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0457_circular_array_loop/readme.md b/src/main/kotlin/g0401_0500/s0457_circular_array_loop/readme.md new file mode 100644 index 00000000..009756c8 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0457_circular_array_loop/readme.md @@ -0,0 +1,100 @@ +[![](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) + +## 457\. Circular Array Loop + +Medium + +You are playing a game involving a **circular** array of non-zero integers `nums`. Each `nums[i]` denotes the number of indices forward/backward you must move if you are located at index `i`: + +* If `nums[i]` is positive, move `nums[i]` steps **forward**, and +* If `nums[i]` is negative, move `nums[i]` steps **backward**. + +Since the array is **circular**, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element. + +A **cycle** in the array consists of a sequence of indices `seq` of length `k` where: + +* Following the movement rules above results in the repeating index sequence `seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ...` +* Every `nums[seq[j]]` is either **all positive** or **all negative**. +* `k > 1` + +Return `true` _if there is a **cycle** in_ `nums`_, or_ `false` _otherwise_. + +**Example 1:** + +**Input:** nums = [2,-1,1,2,2] + +**Output:** true + +**Explanation:** There is a cycle from index 0 -> 2 -> 3 -> 0 -> ... The cycle's length is 3. + +**Example 2:** + +**Input:** nums = [-1,2] + +**Output:** false + +**Explanation:** The sequence from index 1 -> 1 -> 1 -> ... is not a cycle because the sequence's length is 1. By definition the sequence's length must be strictly greater than 1 to be a cycle. + +**Example 3:** + +**Input:** nums = [-2,1,-1,-2,-2] + +**Output:** false + +**Explanation:** The sequence from index 1 -> 2 -> 1 -> ... is not a cycle because nums[1] is positive, but nums[2] is negative. Every nums[seq[j]] must be either all positive or all negative. + +**Constraints:** + +* `1 <= nums.length <= 5000` +* `-1000 <= nums[i] <= 1000` +* `nums[i] != 0` + +**Follow up:** Could you solve it in `O(n)` time complexity and `O(1)` extra space complexity? + +## Solution + +```kotlin +class Solution { + fun circularArrayLoop(arr: IntArray): Boolean { + val n = arr.size + val map: MutableMap = HashMap() + // arr[i]%n==0 (cycle) + for (start in 0 until n) { + if (map.containsKey(start)) { + // check if already visited + continue + } + var curr = start + // Check if the current index is valid + while (isValidCycle(start, curr, arr)) { + // marking current index visited and set value as start of loop + map[curr] = start + // steps to jump; + val jump = arr[curr] % n + // Jumping x steps backwards is same as jumping (n-x) steps forward + // going to next index; + curr = (curr + jump + n) % n + if (map.containsKey(curr)) { + // value already processed + if (map[curr] == start) { + // If equal to start then we have found a loop + return true + } + // Else we can break since this has already been visited hence we will get the + // same result as before + break + } + } + } + return false + } + + private fun isValidCycle(start: Int, curr: Int, arr: IntArray): Boolean { + return ( + (arr[start] <= 0 || arr[curr] >= 0) && + (arr[start] >= 0 || arr[curr] <= 0) && arr[curr] % arr.size != 0 + ) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0458_poor_pigs/readme.md b/src/main/kotlin/g0401_0500/s0458_poor_pigs/readme.md new file mode 100644 index 00000000..41c69ac5 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0458_poor_pigs/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) + +## 458\. Poor Pigs + +Hard + +There are `buckets` buckets of liquid, where **exactly one** of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have `minutesToTest` minutes to determine which bucket is poisonous. + +You can feed the pigs according to these steps: + +1. Choose some live pigs to feed. +2. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. +3. Wait for `minutesToDie` minutes. You may **not** feed any other pigs during this time. +4. After `minutesToDie` minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive. +5. Repeat this process until you run out of time. + +Given `buckets`, `minutesToDie`, and `minutesToTest`, return _the **minimum** number of pigs needed to figure out which bucket is poisonous within the allotted time_. + +**Example 1:** + +**Input:** buckets = 1000, minutesToDie = 15, minutesToTest = 60 + +**Output:** 5 + +**Example 2:** + +**Input:** buckets = 4, minutesToDie = 15, minutesToTest = 15 + +**Output:** 2 + +**Example 3:** + +**Input:** buckets = 4, minutesToDie = 15, minutesToTest = 30 + +**Output:** 2 + +**Constraints:** + +* `1 <= buckets <= 1000` +* `1 <= minutesToDie <= minutesToTest <= 100` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun poorPigs(buckets: Int, minutesToDie: Int, minutesToTest: Int): Int { + var buckets = buckets + if (buckets-- == 1) { + return 0 + } + val base = minutesToTest / minutesToDie + 1 + var count = 0 + while (buckets > 0) { + buckets /= base + count++ + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0459_repeated_substring_pattern/readme.md b/src/main/kotlin/g0401_0500/s0459_repeated_substring_pattern/readme.md new file mode 100644 index 00000000..1ca2813c --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0459_repeated_substring_pattern/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) + +## 459\. Repeated Substring Pattern + +Easy + +Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. + +**Example 1:** + +**Input:** s = "abab" + +**Output:** true + +**Explanation:** It is the substring "ab" twice. + +**Example 2:** + +**Input:** s = "aba" + +**Output:** false + +**Example 3:** + +**Input:** s = "abcabcabcabc" + +**Output:** true + +**Explanation:** It is the substring "abc" four times or the substring "abcabc" twice. + +**Constraints:** + +* 1 <= s.length <= 104 +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun repeatedSubstringPattern(s: String): Boolean { + val n = s.length + if (n < 2) { + return false + } + var i = 0 + while (i < (n + 1) / 2) { + if (n % (i + 1) != 0) { + i++ + continue + } + var match = true + val substring = s.substring(0, i + 1) + var skippedI = i + var j = i + 1 + while (j < n) { + if (s.substring(j, j + i + 1) != substring) { + match = false + break + } + skippedI += i + 1 + j += i + 1 + } + if (match) { + return true + } + i = skippedI + i++ + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0460_lfu_cache/readme.md b/src/main/kotlin/g0401_0500/s0460_lfu_cache/readme.md new file mode 100644 index 00000000..5d8350fb --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0460_lfu_cache/readme.md @@ -0,0 +1,174 @@ +[![](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) + +## 460\. LFU Cache + +Hard + +Design and implement a data structure for a [Least Frequently Used (LFU)](https://en.wikipedia.org/wiki/Least_frequently_used) cache. + +Implement the `LFUCache` class: + +* `LFUCache(int capacity)` Initializes the object with the `capacity` of the data structure. +* `int get(int key)` Gets the value of the `key` if the `key` exists in the cache. Otherwise, returns `-1`. +* `void put(int key, int value)` Update the value of the `key` if present, or inserts the `key` if not already present. When the cache reaches its `capacity`, it should invalidate and remove the **least frequently used** key before inserting a new item. For this problem, when there is a **tie** (i.e., two or more keys with the same frequency), the **least recently used** `key` would be invalidated. + +To determine the least frequently used key, a **use counter** is maintained for each key in the cache. The key with the smallest **use counter** is the least frequently used key. + +When a key is first inserted into the cache, its **use counter** is set to `1` (due to the `put` operation). The **use counter** for a key in the cache is incremented either a `get` or `put` operation is called on it. + +The functions `get` and `put` must each run in `O(1)` average time complexity. + +**Example 1:** + +**Input** + + ["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"] + [[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]] + +**Output:** [null, null, null, 1, null, -1, 3, null, -1, 3, 4] + +**Explanation:** + + // cnt(x) = the use counter for key x + + // cache=[] will show the last used order for tiebreakers (leftmost element is most recent) + + LFUCache lfu = new LFUCache(2); + lfu.put(1, 1); // cache=[1,_], cnt(1)=1 + lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1 + lfu.get(1); // return 1 + // cache=[1,2], cnt(2)=1, cnt(1)=2 + lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2. + // cache=[3,1], cnt(3)=1, cnt(1)=2 + lfu.get(2); // return -1 (not found) + lfu.get(3); // return 3 + // cache=[3,1], cnt(3)=2, cnt(1)=2 + lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1. + // cache=[4,3], cnt(4)=1, cnt(3)=2 + lfu.get(1); // return -1 (not found) + lfu.get(3); // return 3 + // cache=[3,4], cnt(4)=1, cnt(3)=3 + lfu.get(4); // return 4 + // cache=[3,4], cnt(4)=2, cnt(3)=3 + +**Constraints:** + +* 0 <= capacity <= 104 +* 0 <= key <= 105 +* 0 <= value <= 109 +* At most 2 * 105 calls will be made to `get` and `put`. + +## Solution + +```kotlin +class LFUCache(capacity: Int) { + private class Node { + var prev: Node? = null + var next: Node? = null + var key = -1 + var `val` = 0 + var freq = 0 + } + + private val endOfBlock: MutableMap + private val map: MutableMap + private val capacity: Int + private val linkedList: Node + + init { + endOfBlock = HashMap() + map = HashMap() + this.capacity = capacity + linkedList = Node() + } + + operator fun get(key: Int): Int { + if (map.containsKey(key)) { + val newEndNode = map[key] + val endNode: Node? + val currEndNode = endOfBlock[newEndNode!!.freq] + if (currEndNode === newEndNode) { + findNewEndOfBlock(newEndNode) + if (currEndNode.next == null || currEndNode.next!!.freq > newEndNode.freq + 1) { + newEndNode.freq++ + endOfBlock[newEndNode.freq] = newEndNode + return newEndNode.`val` + } + } + if (newEndNode.next != null) { + newEndNode.next!!.prev = newEndNode.prev + } + newEndNode.prev!!.next = newEndNode.next + newEndNode.freq++ + endNode = if (currEndNode!!.next == null || currEndNode.next!!.freq > newEndNode.freq) { + currEndNode + } else { + endOfBlock[newEndNode.freq] + } + endOfBlock[newEndNode.freq] = newEndNode + if (endNode!!.next != null) { + endNode.next!!.prev = newEndNode + } + newEndNode.next = endNode.next + endNode.next = newEndNode + newEndNode.prev = endNode + return newEndNode.`val` + } + return -1 + } + + fun put(key: Int, value: Int) { + val endNode: Node? + val newEndNode: Node + if (capacity == 0) { + return + } + if (map.containsKey(key)) { + map[key]!!.`val` = value + get(key) + } else { + if (map.size == capacity) { + val toDelete = linkedList.next + map.remove(toDelete!!.key) + if (toDelete.next != null) { + toDelete.next!!.prev = linkedList + } + linkedList.next = toDelete.next + if (endOfBlock[toDelete.freq] === toDelete) { + endOfBlock.remove(toDelete.freq) + } + } + newEndNode = Node() + newEndNode.key = key + newEndNode.`val` = value + newEndNode.freq = 1 + map[key] = newEndNode + endNode = endOfBlock.getOrDefault(1, linkedList) + endOfBlock[1] = newEndNode + if (endNode!!.next != null) { + endNode.next!!.prev = newEndNode + } + newEndNode.next = endNode.next + endNode.next = newEndNode + newEndNode.prev = endNode + } + } + + private fun findNewEndOfBlock(node: Node?) { + val prev = node!!.prev + if (prev!!.freq == node.freq) { + endOfBlock[node.freq] = prev + } else { + endOfBlock.remove(node.freq) + } + } +} + +/* + * Your LFUCache object will be instantiated and called as such: + * var obj = LFUCache(capacity) + * var param_1 = obj.get(key) + * obj.put(key,value) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0461_hamming_distance/readme.md b/src/main/kotlin/g0401_0500/s0461_hamming_distance/readme.md new file mode 100644 index 00000000..7c8a033d --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0461_hamming_distance/readme.md @@ -0,0 +1,38 @@ +[![](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) + +## 461\. Hamming Distance + +Easy + +The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. + +Given two integers `x` and `y`, return _the **Hamming distance** between them_. + +**Example 1:** + +**Input:** x = 1, y = 4 + +**Output:** 2 + +**Explanation:** 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different. + +**Example 2:** + +**Input:** x = 3, y = 1 + +**Output:** 1 + +**Constraints:** + +* 0 <= x, y <= 231 - 1 + +## Solution + +```kotlin +class Solution { + fun hammingDistance(x: Int, y: Int): Int { + return Integer.bitCount(x xor y) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0462_minimum_moves_to_equal_array_elements_ii/readme.md b/src/main/kotlin/g0401_0500/s0462_minimum_moves_to_equal_array_elements_ii/readme.md new file mode 100644 index 00000000..b73a6c10 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0462_minimum_moves_to_equal_array_elements_ii/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) + +## 462\. Minimum Moves to Equal Array Elements II + +Medium + +Given an integer array `nums` of size `n`, return _the minimum number of moves required to make all array elements equal_. + +In one move, you can increment or decrement an element of the array by `1`. + +Test cases are designed so that the answer will fit in a **32-bit** integer. + +**Example 1:** + +**Input:** nums = [1,2,3] + +**Output:** 2 + +**Explanation:** Only two moves are needed (remember each move increments or decrements one element): + +[1,2,3] => [2,2,3] => [2,2,2] + +**Example 2:** + +**Input:** nums = [1,10,2,9] + +**Output:** 16 + +**Constraints:** + +* `n == nums.length` +* 1 <= nums.length <= 105 +* -109 <= nums[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun minMoves2(nums: IntArray): Int { + nums.sort() + val median = (nums.size - 1) / 2 + var ops = 0 + for (num in nums) { + if (num != nums[median]) { + ops += Math.abs(nums[median] - num) + } + } + return ops + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0463_island_perimeter/readme.md b/src/main/kotlin/g0401_0500/s0463_island_perimeter/readme.md new file mode 100644 index 00000000..d86ba7d6 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0463_island_perimeter/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) + +## 463\. Island Perimeter + +Easy + +You are given `row x col` `grid` representing a map where `grid[i][j] = 1` represents land and `grid[i][j] = 0` represents water. + +Grid cells are connected **horizontally/vertically** (not diagonally). The `grid` is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). + +The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2018/10/12/island.png) + +**Input:** grid = \[\[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]] + +**Output:** 16 + +**Explanation:** The perimeter is the 16 yellow stripes in the image above. + +**Example 2:** + +**Input:** grid = \[\[1]] + +**Output:** 4 + +**Example 3:** + +**Input:** grid = \[\[1,0]] + +**Output:** 4 + +**Constraints:** + +* `row == grid.length` +* `col == grid[i].length` +* `1 <= row, col <= 100` +* `grid[i][j]` is `0` or `1`. +* There is exactly one island in `grid`. + +## Solution + +```kotlin +class Solution { + fun islandPerimeter(grid: Array): Int { + var islands = 0 + var neighbours = 0 + for (i in grid.indices) { + for (j in grid[i].indices) { + if (grid[i][j] == 1) { + islands++ + if (i < grid.size - 1 && grid[i + 1][j] == 1) { + neighbours++ + } + if (j < grid[i].size - 1 && grid[i][j + 1] == 1) { + neighbours++ + } + } + } + } + return 4 * islands - 2 * neighbours + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0464_can_i_win/readme.md b/src/main/kotlin/g0401_0500/s0464_can_i_win/readme.md new file mode 100644 index 00000000..78b13e76 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0464_can_i_win/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) + +## 464\. Can I Win + +Medium + +In the "100 game" two players take turns adding, to a running total, any integer from `1` to `10`. The player who first causes the running total to **reach or exceed** 100 wins. + +What if we change the game so that players **cannot** re-use integers? + +For example, two players might take turns drawing from a common pool of numbers from 1 to 15 without replacement until they reach a total >= 100. + +Given two integers `maxChoosableInteger` and `desiredTotal`, return `true` if the first player to move can force a win, otherwise, return `false`. Assume both players play **optimally**. + +**Example 1:** + +**Input:** maxChoosableInteger = 10, desiredTotal = 11 + +**Output:** false + +**Explanation:** + +No matter which integer the first player choose, the first player will lose. + +The first player can choose an integer from 1 up to 10. + +If the first player choose 1, the second player can only choose integers from 2 up to 10. + +The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal. + +Same with other integers chosen by the first player, the second player will always win. + +**Example 2:** + +**Input:** maxChoosableInteger = 10, desiredTotal = 0 + +**Output:** true + +**Example 3:** + +**Input:** maxChoosableInteger = 10, desiredTotal = 1 + +**Output:** true + +**Constraints:** + +* `1 <= maxChoosableInteger <= 20` +* `0 <= desiredTotal <= 300` + +## Solution + +```kotlin +class Solution { + fun canIWin(maxChoosableInteger: Int, desiredTotal: Int): Boolean { + if (desiredTotal <= maxChoosableInteger) { + return true + } + return if (1.0 * maxChoosableInteger * (1 + maxChoosableInteger) / 2 < desiredTotal) { + false + } else canWin(0, arrayOfNulls(1 shl maxChoosableInteger), desiredTotal, maxChoosableInteger) + } + + private fun canWin(state: Int, dp: Array, desiredTotal: Int, maxChoosableInteger: Int): Boolean { + // state is the bitmap representation of the current state of choosable integers left + // dp[state] represents whether the current player can win the game at state + if (dp[state] != null) { + return dp[state]!! + } + for (i in 1..maxChoosableInteger) { + // current number to pick + val cur = 1 shl i - 1 + if (cur and state == 0 && + ( + i >= desiredTotal || + !canWin(state or cur, dp, desiredTotal - i, maxChoosableInteger) + ) + ) { + // i is greater than the desired total + // or the other player cannot win after the current player picks i + dp[state] = true + return dp[state]!! + } + } + dp[state] = false + return dp[state]!! + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0466_count_the_repetitions/readme.md b/src/main/kotlin/g0401_0500/s0466_count_the_repetitions/readme.md new file mode 100644 index 00000000..14b331c6 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0466_count_the_repetitions/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) + +## 466\. Count The Repetitions + +Hard + +We define `str = [s, n]` as the string `str` which consists of the string `s` concatenated `n` times. + +* For example, `str == ["abc", 3] =="abcabcabc"`. + +We define that string `s1` can be obtained from string `s2` if we can remove some characters from `s2` such that it becomes `s1`. + +* For example, `s1 = "abc"` can be obtained from s2 = "ab**dbe**c" based on our definition by removing the bolded underlined characters. + +You are given two strings `s1` and `s2` and two integers `n1` and `n2`. You have the two strings `str1 = [s1, n1]` and `str2 = [s2, n2]`. + +Return _the maximum integer_ `m` _such that_ `str = [str2, m]` _can be obtained from_ `str1`. + +**Example 1:** + +**Input:** s1 = "acb", n1 = 4, s2 = "ab", n2 = 2 + +**Output:** 2 + +**Example 2:** + +**Input:** s1 = "acb", n1 = 1, s2 = "acb", n2 = 1 + +**Output:** 1 + +**Constraints:** + +* `1 <= s1.length, s2.length <= 100` +* `s1` and `s2` consist of lowercase English letters. +* 1 <= n1, n2 <= 106 + +## Solution + +```kotlin +class Solution { + fun getMaxRepetitions(s1: String, n1: Int, s2: String, n2: Int): Int { + val n = s2.length + val ss1 = s1.toCharArray() + val ss2 = s2.toCharArray() + val memo = arrayOfNulls(n) + val s2CountMap = IntArray(n + 1) + var s1Count = 0 + var s2Count = 0 + var s2Idx = 0 + while (memo[s2Idx] == null) { + memo[s2Idx] = intArrayOf(s1Count, s2Count) + for (c1 in ss1) { + if (c1 == ss2[s2Idx]) { + s2Idx++ + if (s2Idx == n) { + s2Count++ + s2Idx = 0 + } + } + } + s1Count++ + s2CountMap[s1Count] = s2Count + } + var n1Left = n1 - memo[s2Idx]!![0] + val matchedPatternCount = n1Left / (s1Count - memo[s2Idx]!![0]) * (s2Count - memo[s2Idx]!![1]) + n1Left = n1Left % (s1Count - memo[s2Idx]!![0]) + val leftS2Count = s2CountMap[memo[s2Idx]!![0] + n1Left] - memo[s2Idx]!![1] + val totalCount = leftS2Count + matchedPatternCount + memo[s2Idx]!![1] + return totalCount / n2 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0467_unique_substrings_in_wraparound_string/readme.md b/src/main/kotlin/g0401_0500/s0467_unique_substrings_in_wraparound_string/readme.md new file mode 100644 index 00000000..b4a3a357 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0467_unique_substrings_in_wraparound_string/readme.md @@ -0,0 +1,69 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 467\. Unique Substrings in Wraparound String + +Medium + +We define the string `base` to be the infinite wraparound string of `"abcdefghijklmnopqrstuvwxyz"`, so `base` will look like this: + +* `"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd...."`. + +Given a string `s`, return _the number of **unique non-empty substrings** of_ `s` _are present in_ `base`. + +**Example 1:** + +**Input:** s = "a" + +**Output:** 1 + +**Explanation:** Only the substring "a" of s is in base. + +**Example 2:** + +**Input:** s = "cac" + +**Output:** 2 + +**Explanation:** There are two substrings ("a", "c") of s in base. + +**Example 3:** + +**Input:** s = "zab" + +**Output:** 6 + +**Explanation:** There are six substrings ("z", "a", "b", "za", "ab", and "zab") of s in base. + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` consists of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun findSubstringInWraproundString(p: String): Int { + val str = p.toCharArray() + val n = str.size + val map = IntArray(26) + var len = 0 + for (i in 0 until n) { + if (i > 0 && (str[i - 1].code + 1 == str[i].code || str[i - 1] == 'z' && str[i] == 'a')) { + len += 1 + } else { + len = 1 + } + // we are storing the max len of string for each letter and then we will count all these + // length. + map[str[i].code - 'a'.code] = Math.max(map[str[i].code - 'a'.code], len) + } + var answer = 0 + for (num in map) { + answer += num + } + return answer + } +} +``` \ No newline at end of file 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 new file mode 100644 index 00000000..737411e8 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0468_validate_ip_address/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) + +## 468\. Validate IP Address + +Medium + +Given a string `queryIP`, return `"IPv4"` if IP is a valid IPv4 address, `"IPv6"` if IP is a valid IPv6 address or `"Neither"` if IP is not a correct IP of any type. + +**A valid IPv4** address is an IP in the form "x1.x2.x3.x4" where 0 <= xi <= 255 and xi **cannot contain** leading zeros. For example, `"192.168.1.1"` and `"192.168.1.0"` are valid IPv4 addresses while `"192.168.01.1"`, `"192.168.1.00"`, and `"192.168@1.1"` are invalid IPv4 addresses. + +**A valid IPv6** address is an IP in the form "x1:x2:x3:x4:x5:x6:x7:x8" where: + +* 1 <= xi.length <= 4 +* xi is a **hexadecimal string** which may contain digits, lowercase English letter (`'a'` to `'f'`) and upper-case English letters (`'A'` to `'F'`). +* Leading zeros are allowed in xi. + +For example, "`2001:0db8:85a3:0000:0000:8a2e:0370:7334"` and "`2001:db8:85a3:0:0:8A2E:0370:7334"` are valid IPv6 addresses, while "`2001:0db8:85a3::8A2E:037j:7334"` and "`02001:0db8:85a3:0000:0000:8a2e:0370:7334"` are invalid IPv6 addresses. + +**Example 1:** + +**Input:** queryIP = "172.16.254.1" + +**Output:** "IPv4" + +**Explanation:** This is a valid IPv4 address, return "IPv4". + +**Example 2:** + +**Input:** queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334" + +**Output:** "IPv6" + +**Explanation:** This is a valid IPv6 address, return "IPv6". + +**Example 3:** + +**Input:** queryIP = "256.256.256.256" + +**Output:** "Neither" + +**Explanation:** This is neither a IPv4 address nor a IPv6 address. + +**Constraints:** + +* `queryIP` consists only of English letters, digits and the characters `'.'` and `':'`. + +## Solution + +```kotlin +class Solution { + fun validIPAddress(ip: String): String { + if (ip.length == 0) { + return NEITHER + } + val arr = ip.split("\\.".toRegex()).toTypedArray() + val arr1 = ip.split(":".toRegex()).toTypedArray() + if (arr.size == 4) { + for (num in arr) { + try { + if (num.length > 1 && num.startsWith("0") || num.toInt() > 255) { + return NEITHER + } + } catch (e: Exception) { + return NEITHER + } + } + return "IPv4" + } else if (arr1.size == 8) { + for (num in arr1) { + if (num.length < 1 || num.length > 4) { + return NEITHER + } + for (j in 0 until num.length) { + val ch = num[j] + if (ch.code > 9 && + ( + Character.isLowerCase(ch) && ch > 'f' || + Character.isUpperCase(ch) && ch > 'F' + ) + ) { + return NEITHER + } + } + } + return "IPv6" + } + return NEITHER + } + + companion object { + private const val NEITHER = "Neither" + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0470_implement_rand10_using_rand7/readme.md b/src/main/kotlin/g0401_0500/s0470_implement_rand10_using_rand7/readme.md new file mode 100644 index 00000000..c5cb697d --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0470_implement_rand10_using_rand7/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) + +## 470\. Implement Rand10() Using Rand7() + +Medium + +Given the **API** `rand7()` that generates a uniform random integer in the range `[1, 7]`, write a function `rand10()` that generates a uniform random integer in the range `[1, 10]`. You can only call the API `rand7()`, and you shouldn't call any other API. Please **do not** use a language's built-in random API. + +Each test case will have one **internal** argument `n`, the number of times that your implemented function `rand10()` will be called while testing. Note that this is **not an argument** passed to `rand10()`. + +**Example 1:** + +**Input:** n = 1 + +**Output:** [2] + +**Example 2:** + +**Input:** n = 2 + +**Output:** [2,8] + +**Example 3:** + +**Input:** n = 3 + +**Output:** [3,8,10] + +**Constraints:** + +* 1 <= n <= 105 + +**Follow up:** + +* What is the [expected value](https://en.wikipedia.org/wiki/Expected_value) for the number of calls to `rand7()` function? +* Could you minimize the number of calls to `rand7()`? + +## Solution + +```kotlin +import java.util.Random + +/* + * The rand7() API is already defined in the parent class SolBase. + * fun rand7(): Int {} + * @return a random integer in the range 1 to 7 + */ +@Suppress("kotlin:S2245") +class Solution { + private val random: Random = Random() + fun rand10(): Int { + var r1: Int + do { + var r2: Int + do { r2 = rand7() } while (r2 == 7) + if (r2 in 1..3) { r1 = rand7() } else { r1 = 7 + rand7() } + } while (r1 > 10) + return r1 + } + + private fun rand7(): Int { + return random.nextInt(7) + 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0472_concatenated_words/readme.md b/src/main/kotlin/g0401_0500/s0472_concatenated_words/readme.md new file mode 100644 index 00000000..f33c668d --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0472_concatenated_words/readme.md @@ -0,0 +1,99 @@ +[![](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) + +## 472\. Concatenated Words + +Hard + +Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`. + +A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words in the given array. + +**Example 1:** + +**Input:** words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"] + +**Output:** ["catsdogcats","dogcatsdog","ratcatdogcat"] + +**Explanation:** "catsdogcats" can be concatenated by "cats", "dog" and "cats"; "dogcatsdog" can be concatenated by "dog", "cats" and "dog"; "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat". + +**Example 2:** + +**Input:** words = ["cat","dog","catdog"] + +**Output:** ["catdog"] + +**Constraints:** + +* 1 <= words.length <= 104 +* `1 <= words[i].length <= 30` +* `words[i]` consists of only lowercase English letters. +* All the strings of `words` are **unique**. +* 1 <= sum(words[i].length) <= 105 + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + private val ans: MutableList = ArrayList() + private var root: Trie? = null + fun findAllConcatenatedWordsInADict(words: Array): List { + root = Trie() + Arrays.sort( + words + ) { a: String, b: String -> + Integer.compare( + a.length, + b.length + ) + } + for (word in words) { + var ptr = root + if (search(word, 0, 0)) { + ans.add(word) + } else { + for (j in 0 until word.length) { + if (ptr!!.nxt[word[j].code - 'a'.code] == null) { + ptr.nxt[word[j].code - 'a'.code] = Trie() + } + ptr = ptr.nxt[word[j].code - 'a'.code] + } + ptr!!.endHere = true + } + } + return ans + } + + private fun search(cur: String, idx: Int, wordCnt: Int): Boolean { + if (idx == cur.length) { + return wordCnt >= 2 + } + var ptr = root + for (i in idx until cur.length) { + if (ptr!!.nxt[cur[i].code - 'a'.code] == null) { + return false + } + if (ptr.nxt[cur[i].code - 'a'.code]!!.endHere) { + val ret = search(cur, i + 1, wordCnt + 1) + if (ret) { + return true + } + } + ptr = ptr.nxt[cur[i].code - 'a'.code] + } + return ptr!!.endHere && wordCnt >= 2 + } + + private class Trie internal constructor() { + var nxt: Array + var endHere: Boolean + + init { + nxt = arrayOfNulls(26) + endHere = false + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0473_matchsticks_to_square/readme.md b/src/main/kotlin/g0401_0500/s0473_matchsticks_to_square/readme.md new file mode 100644 index 00000000..6c4d10ce --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0473_matchsticks_to_square/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) + +## 473\. Matchsticks to Square + +Medium + +You are given an integer array `matchsticks` where `matchsticks[i]` is the length of the ith matchstick. You want to use **all the matchsticks** to make one square. You **should not break** any stick, but you can link them up, and each matchstick must be used **exactly one time**. + +Return `true` if you can make this square and `false` otherwise. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/09/matchsticks1-grid.jpg) + +**Input:** matchsticks = [1,1,2,2,2] + +**Output:** true + +**Explanation:** You can form a square with length 2, one side of the square came two sticks with length 1. + +**Example 2:** + +**Input:** matchsticks = [3,3,3,3,4] + +**Output:** false + +**Explanation:** You cannot find a way to form a square with all the matchsticks. + +**Constraints:** + +* `1 <= matchsticks.length <= 15` +* 1 <= matchsticks[i] <= 108 + +## Solution + +```kotlin +class Solution { + fun makesquare(matchsticks: IntArray): Boolean { + if (matchsticks.size < 4) { + return false + } + var per = 0 + for (ele in matchsticks) { + per = ele + per + } + if (per % 4 != 0) { + return false + } + matchsticks.sort() + val side = per / 4 + val sides = intArrayOf(side, side, side, side) + return help(matchsticks, matchsticks.size - 1, sides) + } + + private fun help(nums: IntArray, i: Int, side: IntArray): Boolean { + if (i == -1) { + return side[0] == 0 && side[1] == 0 && side[2] == 0 && side[3] == 0 + } + for (j in 0..3) { + if (nums[i] > side[j]) { + continue + } + side[j] -= nums[i] + if (help(nums, i - 1, side)) { + return true + } + side[j] += nums[i] + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0474_ones_and_zeroes/readme.md b/src/main/kotlin/g0401_0500/s0474_ones_and_zeroes/readme.md new file mode 100644 index 00000000..95335cb1 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0474_ones_and_zeroes/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) + +## 474\. Ones and Zeroes + +Medium + +You are given an array of binary strings `strs` and two integers `m` and `n`. + +Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. + +A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`. + +**Example 1:** + +**Input:** strs = ["10","0001","111001","1","0"], m = 5, n = 3 + +**Output:** 4 + +**Explanation:** The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4. + +Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}. + +{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3. + +**Example 2:** + +**Input:** strs = ["10","0","1"], m = 1, n = 1 + +**Output:** 2 + +**Explanation:** The largest subset is {"0", "1"}, so the answer is 2. + +**Constraints:** + +* `1 <= strs.length <= 600` +* `1 <= strs[i].length <= 100` +* `strs[i]` consists only of digits `'0'` and `'1'`. +* `1 <= m, n <= 100` + +## Solution + +```kotlin +class Solution { + /* + * The problem can be interpreted as: + * What's the max number of str can we pick from strs with limitation of m "0"s and n "1"s. + * + * Thus we can define dp[i][j] as it stands for max number of str can we pick from strs with limitation + * of i "0"s and j "1"s. + * + * For each str, assume it has a "0"s and b "1"s, we update the dp array iteratively + * and set dp[i][j] = Math.max(dp[i][j], dp[i - a][j - b] + 1). + * So at the end, dp[m][n] is the answer. + */ + fun findMaxForm(strs: Array, m: Int, n: Int): Int { + val dp = Array(m + 1) { IntArray(n + 1) } + for (str in strs) { + val count = count(str) + for (i in m downTo count[0]) { + for (j in n downTo count[1]) { + dp[i][j] = Math.max(dp[i][j], dp[i - count[0]][j - count[1]] + 1) + } + } + } + return dp[m][n] + } + + private fun count(str: String): IntArray { + val res = IntArray(2) + for (i in 0 until str.length) { + res[str[i].code - '0'.code]++ + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0475_heaters/readme.md b/src/main/kotlin/g0401_0500/s0475_heaters/readme.md new file mode 100644 index 00000000..8e1a12f8 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0475_heaters/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) + +## 475\. Heaters + +Medium + +Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. + +Every house can be warmed, as long as the house is within the heater's warm radius range. + +Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius standard of heaters so that those heaters could cover all houses._ + +**Notice** that all the `heaters` follow your radius standard, and the warm radius will the same. + +**Example 1:** + +**Input:** houses = [1,2,3], heaters = [2] + +**Output:** 1 + +**Explanation:** The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed. + +**Example 2:** + +**Input:** houses = [1,2,3,4], heaters = [1,4] + +**Output:** 1 + +**Explanation:** The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed. + +**Example 3:** + +**Input:** houses = [1,5], heaters = [2] + +**Output:** 3 + +**Constraints:** + +* 1 <= houses.length, heaters.length <= 3 * 104 +* 1 <= houses[i], heaters[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun findRadius(houses: IntArray, heaters: IntArray): Int { + var res = 0 + val m = houses.size + val n = heaters.size + var hs = 0 + var ht = 0 + houses.sort() + heaters.sort() + if (n == 1) { + return Math.max(Math.abs(houses[0] - heaters[0]), Math.abs(houses[m - 1] - heaters[0])) + } + while (hs < m && ht < n - 1) { + if (houses[hs] <= heaters[ht]) { + res = Math.max(heaters[ht] - houses[hs], res) + hs++ + } else if (houses[hs] <= heaters[ht + 1]) { + res = Math.max( + res, + Math.min(houses[hs] - heaters[ht], heaters[ht + 1] - houses[hs]) + ) + hs++ + } else { + ht++ + } + } + if (ht == n - 1) { + res = Math.max(res, houses[m - 1] - heaters[n - 1]) + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0476_number_complement/readme.md b/src/main/kotlin/g0401_0500/s0476_number_complement/readme.md new file mode 100644 index 00000000..1e926802 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0476_number_complement/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) + +## 476\. Number Complement + +Easy + +The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. + +* For example, The integer `5` is `"101"` in binary and its **complement** is `"010"` which is the integer `2`. + +Given an integer `num`, return _its complement_. + +**Example 1:** + +**Input:** num = 5 + +**Output:** 2 + +**Explanation:** The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. + +**Example 2:** + +**Input:** num = 1 + +**Output:** 0 + +**Explanation:** The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. + +**Constraints:** + +* 1 <= num < 231 + +**Note:** This question is the same as 1009: [https://leetcode.com/problems/complement-of-base-10-integer/](https://leetcode.com/problems/complement-of-base-10-integer/) + +## Solution + +```kotlin +class Solution { + fun findComplement(num: Int): Int { + return num.inv() and (Integer.highestOneBit(num) shl 1) - 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0477_total_hamming_distance/readme.md b/src/main/kotlin/g0401_0500/s0477_total_hamming_distance/readme.md new file mode 100644 index 00000000..6e3a03f0 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0477_total_hamming_distance/readme.md @@ -0,0 +1,53 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 477\. Total Hamming Distance + +Medium + +The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. + +Given an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`. + +**Example 1:** + +**Input:** nums = [4,14,2] + +**Output:** 6 + +**Explanation:** In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). + +The answer will be: + +HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. + +**Example 2:** + +**Input:** nums = [4,14,4] + +**Output:** 4 + +**Constraints:** + +* 1 <= nums.length <= 104 +* 0 <= nums[i] <= 109 +* The answer for the given input will fit in a **32-bit** integer. + +## Solution + +```kotlin +class Solution { + fun totalHammingDistance(nums: IntArray): Int { + var ans = 0 + val n = nums.size + for (i in 0..31) { + var ones = 0 + for (k in nums) { + ones += k shr i and 1 + } + ans = ans + ones * (n - ones) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0478_generate_random_point_in_a_circle/readme.md b/src/main/kotlin/g0401_0500/s0478_generate_random_point_in_a_circle/readme.md new file mode 100644 index 00000000..03231360 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0478_generate_random_point_in_a_circle/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) + +## 478\. Generate Random Point in a Circle + +Medium + +Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle. + +Implement the `Solution` class: + +* `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and the position of the center `(x_center, y_center)`. +* `randPoint()` returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array `[x, y]`. + +**Example 1:** + +**Input** ["Solution", "randPoint", "randPoint", "randPoint"] [[1.0, 0.0, 0.0], [], [], []] + +**Output:** [null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]] + +**Explanation:** + + Solution solution = new Solution(1.0, 0.0, 0.0); + solution.randPoint(); // return [-0.02493, -0.38077] + solution.randPoint(); // return [0.82314, 0.38945] + solution.randPoint(); // return [0.36572, 0.17248] + +**Constraints:** + +* 0 < radius <= 108 +* -107 <= x_center, y_center <= 107 +* At most 3 * 104 calls will be made to `randPoint`. + +## Solution + +```kotlin +import java.util.Random + +@Suppress("kotlin:S2245") +class Solution(private val radius: Double, private val xCenter: Double, private val yCenter: Double) { + private val random: Random = Random() + fun randPoint(): DoubleArray { + var x = getCoordinate(xCenter) + var y = getCoordinate(yCenter) + while (getDistance(x, y) >= radius * radius) { + x = getCoordinate(xCenter) + y = getCoordinate(yCenter) + } + return doubleArrayOf(x, y) + } + + private fun getDistance(x: Double, y: Double): Double { + return (xCenter - x) * (xCenter - x) + (yCenter - y) * (yCenter - y) + } + + private fun getCoordinate(center: Double): Double { + return center - radius + random.nextDouble() * 2 * radius + } +} + +/* + * Your Solution object will be instantiated and called as such: + * var obj = Solution(radius, x_center, y_center) + * var param_1 = obj.randPoint() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0479_largest_palindrome_product/readme.md b/src/main/kotlin/g0401_0500/s0479_largest_palindrome_product/readme.md new file mode 100644 index 00000000..73b24070 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0479_largest_palindrome_product/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) + +## 479\. Largest Palindrome Product + +Hard + +Given an integer n, return _the **largest palindromic integer** that can be represented as the product of two `n`\-digits integers_. Since the answer can be very large, return it **modulo** `1337`. + +**Example 1:** + +**Input:** n = 2 + +**Output:** 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 + +**Example 2:** + +**Input:** n = 1 + +**Output:** 9 + +**Constraints:** + +* `1 <= n <= 8` + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun largestPalindrome(n: Int): Int { + val pow10 = Math.pow(10.0, n.toDouble()).toLong() + val max = (pow10 - 1) * (pow10 - Math.sqrt(pow10.toDouble()).toLong() + 1) + val left = max / pow10 + var t = pow10 / 11 + t -= t.inv() and 1L + for (i in left downTo 1) { + var j = t + val num = gen(i) + while (j >= i / 11) { + if (num % j == 0L) { + return (num % 1337).toInt() + } + j -= 2 + } + } + return 9 + } + + private fun gen(x: Long): Long { + var x = x + var r = x + while (x > 0) { + r = r * 10 + x % 10 + x /= 10 + } + return r + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0480_sliding_window_median/readme.md b/src/main/kotlin/g0401_0500/s0480_sliding_window_median/readme.md new file mode 100644 index 00000000..817499b0 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0480_sliding_window_median/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) + +## 480\. Sliding Window Median + +Hard + +The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. + +* For examples, if arr = [2,3,4], the median is `3`. +* For examples, if arr = [1,2,3,4], the median is `(2 + 3) / 2 = 2.5`. + +You are given an integer array `nums` and an integer `k`. There is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position. + +Return _the median array for each window in the original array_. Answers within 10-5 of the actual value will be accepted. + +**Example 1:** + +**Input:** nums = [1,3,-1,-3,5,3,6,7], k = 3 + +**Output:** [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000] + +**Explanation:** Window position Median --------------- ----- [**1 3 -1**] -3 5 3 6 7 1 1 [**3 -1 -3**] 5 3 6 7 -1 1 3 [**\-1 -3 5**] 3 6 7 -1 1 3 -1 [**\-3 5 3**] 6 7 3 1 3 -1 -3 [**5 3 6**] 7 5 1 3 -1 -3 5 [**3 6 7**] 6 + +**Example 2:** + +**Input:** nums = [1,2,3,4,2,3,1,4,2], k = 3 + +**Output:** [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000] + +**Constraints:** + +* 1 <= k <= nums.length <= 105 +* -231 <= nums[i] <= 231 - 1 + +## Solution + +```kotlin +import java.util.TreeSet + +class Solution { + fun medianSlidingWindow(nums: IntArray, k: Int): DoubleArray { + require(k >= 1) { "Input is invalid" } + val len = nums.size + val result = DoubleArray(len - k + 1) + if (k == 1) { + for (i in 0 until len) { + result[i] = nums[i].toDouble() + } + return result + } + val comparator = Comparator { a: Int?, b: Int? -> + if (nums[a!!] != nums[b!!] + ) Integer.compare(nums[a], nums[b]) else Integer.compare(a, b) + } + val smallNums = TreeSet(comparator.reversed()) + val largeNums = TreeSet(comparator) + for (i in 0 until len) { + if (i >= k) { + removeElement(smallNums, largeNums, i - k) + } + addElement(smallNums, largeNums, i) + if (i >= k - 1) { + result[i - (k - 1)] = getMedian(smallNums, largeNums, nums) + } + } + return result + } + + private fun addElement(smallNums: TreeSet, largeNums: TreeSet, idx: Int) { + smallNums.add(idx) + largeNums.add(smallNums.pollFirst()!!) + if (smallNums.size < largeNums.size) { + smallNums.add(largeNums.pollFirst()) + } + } + + private fun removeElement(smallNums: TreeSet, largeNums: TreeSet, idx: Int) { + if (largeNums.contains(idx)) { + largeNums.remove(idx) + if (smallNums.size == largeNums.size + 2) { + largeNums.add(smallNums.pollFirst()!!) + } + } else { + smallNums.remove(idx) + if (smallNums.size < largeNums.size) { + smallNums.add(largeNums.pollFirst()) + } + } + } + + private fun getMedian(smallNums: TreeSet, largeNums: TreeSet, nums: IntArray): Double { + return if (smallNums.size == largeNums.size) { + (nums[smallNums.first()!!].toDouble() + nums[largeNums.first()!!]) / 2 + } else nums[smallNums.first()!!].toDouble() + } +} +``` \ No newline at end of file