From 5a25860f2ac7db1d114f23748ac0417117aa3eb0 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 17 Apr 2023 09:37:53 +0300 Subject: [PATCH] Added tasks 892-923 --- README.md | 37 +++++ .../g0801_0900/s0815_bus_routes/readme.md | 3 - .../s0819_most_common_word/readme.md | 6 +- .../readme.md | 4 +- .../g0801_0900/s0843_guess_the_word/readme.md | 12 +- .../g0801_0900/s0855_exam_room/readme.md | 4 +- .../readme.md | 6 +- .../s0890_find_and_replace_pattern/readme.md | 4 +- .../s0892_surface_area_of_3d_shapes/readme.md | 81 +++++++++++ .../readme.md | 80 +++++++++++ .../readme.md | 91 ++++++++++++ .../s0895_maximum_frequency_stack/readme.md | 117 +++++++++++++++ .../s0896_monotonic_array/readme.md | 62 ++++++++ .../readme.md | 66 +++++++++ .../s0898_bitwise_ors_of_subarrays/readme.md | 66 +++++++++ .../g0801_0900/s0899_orderly_queue/readme.md | 75 ++++++++++ .../g0801_0900/s0900_rle_iterator/readme.md | 79 ++++++++++ .../s0901_online_stock_span/readme.md | 82 +++++++++++ .../readme.md | 74 ++++++++++ .../readme.md | 74 ++++++++++ .../s0904_fruit_into_baskets/readme.md | 84 +++++++++++ .../s0905_sort_array_by_parity/readme.md | 49 +++++++ .../s0906_super_palindromes/readme.md | 96 +++++++++++++ .../s0907_sum_of_subarray_minimums/readme.md | 82 +++++++++++ .../s0908_smallest_range_i/readme.md | 62 ++++++++ .../s0909_snakes_and_ladders/readme.md | 111 ++++++++++++++ .../s0910_smallest_range_ii/readme.md | 66 +++++++++ .../s0911_online_election/readme.md | 92 ++++++++++++ .../g0901_1000/s0912_sort_an_array/readme.md | 74 ++++++++++ .../g0901_1000/s0913_cat_and_mouse/readme.md | 136 ++++++++++++++++++ .../readme.md | 65 +++++++++ .../readme.md | 59 ++++++++ .../g0901_1000/s0916_word_subsets/readme.md | 73 ++++++++++ .../s0917_reverse_only_letters/readme.md | 64 +++++++++ .../readme.md | 75 ++++++++++ .../readme.md | 122 ++++++++++++++++ .../s0920_number_of_music_playlists/readme.md | 77 ++++++++++ .../readme.md | 60 ++++++++ .../s0922_sort_array_by_parity_ii/readme.md | 62 ++++++++ .../s0923_3sum_with_multiplicity/readme.md | 80 +++++++++++ 40 files changed, 2585 insertions(+), 27 deletions(-) create mode 100644 src/main/kotlin/g0801_0900/s0892_surface_area_of_3d_shapes/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0893_groups_of_special_equivalent_strings/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0894_all_possible_full_binary_trees/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0895_maximum_frequency_stack/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0896_monotonic_array/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0897_increasing_order_search_tree/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0898_bitwise_ors_of_subarrays/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0899_orderly_queue/readme.md create mode 100644 src/main/kotlin/g0801_0900/s0900_rle_iterator/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0901_online_stock_span/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0902_numbers_at_most_n_given_digit_set/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0903_valid_permutations_for_di_sequence/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0904_fruit_into_baskets/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0905_sort_array_by_parity/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0906_super_palindromes/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0907_sum_of_subarray_minimums/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0908_smallest_range_i/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0909_snakes_and_ladders/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0910_smallest_range_ii/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0911_online_election/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0912_sort_an_array/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0913_cat_and_mouse/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0914_x_of_a_kind_in_a_deck_of_cards/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0915_partition_array_into_disjoint_intervals/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0916_word_subsets/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0917_reverse_only_letters/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0919_complete_binary_tree_inserter/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0920_number_of_music_playlists/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0921_minimum_add_to_make_parentheses_valid/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0922_sort_array_by_parity_ii/readme.md create mode 100644 src/main/kotlin/g0901_1000/s0923_3sum_with_multiplicity/readme.md diff --git a/README.md b/README.md index c231d44b..3f31322a 100644 --- a/README.md +++ b/README.md @@ -415,6 +415,7 @@ | | | | | | |-|-|-|-|-|- +| 0912 |[Sort an Array](src/main/kotlin/g0901_1000/s0912_sort_an_array)| Medium | Array, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Merge_Sort, Bucket_Sort, Counting_Sort, Radix_Sort | 606 | 98.48 #### Udemy 2D Arrays/Matrix @@ -1241,6 +1242,7 @@ | | | | | | |-|-|-|-|-|- +| 0911 |[Online Election](src/main/kotlin/g0901_1000/s0911_online_election)| Medium | Array, Hash_Table, Binary_Search, Design | 766 | 83.33 ### Dynamic Programming I @@ -1277,6 +1279,7 @@ | | | | | | |-|-|-|-|-|- | 0053 |[Maximum Subarray](src/main/kotlin/g0001_0100/s0053_maximum_subarray)| Easy | Top_100_Liked_Questions, Top_Interview_Questions, Array, Dynamic_Programming, Divide_and_Conquer | 662 | 82.48 +| 0918 |[Maximum Sum Circular Subarray](src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray)| Medium | Array, Dynamic_Programming, Divide_and_Conquer, Queue, Monotonic_Queue | 339 | 86.96 #### Day 6 @@ -1472,6 +1475,7 @@ | | | | | | |-|-|-|-|-|- +| 0896 |[Monotonic Array](src/main/kotlin/g0801_0900/s0896_monotonic_array)| Easy | Array | 576 | 90.91 | 0028 |[Find the Index of the First Occurrence in a String](src/main/kotlin/g0001_0100/s0028_implement_strstr)| Easy | Top_Interview_Questions, String, Two_Pointers, String_Matching | 257 | 32.35 #### Day 2 @@ -1550,6 +1554,7 @@ | | | | | | |-|-|-|-|-|- | 0304 |[Range Sum Query 2D - Immutable](src/main/kotlin/g0301_0400/s0304_range_sum_query_2d_immutable)| Medium | Array, Matrix, Design, Prefix_Sum | 1373 | 85.71 +| 0910 |[Smallest Range II](src/main/kotlin/g0901_1000/s0910_smallest_range_ii)| Medium | Array, Math, Sorting, Greedy | 234 | 100.00 #### Day 14 @@ -1693,6 +1698,38 @@ |------|----------------|-------------|-------------|----------|-------- | 1143 |[Longest Common Subsequence](src/main/kotlin/g1101_1200/s1143_longest_common_subsequence)| Medium | Top_100_Liked_Questions, String, Dynamic_Programming, Algorithm_II_Day_17_Dynamic_Programming, Dynamic_Programming_I_Day_19, Udemy_Dynamic_Programming | 307 | 38.36 | 0994 |[Rotting Oranges](src/main/kotlin/g0901_1000/s0994_rotting_oranges)| Medium | Array, Breadth_First_Search, Matrix, Algorithm_I_Day_9_Breadth_First_Search_Depth_First_Search, Level_2_Day_10_Graph/BFS/DFS | 308 | 57.93 +| 0923 |[3Sum With Multiplicity](src/main/kotlin/g0901_1000/s0923_3sum_with_multiplicity)| Medium | Array, Hash_Table, Sorting, Two_Pointers, Counting | 190 | 100.00 +| 0922 |[Sort Array By Parity II](src/main/kotlin/g0901_1000/s0922_sort_array_by_parity_ii)| Easy | Array, Sorting, Two_Pointers | 257 | 87.50 +| 0921 |[Minimum Add to Make Parentheses Valid](src/main/kotlin/g0901_1000/s0921_minimum_add_to_make_parentheses_valid)| Medium | String, Greedy, Stack | 131 | 92.59 +| 0920 |[Number of Music Playlists](src/main/kotlin/g0901_1000/s0920_number_of_music_playlists)| Hard | Dynamic_Programming, Math, Combinatorics | 136 | 100.00 +| 0919 |[Complete Binary Tree Inserter](src/main/kotlin/g0901_1000/s0919_complete_binary_tree_inserter)| Medium | Breadth_First_Search, Tree, Binary_Tree, Design | 225 | 100.00 +| 0918 |[Maximum Sum Circular Subarray](src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray)| Medium | Array, Dynamic_Programming, Divide_and_Conquer, Queue, Monotonic_Queue, Dynamic_Programming_I_Day_5 | 339 | 86.96 +| 0917 |[Reverse Only Letters](src/main/kotlin/g0901_1000/s0917_reverse_only_letters)| Easy | String, Two_Pointers | 126 | 100.00 +| 0916 |[Word Subsets](src/main/kotlin/g0901_1000/s0916_word_subsets)| Medium | Array, String, Hash_Table | 397 | 88.89 +| 0915 |[Partition Array into Disjoint Intervals](src/main/kotlin/g0901_1000/s0915_partition_array_into_disjoint_intervals)| Medium | Array | 510 | 76.92 +| 0914 |[X of a Kind in a Deck of Cards](src/main/kotlin/g0901_1000/s0914_x_of_a_kind_in_a_deck_of_cards)| Easy | Array, Hash_Table, Math, Counting, Number_Theory | 238 | 70.00 +| 0913 |[Cat and Mouse](src/main/kotlin/g0901_1000/s0913_cat_and_mouse)| Hard | Dynamic_Programming, Math, Graph, Memoization, Topological_Sort, Game_Theory | 211 | 100.00 +| 0912 |[Sort an Array](src/main/kotlin/g0901_1000/s0912_sort_an_array)| Medium | Array, Sorting, Heap_Priority_Queue, Divide_and_Conquer, Merge_Sort, Bucket_Sort, Counting_Sort, Radix_Sort, Udemy_Sorting_Algorithms | 606 | 98.48 +| 0911 |[Online Election](src/main/kotlin/g0901_1000/s0911_online_election)| Medium | Array, Hash_Table, Binary_Search, Design, Binary_Search_II_Day_20 | 766 | 83.33 +| 0910 |[Smallest Range II](src/main/kotlin/g0901_1000/s0910_smallest_range_ii)| Medium | Array, Math, Sorting, Greedy, Programming_Skills_II_Day_13 | 234 | 100.00 +| 0909 |[Snakes and Ladders](src/main/kotlin/g0901_1000/s0909_snakes_and_ladders)| Medium | Array, Breadth_First_Search, Matrix | 203 | 100.00 +| 0908 |[Smallest Range I](src/main/kotlin/g0901_1000/s0908_smallest_range_i)| Easy | Array, Math | 202 | 87.50 +| 0907 |[Sum of Subarray Minimums](src/main/kotlin/g0901_1000/s0907_sum_of_subarray_minimums)| Medium | Array, Dynamic_Programming, Stack, Monotonic_Stack | 341 | 100.00 +| 0906 |[Super Palindromes](src/main/kotlin/g0901_1000/s0906_super_palindromes)| Hard | Math, Enumeration | 153 | 100.00 +| 0905 |[Sort Array By Parity](src/main/kotlin/g0901_1000/s0905_sort_array_by_parity)| Easy | Array, Sorting, Two_Pointers | 219 | 75.00 +| 0904 |[Fruit Into Baskets](src/main/kotlin/g0901_1000/s0904_fruit_into_baskets)| Medium | Array, Hash_Table, Sliding_Window | 371 | 100.00 +| 0903 |[Valid Permutations for DI Sequence](src/main/kotlin/g0901_1000/s0903_valid_permutations_for_di_sequence)| Hard | Dynamic_Programming | 140 | 100.00 +| 0902 |[Numbers At Most N Given Digit Set](src/main/kotlin/g0901_1000/s0902_numbers_at_most_n_given_digit_set)| Hard | Array, Dynamic_Programming, Math, Binary_Search | 138 | 100.00 +| 0901 |[Online Stock Span](src/main/kotlin/g0901_1000/s0901_online_stock_span)| Medium | Stack, Design, Monotonic_Stack, Data_Stream | 641 | 75.00 +| 0900 |[RLE Iterator](src/main/kotlin/g0801_0900/s0900_rle_iterator)| Medium | Array, Design, Counting, Iterator | 175 | 83.33 +| 0899 |[Orderly Queue](src/main/kotlin/g0801_0900/s0899_orderly_queue)| Hard | String, Math, Sorting | 148 | 100.00 +| 0898 |[Bitwise ORs of Subarrays](src/main/kotlin/g0801_0900/s0898_bitwise_ors_of_subarrays)| Medium | Array, Dynamic_Programming, Bit_Manipulation | 812 | 100.00 +| 0897 |[Increasing Order Search Tree](src/main/kotlin/g0801_0900/s0897_increasing_order_search_tree)| Easy | Depth_First_Search, Tree, Binary_Tree, Stack, Binary_Search_Tree | 128 | 85.71 +| 0896 |[Monotonic Array](src/main/kotlin/g0801_0900/s0896_monotonic_array)| Easy | Array, Programming_Skills_II_Day_1 | 576 | 90.91 +| 0895 |[Maximum Frequency Stack](src/main/kotlin/g0801_0900/s0895_maximum_frequency_stack)| Hard | Hash_Table, Stack, Design, Ordered_Set | 617 | 100.00 +| 0894 |[All Possible Full Binary Trees](src/main/kotlin/g0801_0900/s0894_all_possible_full_binary_trees)| Medium | Dynamic_Programming, Tree, Binary_Tree, Recursion, Memoization | 257 | 100.00 +| 0893 |[Groups of Special-Equivalent Strings](src/main/kotlin/g0801_0900/s0893_groups_of_special_equivalent_strings)| Medium | Array, String, Hash_Table | 141 | 100.00 +| 0892 |[Surface Area of 3D Shapes](src/main/kotlin/g0801_0900/s0892_surface_area_of_3d_shapes)| Easy | Array, Math, Matrix, Geometry | 180 | 100.00 | 0891 |[Sum of Subsequence Widths](src/main/kotlin/g0801_0900/s0891_sum_of_subsequence_widths)| Hard | Array, Math, Sorting | 481 | 100.00 | 0890 |[Find and Replace Pattern](src/main/kotlin/g0801_0900/s0890_find_and_replace_pattern)| Medium | Array, String, Hash_Table | 150 | 100.00 | 0889 |[Construct Binary Tree from Preorder and Postorder Traversal](src/main/kotlin/g0801_0900/s0889_construct_binary_tree_from_preorder_and_postorder_traversal)| Medium | Array, Hash_Table, Tree, Binary_Tree, Divide_and_Conquer | 168 | 100.00 diff --git a/src/main/kotlin/g0801_0900/s0815_bus_routes/readme.md b/src/main/kotlin/g0801_0900/s0815_bus_routes/readme.md index a2fad086..ab0749de 100644 --- a/src/main/kotlin/g0801_0900/s0815_bus_routes/readme.md +++ b/src/main/kotlin/g0801_0900/s0815_bus_routes/readme.md @@ -41,9 +41,6 @@ Return _the least number of buses you must take to travel from_ `source` _to_ `t ```kotlin import java.util.LinkedList import java.util.Queue -import kotlin.collections.ArrayList -import kotlin.collections.HashSet -import kotlin.collections.MutableSet class Solution { fun numBusesToDestination(routes: Array, source: Int, target: Int): Int { diff --git a/src/main/kotlin/g0801_0900/s0819_most_common_word/readme.md b/src/main/kotlin/g0801_0900/s0819_most_common_word/readme.md index 5bec2b32..e386370d 100644 --- a/src/main/kotlin/g0801_0900/s0819_most_common_word/readme.md +++ b/src/main/kotlin/g0801_0900/s0819_most_common_word/readme.md @@ -34,16 +34,14 @@ The words in `paragraph` are **case-insensitive** and the answer should be retur ## Solution ```kotlin -import java.util.Locale - @Suppress("NAME_SHADOWING") class Solution { fun mostCommonWord(paragraph: String, banned: Array): String { var paragraph = paragraph - paragraph = paragraph.replace("\\p{Punct}".toRegex(), " ").lowercase(Locale.getDefault()) + paragraph = paragraph.replace("\\p{Punct}".toRegex(), " ").lowercase() val a = paragraph.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() for (i in banned.indices) { - banned[i] = banned[i].lowercase(Locale.getDefault()) + banned[i] = banned[i].lowercase() } val map: MutableMap = HashMap() for (s in a) { diff --git a/src/main/kotlin/g0801_0900/s0831_masking_personal_information/readme.md b/src/main/kotlin/g0801_0900/s0831_masking_personal_information/readme.md index 92f1044c..372a0903 100644 --- a/src/main/kotlin/g0801_0900/s0831_masking_personal_information/readme.md +++ b/src/main/kotlin/g0801_0900/s0831_masking_personal_information/readme.md @@ -86,15 +86,13 @@ Thus, the resulting masked number is "\*\*\*-\*\*\*-7890". ## Solution ```kotlin -import java.util.Locale - class Solution { fun maskPII(s: String): String { val masked = StringBuilder() return if (Character.isAlphabetic(s[0].code)) { val locationOfAtSymbol = s.indexOf("@") - 1 masked.append(s[0]).append("*****").append(s.substring(locationOfAtSymbol)) - masked.toString().lowercase(Locale.getDefault()) + masked.toString().lowercase() } else { val allDigits = StringBuilder() var pointer = -1 diff --git a/src/main/kotlin/g0801_0900/s0843_guess_the_word/readme.md b/src/main/kotlin/g0801_0900/s0843_guess_the_word/readme.md index e5d6105d..906b6bdb 100644 --- a/src/main/kotlin/g0801_0900/s0843_guess_the_word/readme.md +++ b/src/main/kotlin/g0801_0900/s0843_guess_the_word/readme.md @@ -48,8 +48,6 @@ For each test case, you have exactly `10` guesses to guess the word. At the end ## Solution ```kotlin -import java.util.Collections - /* * // This is the Master's API interface. * // You should not implement it, or speculate about its implementation @@ -65,8 +63,8 @@ class Solution { private var next = 0 fun findSecretWord(wordlist: Array, master: Master) { - val list = listOf(*wordlist) - Collections.shuffle(list) + val list = wordlist.copyOf() + list.shuffle() val test = BooleanArray(wordlist.size) while (true) { val num = master.guess(list[next]) @@ -77,7 +75,7 @@ class Solution { } } - private fun updateList(list: List, test: BooleanArray, num: Int) { + private fun updateList(list: Array, test: BooleanArray, num: Int) { val index = next for (i in index + 1 until test.size) { if (test[i]) { @@ -92,10 +90,10 @@ class Solution { } } - private fun getSame(word1: String?, word2: String?): Int { + private fun getSame(word1: String, word2: String): Int { var ret = 0 for (i in 0..5) { - if (word1!![i] == word2!![i]) { + if (word1[i] == word2[i]) { ret++ } } diff --git a/src/main/kotlin/g0801_0900/s0855_exam_room/readme.md b/src/main/kotlin/g0801_0900/s0855_exam_room/readme.md index db739a73..a29bec01 100644 --- a/src/main/kotlin/g0801_0900/s0855_exam_room/readme.md +++ b/src/main/kotlin/g0801_0900/s0855_exam_room/readme.md @@ -42,8 +42,6 @@ Implement the `ExamRoom` class: ## Solution ```kotlin -import java.util.Objects - class ExamRoom() { private class Node(var `val`: Int, map: MutableMap) { var pre: Node? = null @@ -107,7 +105,7 @@ class ExamRoom() { } return if (right > max) { Node(n - 1, map).insert(tail.pre) - } else Node(maxAt, map).insert(Objects.requireNonNull(maxAtLeft)) + } else Node(maxAt, map).insert(maxAtLeft) } fun leave(p: Int) { diff --git a/src/main/kotlin/g0801_0900/s0857_minimum_cost_to_hire_k_workers/readme.md b/src/main/kotlin/g0801_0900/s0857_minimum_cost_to_hire_k_workers/readme.md index 615a4c6a..29d7142e 100644 --- a/src/main/kotlin/g0801_0900/s0857_minimum_cost_to_hire_k_workers/readme.md +++ b/src/main/kotlin/g0801_0900/s0857_minimum_cost_to_hire_k_workers/readme.md @@ -49,10 +49,8 @@ class Solution { workers[i] = Worker(wage[i], quality[i]) } workers.sortBy { it!!.ratio() } - val maxHeap = PriorityQueue { a: Int?, b: Int? -> - Integer.compare( - b!!, a!! - ) + val maxHeap = PriorityQueue { a: Int, b: Int -> + b.compareTo(a) } var sumQuality = 0 var result = Double.MAX_VALUE diff --git a/src/main/kotlin/g0801_0900/s0890_find_and_replace_pattern/readme.md b/src/main/kotlin/g0801_0900/s0890_find_and_replace_pattern/readme.md index f9d71af8..e1338e29 100644 --- a/src/main/kotlin/g0801_0900/s0890_find_and_replace_pattern/readme.md +++ b/src/main/kotlin/g0801_0900/s0890_find_and_replace_pattern/readme.md @@ -35,13 +35,11 @@ Recall that a permutation of letters is a bijection from letters to letters: eve ## Solution ```kotlin -import java.util.Collections - class Solution { fun findAndReplacePattern(words: Array, pattern: String): List { val finalans: MutableList = ArrayList() if (pattern.length == 1) { - Collections.addAll(finalans, *words) + finalans.addAll(words) return finalans } for (word in words) { diff --git a/src/main/kotlin/g0801_0900/s0892_surface_area_of_3d_shapes/readme.md b/src/main/kotlin/g0801_0900/s0892_surface_area_of_3d_shapes/readme.md new file mode 100644 index 00000000..945288b4 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0892_surface_area_of_3d_shapes/readme.md @@ -0,0 +1,81 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 892\. Surface Area of 3D Shapes + +Easy + +You are given an `n x n` `grid` where you have placed some `1 x 1 x 1` cubes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of cell `(i, j)`. + +After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. + +Return _the total surface area of the resulting shapes_. + +**Note:** The bottom face of each shape counts toward its surface area. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/01/08/tmp-grid2.jpg) + +**Input:** grid = \[\[1,2],[3,4]] + +**Output:** 34 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/01/08/tmp-grid4.jpg) + +**Input:** grid = \[\[1,1,1],[1,0,1],[1,1,1]] + +**Output:** 32 + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/01/08/tmp-grid5.jpg) + +**Input:** grid = \[\[2,2,2],[2,1,2],[2,2,2]] + +**Output:** 46 + +**Constraints:** + +* `n == grid.length == grid[i].length` +* `1 <= n <= 50` +* `0 <= grid[i][j] <= 50` + +## Solution + +```kotlin +class Solution { + fun surfaceArea(grid: Array): Int { + var surfaceArea = 0 + for (i in grid.indices) { + for (j in grid[i].indices) { + if (grid[i][j] > 0) { + surfaceArea += 4 * grid[i][j] + 2 + surfaceArea -= hiddenSides(i, j, grid) + } + } + } + return surfaceArea + } + + private fun hiddenSides(i: Int, j: Int, grid: Array): Int { + var hidden = 0 + val tower = grid[i][j] + if (j + 1 < grid[i].size && grid[i][j + 1] > 0) { + hidden += tower.coerceAtMost(grid[i][j + 1]) + } + if (j - 1 >= 0 && grid[i][j - 1] > 0) { + hidden += tower.coerceAtMost(grid[i][j - 1]) + } + if (i + 1 < grid.size && grid[i + 1][j] > 0) { + hidden += tower.coerceAtMost(grid[i + 1][j]) + } + if (i - 1 >= 0 && grid[i - 1][j] > 0) { + hidden += tower.coerceAtMost(grid[i - 1][j]) + } + return hidden + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0893_groups_of_special_equivalent_strings/readme.md b/src/main/kotlin/g0801_0900/s0893_groups_of_special_equivalent_strings/readme.md new file mode 100644 index 00000000..1a21953b --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0893_groups_of_special_equivalent_strings/readme.md @@ -0,0 +1,80 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 893\. Groups of Special-Equivalent Strings + +Medium + +You are given an array of strings of the same length `words`. + +In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. + +Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. + +* For example, `words[i] = "zzxy"` and `words[j] = "xyzz"` are **special-equivalent** because we may make the moves `"zzxy" -> "xzzy" -> "xyzz"`. + +A **group of special-equivalent strings** from `words` is a non-empty subset of words such that: + +* Every pair of strings in the group are special equivalent, and +* The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group). + +Return _the number of **groups of special-equivalent strings** from_ `words`. + +**Example 1:** + +**Input:** words = ["abcd","cdab","cbad","xyzz","zzxy","zzyx"] + +**Output:** 3 + +**Explanation:** + +One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. + +The other two groups are ["xyzz", "zzxy"] and ["zzyx"]. + +Note that in particular, "zzxy" is not special equivalent to "zzyx". + +**Example 2:** + +**Input:** words = ["abc","acb","bac","bca","cab","cba"] + +**Output:** 3 + +**Constraints:** + +* `1 <= words.length <= 1000` +* `1 <= words[i].length <= 20` +* `words[i]` consist of lowercase English letters. +* All the strings are of the same length. + +## Solution + +```kotlin +class Solution { + fun numSpecialEquivGroups(words: Array): Int { + val set: HashSet = HashSet() + var result = 0 + for (str in words) { + if (set.add(getHashBySwap(str.toCharArray()))) { + result++ + } + } + return result + } + + private fun getHashBySwap(chars: CharArray): String { + for (i in chars.indices) { + var j = i + 2 + while (j < chars.size) { + if (chars[i] > chars[j]) { + val temp = chars[j] + chars[j] = chars[i] + chars[i] = temp + } + j += 2 + } + } + return String(chars) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0894_all_possible_full_binary_trees/readme.md b/src/main/kotlin/g0801_0900/s0894_all_possible_full_binary_trees/readme.md new file mode 100644 index 00000000..e40f3657 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0894_all_possible_full_binary_trees/readme.md @@ -0,0 +1,91 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 894\. All Possible Full Binary Trees + +Medium + +Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`. + +Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**. + +A **full binary tree** is a binary tree where each node has exactly `0` or `2` children. + +**Example 1:** + +![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/22/fivetrees.png) + +**Input:** n = 7 + +**Output:** [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]] + +**Example 2:** + +**Input:** n = 3 + +**Output:** [[0,0,0]] + +**Constraints:** + +* `1 <= n <= 20` + +## 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 allPossibleFBT(n: Int): List { + if (n % 2 == 0) { + // no complete binary tree possible + return ArrayList() + } + val dp: Array?> = arrayOfNulls(n + 1) + // form left to right + var i = 1 + while (i <= n) { + helper(i, dp) + i += 2 + } + return dp[n]!! + } + + // Using tabulation + private fun helper(n: Int, dp: Array?>) { + if (n <= 0) { + return + } + if (n == 1) { + dp[1] = ArrayList() + dp[1]!!.add(TreeNode(0)) + return + } + dp[n] = ArrayList() + var i = 1 + while (i < n) { + // left + for (nodeL in dp[i]!!) { + // right + for (nodeR in dp[n - i - 1]!!) { + // 1 node used here + val root = TreeNode(0) + root.left = nodeL + root.right = nodeR + dp[n]!!.add(root) + } + } + i += 2 + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0895_maximum_frequency_stack/readme.md b/src/main/kotlin/g0801_0900/s0895_maximum_frequency_stack/readme.md new file mode 100644 index 00000000..76b0527c --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0895_maximum_frequency_stack/readme.md @@ -0,0 +1,117 @@ +[![](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) + +## 895\. Maximum Frequency Stack + +Hard + +Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. + +Implement the `FreqStack` class: + +* `FreqStack()` constructs an empty frequency stack. +* `void push(int val)` pushes an integer `val` onto the top of the stack. +* `int pop()` removes and returns the most frequent element in the stack. + * If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned. + +**Example 1:** + +**Input** + +["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"] + +[[], [5], [7], [5], [7], [4], [5], [], [], [], []] + +**Output:** [null, null, null, null, null, null, null, 5, 7, 5, 4] + +**Explanation:** + + FreqStack freqStack = new FreqStack(); + freqStack.push(5); // The stack is [5] + freqStack.push(7); // The stack is [5,7] + freqStack.push(5); // The stack is [5,7,5] + freqStack.push(7); // The stack is [5,7,5,7] + freqStack.push(4); // The stack is [5,7,5,7,4] + freqStack.push(5); // The stack is [5,7,5,7,4,5] + freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4]. + freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4]. + freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4]. + freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7]. + +**Constraints:** + +* 0 <= val <= 109 +* At most 2 * 104 calls will be made to `push` and `pop`. +* It is guaranteed that there will be at least one element in the stack before calling `pop`. + +## Solution + +```kotlin +class FreqStack { + private class Node { + var next: Node? + var `val` = 0 + + constructor(`val`: Int) { + this.`val` = `val` + next = null + } + + constructor() { + next = null + } + } + + private class DLL { + var head: Node = Node() + var size: Int = 0 + + fun addNode(x: Int) { + val node = Node(x) + node.next = head.next + head.next = node + size++ + } + + fun removeNode(): Node? { + val node = head.next + if (node != null) { + head.next = node.next + node.next = null + size-- + } + return node + } + } + + private var max = 0 + private val freqMap: HashMap = HashMap() + private val freqListMap: HashMap = HashMap() + + fun push(`val`: Int) { + val count = freqMap.getOrDefault(`val`, 0) + 1 + max = max.coerceAtLeast(count) + freqMap[`val`] = count + val dll = freqListMap.getOrDefault(count, DLL()) + dll.addNode(`val`) + freqListMap[count] = dll + } + + fun pop(): Int { + val dll = freqListMap[max] + val node = dll!!.removeNode() + freqMap[node!!.`val`] = max - 1 + if (dll.size == 0) { + max-- + } + return node.`val` + } +} + +/* + * Your FreqStack object will be instantiated and called as such: + * var obj = FreqStack() + * obj.push(`val`) + * var param_2 = obj.pop() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0896_monotonic_array/readme.md b/src/main/kotlin/g0801_0900/s0896_monotonic_array/readme.md new file mode 100644 index 00000000..c88c6ead --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0896_monotonic_array/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) + +## 896\. Monotonic Array + +Easy + +An array is **monotonic** if it is either monotone increasing or monotone decreasing. + +An array `nums` is monotone increasing if for all `i <= j`, `nums[i] <= nums[j]`. An array `nums` is monotone decreasing if for all `i <= j`, `nums[i] >= nums[j]`. + +Given an integer array `nums`, return `true` _if the given array is monotonic, or_ `false` _otherwise_. + +**Example 1:** + +**Input:** nums = [1,2,2,3] + +**Output:** true + +**Example 2:** + +**Input:** nums = [6,5,4,4] + +**Output:** true + +**Example 3:** + +**Input:** nums = [1,3,2] + +**Output:** false + +**Constraints:** + +* 1 <= nums.length <= 105 +* -105 <= nums[i] <= 105 + +## Solution + +```kotlin +class Solution { + fun isMonotonic(nums: IntArray): Boolean { + var i = 0 + while (i < nums.size - 1) { + if (nums[i] > nums[i + 1]) { + break + } + i++ + } + if (i == nums.size - 1) { + return true + } + i = 0 + while (i < nums.size - 1) { + if (nums[i] < nums[i + 1]) { + break + } + i++ + } + return i == nums.size - 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0897_increasing_order_search_tree/readme.md b/src/main/kotlin/g0801_0900/s0897_increasing_order_search_tree/readme.md new file mode 100644 index 00000000..16af7cf9 --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0897_increasing_order_search_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) + +## 897\. Increasing Order Search Tree + +Easy + +Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/17/ex1.jpg) + +**Input:** root = [5,3,6,2,4,null,8,1,null,null,null,7,9] + +**Output:** [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/11/17/ex2.jpg) + +**Input:** root = [5,1,7] + +**Output:** [1,null,5,null,7] + +**Constraints:** + +* The number of nodes in the given tree will be in the range `[1, 100]`. +* `0 <= Node.val <= 1000` + +## Solution + +```kotlin +import com_github_leetcode.TreeNode +import java.util.LinkedList + +/* + * 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 increasingBST(root: TreeNode?): TreeNode { + val list: MutableList = LinkedList() + traverse(root, list) + for (i in 1 until list.size) { + list[i - 1].right = list[i] + list[i].left = null + } + return list[0] + } + + private fun traverse(root: TreeNode?, list: MutableList) { + if (root != null) { + traverse(root.left, list) + list.add(root) + traverse(root.right, list) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0898_bitwise_ors_of_subarrays/readme.md b/src/main/kotlin/g0801_0900/s0898_bitwise_ors_of_subarrays/readme.md new file mode 100644 index 00000000..263a649d --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0898_bitwise_ors_of_subarrays/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) + +## 898\. Bitwise ORs of Subarrays + +Medium + +Given an integer array `arr`, return _the number of distinct bitwise ORs of all the non-empty subarrays of_ `arr`. + +The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. + +A **subarray** is a contiguous non-empty sequence of elements within an array. + +**Example 1:** + +**Input:** arr = [0] + +**Output:** 1 + +**Explanation:** There is only one possible result: 0. + +**Example 2:** + +**Input:** arr = [1,1,2] + +**Output:** 3 + +**Explanation:** The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2]. + +These yield the results 1, 1, 2, 1, 3, 3. + +There are 3 unique values, so the answer is 3. + +**Example 3:** + +**Input:** arr = [1,2,4] + +**Output:** 6 + +**Explanation:** The possible results are 1, 2, 3, 4, 6, and 7. + +**Constraints:** + +* 1 <= arr.length <= 5 * 104 +* 0 <= arr[i] <= 109 + +## Solution + +```kotlin +class Solution { + fun subarrayBitwiseORs(arr: IntArray): Int { + val set: MutableSet = HashSet() + for (i in arr.indices) { + set.add(arr[i]) + for (j in i - 1 downTo 0) { + if (arr[i] or arr[j] == arr[j]) { + break + } + arr[j] = arr[j] or arr[i] + set.add(arr[j]) + } + } + return set.size + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0899_orderly_queue/readme.md b/src/main/kotlin/g0801_0900/s0899_orderly_queue/readme.md new file mode 100644 index 00000000..1660d09e --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0899_orderly_queue/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) + +## 899\. Orderly Queue + +Hard + +You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string.. + +Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_. + +**Example 1:** + +**Input:** s = "cba", k = 1 + +**Output:** "acb" + +**Explanation:** + +In the first move, we move the 1st character 'c' to the end, obtaining the string "bac". + +In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb". + +**Example 2:** + +**Input:** s = "baaca", k = 3 + +**Output:** "aaabc" + +**Explanation:** + +In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab". + +In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc". + +**Constraints:** + +* `1 <= k <= s.length <= 1000` +* `s` consist of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun orderlyQueue(s: String, k: Int): String { + if (k > 1) { + val ans = s.toCharArray() + ans.sort() + return String(ans) + } + var min = 'z' + val list = ArrayList() + for (element in s) { + if (element < min) { + min = element + } + } + for (i in s.indices) { + if (s[i] == min) { + list.add(i) + } + } + var ans = s + for (integer in list) { + val after = s.substring(0, integer) + val before = s.substring(integer) + val f = before + after + if (f < ans) { + ans = f + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0801_0900/s0900_rle_iterator/readme.md b/src/main/kotlin/g0801_0900/s0900_rle_iterator/readme.md new file mode 100644 index 00000000..9f60adfe --- /dev/null +++ b/src/main/kotlin/g0801_0900/s0900_rle_iterator/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) + +## 900\. RLE Iterator + +Medium + +We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. + +* For example, the sequence `arr = [8,8,8,5,5]` can be encoded to be `encoding = [3,8,2,5]`. `encoding = [3,8,0,9,2,5]` and `encoding = [2,8,1,8,2,5]` are also valid **RLE** of `arr`. + +Given a run-length encoded array, design an iterator that iterates through it. + +Implement the `RLEIterator` class: + +* `RLEIterator(int[] encoded)` Initializes the object with the encoded array `encoded`. +* `int next(int n)` Exhausts the next `n` elements and returns the last element exhausted in this way. If there is no element left to exhaust, return `-1` instead. + +**Example 1:** + +**Input** + +["RLEIterator", "next", "next", "next", "next"] + +[[[3, 8, 0, 9, 2, 5]], [2], [1], [1], [2]] + +**Output:** [null, 8, 8, 5, -1] + +**Explanation:** + + RLEIterator rLEIterator = new RLEIterator([3, 8, 0, 9, 2, 5]); // This maps to the sequence [8,8,8,5,5]. + rLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now [8, 5, 5]. + rLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now [5, 5]. + rLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now [5]. + rLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5, + // but the second term did not exist. Since the last term exhausted does not exist, we return -1. + +**Constraints:** + +* `2 <= encoding.length <= 1000` +* `encoding.length` is even. +* 0 <= encoding[i] <= 109 +* 1 <= n <= 109 +* At most `1000` calls will be made to `next`. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class RLEIterator(private val array: IntArray) { + private var index = 0 + fun next(n: Int): Int { + var n = n + var lastElement = -1 + while (n > 0 && index < array.size) { + if (array[index] > n) { + array[index] -= n + lastElement = array[index + 1] + break + } else if (array[index] == n) { + array[index] = 0 + lastElement = array[index + 1] + index += 2 + break + } else { + n -= array[index] + index += 2 + } + } + return lastElement + } +} + +/* + * Your RLEIterator object will be instantiated and called as such: + * var obj = RLEIterator(encoding) + * var param_1 = obj.next(n) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0901_online_stock_span/readme.md b/src/main/kotlin/g0901_1000/s0901_online_stock_span/readme.md new file mode 100644 index 00000000..ff217c50 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0901_online_stock_span/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) + +## 901\. Online Stock Span + +Medium + +Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day. + +The **span** of the stock's price today is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today's price. + +* For example, if the price of a stock over the next `7` days were `[100,80,60,70,60,75,85]`, then the stock spans would be `[1,1,1,2,1,4,6]`. + +Implement the `StockSpanner` class: + +* `StockSpanner()` Initializes the object of the class. +* `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`. + +**Example 1:** + +**Input** + +["StockSpanner", "next", "next", "next", "next", "next", "next", "next"] + +[[], [100], [80], [60], [70], [60], [75], [85]] + +**Output:** [null, 1, 1, 1, 2, 1, 4, 6] + +**Explanation:** + + StockSpanner stockSpanner = new StockSpanner(); + stockSpanner.next(100); // return 1 + stockSpanner.next(80); // return 1 + stockSpanner.next(60); // return 1 + stockSpanner.next(70); // return 2 + stockSpanner.next(60); // return 1 + stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price. + stockSpanner.next(85); // return 6 + +**Constraints:** + +* 1 <= price <= 105 +* At most 104 calls will be made to `next`. + +## Solution + +```kotlin +import java.util.Deque +import java.util.LinkedList + +class StockSpanner { + private val map: MutableMap + private val stocks: Deque + private var index: Int + + init { + stocks = LinkedList() + index = -1 + map = HashMap() + stocks.push(-1) + } + + fun next(price: Int): Int { + if (index != -1) { + stocks.push(index) + } + map[++index] = price + if (stocks.size == 1) { + return index - stocks.peek() + } + while (stocks.size > 1 && map[stocks.peek()]!! <= price) { + stocks.pop() + } + return index - stocks.peek() + } +} +/* + * Your StockSpanner object will be instantiated and called as such: + * var obj = StockSpanner() + * var param_1 = obj.next(price) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0902_numbers_at_most_n_given_digit_set/readme.md b/src/main/kotlin/g0901_1000/s0902_numbers_at_most_n_given_digit_set/readme.md new file mode 100644 index 00000000..01a9a32a --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0902_numbers_at_most_n_given_digit_set/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 902\. Numbers At Most N Given Digit Set + +Hard + +Given an array of `digits` which is sorted in **non-decreasing** order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`. + +Return _the number of positive integers that can be generated_ that are less than or equal to a given integer `n`. + +**Example 1:** + +**Input:** digits = ["1","3","5","7"], n = 100 + +**Output:** 20 + +**Explanation:** The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. + +**Example 2:** + +**Input:** digits = ["1","4","9"], n = 1000000000 + +**Output:** 29523 + +**Explanation:** We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. + +**Example 3:** + +**Input:** digits = ["7"], n = 8 + +**Output:** 1 + +**Constraints:** + +* `1 <= digits.length <= 9` +* `digits[i].length == 1` +* `digits[i]` is a digit from `'1'` to `'9'`. +* All the values in `digits` are **unique**. +* `digits` is sorted in **non-decreasing** order. +* 1 <= n <= 109 + +## Solution + +```kotlin +import kotlin.math.pow + +class Solution { + fun atMostNGivenDigitSet(digits: Array, n: Int): Int { + var ans = 0 + val num = "" + n + val d = digits.size + val l = num.length + for (i in 1 until l) { + ans += d.toDouble().pow(i.toDouble()).toInt() + } + for (i in 0 until l) { + var flag = false + for (digit in digits) { + if (digit[0] < num[i]) { + ans += d.toDouble().pow((l - i - 1) * 1.0).toInt() + } else if (num[i] == digit[0]) { + flag = true + break + } + } + if (!flag) { + return ans + } + } + return ans + 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0903_valid_permutations_for_di_sequence/readme.md b/src/main/kotlin/g0901_1000/s0903_valid_permutations_for_di_sequence/readme.md new file mode 100644 index 00000000..67f8ff5e --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0903_valid_permutations_for_di_sequence/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 903\. Valid Permutations for DI Sequence + +Hard + +You are given a string `s` of length `n` where `s[i]` is either: + +* `'D'` means decreasing, or +* `'I'` means increasing. + +A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` is called a **valid permutation** if for all valid `i`: + +* If `s[i] == 'D'`, then `perm[i] > perm[i + 1]`, and +* If `s[i] == 'I'`, then `perm[i] < perm[i + 1]`. + +Return _the number of **valid permutations**_ `perm`. Since the answer may be large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** s = "DID" + +**Output:** 5 + +**Explanation:** The 5 valid permutations of (0, 1, 2, 3) are: + + (1, 0, 3, 2) + (2, 0, 3, 1) + (2, 1, 3, 0) + (3, 0, 2, 1) + (3, 1, 2, 0) + +**Example 2:** + +**Input:** s = "D" + +**Output:** 1 + +**Constraints:** + +* `n == s.length` +* `1 <= n <= 200` +* `s[i]` is either `'I'` or `'D'`. + +## Solution + +```kotlin +class Solution { + fun numPermsDISequence(s: String): Int { + val n = s.length + val mod = 1e9.toInt() + 7 + val dp = Array(n + 1) { IntArray(n + 1) } + for (j in 0..n) { + dp[0][j] = 1 + } + for (i in 0 until n) { + var cur = 0 + if (s[i] == 'I') { + for (j in 0 until n - i) { + cur = (cur + dp[i][j]) % mod + dp[i + 1][j] = cur + } + } else { + for (j in n - i - 1 downTo 0) { + cur = (cur + dp[i][j + 1]) % mod + dp[i + 1][j] = cur + } + } + } + return dp[n][0] + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0904_fruit_into_baskets/readme.md b/src/main/kotlin/g0901_1000/s0904_fruit_into_baskets/readme.md new file mode 100644 index 00000000..f81ef8ee --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0904_fruit_into_baskets/readme.md @@ -0,0 +1,84 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 904\. Fruit Into Baskets + +Medium + +You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the ith tree produces. + +You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: + +* You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold. +* Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. +* Once you reach a tree with fruit that cannot fit in your baskets, you must stop. + +Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_. + +**Example 1:** + +**Input:** fruits = [1,2,1] + +**Output:** 3 + +**Explanation:** We can pick from all 3 trees. + +**Example 2:** + +**Input:** fruits = [0,1,2,2] + +**Output:** 3 + +**Explanation:** We can pick from trees [1,2,2]. If we had started at the first tree, we would only pick from trees [0,1]. + +**Example 3:** + +**Input:** fruits = [1,2,3,2,2] + +**Output:** 4 + +**Explanation:** We can pick from trees [2,3,2,2]. If we had started at the first tree, we would only pick from trees [1,2]. + +**Constraints:** + +* 1 <= fruits.length <= 105 +* `0 <= fruits[i] < fruits.length` + +## Solution + +```kotlin +class Solution { + fun totalFruit(fruits: IntArray): Int { + var end = 1 + var basket1 = fruits[0] + var basket2 = -1 + var secondFruitIndex = -1 + var maxTotal = 1 + var counter = 1 + while (end < fruits.size) { + if (fruits[end - 1] != fruits[end]) { + if (basket2 == -1) { + basket2 = fruits[end] + secondFruitIndex = end + counter++ + } else if (fruits[end] == basket1) { + basket1 = basket2 + basket2 = fruits[end] + secondFruitIndex = end + counter++ + } else { + counter = end - secondFruitIndex + 1 + basket1 = basket2 + basket2 = fruits[end] + secondFruitIndex = end + } + } else { + counter++ + } + end++ + maxTotal = maxTotal.coerceAtLeast(counter) + } + return maxTotal + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0905_sort_array_by_parity/readme.md b/src/main/kotlin/g0901_1000/s0905_sort_array_by_parity/readme.md new file mode 100644 index 00000000..2ff6624f --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0905_sort_array_by_parity/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) + +## 905\. Sort Array By Parity + +Easy + +Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers. + +Return _**any array** that satisfies this condition_. + +**Example 1:** + +**Input:** nums = [3,1,2,4] + +**Output:** [2,4,3,1] + +**Explanation:** The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. + +**Example 2:** + +**Input:** nums = [0] + +**Output:** [0] + +**Constraints:** + +* `1 <= nums.length <= 5000` +* `0 <= nums[i] <= 5000` + +## Solution + +```kotlin +class Solution { + fun sortArrayByParity(nums: IntArray): IntArray { + var temp: Int + var i = 0 + for (k in nums.indices) { + if (nums[k] % 2 == 0) { + temp = nums[k] + nums[k] = nums[i] + nums[i] = temp + i++ + } + } + return nums + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0906_super_palindromes/readme.md b/src/main/kotlin/g0901_1000/s0906_super_palindromes/readme.md new file mode 100644 index 00000000..4772d371 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0906_super_palindromes/readme.md @@ -0,0 +1,96 @@ +[![](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) + +## 906\. Super Palindromes + +Hard + +Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome. + +Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`. + +**Example 1:** + +**Input:** left = "4", right = "1000" + +**Output:** 4 + +**Explanation:**: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome. + +**Example 2:** + +**Input:** left = "1", right = "2" + +**Output:** 1 + +**Constraints:** + +* `1 <= left.length, right.length <= 18` +* `left` and `right` consist of only digits. +* `left` and `right` cannot have leading zeros. +* `left` and `right` represent integers in the range [1, 1018 - 1]. +* `left` is less than or equal to `right`. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun superpalindromesInRange(left: String, right: String): Int { + val l = left.toLong() + val r = right.toLong() + var cnt = 0 + var cur: Long = 1 + while (true) { + val p1 = getPalindromeIncLastDigit(cur) + val p2 = getPalindromeExcLastDigit(cur) + val sq1 = p1 * p1 + val sq2 = p2 * p2 + if (sq2 > r) { + break + } + if (sq1 in l..r && isPalindrome(sq1)) { + cnt++ + } + if (sq2 >= l && isPalindrome(sq2)) { + cnt++ + } + cur++ + } + return cnt + } + + private fun isPalindrome(`val`: Long): Boolean { + var `val` = `val` + var construct: Long = 0 + if (`val` % 10 == 0L && `val` >= 10) { + return false + } + while (construct < `val`) { + construct = construct * 10 + `val` % 10 + `val` /= 10 + } + return construct == `val` || construct / 10 == `val` + } + + private fun getPalindromeIncLastDigit(`val`: Long): Long { + var `val` = `val` + var copy = `val` + while (copy != 0L) { + `val` = `val` * 10 + copy % 10 + copy /= 10 + } + return `val` + } + + private fun getPalindromeExcLastDigit(`val`: Long): Long { + var `val` = `val` + var copy = `val` / 10 + while (copy != 0L) { + `val` = `val` * 10 + copy % 10 + copy /= 10 + } + return `val` + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0907_sum_of_subarray_minimums/readme.md b/src/main/kotlin/g0901_1000/s0907_sum_of_subarray_minimums/readme.md new file mode 100644 index 00000000..f28f0235 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0907_sum_of_subarray_minimums/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) + +## 907\. Sum of Subarray Minimums + +Medium + +Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** 109 + 7. + +**Example 1:** + +**Input:** arr = [3,1,2,4] + +**Output:** 17 + +**Explanation:** + +Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. + +Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. + +Sum is 17. + +**Example 2:** + +**Input:** arr = [11,81,94,43,3] + +**Output:** 444 + +**Constraints:** + +* 1 <= arr.length <= 3 * 104 +* 1 <= arr[i] <= 3 * 104 + +## Solution + +```kotlin +class Solution { + private fun calculateRight(i: Int, start: Int, right: IntArray, arr: IntArray, len: Int): Int { + if (start >= len) { + return 0 + } + return if (arr[start] < arr[i]) { + 0 + } else (1 + right[start] + calculateRight(i, start + right[start] + 1, right, arr, len)) % MOD + } + + private fun calculateLeft(i: Int, start: Int, left: IntArray, arr: IntArray, len: Int): Int { + if (start < 0) { + return 0 + } + return if (arr[start] <= arr[i]) { + 0 + } else (1 + left[start] + calculateLeft(i, start - left[start] - 1, left, arr, len)) % MOD + } + + fun sumSubarrayMins(arr: IntArray): Int { + val len = arr.size + val right = IntArray(len) + val left = IntArray(len) + right[len - 1] = 0 + for (i in len - 2 downTo 0) { + right[i] = calculateRight(i, i + 1, right, arr, len) + } + left[0] = 0 + for (i in 1 until len) { + left[i] = calculateLeft(i, i - 1, left, arr, len) + } + var answer = 0 + for (i in 0 until len) { + val model: Long = 1000000007 + answer += ((1 + left[i]) * (1 + right[i]).toLong() % model * arr[i] % model).toInt() + answer %= MOD + } + return answer + } + + companion object { + private const val MOD = 1000000007 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0908_smallest_range_i/readme.md b/src/main/kotlin/g0901_1000/s0908_smallest_range_i/readme.md new file mode 100644 index 00000000..de5a729e --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0908_smallest_range_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) + +## 908\. Smallest Range I + +Easy + +You are given an integer array `nums` and an integer `k`. + +In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index `i`. + +The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. + +Return _the minimum **score** of_ `nums` _after applying the mentioned operation at most once for each index in it_. + +**Example 1:** + +**Input:** nums = [1], k = 0 + +**Output:** 0 + +**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. + +**Example 2:** + +**Input:** nums = [0,10], k = 2 + +**Output:** 6 + +**Explanation:** Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6. + +**Example 3:** + +**Input:** nums = [1,3,6], k = 3 + +**Output:** 0 + +**Explanation:** Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0. + +**Constraints:** + +* 1 <= nums.length <= 104 +* 0 <= nums[i] <= 104 +* 0 <= k <= 104 + +## Solution + +```kotlin +class Solution { + fun smallestRangeI(nums: IntArray, k: Int): Int { + var min = Int.MAX_VALUE + var max = Int.MIN_VALUE + for (num in nums) { + min = min.coerceAtMost(num) + max = max.coerceAtLeast(num) + } + return if (min + k >= max - k) { + 0 + } else max - k - (min + k) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0909_snakes_and_ladders/readme.md b/src/main/kotlin/g0901_1000/s0909_snakes_and_ladders/readme.md new file mode 100644 index 00000000..269eebf3 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0909_snakes_and_ladders/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) + +## 909\. Snakes and Ladders + +Medium + +You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to n2 in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row. + +You start on square `1` of the board. In each move, starting from square `curr`, do the following: + +* Choose a destination square `next` with a label in the range [curr + 1, min(curr + 6, n2)]. + * This choice simulates the result of a standard **6-sided die roll**: i.e., there are always at most 6 destinations, regardless of the size of the board. +* If `next` has a snake or ladder, you **must** move to the destination of that snake or ladder. Otherwise, you move to `next`. +* The game ends when you reach the square n2. + +A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and n2 do not have a snake or ladder. + +Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do **not** follow the subsequent snake or ladder. + +* For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do **not** follow the subsequent ladder to `4`. + +Return _the least number of moves required to reach the square_ n2_. If it is not possible to reach the square, return_ `-1`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2018/09/23/snakes.png) + +**Input:** board = \[\[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]] + +**Output:** 4 + +**Explanation:** + +In the beginning, you start at square 1 (at row 5, column 0). + +You decide to move to square 2 and must take the ladder to square 15. + +You then decide to move to square 17 and must take the snake to square 13. + +You then decide to move to square 14 and must take the ladder to square 35. + +You then decide to move to square 36, ending the game. + +This is the lowest possible number of moves to reach the last square, so return 4. + +**Example 2:** + +**Input:** board = \[\[-1,-1],[-1,3]] + +**Output:** 1 + +**Constraints:** + +* `n == board.length == board[i].length` +* `2 <= n <= 20` +* `grid[i][j]` is either `-1` or in the range [1, n2]. +* The squares labeled `1` and n2 do not have any ladders or snakes. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + private var size = 0 + fun snakesAndLadders(board: Array): Int { + val queue: Queue = LinkedList() + size = board.size + val target = size * size + val visited = BooleanArray(target) + queue.add(1) + visited[0] = true + var step = 0 + while (!queue.isEmpty()) { + val queueSize = queue.size + for (i in 0 until queueSize) { + val previousLabel = queue.poll() + if (previousLabel == target) { + return step + } + for (currentLabel in previousLabel + 1..Math.min(target, previousLabel + 6)) { + if (visited[currentLabel - 1]) { + continue + } + visited[currentLabel - 1] = true + val position = indexToPosition(currentLabel) + if (board[position[0]][position[1]] == -1) { + queue.add(currentLabel) + } else { + queue.add(board[position[0]][position[1]]) + } + } + } + step++ + } + return -1 + } + + private fun indexToPosition(index: Int): IntArray { + val vertical = size - 1 - (index - 1) / size + val horizontal: Int = if ((size - vertical) % 2 == 1) { + (index - 1) % size + } else { + size - 1 - (index - 1) % size + } + return intArrayOf(vertical, horizontal) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0910_smallest_range_ii/readme.md b/src/main/kotlin/g0901_1000/s0910_smallest_range_ii/readme.md new file mode 100644 index 00000000..5e4b9487 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0910_smallest_range_ii/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) + +## 910\. Smallest Range II + +Medium + +You are given an integer array `nums` and an integer `k`. + +For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`. + +The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. + +Return _the minimum **score** of_ `nums` _after changing the values at each index_. + +**Example 1:** + +**Input:** nums = [1], k = 0 + +**Output:** 0 + +**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. + +**Example 2:** + +**Input:** nums = [0,10], k = 2 + +**Output:** 6 + +**Explanation:** Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6. + +**Example 3:** + +**Input:** nums = [1,3,6], k = 3 + +**Output:** 3 + +**Explanation:** Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3. + +**Constraints:** + +* 1 <= nums.length <= 104 +* 0 <= nums[i] <= 104 +* 0 <= k <= 104 + +## Solution + +```kotlin +import java.util.Arrays + +class Solution { + fun smallestRangeII(nums: IntArray, k: Int): Int { + Arrays.sort(nums) + val n = nums.size + var ans = nums[n - 1] - nums[0] + val min = nums[0] + k + val max = nums[n - 1] - k + for (i in 0 until n - 1) { + val mx = max.coerceAtLeast(nums[i] + k) + val mi = min.coerceAtMost(nums[i + 1] - k) + ans = ans.coerceAtMost(mx - mi) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0911_online_election/readme.md b/src/main/kotlin/g0901_1000/s0911_online_election/readme.md new file mode 100644 index 00000000..5af5f269 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0911_online_election/readme.md @@ -0,0 +1,92 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 911\. Online Election + +Medium + +You are given two integer arrays `persons` and `times`. In an election, the ith vote was cast for `persons[i]` at time `times[i]`. + +For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast at time `t` will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. + +Implement the `TopVotedCandidate` class: + +* `TopVotedCandidate(int[] persons, int[] times)` Initializes the object with the `persons` and `times` arrays. +* `int q(int t)` Returns the number of the person that was leading the election at time `t` according to the mentioned rules. + +**Example 1:** + +**Input** ["TopVotedCandidate", "q", "q", "q", "q", "q", "q"] [[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]] + +**Output:** [null, 0, 1, 1, 0, 0, 1] + +**Explanation:** + + TopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]); + topVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading. + topVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading. + topVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.) + topVotedCandidate.q(15); // return 0 + topVotedCandidate.q(24); // return 0 + topVotedCandidate.q(8); // return 1 + +**Constraints:** + +* `1 <= persons.length <= 5000` +* `times.length == persons.length` +* `0 <= persons[i] < persons.length` +* 0 <= times[i] <= 109 +* `times` is sorted in a strictly increasing order. +* times[0] <= t <= 109 +* At most 104 calls will be made to `q`. + +## Solution + +```kotlin +class TopVotedCandidate(persons: IntArray, private val times: IntArray) { + private val winnersAtTimeT: IntArray = IntArray(times.size) + + init { + val counterArray = IntArray(persons.size) + var maxVote = 0 + var maxVotedPerson = 0 + for (i in persons.indices) { + val person = persons[i] + val voteCount = counterArray[person] + if (voteCount + 1 >= maxVote) { + maxVote = voteCount + 1 + maxVotedPerson = person + } + winnersAtTimeT[i] = maxVotedPerson + counterArray[persons[i]] = voteCount + 1 + } + } + + fun q(t: Int): Int { + var lo = 0 + var hi = times.size - 1 + if (t >= times[hi]) { + lo = hi + } else { + while (lo < hi - 1) { + val mid = lo + (hi - lo) / 2 + if (times[mid] == t) { + lo = mid + break + } else if (times[mid] > t) { + hi = mid + } else { + lo = mid + } + } + } + return winnersAtTimeT[lo] + } +} + +/** + * Your TopVotedCandidate object will be instantiated and called as such: + * var obj = TopVotedCandidate(persons, times) + * var param_1 = obj.q(t) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0912_sort_an_array/readme.md b/src/main/kotlin/g0901_1000/s0912_sort_an_array/readme.md new file mode 100644 index 00000000..2644e2b7 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0912_sort_an_array/readme.md @@ -0,0 +1,74 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 912\. Sort an Array + +Medium + +Given an array of integers `nums`, sort the array in ascending order and return it. + +You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible. + +**Example 1:** + +**Input:** nums = [5,2,3,1] + +**Output:** [1,2,3,5] + +**Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5). + +**Example 2:** + +**Input:** nums = [5,1,1,2,0,0] + +**Output:** [0,0,1,1,2,5] + +**Explanation:** Note that the values of nums are not necessairly unique. + +**Constraints:** + +* 1 <= nums.length <= 5 * 104 +* -5 * 104 <= nums[i] <= 5 * 104 + +## Solution + +```kotlin +class Solution { + fun sortArray(nums: IntArray): IntArray { + return mergeSort(nums, 0, nums.size - 1) + } + + private fun mergeSort(arr: IntArray, lo: Int, hi: Int): IntArray { + if (lo == hi) { + val sortedArr = IntArray(1) + sortedArr[0] = arr[lo] + return sortedArr + } + val mid = (lo + hi) / 2 + val leftArray = mergeSort(arr, lo, mid) + val rightArray = mergeSort(arr, mid + 1, hi) + return mergeSortedArray(leftArray, rightArray) + } + + private fun mergeSortedArray(a: IntArray, b: IntArray): IntArray { + val ans = IntArray(a.size + b.size) + var i = 0 + var j = 0 + var k = 0 + while (i < a.size && j < b.size) { + if (a[i] < b[j]) { + ans[k++] = a[i++] + } else { + ans[k++] = b[j++] + } + } + while (i < a.size) { + ans[k++] = a[i++] + } + while (j < b.size) { + ans[k++] = b[j++] + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0913_cat_and_mouse/readme.md b/src/main/kotlin/g0901_1000/s0913_cat_and_mouse/readme.md new file mode 100644 index 00000000..94d99a18 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0913_cat_and_mouse/readme.md @@ -0,0 +1,136 @@ +[![](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) + +## 913\. Cat and Mouse + +Hard + +A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns. + +The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph. + +The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`. + +During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`. + +Additionally, it is not allowed for the Cat to travel to the Hole (node 0.) + +Then, the game can end in three ways: + +* If ever the Cat occupies the same node as the Mouse, the Cat wins. +* If ever the Mouse reaches the Hole, the Mouse wins. +* If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw. + +Given a `graph`, and assuming both players play optimally, return + +* `1` if the mouse wins the game, +* `2` if the cat wins the game, or +* `0` if the game is a draw. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/17/cat1.jpg) + +**Input:** graph = \[\[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]] + +**Output:** 0 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/11/17/cat2.jpg) + +**Input:** graph = \[\[1,3],[0],[3],[0,2]] + +**Output:** 1 + +**Constraints:** + +* `3 <= graph.length <= 50` +* `1 <= graph[i].length < graph.length` +* `0 <= graph[i][j] < graph.length` +* `graph[i][j] != i` +* `graph[i]` is unique. +* The mouse and the cat can always move. + +## Solution + +```kotlin +import java.util.LinkedList +import java.util.Queue + +class Solution { + fun catMouseGame(graph: Array): Int { + val n = graph.size + val states = Array(n) { + Array(n) { + IntArray( + 2 + ) + } + } + val degree = Array(n) { + Array(n) { + IntArray( + 2 + ) + } + } + for (m in 0 until n) { + for (c in 0 until n) { + degree[m][c][MOUSE] = graph[m].size + degree[m][c][CAT] = graph[c].size + for (node in graph[c]) { + if (node == 0) { + --degree[m][c][CAT] + break + } + } + } + } + val q: Queue = LinkedList() + for (i in 1 until n) { + states[0][i][MOUSE] = MOUSE_WIN + states[0][i][CAT] = MOUSE_WIN + states[i][i][MOUSE] = CAT_WIN + states[i][i][CAT] = CAT_WIN + q.offer(intArrayOf(0, i, MOUSE, MOUSE_WIN)) + q.offer(intArrayOf(i, i, MOUSE, CAT_WIN)) + q.offer(intArrayOf(0, i, CAT, MOUSE_WIN)) + q.offer(intArrayOf(i, i, CAT, CAT_WIN)) + } + while (!q.isEmpty()) { + val state = q.poll() + val mouse = state[0] + val cat = state[1] + val turn = state[2] + val result = state[3] + if (mouse == 1 && cat == 2 && turn == MOUSE) { + return result + } + val prevTurn = 1 - turn + for (prev in graph[if (prevTurn == MOUSE) mouse else cat]) { + val prevMouse = if (prevTurn == MOUSE) prev else mouse + val prevCat = if (prevTurn == CAT) prev else cat + if (prevCat != 0 && states[prevMouse][prevCat][prevTurn] == DRAW && + ( + prevTurn == MOUSE && result == MOUSE_WIN || prevTurn == CAT && result == CAT_WIN || + --degree[prevMouse][prevCat][prevTurn] == 0 + ) + ) { + states[prevMouse][prevCat][prevTurn] = result + q.offer(intArrayOf(prevMouse, prevCat, prevTurn, result)) + } + } + } + return DRAW + } + + companion object { + private const val DRAW = 0 + private const val MOUSE_WIN = 1 + private const val CAT_WIN = 2 + private const val MOUSE = 0 + private const val CAT = 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0914_x_of_a_kind_in_a_deck_of_cards/readme.md b/src/main/kotlin/g0901_1000/s0914_x_of_a_kind_in_a_deck_of_cards/readme.md new file mode 100644 index 00000000..cf18cbc7 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0914_x_of_a_kind_in_a_deck_of_cards/readme.md @@ -0,0 +1,65 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 914\. X of a Kind in a Deck of Cards + +Easy + +You are given an integer array `deck` where `deck[i]` represents the number written on the ith card. + +Partition the cards into **one or more groups** such that: + +* Each group has **exactly** `x` cards where `x > 1`, and +* All the cards in one group have the same integer written on them. + +Return `true` _if such partition is possible, or_ `false` _otherwise_. + +**Example 1:** + +**Input:** deck = [1,2,3,4,4,3,2,1] + +**Output:** true + +**Explanation:**: Possible partition [1,1],[2,2],[3,3],[4,4]. + +**Example 2:** + +**Input:** deck = [1,1,1,2,2,2,3,3] + +**Output:** false + +**Explanation:**: No possible partition. + +**Constraints:** + +* 1 <= deck.length <= 104 +* 0 <= deck[i] < 104 + +## Solution + +```kotlin +class Solution { + fun hasGroupsSizeX(deck: IntArray): Boolean { + val map: HashMap = HashMap() + for (j in deck) { + if (map.containsKey(j)) { + map[j] = map[j]!! + 1 + } else { + map[j] = 1 + } + } + var x = map[deck[0]]!! + + for (entry in map.entries.iterator()) { + x = gcd(x, entry.value) + } + return x >= 2 + } + + private fun gcd(a: Int, b: Int): Int { + return if (b == 0) { + a + } else gcd(b, a % b) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0915_partition_array_into_disjoint_intervals/readme.md b/src/main/kotlin/g0901_1000/s0915_partition_array_into_disjoint_intervals/readme.md new file mode 100644 index 00000000..612712ad --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0915_partition_array_into_disjoint_intervals/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) + +## 915\. Partition Array into Disjoint Intervals + +Medium + +Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: + +* Every element in `left` is less than or equal to every element in `right`. +* `left` and `right` are non-empty. +* `left` has the smallest possible size. + +Return _the length of_ `left` _after such a partitioning_. + +Test cases are generated such that partitioning exists. + +**Example 1:** + +**Input:** nums = [5,0,3,8,6] + +**Output:** 3 + +**Explanation:** left = [5,0,3], right = [8,6] + +**Example 2:** + +**Input:** nums = [1,1,1,0,6,12] + +**Output:** 4 + +**Explanation:** left = [1,1,1,0], right = [6,12] + +**Constraints:** + +* 2 <= nums.length <= 105 +* 0 <= nums[i] <= 106 +* There is at least one valid answer for the given input. + +## Solution + +```kotlin +class Solution { + fun partitionDisjoint(nums: IntArray): Int { + var res = 0 + var leftMax = nums[0] + var greater = nums[0] + for (i in 1 until nums.size) { + if (greater <= nums[i]) { + greater = nums[i] + } else if (nums[i] < leftMax) { + res = i + leftMax = greater + } + } + return res + 1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0916_word_subsets/readme.md b/src/main/kotlin/g0901_1000/s0916_word_subsets/readme.md new file mode 100644 index 00000000..c2be7acc --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0916_word_subsets/readme.md @@ -0,0 +1,73 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 916\. Word Subsets + +Medium + +You are given two string arrays `words1` and `words2`. + +A string `b` is a **subset** of string `a` if every letter in `b` occurs in `a` including multiplicity. + +* For example, `"wrr"` is a subset of `"warrior"` but is not a subset of `"world"`. + +A string `a` from `words1` is **universal** if for every string `b` in `words2`, `b` is a subset of `a`. + +Return an array of all the **universal** strings in `words1`. You may return the answer in **any order**. + +**Example 1:** + +**Input:** words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"] + +**Output:** ["facebook","google","leetcode"] + +**Example 2:** + +**Input:** words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["l","e"] + +**Output:** ["apple","google","leetcode"] + +**Constraints:** + +* 1 <= words1.length, words2.length <= 104 +* `1 <= words1[i].length, words2[i].length <= 10` +* `words1[i]` and `words2[i]` consist only of lowercase English letters. +* All the strings of `words1` are **unique**. + +## Solution + +```kotlin +class Solution { + fun wordSubsets(words1: Array, words2: Array): List { + val l1: MutableList = ArrayList() + val target = IntArray(26) + for (s1 in words2) { + val temp = IntArray(26) + for (ch1 in s1.toCharArray()) { + temp[ch1.code - 'a'.code]++ + target[ch1.code - 'a'.code] = + target[ch1.code - 'a'.code].coerceAtLeast(temp[ch1.code - 'a'.code]) + } + } + for (s1 in words1) { + val count = IntArray(26) + for (ch1 in s1.toCharArray()) { + count[ch1.code - 'a'.code]++ + } + if (checkIt(target, count)) { + l1.add(s1) + } + } + return l1 + } + + private fun checkIt(target: IntArray, count: IntArray): Boolean { + for (i in 0..25) { + if (count[i] < target[i]) { + return false + } + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0917_reverse_only_letters/readme.md b/src/main/kotlin/g0901_1000/s0917_reverse_only_letters/readme.md new file mode 100644 index 00000000..dae3568c --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0917_reverse_only_letters/readme.md @@ -0,0 +1,64 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 917\. Reverse Only Letters + +Easy + +Given a string `s`, reverse the string according to the following rules: + +* All the characters that are not English letters remain in the same position. +* All the English letters (lowercase or uppercase) should be reversed. + +Return `s` _after reversing it_. + +**Example 1:** + +**Input:** s = "ab-cd" + +**Output:** "dc-ba" + +**Example 2:** + +**Input:** s = "a-bC-dEf-ghIj" + +**Output:** "j-Ih-gfE-dCba" + +**Example 3:** + +**Input:** s = "Test1ng-Leet=code-Q!" + +**Output:** "Qedo1ct-eeLg=ntse-T!" + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` consists of characters with ASCII values in the range `[33, 122]`. +* `s` does not contain `'\"'` or `'\\'`. + +## Solution + +```kotlin +class Solution { + fun reverseOnlyLetters(s: String): String { + val array = s.toCharArray() + var i = 0 + var j = array.size - 1 + while (i < j) { + if (Character.isLetter(array[i]) && Character.isLetter(array[j])) { + val temp = array[i] + array[i++] = array[j] + array[j--] = temp + } else if (Character.isLetter(array[i])) { + j-- + } else if (Character.isLetter(array[j])) { + i++ + } else { + i++ + j-- + } + } + return String(array) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray/readme.md b/src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray/readme.md new file mode 100644 index 00000000..8f26384b --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0918_maximum_sum_circular_subarray/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) + +## 918\. Maximum Sum Circular Subarray + +Medium + +Given a **circular integer array** `nums` of length `n`, return _the maximum possible sum of a non-empty **subarray** of_ `nums`. + +A **circular array** means the end of the array connects to the beginning of the array. Formally, the next element of `nums[i]` is `nums[(i + 1) % n]` and the previous element of `nums[i]` is `nums[(i - 1 + n) % n]`. + +A **subarray** may only include each element of the fixed buffer `nums` at most once. Formally, for a subarray `nums[i], nums[i + 1], ..., nums[j]`, there does not exist `i <= k1`, `k2 <= j` with `k1 % n == k2 % n`. + +**Example 1:** + +**Input:** nums = [1,-2,3,-2] + +**Output:** 3 + +**Explanation:** Subarray [3] has maximum sum 3. + +**Example 2:** + +**Input:** nums = [5,-3,5] + +**Output:** 10 + +**Explanation:** Subarray [5,5] has maximum sum 5 + 5 = 10. + +**Example 3:** + +**Input:** nums = [-3,-2,-3] + +**Output:** -2 + +**Explanation:** Subarray [-2] has maximum sum -2. + +**Constraints:** + +* `n == nums.length` +* 1 <= n <= 3 * 104 +* -3 * 104 <= nums[i] <= 3 * 104 + +## Solution + +```kotlin +class Solution { + private fun kadane(nums: IntArray, sign: Int): Int { + var currSum = Int.MIN_VALUE + var maxSum = Int.MIN_VALUE + for (i in nums) { + currSum = sign * i + currSum.coerceAtLeast(0) + maxSum = maxSum.coerceAtLeast(currSum) + } + return maxSum + } + + fun maxSubarraySumCircular(nums: IntArray): Int { + if (nums.size == 1) { + return nums[0] + } + var sumOfArray = 0 + for (i in nums) { + sumOfArray += i + } + val maxSumSubarray = kadane(nums, 1) + val minSumSubarray = kadane(nums, -1) * -1 + return if (sumOfArray == minSumSubarray) { + maxSumSubarray + } else { + maxSumSubarray.coerceAtLeast(sumOfArray - minSumSubarray) + } + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0919_complete_binary_tree_inserter/readme.md b/src/main/kotlin/g0901_1000/s0919_complete_binary_tree_inserter/readme.md new file mode 100644 index 00000000..b2ec288a --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0919_complete_binary_tree_inserter/readme.md @@ -0,0 +1,122 @@ +[![](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) + +## 919\. Complete Binary Tree Inserter + +Medium + +A **complete binary tree** is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. + +Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion. + +Implement the `CBTInserter` class: + +* `CBTInserter(TreeNode root)` Initializes the data structure with the `root` of the complete binary tree. +* `int insert(int v)` Inserts a `TreeNode` into the tree with value `Node.val == val` so that the tree remains complete, and returns the value of the parent of the inserted `TreeNode`. +* `TreeNode get_root()` Returns the root node of the tree. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/08/03/lc-treeinsert.jpg) + +**Input** ["CBTInserter", "insert", "insert", "get\_root"] [[[1, 2]], [3], [4], []] + +**Output:** [null, 1, 2, [1, 2, 3, 4]] + +**Explanation:** + + CBTInserter cBTInserter = new CBTInserter([1, 2]); + cBTInserter.insert(3); // return 1 + cBTInserter.insert(4); // return 2 + cBTInserter.get\_root(); // return [1, 2, 3, 4] + +**Constraints:** + +* The number of nodes in the tree will be in the range `[1, 1000]`. +* `0 <= Node.val <= 5000` +* `root` is a complete binary tree. +* `0 <= val <= 5000` +* At most 104 calls will be made to `insert` and `get_root`. + +## Solution + +```kotlin +import com_github_leetcode.TreeNode +import java.util.LinkedList +import java.util.Queue + +/* + * 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 CBTInserter(root: TreeNode?) { + private val q: Queue + private val head: TreeNode + + init { + q = LinkedList() + head = root!! + addToQueue() + } + + private fun addToQueue() { + val hlq: Queue = LinkedList() + hlq.add(head) + while (!hlq.isEmpty()) { + var size = hlq.size + while (size-- > 0) { + val poll: TreeNode = hlq.poll() + q.add(poll) + if (poll.left != null) { + hlq.add(poll.left) + } + if (poll.right != null) { + hlq.add(poll.right) + } + } + } + } + + fun insert(`val`: Int): Int { + val nn = TreeNode(`val`) + deleteFullNode() + val peek: TreeNode = q.peek() + if (peek.left == null) { + peek.left = nn + } else { + peek.right = nn + } + q.add(nn) + return peek.`val` + } + + private fun deleteFullNode() { + while (!q.isEmpty()) { + val peek: TreeNode = q.peek() + if (peek.left != null && peek.right != null) { + q.poll() + } else { + break + } + } + } + + // get_root() + fun getRoot(): TreeNode { + return head + } +} + +/* + * Your CBTInserter object will be instantiated and called as such: + * var obj = CBTInserter(root) + * var param_1 = obj.insert(`val`) + * var param_2 = obj.get_root() + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0920_number_of_music_playlists/readme.md b/src/main/kotlin/g0901_1000/s0920_number_of_music_playlists/readme.md new file mode 100644 index 00000000..c84b44b0 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0920_number_of_music_playlists/readme.md @@ -0,0 +1,77 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 920\. Number of Music Playlists + +Hard + +Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: + +* Every song is played **at least once**. +* A song can only be played again only if `k` other songs have been played. + +Given `n`, `goal`, and `k`, return _the number of possible playlists that you can create_. Since the answer can be very large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** n = 3, goal = 3, k = 1 + +**Output:** 6 + +**Explanation:** There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1]. + +**Example 2:** + +**Input:** n = 2, goal = 3, k = 0 + +**Output:** 6 + +**Explanation:** There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2]. + +**Example 3:** + +**Input:** n = 2, goal = 3, k = 1 + +**Output:** 2 + +**Explanation:** There are 2 possible playlists: [1, 2, 1] and [2, 1, 2]. + +**Constraints:** + +* `0 <= k < n <= goal <= 100` + +## Solution + +```kotlin +class Solution { + fun numMusicPlaylists(n: Int, l: Int, k: Int): Int { + val dp = Array(l) { LongArray(n + 1) } + for (i in 0 until l) { + dp[i].fill(-1) + } + return helper(0, l, 0, n, k, dp).toInt() + } + + private fun helper(songNumber: Int, l: Int, usedSong: Int, n: Int, k: Int, dp: Array): Long { + if (songNumber == l) { + return if (usedSong == n) 1 else 0 + } + if (dp[songNumber][usedSong] != -1L) { + return dp[songNumber][usedSong] + } + val ans: Long = if (songNumber < k) { + (n - usedSong) * helper(songNumber + 1, l, usedSong + 1, n, k, dp) + } else if (usedSong == n) { + (usedSong - k) * helper(songNumber + 1, l, usedSong, n, k, dp) + } else { + ( + (n - usedSong) * helper(songNumber + 1, l, usedSong + 1, n, k, dp) + + (usedSong - k) * helper(songNumber + 1, l, usedSong, n, k, dp) + ) + } + val mod = 1e9.toInt() + 7 + dp[songNumber][usedSong] = ans % mod + return ans % mod + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0921_minimum_add_to_make_parentheses_valid/readme.md b/src/main/kotlin/g0901_1000/s0921_minimum_add_to_make_parentheses_valid/readme.md new file mode 100644 index 00000000..64005918 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0921_minimum_add_to_make_parentheses_valid/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) + +## 921\. Minimum Add to Make Parentheses Valid + +Medium + +A parentheses string is valid if and only if: + +* It is the empty string, +* It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or +* It can be written as `(A)`, where `A` is a valid string. + +You are given a parentheses string `s`. In one move, you can insert a parenthesis at any position of the string. + +* For example, if `s = "()))"`, you can insert an opening parenthesis to be "(**(**)))" or a closing parenthesis to be "())**)**)". + +Return _the minimum number of moves required to make_ `s` _valid_. + +**Example 1:** + +**Input:** s = "())" + +**Output:** 1 + +**Example 2:** + +**Input:** s = "(((" + +**Output:** 3 + +**Constraints:** + +* `1 <= s.length <= 1000` +* `s[i]` is either `'('` or `')'`. + +## Solution + +```kotlin +import java.util.Deque +import java.util.LinkedList + +class Solution { + fun minAddToMakeValid(s: String): Int { + val stack: Deque = LinkedList() + for (c in s.toCharArray()) { + if (c == ')') { + if (!stack.isEmpty() && stack.peek() == '(') { + stack.pop() + } else { + stack.push(c) + } + } else { + stack.push(c) + } + } + return stack.size + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0922_sort_array_by_parity_ii/readme.md b/src/main/kotlin/g0901_1000/s0922_sort_array_by_parity_ii/readme.md new file mode 100644 index 00000000..83e2f50a --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0922_sort_array_by_parity_ii/readme.md @@ -0,0 +1,62 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 922\. Sort Array By Parity II + +Easy + +Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**. + +Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**. + +Return _any answer array that satisfies this condition_. + +**Example 1:** + +**Input:** nums = [4,2,5,7] + +**Output:** [4,5,2,7] + +**Explanation:** [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. + +**Example 2:** + +**Input:** nums = [2,3] + +**Output:** [2,3] + +**Constraints:** + +* 2 <= nums.length <= 2 * 104 +* `nums.length` is even. +* Half of the integers in `nums` are even. +* `0 <= nums[i] <= 1000` + +**Follow Up:** Could you solve it in-place? + +## Solution + +```kotlin +class Solution { + fun sortArrayByParityII(nums: IntArray): IntArray { + var i = 0 + var j = 1 + while (i < nums.size - 1 && j < nums.size) { + if (nums[i] % 2 != 0 && nums[j] % 2 == 0) { + val tmp = nums[i] + nums[i] = nums[j] + nums[j] = tmp + i += 2 + j += 2 + } + while (i < nums.size - 1 && nums[i] % 2 == 0) { + i += 2 + } + while (j < nums.size && nums[j] % 2 != 0) { + j += 2 + } + } + return nums + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0923_3sum_with_multiplicity/readme.md b/src/main/kotlin/g0901_1000/s0923_3sum_with_multiplicity/readme.md new file mode 100644 index 00000000..fbafee21 --- /dev/null +++ b/src/main/kotlin/g0901_1000/s0923_3sum_with_multiplicity/readme.md @@ -0,0 +1,80 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 923\. 3Sum With Multiplicity + +Medium + +Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`. + +As the answer can be very large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** arr = [1,1,2,2,3,3,4,4,5,5], target = 8 + +**Output:** 20 + +**Explanation:** + + Enumerating by the values (arr[i], arr[j], arr[k]): + (1, 2, 5) occurs 8 times; + (1, 3, 4) occurs 8 times; + (2, 2, 4) occurs 2 times; + (2, 3, 3) occurs 2 times. + +**Example 2:** + +**Input:** arr = [1,1,2,2,2,2], target = 5 + +**Output:** 12 + +**Explanation:** + +arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times: + +We choose one 1 from [1,1] in 2 ways, + +and two 2s from [2,2,2,2] in 6 ways. + +**Constraints:** + +* `3 <= arr.length <= 3000` +* `0 <= arr[i] <= 100` +* `0 <= target <= 300` + +## Solution + +```kotlin +class Solution { + fun threeSumMulti(arr: IntArray, target: Int): Int { + var answer = 0 + val countRight = IntArray(MAX + 1) + for (num in arr) { + ++countRight[num] + } + val countLeft = IntArray(MAX + 1) + for (j in 0 until arr.size - 1) { + --countRight[arr[j]] + val remains = target - arr[j] + if (remains <= 2 * MAX) { + for (v in 0..remains.coerceAtMost(MAX)) { + if (remains - v <= MAX) { + val count = countRight[v] * countLeft[remains - v] + if (count > 0) { + answer = (answer + count) % MOD + } + } + } + } + ++countLeft[arr[j]] + } + return answer + } + + companion object { + private const val MOD = 1e9.toInt() + 7 + private const val MAX = 100 + } +} +``` \ No newline at end of file