From 6aaf06b6cf53de73beda27bc278f9682064c62d6 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Fri, 13 Jan 2023 03:56:42 +0200 Subject: [PATCH] Added tasks 481-513. --- README.md | 34 ++++- .../readme.md | 36 ++--- .../readme.md | 2 - .../g0401_0500/s0481_magical_string/readme.md | 59 ++++++++ .../s0482_license_key_formatting/readme.md | 69 ++++++++++ .../s0483_smallest_good_base/readme.md | 83 +++++++++++ .../s0485_max_consecutive_ones/readme.md | 48 +++++++ .../s0486_predict_the_winner/readme.md | 54 ++++++++ .../g0401_0500/s0488_zuma_game/readme.md | 129 ++++++++++++++++++ .../s0491_increasing_subsequences/readme.md | 59 ++++++++ .../s0492_construct_the_rectangle/readme.md | 60 ++++++++ .../g0401_0500/s0493_reverse_pairs/readme.md | 75 ++++++++++ .../s0495_teemo_attacking/readme.md | 72 ++++++++++ .../s0496_next_greater_element_i/readme.md | 83 +++++++++++ .../readme.md | 106 ++++++++++++++ .../s0498_diagonal_traverse/readme.md | 55 ++++++++ .../g0401_0500/s0500_keyboard_row/readme.md | 70 ++++++++++ .../readme.md | 93 +++++++++++++ .../kotlin/g0501_0600/s0502_ipo/readme.md | 87 ++++++++++++ .../s0503_next_greater_element_ii/readme.md | 49 +++++++ .../kotlin/g0501_0600/s0504_base_7/readme.md | 34 +++++ .../g0501_0600/s0506_relative_ranks/readme.md | 62 +++++++++ .../g0501_0600/s0507_perfect_number/readme.md | 44 ++++++ .../s0508_most_frequent_subtree_sum/readme.md | 70 ++++++++++ .../s0509_fibonacci_number/readme.md | 61 +++++++++ .../s0511_game_play_analysis_i/readme.md | 62 +++++++++ .../readme.md | 82 +++++++++++ 27 files changed, 1709 insertions(+), 29 deletions(-) create mode 100644 src/main/kotlin/g0401_0500/s0481_magical_string/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0482_license_key_formatting/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0483_smallest_good_base/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0485_max_consecutive_ones/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0486_predict_the_winner/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0488_zuma_game/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0491_increasing_subsequences/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0492_construct_the_rectangle/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0493_reverse_pairs/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0495_teemo_attacking/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0496_next_greater_element_i/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0497_random_point_in_non_overlapping_rectangles/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0498_diagonal_traverse/readme.md create mode 100644 src/main/kotlin/g0401_0500/s0500_keyboard_row/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0501_find_mode_in_binary_search_tree/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0502_ipo/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0503_next_greater_element_ii/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0504_base_7/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0506_relative_ranks/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0507_perfect_number/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0508_most_frequent_subtree_sum/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0509_fibonacci_number/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0511_game_play_analysis_i/readme.md create mode 100644 src/main/kotlin/g0501_0600/s0513_find_bottom_left_tree_value/readme.md diff --git a/README.md b/README.md index 490d4ae4..09dc3059 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ | | | | | | |-|-|-|-|-|- +| 0496 |[Next Greater Element I](src/main/kotlin/g0401_0500/s0496_next_greater_element_i)| Easy | Array, Hash_Table, Stack, Monotonic_Stack | 171 | 100.00 #### Day 6 Array @@ -152,6 +153,7 @@ | | | | | | |-|-|-|-|-|- +| 0503 |[Next Greater Element II](src/main/kotlin/g0501_0600/s0503_next_greater_element_ii)| Medium | Array, Stack, Monotonic_Stack | 331 | 92.68 #### Day 11 @@ -338,6 +340,7 @@ | | | | | | |-|-|-|-|-|- +| 0511 |[Game Play Analysis I](src/main/kotlin/g0501_0600/s0511_game_play_analysis_i)| Easy | LeetCode_Curated_SQL_70, Database | 790 | 45.04 #### Day 9 Control of Flow @@ -413,6 +416,7 @@ | | | | | | |-|-|-|-|-|- +| 0509 |[Fibonacci Number](src/main/kotlin/g0501_0600/s0509_fibonacci_number)| Easy | Dynamic_Programming, Math, Recursion, Memoization | 139 | 82.72 | 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 11 Dynamic Programming @@ -534,7 +538,7 @@ | | | | | | |-|-|-|-|-|- -| 0416 |[Partition Equal Subset Sum](src/main/kotlin/g0401_0500/s0416_partition_equal_subset_sum)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming | 509 | 57.56 +| 0416 |[Partition Equal Subset Sum](src/main/kotlin/g0401_0500/s0416_partition_equal_subset_sum)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming | 204 | 98.82 | 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 14 Sliding Window/Two Pointer @@ -743,6 +747,7 @@ | 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 | 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 +| 0509 |[Fibonacci Number](src/main/kotlin/g0501_0600/s0509_fibonacci_number)| Easy | Dynamic_Programming, Math, Recursion, Memoization | 139 | 82.72 | 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 | 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 | 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 @@ -1460,6 +1465,7 @@ | | | | | | |-|-|-|-|-|- +| 0509 |[Fibonacci Number](src/main/kotlin/g0501_0600/s0509_fibonacci_number)| Easy | Dynamic_Programming, Math, Recursion, Memoization | 139 | 82.72 #### Day 2 @@ -1607,7 +1613,31 @@ | 0647 |[Palindromic Substrings](src/main/kotlin/g0601_0700/s0647_palindromic_substrings)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming | 266 | 67.83 | 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 +| 0513 |[Find Bottom Left Tree Value](src/main/kotlin/g0501_0600/s0513_find_bottom_left_tree_value)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 190 | 88.24 +| 0511 |[Game Play Analysis I](src/main/kotlin/g0501_0600/s0511_game_play_analysis_i)| Easy | LeetCode_Curated_SQL_70, Database, SQL_I_Day_8_Function | 790 | 45.04 +| 0509 |[Fibonacci Number](src/main/kotlin/g0501_0600/s0509_fibonacci_number)| Easy | Dynamic_Programming, Math, Recursion, Memoization, Dynamic_Programming_I_Day_1, Level_1_Day_10_Dynamic_Programming, Udemy_Dynamic_Programming | 139 | 82.72 +| 0508 |[Most Frequent Subtree Sum](src/main/kotlin/g0501_0600/s0508_most_frequent_subtree_sum)| Medium | Hash_Table, Depth_First_Search, Tree, Binary_Tree | 246 | 80.00 +| 0507 |[Perfect Number](src/main/kotlin/g0501_0600/s0507_perfect_number)| Easy | Math | 172 | 81.82 +| 0506 |[Relative Ranks](src/main/kotlin/g0501_0600/s0506_relative_ranks)| Easy | Array, Sorting, Heap_Priority_Queue | 244 | 94.23 +| 0504 |[Base 7](src/main/kotlin/g0501_0600/s0504_base_7)| Easy | Math | 136 | 100.00 +| 0503 |[Next Greater Element II](src/main/kotlin/g0501_0600/s0503_next_greater_element_ii)| Medium | Array, Stack, Monotonic_Stack, Programming_Skills_II_Day_10 | 331 | 92.68 +| 0502 |[IPO](src/main/kotlin/g0501_0600/s0502_ipo)| Hard | Array, Sorting, Greedy, Heap_Priority_Queue | 799 | 54.55 +| 0501 |[Find Mode in Binary Search Tree](src/main/kotlin/g0501_0600/s0501_find_mode_in_binary_search_tree)| Easy | Depth_First_Search, Tree, Binary_Tree, Binary_Search_Tree | 235 | 86.67 +| 0500 |[Keyboard Row](src/main/kotlin/g0401_0500/s0500_keyboard_row)| Easy | Array, String, Hash_Table | 170 | 85.19 +| 0498 |[Diagonal Traverse](src/main/kotlin/g0401_0500/s0498_diagonal_traverse)| Medium | Array, Matrix, Simulation | 430 | 61.54 +| 0497 |[Random Point in Non-overlapping Rectangles](src/main/kotlin/g0401_0500/s0497_random_point_in_non_overlapping_rectangles)| Medium | Math, Binary_Search, Prefix_Sum, Ordered_Set, Randomized, Reservoir_Sampling | 759 | 100.00 +| 0496 |[Next Greater Element I](src/main/kotlin/g0401_0500/s0496_next_greater_element_i)| Easy | Array, Hash_Table, Stack, Monotonic_Stack, Programming_Skills_I_Day_5_Function | 171 | 100.00 +| 0495 |[Teemo Attacking](src/main/kotlin/g0401_0500/s0495_teemo_attacking)| Easy | Array, Simulation | 283 | 100.00 | 0494 |[Target Sum](src/main/kotlin/g0401_0500/s0494_target_sum)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Backtracking | 308 | 89.61 +| 0493 |[Reverse Pairs](src/main/kotlin/g0401_0500/s0493_reverse_pairs)| Hard | Array, Binary_Search, Ordered_Set, Divide_and_Conquer, Segment_Tree, Binary_Indexed_Tree, Merge_Sort | 887 | 66.67 +| 0492 |[Construct the Rectangle](src/main/kotlin/g0401_0500/s0492_construct_the_rectangle)| Easy | Math | 202 | 88.89 +| 0491 |[Non-decreasing Subsequences](src/main/kotlin/g0401_0500/s0491_increasing_subsequences)| Medium | Array, Hash_Table, Bit_Manipulation, Backtracking | 499 | 100.00 +| 0488 |[Zuma Game](src/main/kotlin/g0401_0500/s0488_zuma_game)| Hard | String, Dynamic_Programming, Breadth_First_Search, Memoization | 1727 | 100.00 +| 0486 |[Predict the Winner](src/main/kotlin/g0401_0500/s0486_predict_the_winner)| Medium | Array, Dynamic_Programming, Math, Recursion, Game_Theory | 158 | 84.62 +| 0485 |[Max Consecutive Ones](src/main/kotlin/g0401_0500/s0485_max_consecutive_ones)| Easy | Array | 272 | 88.46 +| 0483 |[Smallest Good Base](src/main/kotlin/g0401_0500/s0483_smallest_good_base)| Hard | Math, Binary_Search | 164 | 100.00 +| 0482 |[License Key Formatting](src/main/kotlin/g0401_0500/s0482_license_key_formatting)| Easy | String | 234 | 87.18 +| 0481 |[Magical String](src/main/kotlin/g0401_0500/s0481_magical_string)| Medium | String, Two_Pointers | 124 | 100.00 | 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 @@ -1661,7 +1691,7 @@ | 0420 |[Strong Password Checker](src/main/kotlin/g0401_0500/s0420_strong_password_checker)| Hard | String, Greedy, Heap_Priority_Queue | 157 | 80.00 | 0419 |[Battleships in a Board](src/main/kotlin/g0401_0500/s0419_battleships_in_a_board)| Medium | Array, Depth_First_Search, Matrix | 273 | 76.92 | 0417 |[Pacific Atlantic Water Flow](src/main/kotlin/g0401_0500/s0417_pacific_atlantic_water_flow)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Graph_Theory_I_Day_4_Matrix_Related_Problems, Level_2_Day_10_Graph/BFS/DFS, Udemy_Graph | 319 | 100.00 -| 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 +| 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 | 204 | 98.82 | 0415 |[Add Strings](src/main/kotlin/g0401_0500/s0415_add_strings)| Easy | String, Math, Simulation, Data_Structure_II_Day_6_String | 296 | 76.00 | 0414 |[Third Maximum Number](src/main/kotlin/g0401_0500/s0414_third_maximum_number)| Easy | Array, Sorting | 317 | 73.00 | 0413 |[Arithmetic Slices](src/main/kotlin/g0401_0500/s0413_arithmetic_slices)| Medium | Array, Dynamic_Programming, Algorithm_II_Day_14_Dynamic_Programming, Dynamic_Programming_I_Day_10 | 156 | 100.00 diff --git a/src/main/kotlin/g0401_0500/s0416_partition_equal_subset_sum/readme.md b/src/main/kotlin/g0401_0500/s0416_partition_equal_subset_sum/readme.md index d33c587b..010beb6a 100644 --- a/src/main/kotlin/g0401_0500/s0416_partition_equal_subset_sum/readme.md +++ b/src/main/kotlin/g0401_0500/s0416_partition_equal_subset_sum/readme.md @@ -33,36 +33,22 @@ Given a **non-empty** array `nums` containing **only positive integers**, find i ```kotlin class Solution { fun canPartition(nums: IntArray): Boolean { - var sum = 0 + var sums = 0 for (num in nums) { - sum += num + sums += num } - if (sum % 2 != 0) { + if (sums % 2 == 1) { return false } - sum /= 2 - // if use primitive boolean array will make default value to false - // we need the default value "null" to help us to do the memo - val dp = arrayOfNulls(sum + 1) - return sumTo(nums, sum, 0, dp) - } - - private fun sumTo(nums: IntArray, sum: Int, index: Int, dp: Array): Boolean { - if (sum == 0) { - return true - } - if (sum < 0) { - return false - } - if (index == nums.size) { - return false - } - if (dp[sum] != null) { - return dp[sum]!! + sums /= 2 + val dp = BooleanArray(sums + 1) + dp[0] = true + for (num in nums) { + for (sum in sums downTo num) { + dp[sum] = dp[sum] || dp[sum - num] + } } - // use the number or not use the number - dp[sum] = sumTo(nums, sum - nums[index], index + 1, dp) || sumTo(nums, sum, index + 1, dp) - return dp[sum]!! + return dp[sums] } } ``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0430_flatten_a_multilevel_doubly_linked_list/readme.md b/src/main/kotlin/g0401_0500/s0430_flatten_a_multilevel_doubly_linked_list/readme.md index fff3091e..c1140756 100644 --- a/src/main/kotlin/g0401_0500/s0430_flatten_a_multilevel_doubly_linked_list/readme.md +++ b/src/main/kotlin/g0401_0500/s0430_flatten_a_multilevel_doubly_linked_list/readme.md @@ -65,8 +65,6 @@ Merging the serialization of each level and removing trailing nulls we obtain: ## Solution ```kotlin -import com_github_leetcode.prev_next.Node - /* * Definition for a Node. * class Node(var `val`: Int) { diff --git a/src/main/kotlin/g0401_0500/s0481_magical_string/readme.md b/src/main/kotlin/g0401_0500/s0481_magical_string/readme.md new file mode 100644 index 00000000..bc5a470d --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0481_magical_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) + +## 481\. Magical String + +Medium + +A magical string `s` consists of only `'1'` and `'2'` and obeys the following rules: + +* The string s is magical because concatenating the number of contiguous occurrences of characters `'1'` and `'2'` generates the string `s` itself. + +The first few elements of `s` is `s = "1221121221221121122……"`. If we group the consecutive `1`'s and `2`'s in `s`, it will be `"1 22 11 2 1 22 1 22 11 2 11 22 ......"` and the occurrences of `1`'s or `2`'s in each group are `"1 2 2 1 1 2 1 2 2 1 2 2 ......"`. You can see that the occurrence sequence is `s` itself. + +Given an integer `n`, return the number of `1`'s in the first `n` number in the magical string `s`. + +**Example 1:** + +**Input:** n = 6 + +**Output:** 3 + +**Explanation:** The first 6 elements of magical string s is "122112" and it contains three 1's, so return 3. + +**Example 2:** + +**Input:** n = 1 + +**Output:** 1 + +**Constraints:** + +* 1 <= n <= 105 + +## Solution + +```kotlin +class Solution { + fun magicalString(n: Int): Int { + val a = IntArray(n + 2) + var fast = 1 + var slow = 1 + var num = 1 + while (fast <= n) { + a[fast++] = num + if (a[slow++] == 2) { + a[fast++] = num + } + num = 3 - num + } + var count = 0 + for (j in 1..n) { + if (a[j] == 1) { + count++ + } + } + return count + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0482_license_key_formatting/readme.md b/src/main/kotlin/g0401_0500/s0482_license_key_formatting/readme.md new file mode 100644 index 00000000..02c43f25 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0482_license_key_formatting/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) + +## 482\. License Key Formatting + +Easy + +You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. + +We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first group, which could be shorter than `k` but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. + +Return _the reformatted license key_. + +**Example 1:** + +**Input:** s = "5F3Z-2e-9-w", k = 4 + +**Output:** "5F3Z-2E9W" + +**Explanation:** The string s has been split into two parts, each part has 4 characters. Note that the two extra dashes are not needed and can be removed. + +**Example 2:** + +**Input:** s = "2-5g-3-J", k = 2 + +**Output:** "2-5G-3J" + +**Explanation:** The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above. + +**Constraints:** + +* 1 <= s.length <= 105 +* `s` consists of English letters, digits, and dashes `'-'`. +* 1 <= k <= 104 + +## Solution + +```kotlin +class Solution { + fun licenseKeyFormatting(s: String, k: Int): String { + val sb = StringBuilder() + var cnt = 0 + var occ = 0 + for (c in s.toCharArray()) { + if (c == '-') { + continue + } + cnt++ + } + var l = cnt % k + for (c in s.toCharArray()) { + if (c == '-') { + continue + } + if (occ == k) { + occ = 0 + sb.append('-') + } else if (occ == l && l != 0) { + l = 0 + occ = 0 + sb.append('-') + } + sb.append(c.uppercaseChar()) + occ++ + } + return sb.toString() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0483_smallest_good_base/readme.md b/src/main/kotlin/g0401_0500/s0483_smallest_good_base/readme.md new file mode 100644 index 00000000..3811f97f --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0483_smallest_good_base/readme.md @@ -0,0 +1,83 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 483\. Smallest Good Base + +Hard + +Given an integer `n` represented as a string, return _the smallest **good base** of_ `n`. + +We call `k >= 2` a **good base** of `n`, if all digits of `n` base `k` are `1`'s. + +**Example 1:** + +**Input:** n = "13" + +**Output:** "3" + +**Explanation:** 13 base 3 is 111. + +**Example 2:** + +**Input:** n = "4681" + +**Output:** "8" + +**Explanation:** 4681 base 8 is 11111. + +**Example 3:** + +**Input:** n = "1000000000000000000" + +**Output:** "999999999999999999" + +**Explanation:** 1000000000000000000 base 999999999999999999 is 11. + +**Constraints:** + +* `n` is an integer in the range [3, 1018]. +* `n` does not contain any leading zeros. + +## Solution + +```kotlin +class Solution { + fun smallestGoodBase(n: String): String { + return sol1(n) + } + + private fun sol1(n: String): String { + val x = n.toLong() + val ans: MutableList = ArrayList() + ans.add(x - 1) + val y = x - 1 + for (i in 2..62) { + val dm = Math.pow(y.toDouble(), 1.0 / i) + val dml = dm.toLong() + var j = 0 + while (j > -3 && dml + j > 1) { + val d = dml + j + if (y % d == 0L) { + val poly = poly(d, i) + if (poly == x) { + ans.add(d) + } + } + j-- + } + } + val end = ans[ans.size - 1] + return end.toString() + } + + private fun poly(b: Long, n: Int): Long { + var ans: Long = 1 + var m: Long = 1 + for (i in 0 until n) { + m *= b + ans += m + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0485_max_consecutive_ones/readme.md b/src/main/kotlin/g0401_0500/s0485_max_consecutive_ones/readme.md new file mode 100644 index 00000000..af54dabc --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0485_max_consecutive_ones/readme.md @@ -0,0 +1,48 @@ +[![](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) + +## 485\. Max Consecutive Ones + +Easy + +Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. + +**Example 1:** + +**Input:** nums = [1,1,0,1,1,1] + +**Output:** 3 + +**Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. + +**Example 2:** + +**Input:** nums = [1,0,1,1,0,1] + +**Output:** 2 + +**Constraints:** + +* 1 <= nums.length <= 105 +* `nums[i]` is either `0` or `1`. + +## Solution + +```kotlin +class Solution { + fun findMaxConsecutiveOnes(nums: IntArray): Int { + var maxLen = 0 + var i = 0 + while (i < nums.size) { + var currentLen = 0 + while (i < nums.size && nums[i] == 1) { + i++ + currentLen++ + } + maxLen = Math.max(maxLen, currentLen) + i++ + } + return maxLen + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0486_predict_the_winner/readme.md b/src/main/kotlin/g0401_0500/s0486_predict_the_winner/readme.md new file mode 100644 index 00000000..17855f7d --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0486_predict_the_winner/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) + +## 486\. Predict the Winner + +Medium + +You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2. + +Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` or `nums[nums.length - 1]`) which reduces the size of the array by `1`. The player adds the chosen number to their score. The game ends when there are no more elements in the array. + +Return `true` if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return `true`. You may assume that both players are playing optimally. + +**Example 1:** + +**Input:** nums = [1,5,2] + +**Output:** false + +**Explanation:** Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return false. + +**Example 2:** + +**Input:** nums = [1,5,233,7] + +**Output:** true + +**Explanation:** Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233. Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win. + +**Constraints:** + +* `1 <= nums.length <= 20` +* 0 <= nums[i] <= 107 + +## Solution + +```kotlin +class Solution { + fun predictTheWinner(nums: IntArray): Boolean { + val n = nums.size + val dp = Array(n) { IntArray(n) } + for (i in 0 until n) { + dp[i][i] = nums[i] + } + for (len in 1 until n) { + for (i in 0 until n - len) { + val j = i + len + dp[i][j] = Math.max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]) + } + } + return dp[0][n - 1] >= 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0488_zuma_game/readme.md b/src/main/kotlin/g0401_0500/s0488_zuma_game/readme.md new file mode 100644 index 00000000..4db742cc --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0488_zuma_game/readme.md @@ -0,0 +1,129 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 488\. Zuma Game + +Hard + +You are playing a variation of the game Zuma. + +In this variation of Zuma, there is a **single row** of colored balls on a board, where each ball can be colored red `'R'`, yellow `'Y'`, blue `'B'`, green `'G'`, or white `'W'`. You also have several colored balls in your hand. + +Your goal is to **clear all** of the balls from the board. On each turn: + +* Pick **any** ball from your hand and insert it in between two balls in the row or on either end of the row. +* If there is a group of **three or more consecutive balls** of the **same color**, remove the group of balls from the board. + * If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left. +* If there are no more balls on the board, then you win the game. +* Repeat this process until you either win or do not have any more balls in your hand. + +Given a string `board`, representing the row of balls on the board, and a string `hand`, representing the balls in your hand, return _the **minimum** number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return_ `-1`. + +**Example 1:** + +**Input:** board = "WRRBBW", hand = "RB" + +**Output:** -1 + +**Explanation:** It is impossible to clear all the balls. The best you can do is: - Insert 'R' so the board becomes WRRRBBW. WRRRBBW -> WBBW. - Insert 'B' so the board becomes WBBBW. WBBBW -> WW. There are still balls remaining on the board, and you are out of balls to insert. + +**Example 2:** + +**Input:** board = "WWRRBBWW", hand = "WRBRW" + +**Output:** 2 + +**Explanation:** To make the board empty: - Insert 'R' so the board becomes WWRRRBBWW. WWRRRBBWW -> WWBBWW. - Insert 'B' so the board becomes WWBBBWW. WWBBBWW -> WWWW -> empty. 2 balls from your hand were needed to clear the board. + +**Example 3:** + +**Input:** board = "G", hand = "GGGGG" + +**Output:** 2 + +**Explanation:** To make the board empty: - Insert 'G' so the board becomes GG. - Insert 'G' so the board becomes GGG. GGG -> empty. 2 balls from your hand were needed to clear the board. + +**Constraints:** + +* `1 <= board.length <= 16` +* `1 <= hand.length <= 5` +* `board` and `hand` consist of the characters `'R'`, `'Y'`, `'B'`, `'G'`, and `'W'`. +* The initial row of balls on the board will **not** have any groups of three or more consecutive balls of the same color. + +## Solution + +```kotlin +class Solution { + fun findMinStep(board: String, hand: String): Int { + return dfs(board, hand) + } + + private fun dfs(board: String, hand: String): Int { + return findMinStepDp(board, hand, HashMap()) + } + + private fun findMinStepDp(board: String, hand: String, dp: MutableMap?>): Int { + if (board.length == 0) { + return 0 + } + if (hand.length == 0) { + return -1 + } + if (dp[board] != null && dp[board]!![hand] != null) { + return dp[board]!![hand]!! + } + var min = -1 + for (i in 0..board.length) { + for (j in 0 until hand.length) { + if ((j == 0 || hand[j] != hand[j - 1]) && + (i == 0 || board[i - 1] != hand[j]) && + ( + i < board.length && board[i] == hand[j] || i > 0 && + i < board.length && board[i - 1] == board[i] && board[i] != hand[j] + ) + ) { + val newS = StringBuilder(board) + newS.insert(i, hand[j]) + val sR = findMinStepDp( + removeRepeated(newS.toString()), + hand.substring(0, j) + hand.substring(j + 1, hand.length), + dp + ) + if (sR != -1) { + min = if (min == -1) sR + 1 else Integer.min(min, sR + 1) + } + } + } + } + dp.putIfAbsent(board, HashMap()) + dp[board]!![hand] = min + return min + } + + private fun removeRepeated(original: String): String { + var count = 1 + var i = 1 + while (i < original.length) { + if (original[i] == original[i - 1]) { + count++ + i++ + } else { + if (count >= 3) { + return removeRepeated( + original.substring(0, i - count) + + original.substring(i, original.length) + ) + } else { + count = 1 + i++ + } + } + } + return if (count >= 3) { + removeRepeated(original.substring(0, original.length - count)) + } else { + original + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0491_increasing_subsequences/readme.md b/src/main/kotlin/g0401_0500/s0491_increasing_subsequences/readme.md new file mode 100644 index 00000000..2f22f2af --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0491_increasing_subsequences/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) + +## 491\. Non-decreasing Subsequences + +Medium + +Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. + +**Example 1:** + +**Input:** nums = [4,6,7,7] + +**Output:** [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]] + +**Example 2:** + +**Input:** nums = [4,4,3,2,1] + +**Output:** [[4,4]] + +**Constraints:** + +* `1 <= nums.length <= 15` +* `-100 <= nums[i] <= 100` + +## Solution + +```kotlin +class Solution { + fun findSubsequences(nums: IntArray?): List> { + if (nums == null || nums.size == 1) { + return ArrayList() + } + val answer: MutableSet> = HashSet() + val list: MutableList = ArrayList() + return ArrayList(backtracking(nums, 0, list, answer)) + } + + private fun backtracking( + nums: IntArray, + start: Int, + currList: MutableList, + answer: MutableSet> + ): Set> { + if (currList.size >= 2) { + answer.add(ArrayList(currList)) + } + for (i in start until nums.size) { + if (currList.isEmpty() || currList[currList.size - 1] <= nums[i]) { + currList.add(nums[i]) + backtracking(nums, i + 1, currList, answer) + currList.removeAt(currList.size - 1) + } + } + return answer + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0492_construct_the_rectangle/readme.md b/src/main/kotlin/g0401_0500/s0492_construct_the_rectangle/readme.md new file mode 100644 index 00000000..b1d3c2b7 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0492_construct_the_rectangle/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) + +## 492\. Construct the Rectangle + +Easy + +A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: + +1. The area of the rectangular web page you designed must equal to the given target area. +2. The width `W` should not be larger than the length `L`, which means `L >= W`. +3. The difference between length `L` and width `W` should be as small as possible. + +Return _an array `[L, W]` where `L` and `W` are the length and width of the web page you designed in sequence._ + +**Example 1:** + +**Input:** area = 4 + +**Output:** [2,2] + +**Explanation:** The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2. + +**Example 2:** + +**Input:** area = 37 + +**Output:** [37,1] + +**Example 3:** + +**Input:** area = 122122 + +**Output:** [427,286] + +**Constraints:** + +* 1 <= area <= 107 + +## Solution + +```kotlin +class Solution { + /* + Algorithm: + - start with an index i from the square root all the way to 1; + - if at any time, area % i == 0 (so i is a divisor of area), then it's the closest solution. + */ + fun constructRectangle(area: Int): IntArray { + var low = Math.sqrt(area.toDouble()).toInt() + while (low > 0) { + if (area % low == 0) { + return intArrayOf(area / low, low) + } + low-- + } + return intArrayOf(0, 0) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0493_reverse_pairs/readme.md b/src/main/kotlin/g0401_0500/s0493_reverse_pairs/readme.md new file mode 100644 index 00000000..d41e2799 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0493_reverse_pairs/readme.md @@ -0,0 +1,75 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 493\. Reverse Pairs + +Hard + +Given an integer array `nums`, return _the number of **reverse pairs** in the array_. + +A **reverse pair** is a pair `(i, j)` where: + +* `0 <= i < j < nums.length` and +* `nums[i] > 2 * nums[j]`. + +**Example 1:** + +**Input:** nums = [1,3,2,3,1] + +**Output:** 2 + +**Explanation:** The reverse pairs are: + +(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 \* 1 + +(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 \* 1 + +**Example 2:** + +**Input:** nums = [2,4,3,5,1] + +**Output:** 3 + +**Explanation:** The reverse pairs are: + +(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 \* 1 + +(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 \* 1 + +(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 \* 1 + +**Constraints:** + +* 1 <= nums.length <= 5 * 104 +* -231 <= nums[i] <= 231 - 1 + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun reversePairs(nums: IntArray): Int { + return mergeSort(nums, 0, nums.size - 1) + } + + private fun mergeSort(nums: IntArray, start: Int, end: Int): Int { + if (start >= end) { + return 0 + } + val mid = start + (end - start) / 2 + var cnt = mergeSort(nums, start, mid) + mergeSort(nums, mid + 1, end) + var j = mid + 1 + for (i in start..mid) { + // it has to be 2.0 instead of 2, otherwise it's going to stack overflow, i.e. test3 is + // going to fail + while (j <= end && nums[i] > nums[j] * 2.0) { + j++ + } + cnt += j - (mid + 1) + } + Arrays.sort(nums, start, end + 1) + return cnt + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0495_teemo_attacking/readme.md b/src/main/kotlin/g0401_0500/s0495_teemo_attacking/readme.md new file mode 100644 index 00000000..b2040fe3 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0495_teemo_attacking/readme.md @@ -0,0 +1,72 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 495\. Teemo Attacking + +Easy + +Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effect ends, the timer for it is **reset**, and the poison effect will end `duration` seconds after the new attack. + +You are given a **non-decreasing** integer array `timeSeries`, where `timeSeries[i]` denotes that Teemo attacks Ashe at second `timeSeries[i]`, and an integer `duration`. + +Return _the **total** number of seconds that Ashe is poisoned_. + +**Example 1:** + +**Input:** timeSeries = [1,4], duration = 2 + +**Output:** 4 + +**Explanation:** Teemo's attacks on Ashe go as follows: + +- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. + +- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5. + +- Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total. + +**Example 2:** + +**Input:** timeSeries = [1,2], duration = 2 + +**Output:** 3 + +**Explanation:** Teemo's attacks on Ashe go as follows: + +- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. + +- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3. + +- Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total. + +**Constraints:** + +* 1 <= timeSeries.length <= 104 +* 0 <= timeSeries[i], duration <= 107 +* `timeSeries` is sorted in **non-decreasing** order. + +## Solution + +```kotlin +class Solution { + fun findPoisonedDuration(timeSeries: IntArray, duration: Int): Int { + if (duration == 0) { + return 0 + } + var start = timeSeries[0] + var end = timeSeries[0] + duration - 1 + var poisonDuration = end - start + 1 + for (i in 1 until timeSeries.size) { + if (timeSeries[i] <= end) { + poisonDuration += duration - (end - timeSeries[i] + 1) + end += duration - (end - timeSeries[i] + 1) + } else { + start = timeSeries[i] + end = timeSeries[i] + duration - 1 + poisonDuration += end - start + 1 + } + } + return poisonDuration + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0496_next_greater_element_i/readme.md b/src/main/kotlin/g0401_0500/s0496_next_greater_element_i/readme.md new file mode 100644 index 00000000..395bb297 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0496_next_greater_element_i/readme.md @@ -0,0 +1,83 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 496\. Next Greater Element I + +Easy + +The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array. + +You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`. + +For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the **next greater element** of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`. + +Return _an array_ `ans` _of length_ `nums1.length` _such that_ `ans[i]` _is the **next greater element** as described above._ + +**Example 1:** + +**Input:** nums1 = [4,1,2], nums2 = [1,3,4,2] + +**Output:** [-1,3,-1] + +**Explanation:** The next greater element for each value of nums1 is as follows: + +- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. + +- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3. + +- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. + +**Example 2:** + +**Input:** nums1 = [2,4], nums2 = [1,2,3,4] + +**Output:** [3,-1] + +**Explanation:** The next greater element for each value of nums1 is as follows: + +- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3. + +- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1. + +**Constraints:** + +* `1 <= nums1.length <= nums2.length <= 1000` +* 0 <= nums1[i], nums2[i] <= 104 +* All integers in `nums1` and `nums2` are **unique**. +* All the integers of `nums1` also appear in `nums2`. + +**Follow up:** Could you find an `O(nums1.length + nums2.length)` solution? + +## Solution + +```kotlin +class Solution { + fun nextGreaterElement(nums1: IntArray, nums2: IntArray): IntArray { + val indexMap: MutableMap = HashMap() + for (i in nums2.indices) { + indexMap[nums2[i]] = i + } + for (i in nums1.indices) { + val num = nums1[i] + var index = indexMap[num]!! + if (index == nums2.size - 1) { + nums1[i] = -1 + } else { + var found = false + while (index < nums2.size) { + if (nums2[index] > num) { + nums1[i] = nums2[index] + found = true + break + } + index++ + } + if (!found) { + nums1[i] = -1 + } + } + } + return nums1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0497_random_point_in_non_overlapping_rectangles/readme.md b/src/main/kotlin/g0401_0500/s0497_random_point_in_non_overlapping_rectangles/readme.md new file mode 100644 index 00000000..808ca842 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0497_random_point_in_non_overlapping_rectangles/readme.md @@ -0,0 +1,106 @@ +[![](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) + +## 497\. Random Point in Non-overlapping Rectangles + +Medium + +You are given an array of non-overlapping axis-aligned rectangles `rects` where rects[i] = [ai, bi, xi, yi] indicates that (ai, bi) is the bottom-left corner point of the ith rectangle and (xi, yi) is the top-right corner point of the ith rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle. + +Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned. + +**Note** that an integer point is a point that has integer coordinates. + +Implement the `Solution` class: + +* `Solution(int[][] rects)` Initializes the object with the given rectangles `rects`. +* `int[] pick()` Returns a random integer point `[u, v]` inside the space covered by one of the given rectangles. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/07/24/lc-pickrandomrec.jpg) + +**Input** ["Solution", "pick", "pick", "pick", "pick", "pick"] [[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []] + +**Output:** [null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]] + +**Explanation:** + + Solution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]); + solution.pick(); // return [1, -2] + solution.pick(); // return [1, -1] + solution.pick(); // return [-1, -2] + solution.pick(); // return [-2, -2] + solution.pick(); // return [0, 0] + +**Constraints:** + +* `1 <= rects.length <= 100` +* `rects[i].length == 4` +* -109 <= ai < xi <= 109 +* -109 <= bi < yi <= 109 +* xi - ai <= 2000 +* yi - bi <= 2000 +* All the rectangles do not overlap. +* At most 104 calls will be made to `pick`. + +## Solution + +```kotlin +import java.util.Random + +@Suppress("kotlin:S2245") +class Solution(rects: Array) { + private val weights: IntArray + private val rects: Array + private val random: Random + + init { + weights = IntArray(rects.size) + this.rects = rects + random = Random() + for (i in rects.indices) { + val rect = rects[i] + val count = (1 + rect[2] - rect[0]) * (1 + rect[3] - rect[1]) + weights[i] = (if (i == 0) 0 else weights[i - 1]) + count + } + } + + fun pick(): IntArray { + val picked: Int = 1 + random.nextInt(weights[weights.size - 1]) + val idx = findGreaterOrEqual(picked) + return getRandomPoint(idx) + } + + private fun findGreaterOrEqual(target: Int): Int { + var left = 0 + var right = weights.size - 1 + while (left + 1 < right) { + val mid = left + (right - left) / 2 + if (weights[mid] >= target) { + right = mid + } else { + left = mid + 1 + } + } + return if (weights[left] >= target) left else right + } + + private fun getRandomPoint(idx: Int): IntArray { + val r = rects[idx] + val left = r[0] + val right = r[2] + val bot = r[1] + val top = r[3] + return intArrayOf( + left + random.nextInt(right - left + 1), bot + random.nextInt(top - bot + 1) + ) + } +} + +/* + * Your Solution object will be instantiated and called as such: + * var obj = Solution(rects) + * var param_1 = obj.pick() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0498_diagonal_traverse/readme.md b/src/main/kotlin/g0401_0500/s0498_diagonal_traverse/readme.md new file mode 100644 index 00000000..277b2a55 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0498_diagonal_traverse/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) + +## 498\. Diagonal Traverse + +Medium + +Given an `m x n` matrix `mat`, return _an array of all the elements of the array in a diagonal order_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/10/diag1-grid.jpg) + +**Input:** mat = \[\[1,2,3],[4,5,6],[7,8,9]] + +**Output:** [1,2,4,7,5,3,6,8,9] + +**Example 2:** + +**Input:** mat = \[\[1,2],[3,4]] + +**Output:** [1,2,3,4] + +**Constraints:** + +* `m == mat.length` +* `n == mat[i].length` +* 1 <= m, n <= 104 +* 1 <= m * n <= 104 +* -105 <= mat[i][j] <= 105 + +## Solution + +```kotlin +class Solution { + fun findDiagonalOrder(mat: Array): IntArray { + val m = mat.size + val n = mat[0].size + val output = IntArray(m * n) + var idx = 0 + for (diag in 0..m + n - 2) { + if (diag % 2 == 0) { + for (k in Math.max(0, diag - m + 1)..Math.min(diag, n - 1)) { + output[idx++] = mat[diag - k][k] + } + } else { + for (k in Math.max(0, diag - n + 1)..Math.min(diag, m - 1)) { + output[idx++] = mat[k][diag - k] + } + } + } + return output + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0401_0500/s0500_keyboard_row/readme.md b/src/main/kotlin/g0401_0500/s0500_keyboard_row/readme.md new file mode 100644 index 00000000..a4f92a68 --- /dev/null +++ b/src/main/kotlin/g0401_0500/s0500_keyboard_row/readme.md @@ -0,0 +1,70 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 500\. Keyboard Row + +Easy + +Given an array of strings `words`, return _the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below_. + +In the **American keyboard**: + +* the first row consists of the characters `"qwertyuiop"`, +* the second row consists of the characters `"asdfghjkl"`, and +* the third row consists of the characters `"zxcvbnm"`. + +![](https://assets.leetcode.com/uploads/2018/10/12/keyboard.png) + +**Example 1:** + +**Input:** words = ["Hello","Alaska","Dad","Peace"] + +**Output:** ["Alaska","Dad"] + +**Example 2:** + +**Input:** words = ["omk"] + +**Output:** [] + +**Example 3:** + +**Input:** words = ["adsdf","sfd"] + +**Output:** ["adsdf","sfd"] + +**Constraints:** + +* `1 <= words.length <= 20` +* `1 <= words[i].length <= 100` +* `words[i]` consists of English letters (both lowercase and uppercase). + +## Solution + +```kotlin +import java.util.Locale + +class Solution { + private fun check(str: String, word: String): Boolean { + for (ch in word.toCharArray()) { + if (str.indexOf(ch) < 0) { + return false + } + } + return true + } + + fun findWords(words: Array): Array { + val arr: MutableList = ArrayList() + for (word in words) { + val w = word.lowercase(Locale.getDefault()) + if (check("qwertyuiop", w) || check("asdfghjkl", w) || check("zxcvbnm", w)) { + arr.add(word) + } + } + var ans: Array + ans = arr.toTypedArray() + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0501_find_mode_in_binary_search_tree/readme.md b/src/main/kotlin/g0501_0600/s0501_find_mode_in_binary_search_tree/readme.md new file mode 100644 index 00000000..7b4552c6 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0501_find_mode_in_binary_search_tree/readme.md @@ -0,0 +1,93 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 501\. Find Mode in Binary Search Tree + +Easy + +Given the `root` of a binary search tree (BST) with duplicates, return _all the [mode(s)](https://en.wikipedia.org/wiki/Mode_(statistics)) (i.e., the most frequently occurred element) in it_. + +If the tree has more than one mode, return them in **any order**. + +Assume a BST is defined as follows: + +* The left subtree of a node contains only nodes with keys **less than or equal to** the node's key. +* The right subtree of a node contains only nodes with keys **greater than or equal to** the node's key. +* Both the left and right subtrees must also be binary search trees. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/11/mode-tree.jpg) + +**Input:** root = [1,null,2,2] + +**Output:** [2] + +**Example 2:** + +**Input:** root = [0] + +**Output:** [0] + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 104]. +* -105 <= Node.val <= 105 + +**Follow up:** Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count). + +## 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 findMode(root: TreeNode?): IntArray { + var maxOccurTimes = 0 + var prevValue: Int? = null + var prevOccurTime = 1 + val ans = hashSetOf() + + fun updateGlobal(currValue: Int) { + if (currValue == prevValue) { + prevOccurTime++ + when { + prevOccurTime == maxOccurTimes -> ans.add(currValue) + prevOccurTime > maxOccurTimes -> { + maxOccurTimes = prevOccurTime + ans.clear() + ans.add(currValue) + } + } + } else { + prevOccurTime = 1 + prevValue = currValue + if (maxOccurTimes <= 1) { + ans.add(currValue) + } + } + } + + fun processInOrder(node: TreeNode? = root) { + if (node != null) { + node.left?.let { processInOrder(it) } + updateGlobal(node.`val`) + node.right?.let { processInOrder(it) } + } + } + processInOrder() + + return ans.toIntArray() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0502_ipo/readme.md b/src/main/kotlin/g0501_0600/s0502_ipo/readme.md new file mode 100644 index 00000000..892b788c --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0502_ipo/readme.md @@ -0,0 +1,87 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 502\. IPO + +Hard + +Suppose LeetCode will start its **IPO** soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the **IPO**. Since it has limited resources, it can only finish at most `k` distinct projects before the **IPO**. Help LeetCode design the best way to maximize its total capital after finishing at most `k` distinct projects. + +You are given `n` projects where the ith project has a pure profit `profits[i]` and a minimum capital of `capital[i]` is needed to start it. + +Initially, you have `w` capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. + +Pick a list of **at most** `k` distinct projects from given projects to **maximize your final capital**, and return _the final maximized capital_. + +The answer is guaranteed to fit in a 32-bit signed integer. + +**Example 1:** + +**Input:** k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] + +**Output:** 4 + +**Explanation:** Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. + +**Example 2:** + +**Input:** k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] + +**Output:** 6 + +**Constraints:** + +* 1 <= k <= 105 +* 0 <= w <= 109 +* `n == profits.length` +* `n == capital.length` +* 1 <= n <= 105 +* 0 <= profits[i] <= 104 +* 0 <= capital[i] <= 109 + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + inner class Data(var profit: Int, var capital: Int) + + // max heap for profit + var profitMaxHeap = PriorityQueue { d1, d2 -> + -1 * Integer.compare( + d1.profit, + d2.profit + ) + } + + // min heap for capital + var capitalMinHeap = PriorityQueue { d1, d2 -> Integer.compare(d1.capital, d2.capital) } + fun findMaximizedCapital(k: Int, w: Int, profits: IntArray, capital: IntArray): Int { + init(profits, capital) + var maxCapital = w + var currentCapital = w + for (i in 0 until k) { + + // first fetch all tasks you can do with current capital and add those in profit max heap + while (!capitalMinHeap.isEmpty() && currentCapital >= capitalMinHeap.peek().capital) { + profitMaxHeap.add(capitalMinHeap.poll()) + } + + // if profit max heap is empty we can do nothing so break + if (profitMaxHeap.isEmpty()) break + + // add profit to current capital and update maxCapital + currentCapital += profitMaxHeap.poll().profit + maxCapital = Math.max(maxCapital, currentCapital) + } + return maxCapital + } + + private fun init(profits: IntArray, capital: IntArray) { + for (i in profits.indices) { + capitalMinHeap.add(Data(profits[i], capital[i])) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0503_next_greater_element_ii/readme.md b/src/main/kotlin/g0501_0600/s0503_next_greater_element_ii/readme.md new file mode 100644 index 00000000..648e6190 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0503_next_greater_element_ii/readme.md @@ -0,0 +1,49 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 503\. Next Greater Element II + +Medium + +Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`. + +The **next greater number** of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return `-1` for this number. + +**Example 1:** + +**Input:** nums = [1,2,1] + +**Output:** [2,-1,2] Explanation: The first 1's next greater number is 2; The number 2 can't find next greater number. The second 1's next greater number needs to search circularly, which is also 2. + +**Example 2:** + +**Input:** nums = [1,2,3,4,3] + +**Output:** [2,3,4,-1,4] + +**Constraints:** + +* 1 <= nums.length <= 104 +* -109 <= nums[i] <= 109 + +## Solution + +```kotlin +import java.util.ArrayDeque +import java.util.Deque + +class Solution { + fun nextGreaterElements(nums: IntArray): IntArray { + val result = IntArray(nums.size) + val stack: Deque = ArrayDeque() + for (i in nums.size * 2 - 1 downTo 0) { + while (!stack.isEmpty() && nums[stack.peek()] <= nums[i % nums.size]) { + stack.pop() + } + result[i % nums.size] = if (stack.isEmpty()) -1 else nums[stack.peek()] + stack.push(i % nums.size) + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0504_base_7/readme.md b/src/main/kotlin/g0501_0600/s0504_base_7/readme.md new file mode 100644 index 00000000..8f92d6ef --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0504_base_7/readme.md @@ -0,0 +1,34 @@ +[![](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) + +## 504\. Base 7 + +Easy + +Given an integer `num`, return _a string of its **base 7** representation_. + +**Example 1:** + +**Input:** num = 100 + +**Output:** "202" + +**Example 2:** + +**Input:** num = -7 + +**Output:** "-10" + +**Constraints:** + +* -107 <= num <= 107 + +## Solution + +```kotlin +class Solution { + fun convertToBase7(num: Int): String { + return Integer.toString(num, 7) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0506_relative_ranks/readme.md b/src/main/kotlin/g0501_0600/s0506_relative_ranks/readme.md new file mode 100644 index 00000000..f7c1bccb --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0506_relative_ranks/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) + +## 506\. Relative Ranks + +Easy + +You are given an integer array `score` of size `n`, where `score[i]` is the score of the ith athlete in a competition. All the scores are guaranteed to be **unique**. + +The athletes are **placed** based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank: + +* The 1st place athlete's rank is `"Gold Medal"`. +* The 2nd place athlete's rank is `"Silver Medal"`. +* The 3rd place athlete's rank is `"Bronze Medal"`. +* For the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is `"x"`). + +Return an array `answer` of size `n` where `answer[i]` is the **rank** of the ith athlete. + +**Example 1:** + +**Input:** score = [5,4,3,2,1] + +**Output:** ["Gold Medal","Silver Medal","Bronze Medal","4","5"] + +**Explanation:** The placements are [1st, 2nd, 3rd, 4th, 5th]. + +**Example 2:** + +**Input:** score = [10,3,8,9,4] + +**Output:** ["Gold Medal","5","Bronze Medal","Silver Medal","4"] + +**Explanation:** The placements are [1st, 5th, 3rd, 2nd, 4th]. + +**Constraints:** + +* `n == score.length` +* 1 <= n <= 104 +* 0 <= score[i] <= 106 +* All the values in `score` are **unique**. + +## Solution + +```kotlin +class Solution { + fun findRelativeRanks(score: IntArray): Array { + fun mapPlace(score: Int, sortedScores: IntArray): String { + val place = sortedScores.lastIndex - sortedScores.binarySearch(score) + return when { + place > 2 -> "${place + 1}" + place == 0 -> "Gold Medal" + place == 1 -> "Silver Medal" + place == 2 -> "Bronze Medal" + else -> throw NoWhenBranchMatchedException() + } + } + + val sortedScores = score.clone().apply { sort() } + return score.map { mapPlace(it, sortedScores) }.toTypedArray() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0507_perfect_number/readme.md b/src/main/kotlin/g0501_0600/s0507_perfect_number/readme.md new file mode 100644 index 00000000..6e08bfbf --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0507_perfect_number/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) + +## 507\. Perfect Number + +Easy + +A [**perfect number**](https://en.wikipedia.org/wiki/Perfect_number) is a **positive integer** that is equal to the sum of its **positive divisors**, excluding the number itself. A **divisor** of an integer `x` is an integer that can divide `x` evenly. + +Given an integer `n`, return `true` _if_ `n` _is a perfect number, otherwise return_ `false`. + +**Example 1:** + +**Input:** num = 28 + +**Output:** true + +**Explanation:** 28 = 1 + 2 + 4 + 7 + 14 1, 2, 4, 7, and 14 are all divisors of 28. + +**Example 2:** + +**Input:** num = 7 + +**Output:** false + +**Constraints:** + +* 1 <= num <= 108 + +## Solution + +```kotlin +class Solution { + fun checkPerfectNumber(num: Int): Boolean { + var s = 1 + for (sq in Math.sqrt(num.toDouble()).toInt() downTo 2) { + if (num % sq == 0) { + s += sq + num / sq + } + } + return num != 1 && s == num + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0508_most_frequent_subtree_sum/readme.md b/src/main/kotlin/g0501_0600/s0508_most_frequent_subtree_sum/readme.md new file mode 100644 index 00000000..83b55b0b --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0508_most_frequent_subtree_sum/readme.md @@ -0,0 +1,70 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 508\. Most Frequent Subtree Sum + +Medium + +Given the `root` of a binary tree, return the most frequent **subtree sum**. If there is a tie, return all the values with the highest frequency in any order. + +The **subtree sum** of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/04/24/freq1-tree.jpg) + +**Input:** root = [5,2,-3] + +**Output:** [2,-3,4] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/04/24/freq2-tree.jpg) + +**Input:** root = [5,2,-5] + +**Output:** [2] + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 104]. +* -105 <= Node.val <= 105 + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private val cache = mutableMapOf() + + fun findFrequentTreeSum(root: TreeNode?): IntArray { + treeSum(root) + if (cache.isEmpty()) { + return IntArray(0) + } + val max = cache.maxBy { it.value }.value + return cache.filter { it.value == max }.map { it.key }.toIntArray() + } + + private fun treeSum(node: TreeNode?): Int { + if (node == null) { + return 0 + } else { + val sum = node.`val` + treeSum(node.left) + treeSum(node.right) + cache[sum] = cache.getOrDefault(sum, 0) + 1 + return sum + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0509_fibonacci_number/readme.md b/src/main/kotlin/g0501_0600/s0509_fibonacci_number/readme.md new file mode 100644 index 00000000..b0bb26ac --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0509_fibonacci_number/readme.md @@ -0,0 +1,61 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 509\. Fibonacci Number + +Easy + +The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is, + +F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. + +Given `n`, calculate `F(n)`. + +**Example 1:** + +**Input:** n = 2 + +**Output:** 1 + +**Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1. + +**Example 2:** + +**Input:** n = 3 + +**Output:** 2 + +**Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2. + +**Example 3:** + +**Input:** n = 4 + +**Output:** 3 + +**Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3. + +**Constraints:** + +* `0 <= n <= 30` + +## Solution + +```kotlin +class Solution { + private val memo = IntArray(31) + fun fib(n: Int): Int { + if (n == 0) { + return 0 + } + if (n == 1) { + return 1 + } + if (memo[n] != 0) { + return memo[n] + } + memo[n] = fib(n - 1) + fib(n - 2) + return memo[n] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0511_game_play_analysis_i/readme.md b/src/main/kotlin/g0501_0600/s0511_game_play_analysis_i/readme.md new file mode 100644 index 00000000..0ba61158 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0511_game_play_analysis_i/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) + +## 511\. Game Play Analysis I + +Easy + +SQL Schema + +Table: `Activity` + + +--------------+---------+ + | Column Name | Type | + +--------------+---------+ + | player_id | int | + | device_id | int | + | event_date | date | + | games_played | int | + +--------------+---------+ + (player_id, event_date) is the primary key of this table. + This table shows the activity of players of some games. + Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device. + +Write an SQL query to report the **first login date** for each player. + +Return the result table in **any order**. + +The query result format is in the following example. + +**Example 1:** + +**Input:** + + Activity table: + +-----------+-----------+------------+--------------+ + | player_id | device_id | event_date | games_played | + +-----------+-----------+------------+--------------+ + | 1 | 2 | 2016-03-01 | 5 | + | 1 | 2 | 2016-05-02 | 6 | + | 2 | 3 | 2017-06-25 | 1 | + | 3 | 1 | 2016-03-02 | 0 | + | 3 | 4 | 2018-07-03 | 5 | + +-----------+-----------+------------+--------------+ + +**Output:** + + +-----------+-------------+ + | player_id | first_login | + +-----------+-------------+ + | 1 | 2016-03-01 | + | 2 | 2017-06-25 | + | 3 | 2016-03-02 | + +-----------+-------------+ + +## Solution + +```sql +# Write your MySQL query statement below +select distinct(player_id), min(event_date) as first_login +from activity +group by player_id +``` \ No newline at end of file diff --git a/src/main/kotlin/g0501_0600/s0513_find_bottom_left_tree_value/readme.md b/src/main/kotlin/g0501_0600/s0513_find_bottom_left_tree_value/readme.md new file mode 100644 index 00000000..25201200 --- /dev/null +++ b/src/main/kotlin/g0501_0600/s0513_find_bottom_left_tree_value/readme.md @@ -0,0 +1,82 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 513\. Find Bottom Left Tree Value + +Medium + +Given the `root` of a binary tree, return the leftmost value in the last row of the tree. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/12/14/tree1.jpg) + +**Input:** root = [2,1,3] + +**Output:** 1 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/12/14/tree2.jpg) + +**Input:** root = [1,2,3,4,null,5,6,null,null,7] + +**Output:** 7 + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 104]. +* -231 <= Node.val <= 231 - 1 + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + private fun func(root: TreeNode?, level: Int): IntArray? { + if (root!!.left == null && root.right == null) { + val a = IntArray(2) + a[0] = root.`val` + a[1] = level + return a + } + var a: IntArray? = null + var b: IntArray? = null + if (root.left != null) { + a = func(root.left, level + 1) + } + if (root.right != null) { + b = func(root.right, level + 1) + } + return if (a == null) { + b + } else if (b == null) { + a + } else { + if (a[1] >= b[1]) { + a + } else { + b + } + } + } + + fun findBottomLeftValue(root: TreeNode?): Int { + val a = func(root, 0) + return if (a != null && a.size > 0) { + a[0] + } else -1 + } +} +``` \ No newline at end of file