diff --git a/README.md b/README.md index fc95b939..6413c5b4 100644 --- a/README.md +++ b/README.md @@ -1816,9 +1816,39 @@ | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- +| 2706 |[Buy Two Chocolates](src/main/kotlin/g2701_2800/s2706_buy_two_chocolates)| Easy | Array, Sorting | 187 | 96.43 +| 2705 |[Compact Object](src/main/kotlin/g2701_2800/s2705_compact_object)| Medium || 78 | 99.38 +| 2704 |[To Be Or Not To Be](src/main/kotlin/g2701_2800/s2704_to_be_or_not_to_be)| Easy || 49 | 97.88 +| 2703 |[Return Length of Arguments Passed](src/main/kotlin/g2701_2800/s2703_return_length_of_arguments_passed)| Easy || 47 | 98.59 +| 2699 |[Modify Graph Edge Weights](src/main/kotlin/g2601_2700/s2699_modify_graph_edge_weights)| Hard | Heap_Priority_Queue, Graph, Shortest_Path | 1592 | 40.00 +| 2698 |[Find the Punishment Number of an Integer](src/main/kotlin/g2601_2700/s2698_find_the_punishment_number_of_an_integer)| Medium | Math, Backtracking | 133 | 100.00 +| 2697 |[Lexicographically Smallest Palindrome](src/main/kotlin/g2601_2700/s2697_lexicographically_smallest_palindrome)| Easy | String, Two_Pointers | 267 | 100.00 +| 2696 |[Minimum String Length After Removing Substrings](src/main/kotlin/g2601_2700/s2696_minimum_string_length_after_removing_substrings)| Easy | String, Stack, Simulation | 185 | 100.00 +| 2695 |[Array Wrapper](src/main/kotlin/g2601_2700/s2695_array_wrapper)| Easy || 40 | 100.00 +| 2694 |[Event Emitter](src/main/kotlin/g2601_2700/s2694_event_emitter)| Medium || 45 | 99.58 +| 2693 |[Call Function with Custom Context](src/main/kotlin/g2601_2700/s2693_call_function_with_custom_context)| Medium | Array, Dynamic_Programming, Matrix | 51 | 97.92 +| 2685 |[Count the Number of Complete Components](src/main/kotlin/g2601_2700/s2685_count_the_number_of_complete_components)| Medium | Array, Dynamic_Programming, Depth_First_Search, Breadth_First_Search, Matrix, Graph | 436 | 100.00 +| 2684 |[Maximum Number of Moves in a Grid](src/main/kotlin/g2601_2700/s2684_maximum_number_of_moves_in_a_grid)| Medium | Array, Dynamic_Programming, Matrix | 542 | 100.00 +| 2683 |[Neighboring Bitwise XOR](src/main/kotlin/g2601_2700/s2683_neighboring_bitwise_xor)| Medium | Array, Bit_Manipulation | 988 | 100.00 +| 2682 |[Find the Losers of the Circular Game](src/main/kotlin/g2601_2700/s2682_find_the_losers_of_the_circular_game)| Easy | Array, Hash_Table, Simulation | 186 | 100.00 +| 2681 |[Power of Heroes](src/main/kotlin/g2601_2700/s2681_power_of_heroes)| Hard | Array, Math, Sorting, Prefix_Sum | 454 | 85.71 +| 2680 |[Maximum OR](src/main/kotlin/g2601_2700/s2680_maximum_or)| Medium | Array, Greedy, Bit_Manipulation, Prefix_Sum | 592 | 90.91 +| 2679 |[Sum in a Matrix](src/main/kotlin/g2601_2700/s2679_sum_in_a_matrix)| Medium | Array, Sorting, Matrix, Heap_Priority_Queue, Simulation | 581 | 100.00 +| 2678 |[Number of Senior Citizens](src/main/kotlin/g2601_2700/s2678_number_of_senior_citizens)| Easy | Array, String | 163 | 96.30 +| 2677 |[Chunk Array](src/main/kotlin/g2601_2700/s2677_chunk_array)| Easy || 55 | 96.89 +| 2673 |[Make Costs of Paths Equal in a Binary Tree](src/main/kotlin/g2601_2700/s2673_make_costs_of_paths_equal_in_a_binary_tree)| Medium | Array, Dynamic_Programming, Greedy, Tree, Binary_Tree | 645 | 75.00 +| 2672 |[Number of Adjacent Elements With the Same Color](src/main/kotlin/g2601_2700/s2672_number_of_adjacent_elements_with_the_same_color)| Medium | Array | 1208 | 100.00 +| 2671 |[Frequency Tracker](src/main/kotlin/g2601_2700/s2671_frequency_tracker)| Medium | Hash_Table, Design | 1109 | 80.00 +| 2670 |[Find the Distinct Difference Array](src/main/kotlin/g2601_2700/s2670_find_the_distinct_difference_array)| Easy | Array, Hash_Table | 320 | 94.74 +| 2667 |[Create Hello World Function](src/main/kotlin/g2601_2700/s2667_create_hello_world_function)| Easy || 52 | 92.72 +| 2666 |[Allow One Function Call](src/main/kotlin/g2601_2700/s2666_allow_one_function_call)| Easy || 53 | 93.29 +| 2665 |[Counter II](src/main/kotlin/g2601_2700/s2665_counter_ii)| Easy || 65 | 86.59 +| 2663 |[Lexicographically Smallest Beautiful String](src/main/kotlin/g2601_2700/s2663_lexicographically_smallest_beautiful_string)| Hard | String, Greedy | 324 | 100.00 +| 2662 |[Minimum Cost of a Path With Special Roads](src/main/kotlin/g2601_2700/s2662_minimum_cost_of_a_path_with_special_roads)| Medium | Array, Heap_Priority_Queue, Graph, Shortest_Path | 690 | 100.00 +| 2661 |[First Completely Painted Row or Column](src/main/kotlin/g2601_2700/s2661_first_completely_painted_row_or_column)| Medium | Array, Hash_Table, Matrix | 901 | 100.00 | 2660 |[Determine the Winner of a Bowling Game](src/main/kotlin/g2601_2700/s2660_determine_the_winner_of_a_bowling_game)| Easy | Array, Simulation | 263 | 85.71 | 2659 |[Make Array Empty](src/main/kotlin/g2601_2700/s2659_make_array_empty)| Hard | Array, Sorting, Greedy, Binary_Search, Ordered_Set, Segment_Tree, Binary_Indexed_Tree | 728 | 100.00 -| 2658 |[Maximum Number of Fish in a Grid](src/main/kotlin/g2601_2700/s2658_maximum_number_of_fish_in_a_grid)| Medium | Array, Matrix, Union_Find, Depth_First_Search, Breadth_First_Search | 269 | 80.00 +| 2658 |[Maximum Number of Fish in a Grid](src/main/kotlin/g2601_2700/s2658_maximum_number_of_fish_in_a_grid)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 269 | 80.00 | 2657 |[Find the Prefix Common Array of Two Arrays](src/main/kotlin/g2601_2700/s2657_find_the_prefix_common_array_of_two_arrays)| Medium | Array, Hash_Table | 288 | 88.89 | 2656 |[Maximum Sum With Exactly K Elements](src/main/kotlin/g2601_2700/s2656_maximum_sum_with_exactly_k_elements)| Easy | Array, Greedy | 241 | 93.94 | 2654 |[Minimum Number of Operations to Make All Array Elements Equal to 1](src/main/kotlin/g2601_2700/s2654_minimum_number_of_operations_to_make_all_array_elements_equal_to_1)| Medium | Array, Math, Number_Theory | 172 | 100.00 @@ -1828,12 +1858,12 @@ | 2650 |[Design Cancellable Function](src/main/kotlin/g2601_2700/s2650_design_cancellable_function)| Hard || 58 | 95.56 | 2649 |[Nested Array Generator](src/main/kotlin/g2601_2700/s2649_nested_array_generator)| Medium || 192 | 70.11 | 2648 |[Generate Fibonacci Sequence](src/main/kotlin/g2601_2700/s2648_generate_fibonacci_sequence)| Easy || 53 | 93.66 -| 2646 |[Minimize the Total Price of the Trips](src/main/kotlin/g2601_2700/s2646_minimize_the_total_price_of_the_trips)| Hard | Array, Dynamic_Programming, Tree, Graph, Depth_First_Search | 264 | 100.00 +| 2646 |[Minimize the Total Price of the Trips](src/main/kotlin/g2601_2700/s2646_minimize_the_total_price_of_the_trips)| Hard | Array, Dynamic_Programming, Depth_First_Search, Tree, Graph | 264 | 100.00 | 2645 |[Minimum Additions to Make Valid String](src/main/kotlin/g2601_2700/s2645_minimum_additions_to_make_valid_string)| Medium | String, Dynamic_Programming, Greedy, Stack | 154 | 100.00 | 2644 |[Find the Maximum Divisibility Score](src/main/kotlin/g2601_2700/s2644_find_the_maximum_divisibility_score)| Easy | Array | 585 | 100.00 | 2643 |[Row With Maximum Ones](src/main/kotlin/g2601_2700/s2643_row_with_maximum_ones)| Easy | Array, Matrix | 530 | 100.00 | 2642 |[Design Graph With Shortest Path Calculator](src/main/kotlin/g2601_2700/s2642_design_graph_with_shortest_path_calculator)| Hard | Design, Heap_Priority_Queue, Graph, Shortest_Path | 789 | 100.00 -| 2641 |[Cousins in Binary Tree II](src/main/kotlin/g2601_2700/s2641_cousins_in_binary_tree_ii)| Medium | Hash_Table, Tree, Binary_Tree, Depth_First_Search, Breadth_First_Search | 922 | 90.91 +| 2641 |[Cousins in Binary Tree II](src/main/kotlin/g2601_2700/s2641_cousins_in_binary_tree_ii)| Medium | Hash_Table, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 922 | 90.91 | 2640 |[Find the Score of All Prefixes of an Array](src/main/kotlin/g2601_2700/s2640_find_the_score_of_all_prefixes_of_an_array)| Medium | Array, Prefix_Sum | 587 | 100.00 | 2639 |[Find the Width of Columns of a Grid](src/main/kotlin/g2601_2700/s2639_find_the_width_of_columns_of_a_grid)| Easy | Array, Matrix | 222 | 100.00 | 2637 |[Promise Time Limit](src/main/kotlin/g2601_2700/s2637_promise_time_limit)| Easy || 64 | 75.36 @@ -1856,11 +1886,11 @@ | 2616 |[Minimize the Maximum Difference of Pairs](src/main/kotlin/g2601_2700/s2616_minimize_the_maximum_difference_of_pairs)| Medium | Array, Greedy, Binary_Search | 556 | 100.00 | 2615 |[Sum of Distances](src/main/kotlin/g2601_2700/s2615_sum_of_distances)| Medium | Array, Hash_Table, Prefix_Sum | 902 | 100.00 | 2614 |[Prime In Diagonal](src/main/kotlin/g2601_2700/s2614_prime_in_diagonal)| Easy | Array, Math, Matrix, Number_Theory | 465 | 100.00 -| 2612 |[Minimum Reverse Operations](src/main/kotlin/g2601_2700/s2612_minimum_reverse_operations)| Hard | Array, Ordered_Set, Breadth_First_Search | 923 | 100.00 +| 2612 |[Minimum Reverse Operations](src/main/kotlin/g2601_2700/s2612_minimum_reverse_operations)| Hard | Array, Breadth_First_Search, Ordered_Set | 923 | 100.00 | 2611 |[Mice and Cheese](src/main/kotlin/g2601_2700/s2611_mice_and_cheese)| Medium | Array, Sorting, Greedy, Heap_Priority_Queue | 554 | 100.00 | 2610 |[Convert an Array Into a 2D Array With Conditions](src/main/kotlin/g2601_2700/s2610_convert_an_array_into_a_2d_array_with_conditions)| Medium | Array, Hash_Table | 240 | 88.24 | 2609 |[Find the Longest Balanced Substring of a Binary String](src/main/kotlin/g2601_2700/s2609_find_the_longest_balanced_substring_of_a_binary_string)| Easy | String | 174 | 100.00 -| 2608 |[Shortest Cycle in a Graph](src/main/kotlin/g2601_2700/s2608_shortest_cycle_in_a_graph)| Hard | Graph, Breadth_First_Search | 1061 | 100.00 +| 2608 |[Shortest Cycle in a Graph](src/main/kotlin/g2601_2700/s2608_shortest_cycle_in_a_graph)| Hard | Breadth_First_Search, Graph | 1061 | 100.00 | 2607 |[Make K-Subarray Sums Equal](src/main/kotlin/g2601_2700/s2607_make_k_subarray_sums_equal)| Medium | Array, Math, Sorting, Number_Theory | 1062 | 100.00 | 2606 |[Find the Substring With Maximum Cost](src/main/kotlin/g2601_2700/s2606_find_the_substring_with_maximum_cost)| Medium | Array, String, Hash_Table, Dynamic_Programming | 238 | 100.00 | 2605 |[Form Smallest Number From Two Digit Arrays](src/main/kotlin/g2601_2700/s2605_form_smallest_number_from_two_digit_arrays)| Easy | Array, Hash_Table, Enumeration | 161 | 100.00 diff --git a/src/main/kotlin/g0001_0100/s0020_valid_parentheses/readme.md b/src/main/kotlin/g0001_0100/s0020_valid_parentheses/readme.md index a2d4f77e..5d3a70a9 100644 --- a/src/main/kotlin/g0001_0100/s0020_valid_parentheses/readme.md +++ b/src/main/kotlin/g0001_0100/s0020_valid_parentheses/readme.md @@ -50,21 +50,19 @@ An input string is valid if: ## Solution ```kotlin -import java.util.Stack - class Solution { fun isValid(s: String): Boolean { - val stack = Stack() + val stack = ArrayDeque() for (element in s) { val c = element if (c == '(' || c == '[' || c == '{') { - stack.push(c) - } else if (c == ')' && stack.isNotEmpty() && stack.peek() == '(') { - stack.pop() - } else if (c == '}' && stack.isNotEmpty() && stack.peek() == '{') { - stack.pop() - } else if (c == ']' && stack.isNotEmpty() && stack.peek() == '[') { - stack.pop() + stack.addLast(c) + } else if (c == ')' && stack.isNotEmpty() && stack.last() == '(') { + stack.removeLast() + } else if (c == '}' && stack.isNotEmpty() && stack.last() == '{') { + stack.removeLast() + } else if (c == ']' && stack.isNotEmpty() && stack.last() == '[') { + stack.removeLast() } else { return false } diff --git a/src/main/kotlin/g0001_0100/s0077_combinations/readme.md b/src/main/kotlin/g0001_0100/s0077_combinations/readme.md index 200f9220..a07ada78 100644 --- a/src/main/kotlin/g0001_0100/s0077_combinations/readme.md +++ b/src/main/kotlin/g0001_0100/s0077_combinations/readme.md @@ -33,8 +33,6 @@ You may return the answer in **any order**. ## Solution ```kotlin -import java.util.Stack - class Solution { fun combine(n: Int, k: Int): List> { val ans: MutableList> = ArrayList() @@ -42,11 +40,11 @@ class Solution { if (n > 20 || k < 1 || k > n) { return ans } - backtrack(ans, n, k, 1, Stack()) + backtrack(ans, n, k, 1, ArrayDeque()) return ans } - private fun backtrack(ans: MutableList>, n: Int, k: Int, s: Int, stack: Stack) { + private fun backtrack(ans: MutableList>, n: Int, k: Int, s: Int, stack: ArrayDeque) { // Base case // If k becomes 0 if (k == 0) { @@ -55,10 +53,10 @@ class Solution { } // Start with s till n-k+1 for (i in s..n - k + 1) { - stack.push(i) + stack.addLast(i) // Update start for recursion and decrease k by 1 backtrack(ans, n, k - 1, i + 1, stack) - stack.pop() + stack.removeLast() } } } diff --git a/src/main/kotlin/g0101_0200/s0144_binary_tree_preorder_traversal/readme.md b/src/main/kotlin/g0101_0200/s0144_binary_tree_preorder_traversal/readme.md index 62a87097..f145278b 100644 --- a/src/main/kotlin/g0101_0200/s0144_binary_tree_preorder_traversal/readme.md +++ b/src/main/kotlin/g0101_0200/s0144_binary_tree_preorder_traversal/readme.md @@ -38,7 +38,6 @@ Given the `root` of a binary tree, return _the preorder traversal of its nodes' ```kotlin import com_github_leetcode.TreeNode -import java.util.Stack /* * Example: @@ -56,15 +55,15 @@ class Solution { if (root == null) { return result } - val stack: Stack = Stack() + val stack: ArrayDeque = ArrayDeque() var current: TreeNode? = root while (current != null || stack.isNotEmpty()) { while (current != null) { result.add(current.`val`) - stack.push(current.right) + stack.addLast(current.right) current = current.left } - current = stack.pop() + current = stack.removeLast() } return result } diff --git a/src/main/kotlin/g0101_0200/s0155_min_stack/readme.md b/src/main/kotlin/g0101_0200/s0155_min_stack/readme.md index da052ead..e74dc81f 100644 --- a/src/main/kotlin/g0101_0200/s0155_min_stack/readme.md +++ b/src/main/kotlin/g0101_0200/s0155_min_stack/readme.md @@ -44,31 +44,28 @@ Implement the `MinStack` class: ## Solution ```kotlin -import java.util.Stack - class MinStack() { - private val stack: Stack> = Stack() + private val stack: ArrayDeque> = ArrayDeque() fun push(x: Int) { val min: Int = if (stack.isEmpty()) x else getMin() - - stack.push(x to minOf(min, x)) + stack.addLast(x to minOf(min, x)) } fun pop() { - stack.pop() + stack.removeLast() } fun top(): Int { return stack - .peek() + .last() .first } fun getMin(): Int { return stack - .peek() + .last() .second } } diff --git a/src/main/kotlin/g0501_0600/s0552_student_attendance_record_ii/readme.md b/src/main/kotlin/g0501_0600/s0552_student_attendance_record_ii/readme.md index 9a7e2d1d..101e5b82 100644 --- a/src/main/kotlin/g0501_0600/s0552_student_attendance_record_ii/readme.md +++ b/src/main/kotlin/g0501_0600/s0552_student_attendance_record_ii/readme.md @@ -45,8 +45,6 @@ Given an integer `n`, return _the **number** of possible attendance records of l ## Solution ```kotlin -import java.util.Arrays - @Suppress("NAME_SHADOWING") class Solution { fun checkRecord(n: Int): Int { @@ -64,7 +62,7 @@ class Solution { ) val e = quickPower(matrix, n - 1) return ( - (Arrays.stream(e[0]).sum() + Arrays.stream(e[1]).sum() + Arrays.stream(e[3]).sum()) % + (e[0].sum() + e[1].sum() + e[3].sum()) % mod ).toInt() } diff --git a/src/main/kotlin/g0601_0700/s0679_24_game/readme.md b/src/main/kotlin/g0601_0700/s0679_24_game/readme.md index 3a807d14..3a3a0363 100644 --- a/src/main/kotlin/g0601_0700/s0679_24_game/readme.md +++ b/src/main/kotlin/g0601_0700/s0679_24_game/readme.md @@ -40,11 +40,10 @@ Return `true` if you can get such expression that evaluates to `24`, and `false` ## Solution ```kotlin -import java.util.Arrays import kotlin.math.abs class Solution { - private fun backtrack(list: DoubleArray, n: Int): Boolean { + private fun backtrack(list: Array, n: Int): Boolean { if (n == 1) { return abs(list[0] - 24) < EPS } @@ -89,7 +88,7 @@ class Solution { } fun judgePoint24(nums: IntArray): Boolean { - val a = Arrays.stream(nums).asDoubleStream().toArray() + val a = nums.map { it.toDouble() }.toTypedArray() return backtrack(a, a.size) } diff --git a/src/main/kotlin/g0701_0800/s0770_basic_calculator_iv/readme.md b/src/main/kotlin/g0701_0800/s0770_basic_calculator_iv/readme.md index 024fe99f..2c0775b3 100644 --- a/src/main/kotlin/g0701_0800/s0770_basic_calculator_iv/readme.md +++ b/src/main/kotlin/g0701_0800/s0770_basic_calculator_iv/readme.md @@ -62,7 +62,6 @@ The format of the output is as follows: ```kotlin import java.util.Collections -import java.util.Stack class Solution { internal inner class Node { @@ -184,10 +183,10 @@ class Solution { return 0 } - private fun helper(numS: Stack, ops: Stack): Node { - val b = numS.pop() - val a = numS.pop() - val op = ops.pop() + private fun helper(numS: ArrayDeque, ops: ArrayDeque): Node { + val b = numS.removeLast() + val a = numS.removeLast() + val op = ops.removeLast() if (op == '*') { return a.mul(b) } else if (op == '+') { @@ -206,8 +205,8 @@ class Solution { vars[evalvarS[i]] = evalintS[i] } val n = expression.length - val numS = Stack() - val ops = Stack() + val numS = ArrayDeque() + val ops = ArrayDeque() var i = 0 while (i < n) { val a = expression[i] @@ -220,12 +219,12 @@ class Solution { } else if (a == '(') { ops.add(a) } else if (a == ')') { - while (ops.peek() != '(') { + while (ops.last() != '(') { numS.add(helper(numS, ops)) } - ops.pop() + ops.removeLast() } else if (a == '+' || a == '-' || a == '*') { - while (ops.isNotEmpty() && getPriority(ops.peek()) >= getPriority(a)) { + while (ops.isNotEmpty() && getPriority(ops.last()) >= getPriority(a)) { numS.add(helper(numS, ops)) } ops.add(a) @@ -235,7 +234,7 @@ class Solution { while (ops.isNotEmpty()) { numS.add(helper(numS, ops)) } - return numS.peek().evaluate(vars).toList() + return numS.last().evaluate(vars).toList() } } ``` \ No newline at end of file diff --git a/src/main/kotlin/g0901_1000/s0954_array_of_doubled_pairs/readme.md b/src/main/kotlin/g0901_1000/s0954_array_of_doubled_pairs/readme.md index 365027c0..7958f004 100644 --- a/src/main/kotlin/g0901_1000/s0954_array_of_doubled_pairs/readme.md +++ b/src/main/kotlin/g0901_1000/s0954_array_of_doubled_pairs/readme.md @@ -36,12 +36,10 @@ Given an integer array of even length `arr`, return `true` _if it is possible to ## Solution ```kotlin -import java.util.Arrays - class Solution { fun canReorderDoubled(arr: IntArray): Boolean { - val max = 0.coerceAtLeast(Arrays.stream(arr).max().asInt) - val min = 0.coerceAtMost(Arrays.stream(arr).min().asInt) + val max = 0.coerceAtLeast(arr.max()) + val min = 0.coerceAtMost(arr.min()) val positive = IntArray(max + 1) val negative = IntArray(-min + 1) for (a in arr) { diff --git a/src/main/kotlin/g1001_1100/s1005_maximize_sum_of_array_after_k_negations/readme.md b/src/main/kotlin/g1001_1100/s1005_maximize_sum_of_array_after_k_negations/readme.md index b3ef16a0..7f1a4249 100644 --- a/src/main/kotlin/g1001_1100/s1005_maximize_sum_of_array_after_k_negations/readme.md +++ b/src/main/kotlin/g1001_1100/s1005_maximize_sum_of_array_after_k_negations/readme.md @@ -46,8 +46,6 @@ Return _the largest possible sum of the array after modifying it in this way_. ## Solution ```kotlin -import java.util.Arrays - @Suppress("NAME_SHADOWING") class Solution { fun largestSumAfterKNegations(nums: IntArray, k: Int): Int { @@ -68,7 +66,7 @@ class Solution { if (k and 1 == 1) { nums[minIndex] *= -1 } - return Arrays.stream(nums).sum() + return nums.sum() } } ``` \ No newline at end of file diff --git a/src/main/kotlin/g1101_1200/s1172_dinner_plate_stacks/readme.md b/src/main/kotlin/g1101_1200/s1172_dinner_plate_stacks/readme.md index 25c96e3d..9934742e 100644 --- a/src/main/kotlin/g1101_1200/s1172_dinner_plate_stacks/readme.md +++ b/src/main/kotlin/g1101_1200/s1172_dinner_plate_stacks/readme.md @@ -69,11 +69,10 @@ Implement the `DinnerPlates` class: ## Solution ```kotlin -import java.util.Stack import java.util.TreeSet class DinnerPlates(private val stackCap: Int) { - private val stacks: MutableList> + private val stacks: MutableList> private val leftIndex: TreeSet init { @@ -84,17 +83,17 @@ class DinnerPlates(private val stackCap: Int) { fun push(`val`: Int) { if (leftIndex.isNotEmpty()) { val i = leftIndex.first() - stacks[i].push(`val`) + stacks[i].addLast(`val`) if (stacks[i].size == stackCap) { leftIndex.remove(i) } return } if (stacks.isEmpty() || stacks[stacks.size - 1].size == stackCap) { - val newStack = Stack() + val newStack = ArrayDeque() stacks.add(newStack) } - stacks[stacks.size - 1].push(`val`) + stacks[stacks.size - 1].addLast(`val`) } fun pop(): Int { @@ -105,7 +104,7 @@ class DinnerPlates(private val stackCap: Int) { leftIndex.remove(stacks.size - 1) stacks.removeAt(stacks.size - 1) } - val `val` = stacks[stacks.size - 1].pop() + val `val` = stacks[stacks.size - 1].removeLast() if (stacks[stacks.size - 1].isEmpty()) { leftIndex.remove(stacks.size - 1) stacks.removeAt(stacks.size - 1) @@ -117,7 +116,7 @@ class DinnerPlates(private val stackCap: Int) { if (stacks.size - 1 >= index) { var `val` = -1 if (stacks[index].isNotEmpty()) { - `val` = stacks[index].pop() + `val` = stacks[index].removeLast() } if (stacks[index].isEmpty() && index == stacks.size - 1) { leftIndex.remove(stacks.size - 1) diff --git a/src/main/kotlin/g1401_1500/s1496_path_crossing/readme.md b/src/main/kotlin/g1401_1500/s1496_path_crossing/readme.md index 889c684d..82af60f5 100644 --- a/src/main/kotlin/g1401_1500/s1496_path_crossing/readme.md +++ b/src/main/kotlin/g1401_1500/s1496_path_crossing/readme.md @@ -37,14 +37,12 @@ Return `true` _if the path crosses itself at any point, that is, if at any time ## Solution ```kotlin -import java.util.Stack - class Solution { fun isPathCrossing(path: String): Boolean { - val visited = Stack() + val visited = ArrayDeque() visited.add(Coord(0, 0)) for (c in path.toCharArray()) { - val last = visited.peek() + val last = visited.last() if (c == 'N') { val nextStep = Coord(last.x, last.y + 1) if (visited.contains(nextStep)) { diff --git a/src/main/kotlin/g1501_1600/s1544_make_the_string_great/readme.md b/src/main/kotlin/g1501_1600/s1544_make_the_string_great/readme.md index b0aef16d..21aea030 100644 --- a/src/main/kotlin/g1501_1600/s1544_make_the_string_great/readme.md +++ b/src/main/kotlin/g1501_1600/s1544_make_the_string_great/readme.md @@ -48,20 +48,18 @@ Return _the string_ after making it good. The answer is guaranteed to be unique ## Solution ```kotlin -import java.util.Stack - class Solution { fun makeGood(s: String): String { - val stack = Stack() + val stack = ArrayDeque() for (element in s) { if (stack.isEmpty()) { stack.add(element) } else { - if (stack.peek().lowercaseChar() == element.lowercaseChar()) { - if (Character.isLowerCase(stack.peek()) && Character.isUpperCase(element)) { - stack.pop() - } else if (Character.isUpperCase(stack.peek()) && Character.isLowerCase(element)) { - stack.pop() + if (stack.last().lowercaseChar() == element.lowercaseChar()) { + if (Character.isLowerCase(stack.last()) && Character.isUpperCase(element)) { + stack.removeLast() + } else if (Character.isUpperCase(stack.last()) && Character.isLowerCase(element)) { + stack.removeLast() } else { stack.add(element) } @@ -72,7 +70,7 @@ class Solution { } val sb = StringBuilder() while (stack.isNotEmpty()) { - sb.append(stack.pop()) + sb.append(stack.removeLast()) } return sb.reverse().toString() } diff --git a/src/main/kotlin/g2601_2700/s2618_check_if_object_instance_of_class/readme.md b/src/main/kotlin/g2601_2700/s2618_check_if_object_instance_of_class/readme.md index b5d128fb..2c3186df 100644 --- a/src/main/kotlin/g2601_2700/s2618_check_if_object_instance_of_class/readme.md +++ b/src/main/kotlin/g2601_2700/s2618_check_if_object_instance_of_class/readme.md @@ -63,7 +63,7 @@ function checkIfInstanceOf(obj: any, classFunction: any): boolean { return false } -/** +/* * checkIfInstanceOf(new Date(), Date); // true */ diff --git a/src/main/kotlin/g2601_2700/s2619_array_prototype_last/readme.md b/src/main/kotlin/g2601_2700/s2619_array_prototype_last/readme.md index c646e742..6a191034 100644 --- a/src/main/kotlin/g2601_2700/s2619_array_prototype_last/readme.md +++ b/src/main/kotlin/g2601_2700/s2619_array_prototype_last/readme.md @@ -42,7 +42,7 @@ Array.prototype.last = function (): T | -1 { //NOSONAR return this.length ? this.at(-1) : -1 } -/** +/* * const arr = [1, 2, 3]; * arr.last(); // 3 */ diff --git a/src/main/kotlin/g2601_2700/s2620_counter/readme.md b/src/main/kotlin/g2601_2700/s2620_counter/readme.md index f353ac1e..03dcfa40 100644 --- a/src/main/kotlin/g2601_2700/s2620_counter/readme.md +++ b/src/main/kotlin/g2601_2700/s2620_counter/readme.md @@ -45,7 +45,7 @@ function createCounter(n: number): () => number { return fun } -/** +/* * const counter = createCounter(10) * counter() // 10 * counter() // 11 diff --git a/src/main/kotlin/g2601_2700/s2621_sleep/readme.md b/src/main/kotlin/g2601_2700/s2621_sleep/readme.md index 0420bd24..bda25508 100644 --- a/src/main/kotlin/g2601_2700/s2621_sleep/readme.md +++ b/src/main/kotlin/g2601_2700/s2621_sleep/readme.md @@ -36,7 +36,7 @@ async function sleep(millis: number): Promise { }) } -/** +/* * let t = Date.now() * sleep(100).then(() => console.log(Date.now() - t)) // 100 */ diff --git a/src/main/kotlin/g2601_2700/s2622_cache_with_time_limit/readme.md b/src/main/kotlin/g2601_2700/s2622_cache_with_time_limit/readme.md index a4621b74..497bf7d8 100644 --- a/src/main/kotlin/g2601_2700/s2622_cache_with_time_limit/readme.md +++ b/src/main/kotlin/g2601_2700/s2622_cache_with_time_limit/readme.md @@ -93,7 +93,7 @@ class TimeLimitedCache { } } -/** +/* * Your TimeLimitedCache object will be instantiated and called as such: * var obj = new TimeLimitedCache() * obj.set(1, 42, 1000); // false diff --git a/src/main/kotlin/g2601_2700/s2623_memoize/readme.md b/src/main/kotlin/g2601_2700/s2623_memoize/readme.md index 984a981c..bad573bc 100644 --- a/src/main/kotlin/g2601_2700/s2623_memoize/readme.md +++ b/src/main/kotlin/g2601_2700/s2623_memoize/readme.md @@ -96,7 +96,7 @@ function memoize(fn: Fn): Fn { } } -/** +/* * let callCount = 0; * const memoizedFn = memoize(function (a, b) { * callCount += 1; diff --git a/src/main/kotlin/g2601_2700/s2624_snail_traversal/readme.md b/src/main/kotlin/g2601_2700/s2624_snail_traversal/readme.md index 36d025cf..ba979b46 100644 --- a/src/main/kotlin/g2601_2700/s2624_snail_traversal/readme.md +++ b/src/main/kotlin/g2601_2700/s2624_snail_traversal/readme.md @@ -68,7 +68,7 @@ Array.prototype.snail = function (rowsCount: number, colsCount: number): number[ return res } -/** +/* * const arr = [1,2,3,4]; * arr.snail(1,4); // [[1,2,3,4]] */ diff --git a/src/main/kotlin/g2601_2700/s2627_debounce/readme.md b/src/main/kotlin/g2601_2700/s2627_debounce/readme.md index be864a86..dfee5497 100644 --- a/src/main/kotlin/g2601_2700/s2627_debounce/readme.md +++ b/src/main/kotlin/g2601_2700/s2627_debounce/readme.md @@ -95,7 +95,7 @@ function debounce(fn: F, t: number): F { } } -/** +/* * const log = debounce(console.log, 100); * log('Hello'); // cancelled * log('Hello'); // cancelled diff --git a/src/main/kotlin/g2601_2700/s2629_function_composition/readme.md b/src/main/kotlin/g2601_2700/s2629_function_composition/readme.md index 0723a25f..5ad56402 100644 --- a/src/main/kotlin/g2601_2700/s2629_function_composition/readme.md +++ b/src/main/kotlin/g2601_2700/s2629_function_composition/readme.md @@ -79,7 +79,7 @@ function compose(functions: F[]): F { } } -/** +/* * const fn = compose([x => x + 1, x => 2 * x]) * fn(4) // 9 */ diff --git a/src/main/kotlin/g2601_2700/s2630_memoize_ii/readme.md b/src/main/kotlin/g2601_2700/s2630_memoize_ii/readme.md index c28899ab..12ed244e 100644 --- a/src/main/kotlin/g2601_2700/s2630_memoize_ii/readme.md +++ b/src/main/kotlin/g2601_2700/s2630_memoize_ii/readme.md @@ -111,7 +111,7 @@ function memoize(fn: Fn): Fn { } } -/** +/* * let callCount = 0; * const memoizedFn = memoize(function (a, b) { * callCount += 1; diff --git a/src/main/kotlin/g2601_2700/s2631_group_by/readme.md b/src/main/kotlin/g2601_2700/s2631_group_by/readme.md index a01b1859..788974cc 100644 --- a/src/main/kotlin/g2601_2700/s2631_group_by/readme.md +++ b/src/main/kotlin/g2601_2700/s2631_group_by/readme.md @@ -116,7 +116,7 @@ Array.prototype.groupBy = function (fn: (item: T) => string) { //NOSONAR return returnObject } -/** +/* * [1,2,3].groupBy(String) // {"1":[1],"2":[2],"3":[3]} */ diff --git a/src/main/kotlin/g2601_2700/s2637_promise_time_limit/readme.md b/src/main/kotlin/g2601_2700/s2637_promise_time_limit/readme.md index e230f532..432b2b64 100644 --- a/src/main/kotlin/g2601_2700/s2637_promise_time_limit/readme.md +++ b/src/main/kotlin/g2601_2700/s2637_promise_time_limit/readme.md @@ -116,7 +116,7 @@ function timeLimit(fn: Fn, t: number): Fn { } } -/** +/* * const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100); * limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms */ diff --git a/src/main/kotlin/g2601_2700/s2661_first_completely_painted_row_or_column/readme.md b/src/main/kotlin/g2601_2700/s2661_first_completely_painted_row_or_column/readme.md new file mode 100644 index 00000000..bb36debc --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2661_first_completely_painted_row_or_column/readme.md @@ -0,0 +1,72 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2661\. First Completely Painted Row or Column + +Medium + +You are given a **0-indexed** integer array `arr`, and an `m x n` integer **matrix** `mat`. `arr` and `mat` both contain **all** the integers in the range `[1, m * n]`. + +Go through each index `i` in `arr` starting from index `0` and paint the cell in `mat` containing the integer `arr[i]`. + +Return _the smallest index_ `i` _at which either a row or a column will be completely painted in_ `mat`. + +**Example 1:** + +![](image explanation for example 1)![image explanation for example 1](https://assets.leetcode.com/uploads/2023/01/18/grid1.jpg) + +**Input:** arr = [1,3,4,2], mat = \[\[1,4],[2,3]] + +**Output:** 2 + +**Explanation:** The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2]. + +**Example 2:** + +![image explanation for example 2](https://assets.leetcode.com/uploads/2023/01/18/grid2.jpg) + +**Input:** arr = [2,8,7,4,1,3,5,6,9], mat = \[\[3,2,5],[1,4,6],[8,7,9]] + +**Output:** 3 + +**Explanation:** The second column becomes fully painted at arr[3]. + +**Constraints:** + +* `m == mat.length` +* `n = mat[i].length` +* `arr.length == m * n` +* 1 <= m, n <= 105 +* 1 <= m * n <= 105 +* `1 <= arr[i], mat[r][c] <= m * n` +* All the integers of `arr` are **unique**. +* All the integers of `mat` are **unique**. + +## Solution + +```kotlin +class Solution { + fun firstCompleteIndex(arr: IntArray, mat: Array): Int { + val map: HashMap = HashMap() + var ans = mat.size * mat[0].size + for (i in arr.indices) { + map.put(arr[i], i) + } + for (i in mat.indices) { + var maxV = 0 + for (j in mat[0].indices) { + maxV = maxV.coerceAtLeast(map[mat[i][j]]!!) + } + ans = ans.coerceAtMost(maxV) + } + for (i in mat[0].indices) { + var maxV = 0 + for (j in mat.indices) { + maxV = maxV.coerceAtLeast(map[mat[j][i]]!!) + } + ans = ans.coerceAtMost(maxV) + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2662_minimum_cost_of_a_path_with_special_roads/readme.md b/src/main/kotlin/g2601_2700/s2662_minimum_cost_of_a_path_with_special_roads/readme.md new file mode 100644 index 00000000..c6374d89 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2662_minimum_cost_of_a_path_with_special_roads/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) + +## 2662\. Minimum Cost of a Path With Special Roads + +Medium + +You are given an array `start` where `start = [startX, startY]` represents your initial position `(startX, startY)` in a 2D space. You are also given the array `target` where `target = [targetX, targetY]` represents your target position `(targetX, targetY)`. + +The cost of going from a position `(x1, y1)` to any other position in the space `(x2, y2)` is `|x2 - x1| + |y2 - y1|`. + +There are also some special roads. You are given a 2D array `specialRoads` where specialRoads[i] = [x1i, y1i, x2i, y2i, costi] indicates that the ith special road can take you from (x1i, y1i) to (x2i, y2i) with a cost equal to costi. You can use each special road any number of times. + +Return _the minimum cost required to go from_ `(startX, startY)` to `(targetX, targetY)`. + +**Example 1:** + +**Input:** start = [1,1], target = [4,5], specialRoads = \[\[1,2,3,3,2],[3,4,4,5,1]] + +**Output:** 5 + +**Explanation:** The optimal path from (1,1) to (4,5) is the following: +- (1,1) -> (1,2). This move has a cost of \|1 - 1\| + \|2 - 1\| = 1. +- (1,2) -> (3,3). This move uses the first special edge, the cost is 2. +- (3,3) -> (3,4). This move has a cost of \|3 - 3\| + \|4 - 3\| = 1. +- (3,4) -> (4,5). This move uses the second special edge, the cost is 1. + +So the total cost is 1 + 2 + 1 + 1 = 5. + +It can be shown that we cannot achieve a smaller total cost than 5. + +**Example 2:** + +**Input:** start = [3,2], target = [5,7], specialRoads = \[\[3,2,3,4,4],[3,3,5,5,5],[3,4,5,6,6]] + +**Output:** 7 + +**Explanation:** It is optimal to not use any special edges and go directly from the starting to the ending position with a cost \|5 - 3\| + \|7 - 2\| = 7. + +**Constraints:** + +* `start.length == target.length == 2` +* 1 <= startX <= targetX <= 105 +* 1 <= startY <= targetY <= 105 +* `1 <= specialRoads.length <= 200` +* `specialRoads[i].length == 5` +* startX <= x1i, x2i <= targetX +* startY <= y1i, y2i <= targetY +* 1 <= costi <= 105 + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + fun minimumCost(start: IntArray, target: IntArray, specialRoads: Array): Int { + val pointList = mutableListOf() + val costMap = HashMap, Int>() + val distMap = HashMap() + val sp = Point(start[0], start[1]) + distMap[sp] = 0 + for (road in specialRoads) { + val p = Point(road[0], road[1]) + val q = Point(road[2], road[3]) + val cost = road[4] + if (costMap.getOrDefault(Pair(p, q), Int.MAX_VALUE) > cost) { + costMap[Pair(p, q)] = cost + } + pointList.add(p) + pointList.add(q) + distMap[p] = Int.MAX_VALUE + distMap[q] = Int.MAX_VALUE + } + val tp = Point(target[0], target[1]) + pointList.add(tp) + distMap[tp] = Int.MAX_VALUE + val points = pointList.distinct() + val pq = PriorityQueue() + pq.offer(PointWithCost(sp, 0)) + while (pq.isNotEmpty()) { + val curr = pq.poll() + val cost = curr.cost + val cp = curr.p + if (cp == tp) return cost + for (np in points) { + if (cp == np) continue + var nextCost = cost + dist(cp, np) + if (costMap.containsKey(Pair(cp, np))) { + nextCost = nextCost.coerceAtMost(cost + costMap[Pair(cp, np)]!!) + } + if (nextCost < distMap[np]!!) { + distMap[np] = nextCost + pq.offer(PointWithCost(np, nextCost)) + } + } + } + return -1 + } + + fun dist(sp: Point, tp: Point): Int { + return kotlin.math.abs(sp.x - tp.x) + kotlin.math.abs(sp.y - tp.y) + } +} + +data class Point(val x: Int, val y: Int) + +data class PointWithCost(val p: Point, val cost: Int) : Comparable { + override fun compareTo(other: PointWithCost) = compareValuesBy(this, other) { it.cost } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2663_lexicographically_smallest_beautiful_string/readme.md b/src/main/kotlin/g2601_2700/s2663_lexicographically_smallest_beautiful_string/readme.md new file mode 100644 index 00000000..e0d78ce5 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2663_lexicographically_smallest_beautiful_string/readme.md @@ -0,0 +1,83 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2663\. Lexicographically Smallest Beautiful String + +Hard + +A string is **beautiful** if: + +* It consists of the first `k` letters of the English lowercase alphabet. +* It does not contain any substring of length `2` or more which is a palindrome. + +You are given a beautiful string `s` of length `n` and a positive integer `k`. + +Return _the lexicographically smallest string of length_ `n`_, which is larger than_ `s` _and is **beautiful**_. If there is no such string, return an empty string. + +A string `a` is lexicographically larger than a string `b` (of the same length) if in the first position where `a` and `b` differ, `a` has a character strictly larger than the corresponding character in `b`. + +* For example, `"abcd"` is lexicographically larger than `"abcc"` because the first position they differ is at the fourth character, and `d` is greater than `c`. + +**Example 1:** + +**Input:** s = "abcz", k = 26 + +**Output:** "abda" + +**Explanation:** + +The string "abda" is beautiful and lexicographically larger than the string "abcz". + +It can be proven that there is no string that is lexicographically larger than the string "abcz", beautiful, and lexicographically smaller than the string "abda". + +**Example 2:** + +**Input:** s = "dc", k = 4 + +**Output:** "" + +**Explanation:** It can be proven that there is no string that is lexicographically larger than the string "dc" and is beautiful. + +**Constraints:** + +* 1 <= n == s.length <= 105 +* `4 <= k <= 26` +* `s` is a beautiful string. + +## Solution + +```kotlin +class Solution { + fun smallestBeautifulString(s: String, k: Int): String { + val n = s.length + val charr = s.toCharArray() + for (i in n - 1 downTo 0) { + ++charr[i] + var canbuild = true + if (charr[i] > 'a' + k - 1) continue + while (!isValid(charr, i)) { + ++charr[i] + if (charr[i] > 'a' + k - 1) { + canbuild = false + break + } + } + if (!canbuild) continue + for (j in i + 1 until n) { + charr[j] = 'a' + while (!isValid(charr, j)) { + ++charr[j] + } + } + return StringBuilder().append(charr).toString() + } + return "" + } + + private fun isValid(s: CharArray, i: Int): Boolean { + if (i - 1 >= 0 && s[i - 1] == s[i]) return false + if (i - 2 >= 0 && s[i - 2] == s[i]) return false + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2665_counter_ii/readme.md b/src/main/kotlin/g2601_2700/s2665_counter_ii/readme.md new file mode 100644 index 00000000..9f5deb33 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2665_counter_ii/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) + +## 2665\. Counter II + +Easy + +Write a function `createCounter`. It should accept an initial integer `init`. It should return an object with three functions. + +The three functions are: + +* `increment()` increases the current value by 1 and then returns it. +* `decrement()` reduces the current value by 1 and then returns it. +* `reset()` sets the current value to `init` and then returns it. + +**Example 1:** + +**Input:** init = 5, calls = ["increment","reset","decrement"] + +**Output:** [6,5,4] + +**Explanation:** + + const counter = createCounter(5); + counter.increment(); // 6 + counter.reset(); // 5 + counter.decrement(); // 4 + +**Example 2:** + +**Input:** init = 0, calls = ["increment","increment","decrement","reset","reset"] + +**Output:** [1,2,1,0,0] + +**Explanation:** + + const counter = createCounter(0); + counter.increment(); // 1 + counter.increment(); // 2 + counter.decrement(); // 1 + counter.reset(); // 0 + counter.reset(); // 0 + +**Constraints:** + +* `-1000 <= init <= 1000` +* `total calls not to exceed 1000` + +## Solution + +```typescript +type ReturnObj = { + increment: () => number + decrement: () => number + reset: () => number +} + +function createCounter(init: number): ReturnObj { + let n = init + return { + increment: () => { + n = n + 1 + return n + }, + decrement: () => { + n = n - 1 + return n + }, + reset: () => { + n = init + return n + }, + } +} + +/* + * const counter = createCounter(5) + * counter.increment(); // 6 + * counter.reset(); // 5 + * counter.decrement(); // 4 + */ + +export { createCounter } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2666_allow_one_function_call/readme.md b/src/main/kotlin/g2601_2700/s2666_allow_one_function_call/readme.md new file mode 100644 index 00000000..1bc35e01 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2666_allow_one_function_call/readme.md @@ -0,0 +1,68 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2666\. Allow One Function Call + +Easy + +Given a function `fn`, return a new function that is identical to the original function except that it ensures `fn` is called at most once. + +* The first time the returned function is called, it should return the same result as `fn`. +* Every subsequent time it is called, it should return `undefined`. + +**Example 1:** + +**Input:** fn = (a,b,c) => (a + b + c), calls = \[\[1,2,3],[2,3,6]] + +**Output:** [{"calls":1,"value":6}] + +**Explanation:** + + const onceFn = once(fn); + onceFn(1, 2, 3); // 6 + onceFn(2, 3, 6); // undefined, fn was not called + +**Example 2:** + +**Input:** fn = (a,b,c) => (a \* b \* c), calls = \[\[5,7,4],[2,3,6],[4,6,8]] + +**Output:** [{"calls":1,"value":140}] + +**Explanation:** + + const onceFn = once(fn); + onceFn(5, 7, 4); // 140 + onceFn(2, 3, 6); // undefined, fn was not called + onceFn(4, 6, 8); // undefined, fn was not called + +**Constraints:** + +* `1 <= calls.length <= 10` +* `1 <= calls[i].length <= 100` +* `2 <= JSON.stringify(calls).length <= 1000` + +## Solution + +```typescript +function once any>(fn: T): (...args: Parameters) => ReturnType | undefined { + let hasRun: boolean + return function (...args: T[]): ReturnType | undefined { + if (!hasRun) { + hasRun = true + return fn(...args) + } else { + return undefined + } + } +} + +/* + * let fn = (a,b,c) => (a + b + c) + * let onceFn = once(fn) + * + * onceFn(1,2,3); // 6 + * onceFn(2,3,6); // returns undefined without calling fn + */ + +export { once } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2667_create_hello_world_function/readme.md b/src/main/kotlin/g2601_2700/s2667_create_hello_world_function/readme.md new file mode 100644 index 00000000..596e02b2 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2667_create_hello_world_function/readme.md @@ -0,0 +1,55 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2667\. Create Hello World Function + +Easy + +Write a function `createHelloWorld`. It should return a new function that always returns `"Hello World"`. + +**Example 1:** + +**Input:** args = [] + +**Output:** "Hello World" + +**Explanation:** + + const f = createHelloWorld(); + f(); // "Hello World" + +The function returned by createHelloWorld should always return "Hello World". + +**Example 2:** + +**Input:** args = [{},null,42] + +**Output:** "Hello World" + +**Explanation:** + + const f = createHelloWorld(); + f({}, null, 42); // "Hello World" + +Any arguments could be passed to the function but it should still always return "Hello World". + +**Constraints:** + +* `0 <= args.length <= 10` + +## Solution + +```typescript +function createHelloWorld() { + return function (...args): string { + return 'Hello World' + } +} + +/* + * const f = createHelloWorld(); + * f(); // "Hello World" + */ + +export { createHelloWorld } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2670_find_the_distinct_difference_array/readme.md b/src/main/kotlin/g2601_2700/s2670_find_the_distinct_difference_array/readme.md new file mode 100644 index 00000000..aad4a8d3 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2670_find_the_distinct_difference_array/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) + +## 2670\. Find the Distinct Difference Array + +Easy + +You are given a **0-indexed** array `nums` of length `n`. + +The **distinct difference** array of `nums` is an array `diff` of length `n` such that `diff[i]` is equal to the number of distinct elements in the suffix `nums[i + 1, ..., n - 1]` **subtracted from** the number of distinct elements in the prefix `nums[0, ..., i]`. + +Return _the **distinct difference** array of_ `nums`. + +Note that `nums[i, ..., j]` denotes the subarray of `nums` starting at index `i` and ending at index `j` inclusive. Particularly, if `i > j` then `nums[i, ..., j]` denotes an empty subarray. + +**Example 1:** + +**Input:** nums = [1,2,3,4,5] + +**Output:** [-3,-1,1,3,5] + +**Explanation:** + +For index i = 0, there is 1 element in the prefix and 4 distinct elements in the suffix. Thus, diff[0] = 1 - 4 = -3. + +For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. + +For index i = 2, there are 3 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 3 - 2 = 1. + +For index i = 3, there are 4 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 4 - 1 = 3. + +For index i = 4, there are 5 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 5 - 0 = 5. + +**Example 2:** + +**Input:** nums = [3,2,3,4,2] + +**Output:** [-2,-1,0,2,3] + +**Explanation:** + +For index i = 0, there is 1 element in the prefix and 3 distinct elements in the suffix. Thus, diff[0] = 1 - 3 = -2. + +For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. + +For index i = 2, there are 2 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 2 - 2 = 0. + +For index i = 3, there are 3 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 3 - 1 = 2. + +For index i = 4, there are 3 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 3 - 0 = 3. + +**Constraints:** + +* `1 <= n == nums.length <= 50` +* `1 <= nums[i] <= 50` + +## Solution + +```kotlin +class Solution { + fun distinctDifferenceArray(nums: IntArray): IntArray { + val n = nums.size + val prefixSet = HashSet() + val suffixSet = HashSet() + val preList = IntArray(n) + val sufList = IntArray(n) + val ans = IntArray(n) + for (i in 0..nums.lastIndex) { + prefixSet.add(nums[i]) + suffixSet.add(nums[n - 1 - i]) + preList[i] = prefixSet.size + sufList[n - 1 - i] = suffixSet.size + } + for (i in 0..nums.lastIndex) { + if (i == nums.lastIndex) { + ans[i] = preList[i] + } else { + ans[i] = preList[i] - sufList[i + 1] + } + } + return ans + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2671_frequency_tracker/readme.md b/src/main/kotlin/g2601_2700/s2671_frequency_tracker/readme.md new file mode 100644 index 00000000..22906b81 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2671_frequency_tracker/readme.md @@ -0,0 +1,93 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2671\. Frequency Tracker + +Medium + +Design a data structure that keeps track of the values in it and answers some queries regarding their frequencies. + +Implement the `FrequencyTracker` class. + +* `FrequencyTracker()`: Initializes the `FrequencyTracker` object with an empty array initially. +* `void add(int number)`: Adds `number` to the data structure. +* `void deleteOne(int number)`: Deletes **one** occurrence of `number` from the data structure. The data structure **may not contain** `number`, and in this case nothing is deleted. +* `bool hasFrequency(int frequency)`: Returns `true` if there is a number in the data structure that occurs `frequency` number of times, otherwise, it returns `false`. + +**Example 1:** + +**Input** ["FrequencyTracker", "add", "add", "hasFrequency"] [[], [3], [3], [2]] + +**Output:** [null, null, null, true] + +**Explanation:** + + FrequencyTracker frequencyTracker = new FrequencyTracker(); + frequencyTracker.add(3); // The data structure now contains [3] + frequencyTracker.add(3); // The data structure now contains [3, 3] + frequencyTracker.hasFrequency(2); // Returns true, because 3 occurs twice + +**Example 2:** + +**Input** ["FrequencyTracker", "add", "deleteOne", "hasFrequency"] [[], [1], [1], [1]] + +**Output:** [null, null, null, false] + +**Explanation:** + + FrequencyTracker frequencyTracker = new FrequencyTracker(); + frequencyTracker.add(1); // The data structure now contains [1] + frequencyTracker.deleteOne(1); // The data structure becomes empty [] + frequencyTracker.hasFrequency(1); // Returns false, because the data structure is empty + +**Example 3:** + +**Input** ["FrequencyTracker", "hasFrequency", "add", "hasFrequency"] [[], [2], [3], [1]] + +**Output:** [null, false, null, true] + +**Explanation:** + + FrequencyTracker frequencyTracker = new FrequencyTracker(); + frequencyTracker.hasFrequency(2); // Returns false, because the data structure is empty + frequencyTracker.add(3); // The data structure now contains [3] + frequencyTracker.hasFrequency(1); // Returns true, because 3 occurs once + +**Constraints:** + +* 1 <= number <= 105 +* 1 <= frequency <= 105 +* At most, 2 * 105 calls will be made to `add`, `deleteOne`, and `hasFrequency` in **total**. + +## Solution + +```kotlin +class FrequencyTracker() { + private val count = IntArray(100001) + private val freq = IntArray(100001) + + fun add(number: Int) { + val curFreq = ++count[number] + freq[curFreq - 1]-- + freq[curFreq]++ + } + + fun deleteOne(number: Int) { + if (count[number] > 0) { + val curFreq = --count[number] + freq[curFreq + 1]-- + freq[curFreq]++ + } + } + + fun hasFrequency(frequency: Int) = freq[frequency] > 0 +} + +/* + * Your FrequencyTracker object will be instantiated and called as such: + * var obj = FrequencyTracker() + * obj.add(number) + * obj.deleteOne(number) + * var param_3 = obj.hasFrequency(frequency) + */ +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2672_number_of_adjacent_elements_with_the_same_color/readme.md b/src/main/kotlin/g2601_2700/s2672_number_of_adjacent_elements_with_the_same_color/readme.md new file mode 100644 index 00000000..04c2452b --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2672_number_of_adjacent_elements_with_the_same_color/readme.md @@ -0,0 +1,68 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2672\. Number of Adjacent Elements With the Same Color + +Medium + +There is a **0-indexed** array `nums` of length `n`. Initially, all elements are **uncolored** (has a value of `0`). + +You are given a 2D integer array `queries` where queries[i] = [indexi, colori]. + +For each query, you color the index indexi with the color colori in the array `nums`. + +Return _an array_ `answer` _of the same length as_ `queries` _where_ `answer[i]` _is the number of adjacent elements with the same color **after** the_ ith _query_. + +More formally, `answer[i]` is the number of indices `j`, such that `0 <= j < n - 1` and `nums[j] == nums[j + 1]` and `nums[j] != 0` after the ith query. + +**Example 1:** + +**Input:** n = 4, queries = \[\[0,2],[1,2],[3,1],[1,1],[2,1]] + +**Output:** [0,1,1,0,2] + +**Explanation:** Initially array nums = [0,0,0,0], where 0 denotes uncolored elements of the array. +- After the 1st query nums = [2,0,0,0]. The count of adjacent elements with the same color is 0. +- After the 2nd query nums = [2,2,0,0]. The count of adjacent elements with the same color is 1. +- After the 3rd query nums = [2,2,0,1]. The count of adjacent elements with the same color is 1. +- After the 4th query nums = [2,1,0,1]. The count of adjacent elements with the same color is 0. +- After the 5th query nums = [2,1,1,1]. The count of adjacent elements with the same color is 2. + +**Example 2:** + +**Input:** n = 1, queries = \[\[0,100000]] + +**Output:** [0] + +**Explanation:** Initially array nums = [0], where 0 denotes uncolored elements of the array. +- After the 1st query nums = [100000]. The count of adjacent elements with the same color is 0. + +**Constraints:** + +* 1 <= n <= 105 +* 1 <= queries.length <= 105 +* `queries[i].length == 2` +* 0 <= indexi <= n - 1 +* 1 <= colori <= 105 + +## Solution + +```kotlin +class Solution { + fun colorTheArray(n: Int, queries: Array): IntArray { + val nums = IntArray(n) + val res = IntArray(queries.size) + var count = 0 + for ((i, q) in queries.withIndex()) { + val (e, c) = q + if (e > 0 && nums[e] != 0 && nums[e - 1] == nums[e]) count-- + if (e < n - 1 && nums[e] != 0 && nums[e + 1] == nums[e]) count-- + nums[e] = c + if (e > 0 && nums[e] != 0 && nums[e - 1] == nums[e]) count++ + if (e < n - 1 && nums[e] != 0 && nums[e + 1] == nums[e]) count++ + res[i] = count + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2673_make_costs_of_paths_equal_in_a_binary_tree/readme.md b/src/main/kotlin/g2601_2700/s2673_make_costs_of_paths_equal_in_a_binary_tree/readme.md new file mode 100644 index 00000000..69817122 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2673_make_costs_of_paths_equal_in_a_binary_tree/readme.md @@ -0,0 +1,70 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2673\. Make Costs of Paths Equal in a Binary Tree + +Medium + +You are given an integer `n` representing the number of nodes in a **perfect binary tree** consisting of nodes numbered from `1` to `n`. The root of the tree is node `1` and each node `i` in the tree has two children where the left child is the node `2 * i` and the right child is `2 * i + 1`. + +Each node in the tree also has a **cost** represented by a given **0-indexed** integer array `cost` of size `n` where `cost[i]` is the cost of node `i + 1`. You are allowed to **increment** the cost of **any** node by `1` **any** number of times. + +Return _the **minimum** number of increments you need to make the cost of paths from the root to each **leaf** node equal_. + +**Note**: + +* A **perfect binary tree** is a tree where each node, except the leaf nodes, has exactly 2 children. +* The **cost of a path** is the sum of costs of nodes in the path. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/04/04/binaryytreeedrawio-4.png) + +**Input:** n = 7, cost = [1,5,2,2,3,3,1] + +**Output:** 6 + +**Explanation:** We can do the following increments: +- Increase the cost of node 4 one time. +- Increase the cost of node 3 three times. +- Increase the cost of node 7 two times. + +Each path from the root to a leaf will have a total cost of 9. + +The total increments we did is 1 + 3 + 2 = 6. +It can be shown that this is the minimum answer we can achieve. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/04/04/binaryytreee2drawio.png) + +**Input:** n = 3, cost = [5,3,3] + +**Output:** 0 + +**Explanation:** The two paths already have equal total costs, so no increments are needed. + +**Constraints:** + +* 3 <= n <= 105 +* `n + 1` is a power of `2` +* `cost.length == n` +* 1 <= cost[i] <= 104 + +## Solution + +```kotlin +class Solution { + fun minIncrements(n: Int, cost: IntArray): Int { + val last = n / 2 - 1 + var res = 0 + for (i in last downTo 0) { + var abs = cost[2 * i + 1] - cost[2 * i + 2] + if (abs < 0) abs *= -1 + cost[i] += maxOf(cost[2 * i + 1], cost[2 * i + 2]) + res += abs + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2677_chunk_array/readme.md b/src/main/kotlin/g2601_2700/s2677_chunk_array/readme.md new file mode 100644 index 00000000..cca6a1ab --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2677_chunk_array/readme.md @@ -0,0 +1,68 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2677\. Chunk Array + +Easy + +Given an array `arr` and a chunk size `size`, return a **chunked** array. A **chunked** array contains the original elements in `arr`, but consists of subarrays each of length `size`. The length of the last subarray may be less than `size` if `arr.length` is not evenly divisible by `size`. + +You may assume the array is the output of `JSON.parse`. In other words, it is valid JSON. + +Please solve it without using lodash's `_.chunk` function. + +**Example 1:** + +**Input:** arr = [1,2,3,4,5], size = 1 + +**Output:** [[1],[2],[3],[4],[5]] + +**Explanation:** The arr has been split into subarrays each with 1 element. + +**Example 2:** + +**Input:** arr = [1,9,6,3,2], size = 3 + +**Output:** [[1,9,6],[3,2]] + +**Explanation:** The arr has been split into subarrays with 3 elements. However, only two elements are left for the 2nd subarray. + +**Example 3:** + +**Input:** arr = [8,5,3,2,6], size = 6 + +**Output:** [[8,5,3,2,6]] + +**Explanation:** Size is greater than arr.length thus all elements are in the first subarray. + +**Example 4:** + +**Input:** arr = [], size = 1 + +**Output:** [] + +**Explanation:** There are no elements to be chunked so an empty array is returned. + +**Constraints:** + +* `arr is a valid JSON array` +* 2 <= JSON.stringify(arr).length <= 105 +* `1 <= size <= arr.length + 1` + +## Solution + +```typescript +function chunk(arr: any[], size: number): any[][] { + if (arr.length === 0) return [] + if (size >= arr.length) return [arr] + let i: number = 0 + let res: Array> = [] + while (i < arr.length) { + res.push(arr.slice(i, i + size)) + i += size + } + return res +} + +export { chunk } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2678_number_of_senior_citizens/readme.md b/src/main/kotlin/g2601_2700/s2678_number_of_senior_citizens/readme.md new file mode 100644 index 00000000..1b15f677 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2678_number_of_senior_citizens/readme.md @@ -0,0 +1,48 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2678\. Number of Senior Citizens + +Easy + +You are given a **0-indexed** array of strings `details`. Each element of `details` provides information about a given passenger compressed into a string of length `15`. The system is such that: + +* The first ten characters consist of the phone number of passengers. +* The next character denotes the gender of the person. +* The following two characters are used to indicate the age of the person. +* The last two characters determine the seat allotted to that person. + +Return _the number of passengers who are **strictly** **more than 60 years old**._ + +**Example 1:** + +**Input:** details = ["7868190130M7522","5303914400F9211","9273338290F4010"] + +**Output:** 2 + +**Explanation:** The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old. + +**Example 2:** + +**Input:** details = ["1313579440F2036","2921522980M5644"] + +**Output:** 0 + +**Explanation:** None of the passengers are older than 60. + +**Constraints:** + +* `1 <= details.length <= 100` +* `details[i].length == 15` +* `details[i] consists of digits from '0' to '9'.` +* `details[i][10] is either 'M' or 'F' or 'O'.` +* The phone numbers and seat numbers of the passengers are distinct. + +## Solution + +```kotlin +class Solution { + fun countSeniors(details: Array): Int = + details.filter { it.substring(11, 13).toInt() > 60 }.size +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2679_sum_in_a_matrix/readme.md b/src/main/kotlin/g2601_2700/s2679_sum_in_a_matrix/readme.md new file mode 100644 index 00000000..92c9b6e0 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2679_sum_in_a_matrix/readme.md @@ -0,0 +1,56 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2679\. Sum in a Matrix + +Medium + +You are given a **0-indexed** 2D integer array `nums`. Initially, your score is `0`. Perform the following operations until the matrix becomes empty: + +1. From each row in the matrix, select the largest number and remove it. In the case of a tie, it does not matter which number is chosen. +2. Identify the highest number amongst all those removed in step 1. Add that number to your **score**. + +Return _the final **score**._ + +**Example 1:** + +**Input:** nums = \[\[7,2,1],[6,4,2],[6,5,3],[3,2,1]] + +**Output:** 15 + +**Explanation:** In the first operation, we remove 7, 6, 6, and 3. We then add 7 to our score. Next, we remove 2, 4, 5, and 2. We add 5 to our score. Lastly, we remove 1, 2, 3, and 1. We add 3 to our score. Thus, our final score is 7 + 5 + 3 = 15. + +**Example 2:** + +**Input:** nums = \[\[1]] + +**Output:** 1 + +**Explanation:** We remove 1 and add it to the answer. We return 1. + +**Constraints:** + +* `1 <= nums.length <= 300` +* `1 <= nums[i].length <= 500` +* 0 <= nums[i][j] <= 103 + +## Solution + +```kotlin +class Solution { + fun matrixSum(nums: Array): Int { + var result = 0 + nums.forEach { row -> + row.sortDescending() + } + for (i in 0 until nums[0].size) { + var max = 0 + for (j in 0 until nums.size) { + max = maxOf(max, nums[j][i]) + } + result += max + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2680_maximum_or/readme.md b/src/main/kotlin/g2601_2700/s2680_maximum_or/readme.md new file mode 100644 index 00000000..f2512c66 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2680_maximum_or/readme.md @@ -0,0 +1,58 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2680\. Maximum OR + +Medium + +You are given a **0-indexed** integer array `nums` of length `n` and an integer `k`. In an operation, you can choose an element and multiply it by `2`. + +Return _the maximum possible value of_ `nums[0] | nums[1] | ... | nums[n - 1]` _that can be obtained after applying the operation on nums at most_ `k` _times_. + +Note that `a | b` denotes the **bitwise or** between two integers `a` and `b`. + +**Example 1:** + +**Input:** nums = [12,9], k = 1 + +**Output:** 30 + +**Explanation:** If we apply the operation to index 1, our new array nums will be equal to [12,18]. Thus, we return the bitwise or of 12 and 18, which is 30. + +**Example 2:** + +**Input:** nums = [8,1,2], k = 2 + +**Output:** 35 + +**Explanation:** If we apply the operation twice on index 0, we yield a new array of [32,1,2]. Thus, we return 32\|1\|2 = 35. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 109 +* `1 <= k <= 15` + +## Solution + +```kotlin +class Solution { + fun maximumOr(nums: IntArray, k: Int): Long { + val suffix = IntArray(nums.size).apply { + for (i in nums.lastIndex - 1 downTo 0) + this[i] = this[i + 1] or nums[i + 1] + } + var prefix = 0L + var max = 0L + for (i in 0..nums.lastIndex) { + val num = nums[i].toLong() + max = maxOf( + max, + prefix or (num shl k) or suffix[i].toLong() + ) + prefix = prefix or num + } + return max + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2681_power_of_heroes/readme.md b/src/main/kotlin/g2601_2700/s2681_power_of_heroes/readme.md new file mode 100644 index 00000000..bbc03293 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2681_power_of_heroes/readme.md @@ -0,0 +1,69 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2681\. Power of Heroes + +Hard + +You are given a **0-indexed** integer array `nums` representing the strength of some heroes. The **power** of a group of heroes is defined as follows: + +* Let i0, i1, ... ,ik be the indices of the heroes in a group. Then, the power of this group is max(nums[i0], nums[i1], ... ,nums[ik])2 * min(nums[i0], nums[i1], ... ,nums[ik]). + +Return _the sum of the **power** of all **non-empty** groups of heroes possible._ Since the sum could be very large, return it **modulo** 109 + 7. + +**Example 1:** + +**Input:** nums = [2,1,4] + +**Output:** 141 + +**Explanation:** + +1st group: [2] has power = 22 \* 2 = 8. + +2nd group: [1] has power = 12 \* 1 = 1. + +3rd group: [4] has power = 42 \* 4 = 64. + +4th group: [2,1] has power = 22 \* 1 = 4. + +5th group: [2,4] has power = 42 \* 2 = 32. + +6th group: [1,4] has power = 42 \* 1 = 16. + +7th group: [2,1,4] has power = 42 \* 1 = 16. + +The sum of powers of all groups is 8 + 1 + 64 + 4 + 32 + 16 + 16 = 141. + +**Example 2:** + +**Input:** nums = [1,1,1] + +**Output:** 7 + +**Explanation:** A total of 7 groups are possible, and the power of each group will be 1. Therefore, the sum of the powers of all groups is 7. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 109 + +## Solution + +```kotlin +class Solution { + private val mod = 1_000_000_007L + fun sumOfPower(nums: IntArray): Int { + nums.sort() + var sumOfMin = 0L + var res = 0L + for (num in nums) { + val max = (num.toLong() * num.toLong()) % mod + val mySumOfMin = (sumOfMin + num) % mod + res = (res + max * mySumOfMin) % mod + sumOfMin = (sumOfMin + mySumOfMin) % mod + } + return res.toInt() + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2682_find_the_losers_of_the_circular_game/readme.md b/src/main/kotlin/g2601_2700/s2682_find_the_losers_of_the_circular_game/readme.md new file mode 100644 index 00000000..257b7745 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2682_find_the_losers_of_the_circular_game/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) + +## 2682\. Find the Losers of the Circular Game + +Easy + +There are `n` friends that are playing a game. The friends are sitting in a circle and are numbered from `1` to `n` in **clockwise order**. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for `1 <= i < n`, and moving clockwise from the nth friend brings you to the 1st friend. + +The rules of the game are as follows: + +1st friend receives the ball. + +* After that, 1st friend passes it to the friend who is `k` steps away from them in the **clockwise** direction. +* After that, the friend who receives the ball should pass it to the friend who is `2 * k` steps away from them in the **clockwise** direction. +* After that, the friend who receives the ball should pass it to the friend who is `3 * k` steps away from them in the **clockwise** direction, and so on and so forth. + +In other words, on the ith turn, the friend holding the ball should pass it to the friend who is `i * k` steps away from them in the **clockwise** direction. + +The game is finished when some friend receives the ball for the second time. + +The **losers** of the game are friends who did not receive the ball in the entire game. + +Given the number of friends, `n`, and an integer `k`, return _the array answer, which contains the losers of the game in the **ascending** order_. + +**Example 1:** + +**Input:** n = 5, k = 2 + +**Output:** [4,5] + +**Explanation:** The game goes as follows: +1) Start at 1st friend and pass the ball to the friend who is 2 steps away from them - 3rd friend. +2) 3rd friend passes the ball to the friend who is 4 steps away from them - 2nd friend. +3) 2nd friend passes the ball to the friend who is 6 steps away from them - 3rd friend. +4) The game ends as 3rd friend receives the ball for the second time. + +**Example 2:** + +**Input:** n = 4, k = 4 + +**Output:** [2,3,4] + +**Explanation:** The game goes as follows: +1) Start at the 1st friend and pass the ball to the friend who is 4 steps away from them - 1st friend. +2) The game ends as 1st friend receives the ball for the second time. + +**Constraints:** + +* `1 <= k <= n <= 50` + +## Solution + +```kotlin +class Solution { + fun circularGameLosers(n: Int, k: Int): IntArray { + val pointsMap = IntArray(n) + var friend = 0 + var turn = 1 + while (true) { + pointsMap[friend] = pointsMap[friend] + 1 + if (pointsMap[friend] == 2) break + friend = (friend + turn * k) % n + turn++ + } + val result = IntArray(n - (turn - 1)) + var i = 0 + pointsMap.forEachIndexed { index, points -> + if (points == 0) { + result[i] = index + 1 + i++ + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2683_neighboring_bitwise_xor/readme.md b/src/main/kotlin/g2601_2700/s2683_neighboring_bitwise_xor/readme.md new file mode 100644 index 00000000..83090970 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2683_neighboring_bitwise_xor/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) + +## 2683\. Neighboring Bitwise XOR + +Medium + +A **0-indexed** array `derived` with length `n` is derived by computing the **bitwise XOR** (⊕) of adjacent values in a **binary array** `original` of length `n`. + +Specifically, for each index `i` in the range `[0, n - 1]`: + +* If `i = n - 1`, then `derived[i] = original[i] ⊕ original[0]`. +* Otherwise, `derived[i] = original[i] ⊕ original[i + 1]`. + +Given an array `derived`, your task is to determine whether there exists a **valid binary array** `original` that could have formed `derived`. + +Return _**true** if such an array exists or **false** otherwise._ + +* A binary array is an array containing only **0's** and **1's** + +**Example 1:** + +**Input:** derived = [1,1,0] + +**Output:** true + +**Explanation:** A valid original array that gives derived is [0,1,0]. + +derived[0] = original[0] ⊕ original[1] = 0 ⊕ 1 = 1 + +derived[1] = original[1] ⊕ original[2] = 1 ⊕ 0 = 1 + +derived[2] = original[2] ⊕ original[0] = 0 ⊕ 0 = 0 + +**Example 2:** + +**Input:** derived = [1,1] + +**Output:** true + +**Explanation:** A valid original array that gives derived is [0,1]. + +derived[0] = original[0] ⊕ original[1] = 1 + +derived[1] = original[1] ⊕ original[0] = 1 + +**Example 3:** + +**Input:** derived = [1,0] + +**Output:** false + +**Explanation:** There is no valid original array that gives derived. + +**Constraints:** + +* `n == derived.length` +* 1 <= n <= 105 +* The values in `derived` are either **0's** or **1's** + +## Solution + +```kotlin +class Solution { + fun doesValidArrayExist(derived: IntArray): Boolean { + var xor = 0 + for (j in derived) { + xor = xor xor j + } + return xor == 0 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2684_maximum_number_of_moves_in_a_grid/readme.md b/src/main/kotlin/g2601_2700/s2684_maximum_number_of_moves_in_a_grid/readme.md new file mode 100644 index 00000000..d6b87f97 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2684_maximum_number_of_moves_in_a_grid/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) + +## 2684\. Maximum Number of Moves in a Grid + +Medium + +You are given a **0-indexed** `m x n` matrix `grid` consisting of **positive** integers. + +You can start at **any** cell in the first column of the matrix, and traverse the grid in the following way: + +* From a cell `(row, col)`, you can move to any of the cells: `(row - 1, col + 1)`, `(row, col + 1)` and `(row + 1, col + 1)` such that the value of the cell you move to, should be **strictly** bigger than the value of the current cell. + +Return _the **maximum** number of **moves** that you can perform._ + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/04/11/yetgriddrawio-10.png) + +**Input:** grid = \[\[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]] + +**Output:** 3 + +**Explanation:** We can start at the cell (0, 0) and make the following moves: +- (0, 0) -> (0, 1). +- (0, 1) -> (1, 2). +- (1, 2) -> (2, 3). + +It can be shown that it is the maximum number of moves that can be made. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/04/12/yetgrid4drawio.png) **Input:** grid = \[\[3,2,4],[2,1,9],[1,1,7]] + +**Output:** 0 + +**Explanation:** Starting from any cell in the first column we cannot perform any moves. + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `2 <= m, n <= 1000` +* 4 <= m * n <= 105 +* 1 <= grid[i][j] <= 106 + +## Solution + +```kotlin +class Solution { + fun maxMoves(grid: Array): Int { + val height = grid.size + val width = grid[0].size + val dp = Array(height) { IntArray(width) { Int.MIN_VALUE } } + var result = 0 + for (i in 0 until height) { + dp[i][0] = 0 + } + for (c in 1 until width) { + for (r in 0 until height) { + if (r > 0 && grid[r - 1][c - 1] < grid[r][c]) { + dp[r][c] = dp[r][c].coerceAtLeast(dp[r - 1][c - 1] + 1) + } + if (grid[r][c - 1] < grid[r][c]) dp[r][c] = dp[r][c].coerceAtLeast(dp[r][c - 1] + 1) + if (r < height - 1 && grid[r + 1][c - 1] < grid[r][c]) { + dp[r][c] = dp[r][c].coerceAtLeast(dp[r + 1][c - 1] + 1) + } + result = result.coerceAtLeast(dp[r][c]) + } + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2685_count_the_number_of_complete_components/readme.md b/src/main/kotlin/g2601_2700/s2685_count_the_number_of_complete_components/readme.md new file mode 100644 index 00000000..925b40a9 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2685_count_the_number_of_complete_components/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) + +## 2685\. Count the Number of Complete Components + +Medium + +You are given an integer `n`. There is an **undirected** graph with `n` vertices, numbered from `0` to `n - 1`. You are given a 2D integer array `edges` where edges[i] = [ai, bi] denotes that there exists an **undirected** edge connecting vertices ai and bi. + +Return _the number of **complete connected components** of the graph_. + +A **connected component** is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph. + +A connected component is said to be **complete** if there exists an edge between every pair of its vertices. + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2023/04/11/screenshot-from-2023-04-11-23-31-23.png)** + +**Input:** n = 6, edges = \[\[0,1],[0,2],[1,2],[3,4]] + +**Output:** 3 + +**Explanation:** From the picture above, one can see that all of the components of this graph are complete. + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2023/04/11/screenshot-from-2023-04-11-23-32-00.png)** + +**Input:** n = 6, edges = \[\[0,1],[0,2],[1,2],[3,4],[3,5]] + +**Output:** 1 + +**Explanation:** The component containing vertices 0, 1, and 2 is complete since there is an edge between every pair of two vertices. On the other hand, the component containing vertices 3, 4, and 5 is not complete since there is no edge between vertices 4 and 5. Thus, the number of complete components in this graph is 1. + +**Constraints:** + +* `1 <= n <= 50` +* `0 <= edges.length <= n * (n - 1) / 2` +* `edges[i].length == 2` +* 0 <= ai, bi <= n - 1 +* ai != bi +* There are no repeated edges. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun countCompleteComponents(n: Int, edges: Array): Int { + val adj = HashMap>().apply { + for ((u, v) in edges) { + this[u] = getOrDefault(u, arrayListOf()).apply { add(v) } + this[v] = getOrDefault(v, arrayListOf()).apply { add(u) } + } + } + val visited = BooleanArray(n) + fun bfs(i: Int): Pair { + if (visited[i]) return 0 to 0 + visited[i] = true + var nodes = 1 + var edges = (adj[i]?.size ?: 0) + adj[i]?.forEach { + val (nodes2, edges2) = bfs(it) + nodes += nodes2 + edges += edges2 + } + return nodes to edges + } + var res = 0 + for (i in 0 until n) { + if (!visited[i]) { + val (nodes, edges) = bfs(i) + if ((nodes * (nodes - 1)) == edges) + res++ + } + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2693_call_function_with_custom_context/readme.md b/src/main/kotlin/g2601_2700/s2693_call_function_with_custom_context/readme.md new file mode 100644 index 00000000..4aa419c7 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2693_call_function_with_custom_context/readme.md @@ -0,0 +1,78 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2693\. Call Function with Custom Context + +Medium + +Enhance all functions to have the `callPolyfill` method. The method accepts an object `obj` as it's first parameter and any number of additional arguments. The `obj` becomes the `this` context for the function. The additional arguments are passed to the function (that the `callPolyfill` method belongs on). + +For example if you had the function: + +function tax(price, taxRate) { const totalCost = price \* (1 + taxRate); console.log(\`The cost of ${this.item} is ${totalCost}\`); } + +Calling this function like `tax(10, 0.1)` will log `"The cost of undefined is 11"`. This is because the `this` context was not defined. + +However, calling the function like `tax.callPolyfill({item: "salad"}, 10, 0.1)` will log `"The cost of salad is 11"`. The `this` context was appropriately set, and the function logged an appropriate output. + +Please solve this without using the built-in `Function.call` method. + +**Example 1:** + +**Input:** + + fn = function add(b) { + return this.a + b; + } + + args = [{"a": 5}, 7] + +**Output:** 12 + +**Explanation:** + + fn.callPolyfill({"a": 5}, 7); // 12 + +callPolyfill sets the "this" context to {"a": 5}. 7 is passed as an argument. + +**Example 2:** + +**Input:** + + fn = function tax(price, taxRate) { + return \`The cost of the ${this.item} is ${price \* taxRate}\`; + } + + args = [{"item": "burger"}, 10, 1.1] + +**Output:** "The cost of the burger is 11" + +**Explanation:** callPolyfill sets the "this" context to {"item": "burger"}. 10 and 1.1 are passed as additional arguments. + +**Constraints:** + +* `typeof args[0] == 'object' and args[0] != null` +* `1 <= args.length <= 100` +* 2 <= JSON.stringify(args[0]).length <= 105 + +## Solution + +```typescript +declare global { + interface Function { + callPolyfill(context: Record, ...args: any[]): any + } +} + +Function.prototype.callPolyfill = function (context, ...args): any { //NOSONAR + let fn = this.bind(context) + return fn(...args) +} + +/* + * function increment() { this.count++; return this.count; } + * increment.callPolyfill({count: 1}); // 2 + */ + +export {} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2694_event_emitter/readme.md b/src/main/kotlin/g2601_2700/s2694_event_emitter/readme.md new file mode 100644 index 00000000..ea239702 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2694_event_emitter/readme.md @@ -0,0 +1,119 @@ +[![](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) + +## 2694\. Event Emitter + +Medium + +Design an `EventEmitter` class. This interface is similar (but with some differences) to the one found in Node.js or the Event Target interface of the DOM. The `EventEmitter` should allow for subscribing to events and emitting them. + +Your `EventEmitter` class should have the following two methods: + +* **subscribe** - This method takes in two arguments: the name of an event as a string and a callback function. This callback function will later be called when the event is emitted. + An event should be able to have multiple listeners for the same event. When emitting an event with multiple callbacks, each should be called in the order in which they were subscribed. An array of results should be returned. You can assume no callbacks passed to `subscribe` are referentially identical. + The `subscribe` method should also return an object with an `unsubscribe` method that enables the user to unsubscribe. When it is called, the callback should be removed from the list of subscriptions and `undefined` should be returned. +* **emit** - This method takes in two arguments: the name of an event as a string and an optional array of arguments that will be passed to the callback(s). If there are no callbacks subscribed to the given event, return an empty array. Otherwise, return an array of the results of all callback calls in the order they were subscribed. + +**Example 1:** + +**Input:** actions = ["EventEmitter", "emit", "subscribe", "subscribe", "emit"], values = \[\[], ["firstEvent", "function cb1() { return 5; }"], ["firstEvent", "function cb1() { return 6; }"], ["firstEvent"]] + +**Output:** [[],["emitted",[]],["subscribed"],["subscribed"],["emitted",[5,6]]] + +**Explanation:** + + const emitter = new EventEmitter(); + emitter.emit("firstEvent"); // [], no callback are subscribed yet + emitter.subscribe("firstEvent", function cb1() { return 5; }); + emitter.subscribe("firstEvent", function cb2() { return 6; }); + emitter.emit("firstEvent"); // [5, 6], returns the output of cb1 and cb2 + +**Example 2:** + +**Input:** actions = ["EventEmitter", "subscribe", "emit", "emit"], values = \[\[], ["firstEvent", "function cb1(...args) { return args.join(','); }"], ["firstEvent", [1,2,3]], ["firstEvent", [3,4,6]]] + +**Output:** [[],["subscribed"],["emitted",["1,2,3"]],["emitted",["3,4,6"]]] + +**Explanation:** Note that the emit method should be able to accept an OPTIONAL array of arguments. + + const emitter = new EventEmitter(); + emitter.subscribe("firstEvent, function cb1(...args) { return args.join(','); }); + emitter.emit("firstEvent", [1, 2, 3]); // ["1,2,3"] + emitter.emit("firstEvent", [3, 4, 6]); // ["3,4,6"] + +**Example 3:** + +**Input:** actions = ["EventEmitter", "subscribe", "emit", "unsubscribe", "emit"], values = \[\[], ["firstEvent", "(...args) => args.join(',')"], ["firstEvent", [1,2,3]], [0], ["firstEvent", [4,5,6]]] + +**Output:** [[],["subscribed"],["emitted",["1,2,3"]],["unsubscribed",0],["emitted",[]]] + +**Explanation:** + + const emitter = new EventEmitter(); + const sub = emitter.subscribe("firstEvent", (...args) => args.join(',')); + emitter.emit("firstEvent", [1, 2, 3]); // ["1,2,3"] sub.unsubscribe(); // undefined + emitter.emit("firstEvent", [4, 5, 6]); // [], there are no subscriptions + +**Example 4:** + +**Input:** actions = ["EventEmitter", "subscribe", "subscribe", "unsubscribe", "emit"], values = \[\[], ["firstEvent", "x => x + 1"], ["firstEvent", "x => x + 2"], [0], ["firstEvent", [5]]] + +**Output:** [[],["subscribed"],["emitted",["1,2,3"]],["unsubscribed",0],["emitted",[7]]] + +**Explanation:** + + const emitter = new EventEmitter(); + const sub1 = emitter.subscribe("firstEvent", x => x + 1); + const sub2 = emitter.subscribe("firstEvent", x => x + 2); + sub1.unsubscribe(); // undefined + emitter.emit("firstEvent", [5]); // [7] + +**Constraints:** + +* `1 <= actions.length <= 10` +* `values.length === actions.length` +* All test cases are valid, e.g. you don't need to handle scenarios when unsubscribing from a non-existing subscription. +* There are only 4 different actions: `EventEmitter`, `emit`, `subscribe`, and `unsubscribe`. +* The `EventEmitter` action doesn't take any arguments. +* The `emit` action takes between either 1 or 2 arguments. The first argument is the name of the event we want to emit, and the 2nd argument is passed to the callback functions. +* The `subscribe` action takes 2 arguments, where the first one is the event name and the second is the callback function. +* The `unsubscribe` action takes one argument, which is the 0-indexed order of the subscription made before. + +## Solution + +```typescript +type Callback = (...args: any[]) => any +type Subscription = { + unsubscribe: () => void +} + +class EventEmitter { + subs: Record = {} + + subscribe(eventName: string, callback: Callback): Subscription { + if (!this.subs[eventName]) this.subs[eventName] = [] + const idx = this.subs[eventName].push(callback) - 1 + return { + unsubscribe: () => this.subs[eventName].splice(idx, 1), + } + } + + emit(eventName: string, args: any[] = []): any[] { + return this.subs[eventName]?.map((callback) => callback(...args)) || [] + } +} + +/* + * const emitter = new EventEmitter(); + * + * // Subscribe to the onClick event with onClickCallback + * function onClickCallback() { return 99 } + * const sub = emitter.subscribe('onClick', onClickCallback); + * + * emitter.emit('onClick'); // [99] + * sub.unsubscribe(); // undefined + * emitter.emit('onClick'); // [] + */ + +export { EventEmitter } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2695_array_wrapper/readme.md b/src/main/kotlin/g2601_2700/s2695_array_wrapper/readme.md new file mode 100644 index 00000000..25f556f5 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2695_array_wrapper/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) + +## 2695\. Array Wrapper + +Easy + +Create a class `ArrayWrapper` that accepts an array of integers in its constructor. This class should have two features: + +* When two instances of this class are added together with the `+` operator, the resulting value is the sum of all the elements in both arrays. +* When the `String()` function is called on the instance, it will return a comma separated string surrounded by brackets. For example, `[1,2,3]`. + +**Example 1:** + +**Input:** nums = \[\[1,2],[3,4]], operation = "Add" + +**Output:** 10 + +**Explanation:** + + const obj1 = new ArrayWrapper([1,2]); + const obj2 = new ArrayWrapper([3,4]); + obj1 + obj2; // 10 + +**Example 2:** + +**Input:** nums = \[\[23,98,42,70]], operation = "String" + +**Output:** "[23,98,42,70]" + +**Explanation:** + + const obj = new ArrayWrapper([23,98,42,70]); + String(obj); // "[23,98,42,70]" + +**Example 3:** + +**Input:** nums = \[\[],[]], operation = "Add" + +**Output:** 0 + +**Explanation:** + + const obj1 = new ArrayWrapper([]); + const obj2 = new ArrayWrapper([]); + obj1 + obj2; // 0 + +**Constraints:** + +* `0 <= nums.length <= 1000` +* `0 <= nums[i] <= 1000` +* `Note: nums is the array passed to the constructor` + +## Solution + +```typescript +class ArrayWrapper { + nums: number[] + constructor(nums: number[]) { + this.nums = nums + } + + valueOf() { + return this.nums.reduce((n, a) => n + a, 0) + } + + toString() { + return '[' + this.nums.join(',') + ']' + } +} + +/* + * const obj1 = new ArrayWrapper([1,2]); + * const obj2 = new ArrayWrapper([3,4]); + * obj1 + obj2; // 10 + * String(obj1); // "[1,2]" + * String(obj2); // "[3,4]" + */ + +export { ArrayWrapper } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2696_minimum_string_length_after_removing_substrings/readme.md b/src/main/kotlin/g2601_2700/s2696_minimum_string_length_after_removing_substrings/readme.md new file mode 100644 index 00000000..0d422d4e --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2696_minimum_string_length_after_removing_substrings/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) + +## 2696\. Minimum String Length After Removing Substrings + +Easy + +You are given a string `s` consisting only of **uppercase** English letters. + +You can apply some operations to this string where, in one operation, you can remove **any** occurrence of one of the substrings `"AB"` or `"CD"` from `s`. + +Return _the **minimum** possible length of the resulting string that you can obtain_. + +**Note** that the string concatenates after removing the substring and could produce new `"AB"` or `"CD"` substrings. + +**Example 1:** + +**Input:** s = "ABFCACDB" + +**Output:** 2 + +**Explanation:** We can do the following operations: +- Remove the substring "ABFCACDB", so s = "FCACDB". +- Remove the substring "FCACDB", so s = "FCAB". +- Remove the substring "FCAB", so s = "FC". + +So the resulting length of the string is 2. + +It can be shown that it is the minimum length that we can obtain. + +**Example 2:** + +**Input:** s = "ACBBD" + +**Output:** 5 + +**Explanation:** We cannot do any operations on the string so the length remains the same. + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` consists only of uppercase English letters. + +## Solution + +```kotlin +class Solution { + fun minLength(s: String): Int { + val stack = ArrayDeque() + s.forEach { c -> + if (stack.isNotEmpty() && + ( + (c == 'B' && stack.last() == 'A') || + (c == 'D' && stack.last() == 'C') + ) + ) { + stack.removeLast() + } else { + stack.addLast(c) + } + } + return stack.size + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2697_lexicographically_smallest_palindrome/readme.md b/src/main/kotlin/g2601_2700/s2697_lexicographically_smallest_palindrome/readme.md new file mode 100644 index 00000000..62ca978a --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2697_lexicographically_smallest_palindrome/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) + +## 2697\. Lexicographically Smallest Palindrome + +Easy + +You are given a string `s` consisting of **lowercase English letters**, and you are allowed to perform operations on it. In one operation, you can **replace** a character in `s` with another lowercase English letter. + +Your task is to make `s` a **palindrome** with the **minimum** **number** **of operations** possible. If there are **multiple palindromes** that can be made using the **minimum** number of operations, make the **lexicographically smallest** one. + +A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. + +Return _the resulting palindrome string._ + +**Example 1:** + +**Input:** s = "egcfe" + +**Output:** "efcfe" + +**Explanation:** The minimum number of operations to make "egcfe" a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is "efcfe", by changing 'g'. + +**Example 2:** + +**Input:** s = "abcd" + +**Output:** "abba" + +**Explanation:** The minimum number of operations to make "abcd" a palindrome is 2, and the lexicographically smallest palindrome string we can get by modifying two characters is "abba". + +**Example 3:** + +**Input:** s = "seven" + +**Output:** "neven" + +**Explanation:** The minimum number of operations to make "seven" a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is "neven". + +**Constraints:** + +* `1 <= s.length <= 1000` +* `s` consists of only lowercase English letters**.** + +## Solution + +```kotlin +class Solution { + fun makeSmallestPalindrome(s: String): String { + var l = 0 + var r = s.lastIndex + val res = s.toCharArray() + while (l <= r) { + if (s[l] < s[r]) + res[r] = s[l] + else + res[l] = s[r] + l++ + r-- + } + return String(res) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2698_find_the_punishment_number_of_an_integer/readme.md b/src/main/kotlin/g2601_2700/s2698_find_the_punishment_number_of_an_integer/readme.md new file mode 100644 index 00000000..45b31bb1 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2698_find_the_punishment_number_of_an_integer/readme.md @@ -0,0 +1,67 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2698\. Find the Punishment Number of an Integer + +Medium + +Given a positive integer `n`, return _the **punishment number**_ of `n`. + +The **punishment number** of `n` is defined as the sum of the squares of all integers `i` such that: + +* `1 <= i <= n` +* The decimal representation of `i * i` can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals `i`. + +**Example 1:** + +**Input:** n = 10 + +**Output:** 182 + +**Explanation:** There are exactly 3 integers i that satisfy the conditions in the statement: +- 1 since 1 \* 1 = 1 +- 9 since 9 \* 9 = 81 and 81 can be partitioned into 8 + 1. +- 10 since 10 \* 10 = 100 and 100 can be partitioned into 10 + 0. + +Hence, the punishment number of 10 is 1 + 81 + 100 = 182 + +**Example 2:** + +**Input:** n = 37 + +**Output:** 1478 + +**Explanation:** There are exactly 4 integers i that satisfy the conditions in the statement: +- 1 since 1 \* 1 = 1. +- 9 since 9 \* 9 = 81 and 81 can be partitioned into 8 + 1. +- 10 since 10 \* 10 = 100 and 100 can be partitioned into 10 + 0. +- 36 since 36 \* 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6. + +Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478 + +**Constraints:** + +* `1 <= n <= 1000` + +## Solution + +```kotlin +class Solution { + fun punishmentNumber(n: Int): Int { + fun partition(x: Int, target: Int): Boolean { + if (x == target) return true + if (target < 0 || x < target) return false + return partition(x / 10, target - (x % 10)) || + partition(x / 100, target - (x % 100)) || + partition(x / 1000, target - (x % 1000)) + } + var res = 0 + for (i in 1..n) { + val iSq = i * i + if (partition(iSq, i)) + res += iSq + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2601_2700/s2699_modify_graph_edge_weights/readme.md b/src/main/kotlin/g2601_2700/s2699_modify_graph_edge_weights/readme.md new file mode 100644 index 00000000..aea8ee43 --- /dev/null +++ b/src/main/kotlin/g2601_2700/s2699_modify_graph_edge_weights/readme.md @@ -0,0 +1,153 @@ +[![](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) + +## 2699\. Modify Graph Edge Weights + +Hard + +You are given an **undirected weighted** **connected** graph containing `n` nodes labeled from `0` to `n - 1`, and an integer array `edges` where edges[i] = [ai, bi, wi] indicates that there is an edge between nodes ai and bi with weight wi. + +Some edges have a weight of `-1` (wi = -1), while others have a **positive** weight (wi > 0). + +Your task is to modify **all edges** with a weight of `-1` by assigning them **positive integer values** in the range [1, 2 * 109] so that the **shortest distance** between the nodes `source` and `destination` becomes equal to an integer `target`. If there are **multiple** **modifications** that make the shortest distance between `source` and `destination` equal to `target`, any of them will be considered correct. + +Return _an array containing all edges (even unmodified ones) in any order if it is possible to make the shortest distance from_ `source` _to_ `destination` _equal to_ `target`_, or an **empty array** if it's impossible._ + +**Note:** You are not allowed to modify the weights of edges with initial positive weights. + +**Example 1:** + +**![](https://assets.leetcode.com/uploads/2023/04/18/graph.png)** + +**Input:** n = 5, edges = \[\[4,1,-1],[2,0,-1],[0,3,-1],[4,3,-1]], source = 0, destination = 1, target = 5 + +**Output:** [[4,1,1],[2,0,1],[0,3,3],[4,3,1]] + +**Explanation:** The graph above shows a possible modification to the edges, making the distance from 0 to 1 equal to 5. + +**Example 2:** + +**![](https://assets.leetcode.com/uploads/2023/04/18/graph-2.png)** + +**Input:** n = 3, edges = \[\[0,1,-1],[0,2,5]], source = 0, destination = 2, target = 6 + +**Output:** [] + +**Explanation:** The graph above contains the initial edges. It is not possible to make the distance from 0 to 2 equal to 6 by modifying the edge with weight -1. So, an empty array is returned. + +**Example 3:** + +**![](https://assets.leetcode.com/uploads/2023/04/19/graph-3.png)** + +**Input:** n = 4, edges = \[\[1,0,4],[1,2,3],[2,3,5],[0,3,-1]], source = 0, destination = 2, target = 6 + +**Output:** [[1,0,4],[1,2,3],[2,3,5],[0,3,1]] + +**Explanation:** The graph above shows a modified graph having the shortest distance from 0 to 2 as 6. + +**Constraints:** + +* `1 <= n <= 100` +* `1 <= edges.length <= n * (n - 1) / 2` +* `edges[i].length == 3` +* 0 <= ai, bi < n +* wi = -1 or 1 <= wi <= 107 +* ai != bi +* `0 <= source, destination < n` +* `source != destination` +* 1 <= target <= 109 +* The graph is connected, and there are no self-loops or repeated edges + +## Solution + +```kotlin +import java.util.PriorityQueue + +class Solution { + private inner class Edge(var s: Int, var d: Int, var wt: Int) + private lateinit var g: Array?> + private var n = 0 + private var t = 0 + fun modifiedGraphEdges( + n: Int, + edges: Array, + source: Int, + destination: Int, + target: Int + ): Array { + this.n = n + g = arrayOfNulls(n) + t = target + for (i in 0 until n) { + g[i] = ArrayList() + } + for (e in edges) { + val s = e[0] + val d = e[1] + val wt = e[2] + if (wt == -1) continue + g[s]!!.add(Edge(s, d, wt)) + g[d]!!.add(Edge(d, s, wt)) + } + val inc = shortestPath(source, destination) + if (inc != -1 && inc < target) return Array(0) { IntArray(0) } + if (inc == target) { + ntomax(edges) + return edges + } + for (e in edges) { + if (e[2] == -1) { + e[2] = 1 + val s = e[0] + val d = e[1] + val wt = e[2] + g[s]!!.add(Edge(s, d, wt)) + g[d]!!.add(Edge(d, s, wt)) + val cost = shortestPath(source, destination) + if (cost == -1) continue + if (cost < target) { + e[2] = target - cost + 1 + ntomax(edges) + return edges + } + if (cost == target) { + ntomax(edges) + return edges + } + } + } + return Array(0) { IntArray(0) } + } + + private fun ntomax(edges: Array) { + for (e in edges) { + if (e[2] == -1) { + e[2] = 1000000000 + } + } + } + + private inner class Pair(var s: Int, var cost: Int) : Comparable { + override operator fun compareTo(other: Pair?): Int { + return cost - other!!.cost + } + } + + private fun shortestPath(s: Int, d: Int): Int { + val q = PriorityQueue() + q.add(Pair(s, 0)) + val vis = BooleanArray(n) + while (q.isNotEmpty()) { + val rem = q.remove() + vis[rem.s] = true + if (rem.s == d) return rem.cost + for (e in g[rem.s]!!) { + if (!vis[e.d]) { + q.add(Pair(e.d, rem.cost + e.wt)) + } + } + } + return -1 + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2703_return_length_of_arguments_passed/readme.md b/src/main/kotlin/g2701_2800/s2703_return_length_of_arguments_passed/readme.md new file mode 100644 index 00000000..821c60bb --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2703_return_length_of_arguments_passed/readme.md @@ -0,0 +1,47 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2703\. Return Length of Arguments Passed + +Easy + +Write a function `argumentsLength` that returns the count of arguments passed to it. + +**Example 1:** + +**Input:** argsArr = [5] + +**Output:** 1 + +**Explanation:** argumentsLength(5); // 1 One value was passed to the function so it should return 1. + +**Example 2:** + +**Input:** argsArr = [{}, null, "3"] + +**Output:** 3 + +**Explanation:** argumentsLength({}, null, "3"); // 3 Three values were passed to the function so it should return 3. + +**Constraints:** + +* `argsArr is a valid JSON array` +* `0 <= argsArr.length <= 100` + +## Solution + +```typescript +function argumentsLength(...args: any[]): number { + let result = 0 + for (let value of args) { //NOSONAR + result += 1 + } + return result +} + +/* + * argumentsLength(1, 2, 3); // 3 + */ + +export { argumentsLength } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2704_to_be_or_not_to_be/readme.md b/src/main/kotlin/g2701_2800/s2704_to_be_or_not_to_be/readme.md new file mode 100644 index 00000000..95e4ab5e --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2704_to_be_or_not_to_be/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) + +## 2704\. To Be Or Not To Be + +Easy + +Write a function `expect` that helps developers test their code. It should take in any value `val` and return an object with the following two functions. + +* `toBe(val)` accepts another value and returns `true` if the two values `===` each other. If they are not equal, it should throw an error `"Not Equal"`. +* `notToBe(val)` accepts another value and returns `true` if the two values `!==` each other. If they are equal, it should throw an error `"Equal"`. + +**Example 1:** + +**Input:** func = () => expect(5).toBe(5) + +**Output:** {"value": true} + +**Explanation:** 5 === 5 so this expression returns true. + +**Example 2:** + +**Input:** func = () => expect(5).toBe(null) + +**Output:** {"error": "Not Equal"} + +**Explanation:** 5 !== null so this expression throw the error "Not Equal". + +**Example 3:** + +**Input:** func = () => expect(5).notToBe(null) + +**Output:** {"value": true} + +**Explanation:** 5 !== null so this expression returns true. + +## Solution + +```typescript +type ToBeOrNotToBe = { + toBe: (val: any) => boolean + notToBe: (val: any) => boolean +} + +const expect = (val: any): ToBeOrNotToBe => ({ + toBe: (equality: any) => { + if (val !== equality) { + throw new Error('Not Equal') + } + return true + }, + notToBe: (equality: any) => { + if (val === equality) { + throw new Error('Equal') + } + return true + }, +}) + +/* + * expect(5).toBe(5); // true + * expect(5).notToBe(5); // throws "Equal" + */ + +export { expect } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2705_compact_object/readme.md b/src/main/kotlin/g2701_2800/s2705_compact_object/readme.md new file mode 100644 index 00000000..5e206588 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2705_compact_object/readme.md @@ -0,0 +1,68 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 2705\. Compact Object + +Medium + +Given an object or array `obj`, return a **compact object**. A **compact object** is the same as the original object, except with keys containing **falsy** values removed. This operation applies to the object and any nested objects. Arrays are considered objects where the indices are keys. A value is considered **falsy** when `Boolean(value)` returns `false`. + +You may assume the `obj` is the output of `JSON.parse`. In other words, it is valid JSON. + +**Example 1:** + +**Input:** obj = [null, 0, false, 1] + +**Output:** [1] + +**Explanation:** All falsy values have been removed from the array. + +**Example 2:** + +**Input:** obj = {"a": null, "b": [false, 1]} + +**Output:** {"b": [1]} + +**Explanation:** obj["a"] and obj["b"][0] had falsy values and were removed. + +**Example 3:** + +**Input:** obj = [null, 0, 5, [0], [false, 16]] + +**Output:** [5, [], [16]] + +**Explanation:** obj[0], obj[1], obj[3][0], and obj[4][0] were falsy and removed. + +**Constraints:** + +* `obj is a valid JSON object` +* 2 <= JSON.stringify(obj).length <= 106 + +## Solution + +```typescript +type Obj = Record + +function compactObject(obj: Obj): Obj { + if (Array.isArray(obj)) { + let retArr = [] + obj.forEach((e, idx) => { + if (e) { + retArr.push(compactObject(e)) + } + }) + return retArr + } else if (obj !== null && typeof obj === 'object') { + let retObj = {} + for (const key of Object.keys(obj)) { + if (obj[key]) { + retObj[key] = compactObject(obj[key]) + } + } + return retObj + } + return obj +} + +export { compactObject } +``` \ No newline at end of file diff --git a/src/main/kotlin/g2701_2800/s2706_buy_two_chocolates/readme.md b/src/main/kotlin/g2701_2800/s2706_buy_two_chocolates/readme.md new file mode 100644 index 00000000..865ee996 --- /dev/null +++ b/src/main/kotlin/g2701_2800/s2706_buy_two_chocolates/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) + +## 2706\. Buy Two Chocolates + +Easy + +You are given an integer array `prices` representing the prices of various chocolates in a store. You are also given a single integer `money`, which represents your initial amount of money. + +You must buy **exactly** two chocolates in such a way that you still have some **non-negative** leftover money. You would like to minimize the sum of the prices of the two chocolates you buy. + +Return _the amount of money you will have leftover after buying the two chocolates_. If there is no way for you to buy two chocolates without ending up in debt, return `money`. Note that the leftover must be non-negative. + +**Example 1:** + +**Input:** prices = [1,2,2], money = 3 + +**Output:** 0 + +**Explanation:** Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0. + +**Example 2:** + +**Input:** prices = [3,2,3], money = 3 + +**Output:** 3 + +**Explanation:** You cannot buy 2 chocolates without going in debt, so we return 3. + +**Constraints:** + +* `2 <= prices.length <= 50` +* `1 <= prices[i] <= 100` +* `1 <= money <= 100` + +## Solution + +```kotlin +class Solution { + fun buyChoco(prices: IntArray, money: Int): Int { + var minPrice1 = Int.MAX_VALUE + var minPrice2 = Int.MAX_VALUE + for (price in prices) { + if (price < minPrice1) { + minPrice2 = minPrice1 + minPrice1 = price + } else if (price < minPrice2) { + minPrice2 = price + } + } + val totalPrice = minPrice1 + minPrice2 + return if (totalPrice > money) { + money + } else { + money - totalPrice + } + } +} +``` \ No newline at end of file