From 7441555c7d998b7d0b923679014e01df82bc9e1a Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Sun, 20 Nov 2022 05:39:21 +0200 Subject: [PATCH] Added tasks 331-368. --- README.md | 32 ++++- .../kotlin/g0001_0100/s0015_3sum/readme.md | 3 +- .../g0001_0100/s0016_3sum_closest/readme.md | 4 +- .../kotlin/g0001_0100/s0018_4sum/readme.md | 4 +- .../s0040_combination_sum_ii/readme.md | 3 +- .../g0001_0100/s0049_group_anagrams/readme.md | 4 +- .../s0056_merge_intervals/readme.md | 6 +- .../g0001_0100/s0090_subsets_ii/readme.md | 4 +- .../g0101_0200/s0164_maximum_gap/readme.md | 4 +- .../g0101_0200/s0179_largest_number/readme.md | 4 +- .../readme.md | 4 +- .../g0301_0400/s0324_wiggle_sort_ii/readme.md | 4 +- .../g0301_0400/s0326_power_of_three/readme.md | 34 +++-- .../readme.md | 66 ++++++++++ .../s0332_reconstruct_itinerary/readme.md | 79 +++++++++++ .../readme.md | 67 ++++++++++ .../g0301_0400/s0335_self_crossing/readme.md | 67 ++++++++++ .../s0336_palindrome_pairs/readme.md | 114 ++++++++++++++++ .../s0337_house_robber_iii/readme.md | 76 +++++++++++ .../g0301_0400/s0342_power_of_four/readme.md | 52 ++++++++ .../g0301_0400/s0343_integer_break/readme.md | 55 ++++++++ .../g0301_0400/s0344_reverse_string/readme.md | 43 ++++++ .../readme.md | 59 +++++++++ .../s0347_top_k_frequent_elements/readme.md | 3 +- .../readme.md | 52 ++++++++ .../readme.md | 54 ++++++++ .../readme.md | 111 ++++++++++++++++ .../s0354_russian_doll_envelopes/readme.md | 66 ++++++++++ .../g0301_0400/s0355_design_twitter/readme.md | 123 ++++++++++++++++++ .../readme.md | 43 ++++++ .../readme.md | 85 ++++++++++++ .../s0365_water_and_jug_problem/readme.md | 60 +++++++++ .../s0367_valid_perfect_square/readme.md | 59 +++++++++ .../s0368_largest_divisible_subset/readme.md | 68 ++++++++++ 34 files changed, 1463 insertions(+), 49 deletions(-) create mode 100644 src/main/kotlin/g0301_0400/s0331_verify_preorder_serialization_of_a_binary_tree/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0332_reconstruct_itinerary/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0334_increasing_triplet_subsequence/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0335_self_crossing/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0336_palindrome_pairs/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0337_house_robber_iii/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0342_power_of_four/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0343_integer_break/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0344_reverse_string/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0345_reverse_vowels_of_a_string/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0349_intersection_of_two_arrays/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0350_intersection_of_two_arrays_ii/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0352_data_stream_as_disjoint_intervals/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0354_russian_doll_envelopes/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0355_design_twitter/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0357_count_numbers_with_unique_digits/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0363_max_sum_of_rectangle_no_larger_than_k/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0365_water_and_jug_problem/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0367_valid_perfect_square/readme.md create mode 100644 src/main/kotlin/g0301_0400/s0368_largest_divisible_subset/readme.md diff --git a/README.md b/README.md index 7772719c..3dd8d02a 100644 --- a/README.md +++ b/README.md @@ -262,6 +262,7 @@ | | | | | | |-|-|-|-|-|- +| 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 ### Programming Skills I @@ -512,6 +513,7 @@ | | | | | | |-|-|-|-|-|- +| 0365 |[Water and Jug Problem](src/main/kotlin/g0301_0400/s0365_water_and_jug_problem)| Medium | Math, Depth_First_Search, Breadth_First_Search | 130 | 100.00 #### Day 12 Breadth First Search @@ -835,6 +837,7 @@ | | | | | | |-|-|-|-|-|- +| 0344 |[Reverse String](src/main/kotlin/g0301_0400/s0344_reverse_string)| Easy | Top_Interview_Questions, String, Two_Pointers, Recursion | 445 | 69.75 | 0014 |[Longest Common Prefix](src/main/kotlin/g0001_0100/s0014_longest_common_prefix)| Easy | Top_Interview_Questions, String | 209 | 88.86 | 0187 |[Repeated DNA Sequences](src/main/kotlin/g0101_0200/s0187_repeated_dna_sequences)| Medium | String, Hash_Table, Bit_Manipulation, Sliding_Window, Hash_Function, Rolling_Hash | 319 | 79.03 | 0003 |[Longest Substring Without Repeating Characters](src/main/kotlin/g0001_0100/s0003_longest_substring_without_repeating_characters)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, String, Hash_Table, Sliding_Window | 258 | 91.09 @@ -941,6 +944,7 @@ | 0297 |[Serialize and Deserialize Binary Tree](src/main/kotlin/g0201_0300/s0297_serialize_and_deserialize_binary_tree)| Hard | Top_Interview_Questions, String, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Design | 475 | 78.85 | 0124 |[Binary Tree Maximum Path Sum](src/main/kotlin/g0101_0200/s0124_binary_tree_maximum_path_sum)| Hard | Top_100_Liked_Questions, Top_Interview_Questions, Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree | 331 | 74.42 | 0098 |[Validate Binary Search Tree](src/main/kotlin/g0001_0100/s0098_validate_binary_search_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 330 | 41.38 +| 0337 |[House Robber III](src/main/kotlin/g0301_0400/s0337_house_robber_iii)| Medium | Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree | 282 | 84.62 | 0236 |[Lowest Common Ancestor of a Binary Tree](src/main/kotlin/g0201_0300/s0236_lowest_common_ancestor_of_a_binary_tree)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Depth_First_Search, Tree, Binary_Tree | 386 | 45.21 #### Udemy Trie and Heap @@ -1021,6 +1025,7 @@ | | | | | | |-|-|-|-|-|- +| 0350 |[Intersection of Two Arrays II](src/main/kotlin/g0301_0400/s0350_intersection_of_two_arrays_ii)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting, Binary_Search, Two_Pointers | 321 | 73.37 | 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 #### Day 4 Array @@ -1134,6 +1139,7 @@ | | | | | | |-|-|-|-|-|- +| 0334 |[Increasing Triplet Subsequence](src/main/kotlin/g0301_0400/s0334_increasing_triplet_subsequence)| Medium | Top_Interview_Questions, Array, Greedy | 672 | 60.61 | 0238 |[Product of Array Except Self](src/main/kotlin/g0201_0300/s0238_product_of_array_except_self)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Prefix_Sum | 669 | 48.96 | 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 | 692 | 53.27 @@ -1268,6 +1274,7 @@ | | | | | | |-|-|-|-|-|- +| 0344 |[Reverse String](src/main/kotlin/g0301_0400/s0344_reverse_string)| Easy | Top_Interview_Questions, String, Two_Pointers, Recursion | 445 | 69.75 #### Day 5 Two Pointers @@ -1457,6 +1464,7 @@ |-|-|-|-|-|- | 0072 |[Edit Distance](src/main/kotlin/g0001_0100/s0072_edit_distance)| Hard | Top_100_Liked_Questions, String, Dynamic_Programming | 320 | 63.53 | 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 +| 0343 |[Integer Break](src/main/kotlin/g0301_0400/s0343_integer_break)| Medium | Dynamic_Programming, Math | 218 | 63.89 #### Day 19 Bit Manipulation @@ -1493,6 +1501,7 @@ | | | | | | |-|-|-|-|-|- +| 0367 |[Valid Perfect Square](src/main/kotlin/g0301_0400/s0367_valid_perfect_square)| Easy | Math, Binary_Search | 137 | 94.55 #### Day 4 @@ -1533,6 +1542,7 @@ | | | | | | |-|-|-|-|-|- +| 0350 |[Intersection of Two Arrays II](src/main/kotlin/g0301_0400/s0350_intersection_of_two_arrays_ii)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting, Binary_Search, Two_Pointers | 321 | 73.37 #### Day 11 @@ -1564,13 +1574,33 @@ | 0416 |[Partition Equal Subset Sum](src/main/kotlin/g0401_0500/s0416_partition_equal_subset_sum)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Level_2_Day_13_Dynamic_Programming | 509 | 57.56 | 0394 |[Decode String](src/main/kotlin/g0301_0400/s0394_decode_string)| Medium | Top_100_Liked_Questions, String, Stack, Recursion, Level_1_Day_14_Stack, Udemy_Strings | 224 | 64.86 | 0378 |[Kth Smallest Element in a Sorted Matrix](src/main/kotlin/g0301_0400/s0378_kth_smallest_element_in_a_sorted_matrix)| Medium | Top_Interview_Questions, Array, Sorting, Binary_Search, Matrix, Heap_Priority_Queue | 522 | 59.78 +| 0368 |[Largest Divisible Subset](src/main/kotlin/g0301_0400/s0368_largest_divisible_subset)| Medium | Array, Dynamic_Programming, Math, Sorting | 412 | 73.33 +| 0367 |[Valid Perfect Square](src/main/kotlin/g0301_0400/s0367_valid_perfect_square)| Easy | Math, Binary_Search, Binary_Search_I_Day_3 | 137 | 94.55 +| 0365 |[Water and Jug Problem](src/main/kotlin/g0301_0400/s0365_water_and_jug_problem)| Medium | Math, Depth_First_Search, Breadth_First_Search, Graph_Theory_I_Day_11_Breadth_First_Search | 130 | 100.00 +| 0363 |[Max Sum of Rectangle No Larger Than K](src/main/kotlin/g0301_0400/s0363_max_sum_of_rectangle_no_larger_than_k)| Hard | Array, Dynamic_Programming, Binary_Search, Matrix, Ordered_Set | 243 | 100.00 +| 0357 |[Count Numbers with Unique Digits](src/main/kotlin/g0301_0400/s0357_count_numbers_with_unique_digits)| Medium | Dynamic_Programming, Math, Backtracking | 104 | 100.00 +| 0355 |[Design Twitter](src/main/kotlin/g0301_0400/s0355_design_twitter)| Medium | Hash_Table, Design, Heap_Priority_Queue, Linked_List | 288 | 68.75 +| 0354 |[Russian Doll Envelopes](src/main/kotlin/g0301_0400/s0354_russian_doll_envelopes)| Hard | Array, Dynamic_Programming, Sorting, Binary_Search | 788 | 100.00 +| 0352 |[Data Stream as Disjoint Intervals](src/main/kotlin/g0301_0400/s0352_data_stream_as_disjoint_intervals)| Hard | Binary_Search, Design, Ordered_Set | 905 | 75.00 +| 0350 |[Intersection of Two Arrays II](src/main/kotlin/g0301_0400/s0350_intersection_of_two_arrays_ii)| Easy | Top_Interview_Questions, Array, Hash_Table, Sorting, Binary_Search, Two_Pointers, Data_Structure_I_Day_3_Array, Binary_Search_I_Day_10 | 321 | 73.37 +| 0349 |[Intersection of Two Arrays](src/main/kotlin/g0301_0400/s0349_intersection_of_two_arrays)| Easy | Array, Hash_Table, Sorting, Binary_Search, Two_Pointers | 346 | 66.99 | 0347 |[Top K Frequent Elements](src/main/kotlin/g0301_0400/s0347_top_k_frequent_elements)| Medium | Top_100_Liked_Questions, Top_Interview_Questions, Array, Hash_Table, Sorting, Heap_Priority_Queue, Counting, Divide_and_Conquer, Quickselect, Bucket_Sort, Data_Structure_II_Day_20_Heap_Priority_Queue | 268 | 99.74 +| 0345 |[Reverse Vowels of a String](src/main/kotlin/g0301_0400/s0345_reverse_vowels_of_a_string)| Easy | String, Two_Pointers | 349 | 80.63 +| 0344 |[Reverse String](src/main/kotlin/g0301_0400/s0344_reverse_string)| Easy | Top_Interview_Questions, String, Two_Pointers, Recursion, Algorithm_I_Day_4_Two_Pointers, Udemy_Strings | 445 | 69.75 +| 0343 |[Integer Break](src/main/kotlin/g0301_0400/s0343_integer_break)| Medium | Dynamic_Programming, Math, Algorithm_II_Day_18_Dynamic_Programming, Dynamic_Programming_I_Day_21 | 218 | 63.89 +| 0342 |[Power of Four](src/main/kotlin/g0301_0400/s0342_power_of_four)| Easy | Math, Bit_Manipulation, Recursion | 150 | 92.11 | 0338 |[Counting Bits](src/main/kotlin/g0301_0400/s0338_counting_bits)| Easy | Top_100_Liked_Questions, Dynamic_Programming, Bit_Manipulation, Udemy_Bit_Manipulation | 186 | 99.26 +| 0337 |[House Robber III](src/main/kotlin/g0301_0400/s0337_house_robber_iii)| Medium | Dynamic_Programming, Depth_First_Search, Tree, Binary_Tree, Udemy_Tree_Stack_Queue | 282 | 84.62 +| 0336 |[Palindrome Pairs](src/main/kotlin/g0301_0400/s0336_palindrome_pairs)| Hard | Array, String, Hash_Table, Trie | 2451 | 67.33 +| 0335 |[Self Crossing](src/main/kotlin/g0301_0400/s0335_self_crossing)| Hard | Array, Math, Geometry | 477 | 100.00 +| 0334 |[Increasing Triplet Subsequence](src/main/kotlin/g0301_0400/s0334_increasing_triplet_subsequence)| Medium | Top_Interview_Questions, Array, Greedy, Data_Structure_II_Day_5_Array | 672 | 60.61 +| 0332 |[Reconstruct Itinerary](src/main/kotlin/g0301_0400/s0332_reconstruct_itinerary)| Hard | Depth_First_Search, Graph, Eulerian_Circuit | 240 | 93.88 +| 0331 |[Verify Preorder Serialization of a Binary Tree](src/main/kotlin/g0301_0400/s0331_verify_preorder_serialization_of_a_binary_tree)| Medium | String, Tree, Binary_Tree, Stack | 335 | 70.00 | 0330 |[Patching Array](src/main/kotlin/g0301_0400/s0330_patching_array)| Hard | Array, Greedy | 201 | 100.00 | 0329 |[Longest Increasing Path in a Matrix](src/main/kotlin/g0301_0400/s0329_longest_increasing_path_in_a_matrix)| Hard | Top_Interview_Questions, Dynamic_Programming, Depth_First_Search, Breadth_First_Search, Graph, Memoization, Topological_Sort | 322 | 92.65 | 0328 |[Odd Even Linked List](src/main/kotlin/g0301_0400/s0328_odd_even_linked_list)| Medium | Top_Interview_Questions, Linked_List, Level_2_Day_4_Linked_List, Udemy_Linked_List | 216 | 86.96 | 0327 |[Count of Range Sum](src/main/kotlin/g0301_0400/s0327_count_of_range_sum)| Hard | Array, Binary_Search, Ordered_Set, Divide_and_Conquer, Segment_Tree, Binary_Indexed_Tree, Merge_Sort | 638 | 100.00 -| 0326 |[Wiggle Sort II](src/main/kotlin/g0301_0400/s0326_power_of_three)| Easy | Top_Interview_Questions, Math, Recursion | 413 | 76.12 +| 0326 |[Power of Three](src/main/kotlin/g0301_0400/s0326_power_of_three)| Easy | Top_Interview_Questions, Math, Recursion | 413 | 76.12 | 0324 |[Wiggle Sort II](src/main/kotlin/g0301_0400/s0324_wiggle_sort_ii)| Medium | Top_Interview_Questions, Array, Sorting, Divide_and_Conquer, Quickselect | 545 | 57.14 | 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, Algorithm_II_Day_18_Dynamic_Programming, Dynamic_Programming_I_Day_20, Level_2_Day_12_Dynamic_Programming | 332 | 50.68 | 0321 |[Create Maximum Number](src/main/kotlin/g0301_0400/s0321_create_maximum_number)| Hard | Greedy, Stack, Monotonic_Stack | 209 | 100.00 diff --git a/src/main/kotlin/g0001_0100/s0015_3sum/readme.md b/src/main/kotlin/g0001_0100/s0015_3sum/readme.md index 03b85e4b..73f10de5 100644 --- a/src/main/kotlin/g0001_0100/s0015_3sum/readme.md +++ b/src/main/kotlin/g0001_0100/s0015_3sum/readme.md @@ -35,12 +35,11 @@ Notice that the solution set must not contain duplicate triplets. ## Solution ```kotlin -import java.util.Arrays import kotlin.collections.ArrayList class Solution { fun threeSum(nums: IntArray): List> { - Arrays.sort(nums) + nums.sort() val len = nums.size val result: MutableList> = ArrayList() var l: Int diff --git a/src/main/kotlin/g0001_0100/s0016_3sum_closest/readme.md b/src/main/kotlin/g0001_0100/s0016_3sum_closest/readme.md index a80dc861..88b75bed 100644 --- a/src/main/kotlin/g0001_0100/s0016_3sum_closest/readme.md +++ b/src/main/kotlin/g0001_0100/s0016_3sum_closest/readme.md @@ -34,8 +34,6 @@ You may assume that each input would have exactly one solution. ## Solution ```kotlin -import java.util.Arrays - class Solution { fun threeSumClosest(nums: IntArray?, target: Int): Int { if (nums == null || nums.size < 3) { @@ -44,7 +42,7 @@ class Solution { if (nums.size == 3) { return nums[0] + nums[1] + nums[2] } - Arrays.sort(nums) + nums.sort() val n = nums.size var sum = nums[0] + nums[1] + nums[2] for (i in 0 until n - 2) { diff --git a/src/main/kotlin/g0001_0100/s0018_4sum/readme.md b/src/main/kotlin/g0001_0100/s0018_4sum/readme.md index 5f62d5e8..b07e726c 100644 --- a/src/main/kotlin/g0001_0100/s0018_4sum/readme.md +++ b/src/main/kotlin/g0001_0100/s0018_4sum/readme.md @@ -34,8 +34,6 @@ You may return the answer in **any order**. ## Solution ```kotlin -import java.util.Arrays - class Solution { fun fourSum(nums: IntArray, target: Int): List> { val ret: MutableList> = ArrayList() @@ -45,7 +43,7 @@ class Solution { if (nums[0] == 1000000000 && nums[1] == 1000000000) { return ret } - Arrays.sort(nums) + nums.sort() for (i in 0 until nums.size - 3) { if (i != 0 && nums[i] == nums[i - 1]) { continue diff --git a/src/main/kotlin/g0001_0100/s0040_combination_sum_ii/readme.md b/src/main/kotlin/g0001_0100/s0040_combination_sum_ii/readme.md index b1fe40bd..ee397601 100644 --- a/src/main/kotlin/g0001_0100/s0040_combination_sum_ii/readme.md +++ b/src/main/kotlin/g0001_0100/s0040_combination_sum_ii/readme.md @@ -32,14 +32,13 @@ Each number in `candidates` may only be used **once** in the combination. ## Solution ```kotlin -import java.util.Arrays import java.util.LinkedList class Solution { fun combinationSum2(candidates: IntArray, target: Int): List> { val sums: MutableList> = ArrayList() // optimize - Arrays.sort(candidates) + candidates.sort() combinationSum(candidates, target, 0, sums, LinkedList()) return sums } 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 90235862..03852ca0 100644 --- a/src/main/kotlin/g0001_0100/s0049_group_anagrams/readme.md +++ b/src/main/kotlin/g0001_0100/s0049_group_anagrams/readme.md @@ -36,14 +36,12 @@ An **Anagram** is a word or phrase formed by rearranging the letters of a differ ## Solution ```kotlin -import java.util.Arrays - class Solution { fun groupAnagrams(strs: Array): List> { val hm: MutableMap> = HashMap() for (s in strs) { val ch = s.toCharArray() - Arrays.sort(ch) + ch.sort() val temp = String(ch) hm.computeIfAbsent( temp diff --git a/src/main/kotlin/g0001_0100/s0056_merge_intervals/readme.md b/src/main/kotlin/g0001_0100/s0056_merge_intervals/readme.md index 6afc1ec3..8543110b 100644 --- a/src/main/kotlin/g0001_0100/s0056_merge_intervals/readme.md +++ b/src/main/kotlin/g0001_0100/s0056_merge_intervals/readme.md @@ -32,13 +32,9 @@ Given an array of `intervals` where intervals[i] = [starti, end ## Solution ```kotlin -import java.util.Arrays - class Solution { fun merge(intervals: Array): Array { - Arrays.sort( - intervals - ) { a: IntArray, b: IntArray -> + intervals.sortWith { a: IntArray, b: IntArray -> Integer.compare( a[0], b[0] diff --git a/src/main/kotlin/g0001_0100/s0090_subsets_ii/readme.md b/src/main/kotlin/g0001_0100/s0090_subsets_ii/readme.md index 7de19bde..64c8e7cd 100644 --- a/src/main/kotlin/g0001_0100/s0090_subsets_ii/readme.md +++ b/src/main/kotlin/g0001_0100/s0090_subsets_ii/readme.md @@ -29,14 +29,12 @@ The solution set **must not** contain duplicate subsets. Return the solution in ## Solution ```kotlin -import java.util.Arrays - class Solution { var allComb: MutableList> = ArrayList() var comb: MutableList = ArrayList() lateinit var nums: IntArray fun subsetsWithDup(nums: IntArray): List> { - Arrays.sort(nums) + nums.sort() this.nums = nums dfs(0) allComb.add(ArrayList()) diff --git a/src/main/kotlin/g0101_0200/s0164_maximum_gap/readme.md b/src/main/kotlin/g0101_0200/s0164_maximum_gap/readme.md index 351c4242..fd806f3f 100644 --- a/src/main/kotlin/g0101_0200/s0164_maximum_gap/readme.md +++ b/src/main/kotlin/g0101_0200/s0164_maximum_gap/readme.md @@ -33,15 +33,13 @@ You must write an algorithm that runs in linear time and uses linear extra space ## Solution ```kotlin -import java.util.Arrays - class Solution { fun maximumGap(nums: IntArray): Int { if (nums.size < 2) { return 0 } var ret = Int.MIN_VALUE - Arrays.sort(nums) + nums.sort() for (i in 0 until nums.size - 1) { if (nums[i + 1] - nums[i] > ret) { ret = nums[i + 1] - nums[i] diff --git a/src/main/kotlin/g0101_0200/s0179_largest_number/readme.md b/src/main/kotlin/g0101_0200/s0179_largest_number/readme.md index 6caf2884..277a7b87 100644 --- a/src/main/kotlin/g0101_0200/s0179_largest_number/readme.md +++ b/src/main/kotlin/g0101_0200/s0179_largest_number/readme.md @@ -29,8 +29,6 @@ Since the result may be very large, so you need to return a string instead of an ## Solution ```kotlin -import java.util.Arrays - class Solution { fun largestNumber(nums: IntArray): String { val n = nums.size @@ -38,7 +36,7 @@ class Solution { for (i in 0 until n) { s[i] = nums[i].toString() } - Arrays.sort(s) { a: String?, b: String? -> + s.sortWith { a: String?, b: String? -> (b + a).compareTo( a + b ) diff --git a/src/main/kotlin/g0201_0300/s0215_kth_largest_element_in_an_array/readme.md b/src/main/kotlin/g0201_0300/s0215_kth_largest_element_in_an_array/readme.md index 73f8680c..84de2ef4 100644 --- a/src/main/kotlin/g0201_0300/s0215_kth_largest_element_in_an_array/readme.md +++ b/src/main/kotlin/g0201_0300/s0215_kth_largest_element_in_an_array/readme.md @@ -31,12 +31,10 @@ You must solve it in `O(n)` time complexity. ## Solution ```kotlin -import java.util.Arrays - class Solution { fun findKthLargest(nums: IntArray, k: Int): Int { val n = nums.size - Arrays.sort(nums) + nums.sort() return nums[n - k] } } diff --git a/src/main/kotlin/g0301_0400/s0324_wiggle_sort_ii/readme.md b/src/main/kotlin/g0301_0400/s0324_wiggle_sort_ii/readme.md index 2f05d38e..23ccdb3e 100644 --- a/src/main/kotlin/g0301_0400/s0324_wiggle_sort_ii/readme.md +++ b/src/main/kotlin/g0301_0400/s0324_wiggle_sort_ii/readme.md @@ -34,11 +34,9 @@ You may assume the input array always has a valid answer. ## Solution ```kotlin -import java.util.Arrays - class Solution { fun wiggleSort(nums: IntArray) { - Arrays.sort(nums) + nums.sort() val result = IntArray(nums.size) var index = nums.size - 1 var i = 1 diff --git a/src/main/kotlin/g0301_0400/s0326_power_of_three/readme.md b/src/main/kotlin/g0301_0400/s0326_power_of_three/readme.md index 8f199bf4..8786cc61 100644 --- a/src/main/kotlin/g0301_0400/s0326_power_of_three/readme.md +++ b/src/main/kotlin/g0301_0400/s0326_power_of_three/readme.md @@ -1,35 +1,43 @@ [![](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) -## 324\. Wiggle Sort II +## 326\. Power of Three -Medium +Easy -Given an integer array `nums`, reorder it such that `nums[0] < nums[1] > nums[2] < nums[3]...`. +Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_. -You may assume the input array always has a valid answer. +An integer `n` is a power of three, if there exists an integer `x` such that n == 3x. **Example 1:** -**Input:** nums = [1,5,1,1,6,4] +**Input:** n = 27 -**Output:** [1,6,1,5,1,4] +**Output:** true -**Explanation:** [1,4,1,5,1,6] is also accepted. +**Explanation:** 27 = 33 **Example 2:** -**Input:** nums = [1,3,2,2,3,1] +**Input:** n = 0 -**Output:** [2,3,1,3,1,2] +**Output:** false + +**Explanation:** There is no x where 3x = 0. + +**Example 3:** + +**Input:** n = -1 + +**Output:** false + +**Explanation:** There is no x where 3x = (-1). **Constraints:** -* 1 <= nums.length <= 5 * 104 -* `0 <= nums[i] <= 5000` -* It is guaranteed that there will be an answer for the given input `nums`. +* -231 <= n <= 231 - 1 -**Follow Up:** Can you do it in `O(n)` time and/or **in-place** with `O(1)` extra space? +**Follow up:** Could you solve it without loops/recursion? ## Solution diff --git a/src/main/kotlin/g0301_0400/s0331_verify_preorder_serialization_of_a_binary_tree/readme.md b/src/main/kotlin/g0301_0400/s0331_verify_preorder_serialization_of_a_binary_tree/readme.md new file mode 100644 index 00000000..4d474d5a --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0331_verify_preorder_serialization_of_a_binary_tree/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) + +## 331\. Verify Preorder Serialization of a Binary Tree + +Medium + +One way to serialize a binary tree is to use **preorder traversal**. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as `'#'`. + +![](https://assets.leetcode.com/uploads/2021/03/12/pre-tree.jpg) + +For example, the above binary tree can be serialized to the string `"9,3,4,#,#,1,#,#,2,#,6,#,#"`, where `'#'` represents a null node. + +Given a string of comma-separated values `preorder`, return `true` if it is a correct preorder traversal serialization of a binary tree. + +It is **guaranteed** that each comma-separated value in the string must be either an integer or a character `'#'` representing null pointer. + +You may assume that the input format is always valid. + +* For example, it could never contain two consecutive commas, such as `"1,,3"`. + +**Note:** You are not allowed to reconstruct the tree. + +**Example 1:** + +**Input:** preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" + +**Output:** true + +**Example 2:** + +**Input:** preorder = "1,#" + +**Output:** false + +**Example 3:** + +**Input:** preorder = "9,#,#,1" + +**Output:** false + +**Constraints:** + +* 1 <= preorder.length <= 104 +* `preorder` consist of integers in the range `[0, 100]` and `'#'` separated by commas `','`. + +## Solution + +```kotlin +class Solution { + fun isValidSerialization(preorder: String): Boolean { + var count = 1 + val length = preorder.length + for (i in 1..length) { + if (i == length || preorder[i] == ',') { + --count + if (count < 0) { + return false + } + count += if (preorder[i - 1] == '#') 0 else 2 + } + } + return count == 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0332_reconstruct_itinerary/readme.md b/src/main/kotlin/g0301_0400/s0332_reconstruct_itinerary/readme.md new file mode 100644 index 00000000..15bf936d --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0332_reconstruct_itinerary/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) + +## 332\. Reconstruct Itinerary + +Hard + +You are given a list of airline `tickets` where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. + +All of the tickets belong to a man who departs from `"JFK"`, thus, the itinerary must begin with `"JFK"`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. + +* For example, the itinerary `["JFK", "LGA"]` has a smaller lexical order than `["JFK", "LGB"]`. + +You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/14/itinerary1-graph.jpg) + +**Input:** tickets = \[\["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] + +**Output:** ["JFK","MUC","LHR","SFO","SJC"] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/03/14/itinerary2-graph.jpg) + +**Input:** tickets = \[\["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] + +**Output:** ["JFK","ATL","JFK","SFO","ATL","SFO"] + +**Explanation:** + + Another possible reconstruction is + ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order. + +**Constraints:** + +* `1 <= tickets.length <= 300` +* `tickets[i].length == 2` +* fromi.length == 3 +* toi.length == 3 +* fromi and toi consist of uppercase English letters. +* fromi != toi + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.PriorityQueue + +class Solution { + fun findItinerary(tickets: List>): List { + val map: HashMap> = HashMap() + val ans = LinkedList() + for (ticket in tickets) { + val src = ticket[0] + val dest = ticket[1] + var pq = map[src] + if (pq == null) { + pq = PriorityQueue() + } + pq.add(dest) + map[src] = pq + } + dfs(map, "JFK", ans) + return ans + } + + private fun dfs(map: Map>, src: String, ans: LinkedList) { + val temp = map[src] + while (temp != null && !temp.isEmpty()) { + val nbr = temp.remove() + dfs(map, nbr, ans) + } + ans.addFirst(src) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0334_increasing_triplet_subsequence/readme.md b/src/main/kotlin/g0301_0400/s0334_increasing_triplet_subsequence/readme.md new file mode 100644 index 00000000..43f1f65a --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0334_increasing_triplet_subsequence/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) + +## 334\. Increasing Triplet Subsequence + +Medium + +Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`. + +**Example 1:** + +**Input:** nums = [1,2,3,4,5] + +**Output:** true + +**Explanation:** Any triplet where i < j < k is valid. + +**Example 2:** + +**Input:** nums = [5,4,3,2,1] + +**Output:** false + +**Explanation:** No triplet exists. + +**Example 3:** + +**Input:** nums = [2,1,5,0,4,6] + +**Output:** true + +**Explanation:** The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6. + +**Constraints:** + +* 1 <= nums.length <= 5 * 105 +* -231 <= nums[i] <= 231 - 1 + +**Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity? + +## Solution + +```kotlin +class Solution { + fun increasingTriplet(nums: IntArray): Boolean { + if (nums.size == 1) { + return false + } + var big: Int = nums.lastIndex + var medium: Int? = null + for (i in nums.lastIndex - 1 downTo 0) { + if (nums[i] > nums[big]) { + big = i + continue + } else if ((medium != null && nums[i] > nums[medium] && nums[i] < nums[big]) || + (medium == null && nums[i] < nums[big]) + ) { + medium = i + continue + } else if (medium != null && nums[i] < nums[medium]) { + return true + } + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0335_self_crossing/readme.md b/src/main/kotlin/g0301_0400/s0335_self_crossing/readme.md new file mode 100644 index 00000000..13cd7c97 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0335_self_crossing/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) + +## 335\. Self Crossing + +Hard + +You are given an array of integers `distance`. + +You start at point `(0,0)` on an **X-Y** plane and you move `distance[0]` meters to the north, then `distance[1]` meters to the west, `distance[2]` meters to the south, `distance[3]` meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise. + +Return `true` if your path crosses itself, and `false` if it does not. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/14/selfcross1-plane.jpg) + +**Input:** distance = [2,1,1,2] + +**Output:** true + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/03/14/selfcross2-plane.jpg) + +**Input:** distance = [1,2,3,4] + +**Output:** false + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/03/14/selfcross3-plane.jpg) + +**Input:** distance = [1,1,1,1] + +**Output:** true + +**Constraints:** + +* 1 <= distance.length <= 105 +* 1 <= distance[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun isSelfCrossing(x: IntArray): Boolean { + if (x.size < 4) { + return false + } + for (i in 3 until x.size) { + if (x[i - 1] <= x[i - 3] && x[i] >= x[i - 2]) { + return true + } + if (i > 4 && x[i] >= x[i - 2] - x[i - 4] && x[i - 1] >= x[i - 3] - x[i - 5] && x[i - 1] <= x[i - 3] && + x[i - 2] >= x[i - 4] + ) { + return true + } + if (i > 3 && x[i - 1] == x[i - 3] && x[i] >= x[i - 2] - x[i - 4]) { + return true + } + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0336_palindrome_pairs/readme.md b/src/main/kotlin/g0301_0400/s0336_palindrome_pairs/readme.md new file mode 100644 index 00000000..b007458f --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0336_palindrome_pairs/readme.md @@ -0,0 +1,114 @@ +[![](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) + +## 336\. Palindrome Pairs + +Hard + +You are given a **0-indexed** array of **unique** strings `words`. + +A **palindrome pair** is a pair of integers `(i, j)` such that: + +* `0 <= i, j < word.length`, +* `i != j`, and +* `words[i] + words[j]` (the concatenation of the two strings) is a palindrome. + +Return _an array of all the **palindrome pairs** of_ `words`. + +**Example 1:** + +**Input:** words = ["abcd","dcba","lls","s","sssll"] + +**Output:** [[0,1],[1,0],[3,2],[2,4]] + +**Explanation:** The palindromes are ["abcddcba","dcbaabcd","slls","llssssll"] + +**Example 2:** + +**Input:** words = ["bat","tab","cat"] + +**Output:** [[0,1],[1,0]] + +**Explanation:** The palindromes are ["battab","tabbat"] + +**Example 3:** + +**Input:** words = ["a",""] + +**Output:** [[0,1],[1,0]] + +**Explanation:** The palindromes are ["a","a"] + +**Constraints:** + +* `1 <= words.length <= 5000` +* `0 <= words[i].length <= 300` +* `words[i]` consists of lowercase English letters. + +## Solution + +```kotlin +@Suppress("kotlin:S6218", "NAME_SHADOWING") +class Solution { + fun palindromePairs(words: Array): List> { + val ans = mutableListOf>() + val root = TrieNode() + for (idx in words.indices) { + addWord(root, words[idx], idx) + } + for (idx in words.indices) { + search(idx, root, words, ans) + } + return ans + } + + private fun search(idxCurWord: Int, root: TrieNode, words: Array, res: MutableList>) { + var cur: TrieNode? = root + val curWord = words[idxCurWord] + val lenW = curWord.length + for (idxCh in curWord.indices) { + if (cur!!.index >= 0 && cur.index != idxCurWord && isPalindrome(curWord, idxCh, lenW - 1)) + res.add(listOf(idxCurWord, cur.index)) + cur = cur.children[curWord[idxCh] - 'a'] + if (cur == null) + return + } + for (idxPalin in cur!!.panlinIndicies) { + if (idxPalin == idxCurWord) continue + res.add(listOf(idxCurWord, idxPalin)) + } + } + + private fun addWord(root: TrieNode, word: String, index: Int) { + var cur: TrieNode? = root + for (idx in word.indices.reversed()) { + val idxCh = word[idx] - 'a' + if (cur!!.children[idxCh] == null) + cur.children[idxCh] = TrieNode() + if (isPalindrome(word, 0, idx)) + cur.panlinIndicies.add(index) + cur = cur.children[idxCh] + } + cur!!.panlinIndicies.add(index) + cur.index = index + } + + private fun isPalindrome(word: String, lo: Int, hi: Int): Boolean { + var lo = lo + var hi = hi + while (lo < hi) { + if (word[lo] != word[hi]) + return false + ++lo + --hi + } + return true + } + + private data class TrieNode( + val children: Array = Array(26) { null }, + var index: Int = -1, + val panlinIndicies: MutableList = mutableListOf() + ) +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0337_house_robber_iii/readme.md b/src/main/kotlin/g0301_0400/s0337_house_robber_iii/readme.md new file mode 100644 index 00000000..f8ace390 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0337_house_robber_iii/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) + +## 337\. House Robber III + +Medium + +The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`. + +Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**. + +Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/10/rob1-tree.jpg) + +**Input:** root = [3,2,3,null,3,null,1] + +**Output:** 7 + +**Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/03/10/rob2-tree.jpg) + +**Input:** root = [3,4,5,1,3,null,1] + +**Output:** 9 + +**Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9. + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 104]. +* 0 <= Node.val <= 104 + +## 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 rob(root: TreeNode?): Int { + val out = robRec(root) + return Math.max(out[0], out[1]) + } + + private fun robRec(curr: TreeNode?): IntArray { + if (curr == null) { + return intArrayOf(0, 0) + } + val left = robRec(curr.left) + val right = robRec(curr.right) + val out = IntArray(2) + // 1. If choosing to take the house + out[0] = curr.`val` + left[1] + right[1] + // 2. If choosing to skip the house + out[1] = left[0] + right[0] + // 3. Best Solution at house + out[0] = Math.max(out[0], out[1]) + return out + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0342_power_of_four/readme.md b/src/main/kotlin/g0301_0400/s0342_power_of_four/readme.md new file mode 100644 index 00000000..3c72832b --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0342_power_of_four/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) + +## 342\. Power of Four + +Easy + +Given an integer `n`, return _`true` if it is a power of four. Otherwise, return `false`_. + +An integer `n` is a power of four, if there exists an integer `x` such that n == 4x. + +**Example 1:** + +**Input:** n = 16 + +**Output:** true + +**Example 2:** + +**Input:** n = 5 + +**Output:** false + +**Example 3:** + +**Input:** n = 1 + +**Output:** true + +**Constraints:** + +* -231 <= n <= 231 - 1 + +**Follow up:** Could you solve it without loops/recursion? + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun isPowerOfFour(n: Int): Boolean { + var n = n + while (n >= 4) { + if (n % 4 != 0) { + return false + } + n = n / 4 + } + return n == 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0343_integer_break/readme.md b/src/main/kotlin/g0301_0400/s0343_integer_break/readme.md new file mode 100644 index 00000000..14a23a54 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0343_integer_break/readme.md @@ -0,0 +1,55 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 343\. Integer Break + +Medium + +Given an integer `n`, break it into the sum of `k` **positive integers**, where `k >= 2`, and maximize the product of those integers. + +Return _the maximum product you can get_. + +**Example 1:** + +**Input:** n = 2 + +**Output:** 1 + +**Explanation:** 2 = 1 + 1, 1 × 1 = 1. + +**Example 2:** + +**Input:** n = 10 + +**Output:** 36 + +**Explanation:** 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. + +**Constraints:** + +* `2 <= n <= 58` + +## Solution + +```kotlin +class Solution { + fun integerBreak(n: Int): Int { + if (n <= 1) return 0 + if (n == 2) return 1 + if (n == 3) return 2 + + var threes = n / 3 + + // if there's just 1 remaining, it's better to use 2 x 2's instead of 3 and 1: + if (n - threes * 3 == 1) threes-- + val twos = (n - threes * 3) / 2 + + val threeProd = Math.pow(3.0, threes.toDouble()).toInt() + val twoProd = Math.pow(2.0, twos.toDouble()).toInt() + if (threeProd == 0) return twoProd + if (twoProd == 0) return threeProd + + return twoProd * threeProd + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0344_reverse_string/readme.md b/src/main/kotlin/g0301_0400/s0344_reverse_string/readme.md new file mode 100644 index 00000000..f0a868b9 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0344_reverse_string/readme.md @@ -0,0 +1,43 @@ +[![](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) + +## 344\. Reverse String + +Easy + +Write a function that reverses a string. The input string is given as an array of characters `s`. + +You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory. + +**Example 1:** + +**Input:** s = ["h","e","l","l","o"] + +**Output:** ["o","l","l","e","h"] + +**Example 2:** + +**Input:** s = ["H","a","n","n","a","h"] + +**Output:** ["h","a","n","n","a","H"] + +**Constraints:** + +* 1 <= s.length <= 105 +* `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters). + +## Solution + +```kotlin +class Solution { + fun reverseString(s: CharArray) { + var left = 0 + var right = s.size - 1 + while (left < right) { + val tmp = s[left] + s[left++] = s[right] + s[right--] = tmp + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0345_reverse_vowels_of_a_string/readme.md b/src/main/kotlin/g0301_0400/s0345_reverse_vowels_of_a_string/readme.md new file mode 100644 index 00000000..c119c661 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0345_reverse_vowels_of_a_string/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) + +## 345\. Reverse Vowels of a String + +Easy + +Given a string `s`, reverse only all the vowels in the string and return it. + +The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once. + +**Example 1:** + +**Input:** s = "hello" + +**Output:** "holle" + +**Example 2:** + +**Input:** s = "leetcode" + +**Output:** "leotcede" + +**Constraints:** + +* 1 <= s.length <= 3 * 105 +* `s` consist of **printable ASCII** characters. + +## Solution + +```kotlin +class Solution { + private fun isVowel(c: Char): Boolean { + return c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || + c == 'u' || c == 'U' + } + + fun reverseVowels(str: String): String { + var i = 0 + var j = str.length - 1 + val str1 = str.toCharArray() + while (i < j) { + if (!isVowel(str1[i])) { + i++ + } else if (!isVowel(str1[j])) { + j-- + } else { + // swapping + val t = str1[i] + str1[i] = str1[j] + str1[j] = t + i++ + j-- + } + } + return String(str1) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0347_top_k_frequent_elements/readme.md b/src/main/kotlin/g0301_0400/s0347_top_k_frequent_elements/readme.md index 34401e72..17f34bb2 100644 --- a/src/main/kotlin/g0301_0400/s0347_top_k_frequent_elements/readme.md +++ b/src/main/kotlin/g0301_0400/s0347_top_k_frequent_elements/readme.md @@ -31,13 +31,12 @@ Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequen ## Solution ```kotlin -import java.util.Arrays import java.util.PriorityQueue import java.util.Queue class Solution { fun topKFrequent(nums: IntArray, k: Int): IntArray { - Arrays.sort(nums) + nums.sort() // Min heap of val queue: Queue = PriorityQueue(k + 1) { a: IntArray, b: IntArray -> a[1] - b[1] } // Filter with min heap diff --git a/src/main/kotlin/g0301_0400/s0349_intersection_of_two_arrays/readme.md b/src/main/kotlin/g0301_0400/s0349_intersection_of_two_arrays/readme.md new file mode 100644 index 00000000..509da872 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0349_intersection_of_two_arrays/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) + +## 349\. Intersection of Two Arrays + +Easy + +Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**. + +**Example 1:** + +**Input:** nums1 = [1,2,2,1], nums2 = [2,2] + +**Output:** [2] + +**Example 2:** + +**Input:** nums1 = [4,9,5], nums2 = [9,4,9,8,4] + +**Output:** [9,4] + +**Explanation:** [4,9] is also accepted. + +**Constraints:** + +* `1 <= nums1.length, nums2.length <= 1000` +* `0 <= nums1[i], nums2[i] <= 1000` + +## Solution + +```kotlin +class Solution { + fun intersection(nums1: IntArray, nums2: IntArray): IntArray { + val occ = BooleanArray(1001) + for (k in nums1) { + occ[k] = true + } + val res: MutableList = ArrayList() + for (j in nums2) { + if (occ[j]) { + occ[j] = false + res.add(j) + } + } + val result = IntArray(res.size) + for (i in res.indices) { + result[i] = res[i] + } + return result + } +} +``` \ No newline at end of file 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 new file mode 100644 index 00000000..b95c3163 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0350_intersection_of_two_arrays_ii/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) + +## 350\. Intersection of Two Arrays II + +Easy + +Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**. + +**Example 1:** + +**Input:** nums1 = [1,2,2,1], nums2 = [2,2] + +**Output:** [2,2] + +**Example 2:** + +**Input:** nums1 = [4,9,5], nums2 = [9,4,9,8,4] + +**Output:** [4,9] + +**Explanation:** [9,4] is also accepted. + +**Constraints:** + +* `1 <= nums1.length, nums2.length <= 1000` +* `0 <= nums1[i], nums2[i] <= 1000` + +**Follow up:** + +* What if the given array is already sorted? How would you optimize your algorithm? +* What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better? +* What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? + +## Solution + +```kotlin +class Solution { + fun intersect(nums1: IntArray, nums2: IntArray): IntArray { + val a: MutableMap = mutableMapOf() + for (i in 0 until nums1.size) { + a[nums1[i]] = a.getOrDefault(nums1[i], 0) + 1 + } + var s = MutableList(0) { 0 } + 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 + } + } + return s.toIntArray() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0352_data_stream_as_disjoint_intervals/readme.md b/src/main/kotlin/g0301_0400/s0352_data_stream_as_disjoint_intervals/readme.md new file mode 100644 index 00000000..515688f3 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0352_data_stream_as_disjoint_intervals/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) + +## 352\. Data Stream as Disjoint Intervals + +Hard + +Given a data stream input of non-negative integers a1, a2, ..., an, summarize the numbers seen so far as a list of disjoint intervals. + +Implement the `SummaryRanges` class: + +* `SummaryRanges()` Initializes the object with an empty stream. +* `void addNum(int val)` Adds the integer `val` to the stream. +* `int[][] getIntervals()` Returns a summary of the integers in the stream currently as a list of disjoint intervals [starti, endi]. + +**Example 1:** + +**Input** + + ["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"] + [[], [1], [], [3], [], [7], [], [2], [], [6], []] + +**Output:** [null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]] + +**Explanation:** + + SummaryRanges summaryRanges = new SummaryRanges(); + summaryRanges.addNum(1); // arr = [1] + summaryRanges.getIntervals(); // return [[1, 1]] + summaryRanges.addNum(3); // arr = [1, 3] + summaryRanges.getIntervals(); // return [[1, 1], [3, 3]] + summaryRanges.addNum(7); // arr = [1, 3, 7] + summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]] + summaryRanges.addNum(2); // arr = [1, 2, 3, 7] + summaryRanges.getIntervals(); // return [[1, 3], [7, 7]] + summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7] + summaryRanges.getIntervals(); // return [[1, 3], [6, 7]] + +**Constraints:** + +* 0 <= val <= 104 +* At most 3 * 104 calls will be made to `addNum` and `getIntervals`. + +**Follow up:** What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream? + +## Solution + +```kotlin +class SummaryRanges { + private class Node(var min: Int) { + var max: Int + + init { + max = min + } + } + + private val list: MutableList + + init { + list = ArrayList() + } + + fun addNum(`val`: Int) { + var left = 0 + var right = list.size - 1 + var index = list.size + while (left <= right) { + val mid = left + (right - left) / 2 + val node = list[mid] + if (node.min <= `val` && `val` <= node.max) { + return + } else if (`val` < node.min) { + index = mid + right = mid - 1 + } else if (`val` > node.max) { + left = mid + 1 + } + } + list.add(index, Node(`val`)) + } + + fun getIntervals(): Array { + var i = 1 + while (i < list.size) { + val prev = list[i - 1] + val curr = list[i] + if (curr.min == prev.max + 1) { + prev.max = curr.max + list.removeAt(i--) + } + i++ + } + val len = list.size + val res = Array(len) { IntArray(2) } + for (j in 0 until len) { + val node = list[j] + res[j][0] = node.min + res[j][1] = node.max + } + return res + } +} + +/** + * Your SummaryRanges object will be instantiated and called as such: + * var obj = SummaryRanges() + * obj.addNum(value) + * var param_2 = obj.getIntervals() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0354_russian_doll_envelopes/readme.md b/src/main/kotlin/g0301_0400/s0354_russian_doll_envelopes/readme.md new file mode 100644 index 00000000..9eb79aba --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0354_russian_doll_envelopes/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) + +## 354\. Russian Doll Envelopes + +Hard + +You are given a 2D array of integers `envelopes` where envelopes[i] = [wi, hi] represents the width and the height of an envelope. + +One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. + +Return _the maximum number of envelopes you can Russian doll (i.e., put one inside the other)_. + +**Note:** You cannot rotate an envelope. + +**Example 1:** + +**Input:** envelopes = \[\[5,4],[6,4],[6,7],[2,3]] + +**Output:** 3 + +**Explanation:** The maximum number of envelopes you can Russian doll is `3` ([2,3] => [5,4] => [6,7]). + +**Example 2:** + +**Input:** envelopes = \[\[1,1],[1,1],[1,1]] + +**Output:** 1 + +**Constraints:** + +* 1 <= envelopes.length <= 105 +* `envelopes[i].length == 2` +* 1 <= wi, hi <= 105 + +## Solution + +```kotlin +class Solution { + fun maxEnvelopes(envelopes: Array): Int { + envelopes.sortWith { a: IntArray, b: IntArray -> + if (a[0] != b[0] + ) a[0] - b[0] else b[1] - a[1] + } + val tails = IntArray(envelopes.size) + var size = 0 + for (enve in envelopes) { + var i = 0 + var j = size + while (i != j) { + val mid = i + (j - i shr 1) + if (tails[mid] < enve[1]) { + i = mid + 1 + } else { + j = mid + } + } + tails[i] = enve[1] + if (i == size) { + size++ + } + } + return size + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0355_design_twitter/readme.md b/src/main/kotlin/g0301_0400/s0355_design_twitter/readme.md new file mode 100644 index 00000000..7dea0999 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0355_design_twitter/readme.md @@ -0,0 +1,123 @@ +[![](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) + +## 355\. Design Twitter + +Medium + +Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the `10` most recent tweets in the user's news feed. + +Implement the `Twitter` class: + +* `Twitter()` Initializes your twitter object. +* `void postTweet(int userId, int tweetId)` Composes a new tweet with ID `tweetId` by the user `userId`. Each call to this function will be made with a unique `tweetId`. +* `List getNewsFeed(int userId)` Retrieves the `10` most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be **ordered from most recent to least recent**. +* `void follow(int followerId, int followeeId)` The user with ID `followerId` started following the user with ID `followeeId`. +* `void unfollow(int followerId, int followeeId)` The user with ID `followerId` started unfollowing the user with ID `followeeId`. + +**Example 1:** + +**Input** + + ["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] + [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]] + +**Output:** + + [null, null, [5], null, null, [6, 5], null, [5]] + +**Explanation:** + + Twitter twitter = new Twitter(); + twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). + twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5] + twitter.follow(1, 2); // User 1 follows user 2. + twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). + twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. + // Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. + twitter.unfollow(1, 2); // User 1 unfollows user 2. + twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2. + +**Constraints:** + +* `1 <= userId, followerId, followeeId <= 500` +* 0 <= tweetId <= 104 +* All the tweets have **unique** IDs. +* At most 3 * 104 calls will be made to `postTweet`, `getNewsFeed`, `follow`, and `unfollow`. + +## Solution + +```kotlin +class Twitter { + // userId --> user followers + private val twitterData: MutableMap> + + // head of linked list that stores all the tweets + private val head: Tweet + + private class Tweet internal constructor(var userId: Int, var tweetId: Int) { + var next: Tweet? = null + } + + init { + head = Tweet(-1, -1) + twitterData = HashMap() + } + + fun postTweet(userId: Int, tweetId: Int) { + checkNewUser(userId) + val t = Tweet(userId, tweetId) + val next = head.next + head.next = t + t.next = next + } + + fun getNewsFeed(userId: Int): List { + checkNewUser(userId) + val res: MutableList = ArrayList() + val followers = twitterData[userId]!! + var t = head.next + while (t != null && res.size < 10) { + if (followers.contains(t.userId)) { + res.add(t.tweetId) + } + t = t.next + } + return res + } + + fun follow(followerId: Int, followeeId: Int) { + checkNewUser(followeeId) + checkNewUser(followerId) + twitterData[followerId]!!.add(followeeId) + } + + fun unfollow(followerId: Int, followeeId: Int) { + checkNewUser(followeeId) + // cannot unfollower yourself + if (followerId == followeeId) { + return + } + checkNewUser(followerId) + twitterData[followerId]!!.remove(followeeId) + } + + fun checkNewUser(userId: Int) { + if (twitterData.containsKey(userId)) { + return + } + twitterData[userId] = HashSet() + // follow yourself + twitterData[userId]!!.add(userId) + } +} + +/* + * Your Twitter object will be instantiated and called as such: + * var obj = Twitter() + * obj.postTweet(userId,tweetId) + * var param_2 = obj.getNewsFeed(userId) + * obj.follow(followerId,followeeId) + * obj.unfollow(followerId,followeeId) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0357_count_numbers_with_unique_digits/readme.md b/src/main/kotlin/g0301_0400/s0357_count_numbers_with_unique_digits/readme.md new file mode 100644 index 00000000..6933cb27 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0357_count_numbers_with_unique_digits/readme.md @@ -0,0 +1,43 @@ +[![](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) + +## 357\. Count Numbers with Unique Digits + +Medium + +Given an integer `n`, return the count of all numbers with unique digits, `x`, where 0 <= x < 10n. + +**Example 1:** + +**Input:** n = 2 + +**Output:** 91 + +**Explanation:** The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99 + +**Example 2:** + +**Input:** n = 0 + +**Output:** 1 + +**Constraints:** + +* `0 <= n <= 8` + +## Solution + +```kotlin +class Solution { + fun countNumbersWithUniqueDigits(n: Int): Int { + if (n == 0) return 1 + var temp = 9 + var res = 10 + for (i in 1 until n) { + temp *= (10 - i) + res += temp + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0363_max_sum_of_rectangle_no_larger_than_k/readme.md b/src/main/kotlin/g0301_0400/s0363_max_sum_of_rectangle_no_larger_than_k/readme.md new file mode 100644 index 00000000..e453b496 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0363_max_sum_of_rectangle_no_larger_than_k/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) + +## 363\. Max Sum of Rectangle No Larger Than K + +Hard + +Given an `m x n` matrix `matrix` and an integer `k`, return _the max sum of a rectangle in the matrix such that its sum is no larger than_ `k`. + +It is **guaranteed** that there will be a rectangle with a sum no larger than `k`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/18/sum-grid.jpg) + +**Input:** matrix = \[\[1,0,1],[0,-2,3]], k = 2 + +**Output:** 2 + +**Explanation:** Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2). + +**Example 2:** + +**Input:** matrix = \[\[2,2,-1]], k = 3 + +**Output:** 3 + +**Constraints:** + +* `m == matrix.length` +* `n == matrix[i].length` +* `1 <= m, n <= 100` +* `-100 <= matrix[i][j] <= 100` +* -105 <= k <= 105 + +**Follow up:** What if the number of rows is much larger than the number of columns? + +## Solution + +```kotlin +class Solution { + fun maxSumSubmatrix(matrix: Array, k: Int): Int { + if (matrix.size == 0 || matrix[0].size == 0) { + return 0 + } + val row = matrix.size + val col = matrix[0].size + var res = Int.MIN_VALUE + for (i in 0 until col) { + val sum = IntArray(row) + for (j in i until col) { + for (r in 0 until row) { + sum[r] += matrix[r][j] + } + var curr = 0 + var max = sum[0] + for (n in sum) { + curr = Math.max(n, curr + n) + max = Math.max(curr, max) + if (max == k) { + return max + } + } + if (max < k) { + res = Math.max(max, res) + } else { + for (a in 0 until row) { + var currSum = 0 + for (b in a until row) { + currSum += sum[b] + if (currSum <= k) { + res = Math.max(currSum, res) + } + } + } + if (res == k) { + return res + } + } + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0365_water_and_jug_problem/readme.md b/src/main/kotlin/g0301_0400/s0365_water_and_jug_problem/readme.md new file mode 100644 index 00000000..eb896d51 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0365_water_and_jug_problem/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) + +## 365\. Water and Jug Problem + +Medium + +You are given two jugs with capacities `jug1Capacity` and `jug2Capacity` liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly `targetCapacity` liters using these two jugs. + +If `targetCapacity` liters of water are measurable, you must have `targetCapacity` liters of water contained **within one or both buckets** by the end. + +Operations allowed: + +* Fill any of the jugs with water. +* Empty any of the jugs. +* Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty. + +**Example 1:** + +**Input:** jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4 + +**Output:** true + +**Explanation:** The famous [Die Hard](https://www.youtube.com/watch?v=BVtQNK_ZUJg&ab_channel=notnek01) example + +**Example 2:** + +**Input:** jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5 + +**Output:** false + +**Example 3:** + +**Input:** jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3 + +**Output:** true + +**Constraints:** + +* 1 <= jug1Capacity, jug2Capacity, targetCapacity <= 106 + +## Solution + +```kotlin +class Solution { + private fun gcd(n1: Int, n2: Int): Int { + return if (n2 == 0) { + n1 + } else gcd(n2, n1 % n2) + } + + fun canMeasureWater(jug1: Int, jug2: Int, target: Int): Boolean { + if (jug1 + jug2 < target) { + return false + } + val gcd = gcd(jug1, jug2) + return target % gcd == 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0367_valid_perfect_square/readme.md b/src/main/kotlin/g0301_0400/s0367_valid_perfect_square/readme.md new file mode 100644 index 00000000..8c730e18 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0367_valid_perfect_square/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) + +## 367\. Valid Perfect Square + +Easy + +Given a **positive** integer _num_, write a function which returns True if _num_ is a perfect square else False. + +**Follow up:** **Do not** use any built-in library function such as `sqrt`. + +**Example 1:** + +**Input:** num = 16 + +**Output:** true + +**Example 2:** + +**Input:** num = 14 + +**Output:** false + +**Constraints:** + +* `1 <= num <= 2^31 - 1` + +## Solution + +```kotlin +class Solution { + fun isPerfectSquare(num: Int): Boolean { + if (num == 0) { + // If num is 0 return false + return false + } + // long datatype can holds huge number. + var start: Long = 0 + var end = num.toLong() + var mid: Long + while (start <= end) { + // until start is lesser or equal to end do this + // Finding middle value + mid = start + (end - start) / 2 + if (mid * mid == num.toLong()) { + // if mid*mid == num return true + return true + } else if (mid * mid < num) { + // if num is greater than mid*mid then make start = mid + 1 + start = mid + 1 + } else if (mid * mid > num) { + // if num is lesser than mid*mid then make end = mid - 1 + end = mid - 1 + } + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0301_0400/s0368_largest_divisible_subset/readme.md b/src/main/kotlin/g0301_0400/s0368_largest_divisible_subset/readme.md new file mode 100644 index 00000000..036cb1f4 --- /dev/null +++ b/src/main/kotlin/g0301_0400/s0368_largest_divisible_subset/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) + +## 368\. Largest Divisible Subset + +Medium + +Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies: + +* `answer[i] % answer[j] == 0`, or +* `answer[j] % answer[i] == 0` + +If there are multiple solutions, return any of them. + +**Example 1:** + +**Input:** nums = [1,2,3] + +**Output:** [1,2] + +**Explanation:** [1,3] is also accepted. + +**Example 2:** + +**Input:** nums = [1,2,4,8] + +**Output:** [1,2,4,8] + +**Constraints:** + +* `1 <= nums.length <= 1000` +* 1 <= nums[i] <= 2 * 109 +* All the integers in `nums` are **unique**. + +## Solution + +```kotlin +class Solution { + fun largestDivisibleSubset(nums: IntArray): List { + val n = nums.size + val count = IntArray(n) + val pre = IntArray(n) + nums.sort() + var max = 0 + var index = -1 + for (i in 0 until n) { + count[i] = 1 + pre[i] = -1 + for (j in i - 1 downTo 0) { + if (nums[i] % nums[j] == 0 && 1 + count[j] > count[i]) { + count[i] = count[j] + 1 + pre[i] = j + } + } + if (count[i] > max) { + max = count[i] + index = i + } + } + val res: MutableList = ArrayList() + while (index != -1) { + res.add(nums[index]) + index = pre[index] + } + return res + } +} +``` \ No newline at end of file