├── .gitignore ├── GenerateReadMe.kts ├── README.md ├── easy ├── 1.two-sum.kt ├── 104.maximum-depth-of-binary-tree.kt ├── 112.path-sum.kt ├── 13.roman-to-integer.kt ├── 1309.decrypt-string-from-alphabet-to-integer-mapping.kt ├── 1370.increasing-decreasing-string.kt ├── 1374.generate-a-string-with-characters-that-have-odd-counts.kt ├── 1380.lucky-numbers-in-a-matrix.kt ├── 14.longest-common-prefix.kt ├── 1550.three-consecutive-odds.kt ├── 1582.special-positions-in-a-binary-matrix.kt ├── 169.majority-element.kt ├── 198.house-robber.kt ├── 2.add-two-numbers.kt ├── 20.valid-parentheses.kt ├── 204.count-primes.kt ├── 21.merge-two-sorted-lists.kt ├── 26.remove-duplicates-from-sorted-array.kt ├── 268.missing-number.kt ├── 27.remove-element.kt ├── 28.implement-str-str.kt ├── 303.range-sum-query-immutable.kt ├── 38.count-and-say.kt ├── 53.maximum-subarray.kt ├── 67.add-binary.kt ├── 69.sqrt-x.kt ├── 7.reverse-integer.kt ├── 70.climbing-stairs.kt ├── 859.buddy-strings.kt ├── 872.leaf-similar-trees.kt ├── 9.palindrome-number.kt └── 999.available-captures-for-rook.kt ├── hard ├── 10.regular-expression-matching.kt ├── 1377.frog-position-after-t-seconds.kt ├── 140.word-break-ii.kt ├── 1473.paint-house-iii.kt ├── 1585.check-if-string-is-transformable-with-substring-sort-operations.kt ├── 23.merge-k-sorted-lists.kt ├── 25.reverse-nodes-in-k-group.kt ├── 32.longest-valid-parentheses.kt ├── 329.longest-increasing-path-in-a-matrix.kt ├── 44.wildcard-matching.kt ├── 72.edit-distance.kt └── 85.maximal-rectangle.kt └── medium ├── 1038.binary-search-tree-to-greater-sum-tree.kt ├── 11.container-with-most-water.kt ├── 114.flatten-binary-tree-to-linked-list.kt ├── 12.integer-to-roman.kt ├── 120.triangle.kt ├── 127.word-ladder.kt ├── 1305.all-elements-in-two-binary-search-trees.kt ├── 1306.jump-game-iii.kt ├── 134.gas-station.kt ├── 1362.closest-divisors.kt ├── 1375.bulb-switcher-iii.kt ├── 1376.time-needed-to-inform-all-employees.kt ├── 1381.design-a-stack-with-increment-operation.kt ├── 1382.balance-a-binary-search-tree.kt ├── 139.word-break.kt ├── 1404.number-of-steps-to-reduce-a-number-in-binary-representation-to-one.kt ├── 1405.longest-happy-string.kt ├── 1472.design-browser-history.kt ├── 1487.making-file-names-unique.kt ├── 15.3-sum.kt ├── 1551.minimum-operations-to-make-array-equal.kt ├── 1552.magnetic-force-between-two-balls.kt ├── 1583.count-unhappy-friends.kt ├── 1584.min-cost-to-connect-all-points.kt ├── 1589.maximum-sum-obtained-of-any-permutation.kt ├── 16.3-sum-closest.kt ├── 162.find-peak-element.kt ├── 17.letter-combinations-of-a-phone-number.kt ├── 18.4-sum.kt ├── 19.remove-nth-node-from-end-of-list.kt ├── 207.course-schedule.kt ├── 210.course-schedule-ii.kt ├── 213.house-robber-ii.kt ├── 22.generate-parentheses.kt ├── 24.swap-nodes-in-pairs.kt ├── 264.ugly-number-ii.kt ├── 279.perfect-squares.kt ├── 29.divide-two-integers.kt ├── 3.longest-substring-without-repeating-characters.kt ├── 300.longest-increasing-subsequence.kt ├── 304.range-sum-query-2-d-immutable.kt ├── 31.next-permutation.kt ├── 310.minimum-height-trees.kt ├── 322.coin-change.kt ├── 34.find-first-and-last-position-of-element-in-sorted-array.kt ├── 372.super-pow.kt ├── 402.remove-k-digits.kt ├── 5.longest-palindromic-substring.kt ├── 50.pow-x-n.kt ├── 515.find-largest-value-in-each-tree-row.kt ├── 55.jump-game.kt ├── 6.zig-zag-conversion.kt ├── 60.permutation-sequence.kt ├── 62.unique-paths.kt ├── 621.task-scheduler.kt ├── 63.unique-paths-ii.kt ├── 64.minimum-path-sum.kt ├── 8.string-to-integer-atoi.kt ├── 869.reordered-power-of-2.kt ├── 91.decode-ways.kt ├── 94.binary-tree-inorder-traversal.kt ├── 95.unique-binary-search-trees-ii.kt ├── 96.unique-binary-search-trees.kt └── 98.validate-binary-search-tree.kt /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | leetcode/ 3 | *.cpp 4 | *.jar 5 | .sh 6 | 7 | -------------------------------------------------------------------------------- /GenerateReadMe.kts: -------------------------------------------------------------------------------- 1 | import java.io.File 2 | 3 | fun readFiles(filename: String, readmeContents: MutableList>): Int { 4 | val easyFolder = File("./${filename}").walk() 5 | var numOfFiles = 0 6 | easyFolder.maxDepth(1) 7 | .filter { it.isFile } 8 | .filter { it.extension == "kt" || it.extension == "cpp"} 9 | .forEach { f -> 10 | val ext = if (f.extension == "kt") "Kotlin" else "C++" 11 | val name = f.name 12 | val c = if (name[0] == '[') ']' else '.' 13 | val firstIndex = name.indexOf(c, 0) 14 | 15 | var id: String 16 | var title: String = name.substring(firstIndex+1, name.length-3) 17 | 18 | 19 | if (c == '.') { // coding in VS-Code 20 | id = name.substring(0, firstIndex) 21 | } else { // coding in IDEA 22 | id = name.substring(1, firstIndex) 23 | title = title.toLowerCase().split(' ').joinToString("-") 24 | f.renameTo(File("./$filename/${id}.${title}.${f.extension}")) 25 | } 26 | val leetcodeLink = "[$title](https://leetcode.com/problems/$title/description/)" 27 | readmeContents.add( 28 | Pair( 29 | id.toInt(), 30 | "| $id | $leetcodeLink | [$ext](./$filename/${id}.${title}.${f.extension}) | ${filename.capitalize()} |\n" 31 | ) 32 | ) 33 | numOfFiles++ 34 | } 35 | return numOfFiles 36 | } 37 | 38 | var readmeContents = mutableListOf>() 39 | val easy_problems = readFiles("easy", readmeContents) 40 | val hard_problems = readFiles("hard", readmeContents) 41 | val medium_problems = readFiles("medium", readmeContents) 42 | 43 | val file = File("./README.md") 44 | 45 | // clear content 46 | file.writeText("# LeetCode\n") 47 | 48 | // append content 49 | file.appendText("**Total problems: ${easy_problems+medium_problems+hard_problems}, easy: ${easy_problems}, medium: ${medium_problems}, hard: ${hard_problems}**\n") 50 | file.appendText("| # | Title | Solution | Difficulty |\n") 51 | file.appendText("| ------ | ------ | ------ | ------ |\n") 52 | 53 | readmeContents.sortBy( { it.first } ) 54 | readmeContents.forEach { 55 | file.appendText(it.second) 56 | } 57 | -------------------------------------------------------------------------------- /easy/1.two-sum.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1 lang=kotlin 3 | * 4 | * [1] Two Sum 5 | * 6 | * https://leetcode.com/problems/two-sum/description/ 7 | * 8 | * algorithms 9 | * Easy (43.27%) 10 | * Total Accepted: 1.7M 11 | * Total Submissions: 3.9M 12 | * Testcase Example: '[2,7,11,15]\n9' 13 | * 14 | * Given an array of integers, return indices of the two numbers such that they 15 | * add up to a specific target. 16 | * 17 | * You may assume that each input would have exactly one solution, and you may 18 | * not use the same element twice. 19 | * 20 | * Example: 21 | * 22 | * 23 | * Given nums = [2, 7, 11, 15], target = 9, 24 | * 25 | * Because nums[0] + nums[1] = 2 + 7 = 9, 26 | * return [0, 1]. 27 | * 28 | * 29 | * 30 | * 31 | */ 32 | class Solution { 33 | fun twoSum(nums: IntArray, target: Int): IntArray { 34 | val mm = HashMap() 35 | 36 | var res = mutableListOf() 37 | 38 | for (i in nums.indices) { 39 | mm[nums[i]] = i 40 | } 41 | 42 | for (i in nums.indices) { 43 | val temp = mm.get(target - nums[i]) 44 | if (temp != null && (temp ?: -1) > i) { 45 | res.add(i) 46 | res.add(mm.getOrElse(target-nums[i], {0})) 47 | } 48 | } 49 | 50 | return res.toIntArray() 51 | } 52 | } 53 | 54 | -------------------------------------------------------------------------------- /easy/104.maximum-depth-of-binary-tree.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=104 lang=kotlin 3 | * 4 | * [104] Maximum Depth of Binary Tree 5 | * 6 | * https://leetcode.com/problems/maximum-depth-of-binary-tree/description/ 7 | * 8 | * algorithms 9 | * Easy (59.52%) 10 | * Total Accepted: 480.4K 11 | * Total Submissions: 802.8K 12 | * Testcase Example: '[3,9,20,null,null,15,7]' 13 | * 14 | * Given a binary tree, find its maximum depth. 15 | * 16 | * The maximum depth is the number of nodes along the longest path from the 17 | * root node down to the farthest leaf node. 18 | * 19 | * Note: A leaf is a node with no children. 20 | * 21 | * Example: 22 | * 23 | * Given binary tree [3,9,20,null,null,15,7], 24 | * 25 | * 26 | * ⁠ 3 27 | * ⁠ / \ 28 | * ⁠ 9 20 29 | * ⁠ / \ 30 | * ⁠ 15 7 31 | * 32 | * return its depth = 3. 33 | * 34 | */ 35 | /** 36 | * Example: 37 | * var ti = TreeNode(5) 38 | * var v = ti.`val` 39 | * Definition for a binary tree node. 40 | * class TreeNode(var `val`: Int) { 41 | * var left: TreeNode? = null 42 | * var right: TreeNode? = null 43 | * } 44 | */ 45 | class Solution { 46 | var res = 0 47 | fun maxDepth(root: TreeNode?): Int { 48 | if (root == null) return 0 49 | 50 | val left = maxDepth(root.left) 51 | val right = maxDepth(root.right) 52 | 53 | return if (left >= right) left+1 else right+1 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /easy/112.path-sum.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=112 lang=kotlin 3 | * 4 | * [112] Path Sum 5 | * 6 | * https://leetcode.com/problems/path-sum/description/ 7 | * 8 | * algorithms 9 | * Easy (38.47%) 10 | * Likes: 1093 11 | * Dislikes: 358 12 | * Total Accepted: 345.6K 13 | * Total Submissions: 896.5K 14 | * Testcase Example: '[5,4,8,11,null,13,4,7,2,null,null,null,1]\n22' 15 | * 16 | * Given a binary tree and a sum, determine if the tree has a root-to-leaf path 17 | * such that adding up all the values along the path equals the given sum. 18 | * 19 | * Note: A leaf is a node with no children. 20 | * 21 | * Example: 22 | * 23 | * Given the below binary tree and sum = 22, 24 | * 25 | * 26 | * ⁠ 5 27 | * ⁠ / \ 28 | * ⁠ 4 8 29 | * ⁠ / / \ 30 | * ⁠ 11 13 4 31 | * ⁠/ \ \ 32 | * 7 2 1 33 | * 34 | * 35 | * return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 36 | * 37 | */ 38 | /** 39 | * Example: 40 | * var ti = TreeNode(5) 41 | * var v = ti.`val` 42 | * Definition for a binary tree node. 43 | * class TreeNode(var `val`: Int) { 44 | * var left: TreeNode? = null 45 | * var right: TreeNode? = null 46 | * } 47 | */ 48 | class Solution { 49 | private var ans: Int = 0 50 | fun hasPathSum(root: TreeNode?, sum: Int): Boolean { 51 | if (root == null) return false 52 | val cnt = sum-root!!.`val` 53 | if (root?.left == null && root?.right == null && cnt == 0) 54 | return true 55 | return hasPathSum(root?.left, cnt) || 56 | hasPathSum(root?.right, cnt) 57 | } 58 | 59 | } 60 | 61 | -------------------------------------------------------------------------------- /easy/13.roman-to-integer.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=13 lang=kotlin 3 | * 4 | * [13] Roman to Integer 5 | */ 6 | class Solution { 7 | private val Rm2I = mapOf('I' to 1, 'V' to 5, 8 | 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000) 9 | 10 | fun romanToInt(s: String): Int { 11 | var res = 0 12 | var i = 0 13 | while (i < s.length) { 14 | if (i == s.length-1) { 15 | res += Rm2I[s[i]]!! 16 | break 17 | } 18 | if (Rm2I[s[i]]!! < Rm2I[s[i+1]]!!) { 19 | res += Rm2I[s[i+1]]!!-Rm2I[s[i]]!! 20 | i += 2 21 | } else { 22 | res += Rm2I[s[i]]!! 23 | i++ 24 | } 25 | } 26 | return res 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /easy/1309.decrypt-string-from-alphabet-to-integer-mapping.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1309 lang=kotlin 3 | * 4 | * [1309] Decrypt String from Alphabet to Integer Mapping 5 | * 6 | * https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/description/ 7 | * 8 | * algorithms 9 | * Easy (76.60%) 10 | * Likes: 118 11 | * Dislikes: 14 12 | * Total Accepted: 16.4K 13 | * Total Submissions: 21.4K 14 | * Testcase Example: '"10#11#12"' 15 | * 16 | * Given a string s formed by digits ('0' - '9') and '#' . We want to map s to 17 | * English lowercase characters as follows: 18 | * 19 | * 20 | * Characters ('a' to 'i') are represented by ('1' to '9') respectively. 21 | * Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.  22 | * 23 | * 24 | * Return the string formed after mapping. 25 | * 26 | * It's guaranteed that a unique mapping will always exist. 27 | * 28 | * 29 | * Example 1: 30 | * 31 | * 32 | * Input: s = "10#11#12" 33 | * Output: "jkab" 34 | * Explanation: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2". 35 | * 36 | * 37 | * Example 2: 38 | * 39 | * 40 | * Input: s = "1326#" 41 | * Output: "acz" 42 | * 43 | * 44 | * Example 3: 45 | * 46 | * 47 | * Input: s = "25#" 48 | * Output: "y" 49 | * 50 | * 51 | * Example 4: 52 | * 53 | * 54 | * Input: s = "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#" 55 | * Output: "abcdefghijklmnopqrstuvwxyz" 56 | * 57 | * 58 | * 59 | * Constraints: 60 | * 61 | * 62 | * 1 <= s.length <= 1000 63 | * s[i] only contains digits letters ('0'-'9') and '#' letter. 64 | * s will be valid string such that mapping is always possible. 65 | * 66 | */ 67 | 68 | // @lc code=start 69 | class Solution { 70 | fun freqAlphabets(s: String): String { 71 | var res = ""; 72 | var i = s.length-1 73 | while (i >= 0){ 74 | if (s[i] == '#') { 75 | res += ("${s[i-2]}${s[i-1]}".toInt()+'a'.toInt()-1).toChar() 76 | i -= 3 77 | } else { 78 | res += ("${s[i]}".toInt()+'a'.toInt()-1).toChar() 79 | i-- 80 | } 81 | } 82 | return res.reversed() 83 | 84 | } 85 | } 86 | 87 | // @lc code=end 88 | 89 | -------------------------------------------------------------------------------- /easy/1370.increasing-decreasing-string.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1370 lang=kotlin 3 | * 4 | * [1370] Increasing Decreasing String 5 | * 6 | * https://leetcode.com/problems/increasing-decreasing-string/description/ 7 | * 8 | * algorithms 9 | * Easy (78.72%) 10 | * Likes: 51 11 | * Dislikes: 34 12 | * Total Accepted: 5.3K 13 | * Total Submissions: 6.8K 14 | * Testcase Example: '"aaaabbbbcccc"' 15 | * 16 | * Given a string s. You should re-order the string using the following 17 | * algorithm: 18 | * 19 | * 20 | * Pick the smallest character from s and append it to the result. 21 | * Pick the smallest character from s which is greater than the last appended 22 | * character to the result and append it. 23 | * Repeat step 2 until you cannot pick more characters. 24 | * Pick the largest character from s and append it to the result. 25 | * Pick the largest character from s which is smaller than the last appended 26 | * character to the result and append it. 27 | * Repeat step 5 until you cannot pick more characters. 28 | * Repeat the steps from 1 to 6 until you pick all characters from s. 29 | * 30 | * 31 | * In each step, If the smallest or the largest character appears more than 32 | * once you can choose any occurrence and append it to the result. 33 | * 34 | * Return the result string after sorting s with this algorithm. 35 | * 36 | * 37 | * Example 1: 38 | * 39 | * 40 | * Input: s = "aaaabbbbcccc" 41 | * Output: "abccbaabccba" 42 | * Explanation: After steps 1, 2 and 3 of the first iteration, result = "abc" 43 | * After steps 4, 5 and 6 of the first iteration, result = "abccba" 44 | * First iteration is done. Now s = "aabbcc" and we go back to step 1 45 | * After steps 1, 2 and 3 of the second iteration, result = "abccbaabc" 46 | * After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba" 47 | * 48 | * 49 | * Example 2: 50 | * 51 | * 52 | * Input: s = "rat" 53 | * Output: "art" 54 | * Explanation: The word "rat" becomes "art" after re-ordering it with the 55 | * mentioned algorithm. 56 | * 57 | * 58 | * Example 3: 59 | * 60 | * 61 | * Input: s = "leetcode" 62 | * Output: "cdelotee" 63 | * 64 | * 65 | * Example 4: 66 | * 67 | * 68 | * Input: s = "ggggggg" 69 | * Output: "ggggggg" 70 | * 71 | * 72 | * Example 5: 73 | * 74 | * 75 | * Input: s = "spo" 76 | * Output: "ops" 77 | * 78 | * 79 | * 80 | * Constraints: 81 | * 82 | * 83 | * 1 <= s.length <= 500 84 | * s contains only lower-case English letters. 85 | * 86 | * 87 | */ 88 | 89 | // @lc code=start 90 | class Solution { 91 | fun sortString(s: String): String { 92 | var ans = StringBuilder() 93 | var cnt = IntArray(26) 94 | for (c in s) cnt[c-'a']++ 95 | while (ans.length < s.length) { 96 | add(cnt, ans, true) 97 | add(cnt, ans, false) 98 | } 99 | return ans.toString() 100 | } 101 | 102 | private fun add(cnt: IntArray, ans: StringBuilder, asc:Boolean) { 103 | for (i in 0 until 26) { 104 | val j = if (asc) i else 25-i 105 | if (cnt[j]-- > 0) 106 | ans.append((j+'a'.toInt()).toChar()) 107 | } 108 | } 109 | } 110 | // @lc code=end 111 | 112 | -------------------------------------------------------------------------------- /easy/1374.generate-a-string-with-characters-that-have-odd-counts.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1374 lang=kotlin 3 | * 4 | * [1374] Generate a String With Characters That Have Odd Counts 5 | * 6 | * https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/description/ 7 | * 8 | * algorithms 9 | * Easy (77.26%) 10 | * Likes: 10 11 | * Dislikes: 29 12 | * Total Accepted: 7.8K 13 | * Total Submissions: 10.1K 14 | * Testcase Example: '4' 15 | * 16 | * Given an integer n, return a string with n characters such that each 17 | * character in such string occurs an odd number of times. 18 | * 19 | * The returned string must contain only lowercase English letters. If there 20 | * are multiples valid strings, return any of them.   21 | * 22 | * 23 | * Example 1: 24 | * 25 | * 26 | * Input: n = 4 27 | * Output: "pppz" 28 | * Explanation: "pppz" is a valid string since the character 'p' occurs three 29 | * times and the character 'z' occurs once. Note that there are many other 30 | * valid strings such as "ohhh" and "love". 31 | * 32 | * 33 | * Example 2: 34 | * 35 | * 36 | * Input: n = 2 37 | * Output: "xy" 38 | * Explanation: "xy" is a valid string since the characters 'x' and 'y' occur 39 | * once. Note that there are many other valid strings such as "ag" and "ur". 40 | * 41 | * 42 | * Example 3: 43 | * 44 | * 45 | * Input: n = 7 46 | * Output: "holasss" 47 | * 48 | * 49 | * 50 | * Constraints: 51 | * 52 | * 53 | * 1 <= n <= 500 54 | * 55 | */ 56 | 57 | // @lc code=start 58 | class Solution { 59 | fun generateTheString(n: Int): String { 60 | var res = "" 61 | if (n%2 == 1) { 62 | for (i in 0 until n) res += "a" 63 | return res 64 | } else { 65 | for (i in 1 until n) res += "a" 66 | return res+"b" 67 | } 68 | } 69 | } 70 | // @lc code=end 71 | 72 | -------------------------------------------------------------------------------- /easy/1380.lucky-numbers-in-a-matrix.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1380 lang=kotlin 3 | * 4 | * [1380] Lucky Numbers in a Matrix 5 | * 6 | * https://leetcode.com/problems/lucky-numbers-in-a-matrix/description/ 7 | * 8 | * algorithms 9 | * Easy (76.49%) 10 | * Likes: 46 11 | * Dislikes: 2 12 | * Total Accepted: 7.3K 13 | * Total Submissions: 9.5K 14 | * Testcase Example: '[[3,7,8],[9,11,13],[15,16,17]]' 15 | * 16 | * Given a m * n matrix of distinct numbers, return all lucky numbers in the 17 | * matrix in any order. 18 | * 19 | * A lucky number is an element of the matrix such that it is the minimum 20 | * element in its row and maximum in its column. 21 | * 22 | * 23 | * Example 1: 24 | * 25 | * 26 | * Input: matrix = [[3,7,8],[9,11,13],[15,16,17]] 27 | * Output: [15] 28 | * Explanation: 15 is the only lucky number since it is the minimum in its row 29 | * and the maximum in its column 30 | * 31 | * 32 | * Example 2: 33 | * 34 | * 35 | * Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]] 36 | * Output: [12] 37 | * Explanation: 12 is the only lucky number since it is the minimum in its row 38 | * and the maximum in its column. 39 | * 40 | * 41 | * Example 3: 42 | * 43 | * 44 | * Input: matrix = [[7,8],[1,2]] 45 | * Output: [7] 46 | * 47 | * 48 | * 49 | * Constraints: 50 | * 51 | * 52 | * m == mat.length 53 | * n == mat[i].length 54 | * 1 <= n, m <= 50 55 | * 1 <= matrix[i][j] <= 10^5. 56 | * All elements in the matrix are distinct. 57 | * 58 | */ 59 | 60 | // @lc code=start 61 | class Solution { 62 | fun luckyNumbers (matrix: Array): List { 63 | val n = matrix.size 64 | val m = matrix[0].size 65 | val res = mutableListOf() 66 | for (i in 0 until n) { 67 | var temp = 1000000 68 | var pos = 0 69 | for (j in 0 until m) { 70 | if (matrix[i][j] < temp) { 71 | temp = matrix[i][j] 72 | pos = j 73 | } 74 | } 75 | var flag = true 76 | for (j in 0 until n) { 77 | if (j != i && matrix[j][pos] > temp) { 78 | flag = false 79 | break 80 | } 81 | } 82 | if (flag) res.add(temp) 83 | } 84 | return res 85 | } 86 | } 87 | // @lc code=end 88 | 89 | -------------------------------------------------------------------------------- /easy/14.longest-common-prefix.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=14 lang=kotlin 3 | * 4 | * [14] Longest Common Prefix 5 | * 6 | * https://leetcode.com/problems/longest-common-prefix/description/ 7 | * 8 | * algorithms 9 | * Easy (33.28%) 10 | * Likes: 1381 11 | * Dislikes: 1329 12 | * Total Accepted: 475.4K 13 | * Total Submissions: 1.4M 14 | * Testcase Example: '["flower","flow","flight"]' 15 | * 16 | * Write a function to find the longest common prefix string amongst an array 17 | * of strings. 18 | * 19 | * If there is no common prefix, return an empty string "". 20 | * 21 | * Example 1: 22 | * 23 | * 24 | * Input: ["flower","flow","flight"] 25 | * Output: "fl" 26 | * 27 | * 28 | * Example 2: 29 | * 30 | * 31 | * Input: ["dog","racecar","car"] 32 | * Output: "" 33 | * Explanation: There is no common prefix among the input strings. 34 | * 35 | * 36 | * Note: 37 | * 38 | * All given inputs are in lowercase letters a-z. 39 | * 40 | */ 41 | class Solution { 42 | fun longestCommonPrefix(strs: Array): String { 43 | if (strs.size == 0) return "" 44 | var len = 0 45 | var res = "" 46 | for (j in 0 until strs[0].length) { 47 | val c = strs[0][j] 48 | for (i in 1 until strs.size) { 49 | if (j >= strs[i].length || strs[i][j] != c) { 50 | return res 51 | } 52 | } 53 | res += c 54 | } 55 | return res 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /easy/1550.three-consecutive-odds.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1550 lang=kotlin 3 | * 4 | * [1550] Three Consecutive Odds 5 | * 6 | * https://leetcode.com/problems/three-consecutive-odds/description/ 7 | * 8 | * algorithms 9 | * Easy (68.07%) 10 | * Likes: 53 11 | * Dislikes: 8 12 | * Total Accepted: 11.9K 13 | * Total Submissions: 17.4K 14 | * Testcase Example: '[2,6,4,1]' 15 | * 16 | * Given an integer array arr, return true if there are three consecutive odd 17 | * numbers in the array. Otherwise, return false. 18 | * 19 | * Example 1: 20 | * 21 | * 22 | * Input: arr = [2,6,4,1] 23 | * Output: false 24 | * Explanation: There are no three consecutive odds. 25 | * 26 | * 27 | * Example 2: 28 | * 29 | * 30 | * Input: arr = [1,2,34,3,4,5,7,23,12] 31 | * Output: true 32 | * Explanation: [5,7,23] are three consecutive odds. 33 | * 34 | * 35 | * 36 | * Constraints: 37 | * 38 | * 39 | * 1 <= arr.length <= 1000 40 | * 1 <= arr[i] <= 1000 41 | * 42 | * 43 | */ 44 | 45 | // @lc code=start 46 | class Solution { 47 | fun threeConsecutiveOdds(arr: IntArray): Boolean { 48 | val n = arr.size 49 | for (i in 0 until arr.size-2) { 50 | if (arr[i]%2 == 1 && arr[i+1]%2 == 1 && arr[i+2]%2 == 1) { 51 | return true; 52 | } 53 | } 54 | return false; 55 | } 56 | } 57 | // @lc code=end 58 | 59 | -------------------------------------------------------------------------------- /easy/1582.special-positions-in-a-binary-matrix.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1582 lang=kotlin 3 | * 4 | * [1582] Special Positions in a Binary Matrix 5 | * 6 | * https://leetcode.com/problems/special-positions-in-a-binary-matrix/description/ 7 | * 8 | * algorithms 9 | * Easy (63.55%) 10 | * Likes: 84 11 | * Dislikes: 4 12 | * Total Accepted: 9.7K 13 | * Total Submissions: 15.2K 14 | * Testcase Example: '[[1,0,0],[0,0,1],[1,0,0]]' 15 | * 16 | * Given a rows x cols matrix mat, where mat[i][j] is either 0 or 1, return the 17 | * number of special positions in mat. 18 | * 19 | * A position (i,j) is called special if mat[i][j] == 1 and all other elements 20 | * in row i and column j are 0 (rows and columns are 0-indexed). 21 | * 22 | * 23 | * Example 1: 24 | * 25 | * 26 | * Input: mat = [[1,0,0], 27 | * [0,0,1], 28 | * [1,0,0]] 29 | * Output: 1 30 | * Explanation: (1,2) is a special position because mat[1][2] == 1 and all 31 | * other elements in row 1 and column 2 are 0. 32 | * 33 | * 34 | * Example 2: 35 | * 36 | * 37 | * Input: mat = [[1,0,0], 38 | * [0,1,0], 39 | * [0,0,1]] 40 | * Output: 3 41 | * Explanation: (0,0), (1,1) and (2,2) are special positions. 42 | * 43 | * 44 | * Example 3: 45 | * 46 | * 47 | * Input: mat = [[0,0,0,1], 48 | * [1,0,0,0], 49 | * [0,1,1,0], 50 | * [0,0,0,0]] 51 | * Output: 2 52 | * 53 | * 54 | * Example 4: 55 | * 56 | * 57 | * Input: mat = [[0,0,0,0,0], 58 | * [1,0,0,0,0], 59 | * [0,1,0,0,0], 60 | * [0,0,1,0,0], 61 | * [0,0,0,1,1]] 62 | * Output: 3 63 | * 64 | * 65 | * 66 | * Constraints: 67 | * 68 | * 69 | * rows == mat.length 70 | * cols == mat[i].length 71 | * 1 <= rows, cols <= 100 72 | * mat[i][j] is 0 or 1. 73 | * 74 | * 75 | */ 76 | 77 | // @lc code=start 78 | class Solution { 79 | fun numSpecial(mat: Array): Int { 80 | var res = 0 81 | for (i in 0 until mat.size) { 82 | var cnt = 0 83 | for (j in 0 until mat[0].size) { 84 | if (mat[i][j] == 1) { 85 | cnt++ 86 | if (cnt > 1) break 87 | var ok = true 88 | for (k in 0 until mat.size) { 89 | if (i != k && mat[k][j] != 0) { 90 | ok = false 91 | break 92 | } 93 | } 94 | for (k in 0 until mat[0].size) { 95 | if (j != k && mat[i][k] != 0) { 96 | ok = false 97 | break 98 | } 99 | } 100 | res = res + if (ok) 1 else 0 101 | } 102 | } 103 | } 104 | return res 105 | } 106 | } 107 | // @lc code=end 108 | 109 | -------------------------------------------------------------------------------- /easy/169.majority-element.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=169 lang=kotlin 3 | * 4 | * [169] Majority Element 5 | * 6 | * https://leetcode.com/problems/majority-element/description/ 7 | * 8 | * algorithms 9 | * Easy (56.05%) 10 | * Likes: 2615 11 | * Dislikes: 206 12 | * Total Accepted: 528.4K 13 | * Total Submissions: 939.8K 14 | * Testcase Example: '[3,2,3]' 15 | * 16 | * Given an array of size n, find the majority element. The majority element is 17 | * the element that appears more than ⌊ n/2 ⌋ times. 18 | * 19 | * You may assume that the array is non-empty and the majority element always 20 | * exist in the array. 21 | * 22 | * Example 1: 23 | * 24 | * 25 | * Input: [3,2,3] 26 | * Output: 3 27 | * 28 | * Example 2: 29 | * 30 | * 31 | * Input: [2,2,1,1,1,2,2] 32 | * Output: 2 33 | * 34 | * 35 | */ 36 | 37 | // @lc code=start 38 | class Solution { 39 | fun majorityElement(nums: IntArray): Int { 40 | val n = nums.size/2 41 | val mm = mutableMapOf() 42 | nums.forEach { 43 | mm.put(it, mm.getOrDefault(it, 0)+1) 44 | if (mm.getOrDefault(it, 0) > n) return it 45 | } 46 | return -1 47 | } 48 | } 49 | // @lc code=end 50 | 51 | -------------------------------------------------------------------------------- /easy/198.house-robber.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=198 lang=kotlin 3 | * 4 | * [198] House Robber 5 | * 6 | * https://leetcode.com/problems/house-robber/description/ 7 | * 8 | * algorithms 9 | * Easy (41.23%) 10 | * Likes: 2925 11 | * Dislikes: 92 12 | * Total Accepted: 358.6K 13 | * Total Submissions: 869.1K 14 | * Testcase Example: '[1,2,3,1]' 15 | * 16 | * You are a professional robber planning to rob houses along a street. Each 17 | * house has a certain amount of money stashed, the only constraint stopping 18 | * you from robbing each of them is that adjacent houses have security system 19 | * connected and it will automatically contact the police if two adjacent 20 | * houses were broken into on the same night. 21 | * 22 | * Given a list of non-negative integers representing the amount of money of 23 | * each house, determine the maximum amount of money you can rob tonight 24 | * without alerting the police. 25 | * 26 | * Example 1: 27 | * 28 | * 29 | * Input: [1,2,3,1] 30 | * Output: 4 31 | * Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 32 | * 3). 33 | * Total amount you can rob = 1 + 3 = 4. 34 | * 35 | * Example 2: 36 | * 37 | * 38 | * Input: [2,7,9,3,1] 39 | * Output: 12 40 | * Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 41 | * 5 (money = 1). 42 | * Total amount you can rob = 2 + 9 + 1 = 12. 43 | * 44 | * 45 | */ 46 | class Solution { 47 | fun rob(nums: IntArray): Int { 48 | if (nums.size == 0) return 0 49 | if (nums.size == 1) return nums[0] 50 | 51 | var l = Math.max(nums[0], nums[1]) 52 | var ll = nums[0] 53 | 54 | for (i in 2 until nums.size) { 55 | val temp = l 56 | l = Math.max(l, ll+nums[i]) 57 | ll = temp 58 | } 59 | return l 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /easy/2.add-two-numbers.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=2 lang=kotlin 3 | * 4 | * [2] Add Two Numbers 5 | * 6 | * https://leetcode.com/problems/add-two-numbers/description/ 7 | * 8 | * algorithms 9 | * Medium (30.92%) 10 | * Total Accepted: 831.4K 11 | * Total Submissions: 2.7M 12 | * Testcase Example: '[2,4,3]\n[5,6,4]' 13 | * 14 | * You are given two non-empty linked lists representing two non-negative 15 | * integers. The digits are stored in reverse order and each of their nodes 16 | * contain a single digit. Add the two numbers and return it as a linked list. 17 | * 18 | * You may assume the two numbers do not contain any leading zero, except the 19 | * number 0 itself. 20 | * 21 | * Example: 22 | * 23 | * 24 | * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 25 | * Output: 7 -> 0 -> 8 26 | * Explanation: 342 + 465 = 807. 27 | * 28 | * 29 | */ 30 | /** 31 | * Example: 32 | * var li = ListNode(5) 33 | * var v = li.`val` 34 | * Definition for singly-linked list. 35 | * class ListNode(var `val`: Int) { 36 | * var next: ListNode? = null 37 | * } 38 | */ 39 | class Solution { 40 | fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? { 41 | val head = ListNode(0) 42 | var p = l1 43 | var q = l2 44 | var cur = head 45 | var cnt = 0 46 | 47 | while (q != null || p != null) { 48 | val x = p?.`val` ?: 0 49 | val y = q?.`val` ?: 0 50 | 51 | val temp = x+y+cnt 52 | cnt = temp/10 53 | cur.next = ListNode(temp%10) 54 | cur = cur.next 55 | if (p != null) p = p?.next 56 | if (q != null) q = q?.next 57 | } 58 | if (cnt > 0) { 59 | cur.next = ListNode(cnt) 60 | } 61 | return head.next 62 | } 63 | } 64 | 65 | -------------------------------------------------------------------------------- /easy/20.valid-parentheses.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=20 lang=kotlin 3 | * 4 | * [20] Valid Parentheses 5 | * 6 | * https://leetcode.com/problems/valid-parentheses/description/ 7 | * 8 | * algorithms 9 | * Easy (37.80%) 10 | * Likes: 4179 11 | * Dislikes: 197 12 | * Total Accepted: 862.8K 13 | * Total Submissions: 2.3M 14 | * Testcase Example: '"()"' 15 | * 16 | * Given a string containing just the characters '(', ')', '{', '}', '[' and 17 | * ']', determine if the input string is valid. 18 | * 19 | * An input string is valid if: 20 | * 21 | * 22 | * Open brackets must be closed by the same type of brackets. 23 | * Open brackets must be closed in the correct order. 24 | * 25 | * 26 | * Note that an empty string is also considered valid. 27 | * 28 | * Example 1: 29 | * 30 | * 31 | * Input: "()" 32 | * Output: true 33 | * 34 | * 35 | * Example 2: 36 | * 37 | * 38 | * Input: "()[]{}" 39 | * Output: true 40 | * 41 | * 42 | * Example 3: 43 | * 44 | * 45 | * Input: "(]" 46 | * Output: false 47 | * 48 | * 49 | * Example 4: 50 | * 51 | * 52 | * Input: "([)]" 53 | * Output: false 54 | * 55 | * 56 | * Example 5: 57 | * 58 | * 59 | * Input: "{[]}" 60 | * Output: true 61 | * 62 | * 63 | */ 64 | 65 | // @lc code=start 66 | class Solution { 67 | fun isValid(s: String): Boolean { 68 | var stk = Stack() 69 | stk.push('#') 70 | for (i in s) { 71 | if (i == '(') stk.push(i) 72 | if (i == '[') stk.push(i) 73 | if (i == '{') stk.push(i) 74 | if (i == ')') { 75 | val c = stk.pop() 76 | if (c != '(') return false 77 | } 78 | if (i == ']') { 79 | val c = stk.pop() 80 | if (c != '[') return false 81 | } 82 | if (i == '}') { 83 | val c = stk.pop() 84 | if (c != '{') return false 85 | } 86 | } 87 | if (stk.size > 1) return false 88 | return true 89 | } 90 | } 91 | // @lc code=end -------------------------------------------------------------------------------- /easy/204.count-primes.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=204 lang=kotlin 3 | * 4 | * [204] Count Primes 5 | * 6 | * https://leetcode.com/problems/count-primes/description/ 7 | * 8 | * algorithms 9 | * Easy (29.56%) 10 | * Likes: 1209 11 | * Dislikes: 434 12 | * Total Accepted: 259.4K 13 | * Total Submissions: 875.5K 14 | * Testcase Example: '10' 15 | * 16 | * Count the number of prime numbers less than a non-negative number, n. 17 | * 18 | * Example: 19 | * 20 | * 21 | * Input: 10 22 | * Output: 4 23 | * Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 24 | * 25 | * 26 | */ 27 | class Solution { 28 | fun countPrimes(n: Int): Int { 29 | var isp = BooleanArray(n+1) { true } 30 | var p = mutableListOf() 31 | 32 | for (i in 2 until n) { 33 | if (isp[i]) p.add(i) 34 | for (j in 0 until p.size) { 35 | if (i*p[j] >= n) break 36 | isp[i*p[j]] = false 37 | if (i%p[j] == 0) break 38 | } 39 | } 40 | 41 | return p.size.toInt() 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /easy/21.merge-two-sorted-lists.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=21 lang=kotlin 3 | * 4 | * [21] Merge Two Sorted Lists 5 | * 6 | * https://leetcode.com/problems/merge-two-sorted-lists/description/ 7 | * 8 | * algorithms 9 | * Easy (51.55%) 10 | * Likes: 3559 11 | * Dislikes: 529 12 | * Total Accepted: 890.9K 13 | * Total Submissions: 1.7M 14 | * Testcase Example: '[1,2,4]\n[1,3,4]' 15 | * 16 | * Merge two sorted linked lists and return it as a new list. The new list 17 | * should be made by splicing together the nodes of the first two lists. 18 | * 19 | * Example: 20 | * 21 | * Input: 1->2->4, 1->3->4 22 | * Output: 1->1->2->3->4->4 23 | * 24 | * 25 | */ 26 | 27 | // @lc code=start 28 | /** 29 | * Example: 30 | * var li = ListNode(5) 31 | * var v = li.`val` 32 | * Definition for singly-linked list. 33 | * class ListNode(var `val`: Int) { 34 | * var next: ListNode? = null 35 | * } 36 | */ 37 | class Solution { 38 | fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? { 39 | val result = ListNode(0) 40 | var current = result 41 | 42 | var node1 = list1 43 | var node2 = list2 44 | while (node1 != null || node2 != null) { 45 | if (node1 == null) { 46 | current.next = node2 47 | break 48 | } 49 | if (node2 == null) { 50 | current.next = node1 51 | break 52 | } 53 | 54 | if (node1.`val` < node2.`val`) { 55 | current.next = node1 56 | node1 = node1.next 57 | } else { 58 | current.next = node2 59 | node2 = node2.next 60 | } 61 | current = current.next!!/*compiler can't yet determine nullability of/smart cast 'complex expressions', but it is nonetheless guaranteed*/ 62 | } 63 | return result?.next 64 | } 65 | } 66 | // @lc code=end 67 | 68 | -------------------------------------------------------------------------------- /easy/26.remove-duplicates-from-sorted-array.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=26 lang=kotlin 3 | * 4 | * [26] Remove Duplicates from Sorted Array 5 | * 6 | * https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ 7 | * 8 | * algorithms 9 | * Easy (41.60%) 10 | * Likes: 1743 11 | * Dislikes: 3764 12 | * Total Accepted: 695.4K 13 | * Total Submissions: 1.7M 14 | * Testcase Example: '[1,1,2]' 15 | * 16 | * Given a sorted array nums, remove the duplicates in-place such that each 17 | * element appear only once and return the new length. 18 | * 19 | * Do not allocate extra space for another array, you must do this by modifying 20 | * the input array in-place with O(1) extra memory. 21 | * 22 | * Example 1: 23 | * 24 | * 25 | * Given nums = [1,1,2], 26 | * 27 | * Your function should return length = 2, with the first two elements of nums 28 | * being 1 and 2 respectively. 29 | * 30 | * It doesn't matter what you leave beyond the returned length. 31 | * 32 | * Example 2: 33 | * 34 | * 35 | * Given nums = [0,0,1,1,1,2,2,3,3,4], 36 | * 37 | * Your function should return length = 5, with the first five elements of nums 38 | * being modified to 0, 1, 2, 3, and 4 respectively. 39 | * 40 | * It doesn't matter what values are set beyond the returned length. 41 | * 42 | * 43 | * Clarification: 44 | * 45 | * Confused why the returned value is an integer but your answer is an array? 46 | * 47 | * Note that the input array is passed in by reference, which means 48 | * modification to the input array will be known to the caller as well. 49 | * 50 | * Internally you can think of this: 51 | * 52 | * 53 | * // nums is passed in by reference. (i.e., without making a copy) 54 | * int len = removeDuplicates(nums); 55 | * 56 | * // any modification to nums in your function would be known by the caller. 57 | * // using the length returned by your function, it prints the first len 58 | * elements. 59 | * for (int i = 0; i < len; i++) { 60 | * print(nums[i]); 61 | * } 62 | * 63 | */ 64 | 65 | // @lc code=start 66 | class Solution { 67 | fun removeDuplicates(nums: IntArray): Int { 68 | var cnt = if (nums.size > 0) 1 else 0 69 | 70 | for (i in 1 until nums.size) { 71 | if (nums[i] == nums[i-1]) continue 72 | nums[cnt] = nums[i] 73 | cnt++ 74 | } 75 | return cnt 76 | } 77 | } 78 | // @lc code=end 79 | 80 | -------------------------------------------------------------------------------- /easy/268.missing-number.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=268 lang=kotlin 3 | * 4 | * [268] Missing Number 5 | * 6 | * https://leetcode.com/problems/missing-number/description/ 7 | * 8 | * algorithms 9 | * Easy (47.91%) 10 | * Total Accepted: 262.4K 11 | * Total Submissions: 547K 12 | * Testcase Example: '[3,0,1]' 13 | * 14 | * Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, 15 | * find the one that is missing from the array. 16 | * 17 | * Example 1: 18 | * 19 | * 20 | * Input: [3,0,1] 21 | * Output: 2 22 | * 23 | * 24 | * Example 2: 25 | * 26 | * 27 | * Input: [9,6,4,2,3,5,7,0,1] 28 | * Output: 8 29 | * 30 | * 31 | * Note: 32 | * Your algorithm should run in linear runtime complexity. Could you implement 33 | * it using only constant extra space complexity? 34 | */ 35 | class Solution { 36 | fun missingNumber(nums: IntArray): Int { 37 | var sum = 0 38 | var n = nums.size 39 | nums.forEach { 40 | sum += it 41 | } 42 | return n*(n+1)/2 - sum 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /easy/27.remove-element.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=27 lang=kotlin 3 | * 4 | * [27] Remove Element 5 | * 6 | * https://leetcode.com/problems/remove-element/description/ 7 | * 8 | * algorithms 9 | * Easy (43.83%) 10 | * Total Accepted: 390.2K 11 | * Total Submissions: 886K 12 | * Testcase Example: '[3,2,2,3]\n3' 13 | * 14 | * Given an array nums and a value val, remove all instances of that value 15 | * in-place and return the new length. 16 | * 17 | * Do not allocate extra space for another array, you must do this by modifying 18 | * the input array in-place with O(1) extra memory. 19 | * 20 | * The order of elements can be changed. It doesn't matter what you leave 21 | * beyond the new length. 22 | * 23 | * Example 1: 24 | * 25 | * 26 | * Given nums = [3,2,2,3], val = 3, 27 | * 28 | * Your function should return length = 2, with the first two elements of nums 29 | * being 2. 30 | * 31 | * It doesn't matter what you leave beyond the returned length. 32 | 33 | * 34 | * Example 2: 35 | * 36 | * 37 | * Given nums = [0,1,2,2,3,0,4,2], val = 2, 38 | * 39 | * Your function should return length = 5, with the first five elements of nums 40 | * containing 0, 1, 3, 0, and 4. 41 | * 42 | * Note that the order of those five elements can be arbitrary. 43 | * 44 | * It doesn't matter what values are set beyond the returned length. 45 | * 46 | * Clarification: 47 | * 48 | * Confused why the returned value is an integer but your answer is an array? 49 | * 50 | * Note that the input array is passed in by reference, which means 51 | * modification to the input array will be known to the caller as well. 52 | * 53 | * Internally you can think of this: 54 | * 55 | * 56 | * // nums is passed in by reference. (i.e., without making a copy) 57 | * int len = removeElement(nums, val); 58 | * 59 | * // any modification to nums in your function would be known by the caller. 60 | * // using the length returned by your function, it prints the first len 61 | * elements. 62 | * for (int i = 0; i < len; i++) { 63 | * print(nums[i]); 64 | * } 65 | * 66 | */ 67 | class Solution { 68 | fun removeElement(nums: IntArray, `val`: Int): Int { 69 | var res = 0 70 | for (i in 0 until nums.size) { 71 | if (nums[i] != `val`) { 72 | nums[res++] = nums[i] 73 | } 74 | } 75 | return res 76 | } 77 | } 78 | 79 | -------------------------------------------------------------------------------- /easy/28.implement-str-str.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=28 lang=kotlin 3 | * 4 | * [28] Implement strStr() 5 | * 6 | * https://leetcode.com/problems/implement-strstr/description/ 7 | * 8 | * algorithms 9 | * Easy (32.70%) 10 | * Likes: 1053 11 | * Dislikes: 1501 12 | * Total Accepted: 497.5K 13 | * Total Submissions: 1.5M 14 | * Testcase Example: '"hello"\n"ll"' 15 | * 16 | * Implement strStr(). 17 | * 18 | * Return the index of the first occurrence of needle in haystack, or -1 if 19 | * needle is not part of haystack. 20 | * 21 | * Example 1: 22 | * 23 | * 24 | * Input: haystack = "hello", needle = "ll" 25 | * Output: 2 26 | * 27 | * 28 | * Example 2: 29 | * 30 | * 31 | * Input: haystack = "aaaaa", needle = "bba" 32 | * Output: -1 33 | * 34 | * 35 | * Clarification: 36 | * 37 | * What should we return when needle is an empty string? This is a great 38 | * question to ask during an interview. 39 | * 40 | * For the purpose of this problem, we will return 0 when needle is an empty 41 | * string. This is consistent to C's strstr() and Java's indexOf(). 42 | * 43 | */ 44 | 45 | // @lc code=start 46 | class Solution { 47 | fun strStr(haystack: String, needle: String): Int { 48 | if (needle == "") return 0 49 | 50 | val n = haystack.length 51 | val m = needle.length 52 | 53 | for (i in 0 .. n-m) { 54 | for (j in 0 until m) { 55 | if (needle[j] != haystack[i+j]) 56 | break 57 | if (j == m-1) return i 58 | } 59 | } 60 | return -1 61 | } 62 | } 63 | // @lc code=end 64 | 65 | -------------------------------------------------------------------------------- /easy/303.range-sum-query-immutable.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=303 lang=kotlin 3 | * 4 | * [303] Range Sum Query - Immutable 5 | * 6 | * https://leetcode.com/problems/range-sum-query-immutable/description/ 7 | * 8 | * algorithms 9 | * Easy (39.27%) 10 | * Likes: 528 11 | * Dislikes: 832 12 | * Total Accepted: 150.6K 13 | * Total Submissions: 382.7K 14 | * Testcase Example: '["NumArray","sumRange","sumRange","sumRange"]\n[[[-2,0,3,-5,2,-1]],[0,2],[2,5],[0,5]]' 15 | * 16 | * Given an integer array nums, find the sum of the elements between indices i 17 | * and j (i ≤ j), inclusive. 18 | * 19 | * Example: 20 | * 21 | * Given nums = [-2, 0, 3, -5, 2, -1] 22 | * 23 | * sumRange(0, 2) -> 1 24 | * sumRange(2, 5) -> -1 25 | * sumRange(0, 5) -> -3 26 | * 27 | * 28 | * 29 | * Note: 30 | * 31 | * You may assume that the array does not change. 32 | * There are many calls to sumRange function. 33 | * 34 | * 35 | */ 36 | class NumArray(nums: IntArray) { 37 | var dp = IntArray(nums.size+1) 38 | 39 | init { 40 | for (i in 1 .. nums.size) 41 | dp[i] = dp[i-1]+nums[i-1] 42 | } 43 | 44 | fun sumRange(i: Int, j: Int): Int { 45 | return dp[j+1]-dp[i] 46 | } 47 | 48 | } 49 | 50 | /** 51 | * Your NumArray object will be instantiated and called as such: 52 | * var obj = NumArray(nums) 53 | * var param_1 = obj.sumRange(i,j) 54 | */ 55 | 56 | -------------------------------------------------------------------------------- /easy/38.count-and-say.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=38 lang=kotlin 3 | * 4 | * [38] Count and Say 5 | * 6 | * https://leetcode.com/problems/count-and-say/description/ 7 | * 8 | * algorithms 9 | * Easy (39.98%) 10 | * Total Accepted: 270.6K 11 | * Total Submissions: 676.6K 12 | * Testcase Example: '1' 13 | * 14 | * The count-and-say sequence is the sequence of integers with the first five 15 | * terms as following: 16 | * 17 | * 18 | * 1. 1 19 | * 2. 11 20 | * 3. 21 21 | * 4. 1211 22 | * 5. 111221 23 | * 24 | * 25 | * 1 is read off as "one 1" or 11. 26 | * 11 is read off as "two 1s" or 21. 27 | * 21 is read off as "one 2, then one 1" or 1211. 28 | * 29 | * Given an integer n where 1 ≤ n ≤ 30, generate the n^th term of the 30 | * count-and-say sequence. 31 | * 32 | * Note: Each term of the sequence of integers will be represented as a 33 | * string. 34 | * 35 | * 36 | * 37 | * Example 1: 38 | * 39 | * 40 | * Input: 1 41 | * Output: "1" 42 | * 43 | * 44 | * Example 2: 45 | * 46 | * 47 | * Input: 4 48 | * Output: "1211" 49 | * 50 | */ 51 | class Solution { 52 | fun countAndSay(n: Int): String { 53 | var last = "1" 54 | (1 until n).forEach { 55 | var nextStr = "" 56 | var cnt = 0 57 | for (i in 0 until last.length) { 58 | if (i == 0) { 59 | cnt++ 60 | } else if (last[i] == last[i-1]) { 61 | cnt++ 62 | } else { 63 | nextStr += "${cnt}${last[i-1]}" 64 | cnt = 1 65 | } 66 | if (i == last.length-1) 67 | nextStr += "${cnt}${last[i]}" 68 | } 69 | last = nextStr 70 | } 71 | return last 72 | } 73 | } -------------------------------------------------------------------------------- /easy/53.maximum-subarray.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=53 lang=kotlin 3 | * 4 | * [53] Maximum Subarray 5 | * 6 | * https://leetcode.com/problems/maximum-subarray/description/ 7 | * 8 | * algorithms 9 | * Easy (44.19%) 10 | * Likes: 4757 11 | * Dislikes: 176 12 | * Total Accepted: 588.8K 13 | * Total Submissions: 1.3M 14 | * Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]' 15 | * 16 | * Given an integer array nums, find the contiguous subarray (containing at 17 | * least one number) which has the largest sum and return its sum. 18 | * 19 | * Example: 20 | * 21 | * 22 | * Input: [-2,1,-3,4,-1,2,1,-5,4], 23 | * Output: 6 24 | * Explanation: [4,-1,2,1] has the largest sum = 6. 25 | * 26 | * 27 | * Follow up: 28 | * 29 | * If you have figured out the O(n) solution, try coding another solution using 30 | * the divide and conquer approach, which is more subtle. 31 | * 32 | */ 33 | class Solution { 34 | fun maxSubArray(nums: IntArray): Int { 35 | var sum = 0 36 | var maxa = -2147483647 37 | nums.forEach { a -> 38 | if (sum < 0) { 39 | sum = a 40 | } else { 41 | sum += a 42 | } 43 | maxa = Math.max(sum, maxa) 44 | } 45 | return maxa 46 | } 47 | } 48 | 49 | -------------------------------------------------------------------------------- /easy/67.add-binary.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=67 lang=kotlin 3 | * 4 | * [67] Add Binary 5 | * 6 | * https://leetcode.com/problems/add-binary/description/ 7 | * 8 | * algorithms 9 | * Easy (40.17%) 10 | * Likes: 1144 11 | * Dislikes: 219 12 | * Total Accepted: 337.4K 13 | * Total Submissions: 832.8K 14 | * Testcase Example: '"11"\n"1"' 15 | * 16 | * Given two binary strings, return their sum (also a binary string). 17 | * 18 | * The input strings are both non-empty and contains only characters 1 or 0. 19 | * 20 | * Example 1: 21 | * 22 | * 23 | * Input: a = "11", b = "1" 24 | * Output: "100" 25 | * 26 | * Example 2: 27 | * 28 | * 29 | * Input: a = "1010", b = "1011" 30 | * Output: "10101" 31 | * 32 | */ 33 | class Solution { 34 | fun addBinary(a: String, b: String): String { 35 | var lena = a.length-1 36 | var lenb = b.length-1 37 | var res: String = "" 38 | var cnt = 0 39 | 40 | while (lena >= 0 || lenb >= 0) { 41 | var temp = 0 42 | if (lena >= 0) temp += a[lena]-'0' 43 | lena-- 44 | if (lenb >= 0) temp += b[lenb]-'0' 45 | lenb-- 46 | res += ((temp+cnt)%2).toString() 47 | cnt = (temp+cnt)/2 48 | } 49 | if (cnt > 0) res += "1" 50 | return res.reversed() 51 | } 52 | } 53 | 54 | -------------------------------------------------------------------------------- /easy/69.sqrt-x.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=69 lang=kotlin 3 | * 4 | * [69] Sqrt(x) 5 | * 6 | * https://leetcode.com/problems/sqrtx/description/ 7 | * 8 | * algorithms 9 | * Easy (31.83%) 10 | * Likes: 842 11 | * Dislikes: 1469 12 | * Total Accepted: 401.3K 13 | * Total Submissions: 1.3M 14 | * Testcase Example: '4' 15 | * 16 | * Implement int sqrt(int x). 17 | * 18 | * Compute and return the square root of x, where x is guaranteed to be a 19 | * non-negative integer. 20 | * 21 | * Since the return type is an integer, the decimal digits are truncated and 22 | * only the integer part of the result is returned. 23 | * 24 | * Example 1: 25 | * 26 | * 27 | * Input: 4 28 | * Output: 2 29 | * 30 | * 31 | * Example 2: 32 | * 33 | * 34 | * Input: 8 35 | * Output: 2 36 | * Explanation: The square root of 8 is 2.82842..., and since 37 | * the decimal part is truncated, 2 is returned. 38 | * 39 | * 40 | */ 41 | class Solution { 42 | 43 | fun mySqrt(x: Int): Int { 44 | var l: Long = 0 45 | var r: Long = x.toLong() 46 | var mid: Long 47 | var ans: Long = 0 48 | while (l <= r) { 49 | mid = (l+r)/2 50 | // println("mid: ${mid}") 51 | if (mid*mid == x.toLong()) { 52 | return mid.toInt() 53 | } 54 | if (mid*mid > x) { 55 | r = mid-1 56 | } else { 57 | ans = Math.max(ans, mid) 58 | l = mid+1 59 | } 60 | } 61 | return ans.toInt() 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /easy/7.reverse-integer.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=7 lang=kotlin 3 | * 4 | * [7] Reverse Integer 5 | * 6 | * https://leetcode.com/problems/reverse-integer/description/ 7 | * 8 | * algorithms 9 | * Easy (25.24%) 10 | * Total Accepted: 662.6K 11 | * Total Submissions: 2.6M 12 | * Testcase Example: '123' 13 | * 14 | * Given a 32-bit signed integer, reverse digits of an integer. 15 | * 16 | * Example 1: 17 | * 18 | * 19 | * Input: 123 20 | * Output: 321 21 | * 22 | * 23 | * Example 2: 24 | * 25 | * 26 | * Input: -123 27 | * Output: -321 28 | * 29 | * 30 | * Example 3: 31 | * 32 | * 33 | * Input: 120 34 | * Output: 21 35 | * 36 | * 37 | * Note: 38 | * Assume we are dealing with an environment which could only store integers 39 | * within the 32-bit signed integer range: [−2^31,  2^31 − 1]. For the purpose 40 | * of this problem, assume that your function returns 0 when the reversed 41 | * integer overflows. 42 | * 43 | */ 44 | class Solution { 45 | fun reverse(x: Int): Int { 46 | var res = 0 47 | var n = x 48 | while (n != 0) { 49 | if (Math.abs(res) > Int.MAX_VALUE/10) return 0 50 | 51 | res = res*10 + n % 10 52 | n /= 10 53 | } 54 | return res 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /easy/70.climbing-stairs.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=70 lang=kotlin 3 | * 4 | * [70] Climbing Stairs 5 | * 6 | * https://leetcode.com/problems/climbing-stairs/description/ 7 | * 8 | * algorithms 9 | * Easy (44.72%) 10 | * Likes: 2470 11 | * Dislikes: 89 12 | * Total Accepted: 444.8K 13 | * Total Submissions: 994.4K 14 | * Testcase Example: '2' 15 | * 16 | * You are climbing a stair case. It takes n steps to reach to the top. 17 | * 18 | * Each time you can either climb 1 or 2 steps. In how many distinct ways can 19 | * you climb to the top? 20 | * 21 | * Note: Given n will be a positive integer. 22 | * 23 | * Example 1: 24 | * 25 | * 26 | * Input: 2 27 | * Output: 2 28 | * Explanation: There are two ways to climb to the top. 29 | * 1. 1 step + 1 step 30 | * 2. 2 steps 31 | * 32 | * 33 | * Example 2: 34 | * 35 | * 36 | * Input: 3 37 | * Output: 3 38 | * Explanation: There are three ways to climb to the top. 39 | * 1. 1 step + 1 step + 1 step 40 | * 2. 1 step + 2 steps 41 | * 3. 2 steps + 1 step 42 | * 43 | * 44 | */ 45 | class Solution { 46 | fun climbStairs(n: Int): Int { 47 | var dp = IntArray(55, {0}) 48 | dp[1] = 1 49 | dp[2] = 2 50 | 51 | (3 .. n).forEach { i -> 52 | dp[i] = dp[i-1]+dp[i-2] 53 | } 54 | return dp[n] 55 | } 56 | } 57 | 58 | -------------------------------------------------------------------------------- /easy/859.buddy-strings.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=859 lang=kotlin 3 | * 4 | * [859] Buddy Strings 5 | * 6 | * https://leetcode.com/problems/buddy-strings/description/ 7 | * 8 | * algorithms 9 | * Easy (27.80%) 10 | * Likes: 362 11 | * Dislikes: 217 12 | * Total Accepted: 30.8K 13 | * Total Submissions: 110.5K 14 | * Testcase Example: '"ab"\n"ba"' 15 | * 16 | * Given two strings A and B of lowercase letters, return true if and only if 17 | * we can swap two letters in A so that the result equals B. 18 | * 19 | * 20 | * 21 | * Example 1: 22 | * 23 | * 24 | * 25 | * Input: A = "ab", B = "ba" 26 | * Output: true 27 | * 28 | * 29 | * 30 | * Example 2: 31 | * 32 | * 33 | * Input: A = "ab", B = "ab" 34 | * Output: false 35 | * 36 | * 37 | * 38 | * Example 3: 39 | * 40 | * 41 | * Input: A = "aa", B = "aa" 42 | * Output: true 43 | * 44 | * 45 | * 46 | * Example 4: 47 | * 48 | * 49 | * Input: A = "aaaaaaabc", B = "aaaaaaacb" 50 | * Output: true 51 | * 52 | * 53 | * 54 | * Example 5: 55 | * 56 | * 57 | * Input: A = "", B = "aa" 58 | * Output: false 59 | * 60 | * 61 | * 62 | * 63 | * Note: 64 | * 65 | * 66 | * 0 <= A.length <= 20000 67 | * 0 <= B.length <= 20000 68 | * A and B consist only of lowercase letters. 69 | * 70 | * 71 | * 72 | * 73 | * 74 | * 75 | * 76 | */ 77 | 78 | // @lc code=start 79 | class Solution { 80 | private fun judge(A: String, B: String): Boolean{ 81 | if ((A == B && A[0] == A[1]) || (A != B && A[0] == B[1] && A[1] == B[0])) 82 | return true 83 | return false 84 | } 85 | 86 | fun buddyStrings(A: String, B: String): Boolean { 87 | if (A.length != B.length || A.length < 2 || B.length < 2) return false 88 | var diff = 0 89 | var st1 = "" 90 | var st2 = "" 91 | 92 | for (i in 0 until A.length) { 93 | if (A[i] != B[i]) { 94 | diff++ 95 | st1 += A[i] 96 | st2 += B[i] 97 | } 98 | } 99 | if (diff == 1 || diff > 2) return false 100 | else if (diff == 2) return judge(st1, st2) 101 | else { 102 | var nums = IntArray(30) 103 | for (i in 0 until A.length) { 104 | nums[A[i]-'a']++ 105 | if (nums[A[i]-'a'] >= 2) return true 106 | } 107 | return false 108 | } 109 | 110 | } 111 | } 112 | // @lc code=end 113 | 114 | -------------------------------------------------------------------------------- /easy/872.leaf-similar-trees.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=872 lang=kotlin 3 | * 4 | * [872] Leaf-Similar Trees 5 | * 6 | * https://leetcode.com/problems/leaf-similar-trees/description/ 7 | * 8 | * algorithms 9 | * Easy (64.83%) 10 | * Likes: 587 11 | * Dislikes: 30 12 | * Total Accepted: 73.1K 13 | * Total Submissions: 112.8K 14 | * Testcase Example: '[3,5,1,6,2,9,8,null,null,7,4]\n' + 15 | '[3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]' 16 | * 17 | * Consider all the leaves of a binary tree.  From left to right order, the 18 | * values of those leaves form a leaf value sequence. 19 | * 20 | * 21 | * 22 | * For example, in the given tree above, the leaf value sequence is (6, 7, 4, 23 | * 9, 8). 24 | * 25 | * Two binary trees are considered leaf-similar if their leaf value sequence is 26 | * the same. 27 | * 28 | * Return true if and only if the two given trees with head nodes root1 and 29 | * root2 are leaf-similar. 30 | * 31 | * 32 | * Constraints: 33 | * 34 | * 35 | * Both of the given trees will have between 1 and 200 nodes. 36 | * Both of the given trees will have values between 0 and 200 37 | * 38 | * 39 | */ 40 | 41 | // @lc code=start 42 | /** 43 | * Example: 44 | * var ti = TreeNode(5) 45 | * var v = ti.`val` 46 | * Definition for a binary tree node. 47 | * class TreeNode(var `val`: Int) { 48 | * var left: TreeNode? = null 49 | * var right: TreeNode? = null 50 | * } 51 | */ 52 | import java.util.LinkedList 53 | class Solution { 54 | fun leafSimilar(root1: TreeNode?, root2: TreeNode?): Boolean { 55 | val list1 = mutableListOf() 56 | val list2 = mutableListOf() 57 | getSequence(root1, list1) 58 | getSequence(root2, list2) 59 | 60 | if (list1.size != list2.size) return false 61 | 62 | 63 | for (i in 0 until list1.size) { 64 | if (list1[i] != list2[i]) { 65 | return false 66 | } 67 | } 68 | return true 69 | } 70 | 71 | fun getSequence(root: TreeNode?, res: MutableList) { 72 | if (root?.left == null && root?.right == null) res.add(root!!.`val`) 73 | if (root?.left != null) getSequence(root?.left, res) 74 | if (root?.right != null) getSequence(root?.right, res) 75 | } 76 | } 77 | // @lc code=end 78 | 79 | -------------------------------------------------------------------------------- /easy/9.palindrome-number.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=9 lang=kotlin 3 | * 4 | * [9] Palindrome Number 5 | */ 6 | class Solution { 7 | fun isPalindrome(x: Int): Boolean { 8 | if (x < 0) return false 9 | var a = IntArray(20) 10 | var cnt = 0 11 | var n = x 12 | 13 | while (n > 0) { 14 | a[cnt++] = n%10 15 | n /= 10 16 | } 17 | for (i in 0 until cnt/2) { 18 | if (a[i] != a[cnt-i-1]) return false 19 | } 20 | return true 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /hard/10.regular-expression-matching.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=10 lang=kotlin 3 | * 4 | * [10] Regular Expression Matching 5 | * 6 | * https://leetcode.com/problems/regular-expression-matching/description/ 7 | * 8 | * algorithms 9 | * Hard (25.52%) 10 | * Likes: 2878 11 | * Dislikes: 552 12 | * Total Accepted: 326.9K 13 | * Total Submissions: 1.3M 14 | * Testcase Example: '"aa"\n"a"' 15 | * 16 | * Given an input string (s) and a pattern (p), implement regular expression 17 | * matching with support for '.' and '*'. 18 | * 19 | * 20 | * '.' Matches any single character. 21 | * '*' Matches zero or more of the preceding element. 22 | * 23 | * 24 | * The matching should cover the entire input string (not partial). 25 | * 26 | * Note: 27 | * 28 | * 29 | * s could be empty and contains only lowercase letters a-z. 30 | * p could be empty and contains only lowercase letters a-z, and characters 31 | * like . or *. 32 | * 33 | * 34 | * Example 1: 35 | * 36 | * 37 | * Input: 38 | * s = "aa" 39 | * p = "a" 40 | * Output: false 41 | * Explanation: "a" does not match the entire string "aa". 42 | * 43 | * 44 | * Example 2: 45 | * 46 | * 47 | * Input: 48 | * s = "aa" 49 | * p = "a*" 50 | * Output: true 51 | * Explanation: '*' means zero or more of the preceding element, 'a'. 52 | * Therefore, by repeating 'a' once, it becomes "aa". 53 | * 54 | * 55 | * Example 3: 56 | * 57 | * 58 | * Input: 59 | * s = "ab" 60 | * p = ".*" 61 | * Output: true 62 | * Explanation: ".*" means "zero or more (*) of any character (.)". 63 | * 64 | * 65 | * Example 4: 66 | * 67 | * 68 | * Input: 69 | * s = "aab" 70 | * p = "c*a*b" 71 | * Output: true 72 | * Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, 73 | * it matches "aab". 74 | * 75 | * 76 | * Example 5: 77 | * 78 | * 79 | * Input: 80 | * s = "mississippi" 81 | * p = "mis*is*p*." 82 | * Output: false 83 | * 84 | * 85 | */ 86 | class Solution { 87 | fun isMatch(s: String, p: String): Boolean { 88 | var dp = Array(s.length+1){BooleanArray(p.length+1, {false})} 89 | dp[0][0] = true 90 | 91 | for (i in 0 .. s.length) { 92 | for (j in 1 .. p.length) { 93 | if (i > 0 && (s[i-1] == p[j-1] || p[j-1] == '.')) { 94 | dp[i][j] = dp[i-1][j-1] 95 | } 96 | if (p[j-1] == '*') { 97 | if (i == 0 || (s[i-1] != p[j-2] && p[j-2] != '.')) { 98 | dp[i][j] = dp[i][j-2] 99 | } else { 100 | dp[i][j] = dp[i-1][j] || dp[i][j-1] || dp[i][j-2] 101 | } 102 | } 103 | } 104 | } 105 | return dp[s.length][p.length] 106 | } 107 | } 108 | 109 | -------------------------------------------------------------------------------- /hard/1377.frog-position-after-t-seconds.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1377 lang=kotlin 3 | * 4 | * [1377] Frog Position After T Seconds 5 | * 6 | * https://leetcode.com/problems/frog-position-after-t-seconds/description/ 7 | * 8 | * algorithms 9 | * Hard (29.87%) 10 | * Likes: 26 11 | * Dislikes: 20 12 | * Total Accepted: 3K 13 | * Total Submissions: 10.1K 14 | * Testcase Example: '7\n[[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]]\n2\n4' 15 | * 16 | * Given an undirected tree consisting of n vertices numbered from 1 to n. A 17 | * frog starts jumping from the vertex 1. In one second, the frog jumps from 18 | * its current vertex to another unvisited vertex if they are directly 19 | * connected. The frog can not jump back to a visited vertex. In case the frog 20 | * can jump to several vertices it jumps randomly to one of them with the same 21 | * probability, otherwise, when the frog can not jump to any unvisited vertex 22 | * it jumps forever on the same vertex.  23 | * 24 | * The edges of the undirected tree are given in the array edges, where 25 | * edges[i] = [fromi, toi] means that exists an edge connecting directly the 26 | * vertices fromi and toi. 27 | * 28 | * Return the probability that after t seconds the frog is on the vertex 29 | * target. 30 | * 31 | * 32 | * Example 1: 33 | * 34 | * 35 | * 36 | * 37 | * Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 38 | * 4 39 | * Output: 0.16666666666666666 40 | * Explanation: The figure above shows the given graph. The frog starts at 41 | * vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and 42 | * then jumping with 1/2 probability to vertex 4 after second 2. Thus the 43 | * probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 44 | * 1/6 = 0.16666666666666666. 45 | * 46 | * 47 | * Example 2: 48 | * 49 | * 50 | * 51 | * 52 | * Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 53 | * 7 54 | * Output: 0.3333333333333333 55 | * Explanation: The figure above shows the given graph. The frog starts at 56 | * vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 57 | * after second 1. 58 | * 59 | * 60 | * Example 3: 61 | * 62 | * 63 | * Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 20, target 64 | * = 6 65 | * Output: 0.16666666666666666 66 | * 67 | * 68 | * 69 | * Constraints: 70 | * 71 | * 72 | * 1 <= n <= 100 73 | * edges.length == n-1 74 | * edges[i].length == 2 75 | * 1 <= edges[i][0], edges[i][1] <= n 76 | * 1 <= t <= 50 77 | * 1 <= target <= n 78 | * Answers within 10^-5 of the actual value will be accepted as correct. 79 | * 80 | */ 81 | 82 | // @lc code=start 83 | import java.util.LinkedList 84 | class Solution { 85 | data class Node(val root: Int, val p: Double, val time: Int) 86 | 87 | fun frogPosition(n: Int, edges: Array, t: Int, target: Int): Double { 88 | var q = LinkedList() 89 | var vis = BooleanArray(n+1) 90 | var e = Array(n+1, {HashSet()}) 91 | for (edge in edges) { 92 | e[edge[0]].add(edge[1]) 93 | e[edge[1]].add(edge[0]) 94 | } 95 | q.push(Node(1, 1.0, 0)) 96 | vis[1] = true 97 | 98 | while (!q.isEmpty()) { 99 | var top = q.poll() 100 | if (top.time == t && top.root == target) { 101 | return top.p 102 | } 103 | 104 | var cnt = 0 105 | for (id in e[top.root]) 106 | if (!vis[id]) cnt++ 107 | if (top.time < t) { 108 | val p = top.p*1.0/cnt 109 | var ok = false 110 | for (id in e[top.root]) { 111 | if (!vis[id]) { 112 | vis[id] = true 113 | q.offer(Node(id, p, top.time+1)) 114 | ok = true 115 | } 116 | } 117 | if (!ok) q.offer(Node(top.root, top.p, top.time+1)) 118 | } 119 | } 120 | return 0.0 121 | } 122 | } 123 | // @lc code=end 124 | 125 | -------------------------------------------------------------------------------- /hard/140.word-break-ii.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=140 lang=kotlin 3 | * 4 | * [140] Word Break II 5 | * 6 | * https://leetcode.com/problems/word-break-ii/description/ 7 | * 8 | * algorithms 9 | * Hard (27.98%) 10 | * Likes: 1122 11 | * Dislikes: 261 12 | * Total Accepted: 171.4K 13 | * Total Submissions: 611.3K 14 | * Testcase Example: '"catsanddog"\n["cat","cats","and","sand","dog"]' 15 | * 16 | * Given a non-empty string s and a dictionary wordDict containing a list of 17 | * non-empty words, add spaces in s to construct a sentence where each word is 18 | * a valid dictionary word. Return all such possible sentences. 19 | * 20 | * Note: 21 | * 22 | * 23 | * The same word in the dictionary may be reused multiple times in the 24 | * segmentation. 25 | * You may assume the dictionary does not contain duplicate words. 26 | * 27 | * 28 | * Example 1: 29 | * 30 | * 31 | * Input: 32 | * s = "catsanddog" 33 | * wordDict = ["cat", "cats", "and", "sand", "dog"] 34 | * Output: 35 | * [ 36 | * "cats and dog", 37 | * "cat sand dog" 38 | * ] 39 | * 40 | * 41 | * Example 2: 42 | * 43 | * 44 | * Input: 45 | * s = "pineapplepenapple" 46 | * wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] 47 | * Output: 48 | * [ 49 | * "pine apple pen apple", 50 | * "pineapple pen apple", 51 | * "pine applepen apple" 52 | * ] 53 | * Explanation: Note that you are allowed to reuse a dictionary word. 54 | * 55 | * 56 | * Example 3: 57 | * 58 | * 59 | * Input: 60 | * s = "catsandog" 61 | * wordDict = ["cats", "dog", "sand", "and", "cat"] 62 | * Output: 63 | * [] 64 | * 65 | */ 66 | class Solution { 67 | var dp = mutableMapOf>() 68 | 69 | fun wordBreak(s: String, wordDict: List): List { 70 | if (dp.containsKey(s)) return dp[s]!! 71 | var a = mutableListOf() 72 | 73 | for (i in wordDict.indices) { 74 | val temp = wordDict[i] 75 | if (s.length >= temp.length && s.substring(0, temp.length) == temp) { 76 | if (temp.length == s.length) { 77 | a.add(temp) 78 | } else { 79 | val subR = wordBreak(s.substring(temp.length), wordDict) 80 | for (j in subR.indices) { 81 | a.add("${temp} ${subR[j]}") 82 | } 83 | } 84 | } 85 | } 86 | dp[s] = a 87 | return a 88 | } 89 | } 90 | 91 | -------------------------------------------------------------------------------- /hard/1473.paint-house-iii.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1473 lang=kotlin 3 | * 4 | * [1473] Paint House III 5 | * 6 | * https://leetcode.com/problems/paint-house-iii/description/ 7 | * 8 | * algorithms 9 | * Hard (42.66%) 10 | * Likes: 157 11 | * Dislikes: 6 12 | * Total Accepted: 3.8K 13 | * Total Submissions: 8.5K 14 | * Testcase Example: '[0,0,0,0,0]\n[[1,10],[10,1],[10,1],[1,10],[5,1]]\n5\n2\n3' 15 | * 16 | * There is a row of m houses in a small city, each house must be painted with 17 | * one of the n colors (labeled from 1 to n), some houses that has been painted 18 | * last summer should not be painted again. 19 | * 20 | * A neighborhood is a maximal group of continuous houses that are painted with 21 | * the same color. (For example: houses = [1,2,2,3,3,2,1,1] contains 5 22 | * neighborhoods  [{1}, {2,2}, {3,3}, {2}, {1,1}]). 23 | * 24 | * Given an array houses, an m * n matrix cost and an integer target 25 | * where: 26 | * 27 | * 28 | * houses[i]: is the color of the house i, 0 if the house is not painted 29 | * yet. 30 | * cost[i][j]: is the cost of paint the house i with the color j+1. 31 | * 32 | * 33 | * Return the minimum cost of painting all the remaining houses in such a way 34 | * that there are exactly target neighborhoods, if not possible return -1. 35 | * 36 | * 37 | * Example 1: 38 | * 39 | * 40 | * Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 41 | * 5, n = 2, target = 3 42 | * Output: 9 43 | * Explanation: Paint houses of this way [1,2,2,1,1] 44 | * This array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}]. 45 | * Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9. 46 | * 47 | * 48 | * Example 2: 49 | * 50 | * 51 | * Input: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 52 | * 5, n = 2, target = 3 53 | * Output: 11 54 | * Explanation: Some houses are already painted, Paint the houses of this way 55 | * [2,2,1,2,2] 56 | * This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. 57 | * Cost of paint the first and last house (10 + 1) = 11. 58 | * 59 | * 60 | * Example 3: 61 | * 62 | * 63 | * Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[1,10],[10,1],[1,10]], m 64 | * = 5, n = 2, target = 5 65 | * Output: 5 66 | * 67 | * 68 | * Example 4: 69 | * 70 | * 71 | * Input: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, 72 | * n = 3, target = 3 73 | * Output: -1 74 | * Explanation: Houses are already painted with a total of 4 neighborhoods 75 | * [{3},{1},{2},{3}] different of target = 3. 76 | * 77 | * 78 | * 79 | * Constraints: 80 | * 81 | * 82 | * m == houses.length == cost.length 83 | * n == cost[i].length 84 | * 1 <= m <= 100 85 | * 1 <= n <= 20 86 | * 1 <= target <= m 87 | * 0 <= houses[i] <= n 88 | * 1 <= cost[i][j] <= 10^4 89 | * 90 | */ 91 | 92 | // @lc code=start 93 | class Solution { 94 | fun minCost(houses: IntArray, cost: Array, m: Int, n: Int, target: Int): Int { 95 | val dp = Array>>(m){Array>(n+1){Array(target+1) { Int.MAX_VALUE }}} 96 | if (houses[0] == 0) { 97 | for (i in 1 .. n) dp[0][i][0] = cost[0][i-1] 98 | } else { 99 | dp[0][houses[0]][0] = 0 100 | } 101 | 102 | for (i in 1 until m) { 103 | for (j in 1 .. n) { 104 | for (k in 0 until target) { 105 | if (houses[i] == 0) { 106 | for (j_old in 1 .. n) { 107 | if (dp[i-1][j_old][k] == Int.MAX_VALUE) continue 108 | 109 | if (j_old == j) { 110 | dp[i][j][k] = Math.min(dp[i - 1][j_old][k] + cost[i][j - 1], dp[i][j][k]) 111 | } else { 112 | dp[i][j][k + 1] = Math.min(dp[i - 1][j_old][k] + cost[i][j - 1], dp[i][j][k + 1]) 113 | } 114 | } 115 | } else { 116 | if (dp[i - 1][j][k] == Int.MAX_VALUE) continue 117 | 118 | if (houses[i] == j) { 119 | dp[i][j][k] = Math.min(dp[i - 1][j][k], dp[i][j][k]) 120 | } else { 121 | dp[i][houses[i]][k + 1] = Math.min(dp[i - 1][j][k], dp[i][houses[i]][k + 1]) 122 | } 123 | } 124 | } 125 | } 126 | } 127 | var ans = Int.MAX_VALUE 128 | for (j in 1 .. n) { 129 | ans = Math.min(ans, dp[m - 1][j][target - 1]) 130 | } 131 | return if (ans == Int.MAX_VALUE) -1 else ans; 132 | } 133 | } 134 | // @lc code=end 135 | 136 | -------------------------------------------------------------------------------- /hard/1585.check-if-string-is-transformable-with-substring-sort-operations.kt: -------------------------------------------------------------------------------- 1 | //Given two strings s and t, you want to transform string s into string t using 2 | //the following operation any number of times: 3 | // 4 | // 5 | // Choose a non-empty substring in s and sort it in-place so the characters are 6 | //in ascending order. 7 | // 8 | // 9 | // For example, applying the operation on the underlined substring in "14234" re 10 | //sults in "12344". 11 | // 12 | // Return true if it is possible to transform string s into string t. Otherwise, 13 | // return false. 14 | // 15 | // A substring is a contiguous sequence of characters within a string. 16 | // 17 | // 18 | // Example 1: 19 | // 20 | // 21 | //Input: s = "84532", t = "34852" 22 | //Output: true 23 | //Explanation: You can transform s into t using the following sort operations: 24 | //"84532" (from index 2 to 3) -> "84352" 25 | //"84352" (from index 0 to 2) -> "34852" 26 | // 27 | // 28 | // Example 2: 29 | // 30 | // 31 | //Input: s = "34521", t = "23415" 32 | //Output: true 33 | //Explanation: You can transform s into t using the following sort operations: 34 | //"34521" -> "23451" 35 | //"23451" -> "23415" 36 | // 37 | // 38 | // Example 3: 39 | // 40 | // 41 | //Input: s = "12345", t = "12435" 42 | //Output: false 43 | // 44 | // 45 | // Example 4: 46 | // 47 | // 48 | //Input: s = "1", t = "2" 49 | //Output: false 50 | // 51 | // 52 | // 53 | // Constraints: 54 | // 55 | // 56 | // s.length == t.length 57 | // 1 <= s.length <= 105 58 | // s and t only contain digits from '0' to '9'. 59 | // 60 | // Related Topics String Greedy 61 | // 👍 157 👎 3 62 | 63 | 64 | //leetcode submit region begin(Prohibit modification and deletion) 65 | class Solution { 66 | fun isTransformable(s: String, t: String): Boolean { 67 | val idx = Array>(10) { mutableListOf() } 68 | val pos = IntArray(10) 69 | 70 | for ((index, value) in s.withIndex()) { 71 | idx[value-'0'].add(index) 72 | } 73 | 74 | for ((index, value) in t.withIndex()) { 75 | val d = value-'0' 76 | if (pos[d] >= idx[d].size) return false 77 | for (j in 0 until d) { 78 | if (pos[j] < idx[j].size && idx[j][pos[j]] < idx[d][pos[d]]) return false 79 | } 80 | pos[d]++ 81 | } 82 | return true 83 | } 84 | } 85 | //leetcode submit region end(Prohibit modification and deletion) 86 | -------------------------------------------------------------------------------- /hard/23.merge-k-sorted-lists.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=23 lang=kotlin 3 | * 4 | * [23] Merge k Sorted Lists 5 | * 6 | * https://leetcode.com/problems/merge-k-sorted-lists/description/ 7 | * 8 | * algorithms 9 | * Hard (39.49%) 10 | * Likes: 4576 11 | * Dislikes: 284 12 | * Total Accepted: 634.6K 13 | * Total Submissions: 1.6M 14 | * Testcase Example: '[[1,4,5],[1,3,4],[2,6]]' 15 | * 16 | * Merge k sorted linked lists and return it as one sorted list. Analyze and 17 | * describe its complexity. 18 | * 19 | * Example: 20 | * 21 | * 22 | * Input: 23 | * [ 24 | * 1->4->5, 25 | * 1->3->4, 26 | * 2->6 27 | * ] 28 | * Output: 1->1->2->3->4->4->5->6 29 | * 30 | * 31 | */ 32 | 33 | // @lc code=start 34 | /** 35 | * Example: 36 | * var li = ListNode(5) 37 | * var v = li.`val` 38 | * Definition for singly-linked list. 39 | * class ListNode(var `val`: Int) { 40 | * var next: ListNode? = null 41 | * } 42 | */ 43 | class Solution { 44 | fun mergeKLists(lists: Array): ListNode? { 45 | val queue = PriorityQueue() { a, b -> a.`val`-b.`val` } 46 | for (list in lists) { 47 | if (list != null) { 48 | queue.add(list) 49 | } 50 | } 51 | 52 | var head: ListNode? = null 53 | var last: ListNode? = null 54 | while (queue.isNotEmpty()) { 55 | val top = queue.peek() 56 | queue.remove() 57 | if(top?.next != null) { 58 | queue.add(top.next) 59 | } 60 | if (head == null) { 61 | head = top 62 | last = top 63 | } else { 64 | last?.next = top 65 | last = top 66 | } 67 | } 68 | return head 69 | } 70 | } 71 | // @lc code=end 72 | 73 | -------------------------------------------------------------------------------- /hard/25.reverse-nodes-in-k-group.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=25 lang=kotlin 3 | * 4 | * [25] Reverse Nodes in k-Group 5 | * 6 | * https://leetcode.com/problems/reverse-nodes-in-k-group/description/ 7 | * 8 | * algorithms 9 | * Hard (41.26%) 10 | * Likes: 2105 11 | * Dislikes: 357 12 | * Total Accepted: 263.1K 13 | * Total Submissions: 637.5K 14 | * Testcase Example: '[1,2,3,4,5]\n2' 15 | * 16 | * Given a linked list, reverse the nodes of a linked list k at a time and 17 | * return its modified list. 18 | * 19 | * k is a positive integer and is less than or equal to the length of the 20 | * linked list. If the number of nodes is not a multiple of k then left-out 21 | * nodes in the end should remain as it is. 22 | * 23 | * 24 | * 25 | * 26 | * Example: 27 | * 28 | * Given this linked list: 1->2->3->4->5 29 | * 30 | * For k = 2, you should return: 2->1->4->3->5 31 | * 32 | * For k = 3, you should return: 3->2->1->4->5 33 | * 34 | * Note: 35 | * 36 | * 37 | * Only constant extra memory is allowed. 38 | * You may not alter the values in the list's nodes, only nodes itself may be 39 | * changed. 40 | * 41 | * 42 | */ 43 | 44 | // @lc code=start 45 | /** 46 | * Example: 47 | * var li = ListNode(5) 48 | * var v = li.`val` 49 | * Definition for singly-linked list. 50 | * class ListNode(var `val`: Int) { 51 | * var next: ListNode? = null 52 | * } 53 | */ 54 | /** 55 | -1->1->2->3->4->5 56 | | | | 57 | pre cur next 58 | 59 | -1->3->2->1->4->5 60 | | | | 61 | cur pre next 62 | */ 63 | class Solution { 64 | fun reverseKGroup(head: ListNode?, k: Int): ListNode? { 65 | val dummy: ListNode? = ListNode(-1) 66 | dummy?.next = head 67 | var pre = dummy 68 | var cur = pre?.next 69 | 70 | var num = 0 71 | while (cur != null) { 72 | ++num 73 | cur = cur?.next 74 | } 75 | 76 | while (num >= k) { 77 | cur = pre?.next 78 | for (i in 1 until k) { 79 | val t = cur?.next 80 | cur?.next = t?.next 81 | t?.next = pre?.next 82 | pre?.next = t 83 | } 84 | pre = cur 85 | num -= k 86 | } 87 | return dummy?.next 88 | } 89 | } 90 | // @lc code=end 91 | 92 | -------------------------------------------------------------------------------- /hard/32.longest-valid-parentheses.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=32 lang=kotlin 3 | * 4 | * [32] Longest Valid Parentheses 5 | * 6 | * https://leetcode.com/problems/longest-valid-parentheses/description/ 7 | * 8 | * algorithms 9 | * Hard (25.23%) 10 | * Likes: 2094 11 | * Dislikes: 96 12 | * Total Accepted: 205.3K 13 | * Total Submissions: 789.7K 14 | * Testcase Example: '"(()"' 15 | * 16 | * Given a string containing just the characters '(' and ')', find the length 17 | * of the longest valid (well-formed) parentheses substring. 18 | * 19 | * Example 1: 20 | * 21 | * 22 | * Input: "(()" 23 | * Output: 2 24 | * Explanation: The longest valid parentheses substring is "()" 25 | * 26 | * 27 | * Example 2: 28 | * 29 | * 30 | * Input: ")()())" 31 | * Output: 4 32 | * Explanation: The longest valid parentheses substring is "()()" 33 | * 34 | * 35 | */ 36 | class Solution { 37 | fun longestValidParentheses(s: String): Int { 38 | var dp = IntArray(100000, {0}) 39 | var res = 0 40 | for (i in 2 .. s.length) { 41 | if (s[i-1] == ')') { 42 | if (i-dp[i-1]-2 >= 0 && s[i-dp[i-1]-2] == '(') { 43 | dp[i] = dp[i-1]+2 44 | dp[i] += dp[i-dp[i]] 45 | } 46 | } 47 | if (res < dp[i]) res = dp[i] 48 | } 49 | return res 50 | } 51 | } 52 | 53 | -------------------------------------------------------------------------------- /hard/329.longest-increasing-path-in-a-matrix.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=329 lang=kotlin 3 | * 4 | * [329] Longest Increasing Path in a Matrix 5 | * 6 | * https://leetcode.com/problems/longest-increasing-path-in-a-matrix/description/ 7 | * 8 | * algorithms 9 | * Hard (40.64%) 10 | * Likes: 1136 11 | * Dislikes: 19 12 | * Total Accepted: 96.6K 13 | * Total Submissions: 237.4K 14 | * Testcase Example: '[[9,9,4],[6,6,8],[2,1,1]]' 15 | * 16 | * Given an integer matrix, find the length of the longest increasing path. 17 | * 18 | * From each cell, you can either move to four directions: left, right, up or 19 | * down. You may NOT move diagonally or move outside of the boundary (i.e. 20 | * wrap-around is not allowed). 21 | * 22 | * Example 1: 23 | * 24 | * 25 | * Input: nums = 26 | * [ 27 | * ⁠ [9,9,4], 28 | * ⁠ [6,6,8], 29 | * ⁠ [2,1,1] 30 | * ] 31 | * Output: 4 32 | * Explanation: The longest increasing path is [1, 2, 6, 9]. 33 | * 34 | * 35 | * Example 2: 36 | * 37 | * 38 | * Input: nums = 39 | * [ 40 | * ⁠ [3,4,5], 41 | * ⁠ [3,2,6], 42 | * ⁠ [2,2,1] 43 | * ] 44 | * Output: 4 45 | * Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally 46 | * is not allowed. 47 | * 48 | * 49 | */ 50 | class Solution { 51 | private var dp = Array(1005){IntArray(1005)} 52 | private val dir = arrayOf(intArrayOf(0, -1), intArrayOf(0, 1), 53 | intArrayOf(-1, 0), intArrayOf(1, 0)) 54 | 55 | fun longestIncreasingPath(matrix: Array): Int { 56 | if (matrix.size == 0) return 0 57 | 58 | var ans = 0 59 | val n = matrix.size 60 | val m = matrix[0].size 61 | for (i in 0 until n) 62 | for (j in 0 until m) 63 | ans = Math.max(ans, dfs(matrix, i, j)) 64 | return ans 65 | } 66 | 67 | private fun dfs(matrix: Array, x: Int, y: Int): Int { 68 | if (dp[x][y] > 0) return dp[x][y] 69 | dp[x][y] = 1 70 | for (i in 0 .. 3) { 71 | val nx = x+dir[i][0] 72 | val ny = y+dir[i][1] 73 | if (nx >= matrix.size || nx < 0 74 | || ny >= matrix[0].size || ny < 0) continue 75 | if (matrix[nx][ny] > matrix[x][y]) { 76 | dp[x][y] = Math.max(dp[x][y], 1+dfs(matrix, nx, ny)) 77 | } 78 | } 79 | return dp[x][y] 80 | } 81 | } 82 | 83 | -------------------------------------------------------------------------------- /hard/44.wildcard-matching.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=44 lang=kotlin 3 | * 4 | * [44] Wildcard Matching 5 | * 6 | * https://leetcode.com/problems/wildcard-matching/description/ 7 | * 8 | * algorithms 9 | * Hard (23.18%) 10 | * Likes: 1189 11 | * Dislikes: 77 12 | * Total Accepted: 187.9K 13 | * Total Submissions: 810.7K 14 | * Testcase Example: '"aa"\n"a"' 15 | * 16 | * Given an input string (s) and a pattern (p), implement wildcard pattern 17 | * matching with support for '?' and '*'. 18 | * 19 | * 20 | * '?' Matches any single character. 21 | * '*' Matches any sequence of characters (including the empty sequence). 22 | * 23 | * 24 | * The matching should cover the entire input string (not partial). 25 | * 26 | * Note: 27 | * 28 | * 29 | * s could be empty and contains only lowercase letters a-z. 30 | * p could be empty and contains only lowercase letters a-z, and characters 31 | * like ? or *. 32 | * 33 | * 34 | * Example 1: 35 | * 36 | * 37 | * Input: 38 | * s = "aa" 39 | * p = "a" 40 | * Output: false 41 | * Explanation: "a" does not match the entire string "aa". 42 | * 43 | * 44 | * Example 2: 45 | * 46 | * 47 | * Input: 48 | * s = "aa" 49 | * p = "*" 50 | * Output: true 51 | * Explanation: '*' matches any sequence. 52 | * 53 | * 54 | * Example 3: 55 | * 56 | * 57 | * Input: 58 | * s = "cb" 59 | * p = "?a" 60 | * Output: false 61 | * Explanation: '?' matches 'c', but the second letter is 'a', which does not 62 | * match 'b'. 63 | * 64 | * 65 | * Example 4: 66 | * 67 | * 68 | * Input: 69 | * s = "adceb" 70 | * p = "*a*b" 71 | * Output: true 72 | * Explanation: The first '*' matches the empty sequence, while the second '*' 73 | * matches the substring "dce". 74 | * 75 | * 76 | * Example 5: 77 | * 78 | * 79 | * Input: 80 | * s = "acdcb" 81 | * p = "a*c?b" 82 | * Output: false 83 | * 84 | * 85 | */ 86 | class Solution { 87 | fun isMatch(s: String, p: String): Boolean { 88 | var dp = Array(s.length+1){BooleanArray(p.length+1, {false})} 89 | 90 | dp[0][0] = true 91 | for (i in 0 .. s.length) { 92 | for (j in 1 .. p.length) { 93 | if (p[j-1] == '*') { 94 | dp[i][j] = dp[i][j-1] || (i > 0 && dp[i-1][j]) 95 | } else { 96 | dp[i][j] = i > 0 && dp[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == '?') 97 | } 98 | } 99 | } 100 | return dp[s.length][p.length] 101 | } 102 | } 103 | 104 | -------------------------------------------------------------------------------- /hard/72.edit-distance.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=72 lang=kotlin 3 | * 4 | * [72] Edit Distance 5 | * 6 | * https://leetcode.com/problems/edit-distance/description/ 7 | * 8 | * algorithms 9 | * Hard (38.79%) 10 | * Likes: 2323 11 | * Dislikes: 35 12 | * Total Accepted: 187.5K 13 | * Total Submissions: 483.4K 14 | * Testcase Example: '"horse"\n"ros"' 15 | * 16 | * Given two words word1 and word2, find the minimum number of operations 17 | * required to convert word1 to word2. 18 | * 19 | * You have the following 3 operations permitted on a word: 20 | * 21 | * 22 | * Insert a character 23 | * Delete a character 24 | * Replace a character 25 | * 26 | * 27 | * Example 1: 28 | * 29 | * 30 | * Input: word1 = "horse", word2 = "ros" 31 | * Output: 3 32 | * Explanation: 33 | * horse -> rorse (replace 'h' with 'r') 34 | * rorse -> rose (remove 'r') 35 | * rose -> ros (remove 'e') 36 | * 37 | * 38 | * Example 2: 39 | * 40 | * 41 | * Input: word1 = "intention", word2 = "execution" 42 | * Output: 5 43 | * Explanation: 44 | * intention -> inention (remove 't') 45 | * inention -> enention (replace 'i' with 'e') 46 | * enention -> exention (replace 'n' with 'x') 47 | * exention -> exection (replace 'n' with 'c') 48 | * exection -> execution (insert 'u') 49 | * 50 | * 51 | */ 52 | class Solution { 53 | fun minDistance(word1: String, word2: String): Int { 54 | if (word1 == "") return word2.length 55 | if (word2 == "") return word1.length 56 | val n = word1.length 57 | val m = word2.length 58 | 59 | var dp = Array(n+1){IntArray(m+1)} 60 | 61 | 62 | for (i in 0 .. n) dp[i][0] = i 63 | for (i in 0 .. m) dp[0][i] = i 64 | 65 | for (i in 1 .. n) { 66 | for (j in 1 .. m) { 67 | if (word1[i-1] == word2[j-1]) { 68 | dp[i][j] = dp[i-1][j-1] 69 | } else { 70 | dp[i][j] = Math.min(dp[i][j-1], Math.min(dp[i-1][j], dp[i-1][j-1]))+1 71 | } 72 | } 73 | } 74 | return dp[n][m] 75 | } 76 | } 77 | 78 | -------------------------------------------------------------------------------- /hard/85.maximal-rectangle.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=85 lang=kotlin 3 | * 4 | * [85] Maximal Rectangle 5 | * 6 | * https://leetcode.com/problems/maximal-rectangle/description/ 7 | * 8 | * algorithms 9 | * Hard (34.14%) 10 | * Likes: 1614 11 | * Dislikes: 53 12 | * Total Accepted: 130.2K 13 | * Total Submissions: 381.2K 14 | * Testcase Example: '[["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]' 15 | * 16 | * Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle 17 | * containing only 1's and return its area. 18 | * 19 | * Example: 20 | * 21 | * 22 | * Input: 23 | * [ 24 | * ⁠ ["1","0","1","0","0"], 25 | * ⁠ ["1","0","1","1","1"], 26 | * ⁠ ["1","1","1","1","1"], 27 | * ⁠ ["1","0","0","1","0"] 28 | * ] 29 | * Output: 6 30 | * 31 | * 32 | */ 33 | class Solution { 34 | fun maximalRectangle(matrix: Array): Int { 35 | if (matrix.size == 0) return 0 36 | 37 | val n = matrix.size 38 | val m = matrix[0].size 39 | 40 | var dp = Array(n+5){IntArray(m+5)} 41 | 42 | for (i in 0 until n) 43 | for (j in 0 until m) 44 | dp[i+1][j+1] = matrix[i][j]-'0' 45 | 46 | var col = Array(n+5){IntArray(m+5)} 47 | for (i in 1 .. m) { 48 | for (j in 1 .. n) { 49 | if (dp[j][i] == 1) 50 | col[j][i] = col[j-1][i]+dp[j][i] 51 | } 52 | } 53 | // for (i in 1 ..n) { 54 | // for (j in 1 .. m) { 55 | // print("${col[i][j]} ") 56 | // } 57 | // println() 58 | // } 59 | var maxa = 0 60 | for (i in 1 .. n) { 61 | for (j in i .. n) { 62 | var r = IntArray(m+1) 63 | for (k in 1 .. m) 64 | r[k] = col[j][k]-col[i-1][k] 65 | // println("${i} ${j}") 66 | // for (k in 1 .. m) { 67 | // print("${r[k]} ") 68 | // } 69 | // println() 70 | // println() 71 | var temp = 0 72 | for (k in 1 .. m) { 73 | if (r[k] == r[k-1]) { 74 | temp += r[k] 75 | } else { 76 | temp = r[k] 77 | } 78 | maxa = Math.max(maxa, temp) 79 | } 80 | } 81 | } 82 | return maxa 83 | } 84 | } 85 | // fun main(args: Array) { 86 | // val s = Solution() 87 | // println(s.maximalRectangle(arrayOf(charArrayOf('0', '1'), charArrayOf('1', '0')))) 88 | // } 89 | 90 | -------------------------------------------------------------------------------- /medium/1038.binary-search-tree-to-greater-sum-tree.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1038 lang=kotlin 3 | * 4 | * [1038] Binary Search Tree to Greater Sum Tree 5 | */ 6 | /** 7 | * Example: 8 | * var ti = TreeNode(5) 9 | * var v = ti.`val` 10 | * Definition for a binary tree node. 11 | * class TreeNode(var `val`: Int) { 12 | * var left: TreeNode? = null 13 | * var right: TreeNode? = null 14 | * } 15 | */ 16 | class Solution { 17 | private var cnt = 0 18 | 19 | fun bstToGst(root: TreeNode?): TreeNode? { 20 | if (root == null) return null 21 | bstToGst(root?.right) 22 | val temp = root!!.`val` 23 | root!!.`val` += cnt 24 | cnt += temp 25 | bstToGst(root?.left) 26 | return root 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /medium/11.container-with-most-water.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=11 lang=kotlin 3 | * 4 | * [11] Container With Most Water 5 | */ 6 | class Solution { 7 | fun maxArea(height: IntArray): Int { 8 | var left = 0 9 | var right = height.size-1 10 | var maxa = 0 11 | 12 | while (left < right) { 13 | maxa = Math.max(maxa, Math.min(height[left], height[right])*(right-left)) 14 | if (height[left] > height[right]) { 15 | right-- 16 | } else { 17 | left++ 18 | } 19 | } 20 | return maxa 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /medium/114.flatten-binary-tree-to-linked-list.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=114 lang=kotlin 3 | * 4 | * [114] Flatten Binary Tree to Linked List 5 | * 6 | * https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/ 7 | * 8 | * algorithms 9 | * Medium (48.29%) 10 | * Likes: 2761 11 | * Dislikes: 330 12 | * Total Accepted: 345.7K 13 | * Total Submissions: 708.9K 14 | * Testcase Example: '[1,2,5,3,4,null,6]' 15 | * 16 | * Given a binary tree, flatten it to a linked list in-place. 17 | * 18 | * For example, given the following tree: 19 | * 20 | * 21 | * ⁠ 1 22 | * ⁠ / \ 23 | * ⁠ 2 5 24 | * ⁠/ \ \ 25 | * 3 4 6 26 | * 27 | * 28 | * The flattened tree should look like: 29 | * 30 | * 31 | * 1 32 | * ⁠\ 33 | * ⁠ 2 34 | * ⁠ \ 35 | * ⁠ 3 36 | * ⁠ \ 37 | * ⁠ 4 38 | * ⁠ \ 39 | * ⁠ 5 40 | * ⁠ \ 41 | * ⁠ 6 42 | * 43 | * 44 | */ 45 | 46 | // @lc code=start 47 | /** 48 | * Example: 49 | * var ti = TreeNode(5) 50 | * var v = ti.`val` 51 | * Definition for a binary tree node. 52 | * class TreeNode(var `val`: Int) { 53 | * var left: TreeNode? = null 54 | * var right: TreeNode? = null 55 | * } 56 | */ 57 | class Solution { 58 | fun flatten(root: TreeNode?): Unit { 59 | var cur = root 60 | 61 | while (cur != null) { 62 | if (cur?.left != null) { 63 | var p = cur?.left 64 | while (p?.right != null) { 65 | p = p?.right 66 | } 67 | p?.right = cur?.right 68 | cur?.right = cur?.left 69 | cur?.left = null 70 | } 71 | cur = cur?.right 72 | } 73 | } 74 | } 75 | // @lc code=end -------------------------------------------------------------------------------- /medium/12.integer-to-roman.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=12 lang=kotlin 3 | * 4 | * [12] Integer to Roman 5 | * 6 | * https://leetcode.com/problems/integer-to-roman/description/ 7 | * 8 | * algorithms 9 | * Medium (50.49%) 10 | * Likes: 594 11 | * Dislikes: 1873 12 | * Total Accepted: 234.1K 13 | * Total Submissions: 458K 14 | * Testcase Example: '3' 15 | * 16 | * Roman numerals are represented by seven different symbols: I, V, X, L, C, D 17 | * and M. 18 | * 19 | * 20 | * Symbol Value 21 | * I 1 22 | * V 5 23 | * X 10 24 | * L 50 25 | * C 100 26 | * D 500 27 | * M 1000 28 | * 29 | * For example, two is written as II in Roman numeral, just two one's added 30 | * together. Twelve is written as, XII, which is simply X + II. The number 31 | * twenty seven is written as XXVII, which is XX + V + II. 32 | * 33 | * Roman numerals are usually written largest to smallest from left to right. 34 | * However, the numeral for four is not IIII. Instead, the number four is 35 | * written as IV. Because the one is before the five we subtract it making 36 | * four. The same principle applies to the number nine, which is written as IX. 37 | * There are six instances where subtraction is used: 38 | * 39 | * 40 | * I can be placed before V (5) and X (10) to make 4 and 9.  41 | * X can be placed before L (50) and C (100) to make 40 and 90.  42 | * C can be placed before D (500) and M (1000) to make 400 and 900. 43 | * 44 | * 45 | * Given an integer, convert it to a roman numeral. Input is guaranteed to be 46 | * within the range from 1 to 3999. 47 | * 48 | * Example 1: 49 | * 50 | * 51 | * Input: 3 52 | * Output: "III" 53 | * 54 | * Example 2: 55 | * 56 | * 57 | * Input: 4 58 | * Output: "IV" 59 | * 60 | * Example 3: 61 | * 62 | * 63 | * Input: 9 64 | * Output: "IX" 65 | * 66 | * Example 4: 67 | * 68 | * 69 | * Input: 58 70 | * Output: "LVIII" 71 | * Explanation: L = 50, V = 5, III = 3. 72 | * 73 | * 74 | * Example 5: 75 | * 76 | * 77 | * Input: 1994 78 | * Output: "MCMXCIV" 79 | * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. 80 | * 81 | */ 82 | class Solution { 83 | private val m_k = listOf(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1) 84 | private val m_v = listOf("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I") 85 | 86 | fun intToRoman(num: Int): String { 87 | var str = "" 88 | var n = num 89 | 90 | for (i in m_k.indices) { 91 | while (n >= m_k[i]) { 92 | n -= m_k[i] 93 | str += m_v[i] 94 | } 95 | } 96 | return str 97 | } 98 | } 99 | 100 | -------------------------------------------------------------------------------- /medium/120.triangle.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=120 lang=kotlin 3 | * 4 | * [120] Triangle 5 | * 6 | * https://leetcode.com/problems/triangle/description/ 7 | * 8 | * algorithms 9 | * Medium (40.39%) 10 | * Likes: 1261 11 | * Dislikes: 144 12 | * Total Accepted: 195.1K 13 | * Total Submissions: 482.7K 14 | * Testcase Example: '[[2],[3,4],[6,5,7],[4,1,8,3]]' 15 | * 16 | * Given a triangle, find the minimum path sum from top to bottom. Each step 17 | * you may move to adjacent numbers on the row below. 18 | * 19 | * For example, given the following triangle 20 | * 21 | * 22 | * [ 23 | * ⁠ [2], 24 | * ⁠ [3,4], 25 | * ⁠ [6,5,7], 26 | * ⁠ [4,1,8,3] 27 | * ] 28 | * 29 | * 30 | * The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 31 | * 32 | * Note: 33 | * 34 | * Bonus point if you are able to do this using only O(n) extra space, where n 35 | * is the total number of rows in the triangle. 36 | * 37 | */ 38 | class Solution { 39 | fun minimumTotal(triangle: List>): Int { 40 | var n = triangle.size 41 | 42 | if (n == 0) return 0 43 | 44 | var dp = Array(n+1) { IntArray(n+1, {0x3f3f3f3f}) } 45 | dp[0][0] = triangle[0][0] 46 | 47 | for (i in 1 until n) 48 | for (j in 0 .. i) 49 | if (j == 0) dp[i][j] = dp[i-1][j]+triangle[i][j] 50 | else dp[i][j] = Math.min(dp[i-1][j], dp[i-1][j-1])+triangle[i][j] 51 | var maxa = 0x3f3f3f3f 52 | for (i in 0 until n) maxa = Math.min(maxa, dp[n-1][i]) 53 | 54 | return maxa 55 | } 56 | } 57 | 58 | -------------------------------------------------------------------------------- /medium/127.word-ladder.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=127 lang=kotlin 3 | * 4 | * [127] Word Ladder 5 | * 6 | * https://leetcode.com/problems/word-ladder/description/ 7 | * 8 | * algorithms 9 | * Medium (25.13%) 10 | * Likes: 1763 11 | * Dislikes: 883 12 | * Total Accepted: 292.7K 13 | * Total Submissions: 1.2M 14 | * Testcase Example: '"hit"\n"cog"\n["hot","dot","dog","lot","log","cog"]' 15 | * 16 | * Given two words (beginWord and endWord), and a dictionary's word list, find 17 | * the length of shortest transformation sequence from beginWord to endWord, 18 | * such that: 19 | * 20 | * 21 | * Only one letter can be changed at a time. 22 | * Each transformed word must exist in the word list. Note that beginWord is 23 | * not a transformed word. 24 | * 25 | * 26 | * Note: 27 | * 28 | * 29 | * Return 0 if there is no such transformation sequence. 30 | * All words have the same length. 31 | * All words contain only lowercase alphabetic characters. 32 | * You may assume no duplicates in the word list. 33 | * You may assume beginWord and endWord are non-empty and are not the same. 34 | * 35 | * 36 | * Example 1: 37 | * 38 | * 39 | * Input: 40 | * beginWord = "hit", 41 | * endWord = "cog", 42 | * wordList = ["hot","dot","dog","lot","log","cog"] 43 | * 44 | * Output: 5 45 | * 46 | * Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> 47 | * "dog" -> "cog", 48 | * return its length 5. 49 | * 50 | * 51 | * Example 2: 52 | * 53 | * 54 | * Input: 55 | * beginWord = "hit" 56 | * endWord = "cog" 57 | * wordList = ["hot","dot","dog","lot","log"] 58 | * 59 | * Output: 0 60 | * 61 | * Explanation: The endWord "cog" is not in wordList, therefore no possible 62 | * transformation. 63 | * 64 | * 65 | * 66 | * 67 | * 68 | */ 69 | import java.util.LinkedList 70 | 71 | class Solution { 72 | data class Node( 73 | var str: String = "", 74 | var step: Int = 0 75 | ) 76 | fun ladderLength(beginWord: String, endWord: String, wordList: List): Int { 77 | var q = LinkedList() 78 | var vis = mutableMapOf() 79 | 80 | q.offer(Node(beginWord, 1)) 81 | vis[beginWord] = true 82 | 83 | while (!q.isEmpty()) { 84 | val top = q.poll() 85 | 86 | if (top.str == endWord) { 87 | return top.step 88 | } 89 | 90 | for (i in wordList) { 91 | if (vis[i] ?: false) continue 92 | var cnt = 0 93 | for (j in 0 until beginWord.length) 94 | if (top.str[j] != i[j]) cnt++ 95 | if (cnt <= 1) { 96 | vis[i] = true 97 | q.offer(Node(i, top.step+1)) 98 | } 99 | } 100 | } 101 | return 0 102 | } 103 | } 104 | 105 | -------------------------------------------------------------------------------- /medium/1305.all-elements-in-two-binary-search-trees.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1305 lang=kotlin 3 | * 4 | * [1305] 两棵二叉搜索树中的所有元素 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Example: 10 | * var ti = TreeNode(5) 11 | * var v = ti.`val` 12 | * Definition for a binary tree node. 13 | * class TreeNode(var `val`: Int) { 14 | * var left: TreeNode? = null 15 | * var right: TreeNode? = null 16 | * } 17 | */ 18 | class Solution { 19 | private val res: MutableList = mutableListOf() 20 | 21 | fun getAllElements(root1: TreeNode?, root2: TreeNode?): List { 22 | dfs(root1) 23 | dfs(root2) 24 | return res.sorted() 25 | } 26 | 27 | private fun dfs(root: TreeNode?) { 28 | if (root == null) return 29 | if (root?.left != null) dfs(root?.left); 30 | if (root?.right != null) dfs(root?.right); 31 | res.add(root!!.`val`) 32 | } 33 | } 34 | // @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /medium/1306.jump-game-iii.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1306 lang=kotlin 3 | * 4 | * [1306] Jump Game III 5 | * 6 | * https://leetcode.com/problems/jump-game-iii/description/ 7 | * 8 | * algorithms 9 | * Medium (61.14%) 10 | * Likes: 105 11 | * Dislikes: 2 12 | * Total Accepted: 6.7K 13 | * Total Submissions: 11K 14 | * Testcase Example: '[4,2,3,0,3,1,2]\n5' 15 | * 16 | * Given an array of non-negative integers arr, you are initially positioned at 17 | * start index of the array. When you are at index i, you can jump to i + 18 | * arr[i] or i - arr[i], check if you can reach to any index with value 0. 19 | * 20 | * Notice that you can not jump outside of the array at any time. 21 | * 22 | * 23 | * Example 1: 24 | * 25 | * 26 | * Input: arr = [4,2,3,0,3,1,2], start = 5 27 | * Output: true 28 | * Explanation: 29 | * All possible ways to reach at index 3 with value 0 are: 30 | * index 5 -> index 4 -> index 1 -> index 3 31 | * index 5 -> index 6 -> index 4 -> index 1 -> index 3 32 | * 33 | * 34 | * Example 2: 35 | * 36 | * 37 | * Input: arr = [4,2,3,0,3,1,2], start = 0 38 | * Output: true 39 | * Explanation: 40 | * One possible way to reach at index 3 with value 0 is: 41 | * index 0 -> index 4 -> index 1 -> index 3 42 | * 43 | * 44 | * Example 3: 45 | * 46 | * 47 | * Input: arr = [3,0,2,1,2], start = 2 48 | * Output: false 49 | * Explanation: There is no way to reach at index 1 with value 0. 50 | * 51 | * 52 | * 53 | * Constraints: 54 | * 55 | * 56 | * 1 <= arr.length <= 5 * 10^4 57 | * 0 <= arr[i] < arr.length 58 | * 0 <= start < arr.length 59 | * 60 | */ 61 | 62 | import java.util.LinkedList 63 | class Solution { 64 | fun canReach(arr: IntArray, start: Int): Boolean { 65 | val n = arr.size 66 | var q = LinkedList() 67 | var vis = BooleanArray(n) 68 | q.offer(start) 69 | vis[start] = true 70 | 71 | while (!q.isEmpty()) { 72 | val top = q.poll() 73 | 74 | if (arr[top] == 0) return true 75 | 76 | if (top+arr[top] < n && !vis[top+arr[top]]) { 77 | vis[top+arr[top]] = true 78 | q.offer(top+arr[top]) 79 | } 80 | 81 | if (top-arr[top] >= 0 && !vis[top-arr[top]]) { 82 | vis[top-arr[top]] = true 83 | q.offer(top-arr[top]) 84 | } 85 | } 86 | return false 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /medium/134.gas-station.kt: -------------------------------------------------------------------------------- 1 | //There are N gas stations along a circular route, where the amount of gas at st 2 | //ation i is gas[i]. 3 | // 4 | // You have a car with an unlimited gas tank and it costs cost[i] of gas to trav 5 | //el from station i to its next station (i+1). You begin the journey with an empty 6 | // tank at one of the gas stations. 7 | // 8 | // Return the starting gas station's index if you can travel around the circuit 9 | //once in the clockwise direction, otherwise return -1. 10 | // 11 | // Note: 12 | // 13 | // 14 | // If there exists a solution, it is guaranteed to be unique. 15 | // Both input arrays are non-empty and have the same length. 16 | // Each element in the input arrays is a non-negative integer. 17 | // 18 | // 19 | // Example 1: 20 | // 21 | // 22 | //Input: 23 | //gas = [1,2,3,4,5] 24 | //cost = [3,4,5,1,2] 25 | // 26 | //Output: 3 27 | // 28 | //Explanation: 29 | //Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 30 | // = 4 31 | //Travel to station 4. Your tank = 4 - 1 + 5 = 8 32 | //Travel to station 0. Your tank = 8 - 2 + 1 = 7 33 | //Travel to station 1. Your tank = 7 - 3 + 2 = 6 34 | //Travel to station 2. Your tank = 6 - 4 + 3 = 5 35 | //Travel to station 3. The cost is 5. Your gas is just enough to travel back to 36 | //station 3. 37 | //Therefore, return 3 as the starting index. 38 | // 39 | // 40 | // Example 2: 41 | // 42 | // 43 | //Input: 44 | //gas = [2,3,4] 45 | //cost = [3,4,3] 46 | // 47 | //Output: -1 48 | // 49 | //Explanation: 50 | //You can't start at station 0 or 1, as there is not enough gas to travel to the 51 | // next station. 52 | //Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 53 | // 54 | //Travel to station 0. Your tank = 4 - 3 + 2 = 3 55 | //Travel to station 1. Your tank = 3 - 3 + 3 = 3 56 | //You cannot travel back to station 2, as it requires 4 unit of gas but you only 57 | // have 3. 58 | //Therefore, you can't travel around the circuit once no matter where you start. 59 | // 60 | // 61 | // Related Topics Greedy 62 | // 👍 1994 👎 388 63 | 64 | 65 | //leetcode submit region begin(Prohibit modification and deletion) 66 | class Solution { 67 | fun canCompleteCircuit(gas: IntArray, cost: IntArray): Int { 68 | val n = gas.size 69 | var sum = 0 70 | for (i in 0 until n) { 71 | sum += gas[i]-cost[i] 72 | } 73 | if (sum < 0) return -1 74 | var start = 0 75 | var restGas = 0 76 | 77 | for (i in 0 until n) { 78 | var temp = gas[i]-cost[i] 79 | 80 | if (restGas+temp < 0) { 81 | start = i+1 82 | restGas = 0 83 | } else { 84 | restGas += temp 85 | } 86 | } 87 | return start 88 | } 89 | } 90 | //leetcode submit region end(Prohibit modification and deletion) 91 | -------------------------------------------------------------------------------- /medium/1362.closest-divisors.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1362 lang=kotlin 3 | * 4 | * [1362] Closest Divisors 5 | * 6 | * https://leetcode.com/problems/closest-divisors/description/ 7 | * 8 | * algorithms 9 | * Medium (53.70%) 10 | * Likes: 40 11 | * Dislikes: 21 12 | * Total Accepted: 5.9K 13 | * Total Submissions: 10.9K 14 | * Testcase Example: '8' 15 | * 16 | * Given an integer num, find the closest two integers in absolute difference 17 | * whose product equals num + 1 or num + 2. 18 | * 19 | * Return the two integers in any order. 20 | * 21 | * 22 | * Example 1: 23 | * 24 | * 25 | * Input: num = 8 26 | * Output: [3,3] 27 | * Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 28 | * 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen. 29 | * 30 | * 31 | * Example 2: 32 | * 33 | * 34 | * Input: num = 123 35 | * Output: [5,25] 36 | * 37 | * 38 | * Example 3: 39 | * 40 | * 41 | * Input: num = 999 42 | * Output: [40,25] 43 | * 44 | * 45 | * 46 | * Constraints: 47 | * 48 | * 49 | * 1 <= num <= 10^9 50 | * 51 | * 52 | */ 53 | 54 | // @lc code=start 55 | class Solution { 56 | fun closestDivisors(num: Int): IntArray { 57 | val len = Math.sqrt((num+2).toDouble()).toInt() 58 | for (i in len downTo 1) { 59 | if ((num+1)%i == 0) return intArrayOf(i, (num+1)/i) 60 | if ((num+2)%i == 0) return intArrayOf(i, (num+2)/i) 61 | } 62 | return intArrayOf(0, 0) 63 | } 64 | } 65 | // @lc code=end 66 | 67 | -------------------------------------------------------------------------------- /medium/1375.bulb-switcher-iii.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1375 lang=kotlin 3 | * 4 | * [1375] Bulb Switcher III 5 | * 6 | * https://leetcode.com/problems/bulb-switcher-iii/description/ 7 | * 8 | * algorithms 9 | * Medium (55.96%) 10 | * Likes: 34 11 | * Dislikes: 6 12 | * Total Accepted: 5.4K 13 | * Total Submissions: 9.7K 14 | * Testcase Example: '[2,1,3,5,4]' 15 | * 16 | * There is a room with n bulbs, numbered from 1 to n, arranged in a row from 17 | * left to right. Initially, all the bulbs are turned off. 18 | * 19 | * At moment k (for k from 0 to n - 1), we turn on the light[k] bulb. A bulb 20 | * change color to blue only if it is on and all the previous bulbs (to the 21 | * left) are turned on too. 22 | * 23 | * Return the number of moments in which all turned on bulbs are blue. 24 | * 25 | * 26 | * Example 1: 27 | * 28 | * 29 | * 30 | * 31 | * Input: light = [2,1,3,5,4] 32 | * Output: 3 33 | * Explanation: All bulbs turned on, are blue at the moment 1, 2 and 4. 34 | * 35 | * 36 | * Example 2: 37 | * 38 | * 39 | * Input: light = [3,2,4,1,5] 40 | * Output: 2 41 | * Explanation: All bulbs turned on, are blue at the moment 3, and 4 42 | * (index-0). 43 | * 44 | * 45 | * Example 3: 46 | * 47 | * 48 | * Input: light = [4,1,2,3] 49 | * Output: 1 50 | * Explanation: All bulbs turned on, are blue at the moment 3 (index-0). 51 | * Bulb 4th changes to blue at the moment 3. 52 | * 53 | * 54 | * Example 4: 55 | * 56 | * 57 | * Input: light = [2,1,4,3,6,5] 58 | * Output: 3 59 | * 60 | * 61 | * Example 5: 62 | * 63 | * 64 | * Input: light = [1,2,3,4,5,6] 65 | * Output: 6 66 | * 67 | * 68 | * 69 | * Constraints: 70 | * 71 | * 72 | * n == light.length 73 | * 1 <= n <= 5 * 10^4 74 | * light is a permutation of  [1, 2, ..., n] 75 | * 76 | * 77 | */ 78 | 79 | // @lc code=start 80 | class Solution { 81 | fun numTimesAllBlue(light: IntArray): Int { 82 | var sum = 0 83 | var ans = 0 84 | var mm = IntArray(light.size+1) 85 | for (i in 1 .. light.size) { 86 | sum += i 87 | mm[i] = sum 88 | } 89 | sum = 0 90 | for (i in 0 until light.size) { 91 | sum += light[i] 92 | if (sum == mm[i+1]) ans++ 93 | } 94 | return ans 95 | } 96 | } 97 | // @lc code=end 98 | 99 | -------------------------------------------------------------------------------- /medium/1376.time-needed-to-inform-all-employees.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1376 lang=kotlin 3 | * 4 | * [1376] Time Needed to Inform All Employees 5 | * 6 | * https://leetcode.com/problems/time-needed-to-inform-all-employees/description/ 7 | * 8 | * algorithms 9 | * Medium (54.09%) 10 | * Likes: 42 11 | * Dislikes: 2 12 | * Total Accepted: 4.2K 13 | * Total Submissions: 7.8K 14 | * Testcase Example: '1\n0\n[-1]\n[0]' 15 | * 16 | * A company has n employees with a unique ID for each employee from 0 to n - 17 | * 1. The head of the company has is the one with headID. 18 | * 19 | * Each employee has one direct manager given in the manager array where 20 | * manager[i] is the direct manager of the i-th employee, manager[headID] = -1. 21 | * Also it's guaranteed that the subordination relationships have a tree 22 | * structure. 23 | * 24 | * The head of the company wants to inform all the employees of the company of 25 | * an urgent piece of news. He will inform his direct subordinates and they 26 | * will inform their subordinates and so on until all employees know about the 27 | * urgent news. 28 | * 29 | * The i-th employee needs informTime[i] minutes to inform all of his direct 30 | * subordinates (i.e After informTime[i] minutes, all his direct subordinates 31 | * can start spreading the news). 32 | * 33 | * Return the number of minutes needed to inform all the employees about the 34 | * urgent news. 35 | * 36 | * 37 | * Example 1: 38 | * 39 | * 40 | * Input: n = 1, headID = 0, manager = [-1], informTime = [0] 41 | * Output: 0 42 | * Explanation: The head of the company is the only employee in the company. 43 | * 44 | * 45 | * Example 2: 46 | * 47 | * 48 | * Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = 49 | * [0,0,1,0,0,0] 50 | * Output: 1 51 | * Explanation: The head of the company with id = 2 is the direct manager of 52 | * all the employees in the company and needs 1 minute to inform them all. 53 | * The tree structure of the employees in the company is shown. 54 | * 55 | * 56 | * Example 3: 57 | * 58 | * 59 | * Input: n = 7, headID = 6, manager = [1,2,3,4,5,6,-1], informTime = 60 | * [0,6,5,4,3,2,1] 61 | * Output: 21 62 | * Explanation: The head has id = 6. He will inform employee with id = 5 in 1 63 | * minute. 64 | * The employee with id = 5 will inform the employee with id = 4 in 2 minutes. 65 | * The employee with id = 4 will inform the employee with id = 3 in 3 minutes. 66 | * The employee with id = 3 will inform the employee with id = 2 in 4 minutes. 67 | * The employee with id = 2 will inform the employee with id = 1 in 5 minutes. 68 | * The employee with id = 1 will inform the employee with id = 0 in 6 minutes. 69 | * Needed time = 1 + 2 + 3 + 4 + 5 + 6 = 21. 70 | * 71 | * 72 | * Example 4: 73 | * 74 | * 75 | * Input: n = 15, headID = 0, manager = [-1,0,0,1,1,2,2,3,3,4,4,5,5,6,6], 76 | * informTime = [1,1,1,1,1,1,1,0,0,0,0,0,0,0,0] 77 | * Output: 3 78 | * Explanation: The first minute the head will inform employees 1 and 2. 79 | * The second minute they will inform employees 3, 4, 5 and 6. 80 | * The third minute they will inform the rest of employees. 81 | * 82 | * 83 | * Example 5: 84 | * 85 | * 86 | * Input: n = 4, headID = 2, manager = [3,3,-1,2], informTime = [0,0,162,914] 87 | * Output: 1076 88 | * 89 | * 90 | * 91 | * Constraints: 92 | * 93 | * 94 | * 1 <= n <= 10^5 95 | * 0 <= headID < n 96 | * manager.length == n 97 | * 0 <= manager[i] < n 98 | * manager[headID] == -1 99 | * informTime.length == n 100 | * 0 <= informTime[i] <= 1000 101 | * informTime[i] == 0 if employee i has no subordinates. 102 | * It is guaranteed that all the employees can be informed. 103 | * 104 | */ 105 | 106 | // @lc code=start 107 | class Solution { 108 | fun numOfMinutes(n: Int, headID: Int, manager: IntArray, informTime: IntArray): Int { 109 | var mm = Array(n, {HashSet()}) 110 | var dp = IntArray(n) 111 | for (i in 0 until n) 112 | if (i != headID) mm[manager[i]].add(i) 113 | 114 | fun DP(i: Int): Int { 115 | if (dp[i] > 0) return dp[i] 116 | for (j in mm[i]) { 117 | dp[i] = Math.max(dp[i], DP(j) + informTime[i]) 118 | } 119 | return dp[i] 120 | } 121 | return DP(headID) 122 | } 123 | } 124 | 125 | // @lc code=end 126 | 127 | -------------------------------------------------------------------------------- /medium/1381.design-a-stack-with-increment-operation.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1381 lang=kotlin 3 | * 4 | * [1381] Design a Stack With Increment Operation 5 | * 6 | * https://leetcode.com/problems/design-a-stack-with-increment-operation/description/ 7 | * 8 | * algorithms 9 | * Medium (71.81%) 10 | * Likes: 60 11 | * Dislikes: 2 12 | * Total Accepted: 6.4K 13 | * Total Submissions: 8.9K 14 | * Testcase Example: '["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"]\n' + 15 | '[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]' 16 | * 17 | * Design a stack which supports the following operations. 18 | * 19 | * Implement the CustomStack class: 20 | * 21 | * 22 | * CustomStack(int maxSize) Initializes the object with maxSize which is the 23 | * maximum number of elements in the stack or do nothing if the stack reached 24 | * the maxSize. 25 | * void push(int x) Adds x to the top of the stack if the stack hasn't reached 26 | * the maxSize. 27 | * int pop() Pops and returns the top of stack or -1 if the stack is empty. 28 | * void inc(int k, int val) Increments the bottom k elements of the stack by 29 | * val. If there are less than k elements in the stack, just increment all the 30 | * elements in the stack. 31 | * 32 | * 33 | * 34 | * Example 1: 35 | * 36 | * 37 | * Input 38 | * 39 | * ["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"] 40 | * [[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]] 41 | * Output 42 | * [null,null,null,2,null,null,null,null,null,103,202,201,-1] 43 | * Explanation 44 | * CustomStack customStack = new CustomStack(3); // Stack is Empty [] 45 | * customStack.push(1); // stack becomes [1] 46 | * customStack.push(2); // stack becomes [1, 2] 47 | * customStack.pop(); // return 2 --> Return top of 48 | * the stack 2, stack becomes [1] 49 | * customStack.push(2); // stack becomes [1, 2] 50 | * customStack.push(3); // stack becomes [1, 2, 3] 51 | * customStack.push(4); // stack still [1, 2, 3], 52 | * Don't add another elements as size is 4 53 | * customStack.increment(5, 100); // stack becomes [101, 102, 54 | * 103] 55 | * customStack.increment(2, 100); // stack becomes [201, 202, 56 | * 103] 57 | * customStack.pop(); // return 103 --> Return top 58 | * of the stack 103, stack becomes [201, 202] 59 | * customStack.pop(); // return 202 --> Return top 60 | * of the stack 102, stack becomes [201] 61 | * customStack.pop(); // return 201 --> Return top 62 | * of the stack 101, stack becomes [] 63 | * customStack.pop(); // return -1 --> Stack is 64 | * empty return -1. 65 | * 66 | * 67 | * 68 | * Constraints: 69 | * 70 | * 71 | * 1 <= maxSize <= 1000 72 | * 1 <= x <= 1000 73 | * 1 <= k <= 1000 74 | * 0 <= val <= 100 75 | * At most 1000 calls will be made to each method of increment, push and pop 76 | * each separately. 77 | * 78 | */ 79 | 80 | // @lc code=start 81 | class CustomStack(maxSize: Int) { 82 | private var stk: IntArray 83 | private var size: Int 84 | private var top: Int 85 | 86 | init { 87 | this.size = maxSize 88 | this.top = 0 89 | this.stk = IntArray(maxSize+1) 90 | } 91 | 92 | fun push(x: Int) { 93 | if (top+1 <= size) { 94 | stk[top+1] = x 95 | top++ 96 | } 97 | } 98 | 99 | fun pop(): Int { 100 | if (top == 0) return -1 101 | return stk[top--]; 102 | } 103 | 104 | fun increment(k: Int, `val`: Int) { 105 | for (i in 0 .. Math.min(size, k)) { 106 | stk[i] += `val` 107 | } 108 | } 109 | 110 | } 111 | 112 | /** 113 | * Your CustomStack object will be instantiated and called as such: 114 | * var obj = CustomStack(maxSize) 115 | * obj.push(x) 116 | * var param_2 = obj.pop() 117 | * obj.increment(k,`val`) 118 | */ 119 | // @lc code=end 120 | 121 | -------------------------------------------------------------------------------- /medium/1382.balance-a-binary-search-tree.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1382 lang=kotlin 3 | * 4 | * [1382] Balance a Binary Search Tree 5 | * 6 | * https://leetcode.com/problems/balance-a-binary-search-tree/description/ 7 | * 8 | * algorithms 9 | * Medium (73.89%) 10 | * Likes: 52 11 | * Dislikes: 9 12 | * Total Accepted: 5.2K 13 | * Total Submissions: 7K 14 | * Testcase Example: '[1,null,2,null,3,null,4,null,null]' 15 | * 16 | * Given a binary search tree, return a balanced binary search tree with the 17 | * same node values. 18 | * 19 | * A binary search tree is balanced if and only if the depth of the two 20 | * subtrees of every node never differ by more than 1. 21 | * 22 | * If there is more than one answer, return any of them. 23 | * 24 | * 25 | * Example 1: 26 | * 27 | * 28 | * 29 | * 30 | * Input: root = [1,null,2,null,3,null,4,null,null] 31 | * Output: [2,1,3,null,null,null,4] 32 | * Explanation: This is not the only correct answer, [3,1,4,null,2,null,null] 33 | * is also correct. 34 | * 35 | * 36 | * 37 | * Constraints: 38 | * 39 | * 40 | * The number of nodes in the tree is between 1 and 10^4. 41 | * The tree nodes will have distinct values between 1 and 10^5. 42 | * 43 | */ 44 | 45 | // @lc code=start 46 | /** 47 | * Example: 48 | * var ti = TreeNode(5) 49 | * var v = ti.`val` 50 | * Definition for a binary tree node. 51 | * class TreeNode(var `val`: Int) { 52 | * var left: TreeNode? = null 53 | * var right: TreeNode? = null 54 | * } 55 | */ 56 | class Solution { 57 | private var arr = IntArray(10005) 58 | private var cnt = 0 59 | 60 | fun balanceBST(root: TreeNode?): TreeNode? { 61 | cnt = 0 62 | var head = root 63 | dfs(head) 64 | return sortedArrayToBST(cnt) 65 | } 66 | 67 | fun dfs(root: TreeNode?) { 68 | if (root?.left != null) dfs(root?.left) 69 | arr[cnt++] = root!!.`val` 70 | if (root?.right != null) dfs(root?.right) 71 | } 72 | 73 | fun sortedArrayToBST(start: Int, end: Int): TreeNode? { 74 | if (start > end) return null 75 | val mid = start + (end - start) / 2 76 | var root: TreeNode? = TreeNode(arr[mid]) 77 | root?.left = sortedArrayToBST(start, mid-1) 78 | root?.right = sortedArrayToBST(mid+1, end) 79 | return root 80 | } 81 | 82 | fun sortedArrayToBST(n: Int): TreeNode? { 83 | return sortedArrayToBST(0, n-1) 84 | } 85 | } 86 | // @lc code=end 87 | 88 | -------------------------------------------------------------------------------- /medium/139.word-break.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=139 lang=kotlin 3 | * 4 | * [139] Word Break 5 | * 6 | * https://leetcode.com/problems/word-break/description/ 7 | * 8 | * algorithms 9 | * Medium (36.23%) 10 | * Likes: 2558 11 | * Dislikes: 137 12 | * Total Accepted: 372K 13 | * Total Submissions: 1M 14 | * Testcase Example: '"leetcode"\n["leet","code"]' 15 | * 16 | * Given a non-empty string s and a dictionary wordDict containing a list of 17 | * non-empty words, determine if s can be segmented into a space-separated 18 | * sequence of one or more dictionary words. 19 | * 20 | * Note: 21 | * 22 | * 23 | * The same word in the dictionary may be reused multiple times in the 24 | * segmentation. 25 | * You may assume the dictionary does not contain duplicate words. 26 | * 27 | * 28 | * Example 1: 29 | * 30 | * 31 | * Input: s = "leetcode", wordDict = ["leet", "code"] 32 | * Output: true 33 | * Explanation: Return true because "leetcode" can be segmented as "leet 34 | * code". 35 | * 36 | * 37 | * Example 2: 38 | * 39 | * 40 | * Input: s = "applepenapple", wordDict = ["apple", "pen"] 41 | * Output: true 42 | * Explanation: Return true because "applepenapple" can be segmented as "apple 43 | * pen apple". 44 | * Note that you are allowed to reuse a dictionary word. 45 | * 46 | * 47 | * Example 3: 48 | * 49 | * 50 | * Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] 51 | * Output: false 52 | * 53 | * 54 | */ 55 | class Solution { 56 | fun wordBreak(s: String, wordDict: List): Boolean { 57 | val n = s.length 58 | var dp = BooleanArray(n+1) { false } 59 | dp[0] = true 60 | 61 | for (i in 1 .. n) { 62 | for(j in 0 .. i-1) { 63 | if (dp[j]) { 64 | val str = s.substring(j, i) 65 | if (str in wordDict) { 66 | dp[i] = true 67 | break 68 | } 69 | } 70 | } 71 | } 72 | return dp[n] 73 | } 74 | } 75 | 76 | -------------------------------------------------------------------------------- /medium/1404.number-of-steps-to-reduce-a-number-in-binary-representation-to-one.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1404 lang=kotlin 3 | * 4 | * [1404] Number of Steps to Reduce a Number in Binary Representation to One 5 | * 6 | * https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/description/ 7 | * 8 | * algorithms 9 | * Medium (46.45%) 10 | * Likes: 112 11 | * Dislikes: 16 12 | * Total Accepted: 10.7K 13 | * Total Submissions: 21.6K 14 | * Testcase Example: '"1101"' 15 | * 16 | * Given a number s in their binary representation. Return the number of steps 17 | * to reduce it to 1 under the following rules: 18 | * 19 | * 20 | * 21 | * If the current number is even, you have to divide it by 2. 22 | * 23 | * 24 | * If the current number is odd, you have to add 1 to it. 25 | * 26 | * 27 | * 28 | * It's guaranteed that you can always reach to one for all testcases. 29 | * 30 | * 31 | * Example 1: 32 | * 33 | * 34 | * Input: s = "1101" 35 | * Output: 6 36 | * Explanation: "1101" corressponds to number 13 in their decimal 37 | * representation. 38 | * Step 1) 13 is odd, add 1 and obtain 14.  39 | * Step 2) 14 is even, divide by 2 and obtain 7. 40 | * Step 3) 7 is odd, add 1 and obtain 8. 41 | * Step 4) 8 is even, divide by 2 and obtain 4.  42 | * Step 5) 4 is even, divide by 2 and obtain 2.  43 | * Step 6) 2 is even, divide by 2 and obtain 1.  44 | * 45 | * 46 | * Example 2: 47 | * 48 | * 49 | * Input: s = "10" 50 | * Output: 1 51 | * Explanation: "10" corressponds to number 2 in their decimal representation. 52 | * Step 1) 2 is even, divide by 2 and obtain 1.  53 | * 54 | * 55 | * Example 3: 56 | * 57 | * 58 | * Input: s = "1" 59 | * Output: 0 60 | * 61 | * 62 | * 63 | * Constraints: 64 | * 65 | * 66 | * 1 <= s.length <= 500 67 | * s consists of characters '0' or '1' 68 | * s[0] == '1' 69 | * 70 | * 71 | */ 72 | 73 | // @lc code=start 74 | class Solution { 75 | fun numSteps(s: String): Int { 76 | var res = 0 77 | var cnt = 0 78 | for (i in s.length-1 downTo 1) { 79 | res++ 80 | if (s[i]-'0'+cnt == 1) { 81 | res++ 82 | cnt = 1 83 | } 84 | } 85 | return res+cnt 86 | } 87 | } 88 | // @lc code=end 89 | 90 | -------------------------------------------------------------------------------- /medium/1405.longest-happy-string.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1405 lang=kotlin 3 | * 4 | * [1405] Longest Happy String 5 | * 6 | * https://leetcode.com/problems/longest-happy-string/description/ 7 | * 8 | * algorithms 9 | * Medium (38.06%) 10 | * Likes: 175 11 | * Dislikes: 56 12 | * Total Accepted: 7.2K 13 | * Total Submissions: 15.6K 14 | * Testcase Example: '1\n1\n7' 15 | * 16 | * A string is called happy if it does not have any of the strings 'aaa', 'bbb' 17 | * or 'ccc' as a substring. 18 | * 19 | * Given three integers a, b and c, return any string s, which satisfies 20 | * following conditions: 21 | * 22 | * 23 | * s is happy and longest possible. 24 | * s contains at most a occurrences of the letter 'a', at most b occurrences of 25 | * the letter 'b' and at most c occurrences of the letter 'c'. 26 | * s will only contain 'a', 'b' and 'c' letters. 27 | * 28 | * 29 | * If there is no such string s return the empty string "". 30 | * 31 | * 32 | * Example 1: 33 | * 34 | * 35 | * Input: a = 1, b = 1, c = 7 36 | * Output: "ccaccbcc" 37 | * Explanation: "ccbccacc" would also be a correct answer. 38 | * 39 | * 40 | * Example 2: 41 | * 42 | * 43 | * Input: a = 2, b = 2, c = 1 44 | * Output: "aabbc" 45 | * 46 | * 47 | * Example 3: 48 | * 49 | * 50 | * Input: a = 7, b = 1, c = 0 51 | * Output: "aabaa" 52 | * Explanation: It's the only correct answer in this case. 53 | * 54 | * 55 | * 56 | * Constraints: 57 | * 58 | * 59 | * 0 <= a, b, c <= 100 60 | * a + b + c > 0 61 | * 62 | * 63 | */ 64 | 65 | // @lc code=start 66 | class Solution { 67 | fun longestDiverseString(a: Int, b: Int, c: Int): String { 68 | val total = a + b + c 69 | val f = intArrayOf(a, b, c) 70 | val l = IntArray(3) 71 | var res = "" 72 | for (x in 0 until total) { 73 | for (i in 0 until 3) { 74 | val j = (i+1)%3 75 | val k = (i+2)%3 76 | if ((f[i] >= f[j] && f[i] >= f[k] && l[i] != 2) 77 | || (f[i] > 0 && (l[j] == 2 || l[k] == 2))) { 78 | res += 'a' + i 79 | l[i]++ 80 | f[i]-- 81 | l[j] = 0 82 | l[k] = 0 83 | break 84 | } 85 | } 86 | } 87 | return res 88 | } 89 | } 90 | // @lc code=end 91 | 92 | -------------------------------------------------------------------------------- /medium/1487.making-file-names-unique.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1487 lang=kotlin 3 | * 4 | * [1487] Making File Names Unique 5 | * 6 | * https://leetcode.com/problems/making-file-names-unique/description/ 7 | * 8 | * algorithms 9 | * Medium (24.36%) 10 | * Likes: 58 11 | * Dislikes: 178 12 | * Total Accepted: 5.3K 13 | * Total Submissions: 21.6K 14 | * Testcase Example: '["pes","fifa","gta","pes(2019)"]\r' 15 | * 16 | * Given an array of strings names of size n. You will create n folders in your 17 | * file system such that, at the ith minute, you will create a folder with the 18 | * name names[i]. 19 | * 20 | * Since two files cannot have the same name, if you enter a folder name which 21 | * is previously used, the system will have a suffix addition to its name in 22 | * the form of (k), where, k is the smallest positive integer such that the 23 | * obtained name remains unique. 24 | * 25 | * Return an array of strings of length n where ans[i] is the actual name the 26 | * system will assign to the ith folder when you create it. 27 | * 28 | * 29 | * Example 1: 30 | * 31 | * 32 | * Input: names = ["pes","fifa","gta","pes(2019)"] 33 | * Output: ["pes","fifa","gta","pes(2019)"] 34 | * Explanation: Let's see how the file system creates folder names: 35 | * "pes" --> not assigned before, remains "pes" 36 | * "fifa" --> not assigned before, remains "fifa" 37 | * "gta" --> not assigned before, remains "gta" 38 | * "pes(2019)" --> not assigned before, remains "pes(2019)" 39 | * 40 | * 41 | * Example 2: 42 | * 43 | * 44 | * Input: names = ["gta","gta(1)","gta","avalon"] 45 | * Output: ["gta","gta(1)","gta(2)","avalon"] 46 | * Explanation: Let's see how the file system creates folder names: 47 | * "gta" --> not assigned before, remains "gta" 48 | * "gta(1)" --> not assigned before, remains "gta(1)" 49 | * "gta" --> the name is reserved, system adds (k), since "gta(1)" is also 50 | * reserved, systems put k = 2. it becomes "gta(2)" 51 | * "avalon" --> not assigned before, remains "avalon" 52 | * 53 | * 54 | * Example 3: 55 | * 56 | * 57 | * Input: names = 58 | * ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"] 59 | * Output: ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)"] 60 | * Explanation: When the last folder is created, the smallest positive valid k 61 | * is 4, and it becomes "onepiece(4)". 62 | * 63 | * 64 | * Example 4: 65 | * 66 | * 67 | * Input: names = ["wano","wano","wano","wano"] 68 | * Output: ["wano","wano(1)","wano(2)","wano(3)"] 69 | * Explanation: Just increase the value of k each time you create folder 70 | * "wano". 71 | * 72 | * 73 | * Example 5: 74 | * 75 | * 76 | * Input: names = ["kaido","kaido(1)","kaido","kaido(1)"] 77 | * Output: ["kaido","kaido(1)","kaido(2)","kaido(1)(1)"] 78 | * Explanation: Please note that system adds the suffix (k) to current name 79 | * even it contained the same suffix before. 80 | * 81 | * 82 | * 83 | * Constraints: 84 | * 85 | * 86 | * 1 <= names.length <= 5 * 10^4 87 | * 1 <= names[i].length <= 20 88 | * names[i] consists of lower case English letters, digits and/or round 89 | * brackets. 90 | * 91 | */ 92 | 93 | // @lc code=start 94 | class Solution { 95 | fun getFolderNames(names: Array): Array { 96 | val mm = mutableMapOf() 97 | var res = mutableListOf() 98 | for (name in names) { 99 | if (name !in mm) { 100 | mm.put(name, 0) 101 | res.add(name) 102 | } else { 103 | while (true) { 104 | mm.put(name, mm.getOrDefault(name, 0)+1) 105 | val temp = "${name}(${mm[name]})" 106 | if (temp !in mm) { 107 | res.add(temp) 108 | mm[temp] = 0 109 | break 110 | } 111 | } 112 | } 113 | } 114 | return res.toTypedArray() 115 | } 116 | } 117 | // @lc code=end 118 | 119 | -------------------------------------------------------------------------------- /medium/15.3-sum.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=15 lang=kotlin 3 | * 4 | * [15] 3Sum 5 | * 6 | * https://leetcode.com/problems/3sum/description/ 7 | * 8 | * algorithms 9 | * Medium (23.76%) 10 | * Total Accepted: 521.8K 11 | * Total Submissions: 2.2M 12 | * Testcase Example: '[-1,0,1,2,-1,-4]' 13 | * 14 | * Given an array nums of n integers, are there elements a, b, c in nums such 15 | * that a + b + c = 0? Find all unique triplets in the array which gives the 16 | * sum of zero. 17 | * 18 | * Note: 19 | * 20 | * The solution set must not contain duplicate triplets. 21 | * 22 | * Example: 23 | * 24 | * 25 | * Given array nums = [-1, 0, 1, 2, -1, -4], 26 | * 27 | * A solution set is: 28 | * [ 29 | * ⁠ [-1, 0, 1], 30 | * ⁠ [-1, -1, 2] 31 | * ] 32 | * 33 | * 34 | */ 35 | class Solution { 36 | fun threeSum(nums: IntArray): List> { 37 | nums.sort() 38 | val res = mutableListOf>() 39 | var x: Int 40 | var y: Int 41 | for (i in 0 until nums.size-2) { 42 | if (nums[i] > 0) break 43 | if (i > 0 && nums[i] == nums[i-1]) continue 44 | x = i+1 45 | y = nums.size-1 46 | while (x < y) { 47 | val temp = nums[x]+nums[y]+nums[i] 48 | if (temp == 0) { 49 | res.add(listOf(nums[i], nums[x], nums[y])) 50 | 51 | // 去重操作 52 | while (x < y && nums[x] == nums[x+1]) x++ 53 | while (x < y && nums[y] == nums[y-1]) y-- 54 | x++ 55 | y-- 56 | } else if (temp > 0) { 57 | y-- 58 | } else { 59 | x++ 60 | } 61 | } 62 | } 63 | return res 64 | } 65 | } 66 | // fun main(args: Array) { 67 | // val a = Solution().threeSum(intArrayOf(-1, 0, 1, 2, -1, -4)) 68 | // a.forEach { 69 | // it.forEach { i -> 70 | // print("$i ") 71 | // } 72 | // println("") 73 | // } 74 | // } 75 | -------------------------------------------------------------------------------- /medium/1551.minimum-operations-to-make-array-equal.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1551 lang=kotlin 3 | * 4 | * [1551] Minimum Operations to Make Array Equal 5 | * 6 | * https://leetcode.com/problems/minimum-operations-to-make-array-equal/description/ 7 | * 8 | * algorithms 9 | * Medium (78.63%) 10 | * Likes: 81 11 | * Dislikes: 14 12 | * Total Accepted: 10.4K 13 | * Total Submissions: 13.3K 14 | * Testcase Example: '3' 15 | * 16 | * You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid 17 | * values of i (i.e. 0 <= i < n). 18 | * 19 | * In one operation, you can select two indices x and y where 0 <= x, y < n and 20 | * subtract 1 from arr[x] and add 1 to arr[y] (i.e. perform arr[x] -=1 and 21 | * arr[y] += 1). The goal is to make all the elements of the array equal. It is 22 | * guaranteed that all the elements of the array can be made equal using some 23 | * operations. 24 | * 25 | * Given an integer n, the length of the array. Return the minimum number of 26 | * operations needed to make all the elements of arr equal. 27 | * 28 | * 29 | * Example 1: 30 | * 31 | * 32 | * Input: n = 3 33 | * Output: 2 34 | * Explanation: arr = [1, 3, 5] 35 | * First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4] 36 | * In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 37 | * 3]. 38 | * 39 | * 40 | * Example 2: 41 | * 42 | * 43 | * Input: n = 6 44 | * Output: 9 45 | * 46 | * 47 | * 48 | * Constraints: 49 | * 50 | * 51 | * 1 <= n <= 10^4 52 | * 53 | */ 54 | 55 | // @lc code=start 56 | class Solution { 57 | fun minOperations(n: Int): Int { 58 | var ans = 0 59 | for (i in 0 until n/2) { 60 | ans += n-2*i-1 61 | } 62 | return ans 63 | } 64 | } 65 | // @lc code=end 66 | 67 | -------------------------------------------------------------------------------- /medium/1552.magnetic-force-between-two-balls.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1552 lang=kotlin 3 | * 4 | * [1552] Magnetic Force Between Two Balls 5 | * 6 | * https://leetcode.com/problems/magnetic-force-between-two-balls/description/ 7 | * 8 | * algorithms 9 | * Medium (44.27%) 10 | * Likes: 239 11 | * Dislikes: 27 12 | * Total Accepted: 6.3K 13 | * Total Submissions: 14.1K 14 | * Testcase Example: '[1,2,3,4,7]\n3' 15 | * 16 | * In universe Earth C-137, Rick discovered a special form of magnetic force 17 | * between two balls if they are put in his new invented basket. Rick has n 18 | * empty baskets, the i^th basket is at position[i], Morty has m balls and 19 | * needs to distribute the balls into the baskets such that the minimum 20 | * magnetic force between any two balls is maximum. 21 | * 22 | * Rick stated that magnetic force between two different balls at positions x 23 | * and y is |x - y|. 24 | * 25 | * Given the integer array position and the integer m. Return the required 26 | * force. 27 | * 28 | * 29 | * Example 1: 30 | * 31 | * 32 | * Input: position = [1,2,3,4,7], m = 3 33 | * Output: 3 34 | * Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the 35 | * magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 36 | * 3. We cannot achieve a larger minimum magnetic force than 3. 37 | * 38 | * 39 | * Example 2: 40 | * 41 | * 42 | * Input: position = [5,4,3,2,1,1000000000], m = 2 43 | * Output: 999999999 44 | * Explanation: We can use baskets 1 and 1000000000. 45 | * 46 | * 47 | * 48 | * Constraints: 49 | * 50 | * 51 | * n == position.length 52 | * 2 <= n <= 10^5 53 | * 1 <= position[i] <= 10^9 54 | * All integers in position are distinct. 55 | * 2 <= m <= position.length 56 | * 57 | * 58 | */ 59 | 60 | // @lc code=start 61 | class Solution { 62 | fun ok(position: IntArray, m: Int, mid: Int): Boolean { 63 | var res = 1 64 | val n = position.size 65 | var last = position[0] 66 | for (i in 1 until n) { 67 | if (position[i]- last >= mid) { 68 | res++ 69 | last = position[i] 70 | } 71 | } 72 | return res >= m 73 | } 74 | fun maxDistance(position: IntArray, m: Int): Int { 75 | val pos = position.sorted().toIntArray() 76 | var r = (pos[pos.size - 1] - pos[0]) / (m-1) 77 | var l = 1 78 | var ans = 1 79 | while (l <= r) { 80 | val mid = l+(r-l)/2 81 | if (ok(pos, m, mid)) { 82 | ans = mid 83 | l = mid+1 84 | } else { 85 | r = mid-1 86 | } 87 | } 88 | return ans 89 | } 90 | } 91 | // @lc code=end 92 | 93 | -------------------------------------------------------------------------------- /medium/1583.count-unhappy-friends.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1583 lang=kotlin 3 | * 4 | * [1583] Count Unhappy Friends 5 | * 6 | * https://leetcode.com/problems/count-unhappy-friends/description/ 7 | * 8 | * algorithms 9 | * Medium (51.45%) 10 | * Likes: 48 11 | * Dislikes: 219 12 | * Total Accepted: 5.7K 13 | * Total Submissions: 11K 14 | * Testcase Example: '4\n[[1,2,3],[3,2,0],[3,1,0],[1,2,0]]\n[[0,1],[2,3]]' 15 | * 16 | * You are given a list of preferences for n friends, where n is always even. 17 | * 18 | * For each person i, preferences[i] contains a list of friends sorted in the 19 | * order of preference. In other words, a friend earlier in the list is more 20 | * preferred than a friend later in the list. Friends in each list are denoted 21 | * by integers from 0 to n-1. 22 | * 23 | * All the friends are divided into pairs. The pairings are given in a list 24 | * pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is 25 | * paired with xi. 26 | * 27 | * However, this pairing may cause some of the friends to be unhappy. A friend 28 | * x is unhappy if x is paired with y and there exists a friend u who is paired 29 | * with v but: 30 | * 31 | * 32 | * x prefers u over y, and 33 | * u prefers x over v. 34 | * 35 | * 36 | * Return the number of unhappy friends. 37 | * 38 | * 39 | * Example 1: 40 | * 41 | * 42 | * Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], 43 | * pairs = [[0, 1], [2, 3]] 44 | * Output: 2 45 | * Explanation: 46 | * Friend 1 is unhappy because: 47 | * - 1 is paired with 0 but prefers 3 over 0, and 48 | * - 3 prefers 1 over 2. 49 | * Friend 3 is unhappy because: 50 | * - 3 is paired with 2 but prefers 1 over 2, and 51 | * - 1 prefers 3 over 0. 52 | * Friends 0 and 2 are happy. 53 | * 54 | * 55 | * Example 2: 56 | * 57 | * 58 | * Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]] 59 | * Output: 0 60 | * Explanation: Both friends 0 and 1 are happy. 61 | * 62 | * 63 | * Example 3: 64 | * 65 | * 66 | * Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], 67 | * pairs = [[1, 3], [0, 2]] 68 | * Output: 4 69 | * 70 | * 71 | * 72 | * Constraints: 73 | * 74 | * 75 | * 2 <= n <= 500 76 | * n is even. 77 | * preferences.length == n 78 | * preferences[i].length == n - 1 79 | * 0 <= preferences[i][j] <= n - 1 80 | * preferences[i] does not contain i. 81 | * All values in preferences[i] are unique. 82 | * pairs.length == n/2 83 | * pairs[i].length == 2 84 | * xi != yi 85 | * 0 <= xi, yi <= n - 1 86 | * Each person is contained in exactly one pair. 87 | * 88 | * 89 | */ 90 | 91 | // @lc code=start 92 | class Solution { 93 | fun unhappyFriends(n: Int, preferences: Array, pairs: Array): Int { 94 | var matrix = Array(n){ IntArray(n) } 95 | for (i in 0 until n) { 96 | for (j in 0 until n-1) { 97 | matrix[i][preferences[i][j]] = j 98 | } 99 | } 100 | 101 | var unhappy = BooleanArray(n) 102 | var i = 0 103 | var j = 0 104 | while (i+i < n) { 105 | val x = pairs[i][0] 106 | val y = pairs[i][1] 107 | j = 0 108 | while (j+j < n) { 109 | 110 | if (i == j) { 111 | j++ 112 | continue 113 | } 114 | 115 | val u = pairs[j][0] 116 | val v = pairs[j][1] 117 | 118 | if ((matrix[x][u] < matrix[x][y] && matrix[u][x] < matrix[u][v]) 119 | || (matrix[x][v] < matrix[x][y] && matrix[v][x] < matrix[v][u])) unhappy[x] = true; 120 | if ((matrix[y][u] < matrix[y][x] && matrix[u][y] < matrix[u][v]) 121 | || (matrix[y][v] < matrix[y][x] && matrix[v][y] < matrix[v][u])) unhappy[y] = true; 122 | 123 | j++ 124 | } 125 | i++ 126 | } 127 | var ans = 0 128 | for (i in 0 until n) 129 | if (unhappy[i]) ans++ 130 | return ans 131 | } 132 | } 133 | // @lc code=end 134 | 135 | -------------------------------------------------------------------------------- /medium/1584.min-cost-to-connect-all-points.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | import kotlin.math.abs 3 | 4 | //You are given an array points representing integer coordinates of some points 5 | //on a 2D-plane, where points[i] = [xi, yi]. 6 | // 7 | // The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan dist 8 | //ance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value 9 | // of val. 10 | // 11 | // Return the minimum cost to make all points connected. All points are connecte 12 | //d if there is exactly one simple path between any two points. 13 | // 14 | // 15 | // Example 1: 16 | // 17 | // 18 | // 19 | // 20 | //Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]] 21 | //Output: 20 22 | //Explanation: 23 | // 24 | //We can connect the points as shown above to get the minimum cost of 20. 25 | //Notice that there is a unique path between every pair of points. 26 | // 27 | // 28 | // Example 2: 29 | // 30 | // 31 | //Input: points = [[3,12],[-2,5],[-4,1]] 32 | //Output: 18 33 | // 34 | // 35 | // Example 3: 36 | // 37 | // 38 | //Input: points = [[0,0],[1,1],[1,0],[-1,1]] 39 | //Output: 4 40 | // 41 | // 42 | // Example 4: 43 | // 44 | // 45 | //Input: points = [[-1000000,-1000000],[1000000,1000000]] 46 | //Output: 4000000 47 | // 48 | // 49 | // Example 5: 50 | // 51 | // 52 | //Input: points = [[0,0]] 53 | //Output: 0 54 | // 55 | // 56 | // 57 | // Constraints: 58 | // 59 | // 60 | // 1 <= points.length <= 1000 61 | // -106 <= xi, yi <= 106 62 | // All pairs (xi, yi) are distinct. 63 | // 64 | // Related Topics Union Find 65 | // 👍 199 👎 20 66 | 67 | 68 | //leetcode submit region begin(Prohibit modification and deletion) 69 | class Solution { 70 | data class Node(var u: Int, var v: Int, var w: Int) 71 | 72 | companion object { 73 | val p = IntArray(1005) 74 | 75 | fun find(x: Int): Int { 76 | if (x != p[x]) p[x] = find(p[x]) 77 | return p[x] 78 | } 79 | 80 | } 81 | 82 | fun minCostConnectPoints(points: Array): Int { 83 | val n = points.size 84 | val q = PriorityQueue { x, y -> x.w - y.w } 85 | for (i in 0 until n) { 86 | for (j in i+1 until n) { 87 | q.add(Node(i, j, Math.abs(points[i][0]-points[j][0]) +Math.abs(points[i][1]-points[j][1]))) 88 | } 89 | } 90 | for (i in 0 until n) p[i] = i 91 | var res = 0 92 | 93 | while(!q.isEmpty()) { 94 | val (x, y, w) = q.poll() 95 | val u = find(x) 96 | val v = find(y) 97 | if (u != v) { 98 | res += w 99 | p[u] = v 100 | } 101 | } 102 | return res 103 | } 104 | } 105 | //leetcode submit region end(Prohibit modification and deletion) 106 | -------------------------------------------------------------------------------- /medium/1589.maximum-sum-obtained-of-any-permutation.kt: -------------------------------------------------------------------------------- 1 | //We have an array of integers, nums, and an array of requests where requests[i] 2 | // = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[start 3 | //i + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed. 4 | // 5 | // 6 | // Return the maximum total sum of all requests among all permutations of nums. 7 | // 8 | // 9 | // Since the answer may be too large, return it modulo 109 + 7. 10 | // 11 | // 12 | // Example 1: 13 | // 14 | // 15 | //Input: nums = [1,2,3,4,5], requests = [[1,3],[0,1]] 16 | //Output: 19 17 | //Explanation: One permutation of nums is [2,1,3,4,5] with the following result: 18 | // 19 | //requests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8 20 | //requests[1] -> nums[0] + nums[1] = 2 + 1 = 3 21 | //Total sum: 8 + 3 = 11. 22 | //A permutation with a higher total sum is [3,5,4,2,1] with the following result 23 | //: 24 | //requests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11 25 | //requests[1] -> nums[0] + nums[1] = 3 + 5 = 8 26 | //Total sum: 11 + 8 = 19, which is the best that you can do. 27 | // 28 | // 29 | // Example 2: 30 | // 31 | // 32 | //Input: nums = [1,2,3,4,5,6], requests = [[0,1]] 33 | //Output: 11 34 | //Explanation: A permutation with the max total sum is [6,5,4,3,2,1] with reques 35 | //t sums [11]. 36 | // 37 | // Example 3: 38 | // 39 | // 40 | //Input: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]] 41 | //Output: 47 42 | //Explanation: A permutation with the max total sum is [4,10,5,3,2,1] with reque 43 | //st sums [19,18,10]. 44 | // 45 | // 46 | // Constraints: 47 | // 48 | // 49 | // n == nums.length 50 | // 1 <= n <= 105 51 | // 0 <= nums[i] <= 105 52 | // 1 <= requests.length <= 105 53 | // requests[i].length == 2 54 | // 0 <= starti <= endi < n 55 | // 56 | // Related Topics Greedy 57 | // 👍 182 👎 16 58 | 59 | 60 | //leetcode submit region begin(Prohibit modification and deletion) 61 | class Solution { 62 | fun maxSumRangeQuery(nums: IntArray, requests: Array): Int { 63 | val n = nums.size 64 | val mod = 1000000007L 65 | var count = IntArray(n) 66 | for (r in requests) { 67 | count[r[0]]++ 68 | if (r[1]+1 < n) { 69 | count[r[1]+1]-- 70 | } 71 | } 72 | for (i in 1 until n) count[i] += count[i-1] 73 | nums.sort() 74 | count.sort() 75 | 76 | var res = 0L 77 | for (i in 0 until n) res = (res + nums[i].toLong() * count[i]) % mod 78 | return res.toInt() 79 | } 80 | } 81 | //leetcode submit region end(Prohibit modification and deletion) 82 | -------------------------------------------------------------------------------- /medium/16.3-sum-closest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=16 lang=kotlin 3 | * 4 | * [16] 3Sum Closest 5 | * 6 | * https://leetcode.com/problems/3sum-closest/description/ 7 | * 8 | * algorithms 9 | * Medium (43.58%) 10 | * Likes: 1138 11 | * Dislikes: 82 12 | * Total Accepted: 353.1K 13 | * Total Submissions: 771.6K 14 | * Testcase Example: '[-1,2,1,-4]\n1' 15 | * 16 | * Given an array nums of n integers and an integer target, find three integers 17 | * in nums such that the sum is closest to target. Return the sum of the three 18 | * integers. You may assume that each input would have exactly one solution. 19 | * 20 | * Example: 21 | * 22 | * 23 | * Given array nums = [-1, 2, 1, -4], and target = 1. 24 | * 25 | * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 26 | * 27 | * 28 | */ 29 | class Solution { 30 | fun threeSumClosest(nums: IntArray, target: Int): Int { 31 | nums.sort() 32 | var mina = Int.MAX_VALUE 33 | var closedSum = 0 34 | 35 | for (i in 0 until nums.size-2) { 36 | var left = i+1 37 | var right = nums.size-1 38 | while (left < right) { 39 | var sum = nums[i]+nums[left]+nums[right] 40 | var diff = Math.abs(sum-target) 41 | 42 | if (diff < mina) { 43 | closedSum = sum 44 | mina = diff 45 | } 46 | 47 | if (sum < target) { 48 | left++ 49 | } else if (sum > target) { 50 | right-- 51 | } else { 52 | return sum 53 | } 54 | } 55 | } 56 | return closedSum 57 | } 58 | } 59 | 60 | -------------------------------------------------------------------------------- /medium/162.find-peak-element.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=162 lang=kotlin 3 | * 4 | * [162] Find Peak Element 5 | * 6 | * https://leetcode.com/problems/find-peak-element/description/ 7 | * 8 | * algorithms 9 | * Medium (43.02%) 10 | * Likes: 1656 11 | * Dislikes: 2015 12 | * Total Accepted: 353.7K 13 | * Total Submissions: 821.3K 14 | * Testcase Example: '[1,2,3,1]' 15 | * 16 | * A peak element is an element that is greater than its neighbors. 17 | * 18 | * Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element 19 | * and return its index. 20 | * 21 | * The array may contain multiple peaks, in that case return the index to any 22 | * one of the peaks is fine. 23 | * 24 | * You may imagine that nums[-1] = nums[n] = -∞. 25 | * 26 | * Example 1: 27 | * 28 | * 29 | * Input: nums = [1,2,3,1] 30 | * Output: 2 31 | * Explanation: 3 is a peak element and your function should return the index 32 | * number 2. 33 | * 34 | * Example 2: 35 | * 36 | * 37 | * Input: nums = [1,2,1,3,5,6,4] 38 | * Output: 1 or 5 39 | * Explanation: Your function can return either index number 1 where the peak 40 | * element is 2, 41 | * or index number 5 where the peak element is 6. 42 | * 43 | * 44 | * Follow up: Your solution should be in logarithmic complexity. 45 | * 46 | */ 47 | 48 | // @lc code=start 49 | class Solution { 50 | fun findPeakElement(nums: IntArray): Int { 51 | var left = 0 52 | var right = nums.size - 1 53 | 54 | while (left < right) { 55 | val mid = left + (right - left) / 2 56 | if (nums[mid] < nums[mid+1]) left = mid + 1 57 | else right = mid 58 | } 59 | return right 60 | } 61 | } 62 | // @lc code=end 63 | 64 | -------------------------------------------------------------------------------- /medium/17.letter-combinations-of-a-phone-number.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=17 lang=kotlin 3 | * 4 | * [17] Letter Combinations of a Phone Number 5 | * 6 | * https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/ 7 | * 8 | * algorithms 9 | * Medium (41.07%) 10 | * Likes: 2236 11 | * Dislikes: 301 12 | * Total Accepted: 399.4K 13 | * Total Submissions: 954.7K 14 | * Testcase Example: '"23"' 15 | * 16 | * Given a string containing digits from 2-9 inclusive, return all possible 17 | * letter combinations that the number could represent. 18 | * 19 | * A mapping of digit to letters (just like on the telephone buttons) is given 20 | * below. Note that 1 does not map to any letters. 21 | * 22 | * 23 | * 24 | * Example: 25 | * 26 | * 27 | * Input: "23" 28 | * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 29 | * 30 | * 31 | * Note: 32 | * 33 | * Although the above answer is in lexicographical order, your answer could be 34 | * in any order you want. 35 | * 36 | */ 37 | import java.util.LinkedList 38 | class Solution { 39 | private val mm = mapOf('2' to "abc", '3' to "def", '4' to "ghi", '5' to "jkl", '6' to "mno", '7' to "pqrs", '8' to "tuv", '9' to "wxyz") 40 | 41 | fun letterCombinations(digits: String): List { 42 | var res = mutableListOf() 43 | if (digits.length == 0) return res 44 | var word: String = "" 45 | 46 | fun dfs(cur: Int) { 47 | if (cur >= digits.length) { 48 | res.add(word) 49 | return ; 50 | } 51 | for (i in mm[digits[cur]]!!) { 52 | word += i 53 | dfs(cur+1) 54 | word = word.substring(0, word.length-1) 55 | } 56 | } 57 | dfs(0) 58 | return res 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /medium/18.4-sum.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=18 lang=kotlin 3 | * 4 | * [18] 4Sum 5 | * 6 | * https://leetcode.com/problems/4sum/description/ 7 | * 8 | * algorithms 9 | * Medium (31.15%) 10 | * Likes: 1202 11 | * Dislikes: 238 12 | * Total Accepted: 252.9K 13 | * Total Submissions: 810.5K 14 | * Testcase Example: '[1,0,-1,0,-2,2]\n0' 15 | * 16 | * Given an array nums of n integers and an integer target, are there elements 17 | * a, b, c, and d in nums such that a + b + c + d = target? Find all unique 18 | * quadruplets in the array which gives the sum of target. 19 | * 20 | * Note: 21 | * 22 | * The solution set must not contain duplicate quadruplets. 23 | * 24 | * Example: 25 | * 26 | * 27 | * Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. 28 | * 29 | * A solution set is: 30 | * [ 31 | * ⁠ [-1, 0, 0, 1], 32 | * ⁠ [-2, -1, 1, 2], 33 | * ⁠ [-2, 0, 0, 2] 34 | * ] 35 | * 36 | * 37 | */ 38 | class Solution { 39 | // val res = mutableListOf >() 40 | // var vis = BooleanArray(1005, {false}) 41 | // var visb = BooleanArray(10005, {false}) 42 | // var b = IntArray(1005) 43 | // var id = IntArray(1005) 44 | 45 | fun fourSum(nums: IntArray, target: Int): List> { 46 | var res = mutableListOf>() 47 | 48 | if (nums.isEmpty()) return res 49 | 50 | nums.sort() 51 | val n = nums.size.toInt() 52 | var i = 0 53 | var j = 0 54 | while (i < n) { 55 | j = i+1 56 | while (j < n) { 57 | var left = j+1 58 | var right = n-1 59 | 60 | while (left < right) { 61 | val cursum = nums[i]+nums[j]+nums[left]+nums[right] 62 | if (cursum == target) { 63 | res.add(mutableListOf(nums[i], nums[j], nums[left], nums[right])) 64 | 65 | while (left < right && nums[left] == nums[left+1]) ++left 66 | while (left < right && nums[right] == nums[right-1]) --right 67 | ++left 68 | --right 69 | } else if (cursum < target) { 70 | ++left 71 | } else { 72 | --right 73 | } 74 | } 75 | while (j+1 < n && nums[j] == nums[j+1]) ++j 76 | ++j 77 | } 78 | while (i+1 < n && nums[i] == nums[i+1]) ++i 79 | ++i 80 | } 81 | return res 82 | } 83 | 84 | // fun dfs(nums: IntArray, step: Int, n: Int, t: Int) { 85 | // if (step > 3) { 86 | // val sum = b[0]+b[1]+b[2]+b[3] 87 | // val ok = id[0]+id[1]+id[2]+id[3] 88 | // if (sum == t && visb[ok] == false) { 89 | // visb[ok] = true 90 | // // b.sort(0, 3) 91 | // res.add(mutableListOf(b[0], b[1], b[2], b[3])) 92 | // } 93 | // return 94 | // } 95 | // for (i in 0 until n) { 96 | // if (!vis[i]) { 97 | // b[step] = nums[i] 98 | // id[step] = i 99 | // vis[i] = true 100 | // dfs(nums, step+1, n, t) 101 | // vis[i] = false 102 | // } 103 | // } 104 | // } 105 | } 106 | // fun main(args: Array) { 107 | // val s = Solution().fourSum(intArrayOf(-3,-2,-1,0,0,1,2,3), 0) 108 | // for (i in s) 109 | // println(i) 110 | // } 111 | 112 | -------------------------------------------------------------------------------- /medium/19.remove-nth-node-from-end-of-list.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=19 lang=kotlin 3 | * 4 | * [19] Remove Nth Node From End of List 5 | * 6 | * https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/ 7 | * 8 | * algorithms 9 | * Medium (34.51%) 10 | * Likes: 2187 11 | * Dislikes: 161 12 | * Total Accepted: 459K 13 | * Total Submissions: 1.3M 14 | * Testcase Example: '[1,2,3,4,5]\n2' 15 | * 16 | * Given a linked list, remove the n-th node from the end of list and return 17 | * its head. 18 | * 19 | * Example: 20 | * 21 | * 22 | * Given linked list: 1->2->3->4->5, and n = 2. 23 | * 24 | * After removing the second node from the end, the linked list becomes 25 | * 1->2->3->5. 26 | * 27 | * 28 | * Note: 29 | * 30 | * Given n will always be valid. 31 | * 32 | * Follow up: 33 | * 34 | * Could you do this in one pass? 35 | * 36 | */ 37 | 38 | // @lc code=start 39 | /** 40 | * Example: 41 | * var li = ListNode(5) 42 | * var v = li.`val` 43 | * Definition for singly-linked list. 44 | * class ListNode(var `val`: Int) { 45 | * var next: ListNode? = null 46 | * } 47 | */ 48 | 49 | class Solution { 50 | // 快慢指针 51 | fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? { 52 | val temp: ListNode? = ListNode(0).apply { next = head } 53 | 54 | var fast = temp 55 | var slow = temp 56 | 57 | for (i in 0 .. n) fast = fast?.next 58 | 59 | while (fast != null) { 60 | fast = fast?.next 61 | slow = slow?.next 62 | } 63 | slow?.next = slow?.next?.next 64 | return temp?.next 65 | } 66 | } 67 | // @lc code=end 68 | 69 | -------------------------------------------------------------------------------- /medium/207.course-schedule.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=207 lang=kotlin 3 | * 4 | * [207] Course Schedule 5 | * 6 | * https://leetcode.com/problems/course-schedule/description/ 7 | * 8 | * algorithms 9 | * Medium (38.86%) 10 | * Likes: 2103 11 | * Dislikes: 98 12 | * Total Accepted: 247.1K 13 | * Total Submissions: 634.4K 14 | * Testcase Example: '2\n[[1,0]]' 15 | * 16 | * There are a total of n courses you have to take, labeled from 0 to n-1. 17 | * 18 | * Some courses may have prerequisites, for example to take course 0 you have 19 | * to first take course 1, which is expressed as a pair: [0,1] 20 | * 21 | * Given the total number of courses and a list of prerequisite pairs, is it 22 | * possible for you to finish all courses? 23 | * 24 | * Example 1: 25 | * 26 | * 27 | * Input: 2, [[1,0]] 28 | * Output: true 29 | * Explanation: There are a total of 2 courses to take. 30 | * To take course 1 you should have finished course 0. So it is possible. 31 | * 32 | * Example 2: 33 | * 34 | * 35 | * Input: 2, [[1,0],[0,1]] 36 | * Output: false 37 | * Explanation: There are a total of 2 courses to take. 38 | * To take course 1 you should have finished course 0, and to take course 0 you 39 | * should 40 | * also have finished course 1. So it is impossible. 41 | * 42 | * 43 | * Note: 44 | * 45 | * 46 | * The input prerequisites is a graph represented by a list of edges, not 47 | * adjacency matrices. Read more about how a graph is represented. 48 | * You may assume that there are no duplicate edges in the input 49 | * prerequisites. 50 | * 51 | * 52 | */ 53 | class Solution { 54 | // 拓扑排序 55 | fun canFinish(numCourses: Int, prerequisites: Array): Boolean { 56 | var q = IntArray(numCourses+1) 57 | var edges = Array>(numCourses+1) {mutableListOf()} 58 | 59 | 60 | var ind = IntArray(numCourses+1) 61 | 62 | var head = 0 63 | var tail = 0 64 | 65 | for (i in prerequisites) { 66 | ind[i[1]]++ 67 | edges[i[0]].add(i[1]) 68 | } 69 | var cnt = 0 70 | 71 | for (i in 0 until numCourses) 72 | if (ind[i] == 0) { 73 | q[tail++] = i 74 | cnt++ 75 | } 76 | 77 | while (head < tail) { 78 | var top = q[head] 79 | 80 | for (i in edges[top]) { 81 | ind[i]-- 82 | if (ind[i] == 0) { 83 | cnt++ 84 | q[tail++] = i 85 | } 86 | } 87 | head++ 88 | } 89 | return cnt == numCourses 90 | } 91 | } 92 | 93 | -------------------------------------------------------------------------------- /medium/210.course-schedule-ii.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=210 lang=kotlin 3 | * 4 | * [210] Course Schedule II 5 | * 6 | * https://leetcode.com/problems/course-schedule-ii/description/ 7 | * 8 | * algorithms 9 | * Medium (35.89%) 10 | * Likes: 1175 11 | * Dislikes: 82 12 | * Total Accepted: 169K 13 | * Total Submissions: 468.5K 14 | * Testcase Example: '2\n[[1,0]]' 15 | * 16 | * There are a total of n courses you have to take, labeled from 0 to n-1. 17 | * 18 | * Some courses may have prerequisites, for example to take course 0 you have 19 | * to first take course 1, which is expressed as a pair: [0,1] 20 | * 21 | * Given the total number of courses and a list of prerequisite pairs, return 22 | * the ordering of courses you should take to finish all courses. 23 | * 24 | * There may be multiple correct orders, you just need to return one of them. 25 | * If it is impossible to finish all courses, return an empty array. 26 | * 27 | * Example 1: 28 | * 29 | * 30 | * Input: 2, [[1,0]] 31 | * Output: [0,1] 32 | * Explanation: There are a total of 2 courses to take. To take course 1 you 33 | * should have finished 34 | * course 0. So the correct course order is [0,1] . 35 | * 36 | * Example 2: 37 | * 38 | * 39 | * Input: 4, [[1,0],[2,0],[3,1],[3,2]] 40 | * Output: [0,1,2,3] or [0,2,1,3] 41 | * Explanation: There are a total of 4 courses to take. To take course 3 you 42 | * should have finished both 43 | * ⁠ courses 1 and 2. Both courses 1 and 2 should be taken after you 44 | * finished course 0. 45 | * So one correct course order is [0,1,2,3]. Another correct ordering is 46 | * [0,2,1,3] . 47 | * 48 | * Note: 49 | * 50 | * 51 | * The input prerequisites is a graph represented by a list of edges, not 52 | * adjacency matrices. Read more about how a graph is represented. 53 | * You may assume that there are no duplicate edges in the input 54 | * prerequisites. 55 | * 56 | * 57 | */ 58 | class Solution { 59 | fun findOrder(numCourses: Int, prerequisites: Array): IntArray { 60 | var q = IntArray(numCourses+1) 61 | var edges = Array>(numCourses+1) {mutableListOf()} 62 | 63 | 64 | var ind = IntArray(numCourses+1) 65 | 66 | var head = 0 67 | var tail = 0 68 | 69 | for (i in prerequisites) { 70 | ind[i[0]]++ 71 | edges[i[1]].add(i[0]) 72 | } 73 | var cnt = 0 74 | var ans = IntArray(numCourses) 75 | var res = 0 76 | 77 | for (i in 0 until numCourses) 78 | if (ind[i] == 0) { 79 | ans[res++] = i 80 | q[tail++] = i 81 | cnt++ 82 | } 83 | 84 | while (head < tail) { 85 | var top = q[head] 86 | 87 | for (i in edges[top]) { 88 | ind[i]-- 89 | if (ind[i] == 0) { 90 | ans[res++] = i 91 | cnt++ 92 | q[tail++] = i 93 | } 94 | } 95 | head++ 96 | } 97 | if (cnt == numCourses) return ans 98 | return intArrayOf() 99 | } 100 | } 101 | 102 | -------------------------------------------------------------------------------- /medium/213.house-robber-ii.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=213 lang=kotlin 3 | * 4 | * [213] House Robber II 5 | * 6 | * https://leetcode.com/problems/house-robber-ii/description/ 7 | * 8 | * algorithms 9 | * Medium (35.52%) 10 | * Likes: 1013 11 | * Dislikes: 35 12 | * Total Accepted: 127.2K 13 | * Total Submissions: 357.9K 14 | * Testcase Example: '[2,3,2]' 15 | * 16 | * You are a professional robber planning to rob houses along a street. Each 17 | * house has a certain amount of money stashed. All houses at this place are 18 | * arranged in a circle. That means the first house is the neighbor of the last 19 | * one. Meanwhile, adjacent houses have security system connected and it will 20 | * automatically contact the police if two adjacent houses were broken into on 21 | * the same night. 22 | * 23 | * Given a list of non-negative integers representing the amount of money of 24 | * each house, determine the maximum amount of money you can rob tonight 25 | * without alerting the police. 26 | * 27 | * Example 1: 28 | * 29 | * 30 | * Input: [2,3,2] 31 | * Output: 3 32 | * Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money 33 | * = 2), 34 | * because they are adjacent houses. 35 | * 36 | * 37 | * Example 2: 38 | * 39 | * 40 | * Input: [1,2,3,1] 41 | * Output: 4 42 | * Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 43 | * 3). 44 | * Total amount you can rob = 1 + 3 = 4. 45 | * 46 | */ 47 | class Solution { 48 | fun rob(nums: IntArray): Int { 49 | if (nums.size == 1) return nums[0] 50 | return Math.max(pre_rob(nums.sliceArray(0 until nums.size-1)), 51 | pre_rob(nums.sliceArray(1 until nums.size))) 52 | } 53 | 54 | fun pre_rob(nums: IntArray): Int { 55 | if (nums.size == 0) return 0 56 | if (nums.size == 1) return nums[0] 57 | 58 | var l = Math.max(nums[0], nums[1]) 59 | var ll = nums[0] 60 | 61 | for (i in 2 until nums.size) { 62 | val temp = l 63 | l = Math.max(l, ll+nums[i]) 64 | ll = temp 65 | } 66 | return l 67 | } 68 | } 69 | 70 | -------------------------------------------------------------------------------- /medium/22.generate-parentheses.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=22 lang=kotlin 3 | * 4 | * [22] Generate Parentheses 5 | * 6 | * https://leetcode.com/problems/generate-parentheses/description/ 7 | * 8 | * algorithms 9 | * Medium (56.51%) 10 | * Likes: 3396 11 | * Dislikes: 202 12 | * Total Accepted: 401.8K 13 | * Total Submissions: 700.3K 14 | * Testcase Example: '3' 15 | * 16 | * 17 | * Given n pairs of parentheses, write a function to generate all combinations 18 | * of well-formed parentheses. 19 | * 20 | * 21 | * 22 | * For example, given n = 3, a solution set is: 23 | * 24 | * 25 | * [ 26 | * ⁠ "((()))", 27 | * ⁠ "(()())", 28 | * ⁠ "(())()", 29 | * ⁠ "()(())", 30 | * ⁠ "()()()" 31 | * ] 32 | * 33 | */ 34 | 35 | // @lc code=start 36 | class Solution { 37 | fun generateParenthesis(n: Int): List { 38 | var res = mutableListOf() 39 | dfs(n, n, "", res) 40 | return res 41 | } 42 | 43 | private fun dfs(left: Int, right: Int, str: String, res: MutableList) { 44 | if (left > right) return ; 45 | if (left == 0 && right == 0) { 46 | res.add(str); 47 | } else { 48 | if (left > 0) dfs(left-1, right, str+'(', res); 49 | if (right > 0) dfs(left, right-1, str+')', res); 50 | } 51 | } 52 | } 53 | // @lc code=end 54 | 55 | -------------------------------------------------------------------------------- /medium/24.swap-nodes-in-pairs.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=24 lang=kotlin 3 | * 4 | * [24] Swap Nodes in Pairs 5 | * 6 | * https://leetcode.com/problems/swap-nodes-in-pairs/description/ 7 | * 8 | * algorithms 9 | * Medium (45.94%) 10 | * Likes: 1438 11 | * Dislikes: 128 12 | * Total Accepted: 363.8K 13 | * Total Submissions: 779.5K 14 | * Testcase Example: '[1,2,3,4]' 15 | * 16 | * Given a linked list, swap every two adjacent nodes and return its head. 17 | * 18 | * You may not modify the values in the list's nodes, only nodes itself may be 19 | * changed. 20 | * 21 | * 22 | * 23 | * Example: 24 | * 25 | * 26 | * Given 1->2->3->4, you should return the list as 2->1->4->3. 27 | * 28 | * 29 | */ 30 | 31 | // @lc code=start 32 | /** 33 | * Example: 34 | * var li = ListNode(5) 35 | * var v = li.`val` 36 | * Definition for singly-linked list. 37 | * class ListNode(var `val`: Int) { 38 | * var next: ListNode? = null 39 | * } 40 | */ 41 | class Solution { 42 | fun swapPairs(head: ListNode?): ListNode? { 43 | var G: ListNode? = ListNode(0) 44 | G?.next = head 45 | var p = G 46 | var head = head 47 | 48 | while (head != null && head.next != null) { 49 | var temp = head?.next 50 | head?.next = temp.next 51 | temp?.next = head 52 | p?.next = temp 53 | p = head 54 | head = head?.next 55 | } 56 | return G?.next 57 | } 58 | } 59 | // @lc code=end 60 | 61 | -------------------------------------------------------------------------------- /medium/264.ugly-number-ii.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=264 lang=kotlin 3 | * 4 | * [264] Ugly Number II 5 | * 6 | * https://leetcode.com/problems/ugly-number-ii/description/ 7 | * 8 | * algorithms 9 | * Medium (37.15%) 10 | * Likes: 1085 11 | * Dislikes: 72 12 | * Total Accepted: 115.2K 13 | * Total Submissions: 307.8K 14 | * Testcase Example: '10' 15 | * 16 | * Write a program to find the n-th ugly number. 17 | * 18 | * Ugly numbers are positive numbers whose prime factors only include 2, 3, 19 | * 5.  20 | * 21 | * Example: 22 | * 23 | * 24 | * Input: n = 10 25 | * Output: 12 26 | * Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 27 | * ugly numbers. 28 | * 29 | * Note:   30 | * 31 | * 32 | * 1 is typically treated as an ugly number. 33 | * n does not exceed 1690. 34 | * 35 | */ 36 | class Solution { 37 | fun nthUglyNumber(n: Int): Int { 38 | var ug = IntArray(n+1) 39 | ug[0] = 1 40 | var id2 = 0 41 | var id3 = 0 42 | var id5 = 0 43 | var cnt = 1 44 | while (cnt < n) { 45 | val temp = Math.min(ug[id2]*2, Math.min(ug[id3]*3, ug[id5]*5)) 46 | if (temp == ug[id2]*2) id2++ 47 | if (temp == ug[id3]*3) id3++ 48 | if (temp == ug[id5]*5) id5++ 49 | ug[cnt++] = temp 50 | } 51 | return ug[n-1] 52 | } 53 | } 54 | 55 | -------------------------------------------------------------------------------- /medium/279.perfect-squares.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=279 lang=kotlin 3 | * 4 | * [279] Perfect Squares 5 | * 6 | * https://leetcode.com/problems/perfect-squares/description/ 7 | * 8 | * algorithms 9 | * Medium (41.37%) 10 | * Total Accepted: 173.3K 11 | * Total Submissions: 418K 12 | * Testcase Example: '12' 13 | * 14 | * Given a positive integer n, find the least number of perfect square numbers 15 | * (for example, 1, 4, 9, 16, ...) which sum to n. 16 | * 17 | * Example 1: 18 | * 19 | * 20 | * Input: n = 12 21 | * Output: 3 22 | * Explanation: 12 = 4 + 4 + 4. 23 | * 24 | * Example 2: 25 | * 26 | * 27 | * Input: n = 13 28 | * Output: 2 29 | * Explanation: 13 = 4 + 9. 30 | */ 31 | class Solution { 32 | fun numSquares(n: Int): Int { 33 | var mN = n 34 | while (mN % 4 == 0) mN /= 4 35 | if (mN % 8 == 7) return 4 36 | var i = 0 37 | while (i*i <= n) { 38 | val temp = Math.sqrt(n-i*i*1.0).toInt() 39 | if (n == temp*temp+i*i) { 40 | return if (temp == 0 || i == 0) 1 else 2 41 | } 42 | i++ 43 | } 44 | return 3 45 | } 46 | } 47 | fun main(args: Array) { 48 | val test = Solution() 49 | println(test.numSquares(29825)) 50 | } -------------------------------------------------------------------------------- /medium/29.divide-two-integers.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=29 lang=kotlin 3 | * 4 | * [29] Divide Two Integers 5 | * 6 | * https://leetcode.com/problems/divide-two-integers/description/ 7 | * 8 | * algorithms 9 | * Medium (16.15%) 10 | * Likes: 736 11 | * Dislikes: 3527 12 | * Total Accepted: 208.7K 13 | * Total Submissions: 1.3M 14 | * Testcase Example: '10\n3' 15 | * 16 | * Given two integers dividend and divisor, divide two integers without using 17 | * multiplication, division and mod operator. 18 | * 19 | * Return the quotient after dividing dividend by divisor. 20 | * 21 | * The integer division should truncate toward zero. 22 | * 23 | * Example 1: 24 | * 25 | * 26 | * Input: dividend = 10, divisor = 3 27 | * Output: 3 28 | * 29 | * Example 2: 30 | * 31 | * 32 | * Input: dividend = 7, divisor = -3 33 | * Output: -2 34 | * 35 | * Note: 36 | * 37 | * 38 | * Both dividend and divisor will be 32-bit signed integers. 39 | * The divisor will never be 0. 40 | * Assume we are dealing with an environment which could only store integers 41 | * within the 32-bit signed integer range: [−2^31,  2^31 − 1]. For the purpose 42 | * of this problem, assume that your function returns 2^31 − 1 when the 43 | * division result overflows. 44 | * 45 | * 46 | */ 47 | class Solution { 48 | fun divide(dividend: Int, divisor: Int): Int { 49 | if (dividend == Int.MIN_VALUE && divisor == -1) { 50 | return Int.MAX_VALUE 51 | } 52 | 53 | var a = Math.abs(dividend.toLong()) 54 | var b = Math.abs(divisor.toLong()) 55 | var res = 0 56 | 57 | while (a >= b) { 58 | var sum = b 59 | var cnt = 1 60 | 61 | while (sum+sum <= a) { 62 | sum += sum 63 | cnt += cnt 64 | } 65 | a -= sum 66 | res += cnt 67 | } 68 | if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) 69 | res = -res 70 | return res 71 | } 72 | } 73 | 74 | -------------------------------------------------------------------------------- /medium/3.longest-substring-without-repeating-characters.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=3 lang=kotlin 3 | * 4 | * [3] Longest Substring Without Repeating Characters 5 | * 6 | * https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ 7 | * 8 | * algorithms 9 | * Medium (28.19%) 10 | * Total Accepted: 878.9K 11 | * Total Submissions: 3.1M 12 | * Testcase Example: '"abcabcbb"' 13 | * 14 | * Given a string, find the length of the longest substring without repeating 15 | * characters. 16 | * 17 | * 18 | * Example 1: 19 | * 20 | * 21 | * Input: "abcabcbb" 22 | * Output: 3 23 | * Explanation: The answer is "abc", with the length of 3. 24 | * 25 | * 26 | * 27 | * Example 2: 28 | * 29 | * 30 | * Input: "bbbbb" 31 | * Output: 1 32 | * Explanation: The answer is "b", with the length of 1. 33 | * 34 | * 35 | * 36 | * Example 3: 37 | * 38 | * 39 | * Input: "pwwkew" 40 | * Output: 3 41 | * Explanation: The answer is "wke", with the length of 3. 42 | * ⁠ Note that the answer must be a substring, "pwke" is a 43 | * subsequence and not a substring. 44 | * 45 | * 46 | * 47 | * 48 | */ 49 | class Solution { 50 | fun lengthOfLongestSubstring(s: String): Int { 51 | val mm = HashMap() 52 | var ans = 0 53 | var last = -1 54 | for (i in s.indices) { 55 | last = Math.max(last, mm.getOrElse(s[i], {-1})) 56 | ans = Math.max(ans, i - last) 57 | mm[s[i]] = i 58 | } 59 | return ans 60 | } 61 | } 62 | 63 | -------------------------------------------------------------------------------- /medium/300.longest-increasing-subsequence.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=300 lang=kotlin 3 | * 4 | * [300] Longest Increasing Subsequence 5 | * 6 | * https://leetcode.com/problems/longest-increasing-subsequence/description/ 7 | * 8 | * algorithms 9 | * Medium (41.17%) 10 | * Likes: 2833 11 | * Dislikes: 67 12 | * Total Accepted: 248.1K 13 | * Total Submissions: 601.8K 14 | * Testcase Example: '[10,9,2,5,3,7,101,18]' 15 | * 16 | * Given an unsorted array of integers, find the length of longest increasing 17 | * subsequence. 18 | * 19 | * Example: 20 | * 21 | * 22 | * Input: [10,9,2,5,3,7,101,18] 23 | * Output: 4 24 | * Explanation: The longest increasing subsequence is [2,3,7,101], therefore 25 | * the length is 4. 26 | * 27 | * Note: 28 | * 29 | * 30 | * There may be more than one LIS combination, it is only necessary for you to 31 | * return the length. 32 | * Your algorithm should run in O(n^2) complexity. 33 | * 34 | * 35 | * Follow up: Could you improve it to O(n log n) time complexity? 36 | * 37 | */ 38 | class Solution { 39 | fun lengthOfLIS(nums: IntArray): Int { 40 | var ans = 0 41 | val n = nums.size 42 | 43 | var dp = IntArray(nums.size+1, {1}) 44 | dp[0] = 1 45 | for (i in 1 until n) 46 | for (j in 0 until i) 47 | if (nums[j] < nums[i]) 48 | dp[i] = Math.max(dp[i], dp[j]+1) 49 | 50 | for (i in 0 until n) { 51 | ans = Math.max(ans, dp[i]) 52 | } 53 | return ans 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /medium/304.range-sum-query-2-d-immutable.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=304 lang=kotlin 3 | * 4 | * [304] Range Sum Query 2D - Immutable 5 | * 6 | * https://leetcode.com/problems/range-sum-query-2d-immutable/description/ 7 | * 8 | * algorithms 9 | * Medium (33.53%) 10 | * Likes: 521 11 | * Dislikes: 134 12 | * Total Accepted: 77.5K 13 | * Total Submissions: 230.7K 14 | * Testcase Example: '["NumMatrix","sumRegion","sumRegion","sumRegion"]\n[[[[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]],[2,1,4,3],[1,1,2,2],[1,2,2,4]]' 15 | * 16 | * Given a 2D matrix matrix, find the sum of the elements inside the rectangle 17 | * defined by its upper left corner (row1, col1) and lower right corner (row2, 18 | * col2). 19 | * 20 | * 21 | * 22 | * The above rectangle (with the red border) is defined by (row1, col1) = (2, 23 | * 1) and (row2, col2) = (4, 3), which contains sum = 8. 24 | * 25 | * 26 | * Example: 27 | * 28 | * Given matrix = [ 29 | * ⁠ [3, 0, 1, 4, 2], 30 | * ⁠ [5, 6, 3, 2, 1], 31 | * ⁠ [1, 2, 0, 1, 5], 32 | * ⁠ [4, 1, 0, 1, 7], 33 | * ⁠ [1, 0, 3, 0, 5] 34 | * ] 35 | * 36 | * sumRegion(2, 1, 4, 3) -> 8 37 | * sumRegion(1, 1, 2, 2) -> 11 38 | * sumRegion(1, 2, 2, 4) -> 12 39 | * 40 | * 41 | * 42 | * Note: 43 | * 44 | * You may assume that the matrix does not change. 45 | * There are many calls to sumRegion function. 46 | * You may assume that row1 ≤ row2 and col1 ≤ col2. 47 | * 48 | * 49 | */ 50 | class NumMatrix(matrix: Array) { 51 | var dp = Array(1005) { IntArray(1005) } 52 | 53 | init { 54 | for (i in 1 .. matrix.size) 55 | for (j in 1 .. matrix[0].size) 56 | dp[i][j] = dp[i][j-1]+dp[i-1][j]-dp[i-1][j-1]+matrix[i-1][j-1] 57 | } 58 | 59 | fun sumRegion(row1: Int, col1: Int, row2: Int, col2: Int): Int { 60 | return dp[row2+1][col2+1]-dp[row2+1][col1]-dp[row1][col2+1]+dp[row1][col1] 61 | } 62 | 63 | } 64 | 65 | /** 66 | * Your NumMatrix object will be instantiated and called as such: 67 | * var obj = NumMatrix(matrix) 68 | * var param_1 = obj.sumRegion(row1,col1,row2,col2) 69 | */ 70 | 71 | -------------------------------------------------------------------------------- /medium/31.next-permutation.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=31 lang=kotlin 3 | * 4 | * [31] Next Permutation 5 | * 6 | * https://leetcode.com/problems/next-permutation/description/ 7 | * 8 | * algorithms 9 | * Medium (30.93%) 10 | * Likes: 2193 11 | * Dislikes: 706 12 | * Total Accepted: 273.1K 13 | * Total Submissions: 878.5K 14 | * Testcase Example: '[1,2,3]' 15 | * 16 | * Implement next permutation, which rearranges numbers into the 17 | * lexicographically next greater permutation of numbers. 18 | * 19 | * If such arrangement is not possible, it must rearrange it as the lowest 20 | * possible order (ie, sorted in ascending order). 21 | * 22 | * The replacement must be in-place and use only constant extra memory. 23 | * 24 | * Here are some examples. Inputs are in the left-hand column and its 25 | * corresponding outputs are in the right-hand column. 26 | * 27 | * 1,2,3 → 1,3,2 28 | * 3,2,1 → 1,2,3 29 | * 1,1,5 → 1,5,1 30 | * 31 | */ 32 | class Solution { 33 | fun nextPermutation(nums: IntArray): Unit { 34 | val n = nums.size 35 | var flag = -1 36 | for (i in n-1 downTo 1) { 37 | if (nums[i] > nums[i-1]) { 38 | flag = i-1 39 | break 40 | } 41 | } 42 | if (flag == -1) { 43 | nums.sort(0, n) 44 | } else { 45 | var mina = Int.MAX_VALUE 46 | var st = -1 47 | for (i in flag+1 until n) { 48 | if (nums[i] <= nums[flag]) continue 49 | if (nums[i] < mina) { 50 | mina = nums[i] 51 | st = i 52 | } 53 | } 54 | val temp = nums[flag] 55 | nums[flag] = nums[st] 56 | nums[st] = temp 57 | nums.sort(flag+1, n) 58 | } 59 | } 60 | } 61 | 62 | -------------------------------------------------------------------------------- /medium/310.minimum-height-trees.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=310 lang=kotlin 3 | * 4 | * [310] Minimum Height Trees 5 | * 6 | * https://leetcode.com/problems/minimum-height-trees/description/ 7 | * 8 | * algorithms 9 | * Medium (30.65%) 10 | * Likes: 1167 11 | * Dislikes: 71 12 | * Total Accepted: 71.9K 13 | * Total Submissions: 233.7K 14 | * Testcase Example: '4\n[[1,0],[1,2],[1,3]]' 15 | * 16 | * For an undirected graph with tree characteristics, we can choose any node as 17 | * the root. The result graph is then a rooted tree. Among all possible rooted 18 | * trees, those with minimum height are called minimum height trees (MHTs). 19 | * Given such a graph, write a function to find all the MHTs and return a list 20 | * of their root labels. 21 | * 22 | * Format 23 | * The graph contains n nodes which are labeled from 0 to n - 1. You will be 24 | * given the number n and a list of undirected edges (each edge is a pair of 25 | * labels). 26 | * 27 | * You can assume that no duplicate edges will appear in edges. Since all edges 28 | * are undirected, [0, 1] is the same as [1, 0] and thus will not appear 29 | * together in edges. 30 | * 31 | * Example 1 : 32 | * 33 | * 34 | * Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]] 35 | * 36 | * ⁠ 0 37 | * ⁠ | 38 | * ⁠ 1 39 | * ⁠ / \ 40 | * ⁠ 2 3 41 | * 42 | * Output: [1] 43 | * 44 | * 45 | * Example 2 : 46 | * 47 | * 48 | * Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]] 49 | * 50 | * ⁠ 0 1 2 51 | * ⁠ \ | / 52 | * ⁠ 3 53 | * ⁠ | 54 | * ⁠ 4 55 | * ⁠ | 56 | * ⁠ 5 57 | * 58 | * Output: [3, 4] 59 | * 60 | * Note: 61 | * 62 | * 63 | * According to the definition of tree on Wikipedia: “a tree is an undirected 64 | * graph in which any two vertices are connected by exactly one path. In other 65 | * words, any connected graph without simple cycles is a tree.” 66 | * The height of a rooted tree is the number of edges on the longest downward 67 | * path between the root and a leaf. 68 | * 69 | * 70 | */ 71 | 72 | import java.util.LinkedList 73 | /* 74 | * 拓扑排序,每次删除度为 1 的点,最后剩下 1 或者 2 个点就是答案 75 | */ 76 | class Solution { 77 | fun findMinHeightTrees(n: Int, edges: Array): List { 78 | if (n == 1) return listOf(0) 79 | var q = LinkedList() 80 | var e = Array>(n+1) { mutableListOf() } 81 | var vis = BooleanArray(n+1) 82 | var ind = IntArray(n+1) 83 | 84 | for (edge in edges) { 85 | ind[edge[0]]++ 86 | ind[edge[1]]++ 87 | e[edge[0]].add(edge[1]) 88 | e[edge[1]].add(edge[0]) 89 | } 90 | var cnt = n 91 | 92 | for (i in 0 until n) { 93 | if (ind[i] == 1) { 94 | vis[i] = true 95 | q.offer(i) 96 | } 97 | } 98 | 99 | while (cnt > 2) { 100 | val sz = q.size 101 | cnt -= sz 102 | 103 | for (i in 0 until sz) { 104 | val top = q.poll() 105 | 106 | for (j in e[top]) { 107 | if (!vis[j]) { 108 | ind[j]-- 109 | if (ind[j] == 1) q.offer(j) 110 | } 111 | } 112 | } 113 | } 114 | return q.toList() 115 | } 116 | } 117 | 118 | -------------------------------------------------------------------------------- /medium/322.coin-change.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=322 lang=kotlin 3 | * 4 | * [322] Coin Change 5 | * 6 | * https://leetcode.com/problems/coin-change/description/ 7 | * 8 | * algorithms 9 | * Medium (31.48%) 10 | * Likes: 2116 11 | * Dislikes: 82 12 | * Total Accepted: 231.4K 13 | * Total Submissions: 733K 14 | * Testcase Example: '[1,2,5]\n11' 15 | * 16 | * You are given coins of different denominations and a total amount of money 17 | * amount. Write a function to compute the fewest number of coins that you need 18 | * to make up that amount. If that amount of money cannot be made up by any 19 | * combination of the coins, return -1. 20 | * 21 | * Example 1: 22 | * 23 | * 24 | * Input: coins = [1, 2, 5], amount = 11 25 | * Output: 3 26 | * Explanation: 11 = 5 + 5 + 1 27 | * 28 | * Example 2: 29 | * 30 | * 31 | * Input: coins = [2], amount = 3 32 | * Output: -1 33 | * 34 | * 35 | * Note: 36 | * You may assume that you have an infinite number of each kind of coin. 37 | * 38 | */ 39 | 40 | import java.util.LinkedList 41 | 42 | class Solution { 43 | fun coinChange(coins: IntArray, amount: Int): Int { 44 | var dp = IntArray(amount+1) {0x3f3f3f3f} 45 | 46 | dp[0] = 0 47 | 48 | for (i in coins) { 49 | for (j in i .. amount) { 50 | if (dp[j-i] != 0x3f3f3f3f) { 51 | dp[j] = Math.min(dp[j], dp[j-i]+1) 52 | } 53 | } 54 | } 55 | return if (dp[amount] == 0x3f3f3f3f) -1 else dp[amount] 56 | } 57 | 58 | 59 | 60 | data class Node( 61 | var num: Int = 0, 62 | var step: Int = 0 63 | ) 64 | // dp+bfs 65 | fun coinChange2(coins: IntArray, amount: Int): Int { 66 | val n = coins.size 67 | var dp = BooleanArray(amount+1) 68 | dp[0] = true 69 | for (i in 0 until n) { 70 | for (j in 0 .. amount) { 71 | if (j <= amount-coins[i]) { 72 | if (dp[j]) { 73 | dp[j+coins[i]] = true 74 | } 75 | } 76 | } 77 | } 78 | if (dp[amount]) { 79 | var q = LinkedList() 80 | var vis = BooleanArray(amount+1) 81 | q.offer(Node(0, 0)) 82 | vis[0] = true 83 | 84 | while (!q.isEmpty()) { 85 | val top = q.poll() 86 | if (top.num == amount) 87 | return top.step 88 | 89 | for (i in 0 until n) { 90 | if (top.num <= amount-coins[i] && !vis[top.num+coins[i]]) { 91 | q.offer(Node(top.num+coins[i], top.step+1)) 92 | vis[top.num+coins[i]] = true 93 | } 94 | } 95 | } 96 | return -1 97 | } else { 98 | return -1; 99 | } 100 | } 101 | } 102 | 103 | -------------------------------------------------------------------------------- /medium/34.find-first-and-last-position-of-element-in-sorted-array.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=34 lang=kotlin 3 | * 4 | * [34] Find First and Last Position of Element in Sorted Array 5 | * 6 | * https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/ 7 | * 8 | * algorithms 9 | * Medium (34.46%) 10 | * Likes: 2153 11 | * Dislikes: 100 12 | * Total Accepted: 369.5K 13 | * Total Submissions: 1.1M 14 | * Testcase Example: '[5,7,7,8,8,10]\n8' 15 | * 16 | * Given an array of integers nums sorted in ascending order, find the starting 17 | * and ending position of a given target value. 18 | * 19 | * Your algorithm's runtime complexity must be in the order of O(log n). 20 | * 21 | * If the target is not found in the array, return [-1, -1]. 22 | * 23 | * Example 1: 24 | * 25 | * 26 | * Input: nums = [5,7,7,8,8,10], target = 8 27 | * Output: [3,4] 28 | * 29 | * Example 2: 30 | * 31 | * 32 | * Input: nums = [5,7,7,8,8,10], target = 6 33 | * Output: [-1,-1] 34 | * 35 | */ 36 | 37 | // @lc code=start 38 | class Solution { 39 | fun searchRange(nums: IntArray, target: Int): IntArray { 40 | if (nums.size == 0) return intArrayOf(-1, -1) 41 | 42 | var l: Int = 0 43 | var r: Int = nums.size-1 44 | var mid = 0 45 | var res = IntArray(2) 46 | 47 | while (l < r) { 48 | mid = (l+r) / 2 49 | if (nums[mid] < target) { 50 | l = mid+1 51 | } else { 52 | r = mid 53 | } 54 | } 55 | if (nums[l] != target) return intArrayOf(-1, -1) 56 | res[0] = l 57 | 58 | r = nums.size-1 59 | 60 | while (l < r) { 61 | mid = (l+r) / 2 + 1 62 | if (nums[mid] == target) { 63 | l = mid 64 | } else { 65 | r = mid-1 66 | } 67 | } 68 | res[1] = l 69 | return res 70 | } 71 | } 72 | // @lc code=end 73 | 74 | -------------------------------------------------------------------------------- /medium/372.super-pow.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=372 lang=kotlin 3 | * 4 | * [372] Super Pow 5 | * 6 | * https://leetcode.com/problems/super-pow/description/ 7 | * 8 | * algorithms 9 | * Medium (35.86%) 10 | * Likes: 146 11 | * Dislikes: 602 12 | * Total Accepted: 29.8K 13 | * Total Submissions: 83.1K 14 | * Testcase Example: '2\n[3]' 15 | * 16 | * Your task is to calculate a^b mod 1337 where a is a positive integer and b 17 | * is an extremely large positive integer given in the form of an array. 18 | * 19 | * Example 1: 20 | * 21 | * 22 | * 23 | * Input: a = 2, b = [3] 24 | * Output: 8 25 | * 26 | * 27 | * 28 | * Example 2: 29 | * 30 | * 31 | * Input: a = 2, b = [1,0] 32 | * Output: 1024 33 | * 34 | * 35 | * 36 | */ 37 | class Solution { 38 | private fun qpow(a: Long, b: Long): Long { 39 | var ans = 1L 40 | var b = b 41 | var a = a%1337 42 | while (b > 0) { 43 | if (b%2 == 1L) ans = ans*a 44 | a = a*a%1337 45 | b = b.shr(1) 46 | } 47 | return ans 48 | } 49 | /* 50 | * 4^432 = 4^(400+30+2) 51 | * = 4^400 * 4^30 * 4^2 52 | * = (4^100)^4 * (4^10)^3 * (4^1)^2 53 | */ 54 | fun superPow(a: Int, b: IntArray): Int { 55 | var ans = 1L 56 | var cnt = a.toLong() 57 | 58 | 59 | for (i in b.size-1 downTo 0) { 60 | ans = ans * qpow(cnt, b[i].toLong()) % 1337 61 | cnt = qpow(cnt, 10) 62 | } 63 | 64 | return ans.toInt() 65 | } 66 | } 67 | 68 | -------------------------------------------------------------------------------- /medium/402.remove-k-digits.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=402 lang=kotlin 3 | * 4 | * [402] Remove K Digits 5 | * 6 | * https://leetcode.com/problems/remove-k-digits/description/ 7 | * 8 | * algorithms 9 | * Medium (26.95%) 10 | * Likes: 1099 11 | * Dislikes: 66 12 | * Total Accepted: 71.4K 13 | * Total Submissions: 264.7K 14 | * Testcase Example: '"1432219"\n3' 15 | * 16 | * Given a non-negative integer num represented as a string, remove k digits 17 | * from the number so that the new number is the smallest possible. 18 | * 19 | * 20 | * Note: 21 | * 22 | * The length of num is less than 10002 and will be ≥ k. 23 | * The given num does not contain any leading zero. 24 | * 25 | * 26 | * 27 | * 28 | * Example 1: 29 | * 30 | * Input: num = "1432219", k = 3 31 | * Output: "1219" 32 | * Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 33 | * which is the smallest. 34 | * 35 | * 36 | * 37 | * Example 2: 38 | * 39 | * Input: num = "10200", k = 1 40 | * Output: "200" 41 | * Explanation: Remove the leading 1 and the number is 200. Note that the 42 | * output must not contain leading zeroes. 43 | * 44 | * 45 | * 46 | * Example 3: 47 | * 48 | * Input: num = "10", k = 2 49 | * Output: "0" 50 | * Explanation: Remove all the digits from the number and it is left with 51 | * nothing which is 0. 52 | * 53 | * 54 | */ 55 | class Solution { 56 | fun removeKdigits(num: String, k: Int): String { 57 | var newL = num.length - k 58 | var s = k 59 | var stk = CharArray(num.length) 60 | var top = 0 61 | 62 | for (i in num) { 63 | while (s > 0 && top > 0 && stk[top-1] > i) { 64 | top-- 65 | s-- 66 | } 67 | stk[top++] = i 68 | } 69 | 70 | var offset = 0 71 | while (offset < newL && stk[offset] == '0') { 72 | offset++ 73 | } 74 | return if (offset == newL) "0" else String(stk, offset, newL-offset) 75 | } 76 | } 77 | 78 | -------------------------------------------------------------------------------- /medium/5.longest-palindromic-substring.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=5 lang=kotlin 3 | * 4 | * [5] Longest Palindromic Substring 5 | */ 6 | class Solution { 7 | fun longestPalindrome(s: String): String { 8 | var str = "$#" 9 | for (i in 0 until s.length) { 10 | str += s[i] 11 | str += "#" 12 | } 13 | str += "^" 14 | 15 | var RL = IntArray(str.length, {0}) 16 | var maxr = 0 17 | var pos = 0 18 | 19 | var maxlen = 0 20 | var id = 0 21 | 22 | for (i in 1 until str.length-1) { 23 | RL[i] = if (i < maxr) Math.min(RL[2*pos-i], maxr-i) else 1 24 | 25 | while (str[i-RL[i]] == str[i+RL[i]]) RL[i]++ 26 | 27 | if (RL[i]+i > maxr) { 28 | maxr = RL[i]+i 29 | pos = i 30 | } 31 | } 32 | 33 | for (i in 1 until str.length-1) { 34 | if (RL[i] > maxlen) { 35 | maxlen = RL[i] 36 | id = i 37 | } 38 | } 39 | val start = (id-maxlen)/2 40 | val end = start+maxlen-1 41 | return s.substring(start, end) 42 | } 43 | } -------------------------------------------------------------------------------- /medium/50.pow-x-n.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=50 lang=kotlin 3 | * 4 | * [50] Pow(x, n) 5 | * 6 | * https://leetcode.com/problems/powx-n/description/ 7 | * 8 | * algorithms 9 | * Medium (28.35%) 10 | * Likes: 924 11 | * Dislikes: 2262 12 | * Total Accepted: 346.6K 13 | * Total Submissions: 1.2M 14 | * Testcase Example: '2.00000\n10' 15 | * 16 | * Implement pow(x, n), which calculates x raised to the power n (x^n). 17 | * 18 | * Example 1: 19 | * 20 | * 21 | * Input: 2.00000, 10 22 | * Output: 1024.00000 23 | * 24 | * 25 | * Example 2: 26 | * 27 | * 28 | * Input: 2.10000, 3 29 | * Output: 9.26100 30 | * 31 | * 32 | * Example 3: 33 | * 34 | * 35 | * Input: 2.00000, -2 36 | * Output: 0.25000 37 | * Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25 38 | * 39 | * 40 | * Note: 41 | * 42 | * 43 | * -100.0 < x < 100.0 44 | * n is a 32-bit signed integer, within the range [−2^31, 2^31 − 1] 45 | * 46 | * 47 | */ 48 | class Solution { 49 | fun myPow(x: Double, n: Int): Double { 50 | var ans = 1.0 51 | var a = x 52 | var b = Math.abs(n.toLong()) 53 | 54 | while (b > 0) { 55 | if (b%2 == 1L) ans = ans*a 56 | a *= a 57 | b = b.shr(1) 58 | } 59 | if (n < 0) return 1/ans 60 | else return ans 61 | } 62 | } 63 | 64 | -------------------------------------------------------------------------------- /medium/515.find-largest-value-in-each-tree-row.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=515 lang=kotlin 3 | * 4 | * [515] Find Largest Value in Each Tree Row 5 | * 6 | * https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/ 7 | * 8 | * algorithms 9 | * Medium (58.37%) 10 | * Likes: 562 11 | * Dislikes: 48 12 | * Total Accepted: 71.8K 13 | * Total Submissions: 122.6K 14 | * Testcase Example: '[1,3,2,5,3,null,9]' 15 | * 16 | * You need to find the largest value in each row of a binary tree. 17 | * 18 | * Example: 19 | * 20 | * Input: 21 | * 22 | * ⁠ 1 23 | * ⁠ / \ 24 | * ⁠ 3 2 25 | * ⁠ / \ \ 26 | * ⁠ 5 3 9 27 | * 28 | * Output: [1, 3, 9] 29 | * 30 | * 31 | * 32 | */ 33 | /** 34 | * Example: 35 | * var ti = TreeNode(5) 36 | * var v = ti.`val` 37 | * Definition for a binary tree node. 38 | * class TreeNode(var `val`: Int) { 39 | * var left: TreeNode? = null 40 | * var right: TreeNode? = null 41 | * } 42 | */ 43 | 44 | import java.util.LinkedList 45 | 46 | // BFS 遍历每一层元素 47 | class Solution { 48 | fun largestValues(root: TreeNode?): List { 49 | if (root == null) return listOf() 50 | 51 | var q = LinkedList() 52 | var res = mutableListOf() 53 | q.offer(root) 54 | 55 | while (true) { 56 | var maxa = Int.MIN_VALUE 57 | val cnt = q.size 58 | if (cnt == 0) break 59 | for (i in 0 until cnt) { 60 | val top = q.poll() 61 | // println(top!!.`val`) 62 | maxa = Math.max(maxa, top!!.`val`) 63 | 64 | if (top?.left != null) q.offer(top?.left) 65 | if (top?.right != null) q.offer(top?.right) 66 | } 67 | res.add(maxa) 68 | } 69 | return res 70 | } 71 | } 72 | 73 | -------------------------------------------------------------------------------- /medium/55.jump-game.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=55 lang=kotlin 3 | * 4 | * [55] Jump Game 5 | * 6 | * https://leetcode.com/problems/jump-game/description/ 7 | * 8 | * algorithms 9 | * Medium (31.47%) 10 | * Total Accepted: 243.1K 11 | * Total Submissions: 772.6K 12 | * Testcase Example: '[2,3,1,1,4]' 13 | * 14 | * Given an array of non-negative integers, you are initially positioned at the 15 | * first index of the array. 16 | * 17 | * Each element in the array represents your maximum jump length at that 18 | * position. 19 | * 20 | * Determine if you are able to reach the last index. 21 | * 22 | * Example 1: 23 | * 24 | * 25 | * Input: [2,3,1,1,4] 26 | * Output: true 27 | * Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last 28 | * index. 29 | * 30 | * 31 | * Example 2: 32 | * 33 | * 34 | * Input: [3,2,1,0,4] 35 | * Output: false 36 | * Explanation: You will always arrive at index 3 no matter what. Its 37 | * maximum 38 | * jump length is 0, which makes it impossible to reach the last index. 39 | * 40 | * 41 | */ 42 | class Solution { 43 | fun canJump(nums: IntArray): Boolean { 44 | val n = nums.size 45 | var reach = 0 46 | for (i in 0 until n) { 47 | if (i > reach || reach >= n-1) break 48 | reach = Math.max(reach, i+nums[i]) 49 | } 50 | return reach >= n-1 51 | } 52 | } 53 | 54 | -------------------------------------------------------------------------------- /medium/6.zig-zag-conversion.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=6 lang=kotlin 3 | * 4 | * [6] ZigZag Conversion 5 | */ 6 | class Solution { 7 | fun convert(s: String, numRows: Int): String { 8 | if (numRows == 1) return s 9 | 10 | var n = s.length 11 | var res = "" 12 | var cnt = numRows 13 | 14 | 15 | for (i in 0 until numRows) { 16 | cnt = if (cnt - 1 == 0) numRows-1 else cnt-1 17 | 18 | var x = cnt*2 19 | var j = i 20 | while (j < n) { 21 | res += s[j] 22 | j += x 23 | if ((numRows-1)*2-x != 0) 24 | x = (numRows-1)*2-x 25 | } 26 | } 27 | return res 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /medium/60.permutation-sequence.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=60 lang=kotlin 3 | * 4 | * [60] Permutation Sequence 5 | * 6 | * https://leetcode.com/problems/permutation-sequence/description/ 7 | * 8 | * algorithms 9 | * Medium (33.74%) 10 | * Likes: 931 11 | * Dislikes: 244 12 | * Total Accepted: 146.2K 13 | * Total Submissions: 432.6K 14 | * Testcase Example: '3\n3' 15 | * 16 | * The set [1,2,3,...,n] contains a total of n! unique permutations. 17 | * 18 | * By listing and labeling all of the permutations in order, we get the 19 | * following sequence for n = 3: 20 | * 21 | * 22 | * "123" 23 | * "132" 24 | * "213" 25 | * "231" 26 | * "312" 27 | * "321" 28 | * 29 | * 30 | * Given n and k, return the k^th permutation sequence. 31 | * 32 | * Note: 33 | * 34 | * 35 | * Given n will be between 1 and 9 inclusive. 36 | * Given k will be between 1 and n! inclusive. 37 | * 38 | * 39 | * Example 1: 40 | * 41 | * 42 | * Input: n = 3, k = 3 43 | * Output: "213" 44 | * 45 | * 46 | * Example 2: 47 | * 48 | * 49 | * Input: n = 4, k = 9 50 | * Output: "2314" 51 | * 52 | * 53 | */ 54 | class Solution { 55 | private fun getsum(n: Int): Int{ 56 | var ans = 1 57 | for (i in 2 .. n) ans *= i 58 | return ans 59 | } 60 | // 康托展开· 61 | fun getPermutation(n: Int, k: Int): String { 62 | var vis = IntArray(n+1, {0}) 63 | var res = "" 64 | var tn = n 65 | var tk = k 66 | for (x in 0 until n) { 67 | val p = getsum(tn-1) 68 | var row = tk/p 69 | if (tk != row*p) 70 | row++ 71 | var cnt = 0 72 | var s = 0 73 | for (i in 0 until n) 74 | if (vis[i] == 0) { 75 | cnt++ 76 | if (cnt == row) { 77 | vis[i] = 1 78 | s = i+1 79 | break; 80 | } 81 | } 82 | res += s.toString() 83 | tk =tk%p 84 | if (tk == 0) { 85 | tk = p 86 | } 87 | tn-- 88 | } 89 | return res 90 | } 91 | } 92 | 93 | -------------------------------------------------------------------------------- /medium/62.unique-paths.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=62 lang=kotlin 3 | * 4 | * [62] Unique Paths 5 | * 6 | * https://leetcode.com/problems/unique-paths/description/ 7 | * 8 | * algorithms 9 | * Medium (48.55%) 10 | * Likes: 1773 11 | * Dislikes: 121 12 | * Total Accepted: 314K 13 | * Total Submissions: 646.8K 14 | * Testcase Example: '3\n2' 15 | * 16 | * A robot is located at the top-left corner of a m x n grid (marked 'Start' in 17 | * the diagram below). 18 | * 19 | * The robot can only move either down or right at any point in time. The robot 20 | * is trying to reach the bottom-right corner of the grid (marked 'Finish' in 21 | * the diagram below). 22 | * 23 | * How many possible unique paths are there? 24 | * 25 | * 26 | * Above is a 7 x 3 grid. How many possible unique paths are there? 27 | * 28 | * Note: m and n will be at most 100. 29 | * 30 | * Example 1: 31 | * 32 | * 33 | * Input: m = 3, n = 2 34 | * Output: 3 35 | * Explanation: 36 | * From the top-left corner, there are a total of 3 ways to reach the 37 | * bottom-right corner: 38 | * 1. Right -> Right -> Down 39 | * 2. Right -> Down -> Right 40 | * 3. Down -> Right -> Right 41 | * 42 | * 43 | * Example 2: 44 | * 45 | * 46 | * Input: m = 7, n = 3 47 | * Output: 28 48 | * 49 | */ 50 | class Solution { 51 | fun uniquePaths(m: Int, n: Int): Int { 52 | var dp = Array(105){IntArray(105, {0})} 53 | 54 | dp[0][1] = 1 55 | 56 | for (i in 1 .. m) { 57 | for (j in 1 .. n) { 58 | dp[i][j] = dp[i-1][j]+dp[i][j-1] 59 | } 60 | } 61 | return dp[m][n] 62 | } 63 | } 64 | 65 | -------------------------------------------------------------------------------- /medium/621.task-scheduler.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=621 lang=kotlin 3 | * 4 | * [621] Task Scheduler 5 | * 6 | * https://leetcode.com/problems/task-scheduler/description/ 7 | * 8 | * algorithms 9 | * Medium (46.10%) 10 | * Likes: 1983 11 | * Dislikes: 361 12 | * Total Accepted: 106.9K 13 | * Total Submissions: 229.9K 14 | * Testcase Example: '["A","A","A","B","B","B"]\n2' 15 | * 16 | * Given a char array representing tasks CPU need to do. It contains capital 17 | * letters A to Z where different letters represent different tasks. Tasks 18 | * could be done without original order. Each task could be done in one 19 | * interval. For each interval, CPU could finish one task or just be idle. 20 | * 21 | * However, there is a non-negative cooling interval n that means between two 22 | * same tasks, there must be at least n intervals that CPU are doing different 23 | * tasks or just be idle. 24 | * 25 | * You need to return the least number of intervals the CPU will take to finish 26 | * all the given tasks. 27 | * 28 | * 29 | * 30 | * Example: 31 | * 32 | * 33 | * Input: tasks = ["A","A","A","B","B","B"], n = 2 34 | * Output: 8 35 | * Explanation: A -> B -> idle -> A -> B -> idle -> A -> B. 36 | * 37 | * 38 | * 39 | * 40 | * Note: 41 | * 42 | * 43 | * The number of tasks is in the range [1, 10000]. 44 | * The integer n is in the range [0, 100]. 45 | * 46 | * 47 | */ 48 | 49 | // @lc code=start 50 | class Solution { 51 | 52 | /** 53 | * mx-1是可以分为的块数,n+1是每块中的个数, 54 | * 后面的 25-x 是还需要补全的个数 55 | */ 56 | fun leastInterval(tasks: CharArray, n: Int): Int { 57 | var cnt = IntArray(26) 58 | 59 | for (i in tasks) cnt[i-'A']++ 60 | cnt.sort() 61 | var x = 25 62 | var mx = cnt[25] 63 | while (x >= 0 && cnt[x] == mx) x-- 64 | return Math.max(tasks.size, (mx-1)*(n+1)+25-x) 65 | } 66 | } 67 | // @lc code=end 68 | 69 | -------------------------------------------------------------------------------- /medium/63.unique-paths-ii.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=63 lang=kotlin 3 | * 4 | * [63] Unique Paths II 5 | * 6 | * https://leetcode.com/problems/unique-paths-ii/description/ 7 | * 8 | * algorithms 9 | * Medium (33.60%) 10 | * Likes: 939 11 | * Dislikes: 151 12 | * Total Accepted: 214.9K 13 | * Total Submissions: 639.5K 14 | * Testcase Example: '[[0,0,0],[0,1,0],[0,0,0]]' 15 | * 16 | * A robot is located at the top-left corner of a m x n grid (marked 'Start' in 17 | * the diagram below). 18 | * 19 | * The robot can only move either down or right at any point in time. The robot 20 | * is trying to reach the bottom-right corner of the grid (marked 'Finish' in 21 | * the diagram below). 22 | * 23 | * Now consider if some obstacles are added to the grids. How many unique paths 24 | * would there be? 25 | * 26 | * 27 | * 28 | * An obstacle and empty space is marked as 1 and 0 respectively in the grid. 29 | * 30 | * Note: m and n will be at most 100. 31 | * 32 | * Example 1: 33 | * 34 | * 35 | * Input: 36 | * [ 37 | * [0,0,0], 38 | * [0,1,0], 39 | * [0,0,0] 40 | * ] 41 | * Output: 2 42 | * Explanation: 43 | * There is one obstacle in the middle of the 3x3 grid above. 44 | * There are two ways to reach the bottom-right corner: 45 | * 1. Right -> Right -> Down -> Down 46 | * 2. Down -> Down -> Right -> Right 47 | * 48 | * 49 | */ 50 | class Solution { 51 | fun uniquePathsWithObstacles(obstacleGrid: Array): Int { 52 | var dp = Array(105){IntArray(105, {0})} 53 | 54 | dp[0][0] = if (obstacleGrid[0][0] == 1) 0 else 1 55 | 56 | for (i in 1 until obstacleGrid.size) 57 | if (obstacleGrid[i][0] != 1) 58 | dp[i][0] = dp[i-1][0] 59 | 60 | for (i in 1 until obstacleGrid[0].size) 61 | if (obstacleGrid[0][i] != 1) 62 | dp[0][i] = dp[0][i-1] 63 | 64 | for (i in 1 until obstacleGrid.size) { 65 | for (j in 1 until obstacleGrid[0].size) { 66 | if (obstacleGrid[i][j] == 1) dp[i][j] = 0 67 | else dp[i][j] = dp[i-1][j] + dp[i][j-1] 68 | } 69 | } 70 | return dp[obstacleGrid.size-1][obstacleGrid[0].size-1] 71 | } 72 | } 73 | 74 | -------------------------------------------------------------------------------- /medium/64.minimum-path-sum.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=64 lang=kotlin 3 | * 4 | * [64] Minimum Path Sum 5 | * 6 | * https://leetcode.com/problems/minimum-path-sum/description/ 7 | * 8 | * algorithms 9 | * Medium (47.98%) 10 | * Likes: 1523 11 | * Dislikes: 42 12 | * Total Accepted: 249.1K 13 | * Total Submissions: 519.2K 14 | * Testcase Example: '[[1,3,1],[1,5,1],[4,2,1]]' 15 | * 16 | * Given a m x n grid filled with non-negative numbers, find a path from top 17 | * left to bottom right which minimizes the sum of all numbers along its path. 18 | * 19 | * Note: You can only move either down or right at any point in time. 20 | * 21 | * Example: 22 | * 23 | * 24 | * Input: 25 | * [ 26 | * [1,3,1], 27 | * ⁠ [1,5,1], 28 | * ⁠ [4,2,1] 29 | * ] 30 | * Output: 7 31 | * Explanation: Because the path 1→3→1→1→1 minimizes the sum. 32 | * 33 | * 34 | */ 35 | class Solution { 36 | fun minPathSum(grid: Array): Int { 37 | var dp = Array(1005){IntArray(1005, {0})} 38 | 39 | dp[0][0] = grid[0][0] 40 | for (i in 1 until grid.size) dp[i][0] = dp[i-1][0]+grid[i][0] 41 | for (i in 1 until grid[0].size) dp[0][i] = dp[0][i-1]+grid[0][i] 42 | 43 | for (i in 1 until grid.size) { 44 | for (j in 1 until grid[0].size) { 45 | dp[i][j] = Math.min(dp[i][j-1], dp[i-1][j])+grid[i][j] 46 | } 47 | } 48 | return dp[grid.size-1][grid[0].size-1] 49 | } 50 | } 51 | 52 | -------------------------------------------------------------------------------- /medium/8.string-to-integer-atoi.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=8 lang=kotlin 3 | * 4 | * [8] String to Integer (atoi) 5 | */ 6 | class Solution { 7 | fun myAtoi(str: String): Int { 8 | var ans = arrayListOf() 9 | 10 | var first = false 11 | var flag = 1 12 | var pos = 0 13 | 14 | for (i in 0 until str.length) { 15 | if (str[i] != ' ') { 16 | if (str[i] in '0' .. '9' || str[i] == '-' || str[i] == '+') { 17 | if (str[i] == '-') flag = -1 18 | first = true 19 | pos = i 20 | } 21 | break 22 | } 23 | } 24 | 25 | if (!first) { 26 | return 0 27 | } else { 28 | pos = if (str[pos] == '-' || str[pos] == '+') pos+1 else pos 29 | while (pos < str.length && str[pos] == '0') pos++ 30 | while (pos < str.length && str[pos] in '0'..'9') { 31 | ans.add(str[pos]-'0') 32 | pos++ 33 | } 34 | var cnt: Long = 1 35 | var res: Long = 0 36 | 37 | if (ans.size > 10) { 38 | return if (flag == -1) -2147483648 else 2147483647 39 | } 40 | 41 | for (i in ans.size-1 downTo 0) { 42 | res += ans[i]*cnt 43 | cnt *= 10 44 | 45 | if (res >= Int.MAX_VALUE) break 46 | } 47 | res *= flag 48 | 49 | if (res < Int.MIN_VALUE) res = -2147483648 50 | if (res > Int.MAX_VALUE) res = 2147483647 51 | 52 | return res.toInt() 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /medium/869.reordered-power-of-2.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=869 lang=kotlin 3 | * 4 | * [869] Reordered Power of 2 5 | * 6 | * https://leetcode.com/problems/reordered-power-of-2/description/ 7 | * 8 | * algorithms 9 | * Medium (51.23%) 10 | * Likes: 145 11 | * Dislikes: 70 12 | * Total Accepted: 10.7K 13 | * Total Submissions: 20.9K 14 | * Testcase Example: '1' 15 | * 16 | * Starting with a positive integer N, we reorder the digits in any order 17 | * (including the original order) such that the leading digit is not zero. 18 | * 19 | * Return true if and only if we can do this in a way such that the resulting 20 | * number is a power of 2. 21 | * 22 | * 23 | * 24 | * 25 | * 26 | * 27 | * 28 | * Example 1: 29 | * 30 | * 31 | * Input: 1 32 | * Output: true 33 | * 34 | * 35 | * 36 | * Example 2: 37 | * 38 | * 39 | * Input: 10 40 | * Output: false 41 | * 42 | * 43 | * 44 | * Example 3: 45 | * 46 | * 47 | * Input: 16 48 | * Output: true 49 | * 50 | * 51 | * 52 | * Example 4: 53 | * 54 | * 55 | * Input: 24 56 | * Output: false 57 | * 58 | * 59 | * 60 | * Example 5: 61 | * 62 | * 63 | * Input: 46 64 | * Output: true 65 | * 66 | * 67 | * 68 | * 69 | * Note: 70 | * 71 | * 72 | * 1 <= N <= 10^9 73 | * 74 | * 75 | * 76 | * 77 | * 78 | * 79 | * 80 | */ 81 | class Solution { 82 | private var cnt = IntArray(10) 83 | 84 | fun reorderedPowerOf2(N: Int): Boolean { 85 | val str = N.toString() 86 | 87 | for (i in str) cnt[i - '0']++ 88 | 89 | for (i in 0 until 31) { 90 | val temp = (1.shl(i)).toString() 91 | if (temp.length == str.length && ok(temp)) { 92 | return true 93 | } 94 | } 95 | return false 96 | } 97 | 98 | private fun ok(str: String): Boolean { 99 | var vis = IntArray(10) 100 | for (i in str) vis[i - '0']++ 101 | 102 | for (i in 0 until 10) 103 | if (vis[i] != cnt[i]) return false 104 | return true 105 | } 106 | } 107 | 108 | -------------------------------------------------------------------------------- /medium/91.decode-ways.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=91 lang=kotlin 3 | * 4 | * [91] Decode Ways 5 | * 6 | * https://leetcode.com/problems/decode-ways/description/ 7 | * 8 | * algorithms 9 | * Medium (22.67%) 10 | * Likes: 1542 11 | * Dislikes: 1788 12 | * Total Accepted: 280K 13 | * Total Submissions: 1.2M 14 | * Testcase Example: '"12"' 15 | * 16 | * A message containing letters from A-Z is being encoded to numbers using the 17 | * following mapping: 18 | * 19 | * 20 | * 'A' -> 1 21 | * 'B' -> 2 22 | * ... 23 | * 'Z' -> 26 24 | * 25 | * 26 | * Given a non-empty string containing only digits, determine the total number 27 | * of ways to decode it. 28 | * 29 | * Example 1: 30 | * 31 | * 32 | * Input: "12" 33 | * Output: 2 34 | * Explanation: It could be decoded as "AB" (1 2) or "L" (12). 35 | * 36 | * 37 | * Example 2: 38 | * 39 | * 40 | * Input: "226" 41 | * Output: 3 42 | * Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 43 | * 6). 44 | * 45 | */ 46 | class Solution { 47 | fun numDecodings(s: String): Int { 48 | val n = s.length 49 | 50 | var dp = IntArray(n+1) 51 | 52 | dp[0] = 1 53 | for (i in 1 .. n) { 54 | if (s[i-1] != '0') dp[i] = dp[i-1] 55 | if (i != 1 && (s[i-2]-'0')*10+(s[i-1]-'0') < 27 56 | && (s[i-2]-'0')*10+(s[i-1]-'0') > 9) dp[i] += dp[i-2] 57 | } 58 | return dp[n] 59 | } 60 | } 61 | 62 | -------------------------------------------------------------------------------- /medium/94.binary-tree-inorder-traversal.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=94 lang=kotlin 3 | * 4 | * [94] Binary Tree Inorder Traversal 5 | * 6 | * https://leetcode.com/problems/binary-tree-inorder-traversal/description/ 7 | * 8 | * algorithms 9 | * Medium (55.96%) 10 | * Total Accepted: 439.9K 11 | * Total Submissions: 785.6K 12 | * Testcase Example: '[1,null,2,3]' 13 | * 14 | * Given a binary tree, return the inorder traversal of its nodes' values. 15 | * 16 | * Example: 17 | * 18 | * 19 | * Input: [1,null,2,3] 20 | * ⁠ 1 21 | * ⁠ \ 22 | * ⁠ 2 23 | * ⁠ / 24 | * ⁠ 3 25 | * 26 | * Output: [1,3,2] 27 | * 28 | * Follow up: Recursive solution is trivial, could you do it iteratively? 29 | * 30 | */ 31 | /** 32 | * Example: 33 | * var ti = TreeNode(5) 34 | * var v = ti.`val` 35 | * Definition for a binary tree node. 36 | * class TreeNode(var `val`: Int) { 37 | * var left: TreeNode? = null 38 | * var right: TreeNode? = null 39 | * } 40 | */ 41 | class Solution { 42 | private val res = mutableListOf() 43 | fun inorderTraversal(root: TreeNode?): List { 44 | if (root == null) 45 | return res 46 | 47 | if (root.left != null) { 48 | inorderTraversal(root.left) 49 | } 50 | res.add(root.`val`) 51 | 52 | if (root.right != null) { 53 | inorderTraversal(root.right) 54 | } 55 | return res 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /medium/95.unique-binary-search-trees-ii.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=95 lang=kotlin 3 | * 4 | * [95] Unique Binary Search Trees II 5 | * 6 | * https://leetcode.com/problems/unique-binary-search-trees-ii/description/ 7 | * 8 | * algorithms 9 | * Medium (36.68%) 10 | * Likes: 1406 11 | * Dislikes: 120 12 | * Total Accepted: 149.2K 13 | * Total Submissions: 406.6K 14 | * Testcase Example: '3' 15 | * 16 | * Given an integer n, generate all structurally unique BST's (binary search 17 | * trees) that store values 1 ... n. 18 | * 19 | * Example: 20 | * 21 | * 22 | * Input: 3 23 | * Output: 24 | * [ 25 | * [1,null,3,2], 26 | * [3,2,null,1], 27 | * [3,1,null,null,2], 28 | * [2,1,3], 29 | * [1,null,2,null,3] 30 | * ] 31 | * Explanation: 32 | * The above output corresponds to the 5 unique BST's shown below: 33 | * 34 | * ⁠ 1 3 3 2 1 35 | * ⁠ \ / / / \ \ 36 | * ⁠ 3 2 1 1 3 2 37 | * ⁠ / / \ \ 38 | * ⁠ 2 1 2 3 39 | * 40 | * 41 | */ 42 | /** 43 | * Example: 44 | * var ti = TreeNode(5) 45 | * var v = ti.`val` 46 | * Definition for a binary tree node. 47 | * class TreeNode(var `val`: Int) { 48 | * var left: TreeNode? = null 49 | * var right: TreeNode? = null 50 | * } 51 | */ 52 | class Solution { 53 | fun generateTrees(n: Int): List { 54 | if (n == 0) return mutableListOf() 55 | return dfs(1, n) 56 | } 57 | 58 | private fun dfs(l: Int, r: Int): List { 59 | if (l > r) { 60 | return mutableListOf(null) 61 | } 62 | var res = mutableListOf() 63 | for (root in l .. r) { 64 | var left = dfs(l, root-1) 65 | var right = dfs(root+1, r) 66 | 67 | for (x in left) 68 | for (y in right) { 69 | var temp = TreeNode(root) 70 | temp.left = x 71 | temp.right = y 72 | res.add(temp) 73 | } 74 | } 75 | return res 76 | } 77 | } 78 | 79 | -------------------------------------------------------------------------------- /medium/96.unique-binary-search-trees.kt: -------------------------------------------------------------------------------- 1 | `/* 2 | * @lc app=leetcode id=96 lang=kotlin 3 | * 4 | * [96] Unique Binary Search Trees 5 | * 6 | * https://leetcode.com/problems/unique-binary-search-trees/description/ 7 | * 8 | * algorithms 9 | * Medium (45.70%) 10 | * Total Accepted: 193.2K 11 | * Total Submissions: 422.5K 12 | * Testcase Example: '3' 13 | * 14 | * Given n, how many structurally unique BST's (binary search trees) that store 15 | * values 1 ... n? 16 | * 17 | * Example: 18 | * 19 | * 20 | * Input: 3 21 | * Output: 5 22 | * Explanation: 23 | * Given n = 3, there are a total of 5 unique BST's: 24 | * 25 | * ⁠ 1 3 3 2 1 26 | * ⁠ \ / / / \ \ 27 | * ⁠ 3 2 1 1 3 2 28 | * ⁠ / / \ \ 29 | * ⁠ 2 1 2 3 30 | * 31 | * 32 | */ 33 | class Solution { 34 | // catalan数:h(n) = h(n-1)*(4*n-2)/(n+1) 35 | fun numTrees(n: Int): Int { 36 | var x: Long = 1 37 | var res: Long = 1 38 | 39 | for (i in 1..n) { 40 | res = x*(4*i-2)/(i+1) 41 | x = res 42 | } 43 | return res.toInt() 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /medium/98.validate-binary-search-tree.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=98 lang=kotlin 3 | * 4 | * [98] Validate Binary Search Tree 5 | * 6 | * https://leetcode.com/problems/validate-binary-search-tree/description/ 7 | * 8 | * algorithms 9 | * Medium (26.08%) 10 | * Likes: 2177 11 | * Dislikes: 327 12 | * Total Accepted: 442.1K 13 | * Total Submissions: 1.7M 14 | * Testcase Example: '[2,1,3]' 15 | * 16 | * Given a binary tree, determine if it is a valid binary search tree (BST). 17 | * 18 | * Assume a BST is defined as follows: 19 | * 20 | * 21 | * The left subtree of a node contains only nodes with keys less than the 22 | * node's key. 23 | * The right subtree of a node contains only nodes with keys greater than the 24 | * node's key. 25 | * Both the left and right subtrees must also be binary search trees. 26 | * 27 | * 28 | * 29 | * 30 | * Example 1: 31 | * 32 | * 33 | * ⁠ 2 34 | * ⁠ / \ 35 | * ⁠ 1 3 36 | * 37 | * Input: [2,1,3] 38 | * Output: true 39 | * 40 | * 41 | * Example 2: 42 | * 43 | * 44 | * ⁠ 5 45 | * ⁠ / \ 46 | * ⁠ 1 4 47 | * / \ 48 | * 3 6 49 | * 50 | * Input: [5,1,4,null,null,3,6] 51 | * Output: false 52 | * Explanation: The root node's value is 5 but its right child's value is 4. 53 | * 54 | * 55 | */ 56 | /** 57 | * Example: 58 | * var ti = TreeNode(5) 59 | * var v = ti.`val` 60 | * Definition for a binary tree node. 61 | * class TreeNode(var `val`: Int) { 62 | * var left: TreeNode? = null 63 | * var right: TreeNode? = null 64 | * } 65 | */ 66 | class Solution { 67 | fun isValidBST(root: TreeNode?): Boolean { 68 | if (root == null) return true 69 | return valid(root, Long.MIN_VALUE, Long.MAX_VALUE) 70 | } 71 | 72 | private fun valid(root: TreeNode?, low: Long, high: Long): Boolean { 73 | if (root == null) return true 74 | if (root!!.`val` <= low || root!!.`val` >= high) return false 75 | return valid(root?.left, low, root!!.`val`.toLong()) && valid(root?.right, root!!.`val`.toLong(), high); 76 | } 77 | } 78 | 79 | --------------------------------------------------------------------------------