From ceb526be972d20db2d8444d42ee4082b2a6fd0a8 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Wed, 22 Feb 2023 15:23:50 +0200 Subject: [PATCH] Added tasks 684-696 --- README.md | 15 +++ .../kotlin/g0601_0700/s0679_24_game/readme.md | 2 +- .../s0684_redundant_connection/readme.md | 71 ++++++++++++ .../s0685_redundant_connection_ii/readme.md | 91 +++++++++++++++ .../s0686_repeated_string_match/readme.md | 81 ++++++++++++++ .../s0687_longest_univalue_path/readme.md | 84 ++++++++++++++ .../readme.md | 87 +++++++++++++++ .../readme.md | 103 +++++++++++++++++ .../s0690_employee_importance/readme.md | 79 +++++++++++++ .../s0691_stickers_to_spell_word/readme.md | 105 ++++++++++++++++++ .../s0692_top_k_frequent_words/readme.md | 69 ++++++++++++ .../readme.md | 57 ++++++++++ .../s0695_max_area_of_island/readme.md | 74 ++++++++++++ .../s0696_count_binary_substrings/readme.md | 56 ++++++++++ 14 files changed, 973 insertions(+), 1 deletion(-) create mode 100644 src/main/kotlin/g0601_0700/s0684_redundant_connection/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0685_redundant_connection_ii/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0686_repeated_string_match/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0687_longest_univalue_path/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0688_knight_probability_in_chessboard/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0689_maximum_sum_of_3_non_overlapping_subarrays/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0690_employee_importance/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0691_stickers_to_spell_word/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0692_top_k_frequent_words/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0693_binary_number_with_alternating_bits/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0695_max_area_of_island/readme.md create mode 100644 src/main/kotlin/g0601_0700/s0696_count_binary_substrings/readme.md diff --git a/README.md b/README.md index 8fe76200..a3190379 100644 --- a/README.md +++ b/README.md @@ -158,6 +158,7 @@ | | | | | | |-|-|-|-|-|- +| 0695 |[Max Area of Island](src/main/kotlin/g0601_0700/s0695_max_area_of_island)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 324 | 24.06 #### Day 3 Matrix Related Problems @@ -387,6 +388,7 @@ | | | | | | |-|-|-|-|-|- +| 0692 |[Top K Frequent Words](src/main/kotlin/g0601_0700/s0692_top_k_frequent_words)| Medium | String, Hash_Table, Sorting, Heap_Priority_Queue, Counting, Trie, Bucket_Sort | 239 | 81.10 ### Level 2 @@ -1025,6 +1027,7 @@ | | | | | | |-|-|-|-|-|- +| 0695 |[Max Area of Island](src/main/kotlin/g0601_0700/s0695_max_area_of_island)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find | 324 | 24.06 #### Day 8 Breadth First Search Depth First Search @@ -1644,6 +1647,18 @@ | 0864 |[Shortest Path to Get All Keys](src/main/kotlin/g0801_0900/s0864_shortest_path_to_get_all_keys)| Hard | Breadth_First_Search, Bit_Manipulation | 176 | 100.00 | 0763 |[Partition Labels](src/main/kotlin/g0701_0800/s0763_partition_labels)| Medium | Top_100_Liked_Questions, String, Hash_Table, Greedy, Two_Pointers, Data_Structure_II_Day_7_String | 235 | 84.75 | 0739 |[Daily Temperatures](src/main/kotlin/g0701_0800/s0739_daily_temperatures)| Medium | Top_100_Liked_Questions, Array, Stack, Monotonic_Stack, Programming_Skills_II_Day_6 | 936 | 80.54 +| 0696 |[Count Binary Substrings](src/main/kotlin/g0601_0700/s0696_count_binary_substrings)| Easy | String, Two_Pointers | 222 | 100.00 +| 0695 |[Max Area of Island](src/main/kotlin/g0601_0700/s0695_max_area_of_island)| Medium | Array, Depth_First_Search, Breadth_First_Search, Matrix, Union_Find, Algorithm_I_Day_7_Breadth_First_Search_Depth_First_Search, Graph_Theory_I_Day_2_Matrix_Related_Problems | 324 | 24.06 +| 0693 |[Binary Number with Alternating Bits](src/main/kotlin/g0601_0700/s0693_binary_number_with_alternating_bits)| Easy | Bit_Manipulation | 129 | 100.00 +| 0692 |[Top K Frequent Words](src/main/kotlin/g0601_0700/s0692_top_k_frequent_words)| Medium | String, Hash_Table, Sorting, Heap_Priority_Queue, Counting, Trie, Bucket_Sort, Level_1_Day_15_Heap | 239 | 81.10 +| 0691 |[Stickers to Spell Word](src/main/kotlin/g0601_0700/s0691_stickers_to_spell_word)| Hard | Array, String, Dynamic_Programming, Bit_Manipulation, Backtracking, Bitmask | 249 | 100.00 +| 0690 |[Employee Importance](src/main/kotlin/g0601_0700/s0690_employee_importance)| Medium | Hash_Table, Depth_First_Search, Breadth_First_Search | 255 | 100.00 +| 0689 |[Maximum Sum of 3 Non-Overlapping Subarrays](src/main/kotlin/g0601_0700/s0689_maximum_sum_of_3_non_overlapping_subarrays)| Hard | Array, Dynamic_Programming | 248 | 100.00 +| 0688 |[Knight Probability in Chessboard](src/main/kotlin/g0601_0700/s0688_knight_probability_in_chessboard)| Medium | Dynamic_Programming | 144 | 100.00 +| 0687 |[Longest Univalue Path](src/main/kotlin/g0601_0700/s0687_longest_univalue_path)| Medium | Depth_First_Search, Tree, Binary_Tree | 303 | 100.00 +| 0686 |[Repeated String Match](src/main/kotlin/g0601_0700/s0686_repeated_string_match)| Medium | String, String_Matching | 164 | 100.00 +| 0685 |[Redundant Connection II](src/main/kotlin/g0601_0700/s0685_redundant_connection_ii)| Hard | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 176 | 100.00 +| 0684 |[Redundant Connection](src/main/kotlin/g0601_0700/s0684_redundant_connection)| Medium | Depth_First_Search, Breadth_First_Search, Graph, Union_Find | 181 | 88.24 | 0682 |[Baseball Game](src/main/kotlin/g0601_0700/s0682_baseball_game)| Easy | Array, Stack, Simulation | 159 | 100.00 | 0680 |[Valid Palindrome II](src/main/kotlin/g0601_0700/s0680_valid_palindrome_ii)| Easy | String, Greedy, Two_Pointers | 296 | 79.17 | 0679 |[24 Game](src/main/kotlin/g0601_0700/s0679_24_game)| Hard | Array, Math, Backtracking | 175 | 100.00 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 7e59acca..3a807d14 100644 --- a/src/main/kotlin/g0601_0700/s0679_24_game/readme.md +++ b/src/main/kotlin/g0601_0700/s0679_24_game/readme.md @@ -88,7 +88,7 @@ class Solution { return false } - fun judgePoint24(nums: IntArray?): Boolean { + fun judgePoint24(nums: IntArray): Boolean { val a = Arrays.stream(nums).asDoubleStream().toArray() return backtrack(a, a.size) } diff --git a/src/main/kotlin/g0601_0700/s0684_redundant_connection/readme.md b/src/main/kotlin/g0601_0700/s0684_redundant_connection/readme.md new file mode 100644 index 00000000..5037a07c --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0684_redundant_connection/readme.md @@ -0,0 +1,71 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 684\. Redundant Connection + +Medium + +In this problem, a tree is an **undirected graph** that is connected and has no cycles. + +You are given a graph that started as a tree with `n` nodes labeled from `1` to `n`, with one additional edge added. The added edge has two **different** vertices chosen from `1` to `n`, and was not an edge that already existed. The graph is represented as an array `edges` of length `n` where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph. + +Return _an edge that can be removed so that the resulting graph is a tree of_ `n` _nodes_. If there are multiple answers, return the answer that occurs last in the input. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/05/02/reduntant1-1-graph.jpg) + +**Input:** edges = \[\[1,2],[1,3],[2,3]] + +**Output:** [2,3] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/05/02/reduntant1-2-graph.jpg) + +**Input:** edges = \[\[1,2],[2,3],[3,4],[1,4],[1,5]] + +**Output:** [1,4] + +**Constraints:** + +* `n == edges.length` +* `3 <= n <= 1000` +* `edges[i].length == 2` +* 1 <= ai < bi <= edges.length +* ai != bi +* There are no repeated edges. +* The given graph is connected. + +## Solution + +```kotlin +class Solution { + private lateinit var par: IntArray + fun findRedundantConnection(edges: Array): IntArray { + val ans = IntArray(2) + val n = edges.size + par = IntArray(n + 1) + for (i in 0 until n) { + par[i] = i + } + for (edge in edges) { + val lx = find(edge[0]) + val ly = find(edge[1]) + if (lx != ly) { + par[lx] = ly + } else { + ans[0] = edge[0] + ans[1] = edge[1] + } + } + return ans + } + + private fun find(x: Int): Int { + return if (par[x] == x) { + x + } else find(par[x]) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0685_redundant_connection_ii/readme.md b/src/main/kotlin/g0601_0700/s0685_redundant_connection_ii/readme.md new file mode 100644 index 00000000..a86f95c6 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0685_redundant_connection_ii/readme.md @@ -0,0 +1,91 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 685\. Redundant Connection II + +Hard + +In this problem, a rooted tree is a **directed** graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents. + +The given input is a directed graph that started as a rooted tree with `n` nodes (with distinct values from `1` to `n`), with one additional directed edge added. The added edge has two different vertices chosen from `1` to `n`, and was not an edge that already existed. + +The resulting graph is given as a 2D-array of `edges`. Each element of `edges` is a pair [ui, vi] that represents a **directed** edge connecting nodes ui and vi, where ui is a parent of child vi. + +Return _an edge that can be removed so that the resulting graph is a rooted tree of_ `n` _nodes_. If there are multiple answers, return the answer that occurs last in the given 2D-array. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/12/20/graph1.jpg) + +**Input:** edges = \[\[1,2],[1,3],[2,3]] + +**Output:** [2,3] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/12/20/graph2.jpg) + +**Input:** edges = \[\[1,2],[2,3],[3,4],[4,1],[1,5]] + +**Output:** [4,1] + +**Constraints:** + +* `n == edges.length` +* `3 <= n <= 1000` +* `edges[i].length == 2` +* 1 <= ui, vi <= n +* ui != vi + +## Solution + +```kotlin +class Solution { + private lateinit var par: IntArray + fun findRedundantDirectedConnection(edges: Array): IntArray { + val n = edges.size + val hasPar = IntArray(n + 1) + for (edge in edges) { + val v = edge[1] + hasPar[v]++ + } + par = IntArray(n + 1) + for (i in par.indices) { + par[i] = i + } + for (edge in edges) { + val u = edge[0] + val v = edge[1] + if (hasPar[v] == 1) { + val lu = find(u) + val lv = find(v) + if (lu != lv) { + par[lu] = lv + } else { + return edge + } + } + } + for (edge in edges) { + val u = edge[0] + val v = edge[1] + if (hasPar[v] > 1) { + val lu = find(u) + val lv = find(v) + if (lu != lv) { + par[lu] = lv + } else { + return edge + } + } + } + return IntArray(2) + } + + private fun find(x: Int): Int { + return if (par[x] == x) { + x + } else find(par[x]) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0686_repeated_string_match/readme.md b/src/main/kotlin/g0601_0700/s0686_repeated_string_match/readme.md new file mode 100644 index 00000000..819879e5 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0686_repeated_string_match/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) + +## 686\. Repeated String Match + +Medium + +Given two strings `a` and `b`, return _the minimum number of times you should repeat string_ `a` _so that string_ `b` _is a substring of it_. If it is impossible for `b` to be a substring of `a` after repeating it, return `-1`. + +**Notice:** string `"abc"` repeated 0 times is `""`, repeated 1 time is `"abc"` and repeated 2 times is `"abcabc"`. + +**Example 1:** + +**Input:** a = "abcd", b = "cdabcdab" + +**Output:** 3 + +**Explanation:** We return 3 because by repeating a three times "ab**cdabcdab**cd", b is a substring of it. + +**Example 2:** + +**Input:** a = "a", b = "aa" + +**Output:** 2 + +**Constraints:** + +* 1 <= a.length, b.length <= 104 +* `a` and `b` consist of lowercase English letters. + +## Solution + +```kotlin +class Solution { + fun repeatedStringMatch(a: String, b: String): Int { + val existsChar = CharArray(127) + for (chA in a.toCharArray()) { + existsChar[chA.code] = 1.toChar() + } + for (chB in b.toCharArray()) { + if (existsChar[chB.code].code < 1) { + return -1 + } + } + val lenB = b.length - 1 + val sb = StringBuilder(a) + var lenSbA = sb.length - 1 + var repeatCount = 1 + while (lenSbA < lenB) { + sb.append(a) + repeatCount++ + lenSbA = sb.length - 1 + } + if (!isFound(sb, b)) { + sb.append(a) + repeatCount++ + return if (!isFound(sb, b)) -1 else repeatCount + } + return repeatCount + } + + private fun isFound(a: StringBuilder, b: String): Boolean { + for (i in a.indices) { + var k = i + var m = 0 + while (k < a.length && m < b.length) { + if (a[k] != b[m]) { + break + } else { + k++ + m++ + } + } + if (m == b.length) { + return true + } + } + return false + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0687_longest_univalue_path/readme.md b/src/main/kotlin/g0601_0700/s0687_longest_univalue_path/readme.md new file mode 100644 index 00000000..c8282e72 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0687_longest_univalue_path/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) + +## 687\. Longest Univalue Path + +Medium + +Given the `root` of a binary tree, return _the length of the longest path, where each node in the path has the same value_. This path may or may not pass through the root. + +**The length of the path** between two nodes is represented by the number of edges between them. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/13/ex1.jpg) + +**Input:** root = [5,4,5,1,1,null,5] + +**Output:** 2 + +**Explanation:** The shown image shows that the longest path of the same value (i.e. 5). + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/10/13/ex2.jpg) + +**Input:** root = [1,4,5,4,4,null,5] + +**Output:** 2 + +**Explanation:** The shown image shows that the longest path of the same value (i.e. 4). + +**Constraints:** + +* The number of nodes in the tree is in the range [0, 104]. +* `-1000 <= Node.val <= 1000` +* The depth of the tree will not exceed `1000`. + +## Solution + +```kotlin +import com_github_leetcode.TreeNode + +/* + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun longestUnivaluePath(root: TreeNode?): Int { + if (root == null) { + return 0 + } + val res = IntArray(1) + preorderLongestSinglePathLen(root, res) + return res[0] + } + + private fun preorderLongestSinglePathLen(root: TreeNode?, res: IntArray): Int { + if (root == null) { + return -1 + } + var left = preorderLongestSinglePathLen(root.left, res) + var right = preorderLongestSinglePathLen(root.right, res) + left = if (root.left == null || root.`val` == root.left!!.`val`) { + left + 1 + } else { + 0 + } + right = if (root.right == null || root.`val` == root.right!!.`val`) { + right + 1 + } else { + 0 + } + val longestPathLenPassingThroughRoot = left + right + res[0] = res[0].coerceAtLeast(longestPathLenPassingThroughRoot) + return left.coerceAtLeast(right) + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0688_knight_probability_in_chessboard/readme.md b/src/main/kotlin/g0601_0700/s0688_knight_probability_in_chessboard/readme.md new file mode 100644 index 00000000..5e895201 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0688_knight_probability_in_chessboard/readme.md @@ -0,0 +1,87 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 688\. Knight Probability in Chessboard + +Medium + +On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`. + +A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. + +![](https://assets.leetcode.com/uploads/2018/10/12/knight.png) + +Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. + +The knight continues moving until it has made exactly `k` moves or has moved off the chessboard. + +Return _the probability that the knight remains on the board after it has stopped moving_. + +**Example 1:** + +**Input:** n = 3, k = 2, row = 0, column = 0 + +**Output:** 0.06250 + +**Explanation:** There are two moves (to (1,2), (2,1)) that will keep the knight on the board. From each of those positions, there are also two moves that will keep the knight on the board. The total probability the knight stays on the board is 0.0625. + +**Example 2:** + +**Input:** n = 1, k = 0, row = 0, column = 0 + +**Output:** 1.00000 + +**Constraints:** + +* `1 <= n <= 25` +* `0 <= k <= 100` +* `0 <= row, column <= n - 1` + +## Solution + +```kotlin +class Solution { + private val directions = arrayOf( + intArrayOf(-2, -1), + intArrayOf(-2, 1), + intArrayOf(-1, 2), + intArrayOf(1, 2), + intArrayOf(2, -1), + intArrayOf(2, 1), + intArrayOf(1, -2), + intArrayOf(-1, -2) + ) + private lateinit var probabilityGiven: Array> + fun knightProbability(n: Int, k: Int, row: Int, column: Int): Double { + probabilityGiven = Array(n) { + Array(n) { + DoubleArray( + k + 1 + ) + } + } + return probability(row, column, k, n) + } + + private fun probability(row: Int, column: Int, k: Int, n: Int): Double { + return if (k == 0) { + 1.0 + } else if (probabilityGiven[row][column][k] != 0.0) { + probabilityGiven[row][column][k] + } else { + var p = 0.0 + for (dir in directions) { + if (isValid(row + dir[0], column + dir[1], n)) { + p += probability(row + dir[0], column + dir[1], k - 1, n) + } + } + probabilityGiven[row][column][k] = p / 8.0 + probabilityGiven[row][column][k] + } + } + + private fun isValid(row: Int, column: Int, n: Int): Boolean { + return row in 0 until n && column >= 0 && column < n + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0689_maximum_sum_of_3_non_overlapping_subarrays/readme.md b/src/main/kotlin/g0601_0700/s0689_maximum_sum_of_3_non_overlapping_subarrays/readme.md new file mode 100644 index 00000000..d7acd91b --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0689_maximum_sum_of_3_non_overlapping_subarrays/readme.md @@ -0,0 +1,103 @@ +[![](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) + +## 689\. Maximum Sum of 3 Non-Overlapping Subarrays + +Hard + +Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them. + +Return the result as a list of indices representing the starting position of each interval (**0-indexed**). If there are multiple answers, return the lexicographically smallest one. + +**Example 1:** + +**Input:** nums = [1,2,1,2,6,7,5,1], k = 2 + +**Output:** [0,3,5] + +**Explanation:** + +Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5]. + +We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger. + +**Example 2:** + +**Input:** nums = [1,2,1,2,1,2,1,2,1], k = 2 + +**Output:** [0,2,4] + +**Constraints:** + +* 1 <= nums.length <= 2 * 104 +* 1 <= nums[i] < 216 +* `1 <= k <= floor(nums.length / 3)` + +## Solution + +```kotlin +class Solution { + fun maxSumOfThreeSubarrays(nums: IntArray, k: Int): IntArray { + val len = nums.size + if (len < 3 * k) { + return intArrayOf() + } + val res = IntArray(3) + val left = Array(2) { IntArray(len) } + val right = Array(2) { IntArray(len) } + var s = 0 + for (i in 0 until k) { + s += nums[i] + } + left[0][k - 1] = s + run { + var i = k + while (i + 2 * k <= len) { + s = s + nums[i] - nums[i - k] + if (s > left[0][i - 1]) { + left[0][i] = s + left[1][i] = i - k + 1 + } else { + left[0][i] = left[0][i - 1] + left[1][i] = left[1][i - 1] + } + i++ + } + } + s = 0 + for (i in len - 1 downTo len - k) { + s += nums[i] + } + right[0][len - k] = s + right[1][len - k] = len - k + for (i in len - k - 1 downTo 0) { + s = s + nums[i] - nums[i + k] + if (s >= right[0][i + 1]) { + right[0][i] = s + right[1][i] = i + } else { + right[0][i] = right[0][i + 1] + right[1][i] = right[1][i + 1] + } + } + var mid = 0 + for (i in k until 2 * k) { + mid += nums[i] + } + var max = 0 + var i = k + while (i + 2 * k <= len) { + val total = left[0][i - 1] + right[0][i + k] + mid + if (total > max) { + res[0] = left[1][i - 1] + res[1] = i + res[2] = right[1][i + k] + max = total + } + mid = mid + nums[i + k] - nums[i] + i++ + } + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0690_employee_importance/readme.md b/src/main/kotlin/g0601_0700/s0690_employee_importance/readme.md new file mode 100644 index 00000000..eaee504f --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0690_employee_importance/readme.md @@ -0,0 +1,79 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork) + +## 690\. Employee Importance + +Medium + +You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs. + +You are given an array of employees `employees` where: + +* `employees[i].id` is the ID of the ith employee. +* `employees[i].importance` is the importance value of the ith employee. +* `employees[i].subordinates` is a list of the IDs of the direct subordinates of the ith employee. + +Given an integer `id` that represents an employee's ID, return _the **total** importance value of this employee and all their direct and indirect subordinates_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/05/31/emp1-tree.jpg) + +**Input:** employees = \[\[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1 + +**Output:** 11 + +**Explanation:** Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3. They both have an importance value of 3. Thus, the total importance value of employee 1 is 5 + 3 + 3 = 11. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/05/31/emp2-tree.jpg) + +**Input:** employees = \[\[1,2,[5]],[5,-3,[]]], id = 5 + +**Output:** -3 + +**Explanation:** Employee 5 has an importance value of -3 and has no direct subordinates. Thus, the total importance value of employee 5 is -3. + +**Constraints:** + +* `1 <= employees.length <= 2000` +* `1 <= employees[i].id <= 2000` +* All `employees[i].id` are **unique**. +* `-100 <= employees[i].importance <= 100` +* One employee has at most one direct leader and may have several subordinates. +* The IDs in `employees[i].subordinates` are valid IDs. + +## Solution + +```kotlin +import com_github_leetcode.Employee + +/* + * // Definition for Employee. + * class Employee { + * var id:Int = 0 + * var importance:Int = 0 + * var subordinates:List = listOf() + * } + */ + +class Solution { + fun getImportance(employees: List, id: Int): Int { + val map: MutableMap = HashMap() + for (emp in employees) { + map[emp!!.id] = emp + } + return calculateImportance(id, map) + } + + private fun calculateImportance(id: Int, map: Map): Int { + val employee = map[id] + var sum = employee!!.importance + for (sub in employee.subordinates) { + sum += calculateImportance(sub, map) + } + return sum + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0691_stickers_to_spell_word/readme.md b/src/main/kotlin/g0601_0700/s0691_stickers_to_spell_word/readme.md new file mode 100644 index 00000000..16916368 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0691_stickers_to_spell_word/readme.md @@ -0,0 +1,105 @@ +[![](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) + +## 691\. Stickers to Spell Word + +Hard + +We are given `n` different types of `stickers`. Each sticker has a lowercase English word on it. + +You would like to spell out the given string `target` by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker. + +Return _the minimum number of stickers that you need to spell out_ `target`. If the task is impossible, return `-1`. + +**Note:** In all test cases, all words were chosen randomly from the `1000` most common US English words, and `target` was chosen as a concatenation of two random words. + +**Example 1:** + +**Input:** stickers = ["with","example","science"], target = "thehat" + +**Output:** 3 + +**Explanation:** We can use 2 "with" stickers, and 1 "example" sticker. After cutting and rearrange the letters of those stickers, we can form the target "thehat". Also, this is the minimum number of stickers necessary to form the target string. + +**Example 2:** + +**Input:** stickers = ["notice","possible"], target = "basicbasic" + +**Output:** -1 Explanation: We cannot form the target "basicbasic" from cutting letters from the given stickers. + +**Constraints:** + +* `n == stickers.length` +* `1 <= n <= 50` +* `1 <= stickers[i].length <= 10` +* `1 <= target.length <= 15` +* `stickers[i]` and `target` consist of lowercase English letters. + +## Solution + +```kotlin +class Solution { + // count the characters of every sticker + private lateinit var counts: Array + + // For each character, save the sticker index which has this character + private val map: HashMap> = HashMap() + private val cache: HashMap = HashMap() + fun minStickers(stickers: Array, target: String): Int { + counts = Array(stickers.size) { IntArray(26) } + for (i in 0..25) { + map[('a'.code + i).toChar()] = HashSet() + } + for (i in stickers.indices) { + for (c in stickers[i].toCharArray()) { + counts[i][c.code - 'a'.code]++ + map[c]!!.add(i) + } + } + val res = dp(0, target) + return if (res > target.length) { + -1 + } else res + } + + private fun dp(bits: Int, target: String): Int { + val len = target.length + if (bits == (1 shl len) - 1) { + // all bits are 1 + return 0 + } + if (cache.containsKey(bits)) { + return cache[bits]!! + } + var index = 0 + // find the first bit which is 0 + for (i in 0 until len) { + if (bits and (1 shl i) == 0) { + index = i + break + } + } + // In worst case, each character use 1 sticker. So, len + 1 means impossible + var res = len + 1 + for (key in map[target[index]]!!) { + val count = counts[key].clone() + var mask = bits + for (i in index until len) { + if (mask and (1 shl i) != 0) { + // this bit has already been 1 + continue + } + val c = target[i] + if (count[c.code - 'a'.code] > 0) { + count[c.code - 'a'.code]-- + mask = mask or (1 shl i) + } + } + val `val` = dp(mask, target) + 1 + res = res.coerceAtMost(`val`) + } + cache[bits] = res + return res + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0692_top_k_frequent_words/readme.md b/src/main/kotlin/g0601_0700/s0692_top_k_frequent_words/readme.md new file mode 100644 index 00000000..dabda6cf --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0692_top_k_frequent_words/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) + +## 692\. Top K Frequent Words + +Medium + +Given an array of strings `words` and an integer `k`, return _the_ `k` _most frequent strings_. + +Return the answer **sorted** by **the frequency** from highest to lowest. Sort the words with the same frequency by their **lexicographical order**. + +**Example 1:** + +**Input:** words = ["i","love","leetcode","i","love","coding"], k = 2 + +**Output:** ["i","love"] + +**Explanation:** "i" and "love" are the two most frequent words. Note that "i" comes before "love" due to a lower alphabetical order. + +**Example 2:** + +**Input:** words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4 + +**Output:** ["the","is","sunny","day"] + +**Explanation:** "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively. + +**Constraints:** + +* `1 <= words.length <= 500` +* `1 <= words[i].length <= 10` +* `words[i]` consists of lowercase English letters. +* `k` is in the range [1, The number of **unique** words[i]] + +**Follow-up:** Could you solve it in `O(n log(k))` time and `O(n)` extra space? + +## Solution + +```kotlin +import java.util.SortedSet +import java.util.TreeSet + +@Suppress("NAME_SHADOWING") +class Solution { + fun topKFrequent(words: Array, k: Int): List { + var k = k + val map: MutableMap = HashMap() + for (word in words) { + map[word] = map.getOrDefault(word, 0) + 1 + } + val sortedset: SortedSet> = TreeSet( + java.util.Comparator { (key, value): Map.Entry, (key1, value1): Map.Entry -> + if (value != value1) { + return@Comparator value1 - value + } else { + return@Comparator key.compareTo(key1, ignoreCase = true) + } + } + ) + sortedset.addAll(map.entries) + val result: MutableList = ArrayList() + val iterator: Iterator> = sortedset.iterator() + while (iterator.hasNext() && k-- > 0) { + result.add(iterator.next().key) + } + return result + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0693_binary_number_with_alternating_bits/readme.md b/src/main/kotlin/g0601_0700/s0693_binary_number_with_alternating_bits/readme.md new file mode 100644 index 00000000..b8996dad --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0693_binary_number_with_alternating_bits/readme.md @@ -0,0 +1,57 @@ +[![](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) + +## 693\. Binary Number with Alternating Bits + +Easy + +Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. + +**Example 1:** + +**Input:** n = 5 + +**Output:** true + +**Explanation:** The binary representation of 5 is: 101 + +**Example 2:** + +**Input:** n = 7 + +**Output:** false + +**Explanation:** The binary representation of 7 is: 111. + +**Example 3:** + +**Input:** n = 11 + +**Output:** false + +**Explanation:** The binary representation of 11 is: 1011. + +**Constraints:** + +* 1 <= n <= 231 - 1 + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun hasAlternatingBits(n: Int): Boolean { + var n = n + var prev = -1 + while (n != 0) { + val v = n and 1 + n = n shr 1 + if (prev == v) { + return false + } + prev = v + } + return true + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0695_max_area_of_island/readme.md b/src/main/kotlin/g0601_0700/s0695_max_area_of_island/readme.md new file mode 100644 index 00000000..3a5d78cb --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0695_max_area_of_island/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) + +## 695\. Max Area of Island + +Medium + +You are given an `m x n` binary matrix `grid`. An island is a group of `1`'s (representing land) connected **4-directionally** (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. + +The **area** of an island is the number of cells with a value `1` in the island. + +Return _the maximum **area** of an island in_ `grid`. If there is no island, return `0`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/05/01/maxarea1-grid.jpg) + +**Input:** grid = \[\[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]] + +**Output:** 6 + +**Explanation:** The answer is not 11, because the island must be connected 4-directionally. + +**Example 2:** + +**Input:** grid = \[\[0,0,0,0,0,0,0,0]] + +**Output:** 0 + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `1 <= m, n <= 50` +* `grid[i][j]` is either `0` or `1`. + +## Solution + +```kotlin +@Suppress("NAME_SHADOWING") +class Solution { + fun maxAreaOfIsland(grid: Array?): Int { + if (grid.isNullOrEmpty()) { + return 0 + } + val m = grid.size + val n = grid[0].size + var max = 0 + for (i in 0 until m) { + for (j in 0 until n) { + if (grid[i][j] == 1) { + val area = dfs(grid, i, j, m, n, 0) + max = Math.max(area, max) + } + } + } + return max + } + + private fun dfs(grid: Array, i: Int, j: Int, m: Int, n: Int, area: Int): Int { + var area = area + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) { + return area + } + grid[i][j] = 0 + area++ + area = dfs(grid, i + 1, j, m, n, area) + area = dfs(grid, i, j + 1, m, n, area) + area = dfs(grid, i - 1, j, m, n, area) + area = dfs(grid, i, j - 1, m, n, area) + return area + } +} +``` \ No newline at end of file diff --git a/src/main/kotlin/g0601_0700/s0696_count_binary_substrings/readme.md b/src/main/kotlin/g0601_0700/s0696_count_binary_substrings/readme.md new file mode 100644 index 00000000..c56ec5f8 --- /dev/null +++ b/src/main/kotlin/g0601_0700/s0696_count_binary_substrings/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) + +## 696\. Count Binary Substrings + +Easy + +Given a binary string `s`, return the number of non-empty substrings that have the same number of `0`'s and `1`'s, and all the `0`'s and all the `1`'s in these substrings are grouped consecutively. + +Substrings that occur multiple times are counted the number of times they occur. + +**Example 1:** + +**Input:** s = "00110011" + +**Output:** 6 + +**Explanation:** There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01". Notice that some of these substrings repeat and are counted the number of times they occur. Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together. + +**Example 2:** + +**Input:** s = "10101" + +**Output:** 4 + +**Explanation:** There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's. + +**Constraints:** + +* 1 <= s.length <= 105 +* `s[i]` is either `'0'` or `'1'`. + +## Solution + +```kotlin +class Solution { + fun countBinarySubstrings(s: String): Int { + var start = 0 + var ans = 0 + val arr = s.toCharArray() + for (i in 1 until arr.size) { + if (arr[i] != arr[i - 1]) { + ans++ + start = i - 1 + } else if (start > 0 && arr[--start] != arr[i]) { + // if start isn't 0, we may still have a valid substring + ans++ + } else { + // if not, then reset start to 0 + start = 0 + } + } + return ans + } +} +``` \ No newline at end of file