├── .gitignore ├── README.md ├── leetcode-1-two-sum.swift ├── leetcode-1008-construct-binary-search-tree-from-preorder-traversal.swift ├── leetcode-101-symmetric-tree.swift ├── leetcode-102-binary-tree-level-order-traversal.swift ├── leetcode-103-binary-tree-zigzag-level-order-traversal.swift ├── leetcode-104-maximum-depth-of-binary-tree.swift ├── leetcode-1167-minimum-cost-to-connect-sticks.swift ├── leetcode-12-integer-to-roman.swift ├── leetcode-121-best-time-to-buy-and-sell-stock.swift ├── leetcode-1232-check-if-it-is-a-straight-line.swift ├── leetcode-124-binary-tree-maximum-path-sum.swift ├── leetcode-1268-search-suggestions-system.swift ├── leetcode-127-word-ladder.swift ├── leetcode-1277-count-square-submatrices-with-all-ones.swift ├── leetcode-13-roman-to-integer.swift ├── leetcode-1347-minimum-number-of-steps-to-make-two-strings-anagram.swift ├── leetcode-138-copy-list-with-random-pointer.swift ├── leetcode-139-word-break.swift ├── leetcode-1431-kids-with-the-greatest-number-of-candies.swift ├── leetcode-144-binary-tree-preorder-traversal.swift ├── leetcode-1441-build-an-array-with-stack-operations.swift ├── leetcode-145-binary-tree-postorder-traversal.swift ├── leetcode-146-lru-cache.swift ├── leetcode-15-three-sum.swift ├── leetcode-155-min-stack.swift ├── leetcode-160-intersection-of-two-linked-lists.swift ├── leetcode-167-two-sum-II-input-array-is-sorted.swift ├── leetcode-173-binary-search-tree-iterator.swift ├── leetcode-189-rotate-array.swift ├── leetcode-199-binary-tree-right-side-view.swift ├── leetcode-2-add-two-numbers.swift ├── leetcode-20-valid-parentheses.swift ├── leetcode-200-number-of-islands.swift ├── leetcode-203-remove-linked-list-elements.swift ├── leetcode-206-reverse-linked-list.swift ├── leetcode-207-course-schedule.swift ├── leetcode-208-implement-trie-prefix-tree.swift ├── leetcode-21-merge-two-sorted-lists.swift ├── leetcode-210-course-schedule-ii.swift ├── leetcode-226-invert-binary-tree.swift ├── leetcode-23-merge-k-sorted-lists.swift ├── leetcode-230-kth-smallest-element-in-a-bst.swift ├── leetcode-231-power-of-two.swift ├── leetcode-232-implement-queue-using-stacks.swift ├── leetcode-234-palindrome-linked-list.swift ├── leetcode-236-lowest-common-ancestor-of-a-binary-tree.swift ├── leetcode-237-delete-node-in-a-linked-list.swift ├── leetcode-238-product-of-array-except-self.swift ├── leetcode-24-swap-nodes-in-pairs.swift ├── leetcode-240-search-a-2d-matrix-ii.swift ├── leetcode-252-meeting-room.swift ├── leetcode-253-meeting-rooms-ii.swift ├── leetcode-270-closest-binary-search-tree-value.swift ├── leetcode-286-walls-and-gates.swift ├── leetcode-293-flip-game.swift ├── leetcode-297-serialize-and-deserialize-binary-tree.swift ├── leetcode-3-longest-substring-without-repeating-characters.swift ├── leetcode-328-odd-even-linked-list.swift ├── leetcode-332-reconstruct-itinerary.swift ├── leetcode-334-reverse-string.swift ├── leetcode-347-top-k-frequent-elements.swift ├── leetcode-348-design-tic-tac-toe.swift ├── leetcode-349-intersection-of-two-arrays.swift ├── leetcode-367-valid-perfect-square.swift ├── leetcode-380-insert-delete-getrandom-o1.swift ├── leetcode-392-is-subsequence.swift ├── leetcode-402-remove-k-digits.swift ├── leetcode-403-frog-jump.swift ├── leetcode-412-fizz-buzz.swift ├── leetcode-42-trapping-rain-water.swift ├── leetcode-438-find-all-anagrams-in-a-string.swift ├── leetcode-443-string-compression.swift ├── leetcode-448-find-all-numbers-disappeared-in-an-array.swift ├── leetcode-451-sort-characters-by-frequence.swift ├── leetcode-48-rotate-image.swift ├── leetcode-49-group-anagrams.swift ├── leetcode-509-fibonacci-number.swift ├── leetcode-53-maximum-subarray.swift ├── leetcode-540-single-element-in-a-sorted-array.swift ├── leetcode-547-friend-circles.swift ├── leetcode-567-permutation-of-string.swift ├── leetcode-572-subtree-of-another-tree.swift ├── leetcode-58-length-of-last-word.swift ├── leetcode-637-average-of-levels-in-binry-tree.swift ├── leetcode-653-two-sum-iv-input-is-a-bst.swift ├── leetcode-657-robot-return-to-origin.swift ├── leetcode-692-top-k-frequent-words.swift ├── leetcode-695-max-area-of-island.swift ├── leetcode-70-climbing-stairs.swift ├── leetcode-700-search-in-a-binary-search-tree.swift ├── leetcode-706-design-hashmap.swift ├── leetcode-773-flood-fill.swift ├── leetcode-78-subsets.swift ├── leetcode-8-string-to-integer-atoi.swift ├── leetcode-811-subdomain-visit-count.swift ├── leetcode-819-most-common-word.swift ├── leetcode-844-backspace-string-compare.swift ├── leetcode-88-merge-sorted-array.swift ├── leetcode-918-maximum-sum-circular-subarray.swift ├── leetcode-937-reorder-data-in-log-files.swift ├── leetcode-94-binary-tree-inorder-traversal.swift ├── leetcode-957-prison-cells-after-n-days.swift ├── leetcode-966-vowel-spellchecker.swift ├── leetcode-973-k-closest-points-to-origin.swift ├── leetcode-98-validate-binary-search-tree.swift ├── leetcode-993-cousins-in-binary-tree.swift ├── leetcode-994-rotting-oranges.swift └── leetcode-997-find-the-town-judge.swift /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /leetcode-1-two-sum.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/two-sum/ 28 | 29 | 30 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 31 | 32 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 33 | 34 | Example: 35 | 36 | Given nums = [2, 7, 11, 15], target = 9, 37 | 38 | Because nums[0] + nums[1] = 2 + 7 = 9, 39 | return [0, 1]. 40 | 41 | */ 42 | 43 | /** 44 | Big O Annotation 45 | Time complexity O(n) where n is the amount of elements in nums. 46 | Space complexity O(n) where n is the amount of elements in nums. 47 | */ 48 | func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 49 | 50 | /** 51 | Creating a map for every element in nums 52 | with their respecitve indices. 53 | */ 54 | var map: [Int: Int] = [:] 55 | 56 | // Iterate through nums 57 | for (index, element) in nums.enumerated() { 58 | 59 | /** 60 | Check if we have a mapped element can be 61 | created when substracting the current target 62 | with the current element 63 | */ 64 | if let mapped = map[target - element] { 65 | 66 | // And return their indices 67 | return [mapped, index] 68 | } 69 | 70 | // Add the current element to the map 71 | map[element] = index 72 | } 73 | 74 | return [] 75 | } -------------------------------------------------------------------------------- /leetcode-1008-construct-binary-search-tree-from-preorder-traversal.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/ 28 | 29 | 30 | Return the root node of a binary search tree that matches the given preorder traversal. 31 | 32 | (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.) 33 | 34 | It's guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements. 35 | 36 | Example 1: 37 | 38 | Input: [8,5,1,7,10,12] 39 | Output: [8,5,10,1,7,null,12] 40 | 41 | 42 | 43 | Constraints: 44 | 45 | 1 <= preorder.length <= 100 46 | 1 <= preorder[i] <= 10^8 47 | The values of preorder are distinct. 48 | 49 | */ 50 | 51 | /** 52 | Big O Annotation 53 | Time complexity O(n) where n is the amount of elements in preorder. 54 | Space complexity O(1) we're not using any extra space. 55 | */ 56 | func bstFromPreorder(_ preorder: [Int]) -> TreeNode? { 57 | 58 | /** 59 | If there's nothing in the array, 60 | there's not gonna be a BST 61 | */ 62 | guard !preorder.isEmpty else { 63 | return nil 64 | } 65 | 66 | // Get the root node 67 | let root = TreeNode(preorder[0]) 68 | 69 | // Fill it with the remaining values... 70 | for i in 1.. [[Int]] { 54 | return traverseByLevel(root) ?? [] 55 | } 56 | 57 | func traverseByLevel(_ root: TreeNode?) -> [[Int]] { 58 | 59 | // Without a root, no levels 60 | guard let root = root else { 61 | return [] 62 | } 63 | 64 | // This will be our result array 65 | var values: [[Int]] = [] 66 | 67 | /** 68 | We need a queue of nodes and our current level 69 | starting at root and 0. 70 | */ 71 | var queue: [(TreeNode, Int)] = [(root, 0)] 72 | 73 | // The start and end point of our queue 74 | var start = queue.startIndex 75 | var end = queue.endIndex 76 | 77 | // While we have still work to do... 78 | while start < end { 79 | 80 | // Get the current node and level from the queue 81 | let (node, level) = queue[start] 82 | 83 | // If level is above the endIndex 84 | if level >= values.endIndex { 85 | 86 | // Add a new empty result array to values 87 | values.append([]) 88 | } 89 | 90 | // .. So we can access it and add the node's value 91 | values[level].append(node.val) 92 | 93 | // Then add the left node to the queue in the next level 94 | if let left = node.left { 95 | queue.append((left, level + 1)) 96 | } 97 | 98 | // Same for the right child node 99 | if let right = node.right { 100 | queue.append((right, level + 1)) 101 | } 102 | 103 | // Lastly set the end to our new end 104 | end = queue.endIndex 105 | 106 | // And move start forward 107 | start += 1 108 | } 109 | 110 | return values 111 | } -------------------------------------------------------------------------------- /leetcode-104-maximum-depth-of-binary-tree.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/maximum-depth-of-binary-tree/ 28 | 29 | 30 | Given a binary tree, find its maximum depth. 31 | 32 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 33 | 34 | Note: A leaf is a node with no children. 35 | 36 | Example: 37 | 38 | Given binary tree [3,9,20,null,null,15,7], 39 | 40 | 3 41 | / \ 42 | 9 20 43 | / \ 44 | 15 7 45 | return its depth = 3. 46 | 47 | */ 48 | 49 | /** 50 | Big O Annotation 51 | Time complexity O(n) where n is the amount of nodes in root. 52 | Space complexity O(1) we're not using any extra space. 53 | */ 54 | func maxDepth(_ root: TreeNode?) -> Int { 55 | 56 | // Init a 0 depth 57 | var depth: Int = 0 58 | 59 | /** 60 | Traverse through the whole tree 61 | and get the depth of every node 62 | */ 63 | traverse(root) { level in 64 | 65 | /** 66 | Compare to the current deepest depth 67 | and only keep the depeest one we have seen 68 | */ 69 | depth = max(depth, level) 70 | } 71 | 72 | return depth 73 | } 74 | 75 | /** 76 | Take in a node and a current depth level 77 | and in the close returns the depth level of every node. 78 | 79 | Will traverse the whole tree and be called recursively 80 | until there is no more node left. 81 | */ 82 | func traverse(_ node: TreeNode?, at level: Int = 1, visited: (Int) -> Void) { 83 | 84 | guard let node = node else {return } 85 | visited(level) 86 | traverse(node.left, at: level + 1, visited: visited) 87 | traverse(node.right, at: level + 1, visited: visited) 88 | } -------------------------------------------------------------------------------- /leetcode-12-integer-to-roman.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/integer-to-roman/ 28 | 29 | 30 | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. 31 | 32 | Symbol Value 33 | I 1 34 | V 5 35 | X 10 36 | L 50 37 | C 100 38 | D 500 39 | M 1000 40 | For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. 41 | 42 | Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: 43 | 44 | I can be placed before V (5) and X (10) to make 4 and 9. 45 | X can be placed before L (50) and C (100) to make 40 and 90. 46 | C can be placed before D (500) and M (1000) to make 400 and 900. 47 | Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. 48 | 49 | */ 50 | 51 | /** 52 | Big O Annotation 53 | Time complexity O(1). 54 | Space complexity O(1). 55 | */ 56 | func intToRoman(_ num: Int) -> String { 57 | 58 | let singles: [String] = ["","I","II","III","IV","V","VI","VII","VIII","IX"] 59 | let tens: [String] = ["","X","XX","XXX","XL","L","LX","LXX", "LXXX", "XC"] 60 | let hundreds: [String] = ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"] 61 | let thousands: [String] = ["","M","MM","MMM"] 62 | 63 | let romanThousands = thousands[num/1000] 64 | let romanHundreds = hundreds[num%1000/100] 65 | let romanTens = tens[num%100/10] 66 | let romanSingles = singles[num%10] 67 | 68 | return romanThousands + romanHundreds + romanTens + romanSingles 69 | } -------------------------------------------------------------------------------- /leetcode-121-best-time-to-buy-and-sell-stock.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 28 | 29 | 30 | Input: [7,1,5,3,6,4] 31 | Output: 5 32 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 33 | Not 7-1 = 6, as selling price needs to be larger than buying price. 34 | Example 2: 35 | 36 | Input: [7,6,4,3,1] 37 | Output: 0 38 | Explanation: In this case, no transaction is done, i.e. max profit = 0. 39 | 40 | */ 41 | 42 | /** 43 | Big O Annotation 44 | Time complexity O(n) where n is the amount of elements in prices. 45 | Space complexity O(1) we're not using any extra space. 46 | */ 47 | func maxProfit(_ prices: [Int]) -> Int { 48 | 49 | // Init a minimum reference to the maximum integer 50 | var minimum: Int = Int.max 51 | 52 | // This will be our returned profit 53 | var profit: Int = 0 54 | 55 | // For every element in prices... 56 | for (index, element) in prices.enumerated() { 57 | 58 | // Check if we have found a new mimimum value 59 | if element < minimum { 60 | 61 | // And update our local minimum 62 | minimum = element 63 | } else { 64 | 65 | /** 66 | And check if we could make a 67 | larger profit if we'd sell today 68 | */ 69 | profit = max(profit, element - minimum) 70 | } 71 | } 72 | 73 | return profit 74 | } -------------------------------------------------------------------------------- /leetcode-124-binary-tree-maximum-path-sum.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/binary-tree-maximum-path-sum/ 28 | 29 | 30 | Given a non-empty binary tree, find the maximum path sum. 31 | 32 | For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. 33 | 34 | Example 1: 35 | 36 | Input: [1,2,3] 37 | 38 | 1 39 | / \ 40 | 2 3 41 | 42 | Output: 6 43 | Example 2: 44 | 45 | Input: [-10,9,20,null,null,15,7] 46 | 47 | -10 48 | / \ 49 | 9 20 50 | / \ 51 | 15 7 52 | 53 | Output: 42 54 | 55 | */ 56 | 57 | /** 58 | Big O Annotation 59 | Time complexity O(n) where n is the amount of nodes in root. 60 | Space complexity O(1) we're not using any extra space but maxPathSum. 61 | */ 62 | func maxPathSum(_ root: TreeNode?) -> Int { 63 | 64 | // Get a Int.min max path to start with 65 | var maxPathSum = Int.min 66 | 67 | // Start the recursion 68 | getMaxPathSum(for: root, maxPathSum: &maxPathSum) 69 | 70 | // Return the final sum 71 | return maxPathSum 72 | } 73 | 74 | func getMaxPathSum(for node: TreeNode?, maxPathSum: inout Int) -> Int { 75 | 76 | // If there is no node, there's no sum 77 | guard let node = node else { 78 | return 0 79 | } 80 | 81 | /** 82 | Get the left branch's highest sum. 83 | It's important to check again max(0... to make 84 | sure that we're accounting for negative path sums. 85 | */ 86 | let left = max(0, getMaxPathSum(for: node.left, maxPathSum: &maxPathSum)) 87 | 88 | // Same on the right side... 89 | let right = max(0, getMaxPathSum(for: node.right, maxPathSum: &maxPathSum)) 90 | 91 | // Get the new maximum path sum 92 | maxPathSum = max(maxPathSum, left + right + node.val) 93 | 94 | // Return whatever branch is the larger + node.val 95 | return max(left, right) + node.val 96 | } -------------------------------------------------------------------------------- /leetcode-1347-minimum-number-of-steps-to-make-two-strings-anagram.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/ 28 | 29 | 30 | Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character. 31 | 32 | Return the minimum number of steps to make t an anagram of s. 33 | 34 | An Anagram of a string is a string that contains the same characters with a different (or the same) ordering. 35 | 36 | 37 | 38 | Example 1: 39 | 40 | Input: s = "bab", t = "aba" 41 | Output: 1 42 | Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s. 43 | Example 2: 44 | 45 | Input: s = "leetcode", t = "practice" 46 | Output: 5 47 | Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s. 48 | Example 3: 49 | 50 | Input: s = "anagram", t = "mangaar" 51 | Output: 0 52 | Explanation: "anagram" and "mangaar" are anagrams. 53 | Example 4: 54 | 55 | Input: s = "xxyyzz", t = "xxyyzz" 56 | Output: 0 57 | Example 5: 58 | 59 | Input: s = "friend", t = "family" 60 | Output: 4 61 | 62 | 63 | Constraints: 64 | 65 | 1 <= s.length <= 50000 66 | s.length == t.length 67 | s and t contain lower-case English letters only. 68 | 69 | */ 70 | 71 | /** 72 | Big O Annotation 73 | Time complexity O(n) where n is the amount of characters in the longest string. 74 | Space complexity O(n) where n is the amount of characters in t. 75 | */ 76 | func minSteps(_ s: String, _ t: String) -> Int { 77 | 78 | /** 79 | Init a new map depicting the characters 80 | and the amount in what they appear in t 81 | */ 82 | var hash: [Character: Int] = [:] 83 | 84 | // Iterate through string t 85 | for character in t { 86 | 87 | // And checked if it's in the map 88 | if let mapped = hash[character] { 89 | 90 | // If so, then increase the amount 91 | hash[character] = mapped + 1 92 | } else { 93 | 94 | // If not, set the amount to 0 95 | hash[character] = 1 96 | } 97 | } 98 | 99 | // Potential changes 100 | var changes: Int = 0 101 | 102 | // Iterate through s 103 | for character in s { 104 | 105 | // Check if the character is mapped 106 | if let mapped = hash[character] { 107 | 108 | // And decrease the available count 109 | let newSum = mapped - 1 110 | 111 | // Update or potentially set to nil 112 | hash[character] = (newSum > 0) ? newSum : nil 113 | 114 | } else { 115 | 116 | // If not, add 1 change 117 | changes += 1 118 | } 119 | } 120 | 121 | return changes 122 | } -------------------------------------------------------------------------------- /leetcode-138-copy-list-with-random-pointer.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/copy-list-with-random-pointer/ 28 | 29 | 30 | A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. 31 | 32 | Return a deep copy of the list. 33 | 34 | The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where: 35 | 36 | val: an integer representing Node.val 37 | random_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node. 38 | 39 | 40 | Example 1: 41 | 42 | 43 | Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] 44 | Output: [[7,null],[13,0],[11,4],[10,2],[1,0]] 45 | Example 2: 46 | 47 | 48 | Input: head = [[1,1],[2,1]] 49 | Output: [[1,1],[2,1]] 50 | Example 3: 51 | 52 | 53 | 54 | Input: head = [[3,null],[3,0],[3,null]] 55 | Output: [[3,null],[3,0],[3,null]] 56 | Example 4: 57 | 58 | Input: head = [] 59 | Output: [] 60 | Explanation: Given linked list is empty (null pointer), so return null. 61 | 62 | */ 63 | 64 | /** 65 | Big O Annotation 66 | Time complexity O(n) where n is the amount of nodes in head. 67 | Space complexity O(n) where n is the amount of nodes in head. 68 | */ 69 | func copyRandomList(_ head: Node?) -> Node? { 70 | 71 | /** 72 | Mutable reference of all the nodes 73 | to keep track of the random pointers 74 | */ 75 | var storage: [Node: Node] = [:] 76 | 77 | // Get a copy of the nodes themselves 78 | let copy = copyNode(head, storage: &storage) 79 | 80 | // And adjust the random pointers 81 | copyRandom(head, storage: &storage) 82 | 83 | return copy 84 | } 85 | 86 | func copyNode(_ node: Node?, storage: inout [Node: Node]) -> Node? { 87 | 88 | // Check if there is a node 89 | guard let node = node else { 90 | return nil 91 | } 92 | 93 | // If so, get a new one with same value 94 | let copy = Node(node.val) 95 | 96 | // Store the reference for that new node 97 | storage[node] = copy 98 | 99 | // And continue the recursion down the next elements 100 | copy.next = copyNode(node.next, storage: &storage) 101 | 102 | // Return the new node 103 | return copy 104 | } 105 | 106 | func copyRandom(_ node: Node?, storage: inout [Node: Node]) { 107 | 108 | // Make sure we have a node... 109 | guard let node = node else { 110 | return 111 | } 112 | 113 | // Get the random pointer for the current node 114 | if let random = node.random { 115 | 116 | // And assign it the new one 117 | storage[node]?.random = storage[random] 118 | } 119 | 120 | // And continue down the recursion 121 | copyRandom(node.next, storage: &storage) 122 | } -------------------------------------------------------------------------------- /leetcode-139-word-break.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/word-break/ 28 | 29 | 30 | Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. 31 | 32 | Note: 33 | 34 | The same word in the dictionary may be reused multiple times in the segmentation. 35 | You may assume the dictionary does not contain duplicate words. 36 | Example 1: 37 | 38 | Input: s = "leetcode", wordDict = ["leet", "code"] 39 | Output: true 40 | Explanation: Return true because "leetcode" can be segmented as "leet code". 41 | Example 2: 42 | 43 | Input: s = "applepenapple", wordDict = ["apple", "pen"] 44 | Output: true 45 | Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". 46 | Note that you are allowed to reuse a dictionary word. 47 | Example 3: 48 | 49 | Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] 50 | Output: false 51 | 52 | */ 53 | 54 | /** 55 | Big O Annotation 56 | Time complexity O(n) where n is the amount of elements in nums. 57 | Space complexity O(n) where n is the amount of elements in nums. 58 | */ 59 | func wordBreak(_ s: String, _ wordDict: [String]) -> Bool { 60 | 61 | // Get mutable copy of the string 62 | var s = s 63 | 64 | // Iterate through the list of words 65 | for element in wordDict { 66 | 67 | /** 68 | Try replacing the string's occurence 69 | of element with an empty "" 70 | */ 71 | let replaced = s.replacingOccurrences(of: element, with: "") 72 | 73 | // If we have't replaced anything, return false 74 | if replaced == s { 75 | return false 76 | } 77 | 78 | // Otherwise set string to the new one 79 | s = replaced 80 | } 81 | 82 | // The function succeeds if s is now empty. 83 | return s.isEmpty 84 | } -------------------------------------------------------------------------------- /leetcode-1431-kids-with-the-greatest-number-of-candies.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ 28 | 29 | 30 | Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has. 31 | 32 | For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies. 33 | 34 | 35 | 36 | Example 1: 37 | 38 | Input: candies = [2,3,5,1,3], extraCandies = 3 39 | Output: [true,true,true,false,true] 40 | Explanation: 41 | Kid 1 has 2 candies and if he or she receives all extra candies (3) will have 5 candies --- the greatest number of candies among the kids. 42 | Kid 2 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids. 43 | Kid 3 has 5 candies and this is already the greatest number of candies among the kids. 44 | Kid 4 has 1 candy and even if he or she receives all extra candies will only have 4 candies. 45 | Kid 5 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids. 46 | Example 2: 47 | 48 | Input: candies = [4,2,1,1,2], extraCandies = 1 49 | Output: [true,false,false,false,false] 50 | Explanation: There is only 1 extra candy, therefore only kid 1 will have the greatest number of candies among the kids regardless of who takes the extra candy. 51 | Example 3: 52 | 53 | Input: candies = [12,1,12], extraCandies = 10 54 | Output: [true,false,true] 55 | 56 | */ 57 | 58 | /** 59 | Big O Annotation 60 | Time complexity O(n log n) because of the sorting overhead. 61 | Space complexity O(n) as we're creating the sorted array. 62 | 63 | Space could be optimized by not sorting first, 64 | but iterating through the candies, getting the largest amount 65 | and then iterating again to calculate. 66 | */ 67 | func kidsWithCandies(_ candies: [Int], _ extraCandies: Int) -> [Bool] { 68 | 69 | /** 70 | If we don't have any candies then 71 | there's nothing to supply 72 | */ 73 | guard candies.count > 0 else { 74 | return [] 75 | } 76 | 77 | /** 78 | If we only have one candy, 79 | then that is automatically the largest. 80 | */ 81 | guard candies.count > 1 else { 82 | return [true] 83 | } 84 | 85 | // Sort so we have the largest at the end 86 | let sorted = candies.sorted() 87 | 88 | /** 89 | We can savely force unwrap the last item 90 | as we already checked if we have at least 2 items. 91 | */ 92 | let largestAmountOfCandy = sorted.last! 93 | 94 | // Results array 95 | var result: [Bool] = [] 96 | 97 | // Iterate through the candies 98 | for candy in candies { 99 | 100 | /** 101 | Calculate if the current candy + all the extra candies 102 | is at least equal to the largest amount of candy. 103 | */ 104 | let willHaveLargestAmount = (candy + extraCandies) >= largestAmountOfCandy 105 | result.append(willHaveLargestAmount) 106 | } 107 | 108 | return result 109 | } -------------------------------------------------------------------------------- /leetcode-144-binary-tree-preorder-traversal.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/binary-tree-preorder-traversal/ 28 | 29 | 30 | Given a binary tree, return the preorder traversal of its nodes' values. 31 | 32 | Example: 33 | 34 | Input: [1,null,2,3] 35 | 1 36 | \ 37 | 2 38 | / 39 | 3 40 | 41 | Output: [1,2,3] 42 | Follow up: Recursive solution is trivial, could you do it iteratively? 43 | 44 | */ 45 | 46 | /** 47 | Big O Annotation 48 | Time complexity O(n) where n is the amount of nodes in root. 49 | Space complexity O(n) where n is the amount of nodes in root. 50 | */ 51 | func inorderTraversal(_ root: TreeNode?) -> [Int] { 52 | 53 | var result: [Int] = [] 54 | root?.traversePostOrder { result.append($0) } 55 | return result 56 | } 57 | 58 | extension TreeNode { 59 | 60 | /** 61 | Will be called recursively 62 | until the whole tree is traversed. 63 | */ 64 | func traversePreOrder(_ visit: (Int) -> Void) { 65 | 66 | // Pre order starts at the current node 67 | visit(val) 68 | 69 | // Then moves down the left branch 70 | left?.traversePreOrder(visit) 71 | 72 | // And lastly the right branch 73 | right?.traversePreOrder(visit) 74 | } 75 | } -------------------------------------------------------------------------------- /leetcode-1441-build-an-array-with-stack-operations.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/contest/weekly-contest-188/problems/build-an-array-with-stack-operations/ 28 | 29 | 30 | Given an array target and an integer n. In each iteration, you will read a number from list = {1,2,3..., n}. 31 | 32 | Build the target array using the following operations: 33 | 34 | Push: Read a new element from the beginning list, and push it in the array. 35 | Pop: delete the last element of the array. 36 | If the target array is already built, stop reading more elements. 37 | You are guaranteed that the target array is strictly increasing, only containing numbers between 1 to n inclusive. 38 | 39 | Return the operations to build the target array. 40 | 41 | You are guaranteed that the answer is unique. 42 | 43 | 44 | 45 | Example 1: 46 | 47 | Input: target = [1,3], n = 3 48 | Output: ["Push","Push","Pop","Push"] 49 | Explanation: 50 | Read number 1 and automatically push in the array -> [1] 51 | Read number 2 and automatically push in the array then Pop it -> [1] 52 | Read number 3 and automatically push in the array -> [1,3] 53 | Example 2: 54 | 55 | Input: target = [1,2,3], n = 3 56 | Output: ["Push","Push","Push"] 57 | Example 3: 58 | 59 | Input: target = [1,2], n = 4 60 | Output: ["Push","Push"] 61 | Explanation: You only need to read the first 2 numbers and stop. 62 | Example 4: 63 | 64 | Input: target = [2,3,4], n = 4 65 | Output: ["Push","Pop","Push","Push","Push"] 66 | 67 | 68 | Constraints: 69 | 70 | 1 <= target.length <= 100 71 | 1 <= target[i] <= 100 72 | 1 <= n <= 100 73 | target is strictly increasing. 74 | 75 | */ 76 | 77 | /** 78 | Big O Annotation 79 | Time complexity O(n) where n is the amount of elements between 1 and n. 80 | Space complexity O(n) where n is the amount of elements in target. 81 | */ 82 | func buildArray(_ target: [Int], _ n: Int) -> [String] { 83 | 84 | /** 85 | Init a Set from the target array 86 | for O(1) constant .contains operation 87 | */ 88 | let asSet: Set = Set(target) 89 | 90 | // All performed operations 91 | var operations: [String] = [] 92 | 93 | // Reference to the currently created array 94 | var currentTarget: [Int] = [] 95 | 96 | // Iterate from 1 up to including n 97 | for element in 1...n { 98 | 99 | // Add a "Push" operation... 100 | operations.append("Push") 101 | 102 | // ... and add the element to the target reference 103 | currentTarget.append(element) 104 | 105 | // Check if the set contains the current element... 106 | if !asSet.contains(element) { 107 | 108 | // ... and if not, add a "Pop" operation 109 | operations.append("Pop") 110 | 111 | // and actually pop from the reference array 112 | currentTarget.popLast() 113 | } 114 | 115 | /** 116 | Check if our reference and the target 117 | match to be able to return early 118 | */ 119 | if currentTarget == target { 120 | return operations 121 | } 122 | } 123 | 124 | return operations 125 | } -------------------------------------------------------------------------------- /leetcode-145-binary-tree-postorder-traversal.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/binary-tree-postorder-traversal/ 28 | 29 | 30 | Given a binary tree, return the postorder traversal of its nodes' values. 31 | 32 | Example: 33 | 34 | Input: [1,null,2,3] 35 | 1 36 | \ 37 | 2 38 | / 39 | 3 40 | 41 | Output: [3,2,1] 42 | Follow up: Recursive solution is trivial, could you do it iteratively? 43 | 44 | */ 45 | 46 | /** 47 | Big O Annotation 48 | Time complexity O(n) where n is the amount of nodes in root. 49 | Space complexity O(n) where n is the amount of nodes in root. 50 | */ 51 | func inorderTraversal(_ root: TreeNode?) -> [Int] { 52 | 53 | var result: [Int] = [] 54 | root?.traversePostOrder { result.append($0) } 55 | return result 56 | } 57 | 58 | extension TreeNode { 59 | 60 | /** 61 | Will be called recursively 62 | until the whole tree is traversed. 63 | */ 64 | func traversePostOrder(_ visit: (Int) -> Void) { 65 | 66 | // Post order starts at the left branch 67 | left?.traversePostOrder(visit) 68 | 69 | // Then moves to the right branch 70 | right?.traversePostOrder(visit) 71 | 72 | // And lastly visits the current node 73 | visit(val) 74 | } 75 | } -------------------------------------------------------------------------------- /leetcode-15-three-sum.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/3sum/ 28 | 29 | 30 | Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 31 | 32 | Note: 33 | 34 | The solution set must not contain duplicate triplets. 35 | 36 | Example: 37 | 38 | Given array nums = [-1, 0, 1, 2, -1, -4], 39 | 40 | A solution set is: 41 | [ 42 | [-1, 0, 1], 43 | [-1, -1, 2] 44 | ] 45 | 46 | */ 47 | 48 | /** 49 | Big O Annotation 50 | Time complexity O(n^2) where n is the amount of elements in nums. 51 | Space complexity O(1) where n is the amount of elements in nums. 52 | */ 53 | func threeSum(_ nums: [Int]) -> [[Int]] { 54 | 55 | var subsets: [[Int]] = [] 56 | 57 | /** 58 | Get a mutable reference of nums 59 | and sort to improve BigO from O^3 to O^2 60 | */ 61 | var nums = nums 62 | nums.sort() 63 | 64 | // Iterate through nums 65 | for (index, element) in nums.enumerated() { 66 | 67 | var firstIndex = index + 1 68 | var lastIndex = nums.count - 1 69 | 70 | /** 71 | If the element at index is the same 72 | as the element before, 73 | we will skip as we can ignore 74 | duplicates. 75 | 76 | We already know the outcome. 77 | */ 78 | if index > 0 && element == nums[index - 1] { 79 | continue 80 | } 81 | 82 | /** 83 | Inner loop while start 84 | is smaller than end. 85 | */ 86 | while firstIndex < lastIndex { 87 | 88 | /** 89 | Like above we want to skip 90 | repeating elements at the end. 91 | */ 92 | if lastIndex < nums.count - 1 && nums[lastIndex] == nums[lastIndex + 1] { 93 | lastIndex -= 1 94 | continue 95 | } 96 | 97 | // Get the sum of the current element and the two pointers 98 | let sum = element + nums[firstIndex] + nums[lastIndex] 99 | 100 | // If sum is 0 101 | if sum == 0 { 102 | 103 | // Add to subsets 104 | subsets.append([element, nums[firstIndex], nums[lastIndex]]) 105 | 106 | // And move both pointers along 107 | firstIndex += 1 108 | lastIndex -= 1 109 | 110 | // Otherwise move either the front... 111 | } else if sum < 0 { 112 | 113 | firstIndex += 1 114 | 115 | // ... or end pointer along 116 | } else { 117 | lastIndex -= 1 118 | } 119 | } 120 | } 121 | 122 | return subsets 123 | } -------------------------------------------------------------------------------- /leetcode-160-intersection-of-two-linked-lists.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/intersection-of-two-linked-lists/ 28 | 29 | 30 | Write a program to find the node at which the intersection of two singly linked lists begins. 31 | 32 | For example, the following two linked lists: 33 | 34 | 35 | begin to intersect at node c1. 36 | 37 | 38 | 39 | Example 1: 40 | 41 | 42 | Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 43 | Output: Reference of the node with value = 8 44 | Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. 45 | 46 | */ 47 | 48 | /** 49 | Big O Annotation 50 | Time complexity O(n) where n is the combined number of elements in headA and headB. 51 | Space complexity O(n) where n is the combined number of elements in headA and headB. 52 | */ 53 | func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? { 54 | 55 | var valueListA: Set = [] 56 | var inserSection: ListNode? 57 | 58 | // Traverse A into the Set 59 | headA?.traverse { valueListA.insert($0) } 60 | 61 | // Traverse B and get the intersection 62 | headB?.traverse { node in 63 | 64 | /** 65 | Make sure to not overwrite with later nodes 66 | as that would not be the intersection but 67 | common nodes. 68 | 69 | We could optimize this by interrupting the close calls 70 | and directly returning. 71 | */ 72 | if valueListA.contains(node) && inserSection == nil { 73 | inserSection = node 74 | } 75 | } 76 | 77 | return inserSection 78 | } 79 | 80 | extension ListNode { 81 | 82 | // Function to traverse the list 83 | func traverse(visit: (ListNode) -> Void) { 84 | visit(self) 85 | next?.traverse(visit: visit) 86 | } 87 | } 88 | 89 | /** 90 | Conform ListNode to Hashable to use in a Set 91 | and to take advantage of constant contains operation. 92 | 93 | Using ObjectIdentifier to use the memory reference for equality. 94 | */ 95 | extension ListNode: Hashable { 96 | 97 | public static func == (lhs: ListNode, rhs: ListNode) -> Bool { 98 | return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) 99 | } 100 | 101 | public func hash(into hasher: inout Hasher) { 102 | hasher.combine(val) 103 | } 104 | } -------------------------------------------------------------------------------- /leetcode-167-two-sum-II-input-array-is-sorted.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ 28 | 29 | 30 | Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. 31 | 32 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. 33 | 34 | Note: 35 | 36 | Your returned answers (both index1 and index2) are not zero-based. 37 | You may assume that each input would have exactly one solution and you may not use the same element twice. 38 | Example: 39 | 40 | Input: numbers = [2,7,11,15], target = 9 41 | Output: [1,2] 42 | Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. 43 | 44 | */ 45 | 46 | /** 47 | Big O Annotation 48 | Time complexity O(n) where n is the amount of elements in nums. 49 | Space complexity O(n) where n is the amount of elements in nums. 50 | */ 51 | func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 52 | 53 | /** 54 | Creating a map for every element in nums 55 | with their respecitve indices. 56 | */ 57 | var map: [Int: Int] = [:] 58 | 59 | // Iterate through nums 60 | for (index, element) in nums.enumerated() { 61 | 62 | /** 63 | Check if we have a mapped element can be 64 | created when substracting the current target 65 | with the current element 66 | */ 67 | if let mapped = map[target - element] { 68 | 69 | // And return their indices each +1 70 | return [mapped + 1, index + 1] 71 | } 72 | 73 | // Add the current element to the map 74 | map[element] = index 75 | } 76 | 77 | return [] 78 | } -------------------------------------------------------------------------------- /leetcode-173-binary-search-tree-iterator.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/binary-search-tree-iterator/ 28 | 29 | 30 | Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. 31 | 32 | Calling next() will return the next smallest number in the BST. 33 | 34 | 35 | 36 | Example: 37 | 38 | 39 | 40 | BSTIterator iterator = new BSTIterator(root); 41 | iterator.next(); // return 3 42 | iterator.next(); // return 7 43 | iterator.hasNext(); // return true 44 | iterator.next(); // return 9 45 | iterator.hasNext(); // return true 46 | iterator.next(); // return 15 47 | iterator.hasNext(); // return true 48 | iterator.next(); // return 20 49 | iterator.hasNext(); // return false 50 | 51 | 52 | Note: 53 | 54 | next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. 55 | You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called. 56 | 57 | */ 58 | 59 | /** 60 | Big O Annotation 61 | Time complexity of the init is O(n) where n is the amount of nodes in root 62 | Space complexity O(n) where n is the amount of nodes in root 63 | 64 | Every other operation has O(1) time complexity. 65 | */ 66 | class BSTIterator { 67 | 68 | private var stack: [Int] = [] 69 | 70 | init(_ root: TreeNode?) { 71 | 72 | // Get a queue of the reversed in order 73 | traverse(root) { stack.append($0) } 74 | } 75 | 76 | /** @return the next smallest number */ 77 | public func next() -> Int { 78 | return stack.popLast() ?? 0 79 | } 80 | 81 | /** @return whether we have a next smallest number */ 82 | public func hasNext() -> Bool { 83 | return !stack.isEmpty 84 | } 85 | 86 | // Traverse the BST reversed in order 87 | private func traverse(_ node: TreeNode?, _ visit: (Int) -> Void) { 88 | guard let node = node else { return } 89 | traverse(node.right, visit) 90 | visit(node.val) 91 | traverse(node.left, visit) 92 | } 93 | } 94 | 95 | /** 96 | * Your BSTIterator object will be instantiated and called as such: 97 | * let obj = BSTIterator(root) 98 | * let ret_1: Int = obj.next() 99 | * let ret_2: Bool = obj.hasNext() 100 | */ -------------------------------------------------------------------------------- /leetcode-189-rotate-array.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/rotate-array/ 28 | 29 | 30 | Given an array, rotate the array to the right by k steps, where k is non-negative. 31 | 32 | Follow up: 33 | 34 | Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 35 | Could you do it in-place with O(1) extra space? 36 | 37 | 38 | Example 1: 39 | 40 | Input: nums = [1,2,3,4,5,6,7], k = 3 41 | Output: [5,6,7,1,2,3,4] 42 | Explanation: 43 | rotate 1 steps to the right: [7,1,2,3,4,5,6] 44 | rotate 2 steps to the right: [6,7,1,2,3,4,5] 45 | rotate 3 steps to the right: [5,6,7,1,2,3,4] 46 | Example 2: 47 | 48 | Input: nums = [-1,-100,3,99], k = 2 49 | Output: [3,99,-1,-100] 50 | Explanation: 51 | rotate 1 steps to the right: [99,-1,-100,3] 52 | rotate 2 steps to the right: [3,99,-1,-100] 53 | 54 | 55 | Constraints: 56 | 57 | 1 <= nums.length <= 2 * 10^4 58 | It's guaranteed that nums[i] fits in a 32 bit-signed integer. 59 | k >= 0 60 | 61 | */ 62 | 63 | /** 64 | Big O Annotation 65 | Time complexity O(kn) k for the iterations and n for the insert at 0 operation. 66 | Space complexity O(1) where not using any extra space but the popped element. 67 | */ 68 | func rotate(_ nums: inout [Int], _ k: Int) { 69 | 70 | /** 71 | Without elements in nums 72 | there's nothing to do... 73 | */ 74 | guard nums.count > 0 else { 75 | return 76 | } 77 | 78 | // Iterate through 0 until k-1 79 | for _ in 0.. ListNode? { 49 | 50 | // Get a mutable reference to each head of l1 and l2 51 | var currentL1: ListNode? = l1 52 | var currentL2: ListNode? = l2 53 | 54 | // Create a reference to a node we're going to append on 55 | var sumList: ListNode? = ListNode(-1) 56 | 57 | // And a reference to its head 58 | var head: ListNode? = sumList 59 | 60 | // The carry for values > 9 61 | var carry: Int = 0 62 | 63 | // While we haven't fully iterated both lists yet... 64 | while currentL1 != nil || currentL2 != nil { 65 | 66 | /** 67 | Get a dummy value of 0 for each list 68 | in the niche case that either list 69 | is longer than the other. 70 | */ 71 | var value1: Int = 0 72 | var value2: Int = 0 73 | 74 | // Replace with l1's value if it exists 75 | if let l1 = currentL1 { 76 | value1 = l1.val 77 | } 78 | 79 | // Same for l2 80 | if let l2 = currentL2 { 81 | value2 = l2.val 82 | } 83 | 84 | // Sum up both values and the last carry 85 | let sum: Int = value1 + value2 + carry 86 | 87 | // Get the value < 10 88 | let value = sum % 10 89 | 90 | // Get the carry if above 10 91 | carry = sum / 10 92 | 93 | // Add a node with the new value 94 | sumList?.next = ListNode(value) 95 | 96 | // And move the head reference 97 | sumList = sumList?.next 98 | 99 | // Move l1 and l2 along as well 100 | currentL1 = currentL1?.next 101 | currentL2 = currentL2?.next 102 | } 103 | 104 | // If we still have carry left 105 | if carry > 0 { 106 | /** 107 | Add a node for the carry. 108 | This case could happen on 109 | (9 -> 9) + (1) = (0 -> 0 -> 1) 110 | */ 111 | sumList?.next = ListNode(carry) 112 | } 113 | 114 | // Return head.next to lose the -1 dummy head 115 | return head?.next 116 | } -------------------------------------------------------------------------------- /leetcode-20-valid-parentheses.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/valid-parentheses/ 28 | 29 | 30 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 31 | 32 | An input string is valid if: 33 | 34 | Open brackets must be closed by the same type of brackets. 35 | Open brackets must be closed in the correct order. 36 | Note that an empty string is also considered valid. 37 | 38 | 39 | 40 | 41 | Example 1: 42 | 43 | Input: "()" 44 | Output: true 45 | Example 2: 46 | 47 | Input: "()[]{}" 48 | Output: true 49 | Example 3: 50 | 51 | Input: "(]" 52 | Output: false 53 | Example 4: 54 | 55 | Input: "([)]" 56 | Output: false 57 | Example 5: 58 | 59 | Input: "{[]}" 60 | Output: true 61 | 62 | */ 63 | 64 | /** 65 | Big O Annotation 66 | Time complexity O(n) where n is the amount of characters in s. 67 | Space complexity O(n log n) as we're 68 | always at most holding 1/2 of characters in n 69 | */ 70 | func isValid(_ s: String) -> Bool { 71 | 72 | // Init a Character Stack 73 | var stack = Stack() 74 | 75 | // Iterate through given string 76 | for character in s { 77 | 78 | // Check if the character is (, { or [ 79 | if isOpen(character) { 80 | 81 | // If so put into the stack 82 | stack.push(character) 83 | 84 | } else { 85 | 86 | // Pop the last element of the stack 87 | guard let element = stack.pop() else { 88 | return false 89 | } 90 | 91 | // Check if it's the desired counter part 92 | if !isOpposite(character, of: element) { 93 | return false 94 | } 95 | } 96 | } 97 | 98 | // Check if the Stack is empty 99 | // If not then we did not close all brackets 100 | return stack.isEmpty 101 | } 102 | 103 | func isOpen(_ character: Character) -> Bool { 104 | return character == "(" || 105 | character == "{" || 106 | character == "[" 107 | } 108 | 109 | func isOpposite(_ character: Character, of stackElement: Character) -> Bool { 110 | if character == ")" { 111 | return stackElement == "(" 112 | } 113 | 114 | if character == "}" { 115 | return stackElement == "{" 116 | } 117 | 118 | // character must be ] 119 | return stackElement == "[" 120 | } 121 | 122 | struct Stack { 123 | private var array: [Element] 124 | 125 | public var peek: Element? { 126 | return array.last 127 | } 128 | 129 | public var isEmpty: Bool { 130 | return array.isEmpty 131 | } 132 | 133 | init() { 134 | array = [] 135 | } 136 | 137 | mutating public func push(_ element: Element) { 138 | array.append(element) 139 | } 140 | 141 | mutating public func pop() -> Element? { 142 | return array.popLast() 143 | } 144 | } -------------------------------------------------------------------------------- /leetcode-200-number-of-islands.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/number-of-islands/ 28 | 29 | 30 | Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 31 | 32 | Example 1: 33 | 34 | Input: 35 | 11110 36 | 11010 37 | 11000 38 | 00000 39 | 40 | Output: 1 41 | Example 2: 42 | 43 | Input: 44 | 11000 45 | 11000 46 | 00100 47 | 00011 48 | 49 | Output: 3 50 | 51 | */ 52 | 53 | /** 54 | Big O Annotation 55 | Time complexity O(n) where n is the total amount of elements in the 2D array. 56 | Space complexity O(n) as we're creating a mutable copy of the given grid. 57 | */ 58 | func numIslands(_ grid: [[Character]]) -> Int { 59 | 60 | /** 61 | If the grid is empty we're 62 | not going to have any islands 63 | */ 64 | guard grid.count > 0 && grid[0].count > 0 else { 65 | return 0 66 | } 67 | 68 | var numberOfIslands: Int = 0 69 | 70 | /** 71 | Create a mutable copy of the grid 72 | so we can flatten the islands 73 | */ 74 | var grid = grid 75 | 76 | // Iterate through the grid 77 | for (i, row) in grid.enumerated() { 78 | 79 | // Iterate through each row in the gid 80 | for (j, column) in row.enumerated() { 81 | 82 | // If we have found an island... 83 | if column == "1" { 84 | 85 | // ... we'll count and flatten it 86 | numberOfIslands += flattenIsland(in: &grid, at: i, and: j) 87 | } 88 | } 89 | } 90 | 91 | return numberOfIslands 92 | } 93 | 94 | /** 95 | Function to flatten any island. 96 | discardableResult as we don't need the result. 97 | To mute warnings. 98 | */ 99 | @discardableResult 100 | func flattenIsland(in grid: inout [[Character]], at row: Int, and column: Int) -> Int { 101 | 102 | // Check that we'renot off bounds top and left 103 | guard row >= 0 && column >= 0 else { 104 | return 0 105 | } 106 | 107 | // Check that we're not off bounds right and bottom 108 | guard row < grid.count && column < grid[row].count else { 109 | return 0 110 | } 111 | 112 | // Check if the current element is part of an island 113 | guard grid[row][column] == "1" else { 114 | return 0 115 | } 116 | 117 | // Flatten it 118 | grid[row][column] = "0" 119 | 120 | // Flatten surrounding islands 121 | flattenIsland(in: &grid, at: row + 1, and: column) 122 | flattenIsland(in: &grid, at: row - 1, and: column) 123 | flattenIsland(in: &grid, at: row, and: column + 1) 124 | flattenIsland(in: &grid, at: row, and: column - 1) 125 | 126 | // Return 1 to only cound for 1 island 127 | return 1 128 | } -------------------------------------------------------------------------------- /leetcode-206-reverse-linked-list.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/reverse-linked-list/ 28 | 29 | 30 | Reverse a singly linked list. 31 | 32 | Example: 33 | 34 | Input: 1->2->3->4->5->NULL 35 | Output: 5->4->3->2->1->NULL 36 | Follow up: 37 | 38 | A linked list can be reversed either iteratively or recursively. Could you implement both? 39 | 40 | */ 41 | 42 | /** 43 | Big O Annotation 44 | Time complexity O(n) where n is the amount of node in head. 45 | Space complexity O(n) where n is the amount of node in head. 46 | */ 47 | func reverseList(_ head: ListNode?) -> ListNode? { 48 | 49 | // Withouta head nothing to reverse 50 | guard let originalHead = head else { 51 | return nil 52 | } 53 | 54 | var values: [Int] = [] 55 | 56 | // Create a new dummy root 57 | var root: ListNode? = ListNode(-1) 58 | 59 | // And store the reference to the head 60 | var head: ListNode? = root 61 | 62 | // Traverse the original list 63 | originalHead.traverse { values.append($0) } 64 | 65 | // And while the list of values is not empty... 66 | while !values.isEmpty { 67 | 68 | // ... get the last element of the array 69 | guard let value = values.popLast() else { 70 | break 71 | } 72 | 73 | // Add it as the next element of the current node 74 | root?.next = ListNode(value) 75 | 76 | // And set the current node as the next "current" 77 | root = root?.next 78 | } 79 | 80 | /** 81 | Return the next of head to 82 | lose the -1 temp node 83 | */ 84 | return head?.next 85 | } 86 | 87 | extension ListNode { 88 | 89 | // Function to traverse the list 90 | func traverse(visit: (Int) -> Void) { 91 | visit(val) 92 | next?.traverse(visit: visit) 93 | } 94 | } -------------------------------------------------------------------------------- /leetcode-21-merge-two-sorted-lists.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problemset/all/ 28 | 29 | 30 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 31 | 32 | Example: 33 | 34 | Input: 1->2->4, 1->3->4 35 | Output: 1->1->2->3->4->4 36 | 37 | */ 38 | 39 | /** 40 | Big O Annotation 41 | Time complexity O(n) where n is the combined amount of nodes in l1 + l2. 42 | Space complexity O(n) where n is the combined amount of nodes in l1 + l2. 43 | */ 44 | func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { 45 | 46 | // Check if l1 exists 47 | guard let l1 = l1 else { 48 | return l2 49 | } 50 | 51 | // Check if l2 exists 52 | guard let l2 = l2 else { 53 | return l1 54 | } 55 | 56 | // Get a current node reference and a head to lose 57 | var current: ListNode? = ListNode(-1) 58 | 59 | // Keep a reference of the head 60 | var head: ListNode = current! 61 | 62 | // Get the current list references 63 | var currentL1: ListNode? = l1 64 | var currentL2: ListNode? = l2 65 | 66 | // While both lists still have work to do 67 | while currentL1 != nil && currentL2 != nil { 68 | 69 | // Check if l1 is smaller or l2 70 | if currentL1!.val <= currentL2!.val { 71 | 72 | // Append the smaller element 73 | current!.next = currentL1 74 | 75 | // And update the reference 76 | currentL1 = currentL1!.next 77 | } else { 78 | 79 | // Same as above 80 | current!.next = currentL2 81 | currentL2 = currentL2!.next 82 | } 83 | 84 | // Move current along 85 | current = current?.next 86 | } 87 | 88 | // And append missing elements 89 | if let list = currentL1 { 90 | current?.next = list 91 | } 92 | 93 | // Sane as above 94 | if let list = currentL2 { 95 | current?.next = list 96 | } 97 | 98 | // Return head.next to lose the -1 node 99 | return head.next 100 | } -------------------------------------------------------------------------------- /leetcode-23-merge-k-sorted-lists.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/merge-k-sorted-lists/ 28 | 29 | 30 | Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 31 | 32 | Example: 33 | 34 | Input: 35 | [ 36 | 1->4->5, 37 | 1->3->4, 38 | 2->6 39 | ] 40 | Output: 1->1->2->3->4->4->5->6 41 | 42 | */ 43 | 44 | /** 45 | Big O Annotation 46 | Time complexity O(n log n) where n is the total amount of nodes in all lists. 47 | The complexity is "n log n" because of the sort of the final array. 48 | Space complexity O(n) where n is the total amount of nodes in all lists. 49 | 50 | We're dropping the none dominant Swift sort term O(log n) 51 | */ 52 | func mergeKLists(_ lists: [ListNode?]) -> ListNode? { 53 | 54 | // Temporary array to store the given values 55 | var values: [Int] = [] 56 | 57 | // Iterate through the lists 58 | for list in lists { 59 | 60 | /** 61 | Traverse each list and 62 | add value to our array 63 | */ 64 | list?.traverse { values.append($0) } 65 | } 66 | 67 | /** 68 | Create a new root node with value -1. 69 | We will drop this node later. 70 | */ 71 | var root: ListNode? = ListNode(-1) 72 | 73 | // Store a reference to the new root 74 | var head: ListNode? = root 75 | 76 | // Sort the values array 77 | values.sort() 78 | 79 | // Iterate through the values 80 | for value in values { 81 | 82 | /** 83 | Create a new node for every value 84 | and set it as the existing node's next. 85 | */ 86 | root?.next = ListNode(value) 87 | 88 | /** 89 | Set this new node as the new current node 90 | for the next iteration 91 | */ 92 | root = root?.next 93 | } 94 | 95 | /** 96 | Return the head's next to 97 | drop the -1 temporary node 98 | */ 99 | return head?.next 100 | } 101 | 102 | extension ListNode { 103 | 104 | // Simple function to traverse the list 105 | func traverse(_ value: (Int) -> Void) { 106 | value(val) 107 | next?.traverse(value) 108 | } 109 | } -------------------------------------------------------------------------------- /leetcode-230-kth-smallest-element-in-a-bst.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/kth-smallest-element-in-a-bst/ 28 | 29 | 30 | Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. 31 | 32 | Note: 33 | You may assume k is always valid, 1 ≤ k ≤ BST's total elements. 34 | 35 | Example 1: 36 | 37 | Input: root = [3,1,4,null,2], k = 1 38 | 3 39 | / \ 40 | 1 4 41 | \ 42 | 2 43 | Output: 1 44 | Example 2: 45 | 46 | Input: root = [5,3,6,2,4,null,null,1], k = 3 47 | 5 48 | / \ 49 | 3 6 50 | / \ 51 | 2 4 52 | / 53 | 1 54 | Output: 3 55 | Follow up: 56 | What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine? 57 | 58 | */ 59 | 60 | /** 61 | Big O Annotation 62 | Time complexity O(n) where n is the amount of elements in nums. 63 | Space complexity O(n) where n is the amount of elements in nums. 64 | 65 | I guess since it's a BST we could speed this up by 66 | checking the left side of the Tree, see if we get enough values to match k. 67 | If so, return that, otherwise get the right side as well. 68 | 69 | But I think this is O(n) and fairly good enough for the challenge. 70 | It got us into the 50% range 🤷🏻‍♂️ 71 | 72 | I might improve later on. 73 | */ 74 | func kthSmallest(_ root: TreeNode?, _ k: Int) -> Int { 75 | 76 | // The BSTs values... 77 | var values: [Int] = [] 78 | 79 | // Traversed... 80 | root?.traverse { values.append($0)} 81 | 82 | // Sorted and returned 83 | return values.sorted()[k - 1] 84 | } 85 | 86 | // Simple Pre order traversal 87 | extension TreeNode { 88 | func traverse(_ visit: (Int) -> Void) { 89 | visit(val) 90 | left?.traverse(visit) 91 | right?.traverse(visit) 92 | } 93 | } -------------------------------------------------------------------------------- /leetcode-231-power-of-two.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/power-of-two/ 28 | 29 | 30 | Given an integer, write a function to determine if it is a power of two. 31 | 32 | Example 1: 33 | 34 | Input: 1 35 | Output: true 36 | Explanation: 20 = 1 37 | Example 2: 38 | 39 | Input: 16 40 | Output: true 41 | Explanation: 24 = 16 42 | Example 3: 43 | 44 | Input: 218 45 | Output: false 46 | 47 | */ 48 | 49 | /** 50 | Big O Annotation 51 | Time complexity O(n) where n is the amount of calculations up to n. 52 | Space complexity O(1) we're using constant space in the "last" variable. 53 | */ 54 | func isPowerOfTwo(_ n: Int) -> Bool { 55 | 56 | guard n != 1 && n != 2 else { 57 | return true 58 | } 59 | 60 | var last: Int = 2 61 | 62 | for index in 2...Int.max { 63 | 64 | let current = last * 2 65 | 66 | if current == n { 67 | return true 68 | } 69 | 70 | if current > n { 71 | return false 72 | } 73 | 74 | last = current 75 | } 76 | 77 | return false 78 | } -------------------------------------------------------------------------------- /leetcode-232-implement-queue-using-stacks.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/implement-queue-using-stacks/ 28 | 29 | 30 | Implement the following operations of a queue using stacks. 31 | 32 | push(x) -- Push element x to the back of queue. 33 | pop() -- Removes the element from in front of queue. 34 | peek() -- Get the front element. 35 | empty() -- Return whether the queue is empty. 36 | Example: 37 | 38 | MyQueue queue = new MyQueue(); 39 | 40 | queue.push(1); 41 | queue.push(2); 42 | queue.peek(); // returns 1 43 | queue.pop(); // returns 1 44 | queue.empty(); // returns false 45 | Notes: 46 | 47 | You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid. 48 | Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. 49 | You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). 50 | 51 | */ 52 | 53 | /** 54 | Big O Annotation 55 | Time complexity O(1) All operations are in constant time. 56 | Space complexity O(n) where n is the amount of elements in enqueueStack + dequeueStack. 57 | */ 58 | class MyQueue { 59 | 60 | private var enqueueStack: [Int] = [] 61 | private var dequeueStack: [Int] = [] 62 | 63 | /** Initialize your data structure here. */ 64 | init() { 65 | 66 | } 67 | 68 | /** Push element x to the back of queue. */ 69 | func push(_ x: Int) { 70 | enqueueStack.append(x) 71 | } 72 | 73 | /** Removes the element from in front of queue and returns that element. */ 74 | func pop() -> Int { 75 | 76 | if dequeueStack.isEmpty { 77 | dequeueStack = enqueueStack.reversed() 78 | enqueueStack.removeAll() 79 | } 80 | 81 | return dequeueStack.popLast() ?? Int() 82 | } 83 | 84 | /** Get the front element. */ 85 | func peek() -> Int { 86 | 87 | if dequeueStack.isEmpty { 88 | dequeueStack = enqueueStack.reversed() 89 | enqueueStack.removeAll() 90 | } 91 | 92 | return dequeueStack.last ?? Int() 93 | } 94 | 95 | /** Returns whether the queue is empty. */ 96 | func empty() -> Bool { 97 | return enqueueStack.isEmpty && dequeueStack.isEmpty 98 | } 99 | } -------------------------------------------------------------------------------- /leetcode-234-palindrome-linked-list.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/palindrome-linked-list/ 28 | 29 | 30 | Given a singly linked list, determine if it is a palindrome. 31 | 32 | Example 1: 33 | 34 | Input: 1->2 35 | Output: false 36 | Example 2: 37 | 38 | Input: 1->2->2->1 39 | Output: true 40 | Follow up: 41 | Could you do it in O(n) time and O(1) space? 42 | 43 | */ 44 | 45 | /** 46 | Big O Annotation 47 | Time complexity O(n) where n is the amount of nodes in head. 48 | Space complexity O(n) where n is the amount of nodes in head. 49 | */ 50 | func isPalindrome(_ head: ListNode?) -> Bool { 51 | 52 | /** 53 | If we have no head node, 54 | it's supposed to be a valid palindrome. 55 | 56 | Makes no sense to me, but it's not my challenge. 57 | */ 58 | guard let head = head else { 59 | return true 60 | } 61 | 62 | /** 63 | If we ONLY have a head node, 64 | it's a valid palindrome. 65 | */ 66 | guard head.next != nil else { 67 | return true 68 | } 69 | 70 | // Temporary values 71 | var stack: [Int] = [] 72 | 73 | // Traversing the list 74 | head.traverse { stack.append($0) } 75 | 76 | // Creating a left and a right pointer 77 | var left: Int = 0 78 | var right: Int = stack.count - 1 79 | 80 | // Loop as long as the pointers haven't crossed 81 | while left < right { 82 | 83 | // If left != right, we do not have a palindrome 84 | if stack[left] != stack[right] { 85 | return false 86 | } 87 | 88 | // Move pointers along 89 | left += 1 90 | right -= 1 91 | } 92 | 93 | // If we made it till here we have a palindrome 94 | return true 95 | } 96 | 97 | extension ListNode { 98 | 99 | // Recursive function to traverse the list 100 | func traverse(_ visit: (Int) -> Void) { 101 | visit(val) 102 | next?.traverse(visit) 103 | } 104 | } -------------------------------------------------------------------------------- /leetcode-237-delete-node-in-a-linked-list.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/delete-node-in-a-linked-list/ 28 | 29 | 30 | Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 31 | 32 | Given linked list -- head = [4,5,1,9], which looks like following: 33 | 34 | 35 | 36 | 37 | 38 | Example 1: 39 | 40 | Input: head = [4,5,1,9], node = 5 41 | Output: [4,1,9] 42 | Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. 43 | Example 2: 44 | 45 | Input: head = [4,5,1,9], node = 1 46 | Output: [4,5,9] 47 | Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. 48 | 49 | */ 50 | 51 | /** 52 | Big O Annotation 53 | Time & Space complexity O(1) we're linear in time and space. 54 | */ 55 | func deleteNode(_ node: ListNode?) { 56 | 57 | // Set the given node's value to the next one's value 58 | node?.val = node?.next?.val ?? Int() 59 | 60 | // Set the current node's next to the next node's next 61 | node?.next = node?.next?.next 62 | } -------------------------------------------------------------------------------- /leetcode-238-product-of-array-except-self.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/product-of-array-except-self/ 28 | 29 | 30 | Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 31 | 32 | Example: 33 | 34 | Input: [1,2,3,4] 35 | Output: [24,12,8,6] 36 | Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer. 37 | 38 | Note: Please solve it without division and in O(n). 39 | 40 | Follow up: 41 | Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) 42 | 43 | */ 44 | 45 | /** 46 | Big O Annotation 47 | Time complexity O(n) where n is the amount of elements in nums. 48 | Space complexity O(n) where n is the amount of elements in nums. 49 | */ 50 | func productExceptSelf(_ nums: [Int]) -> [Int] { 51 | 52 | var output: [Int] = Array(repeating: 1, count: nums.count) 53 | 54 | var prefixArray: [Int] = Array(repeating: 1, count: nums.count) 55 | var suffixArray: [Int] = Array(repeating: 1, count: nums.count) 56 | 57 | // Create prefix 58 | for (index, element) in nums.enumerated() { 59 | if index < nums.count - 1 { 60 | prefixArray[index + 1] = prefixArray[index] * element 61 | } 62 | } 63 | 64 | // Create Suffix 65 | for index in 0.. 0 { 69 | let element = nums[index_] 70 | suffixArray[index_ - 1] = suffixArray[index_] * element 71 | } 72 | } 73 | 74 | // Combine 75 | for (index, element) in prefixArray.enumerated() { 76 | output[index] = element * suffixArray[index] 77 | } 78 | 79 | return output 80 | } -------------------------------------------------------------------------------- /leetcode-24-swap-nodes-in-pairs.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/swap-nodes-in-pairs/ 28 | 29 | 30 | Given a linked list, swap every two adjacent nodes and return its head. 31 | 32 | You may not modify the values in the list's nodes, only nodes itself may be changed. 33 | 34 | */ 35 | 36 | /** 37 | Big O Annotation 38 | Time complexity O(n) where n is the amount of nodes in the list. 39 | Space complexity O(1) we're not using any extra space. 40 | */ 41 | func swapPairs(_ head: ListNode?) -> ListNode? { 42 | 43 | // Return is there is no next node 44 | if head?.next == nil { 45 | return head 46 | } 47 | 48 | /** 49 | Get a reference to the current next node 50 | In this example: [1,2,3,4], 51 | we have now [2,3,4] 52 | */ 53 | let next = head?.next 54 | 55 | /** 56 | Now we're computing [1]'s next, 57 | with parameter next?.next what is right now [3,4] 58 | That will give us [1,3,4] 59 | and that iteration called again 60 | will give us [1,4,3] 61 | */ 62 | head?.next = swapPairs(next?.next) 63 | 64 | // Set [2]'s next to [1,4,3] 65 | next?.next = head 66 | 67 | // And return 68 | return next 69 | } -------------------------------------------------------------------------------- /leetcode-240-search-a-2d-matrix-ii.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/search-a-2d-matrix-ii/ 28 | 29 | 30 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 31 | 32 | Integers in each row are sorted in ascending from left to right. 33 | Integers in each column are sorted in ascending from top to bottom. 34 | Example: 35 | 36 | Consider the following matrix: 37 | 38 | [ 39 | [1, 4, 7, 11, 15], 40 | [2, 5, 8, 12, 19], 41 | [3, 6, 9, 16, 22], 42 | [10, 13, 14, 17, 24], 43 | [18, 21, 23, 26, 30] 44 | ] 45 | Given target = 5, return true. 46 | 47 | Given target = 20, return false. 48 | 49 | */ 50 | 51 | /** 52 | Big O Annotation 53 | Time complexity O(nm) where n is the number of rows in 54 | matrix and m the number of elements in each row. 55 | Space complexity O(1). We're not using any extra space. 56 | 57 | I'm sure there is a binary search kind of thing 58 | that would be a better algorithm, 59 | but for now I'm satisfied with my 2 pointer approach. 60 | */ 61 | func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool { 62 | 63 | guard !matrix.isEmpty else { 64 | return false 65 | } 66 | 67 | var i: Int = 0 68 | var j: Int = matrix.count - 1 69 | 70 | while i <= j { 71 | 72 | for element in matrix[i] { 73 | if element == target { 74 | return true 75 | } 76 | } 77 | 78 | for element in matrix[j] { 79 | if element == target { 80 | return true 81 | } 82 | } 83 | 84 | i += 1 85 | j -= 1 86 | } 87 | 88 | return false 89 | } -------------------------------------------------------------------------------- /leetcode-252-meeting-room.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/meeting-rooms/ 28 | 29 | 30 | Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. 31 | 32 | Example 1: 33 | 34 | Input: [[0,30],[5,10],[15,20]] 35 | Output: false 36 | Example 2: 37 | 38 | Input: [[7,10],[2,4]] 39 | Output: true 40 | NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature. 41 | 42 | */ 43 | 44 | /** 45 | Big O Annotation 46 | Time complexity O(n log n) where n is the amount of elements in intervals. 47 | The sorting costs us O(n log n) 48 | 49 | I tried implemetnation with PriorityQueue (Heap), same runtime on leetcode. 50 | Although technically the complexity is O(log n) with a Heap. 51 | But since it's like 100 lines more code as Swift does not 52 | come with native Heaps, we might as well just go with the Stack. 53 | 54 | Space complexity O(n) where n is the amount of elements in intervals. 55 | */ 56 | func canAttendMeetings(_ intervals: [[Int]]) -> Bool { 57 | 58 | // If we have less than 2 meetings, then yes, all good 59 | guard intervals.count > 1 else { 60 | return true 61 | } 62 | 63 | // Sort by meeting end time descending 64 | let sorted = intervals.sorted { interval1, interval2 in 65 | return interval1[1] > interval2[1] 66 | } 67 | 68 | // Get a stack 69 | var stack = Stack(sorted) 70 | 71 | // And pop the first meeting 72 | var last: [Int] = stack.pop()! 73 | 74 | // While the stack is not empty... 75 | while !stack.isEmpty { 76 | 77 | // Pop the last element 78 | let popped = stack.pop()! 79 | 80 | /** 81 | And compare if the new meeting starts 82 | before the old meeting did end 83 | */ 84 | if last[1] > popped[0] { 85 | return false 86 | } 87 | 88 | // Update last 89 | last = popped 90 | } 91 | 92 | /** 93 | If we fell all the way through, 94 | then we're good to go with that schedule. 95 | */ 96 | return true 97 | } 98 | 99 | struct Stack { 100 | private var stack: [[Int]] 101 | public var isEmpty: Bool { return stack.isEmpty } 102 | init(_ array: [[Int]]) { stack = array } 103 | public mutating func pop() -> [Int]? { return stack.popLast() } 104 | } -------------------------------------------------------------------------------- /leetcode-253-meeting-rooms-ii.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/meeting-rooms-ii/ 28 | 29 | 30 | Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. 31 | 32 | Example 1: 33 | 34 | Input: [[0,30],[5,10],[15,20]] 35 | Output: false 36 | Example 2: 37 | 38 | Input: [[7,10],[2,4]] 39 | Output: true 40 | NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature. 41 | 42 | */ 43 | 44 | /** 45 | Big O Annotation 46 | Time complexity O(n log n) where n is the amount of elements in intervals. 47 | Space complexity O(n) where n is the amount of elements in intervals. 48 | */ 49 | func minMeetingRooms(_ intervals: [[Int]]) -> Int { 50 | 51 | // If we have no meetings, we need no rooms 52 | guard !intervals.isEmpty else { 53 | return 0 54 | } 55 | 56 | // If we have 1 meeting, we need 1 room 57 | guard intervals.count > 1 else { 58 | return 1 59 | } 60 | 61 | // Sort by start time 62 | var sorted = intervals.sorted { interval1, interval2 in 63 | return interval1[0] < interval2[0] 64 | } 65 | 66 | /** 67 | Get a min heap with sorting by end time 68 | and init the heap with the first element of sorted. 69 | 70 | Heap implementation taken from: 71 | https://github.com/raywenderlich/swift-algorithm-club/blob/master/Heap/Heap.swift 72 | */ 73 | var minHeap: Heap<[Int]> = Heap([sorted.first!], areSorted: { $0[1] < $1[1] } ) 74 | 75 | // Loop through the remaining elements 76 | for i in 1..= heap[1] { 89 | 90 | /** 91 | ... if not, then adjust the end 92 | time of the heap element 93 | */ 94 | heap[1] = current[1] 95 | } else { 96 | 97 | // If it does, add it to the heap 98 | minHeap.insert(current) 99 | } 100 | 101 | // Add the removed element back 102 | minHeap.insert(heap) 103 | } 104 | 105 | // And return the heap count 106 | return minHeap.count 107 | } -------------------------------------------------------------------------------- /leetcode-270-closest-binary-search-tree-value.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/closest-binary-search-tree-value/ 28 | 29 | 30 | Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. 31 | 32 | Note: 33 | 34 | Given target value is a floating point. 35 | You are guaranteed to have only one unique value in the BST that is closest to the target. 36 | Example: 37 | 38 | Input: root = [4,2,5,1,3], target = 3.714286 39 | 40 | 4 41 | / \ 42 | 2 5 43 | / \ 44 | 1 3 45 | 46 | Output: 4 47 | 48 | */ 49 | 50 | /** 51 | Big O Annotation 52 | Time complexity O(n) where n is the amount of nodes in root. 53 | Space complexity O(n) where n is the amount of nodes in root. 54 | */ 55 | func closestValue(_ root: TreeNode?, _ target: Double) -> Int { 56 | 57 | // First we want to get a rounded target 58 | let floatTarget: Float = Float(target).rounded() 59 | let integerTarget: Int = Int(floatTarget) 60 | 61 | // Then we need to traverse the BST 62 | var values: [Int] = [] 63 | traverse(root) { values.append($0) } 64 | 65 | // Lastly we want to get the closes value 66 | return getClosest(to: Int(target), in: values) 67 | } 68 | 69 | // Simple in order traversal 70 | private func traverse(_ node: TreeNode?, _ visit: (Int) -> Void) { 71 | guard let node = node else { return } 72 | traverse(node.left, visit) 73 | visit(node.val) 74 | traverse(node.right, visit) 75 | } 76 | 77 | // Gets the closes element in an array to target 78 | private func getClosest(to target: Int, in array: [Int]) -> Int { 79 | 80 | var distance: Int = Int.max 81 | var index: Int = 0 82 | var candidate: Int = 0 83 | 84 | for element in array { 85 | 86 | let currentDistance = abs(element - target) 87 | if currentDistance < distance { 88 | distance = currentDistance 89 | candidate = element 90 | } 91 | } 92 | 93 | return candidate 94 | } -------------------------------------------------------------------------------- /leetcode-286-walls-and-gates.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/walls-and-gates/ 28 | 29 | 30 | You are given a m x n 2D grid initialized with these three possible values. 31 | 32 | -1 - A wall or an obstacle. 33 | 0 - A gate. 34 | INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. 35 | Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF. 36 | 37 | Example: 38 | 39 | Given the 2D grid: 40 | 41 | INF -1 0 INF 42 | INF INF INF -1 43 | INF -1 INF -1 44 | 0 -1 INF INF 45 | After running your function, the 2D grid should be: 46 | 47 | 3 -1 0 1 48 | 2 2 1 -1 49 | 1 -1 2 -1 50 | 0 -1 3 4 51 | 52 | */ 53 | 54 | /** 55 | Big O Annotation 56 | Time complexity O(n^2) where n is the amount of elements in nums. 57 | Space complexity O(1) we're not using any extra space. 58 | */ 59 | func wallsAndGates(_ rooms: inout [[Int]]) { 60 | 61 | // Iterate through every row 62 | for (i, row) in rooms.enumerated() { 63 | 64 | // And every column 65 | for (j, column) in row.enumerated() { 66 | 67 | // Check if we have a gate 68 | if column == 0 { 69 | 70 | // And run our DFS function 71 | setRooms(&rooms, atRow: i, andColumn: j) 72 | } 73 | 74 | } 75 | } 76 | } 77 | 78 | // DFS 79 | private func setRooms(_ rooms: inout [[Int]], atRow row: Int, andColumn column: Int, to value: Int = 0) { 80 | 81 | // Check left, right, upper and lower bounds 82 | guard row >= 0 && column >= 0 && row < rooms.count && column < rooms[row].count else { 83 | return 84 | } 85 | 86 | /** 87 | We need to check the room value. 88 | As we only want to update rooms that are 89 | larger than our value. 90 | 91 | That leaves out the doors with value -1 92 | as the minimum value is 0. 93 | 94 | And it sets all the Int.max values to at least 0+1 95 | */ 96 | guard value <= rooms[row][column] else { 97 | return 98 | } 99 | 100 | // Set the room to value 101 | rooms[row][column] = value 102 | 103 | // And traverse in all directions, updating value by 1 104 | setRooms(&rooms, atRow: row + 1, andColumn: column, to: value + 1) 105 | setRooms(&rooms, atRow: row - 1, andColumn: column, to: value + 1) 106 | setRooms(&rooms, atRow: row, andColumn: column + 1, to: value + 1) 107 | setRooms(&rooms, atRow: row, andColumn: column - 1, to: value + 1) 108 | } -------------------------------------------------------------------------------- /leetcode-293-flip-game.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/flip-game/ 28 | 29 | 30 | You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner. 31 | 32 | Write a function to compute all possible states of the string after one valid move. 33 | 34 | Example: 35 | 36 | Input: s = "++++" 37 | Output: 38 | [ 39 | "--++", 40 | "+--+", 41 | "++--" 42 | ] 43 | Note: If there is no valid move, return an empty list []. 44 | 45 | */ 46 | 47 | /** 48 | Big O Annotation 49 | Time complexity O(n) where n is the amount of characters in s. 50 | Space complexity O(n) where n is the amount of possible states. 51 | */ 52 | func generatePossibleNextMoves(_ s: String) -> [String] { 53 | 54 | // Create an empty states array 55 | var states: [String] = [] 56 | 57 | /** 58 | Get a character array from s 59 | for easier index access 60 | */ 61 | var s: [Character] = Array(s) 62 | 63 | // Iterate through S 64 | for (index, character) in s.enumerated() { 65 | 66 | // Check if the current element is a + 67 | if character == "+" { 68 | 69 | // Get a mutable copy of the array 70 | var current = s 71 | 72 | // Check if the next index is also a + 73 | if (index + 1) < s.count && s[index + 1] == "+" { 74 | 75 | // Turn both indices to - 76 | current[index] = "-" 77 | current[index + 1] = "-" 78 | 79 | // ... and add to the states 80 | states.append(String(current)) 81 | } 82 | } 83 | } 84 | 85 | return states 86 | } -------------------------------------------------------------------------------- /leetcode-3-longest-substring-without-repeating-characters.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/longest-substring-without-repeating-characters/ 28 | 29 | 30 | Given a string, find the length of the longest substring without repeating characters. 31 | 32 | Example 1: 33 | 34 | Input: "abcabcbb" 35 | Output: 3 36 | Explanation: The answer is "abc", with the length of 3. 37 | Example 2: 38 | 39 | Input: "bbbbb" 40 | Output: 1 41 | Explanation: The answer is "b", with the length of 1. 42 | Example 3: 43 | 44 | Input: "pwwkew" 45 | Output: 3 46 | Explanation: The answer is "wke", with the length of 3. 47 | Note that the answer must be a substring, "pwke" is a subsequence and not a substring. 48 | 49 | */ 50 | 51 | /** 52 | Big O Annotation 53 | Time complexity O(n) where n is the amount of elements in nums. 54 | Space complexity O(n) where n is the amount of elements in nums. 55 | */ 56 | func lengthOfLongestSubstring(_ s: String) -> Int { 57 | 58 | /** 59 | First we get an array of the string 60 | to more conveniently access the indicies 61 | */ 62 | var array = Array(s) 63 | 64 | /** 65 | We create a set to check for 66 | processed character Set.contains 67 | in contant time 68 | */ 69 | var hash = Set() 70 | 71 | // We create a left and a right pointer 72 | var leftPointer: Int = 0 73 | var rightPointer: Int = 0 74 | 75 | // Our current maximum 76 | var maximum: Int = 0 77 | 78 | // While we still have characters to process... 79 | while rightPointer < array.count { 80 | 81 | // ... get the left and right character 82 | let left = array[leftPointer] 83 | let right = array[rightPointer] 84 | 85 | /** 86 | In the example of "abcabcbb", 87 | we first get left and right pointers 88 | on index 0 aka "a". 89 | 90 | Next we check if "a" is already 91 | in the Set, no, so insert it. 92 | 93 | Then we move the right pointer forwards. 94 | "b", not in the list, add it. 95 | 96 | Next. "c" not in the list. Add it. 97 | Next. "a" already in the list, 98 | so remove "a" and continue to the next character. 99 | 100 | Once removed, our pointer is still on the 101 | 2nd "a", so we move it back to the array. 102 | And move along to the next characters. 103 | 104 | Always updating our maximum to the new total maximum. 105 | */ 106 | 107 | if hash.contains(right) { 108 | 109 | hash.remove(left) 110 | leftPointer += 1 111 | 112 | } else { 113 | 114 | hash.insert(right) 115 | rightPointer += 1 116 | maximum = max(hash.count, maximum) 117 | } 118 | } 119 | 120 | return maximum 121 | } -------------------------------------------------------------------------------- /leetcode-328-odd-even-linked-list.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/odd-even-linked-list/ 28 | 29 | 30 | Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. 31 | 32 | You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. 33 | 34 | Example 1: 35 | 36 | Input: 1->2->3->4->5->NULL 37 | Output: 1->3->5->2->4->NULL 38 | Example 2: 39 | 40 | Input: 2->1->3->5->6->4->7->NULL 41 | Output: 2->3->6->7->1->5->4->NULL 42 | Note: 43 | 44 | The relative order inside both the even and odd groups should remain as it was in the input. 45 | The first node is considered odd, the second node even and so on ... 46 | 47 | */ 48 | 49 | /** 50 | Big O Annotation 51 | Time complexity O(n) where n is the amount of nodes in head. 52 | Space complexity O(1) we're using 3 variables of space. 53 | */ 54 | func oddEvenList(_ head: ListNode?) -> ListNode? { 55 | 56 | guard let head = head else { 57 | return nil 58 | } 59 | 60 | /** 61 | O E O E O 62 | 1 2 3 4 5 63 | Input: 1->2->3->4->5->NULL 64 | 65 | O O O E E 66 | 1 3 4 2 4 67 | Output: 1->3->5->2->4->NULL 68 | 69 | O E O E O E O 70 | 1 2 3 4 5 6 7 71 | Input: 2->1->3->5->6->4->7->NULL 72 | 73 | O O O O E E E 74 | 1 3 5 7 2 4 6 75 | Output: 2->3->6->7->1->5->4->NULL 76 | 77 | */ 78 | 79 | // Get a reference to the first odd node 80 | var odd: ListNode? = head 81 | 82 | // And a reference to the first even node 83 | var even: ListNode? = head.next 84 | 85 | // And a total reference of all even nodes 86 | var evenHead: ListNode? = even 87 | 88 | // While we still have even elements 89 | while even != nil && even!.next != nil { 90 | 91 | // Set even's next element as the next of the odd list 92 | odd?.next = even?.next 93 | 94 | // And move odd a long 95 | odd = odd?.next 96 | 97 | // Same for the even list 98 | even?.next = odd?.next 99 | even = even?.next 100 | } 101 | 102 | // Append the even list to the odd list 103 | odd?.next = evenHead 104 | 105 | // And return the mutated head 106 | return head 107 | } -------------------------------------------------------------------------------- /leetcode-334-reverse-string.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/reverse-string/ 28 | 29 | 30 | Write a function that reverses a string. The input string is given as an array of characters char[]. 31 | 32 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 33 | 34 | You may assume all the characters consist of printable ascii characters. 35 | 36 | 37 | 38 | Example 1: 39 | 40 | Input: ["h","e","l","l","o"] 41 | Output: ["o","l","l","e","h"] 42 | Example 2: 43 | 44 | Input: ["H","a","n","n","a","h"] 45 | Output: ["h","a","n","n","a","H"] 46 | 47 | */ 48 | 49 | /** 50 | Big O Annotation 51 | Time complexity O(log n) where n is the amount of elements in reverseString. 52 | The two pointer recursion cuts the work load in half. 53 | 54 | Space complexity O(1) we're not using any extra space. 55 | */ 56 | func reverseString(_ s: inout [Character]) { 57 | 58 | swapCharacters( 59 | atLeftPointer: 0, 60 | andRightPointer: s.count - 1, 61 | in: &s 62 | ) 63 | } 64 | 65 | /** 66 | The goal of this challenge was to use an iterative approach, 67 | so that's what we're doing. 68 | */ 69 | func swapCharacters(atLeftPointer left: Int, 70 | andRightPointer right: Int, 71 | in array: inout [Character]) { 72 | 73 | // The base case hits when the pointers cross 74 | guard left < right else { 75 | return 76 | } 77 | 78 | // Until then swap the elements at the pointers 79 | array.swapAt(left, right) 80 | 81 | // And repeat by increasing/decreasing the pointers 82 | swapCharacters( 83 | atLeftPointer: left + 1, 84 | andRightPointer: right - 1, 85 | in: &array 86 | ) 87 | } -------------------------------------------------------------------------------- /leetcode-347-top-k-frequent-elements.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/top-k-frequent-elements/ 28 | 29 | 30 | Given a non-empty array of integers, return the k most frequent elements. 31 | 32 | Example 1: 33 | 34 | Input: nums = [1,1,1,2,2,3], k = 2 35 | Output: [1,2] 36 | Example 2: 37 | 38 | Input: nums = [1], k = 1 39 | Output: [1] 40 | Note: 41 | 42 | You may assume k is always valid, 1 ≤ k ≤ number of unique elements. 43 | Your algorithm's time complexity must be better than O(n log n), where n is the array's size. 44 | It's guaranteed that the answer is unique, in other words the set of the top k frequent elements is unique. 45 | You can return the answer in any order. 46 | 47 | */ 48 | 49 | /** 50 | Big O Annotation 51 | Time complexity O(n log n) because of the sorting overhead. 52 | Space complexity O(n) where n is the amount of elements in nums. 53 | */ 54 | func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] { 55 | 56 | /** 57 | Hash map of nums elements and 58 | their frequency 59 | */ 60 | var hash: [Int: Int] = [:] 61 | 62 | // Iterate through nums 63 | for element in nums { 64 | 65 | /** 66 | Check if we have already mapped 67 | the given element.. 68 | */ 69 | if let mapped = hash[element] { 70 | 71 | // ... if so, add 1 72 | hash[element] = mapped + 1 73 | 74 | } else { 75 | 76 | // If not, set 1 77 | hash[element] = 1 78 | } 79 | } 80 | 81 | // Sort the map by value descending 82 | let sorted = hash.sorted { element1, element2 in 83 | return element1.value > element2.value 84 | } 85 | 86 | // Map to only have array of nums elements 87 | let mapped = sorted.map { element in 88 | return element.key 89 | } 90 | 91 | /** 92 | Return the desired elements 93 | as a new array from 0 up to but not including k. 94 | 95 | Safe operation as stated in the notes: 96 | "You may assume k is always valid, 1 ≤ k ≤ number of unique elements." 97 | */ 98 | return Array(mapped[0.. [Int] { 53 | 54 | /** 55 | Get a set of nums1 for 56 | O(1) .contains operation 57 | */ 58 | var asSet: Set = Set(nums1) 59 | var result: Set = [] 60 | 61 | // Iterate through nums2 62 | for element in nums2 { 63 | 64 | // Check if num1 contains element 65 | if asSet.contains(element) { 66 | result.insert(element) 67 | } 68 | } 69 | 70 | return Array(result) 71 | } -------------------------------------------------------------------------------- /leetcode-367-valid-perfect-square.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/valid-perfect-square/ 28 | 29 | 30 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 31 | 32 | Note: Do not use any built-in library function such as sqrt. 33 | 34 | Example 1: 35 | 36 | Input: 16 37 | Output: true 38 | Example 2: 39 | 40 | Input: 14 41 | Output: false 42 | 43 | */ 44 | 45 | /** 46 | Big O Annotation 47 | Time complexity O(n) where n is the elements between 0 and num. 48 | Space complexity O(1) where only using constant space. 49 | */ 50 | func isPerfectSquare(_ num: Int) -> Bool { 51 | 52 | // Iterate from 0 up to including num 53 | for number in 0...num { 54 | 55 | // Get the square of the current number 56 | let numberSquared = number * number 57 | 58 | /** 59 | If that squared number of larger 60 | or equal to num, 61 | check if it is num and 62 | return true if so, false otherwise 63 | */ 64 | if numberSquared >= num { 65 | return numberSquared == num 66 | } 67 | } 68 | return false 69 | } -------------------------------------------------------------------------------- /leetcode-380-insert-delete-getrandom-o1.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/insert-delete-getrandom-o1/ 28 | 29 | 30 | Design a data structure that supports all following operations in average O(1) time. 31 | 32 | insert(val): Inserts an item val to the set if not already present. 33 | remove(val): Removes an item val from the set if present. 34 | getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. 35 | Example: 36 | 37 | // Init an empty set. 38 | RandomizedSet randomSet = new RandomizedSet(); 39 | 40 | // Inserts 1 to the set. Returns true as 1 was inserted successfully. 41 | randomSet.insert(1); 42 | 43 | // Returns false as 2 does not exist in the set. 44 | randomSet.remove(2); 45 | 46 | // Inserts 2 to the set, returns true. Set now contains [1,2]. 47 | randomSet.insert(2); 48 | 49 | // getRandom should return either 1 or 2 randomly. 50 | randomSet.getRandom(); 51 | 52 | // Removes 1 from the set, returns true. Set now contains [2]. 53 | randomSet.remove(1); 54 | 55 | // 2 was already in the set, so return false. 56 | randomSet.insert(2); 57 | 58 | // Since 2 is the only number in the set, getRandom always return 2. 59 | randomSet.getRandom(); 60 | 61 | */ 62 | 63 | /** 64 | Big O Annotation 65 | All operations are O(1) in time complexity. 66 | Space complexity O(n) where n is the amount of elements in data. 67 | */ 68 | class RandomizedSet { 69 | 70 | private var data: Set = [] 71 | 72 | /** Initialize your data structure here. */ 73 | init() { } 74 | 75 | /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ 76 | func insert(_ val: Int) -> Bool { 77 | 78 | if data.contains(val) { 79 | return false 80 | } 81 | data.insert(val) 82 | return true 83 | } 84 | 85 | /** Removes a value from the set. Returns true if the set contained the specified element. */ 86 | func remove(_ val: Int) -> Bool { 87 | 88 | if !data.contains(val) { 89 | return false 90 | } 91 | data.remove(val) 92 | return true 93 | } 94 | 95 | /** Get a random element from the set. */ 96 | func getRandom() -> Int { 97 | return data.randomElement() ?? 0 98 | } 99 | } 100 | 101 | /** 102 | * Your RandomizedSet object will be instantiated and called as such: 103 | * let obj = RandomizedSet() 104 | * let ret_1: Bool = obj.insert(val) 105 | * let ret_2: Bool = obj.remove(val) 106 | * let ret_3: Int = obj.getRandom() 107 | */ -------------------------------------------------------------------------------- /leetcode-392-is-subsequence.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/is-subsequence/ 28 | 29 | 30 | Given a string s and a string t, check if s is subsequence of t. 31 | 32 | A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while "aec" is not). 33 | 34 | Follow up: 35 | If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code? 36 | 37 | Credits: 38 | Special thanks to @pbrother for adding this problem and creating all test cases. 39 | 40 | */ 41 | 42 | /** 43 | Big O Annotation 44 | Time complexity O(n) where n is the amount of characters in t. 45 | Space complexity O(n) where n is the amount of characters in s. 46 | */ 47 | func isSubsequence(_ s: String, _ t: String) -> Bool { 48 | 49 | // Init a stack from String s 50 | var stack = Stack(s) 51 | 52 | // Loop through String t 53 | for character in t { 54 | 55 | // Check if the first element of the stack equals the current character 56 | if let element = stack.peek, character == element { 57 | 58 | // If so, pop it 59 | stack.pop() 60 | } 61 | } 62 | 63 | // Lastly check if the stack is empty 64 | return stack.isEmpty 65 | } 66 | 67 | struct Stack { 68 | 69 | private var stack: [Character] = [] 70 | 71 | init(_ s: String) { 72 | stack = Array(s).reversed() 73 | } 74 | 75 | public var isEmpty: Bool { 76 | return stack.isEmpty 77 | } 78 | 79 | public var peek: Character? { 80 | return stack.last 81 | } 82 | 83 | public mutating func pop() -> Character? { 84 | return stack.popLast() 85 | } 86 | } -------------------------------------------------------------------------------- /leetcode-412-fizz-buzz.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/fizz-buzz/ 28 | 29 | 30 | Write a program that outputs the string representation of numbers from 1 to n. 31 | 32 | But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. 33 | 34 | Example: 35 | 36 | n = 15, 37 | 38 | Return: 39 | [ 40 | "1", 41 | "2", 42 | "Fizz", 43 | "4", 44 | "Buzz", 45 | "Fizz", 46 | "7", 47 | "8", 48 | "Fizz", 49 | "Buzz", 50 | "11", 51 | "Fizz", 52 | "13", 53 | "14", 54 | "FizzBuzz" 55 | ] 56 | 57 | */ 58 | 59 | /** 60 | Big O Annotation 61 | Time complexity O(n) where n is 1...n. 62 | Space complexity O(n) where n is 1...n. 63 | */ 64 | func fizzBuzz(_ n: Int) -> [String] { 65 | 66 | var result: [String] = [] 67 | 68 | // Iterate from 0 to n 69 | for number in 1...n { 70 | 71 | // Check if element is a multiplication of 3 72 | let multiplicationOf3 = (number % 3) == 0 73 | 74 | // Check if element is a multiplication of 5 75 | let multiplicationOf5 = (number % 5) == 0 76 | 77 | // If it's both, then add "FizzBuzz" 78 | if multiplicationOf3 && multiplicationOf5 { 79 | 80 | result.append("FizzBuzz") 81 | 82 | // Add "Fizz" for 3 83 | } else if multiplicationOf3 { 84 | 85 | result.append("Fizz") 86 | 87 | // Add "Fizz" for 5 88 | } else if multiplicationOf5 { 89 | 90 | result.append("Buzz") 91 | 92 | // Else add just the number 93 | } else { 94 | 95 | result.append("\(number)") 96 | } 97 | } 98 | 99 | return result 100 | } -------------------------------------------------------------------------------- /leetcode-42-trapping-rain-water.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/trapping-rain-water/ 28 | 29 | 30 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. 31 | 32 | 33 | The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! 34 | 35 | Example: 36 | 37 | Input: [0,1,0,2,1,0,1,3,2,1,2,1] 38 | Output: 6 39 | 40 | */ 41 | 42 | /** 43 | Big O Annotation 44 | Time complexity O(n) where n is the amount of elements in nums. 45 | Space complexity O(n) where n is the amount of elements in nums. 46 | */ 47 | func trap(_ height: [Int]) -> Int { 48 | 49 | guard !height.isEmpty else { 50 | return 0 51 | } 52 | 53 | /** 54 | We want to precalculate the highest 55 | building to the left and to the right 56 | for every given index. 57 | 58 | To reduce the complexity from O(n^2) to O(n) 59 | */ 60 | var lefties: [Int] = Array(repeating: 0, count: height.count) 61 | lefties[0] = height[0] 62 | 63 | var righties: [Int] = Array(repeating: 0, count: height.count) 64 | righties[height.count - 1] = height[height.count - 1] 65 | 66 | // The final amount 67 | var water: Int = 0 68 | 69 | /** 70 | Iterate first through the heights 71 | and get the highest building 72 | for every given index's left and right side 73 | */ 74 | for i in 1.. Int { 119 | 120 | var water: Int = 0 121 | 122 | for (index, element) in height.enumerated() { 123 | 124 | let leftMax: Int = Array(height[0...index]).max() ?? 0 125 | let rightMax: Int = Array(height[index.. [Int] { 55 | 56 | guard !nums.isEmpty else { 57 | return [] 58 | } 59 | 60 | var resultArray: Set = [] 61 | 62 | for index in 1...nums.count { 63 | resultArray.insert(index) 64 | } 65 | 66 | for element in nums { 67 | if resultArray.contains(element) { 68 | resultArray.remove(element) 69 | } 70 | } 71 | 72 | return Array(resultArray) 73 | } -------------------------------------------------------------------------------- /leetcode-451-sort-characters-by-frequence.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/sort-characters-by-frequency/ 28 | 29 | 30 | Given a string, sort it in decreasing order based on the frequency of characters. 31 | 32 | Example 1: 33 | 34 | Input: 35 | "tree" 36 | 37 | Output: 38 | "eert" 39 | 40 | Explanation: 41 | 'e' appears twice while 'r' and 't' both appear once. 42 | So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. 43 | Example 2: 44 | 45 | Input: 46 | "cccaaa" 47 | 48 | Output: 49 | "cccaaa" 50 | 51 | Explanation: 52 | Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. 53 | Note that "cacaca" is incorrect, as the same characters must be together. 54 | Example 3: 55 | 56 | Input: 57 | "Aabb" 58 | 59 | Output: 60 | "bbAa" 61 | 62 | Explanation: 63 | "bbaA" is also a valid answer, but "Aabb" is incorrect. 64 | Note that 'A' and 'a' are treated as two different characters. 65 | 66 | */ 67 | 68 | /** 69 | Big O Annotation 70 | Time complexity O(n log n) because of the sorting overhead, 71 | where n is the amount of elements in nums. 72 | Space complexity O(n) where n is the amount of elements in nums. 73 | */ 74 | func frequencySort(_ s: String) -> String { 75 | 76 | // Init a map of characters and their counts 77 | var map: [Character: Int] = [:] 78 | 79 | // Fill the map 80 | for character in s { 81 | map[character, default: 0] += 1 82 | } 83 | 84 | // Sort the character : count pairs 85 | let sorted = map.sorted { element1, element2 in 86 | return element1.value > element2.value 87 | } 88 | 89 | // Init the outut String 90 | var output = "" 91 | 92 | // For each key/value pair... 93 | for (key, value) in sorted { 94 | 95 | // Add value amount of... 96 | for _ in 0.. [[String]] { 50 | 51 | /** 52 | We want to get a map. 53 | The idea is to get a sorted string 54 | as the base. And then all uses of that string. 55 | 56 | So example: 57 | 58 | [ 59 | "aet": ["ate","eat","tea"], 60 | "ant": ["nat","tan"], 61 | "abt": ["bat"] 62 | ] 63 | */ 64 | var anagrams: [String: [String]] = [:] 65 | 66 | // Iterate through the string 67 | for string in strs { 68 | 69 | // Get the character sorted version 70 | let sorted: [Character] = Array(string).sorted() 71 | 72 | // And append it's current string of strs 73 | anagrams[String(sorted), default: []].append(string) 74 | } 75 | 76 | // Now let's init a result array 77 | var result: [[String]] = [] 78 | 79 | // And simply append every [String] value 80 | for (key, value) in anagrams { 81 | result.append(value) 82 | } 83 | 84 | return result 85 | } -------------------------------------------------------------------------------- /leetcode-509-fibonacci-number.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/fibonacci-number/ 28 | 29 | 30 | The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 31 | 32 | F(0) = 0, F(1) = 1 33 | F(N) = F(N - 1) + F(N - 2), for N > 1. 34 | Given N, calculate F(N). 35 | 36 | */ 37 | 38 | /** 39 | Big O Annotation 40 | Time complexity O(n) where n is N. 41 | Space complexity O(n) where n is N. 42 | 43 | The bottom up approach takes more memory 44 | than the recursive approach. 45 | 46 | But the recursive approach might fail 47 | as a stackoverflow protection when the 48 | recursive function is called too many times 49 | in a short amount of time. 50 | 51 | Happens for example on the CodeRunner application. 52 | */ 53 | func fib(_ N: Int) -> Int { 54 | 55 | // Init a bottom up array 56 | var bottomUp: [Int] = [] 57 | 58 | /** 59 | Add the 3 known starting cases of 60 | the fibonacci sequence 61 | */ 62 | bottomUp.append(0) 63 | bottomUp.append(1) 64 | bottomUp.append(1) 65 | 66 | // Check that N is larger than 2 67 | if N > 2 { 68 | 69 | // If so, iterate up through N + 1 70 | for index in 3...N + 1 { 71 | 72 | // And calculate the fib for that spot 73 | bottomUp.append(bottomUp[index - 1] + bottomUp[index - 2]) 74 | } 75 | } 76 | 77 | // Return the Nth fib 78 | return bottomUp[N] 79 | } -------------------------------------------------------------------------------- /leetcode-53-maximum-subarray.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/maximum-subarray/ 28 | 29 | 30 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 31 | 32 | Example: 33 | 34 | Input: [-2,1,-3,4,-1,2,1,-5,4], 35 | Output: 6 36 | Explanation: [4,-1,2,1] has the largest sum = 6. 37 | Follow up: 38 | 39 | If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 40 | 41 | */ 42 | 43 | /** 44 | Big O Annotation 45 | Time complexity O(n) where n is the amount of elements in nums. 46 | Space complexity O(1) as we're at most storing 2 variables at the same time. 47 | */ 48 | func maxSubArray(_ nums: [Int]) -> Int { 49 | 50 | /** 51 | If we have nothing in the array, 52 | there's nothing to return. 53 | */ 54 | guard nums.count > 0 else { 55 | return 0 56 | } 57 | 58 | /** 59 | We need a reference to the current 60 | maximum number and the largest maximum 61 | number generally, as we're looking for 62 | "contiguous subarray" 63 | 64 | Intialized with nums first element. 65 | */ 66 | var maximumLocal: Int = nums[0] 67 | var maximumGlobal: Int = nums[0] 68 | 69 | // Iterate through the array from 1 70 | for index in 1.. maximumGlobal { 92 | maximumGlobal = maximumLocal 93 | } 94 | } 95 | 96 | return maximumGlobal 97 | } -------------------------------------------------------------------------------- /leetcode-572-subtree-of-another-tree.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/subtree-of-another-tree/ 28 | 29 | 30 | Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself. 31 | 32 | Example 1: 33 | Given tree s: 34 | 35 | 3 36 | / \ 37 | 4 5 38 | / \ 39 | 1 2 40 | Given tree t: 41 | 4 42 | / \ 43 | 1 2 44 | Return true, because t has the same structure and node values with a subtree of s. 45 | 46 | 47 | Example 2: 48 | Given tree s: 49 | 50 | 3 51 | / \ 52 | 4 5 53 | / \ 54 | 1 2 55 | / 56 | 0 57 | Given tree t: 58 | 4 59 | / \ 60 | 1 2 61 | Return false. 62 | 63 | */ 64 | 65 | /** 66 | Big O Annotation 67 | Time complexity O(n) where n is the amount of nodes in s. 68 | Space complexity O(1) we're not using any extra space. 69 | */ 70 | func isSubtree(_ s: TreeNode?, _ t: TreeNode?) -> Bool { 71 | 72 | // Without no s tree, nothing to check 73 | guard let s = s else { 74 | return false 75 | } 76 | 77 | // Check if t is a subtree of s 78 | guard getEquality(of: s, and: t) else { 79 | 80 | // If not, continue on the left and on the right 81 | return isSubtree(s.left, t) || isSubtree(s.right, t) 82 | } 83 | 84 | return true 85 | } 86 | 87 | private func getEquality(of s: TreeNode?, and t: TreeNode?) -> Bool { 88 | 89 | // If either node is nil... 90 | if s == nil || t == nil { 91 | 92 | // ... both need to be nil 93 | return s == nil && t == nil 94 | 95 | // If the current nodes match 96 | } else if s!.val == t!.val { 97 | 98 | // Then all other children need to match as well 99 | return getEquality(of: s!.left, and: t!.left) && getEquality(of: s!.right, and: t!.right) 100 | } 101 | 102 | // Otherwise it's not a subtree 103 | return false 104 | } -------------------------------------------------------------------------------- /leetcode-58-length-of-last-word.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/length-of-last-word/ 28 | 29 | 30 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string. 31 | 32 | If the last word does not exist, return 0. 33 | 34 | Note: A word is defined as a maximal substring consisting of non-space characters only. 35 | 36 | Example: 37 | 38 | Input: "Hello World" 39 | Output: 5 40 | 41 | */ 42 | 43 | /** 44 | Big O Annotation 45 | Time complexity O(n) where n is the amount of words in s. 46 | Space complexity O(n) where n is the amount of words in s. 47 | */ 48 | func lengthOfLastWord(_ s: String) -> Int { 49 | 50 | // Without characters no last word length 51 | guard s.count > 0 else { 52 | return 0 53 | } 54 | 55 | // Split string by words 56 | var components: [String] = s.components(separatedBy: " ") 57 | 58 | // Filter out empty words 59 | components = components.filter { component in 60 | return component != "" 61 | } 62 | 63 | // Make sure we have a last word 64 | guard let last = components.last else { 65 | return 0 66 | } 67 | 68 | // Return it's length 69 | return Array(last).count 70 | } -------------------------------------------------------------------------------- /leetcode-653-two-sum-iv-input-is-a-bst.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/two-sum-iv-input-is-a-bst/ 28 | 29 | 30 | Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. 31 | 32 | Example 1: 33 | 34 | Input: 35 | 5 36 | / \ 37 | 3 6 38 | / \ \ 39 | 2 4 7 40 | 41 | Target = 9 42 | 43 | Output: True 44 | 45 | 46 | Example 2: 47 | 48 | Input: 49 | 5 50 | / \ 51 | 3 6 52 | / \ \ 53 | 2 4 7 54 | 55 | Target = 28 56 | 57 | Output: False 58 | 59 | */ 60 | 61 | /** 62 | Big O Annotation 63 | Time complexity O(n) where n is the amount of elements in nums. 64 | Space complexity O(n) where n is the amount of elements in nums. 65 | */ 66 | func findTarget(_ root: TreeNode?, _ k: Int) -> Bool { 67 | 68 | /** 69 | Create a map of values. 70 | Key and Value will be the val of a node. 71 | */ 72 | var hash: [Int: Int] = [:] 73 | 74 | // Traverse the tree 75 | root?.traverse { hash[$0, default: 0] = $0 } 76 | 77 | // Check for each element 78 | for (key, _) in hash { 79 | 80 | // If we can find an element that sums up to k 81 | if let mapped = hash[k - key], key != mapped { 82 | return true 83 | } 84 | } 85 | 86 | // If not, return false 87 | return false 88 | } 89 | 90 | // Simple Pre order traversal 91 | fileprivate extension TreeNode { 92 | func traverse(_ visit: (Int) -> Void) { 93 | 94 | visit(val) 95 | left?.traverse(visit) 96 | right?.traverse(visit) 97 | } 98 | } -------------------------------------------------------------------------------- /leetcode-657-robot-return-to-origin.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/robot-return-to-origin/ 28 | 29 | 30 | There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. 31 | 32 | The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false. 33 | 34 | Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move. 35 | 36 | Example 1: 37 | 38 | Input: "UD" 39 | Output: true 40 | Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true. 41 | 42 | 43 | Example 2: 44 | 45 | Input: "LL" 46 | Output: false 47 | Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves. 48 | 49 | */ 50 | 51 | /** 52 | Big O Annotation 53 | Time complexity O(n) where n is the amount of character in moves. 54 | Space complexity O(1) we're not using any extra space. 55 | */ 56 | func judgeCircle(_ moves: String) -> Bool { 57 | 58 | /** 59 | We will have a reference to 60 | where we are space wise. 61 | 62 | Example: "UUURRR" will get us 63 | 3 ups and 3 rights. 64 | Therefore: 65 | 66 | upDowns = 3 67 | leftRights = 3 68 | */ 69 | var upDowns: Int = 0 70 | var leftRights: Int = 0 71 | 72 | for move in moves { 73 | 74 | // For up, add 1 75 | if move == "U" { 76 | upDowns += 1 77 | } 78 | 79 | // For down, remove 1 80 | if move == "D" { 81 | upDowns -= 1 82 | } 83 | 84 | // For left, add 1 85 | if move == "L" { 86 | leftRights += 1 87 | } 88 | 89 | // For right, remove 1 90 | if move == "R" { 91 | leftRights -= 1 92 | } 93 | } 94 | 95 | // In the end we need to be back to 0 / 0 96 | return (upDowns == 0) && (leftRights == 0) 97 | } -------------------------------------------------------------------------------- /leetcode-692-top-k-frequent-words.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/top-k-frequent-words/ 28 | 29 | 30 | Given a non-empty list of words, return the k most frequent elements. 31 | 32 | Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first. 33 | 34 | Example 1: 35 | Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2 36 | Output: ["i", "love"] 37 | Explanation: "i" and "love" are the two most frequent words. 38 | Note that "i" comes before "love" due to a lower alphabetical order. 39 | Example 2: 40 | Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 41 | Output: ["the", "is", "sunny", "day"] 42 | Explanation: "the", "is", "sunny" and "day" are the four most frequent words, 43 | with the number of occurrence being 4, 3, 2 and 1 respectively. 44 | Note: 45 | You may assume k is always valid, 1 ≤ k ≤ number of unique elements. 46 | Input words contain only lowercase letters. 47 | Follow up: 48 | Try to solve it in O(n log k) time and O(n) extra space. 49 | 50 | */ 51 | 52 | /** 53 | Big O Annotation 54 | Time complexity O(n log n) because of the sorting overhead. 55 | Space complexity O(n) where n is the amount of elements in words. 56 | */ 57 | func topKFrequent(_ words: [String], _ k: Int) -> [String] { 58 | 59 | // Create a map for the words 60 | var hash: [String: Int] = [:] 61 | 62 | // Iterate through the words 63 | for word in words { 64 | // .. and count them 65 | hash[word, default: 0] += 1 66 | } 67 | 68 | /** 69 | Sort by frequency or alternatively alphabetically, 70 | as requested in the challenge 71 | */ 72 | let sorted: [(key: String, value: Int)] = hash.sorted { element1, element2 in 73 | 74 | if element1.value == element2.value { 75 | return element1.key < element2.key 76 | } 77 | return element1.value > element2.value 78 | } 79 | 80 | // Get only k elements... 81 | let shrunk: [(key: String, value: Int)] = Array(sorted[0.. Int { 59 | 60 | // Get a mutable copy of the grid 61 | var grid = grid 62 | 63 | /** 64 | Init an empty area set. 65 | We will fill this with all the 66 | available areas of all the islands 67 | and in the end return max() 68 | */ 69 | var islands: Set = [] 70 | 71 | // Iterate through the grid 72 | for (i, row) in grid.enumerated() { 73 | 74 | // And through each row 75 | for (j, column) in row.enumerated() { 76 | 77 | // Init area as 0 78 | var area: Int = 0 79 | 80 | // Flatten all connected parts of this island 81 | flattenIsland(&grid, i, j, area: &area) 82 | 83 | // And add the final area to the set 84 | islands.insert(area) 85 | } 86 | } 87 | 88 | // Return the max element 89 | return islands.max() ?? 0 90 | } 91 | 92 | /** 93 | Takes the grid, the x/y and the area as mutable element. 94 | Will visit all adjacent neighbors, flatten them 95 | and add their count to the area. 96 | */ 97 | func flattenIsland(_ grid: inout [[Int]], _ i: Int, _ j: Int, area: inout Int) { 98 | 99 | // Check left and top bounds 100 | guard i >= 0 && j >= 0 else { 101 | return 102 | } 103 | 104 | // Check right and bottom bounds 105 | guard i < grid.count && j < grid[i].count else { 106 | return 107 | } 108 | 109 | // Make sure it's actually an island 110 | guard grid[i][j] == 1 else { 111 | return 112 | } 113 | 114 | // Flatten it so we dont count it again 115 | grid[i][j] = 0 116 | 117 | // And add +1 to the area 118 | area += 1 119 | 120 | // Continue through the neighbors 121 | flattenIsland(&grid, i + 1, j, area: &area) 122 | flattenIsland(&grid, i - 1, j, area: &area) 123 | flattenIsland(&grid, i, j + 1, area: &area) 124 | flattenIsland(&grid, i, j - 1, area: &area) 125 | } -------------------------------------------------------------------------------- /leetcode-70-climbing-stairs.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/climbing-stairs/ 28 | 29 | 30 | You are climbing a stair case. It takes n steps to reach to the top. 31 | 32 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 33 | 34 | Note: Given n will be a positive integer. 35 | 36 | Example 1: 37 | 38 | Input: 2 39 | Output: 2 40 | Explanation: There are two ways to climb to the top. 41 | 1. 1 step + 1 step 42 | 2. 2 steps 43 | Example 2: 44 | 45 | Input: 3 46 | Output: 3 47 | Explanation: There are three ways to climb to the top. 48 | 1. 1 step + 1 step + 1 step 49 | 2. 1 step + 2 steps 50 | 3. 2 steps + 1 step 51 | 52 | */ 53 | 54 | /** 55 | Big O Annotation 56 | Time complexity O(n) where n is the amount of elements between 0 and target. 57 | Space complexity O(n) where n is the amount of elements between 0 and target. 58 | */ 59 | func climbStairs(_ n: Int) -> Int { 60 | 61 | /** 62 | In our dp approach we're going to use the bottom up way 63 | of creating our output array. The advantage besides 64 | memoization is, that we're not running into 65 | stackoverflow protection territory. 66 | 67 | If we'd call the recursive function hundreds of times, 68 | many code runners return Segment 11 error. 69 | 70 | The idea is, that we're adding the 71 | amount of stairs it will take upfront. 72 | 73 | Example: 74 | 5 stair 75 | 76 | 0 stair -> 1 way 77 | 1 stair -> 1 way 78 | 2 stairs -> 2 ways (0 + 1) 79 | 3 stairs -> 3 ways (1 + 2) 80 | 4 stairs -> 5 ways (2 + 3) 81 | 5 stairs -> 8 ways (3 + 5) 82 | */ 83 | var bottomUp: [Int] = [] 84 | bottomUp.append(1) // 0 stairs -> 1 way 85 | bottomUp.append(2) // 1 stairs -> 1 way 86 | bottomUp.append(3) // 2 stairs -> 2 ways 87 | 88 | /** 89 | Since we're forming bounds from 3 up to n, 90 | we need to make sure, 91 | that we actually have n > 3 92 | otherwise we'll run into bounds forming errors. 93 | */ 94 | if n > 2 { 95 | 96 | for index in 3...n + 1 { 97 | 98 | bottomUp.append(bottomUp[index - 1] + bottomUp[index - 2]) 99 | } 100 | } 101 | 102 | return bottomUp[n - 1] 103 | } -------------------------------------------------------------------------------- /leetcode-700-search-in-a-binary-search-tree.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/search-in-a-binary-search-tree/ 28 | 29 | 30 | Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL. 31 | 32 | For example, 33 | 34 | Given the tree: 35 | 4 36 | / \ 37 | 2 7 38 | / \ 39 | 1 3 40 | 41 | And the value to search: 2 42 | You should return this subtree: 43 | 44 | 2 45 | / \ 46 | 1 3 47 | In the example above, if we want to search the value 5, since there is no node with value 5, we should return NULL. 48 | 49 | Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null. 50 | 51 | */ 52 | 53 | /** 54 | Big O Annotation 55 | Time complexity O(log n) where n is the amount of nodes in the BST. 56 | Space complexity O(1) we're not using any extra space. 57 | */ 58 | func searchBST(_ root: TreeNode?, _ val: Int) -> TreeNode? { 59 | 60 | // Check that the node exists 61 | guard let node = root else { 62 | return nil 63 | } 64 | 65 | /** 66 | We found our candidate 67 | if the current node's val equals val 68 | */ 69 | if node.val == val { 70 | 71 | return node 72 | 73 | /** 74 | Otherwise if value smaller than the node's value, 75 | continue down the left branch 76 | */ 77 | } else if node.val > val { 78 | 79 | return searchBST(node.left, val) 80 | 81 | // Else down the right branch 82 | } else { 83 | 84 | return searchBST(node.right, val) 85 | } 86 | } -------------------------------------------------------------------------------- /leetcode-706-design-hashmap.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/design-hashmap/ 28 | 29 | 30 | Design a HashMap without using any built-in hash table libraries. 31 | 32 | To be specific, your design should include these functions: 33 | 34 | put(key, value) : Insert a (key, value) pair into the HashMap. If the value already exists in the HashMap, update the value. 35 | get(key): Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key. 36 | remove(key) : Remove the mapping for the value key if this map contains the mapping for the key. 37 | 38 | */ 39 | 40 | /** 41 | Big O Annotation 42 | Time complexity O(1) all operations are in constant time. 43 | Space complexity O(1) we have a constant allocation of space. 44 | */ 45 | class MyHashMap { 46 | 47 | private var array: [Int] 48 | 49 | /** Initialize your data structure here. */ 50 | init() { 51 | array = Array(repeating: -1, count: 1000001) 52 | } 53 | 54 | /** value will always be non-negative. */ 55 | func put(_ key: Int, _ value: Int) { 56 | array[key] = value 57 | } 58 | 59 | /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ 60 | func get(_ key: Int) -> Int { 61 | return array[key] 62 | } 63 | 64 | /** Removes the mapping of the specified value key if this map contains a mapping for the key */ 65 | func remove(_ key: Int) { 66 | array[key] = -1 67 | } 68 | } -------------------------------------------------------------------------------- /leetcode-78-subsets.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/subsets/ 28 | 29 | 30 | Given a set of distinct integers, nums, return all possible subsets (the power set). 31 | 32 | Note: The solution set must not contain duplicate subsets. 33 | 34 | Example: 35 | 36 | Input: nums = [1,2,3] 37 | Output: 38 | [ 39 | [3], 40 | [1], 41 | [2], 42 | [1,2,3], 43 | [1,3], 44 | [2,3], 45 | [1,2], 46 | [] 47 | ] 48 | 49 | */ 50 | 51 | /** 52 | Big O Annotation 53 | Time complexity O(2^n) where n is the amount of elements in nums. 54 | Space complexity O(n) where n is the amount of elements in nums. 55 | */ 56 | func subsets(_ nums: [Int]) -> [[Int]] { 57 | 58 | // Create the output array 59 | var subsets: [[Int]] = [] 60 | 61 | // Add all subsets 62 | add(&subsets, for: nums) 63 | 64 | // And returns 65 | return subsets 66 | } 67 | 68 | private func add(_ subsets: inout [[Int]], for numbers: [Int], startAt index: Int = 0, current: [Int] = []) { 69 | 70 | // Add the current value of current to the output 71 | subsets.append(current) 72 | 73 | // Get a mutable copy of current 74 | var current = current 75 | 76 | // Iterate through the remaining indices 77 | for i in index..= (m + insertions) { 101 | 102 | nums1[pointer1] = element2 103 | pointer1 += 1 104 | break 105 | 106 | /** 107 | Else we just want to move the 108 | pointer of array 1 along 109 | */ 110 | } else { 111 | 112 | pointer1 += 1 113 | } 114 | } 115 | 116 | // And lastly move the pointer of array 2 forward 117 | pointer2 += 1 118 | } 119 | } -------------------------------------------------------------------------------- /leetcode-918-maximum-sum-circular-subarray.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/maximum-sum-circular-subarray/ 28 | 29 | 30 | Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty subarray of C. 31 | 32 | Here, a circular array means the end of the array connects to the beginning of the array. (Formally, C[i] = A[i] when 0 <= i < A.length, and C[i+A.length] = C[i] when i >= 0.) 33 | 34 | Also, a subarray may only include each element of the fixed buffer A at most once. (Formally, for a subarray C[i], C[i+1], ..., C[j], there does not exist i <= k1, k2 <= j with k1 % A.length = k2 % A.length.) 35 | 36 | 37 | 38 | Example 1: 39 | 40 | Input: [1,-2,3,-2] 41 | Output: 3 42 | Explanation: Subarray [3] has maximum sum 3 43 | Example 2: 44 | 45 | Input: [5,-3,5] 46 | Output: 10 47 | Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10 48 | Example 3: 49 | 50 | Input: [3,-1,2,-1] 51 | Output: 4 52 | Explanation: Subarray [2,-1,3] has maximum sum 2 + (-1) + 3 = 4 53 | Example 4: 54 | 55 | Input: [3,-2,2,-3] 56 | Output: 3 57 | Explanation: Subarray [3] and [3,-2,2] both have maximum sum 3 58 | Example 5: 59 | 60 | Input: [-2,-3,-1] 61 | Output: -1 62 | Explanation: Subarray [-1] has maximum sum -1 63 | 64 | 65 | Note: 66 | 67 | -30000 <= A[i] <= 30000 68 | 1 <= A.length <= 30000 69 | 70 | */ 71 | 72 | /** 73 | Big O Annotation 74 | Time complexity O(n) where n is the amount of elements in A. 75 | Space complexity O(1) we're not using any extra space. 76 | */ 77 | func maxSubarraySumCircular(_ A: [Int]) -> Int { 78 | 79 | guard !A.isEmpty else { 80 | return 0 81 | } 82 | 83 | /** 84 | Initialize all min and max values 85 | with A's first element 86 | */ 87 | var currentMax: Int = A[0] 88 | var totalMax: Int = A[0] 89 | var currentMin: Int = A[0] 90 | var totalMin: Int = A[0] 91 | 92 | // Including the sum 93 | var sum: Int = A[0] 94 | 95 | // Iterate starting form the 2nd element 96 | for index in 1.. [Int] { 52 | 53 | var result: [Int] = [] 54 | root?.traverseInOrder { result.append($0) } 55 | return result 56 | } 57 | 58 | extension TreeNode { 59 | 60 | /** 61 | Will be called recursively 62 | until the whole tree is traversed. 63 | */ 64 | func traverseInOrder(_ visit: (Int) -> Void) { 65 | 66 | // In order starts at the left node 67 | left?.traverseInOrder(visit) 68 | 69 | // Then the current value 70 | visit(val) 71 | 72 | // And last the right node 73 | right?.traverseInOrder(visit) 74 | } 75 | } -------------------------------------------------------------------------------- /leetcode-973-k-closest-points-to-origin.swift: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Copyright (c) 2020 David Seek, LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 19 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 20 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 21 | OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | 24 | 25 | 26 | 27 | https://leetcode.com/problems/k-closest-points-to-origin/ 28 | 29 | 30 | We have a list of points on the plane. Find the K closest points to the origin (0, 0). 31 | 32 | (Here, the distance between two points on a plane is the Euclidean distance.) 33 | 34 | You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.) 35 | 36 | 37 | 38 | Example 1: 39 | 40 | Input: points = [[1,3],[-2,2]], K = 1 41 | Output: [[-2,2]] 42 | Explanation: 43 | The distance between (1, 3) and the origin is sqrt(10). 44 | The distance between (-2, 2) and the origin is sqrt(8). 45 | Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. 46 | We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]]. 47 | Example 2: 48 | 49 | Input: points = [[3,3],[5,-1],[-2,4]], K = 2 50 | Output: [[3,3],[-2,4]] 51 | (The answer [[-2,4],[3,3]] would also be accepted.) 52 | 53 | */ 54 | 55 | /** 56 | Big O Annotation 57 | Time complexity O(n log n) because of the sorting overhead. 58 | Space complexity O(n) where n is the number elements in points. 59 | 60 | PS: I've also tried to solve the same challenge using a heap. 61 | But due to the siftDown/Up nature of adding elements to the heap, 62 | the final run time was taking just as long... 🤷🏻‍♂️ 63 | 64 | In my presented way we save a 65 | considerable amount of boilerplate code. 66 | */ 67 | func kClosest(_ points: [[Int]], _ K: Int) -> [[Int]] { 68 | 69 | /** 70 | Since the elements are supposed to be unique 71 | we can use a hashmap to store them. 72 | */ 73 | var hash: [String: Point] = [:] 74 | 75 | // Iterate through the points 76 | for element in points { 77 | 78 | let x = element[0] 79 | let y = element[1] 80 | 81 | // Calculate the Euclidean distance 82 | let distance = x * x + y * y 83 | 84 | // Create a point object... 85 | let point = Point(coordinate: element, distance: distance) 86 | 87 | // ... and store it into the map 88 | hash["\(x) \(y)"] = point 89 | } 90 | 91 | // Sort the map by distance of the points descending 92 | let sorted = hash.sorted { element1, element2 in 93 | return element1.value.distance < element2.distance 94 | } 95 | 96 | /** 97 | Map to get only a 2D array of 98 | the original coordinates 99 | */ 100 | let mapped = sorted.map { element in 101 | return element.coordinate 102 | } 103 | 104 | /** 105 | Return a new array splice of 0 106 | up to but not including K 107 | */ 108 | return Array(mapped[0.. Bool { 66 | return root?.isValidBST() ?? true 67 | } 68 | 69 | extension TreeNode { 70 | 71 | public func isValidBST(max: Int? = nil, min: Int? = nil) -> Bool { 72 | 73 | /** 74 | If self is we reached a leaf 75 | and the tree is a valid BST 76 | */ 77 | if self == nil { 78 | 79 | return true 80 | 81 | /** 82 | If the max is greater than val 83 | or the min smaller than val 84 | we have determined that our BST is invalid 85 | */ 86 | } else if (max != nil && val >= max!) || (min != nil && val <= min!) { 87 | 88 | return false 89 | 90 | /** 91 | Continue to recursively check the BST 92 | until we reach a leaf and exit on teh first clause 93 | */ 94 | } else { 95 | 96 | let leftValid = left?.isValidBST(max: val, min: min) ?? true 97 | let rightValid = right?.isValidBST(max: max, min: val) ?? true 98 | return leftValid && rightValid 99 | } 100 | } 101 | } --------------------------------------------------------------------------------