├── .gitignore ├── LICENSE ├── README.md ├── js ├── Combinations.js ├── Insert Interval.js ├── Maximum Subarray.js ├── Permutations.js ├── Remove Duplicates from Sorted Array.js ├── Reverse Integer.js ├── Run Length Encoding.js ├── Search In Rotated Sored Array.js ├── Subsets.js ├── Two Sum.js ├── Unique Path.js ├── Word Break.js ├── Word Ladder.js └── package.json └── swift ├── Best Time to Buy and Sell Stock II.playground ├── Contents.swift └── contents.xcplayground ├── Best Time to Buy and Sell Stock III.playground ├── Contents.swift └── contents.xcplayground ├── Best Time to Buy and Sell Stock.playground ├── Contents.swift └── contents.xcplayground ├── Candy.playground ├── Contents.swift └── contents.xcplayground ├── Climbing Stairs.playground ├── Contents.swift └── contents.xcplayground ├── Combination Sum II.playground ├── Contents.swift ├── contents.xcplayground └── timeline.xctimeline ├── Combination Sum.playground ├── Contents.swift ├── contents.xcplayground └── timeline.xctimeline ├── Combinations.playground ├── Contents.swift ├── contents.xcplayground └── timeline.xctimeline ├── Count and Say.playground ├── Contents.swift └── contents.xcplayground ├── Distinct Subsequences.playground ├── Contents.swift └── contents.xcplayground ├── Edit Distance.playground ├── Contents.swift └── contents.xcplayground ├── FindOneNumber.playground ├── Contents.swift └── contents.xcplayground ├── Generate Parentheses.playground ├── Contents.swift ├── contents.xcplayground └── timeline.xctimeline ├── Implement strStr().playground ├── Contents.swift └── contents.xcplayground ├── Insert Interval.playground ├── Contents.swift └── contents.xcplayground ├── Interleaving String.playground ├── Contents.swift └── contents.xcplayground ├── Jump Game II.playground ├── Contents.swift └── contents.xcplayground ├── Jump Game.playground ├── Contents.swift └── contents.xcplayground ├── LeetCode.xcworkspace └── contents.xcworkspacedata ├── Length of Last Word.playground ├── Contents.swift └── contents.xcplayground ├── Longest Consecutive Sequence.playground ├── Contents.swift ├── contents.xcplayground └── playground.xcworkspace │ └── contents.xcworkspacedata ├── Longest Substring Without Repeating Characters.playground ├── Contents.swift └── contents.xcplayground ├── Maximum Subarray.playground ├── Contents.swift ├── contents.xcplayground └── timeline.xctimeline ├── Median of Two Sorted Arrays.playground ├── Contents.swift └── contents.xcplayground ├── Merge Intervals.playground ├── Contents.swift └── contents.xcplayground ├── Merge Sorted Array.playground ├── Contents.swift └── contents.xcplayground ├── Minimum Window Substring.playground ├── Contents.swift └── contents.xcplayground ├── Multiply Strings.playground ├── Contents.swift └── contents.xcplayground ├── N-Queens.playground ├── Contents.swift └── contents.xcplayground ├── Next Permutation.playground ├── Contents.swift └── contents.xcplayground ├── Palindrome Number.playground ├── Contents.swift └── contents.xcplayground ├── Palindrome Partitioning II.playground ├── Contents.swift └── contents.xcplayground ├── Palindrome Partitioning.playground ├── Contents.swift └── contents.xcplayground ├── Permutation Sequence.playground ├── Contents.swift ├── contents.xcplayground └── timeline.xctimeline ├── Permutations II.playground ├── Contents.swift ├── contents.xcplayground └── timeline.xctimeline ├── Permutations.playground ├── Contents.swift ├── contents.xcplayground └── timeline.xctimeline ├── Plus One.playground ├── Contents.swift └── contents.xcplayground ├── Regular Expression Matching.playground ├── Contents.swift └── contents.xcplayground ├── Remove Duplicates from Sorted Array.playground ├── Contents.swift ├── Sources │ └── SupportCode.swift ├── contents.xcplayground └── playground.xcworkspace │ └── contents.xcworkspacedata ├── Remove Element.playground ├── Contents.swift ├── contents.xcplayground └── timeline.xctimeline ├── Restore IP Addresses.playground ├── Contents.swift └── contents.xcplayground ├── Reverse Integer.playground ├── Contents.swift └── contents.xcplayground ├── Scramble String.playground ├── Contents.swift └── contents.xcplayground ├── Search for a Range.playground ├── Contents.swift └── contents.xcplayground ├── Search in Rotated Sorted Array.playground ├── Contents.swift └── contents.xcplayground ├── Simplify Path.playground ├── Contents.swift └── contents.xcplayground ├── Single Number II.playground ├── Contents.swift └── contents.xcplayground ├── Single Number.playground ├── Contents.swift └── contents.xcplayground ├── Subsets II.playground ├── Contents.swift ├── contents.xcplayground └── timeline.xctimeline ├── Subsets.playground ├── Contents.swift ├── contents.xcplayground └── timeline.xctimeline ├── Text Justification.playground ├── Contents.swift └── contents.xcplayground ├── Trapping Rain Water.playground ├── Contents.swift └── contents.xcplayground ├── Triangle.playground ├── Contents.swift ├── contents.xcplayground └── timeline.xctimeline ├── Two Sum.playground ├── Contents.swift └── contents.xcplayground ├── Unique Paths.playground ├── Contents.swift └── contents.xcplayground ├── Valid Palindrome.playground ├── Contents.swift └── contents.xcplayground ├── Valid Parentheses.playground ├── Contents.swift └── contents.xcplayground ├── Word Break II.playground ├── Contents.swift └── contents.xcplayground ├── Word Break.playground ├── Contents.swift └── contents.xcplayground ├── Word Ladder II.playground ├── Contents.swift └── contents.xcplayground └── Word Ladder.playground ├── Contents.swift └── contents.xcplayground /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | build/ 4 | *.pbxuser 5 | !default.pbxuser 6 | *.mode1v3 7 | !default.mode1v3 8 | *.mode2v3 9 | !default.mode2v3 10 | *.perspectivev3 11 | !default.perspectivev3 12 | xcuserdata 13 | *.xccheckout 14 | *.moved-aside 15 | DerivedData 16 | *.hmap 17 | *.ipa 18 | *.xcuserstate 19 | 20 | # CocoaPods 21 | # 22 | # We recommend against adding the Pods directory to your .gitignore. However 23 | # you should judge for yourself, the pros and cons are mentioned at: 24 | # http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control 25 | # 26 | # Pods/ 27 | 28 | # Logs 29 | logs 30 | *.log 31 | 32 | # Runtime data 33 | pids 34 | *.pid 35 | *.seed 36 | 37 | # Directory for instrumented libs generated by jscoverage/JSCover 38 | lib-cov 39 | 40 | # Coverage directory used by tools like istanbul 41 | coverage 42 | 43 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 44 | .grunt 45 | 46 | # Compiled binary addons (http://nodejs.org/api/addons.html) 47 | build/Release 48 | 49 | # Dependency directory 50 | # Commenting this out is preferred by some people, see 51 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- 52 | node_modules 53 | 54 | # Users Environment Variables 55 | .lock-wscript 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Zhixuan Lai 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, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Algorithms 2 | ========== 3 | 4 | Answers to LeetCode questions in Swift and JavaScript 5 | 6 | Credit 7 | --- 8 | - [LeetCode solutions](https://github.com/soulmachine/leetcode) 9 | -------------------------------------------------------------------------------- /js/Combinations.js: -------------------------------------------------------------------------------- 1 | var should = require('should'); 2 | 3 | /* 4 | Given two integers n and k, return all possible combinations of k numbers out of 1...n. For example, If n = 4 and k = 2, a solution is: 5 | [ 6 | [2,4], 7 | [3,4], 8 | [2,3], 9 | [1,2], 10 | [1,3], 11 | [1,4], 12 | ] 13 | */ 14 | 15 | function combinations(n, k) { 16 | function helper(n, k, from, path, result) { 17 | if (path.length === k) { 18 | result.push(path.slice()); 19 | } else { 20 | for (var i = from; i< n; i++) { 21 | path.push(i); 22 | helper(n, k, i+1, path, result); 23 | path.pop(); 24 | } 25 | } 26 | } 27 | var result = []; 28 | helper(n+1, k, 1, [], result); 29 | return result; 30 | } 31 | 32 | describe("Combinations", function() { 33 | describe("I", function() { 34 | it("a", function() { 35 | var t = combinations(4,2); 36 | t.sort(); 37 | var e = [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]; 38 | e.sort(); 39 | t.should.containDeep(e); 40 | }); 41 | }); 42 | }); 43 | -------------------------------------------------------------------------------- /js/Insert Interval.js: -------------------------------------------------------------------------------- 1 | var should = require('should'); 2 | 3 | /* 4 | Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. 5 | Example 1: Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. 6 | Example 2: Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as 7 | [1,2],[3,10],[12,16]. 8 | This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. 9 | */ 10 | 11 | function inserAndMerge(a, insert) { 12 | function isOverlapping(a, b) { 13 | return a[1] >= b[0] && a[0] <= b[1]; 14 | } 15 | 16 | function merge(a, b) { 17 | return [Math.min(a[0], b[0]), Math.max(a[1], b[1])]; 18 | } 19 | 20 | var ret = []; 21 | var merged = insert; 22 | for (var i = 0; i< a.length; i++) { 23 | var interval = a[i]; 24 | if (isOverlapping(a[i], merged)) { 25 | merged = merge(merged, a[i]); 26 | } else { 27 | ret.push(interval); 28 | } 29 | } 30 | 31 | ret.push(merged); 32 | return ret; 33 | } 34 | 35 | 36 | describe("Insert intervals", function() { 37 | it("a", function() { 38 | var t = inserAndMerge([[1,3],[6,9]], [2,5]); 39 | t.sort(); 40 | var e = [[6,9], [1,5]]; 41 | e.sort(); 42 | t.should.containDeep(e); 43 | }); 44 | it("b", function() { 45 | var t = inserAndMerge([[6,9], [1,3]], [2,5]); 46 | t.sort(); 47 | var e = [[6,9], [1,5]]; 48 | e.sort(); 49 | t.should.containDeep(e); 50 | }); 51 | it("c", function() { 52 | var t = inserAndMerge([[6,9],[4,5], [1,3]], [2,5]); 53 | t.sort(); 54 | var e = [[6,9], [1,5]]; 55 | e.sort(); 56 | t.should.containDeep(e); 57 | e.should.containDeep(t); 58 | }); 59 | it("d", function() { 60 | var t = inserAndMerge([[6,9],[4,5], [2,3]], [3,4]); 61 | t.sort(); 62 | var e = [[6,9], [2,5]]; 63 | e.sort(); 64 | t.should.containDeep(e); 65 | e.should.containDeep(t); 66 | }); 67 | 68 | }); 69 | -------------------------------------------------------------------------------- /js/Maximum Subarray.js: -------------------------------------------------------------------------------- 1 | var should = require('should'); 2 | 3 | /* 4 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 5 | For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6. 6 | */ 7 | 8 | function maxSubarray(a) { 9 | var opt = []; 10 | for (var from = 0; from < a.length; from++) { 11 | opt[from] = new Array(a.length); 12 | opt[from] = opt[from].map(function() {return 0;}); 13 | opt[from][from] = a[from]; 14 | for (var to = from+1; to < a.length; to++) { 15 | opt[from][to] = opt[from][to-1] + a[to]; 16 | } 17 | } 18 | 19 | var max = Number.MIN_VALUE; 20 | var maxRange = []; 21 | for (var from = 0; from < a.length; from++) { 22 | for (var to = from; to < a.length; to++) { 23 | if (opt[from][to]>max) { 24 | max = opt[from][to]; 25 | maxRange = [from, to+1]; 26 | } 27 | } 28 | } 29 | 30 | return Array.prototype.slice.apply(a, maxRange); 31 | } 32 | 33 | 34 | function maxSubarraySum(a) { 35 | var maxSum = a[0]; 36 | var f = a[0]; 37 | for (var i = 0; i= a.length) { 91 | acc.push(path.slice()); 92 | } else { 93 | // for (var j = i; i< a.length; i++) { 94 | // if (j !== 0 && a[j] === a[j-1]) { 95 | // continue; 96 | // } 97 | // } 98 | 99 | // if (i>0 && a[i] === a[i-1]) { 100 | // helper(a, i+1, path, acc); 101 | // return; 102 | // } 103 | 104 | path.push(a[i]); 105 | helper(a, i+1, path, acc); 106 | path.pop(); 107 | 108 | helper(a, i+1, path, acc); 109 | 110 | } 111 | } 112 | a.sort(function(a, b) { 113 | return a - b; 114 | }); 115 | var acc = []; 116 | var path = []; 117 | helper(a, 0, path, acc); 118 | return acc; 119 | } 120 | 121 | describe("Subset", function() { 122 | it("I", function() { 123 | var t = subset([1, 2, 3]); 124 | t.sort(); 125 | var e = [ [3], [1], [2], [1, 2, 3], [1, 3], [2, 3], [1, 2], [] ]; 126 | e.sort(); 127 | t.should.containDeep(e); 128 | }); 129 | 130 | it("II", function() { 131 | var t = subset2([1, 2, 2]); 132 | t.sort(); 133 | var e = [ [2], [1], [1,2,2], [2,2], [1,2], [] ]; 134 | e.sort(); 135 | t.should.containDeep(e); 136 | }); 137 | }); 138 | -------------------------------------------------------------------------------- /js/Two Sum.js: -------------------------------------------------------------------------------- 1 | var should = require('should'); 2 | 3 | /* Given an array of integers, find two numbers such that they add up to a specific target number. 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. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2 4 | */ 5 | 6 | function twoSum(a, n) { 7 | a.sort(function(a, b) { 8 | return a - b; 9 | }); 10 | var dict = a.reduce(function(acc, e, i) { 11 | acc[e] = i; 12 | return acc; 13 | }, {}); 14 | var ret = []; 15 | a.forEach(function(e, i) { 16 | var other = n-e; 17 | if (dict[other]) { 18 | ret = [i, dict[other]]; 19 | } 20 | }); 21 | return ret; 22 | } 23 | 24 | 25 | describe("Two Sum", function() { 26 | it("O(n)", function() { 27 | JSON.stringify(twoSum([2,7,11,15], 9)).should.equal(JSON.stringify([0,1])); 28 | JSON.stringify(twoSum([-3,1,3,15], 0)).should.equal(JSON.stringify([0,2])); 29 | // JSON.stringify(twoSum([1,1,2,6,6,6,55])).should.equal(JSON.stringify([1,2,6,55])); 30 | }); 31 | it("O(logn)", function() { 32 | // JSON.stringify(removeDuplicate2([1,1,2])).should.equal(JSON.stringify([1,1,2])); 33 | // JSON.stringify(removeDuplicate2([1,1,2,2,3,4,5,6])).should.equal(JSON.stringify([1,1,2,2,3,4,5,6])); 34 | // JSON.stringify(removeDuplicate2([1,1,2,6,6,6,55])).should.equal(JSON.stringify([1,1,2,6,6,55])); 35 | }); 36 | 37 | }); 38 | -------------------------------------------------------------------------------- /js/Unique Path.js: -------------------------------------------------------------------------------- 1 | var should = require('should'); 2 | 3 | /* 4 | A robot is located at the top-left corner of a m × n grid (marked ’Start’ in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ’Finish’ in the diagram below). How many possible unique paths are there? 5 | */ 6 | 7 | function uniquePath(m, n) { 8 | function helper(m, n, i, j, c) { 9 | if (i === m && j === n) { 10 | c.count++; 11 | } else { 12 | if (i= 0) { 17 | helper(s, dict, from, r); 18 | } 19 | } 20 | } 21 | } 22 | 23 | var r = { 24 | r: false 25 | }; 26 | helper(s, dict, 0, r); 27 | return r.r; 28 | } 29 | 30 | function wordBreakDP(s, dict) { 31 | var opt = []; 32 | for (var i = 0; i < s.length; i++) { 33 | opt[i] = false; 34 | } 35 | opt[0] = true; 36 | for (var i = 1; i <= s.length; i++) { 37 | for (var j = 0; j <= i; j++) { 38 | opt[i] = opt[i] || opt[j] && dict.indexOf(s.substring(i, j)) >= 0; 39 | } 40 | } 41 | return opt[opt.length - 1]; 42 | } 43 | 44 | /* 45 | Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. 46 | Return all such possible sentences. 47 | For example, given 48 | s = "catsanddog", 49 | dict = ["cat", "cats", "and", "sand", "dog"]. 50 | A solution is ["cats and dog", "cat sand dog"]. 51 | */ 52 | 53 | function wordBreak2(s, dict) { 54 | function helper(s, dict, to, path, r) { 55 | if (to === s.length) { 56 | r.push(path.join(" ")); 57 | } else { 58 | for (var from = to; from <= s.length; from++) { 59 | var substring = s.substring(to, from); 60 | if (dict.indexOf(substring) >= 0) { 61 | path.push(substring); 62 | helper(s, dict, from, path, r); 63 | path.pop(); 64 | } 65 | } 66 | } 67 | } 68 | 69 | var r = []; 70 | helper(s, dict, 0, [], r); 71 | return r; 72 | } 73 | 74 | function wordBreak2DP(s, dict) { 75 | var opt = Array.apply(null, new Array(s.length+1)).map(function() { 76 | return Array.apply(null, new Array(s.length+1)).map(function() { 77 | return false; 78 | }); 79 | }); 80 | 81 | for (var from = 0; from<=s.length; from++) { 82 | opt[from][from] = true; 83 | for (var to = from+1; to<=s.length; to++) { 84 | for (var m = 0; m<=to; m++) { 85 | opt[from][to] = opt[from][to] || opt[from][m] && dict.indexOf(s.substring(m, to))>=0; 86 | } 87 | } 88 | } 89 | 90 | function helper(s, dict, opt, from, path, result) { 91 | if (from === s.length) { 92 | result.push(path.join(" ")); 93 | } else { 94 | for (var to = from+1; to<=s.length; to++) { 95 | if (opt[from][to]) { 96 | path.push(s.substring(from, to)); 97 | helper(s, dict, opt, to, path, result); 98 | path.pop(); 99 | } 100 | } 101 | } 102 | } 103 | 104 | var lastRow = opt[opt.length - 1]; 105 | var isTrue = lastRow[lastRow.length - 1]; 106 | if (isTrue) { 107 | var result = []; 108 | helper(s, dict, opt, 0, [], result); 109 | return result; 110 | } else { 111 | return []; 112 | } 113 | } 114 | 115 | function test1(f) { 116 | it("a", function() { 117 | f("leetcode", ["leet", "code"]).should.eql(true); 118 | }); 119 | it("b", function() { 120 | f("leetcode3", ["leet", "code"]).should.eql(false); 121 | }); 122 | it("c", function() { 123 | f("iambatman", ["i", "am", "bat", "man"]).should.eql(true); 124 | }); 125 | it("d", function() { 126 | f("cargo", ["i", "am", "go", "car"]).should.eql(true); 127 | }); 128 | it("e", function() { 129 | f("cargo", ["i", "am", "car"]).should.eql(false); 130 | }); 131 | } 132 | 133 | function test2(f) { 134 | function helper(input, expect) { 135 | var t = f.apply(null, input); 136 | t.sort(); 137 | var e = expect; 138 | e.sort(); 139 | t.should.containDeep(e); 140 | } 141 | it("a", function() { 142 | helper(["leetcode", ["leet", "code"]], ["leet code"]); 143 | }); 144 | it("b", function() { 145 | helper(["catsanddog", ["cat", "cats", "and", "sand", "dog"]], ["cats and dog", "cat sand dog"]); 146 | }); 147 | it("c", function() { 148 | helper(["iambatman", ["i", "am", "bat", "man"]], ["i am bat man"]); 149 | }); 150 | } 151 | 152 | 153 | describe("Word Break", function() { 154 | describe("I DFS", function() { 155 | test1(wordBreak); 156 | }); 157 | describe("I DP", function() { 158 | test1(wordBreakDP); 159 | }); 160 | 161 | describe("II DFS", function() { 162 | test2(wordBreak2); 163 | }); 164 | 165 | describe("II DP", function() { 166 | test2(wordBreak2DP); 167 | }); 168 | 169 | }); 170 | -------------------------------------------------------------------------------- /js/Word Ladder.js: -------------------------------------------------------------------------------- 1 | var should = require('should'); 2 | 3 | /* 4 | Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that: 5 | • Only one letter can be changed at a time 6 | • Each intermediate word must exist in the dictionary 7 | For example, Given: 8 | start = "hit" 9 | end = "cog" 10 | dict = ["hot","dot","dog","lot","log"] 11 | As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", return its length 5. 12 | Note: 13 | • Return 0 if there is no such transformation sequence. 14 | • All words have the same length. 15 | • All words contain only lowercase alphabetic characters.. 16 | */ 17 | 18 | function wordLadder(start, end, dict) { 19 | 20 | function diffByOneChar(s1, s2) { 21 | if (s1.length != s2.length) { 22 | return false; 23 | } 24 | var nDiff = 0; 25 | for (var i = 0; i< s1.length; i++) { 26 | if (s1[i] != s2[i]) { 27 | nDiff ++; 28 | } 29 | } 30 | return nDiff === 1; 31 | } 32 | 33 | var queue = []; 34 | var visited = []; 35 | queue.push([start, 1]); 36 | while (queue.length > 0) { 37 | var first = queue.shift(); 38 | var curWord = first[0]; 39 | var depth = first[1]; 40 | if (diffByOneChar(curWord, end)) { 41 | return depth + 1; 42 | } else { 43 | for (var i = 0; i (https://zhxnlai.github.io/)", 10 | "license": "MIT", 11 | "devDependencies": { 12 | "should": "^4.6.5" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /swift/Best Time to Buy and Sell Stock II.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | /*: 6 | Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1. 7 | */ -------------------------------------------------------------------------------- /swift/Best Time to Buy and Sell Stock II.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Best Time to Buy and Sell Stock III.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | //func maxProfit(prices: [Int]) -> Int { 6 | // var opt = [Int](count: prices.count, repeatedValue: Int.min) 7 | // for var to=0; to 2 | -------------------------------------------------------------------------------- /swift/Best Time to Buy and Sell Stock.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | /*: 6 | Say you have an array for which the i-th element is the price of a given stock on day i. 7 | 8 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 9 | */ -------------------------------------------------------------------------------- /swift/Best Time to Buy and Sell Stock.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Candy.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | // not tested 6 | func minimunCandies(ratings: [Int]) -> Int { 7 | var increment = [Int]() 8 | 9 | var inc = 1 10 | for i in 1..ratings[i-1] { 12 | increment[i] = max(inc++, increment[i]) 13 | } else { 14 | inc = 1 15 | } 16 | } 17 | inc = 1 18 | for i in 2..ratings[i+1] { 21 | increment[i] = max(inc++, increment[i]) 22 | } else { 23 | inc = 1 24 | } 25 | } 26 | return increment.reduce(0, combine: +) 27 | } 28 | 29 | /*: 30 | There are N children standing in a line. Each child is assigned a rating value. 31 | You are giving candies to these children subjected to the following requirements: 32 | • Each child must have at least one candy. • Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? 33 | */ -------------------------------------------------------------------------------- /swift/Candy.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Climbing Stairs.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func climbingStairs(n: Int) -> Int { 6 | // f[0] = 0 7 | // f[1] = 1 8 | // f[2] = 2 9 | // f[3] = 3 10 | var prevStep = 0 11 | var step = 1 12 | 13 | for i in 2.. 2 | -------------------------------------------------------------------------------- /swift/Combination Sum II.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func combinationSum(set: [Int], t: Int) -> [[Int]] { 6 | if set.count == 0 { 7 | return [] 8 | } 9 | var uniqueSet = set.filter({e in contains(set, e)}).sorted(<) 10 | var result = [[Int]]() 11 | var path = [Int]() 12 | helper(set, t, uniqueSet.last!, &path, &result) 13 | return result.reduce([[Int]](), combine: {acc, e in 14 | var unique = true 15 | for ee in acc { 16 | if e==ee { 17 | unique = false 18 | } 19 | } 20 | if unique { 21 | return acc+[e] 22 | } else { 23 | return acc 24 | } 25 | }) 26 | } 27 | 28 | func helper(set: [Int], t: Int, to: Int, inout path: [Int], inout result: [[Int]]) { 29 | let sum = path.reduce(0, combine: +) 30 | if sum==t { 31 | result.append(path.reverse()) 32 | } else { 33 | for i in 0..a2 >...>ak). • The solution set must not contain duplicate combinations. For example, given candidate set 10,1,2,7,6,1,5 and target 8, A solution set is: 51 | [1, 7] [1, 2, 5] [2, 6] [1, 1, 6] 52 | */ -------------------------------------------------------------------------------- /swift/Combination Sum II.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /swift/Combination Sum II.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /swift/Combination Sum.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func combinationSum(set: [Int], t: Int) -> [[Int]] { 6 | if set.count == 0 { 7 | return [] 8 | } 9 | var uniqueSet = set.filter({e in contains(set, e)}).sorted(<) 10 | var result = [[Int]]() 11 | var path = [Int]() 12 | helper(set, t, 0, &path, &result) 13 | return result 14 | } 15 | 16 | func helper(set: [Int], gap: Int, from: Int, inout path: [Int], inout result: [[Int]]) { 17 | if gap == 0 { 18 | result.append(path) 19 | return 20 | } 21 | for i in from.. [[Int]] { 37 | if set.count == 0 { 38 | return [] 39 | } 40 | var uniqueSet = set.filter({e in contains(set, e)}).sorted(<) 41 | var result = [[Int]]() 42 | var path = [Int]() 43 | helper(set, t, uniqueSet.last!, &path, &result) 44 | return result 45 | } 46 | 47 | func helper(set: [Int], t: Int, to: Int, inout path: [Int], inout result: [[Int]]) { 48 | let sum = path.reduce(0, combine: +) 49 | if sum == t { 50 | result.append(path.reverse()) 51 | } 52 | for e in set { 53 | if e<=to && sum+e <= t { 54 | path.append(e) 55 | helper(set, t, e, &path, &result) 56 | path.removeLast() 57 | } 58 | } 59 | } 60 | 61 | combinationSum([7], 7) 62 | combinationSum([2,3,6,7], 7) 63 | */ 64 | 65 | 66 | 67 | /*: 68 | Given a set of candidate numbers (C ) and a target number (T ), find all unique combinations in C where the candidate numbers sums to T . The same repeated number may be chosen from C unlimited number of times. Note: • All numbers (including target) will be positive integers. • Elements in a combination(a1,a2,...,ak) must be in non-descendingorder.(ie,a1 ≤a2 ≤...≤ak). • The solution set must not contain duplicate combinations. For example, given candidate set 2,3,6,7 and target 7, A solution set is: [7] [2, 2, 3] 69 | * -------------------------------------------------------------------------------- /swift/Combination Sum.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /swift/Combination Sum.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /swift/Combinations.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func combinations(n: Int, k: Int) -> [[Int]] { 6 | var result = [[Int]]() 7 | var path = [Int]() 8 | helper(n+1, k, 1, &path, &result) 9 | return result 10 | } 11 | 12 | func helper(n: Int, k: Int, from: Int, inout path: [Int], inout result: [[Int]]) { 13 | if k==path.count { 14 | result.append(path) 15 | } else { 16 | for i in (from.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /swift/Combinations.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /swift/Count and Say.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | 6 | 7 | /*: 8 | The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1is read off as"one 1"or11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2", then "one 1" or 1211. Given an integer n, generate the nth sequence. Note: The sequence of integers will be represented as a string. 9 | */ -------------------------------------------------------------------------------- /swift/Count and Say.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Distinct Subsequences.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | extension String { 6 | subscript (i: Int) -> String { 7 | return String(Array(self)[i]) 8 | } 9 | subscript (r: Range) -> String { 10 | return String(Array(self)[r]) 11 | } 12 | } 13 | 14 | func distinctSubsequence(s: String, t: String) -> Int { 15 | let strlenS = count(s) 16 | let strlenT = count(t) 17 | if strlenS 2 | -------------------------------------------------------------------------------- /swift/Edit Distance.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | extension String { 6 | subscript (i: Int) -> String { 7 | return String(Array(self)[i]) 8 | } 9 | subscript (r: Range) -> String { 10 | return String(Array(self)[r]) 11 | } 12 | } 13 | 14 | func editDistance(start: String, end: String) -> Int { 15 | let strlenS = count(start), strlenE = count(end) 16 | var f = [[Int]](count: strlenS, repeatedValue: [Int](count: strlenE, repeatedValue: 0)) 17 | 18 | for i in 0.. 2 | -------------------------------------------------------------------------------- /swift/FindOneNumber.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | 6 | func findOneNumber(a: [Int]) -> Int { 7 | var c = a[0] 8 | var t = 1 9 | for i in a[1.. 2 | -------------------------------------------------------------------------------- /swift/Generate Parentheses.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func generateParentheses(n: Int) -> [String] { 6 | var result = [String]() 7 | var path = [String]() 8 | helper(n, 0, 0, &path, &result) 9 | return result 10 | } 11 | 12 | func helper(n: Int, numLeft: Int, numRight: Int, inout path: [String], inout result: [String]) { 13 | if numLeft == n && numRight == n { 14 | result.append("".join(path)) 15 | } else { 16 | path 17 | if numLeft < n { 18 | path.append("(") 19 | helper(n, numLeft+1, numRight, &path, &result) 20 | path.removeLast() 21 | } 22 | if numRight < n && numRight < numLeft { 23 | path.append(")") 24 | helper(n, numLeft, numRight+1, &path, &result) 25 | path.removeLast() 26 | } 27 | } 28 | } 29 | 30 | generateParentheses(3) 31 | 32 | /*: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 33 | */ -------------------------------------------------------------------------------- /swift/Generate Parentheses.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /swift/Generate Parentheses.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /swift/Implement strStr().playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | /*: 6 | Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 7 | */ 8 | // 9 | //func strStr(haystack:String, needle:String) -> Int { 10 | // var start = 0, end = 0 11 | // 12 | // 13 | // 14 | // 15 | // 16 | // 17 | // 18 | // 19 | //} 20 | -------------------------------------------------------------------------------- /swift/Implement strStr().playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Insert Interval.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func insertAndMerge(a: [[Int]], insert: [Int]) -> [[Int]] { 6 | func isOverlapping(a: [Int])(b: [Int]) -> Bool { 7 | return a[0] <= b[1] && a[1] >= b[0] 8 | } 9 | 10 | func merge(a: [Int], b: [Int]) -> [Int] { 11 | return [min(a[0], b[0]), max(a[1], b[1])] 12 | } 13 | 14 | var overlappingIntervals = a.filter(isOverlapping(insert)) 15 | var mergedIntervals = overlappingIntervals.reduce(insert, combine: merge) 16 | 17 | var b = a.filter({x in !isOverlapping(insert)(b: x)}) 18 | b.append(mergedIntervals) 19 | return b 20 | } 21 | 22 | insertAndMerge([[1,3],[6,9]], [2,5]) 23 | insertAndMerge([[1,2],[3,5],[6,7],[8,10],[12,16]], [4,9]) 24 | 25 | /*: 26 | Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. Example 2: Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. 27 | */ -------------------------------------------------------------------------------- /swift/Insert Interval.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Interleaving String.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | extension String { 6 | subscript (i: Int) -> String { 7 | return String(Array(self)[i]) 8 | } 9 | subscript (r: Range) -> String { 10 | return String(Array(self)[r]) 11 | } 12 | } 13 | 14 | func isInterleave(s1: String, s2: String, s3: String) -> Bool { 15 | let strlen1 = count(s1), 16 | strlen2 = count(s2), 17 | strlen3 = count(s3) 18 | if strlen3 != strlen1+strlen2 { 19 | return false 20 | } 21 | if strlen1 == 0 || strlen2 == 0 { 22 | return true 23 | } 24 | 25 | var opt = [[Bool]](count: strlen1, repeatedValue: [Bool](count: strlen2, repeatedValue: false)) 26 | 27 | for var i=0; i 2 | -------------------------------------------------------------------------------- /swift/Jump Game II.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | /*: 6 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 7 | 8 | Each element in the array represents your maximum jump length at that position. 9 | 10 | Your goal is to reach the last index in the minimum number of jumps. 11 | 12 | For example: 13 | Given array A = [2,3,1,1,4] 14 | 15 | The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.) 16 | */ -------------------------------------------------------------------------------- /swift/Jump Game II.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Jump Game.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | 6 | 7 | /*: 8 | Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. 9 | Determine if you are able to reach the last index. 10 | For example: 11 | A = [2,3,1,1,4], return true. 12 | A = [3,2,1,0,4], return false. 13 | */ -------------------------------------------------------------------------------- /swift/Jump Game.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/LeetCode.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 7 | 9 | 10 | 12 | 13 | 15 | 16 | 18 | 19 | 21 | 22 | 24 | 25 | 27 | 28 | 30 | 31 | 33 | 34 | 36 | 37 | 39 | 40 | 42 | 43 | 45 | 46 | 48 | 49 | 51 | 52 | 54 | 55 | 56 | 59 | 61 | 62 | 64 | 65 | 67 | 68 | 70 | 71 | 73 | 74 | 76 | 77 | 78 | 81 | 83 | 84 | 85 | 88 | 90 | 91 | 93 | 94 | 96 | 97 | 99 | 100 | 102 | 103 | 105 | 106 | 108 | 109 | 111 | 112 | 114 | 115 | 117 | 118 | 119 | 122 | 124 | 125 | 127 | 128 | 130 | 131 | 133 | 134 | 136 | 137 | 139 | 140 | 142 | 143 | 144 | 147 | 149 | 150 | 152 | 153 | 154 | 157 | 159 | 160 | 162 | 163 | 165 | 166 | 168 | 169 | 171 | 172 | 173 | 176 | 178 | 179 | 181 | 182 | 184 | 185 | 187 | 188 | 190 | 191 | 193 | 194 | 196 | 197 | 198 | 201 | 203 | 204 | 205 | 208 | 210 | 211 | 213 | 214 | 216 | 217 | 219 | 220 | 222 | 223 | 224 | 225 | -------------------------------------------------------------------------------- /swift/Length of Last Word.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | 6 | func lengthOfLastWord(s: String) -> Int { 7 | let words = s.componentsSeparatedByString(" ") 8 | if let lastWord = words.last { 9 | return count(lastWord) 10 | } else { 11 | return 0 12 | } 13 | } 14 | 15 | lengthOfLastWord("hello world") 16 | 17 | /*: Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. For example, Given s = "Hello World", return 5. 18 | */ -------------------------------------------------------------------------------- /swift/Length of Last Word.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Longest Consecutive Sequence.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | /*: 4 | Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in O(n) complexity. 5 | 6 | */ 7 | 8 | func longestConsecutiveSequence(a:[Int]) -> Int { 9 | var dict = [Int: Bool]() 10 | 11 | for e in a { 12 | dict[e] = false 13 | } 14 | 15 | var longest = 0 16 | 17 | for e in a { 18 | if let visited = dict[e] { 19 | if visited { 20 | continue 21 | } 22 | } 23 | 24 | var l = 1 25 | dict[e] = true 26 | 27 | for var i = e+1; dict[i] != nil; i++ { 28 | l++ 29 | dict[i] = true 30 | } 31 | 32 | for var i = e-1; dict[i] != nil; i-- { 33 | l++ 34 | dict[i] = true 35 | } 36 | 37 | longest = max(longest, l) 38 | } 39 | 40 | return longest 41 | } 42 | 43 | longestConsecutiveSequence([1, 2, 3, 4]) 44 | longestConsecutiveSequence([100, 4, 200, 1, 3, 2]) 45 | -------------------------------------------------------------------------------- /swift/Longest Consecutive Sequence.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Longest Consecutive Sequence.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | -------------------------------------------------------------------------------- /swift/Longest Substring Without Repeating Characters.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | 6 | /*: 7 | Say you have an array for which the i-th element is the price of a given stock on day i. 8 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 9 | 10 | */ -------------------------------------------------------------------------------- /swift/Longest Substring Without Repeating Characters.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Maximum Subarray.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | 6 | func maximumSubarray(a: [Int]) -> [Int]{ 7 | var sum = [[Int]](count: a.count, repeatedValue: [Int](count: a.count, repeatedValue: 0)) 8 | for var from=0; from Int { 33 | let (result, ff) = a.reduce((0,0), combine: { (t, e) -> (Int, Int) in 34 | let (r, f) = t, 35 | newF = max(e, f+e), 36 | newR = max(r, newF) 37 | return (newR, newF) 38 | }) 39 | return result 40 | } 41 | 42 | maximumSubarraySum([-2,1,-3,4,-1,2,1,-5,4]) 43 | 44 | 45 | /*: 46 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6. 47 | */ -------------------------------------------------------------------------------- /swift/Maximum Subarray.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /swift/Maximum Subarray.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /swift/Median of Two Sorted Arrays.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | /*:: There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log(m + n)). 4 | */ 5 | 6 | // O(n) 7 | func median(a:[Int], b:[Int]) -> Int { 8 | var m = [Int]() 9 | var i = 0, j = 0 10 | 11 | while i < a.count && j < b.count { 12 | if a[i] < b[j] { 13 | m.append(a[i]) 14 | i++ 15 | } else { 16 | m.append(b[j]) 17 | j++ 18 | } 19 | } 20 | 21 | if i == a.count { 22 | m+=[Int](b[j...b.count-1]) 23 | } 24 | if j == b.count { 25 | m+=[Int](a[i...a.count-1]) 26 | } 27 | 28 | return m[m.count/2] 29 | } 30 | 31 | var A = [0,1,2,3,4,5] 32 | var B = [2,3,5] 33 | median(A, B) 34 | 35 | 36 | var A1 = [0,1,2,3,4,5] 37 | var B1 = [6,7,8] 38 | median(A1, B1) 39 | 40 | var A2 = [0,1,2,3,4,5] 41 | var B2 = [3,7,8] 42 | median(A2, B2) 43 | 44 | // O(log(n)) 45 | func median2(a:[Int], b:[Int]) -> Int { 46 | var i = 0, j = 0 47 | var total = a.count + b.count 48 | return findKth(a, b, total/2) 49 | } 50 | 51 | func findKth(a:[Int], b:[Int], k:Int) -> Int { 52 | if a.count>b.count { 53 | return findKth(b, a, k) 54 | } 55 | if a.count == 0 { 56 | return b[k-1] 57 | } 58 | if (k == 1) { 59 | return min(a[0], b[0]) 60 | } 61 | 62 | var ia = min(k/2, a.count), ib = k - ia 63 | if a[ia-1] < b[ib-1] { 64 | return findKth([Int](a[ia...a.count]), b, k-ia) 65 | } else if a[ia-1] > b[ib-1] { 66 | return findKth(a, [Int](ib...b.count), k-ia) 67 | } else { 68 | return a[ia-1] 69 | } 70 | } 71 | median2(A, B) 72 | median2(A1, B1) 73 | median2(A2, B2) 74 | 75 | 76 | -------------------------------------------------------------------------------- /swift/Median of Two Sorted Arrays.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Merge Intervals.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func mergeIntervals(intervals: [[Int]]) -> [[Int]] { 6 | var ret = [[Int]]() 7 | for interval in intervals { 8 | ret = insertAndMerge(ret, interval) 9 | } 10 | 11 | return ret 12 | } 13 | 14 | func insertAndMerge(a: [[Int]], insert: [Int]) -> [[Int]] { 15 | func isOverlapping(a: [Int])(b: [Int]) -> Bool { 16 | return a[0] <= b[1] && a[1] >= b[0] 17 | } 18 | 19 | func merge(a: [Int], b: [Int]) -> [Int] { 20 | return [min(a[0], b[0]), max(a[1], b[1])] 21 | } 22 | 23 | var overlappingIntervals = a.filter(isOverlapping(insert)) 24 | var mergedIntervals = overlappingIntervals.reduce(insert, combine: merge) 25 | 26 | var b = a.filter({x in !isOverlapping(insert)(b: x)}) 27 | b.append(mergedIntervals) 28 | return b 29 | } 30 | 31 | mergeIntervals([[1,3],[2,6],[8,10],[15,18]]) 32 | 33 | /*: 34 | Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18] 35 | */ -------------------------------------------------------------------------------- /swift/Merge Intervals.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Merge Sorted Array.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func mergeSort(a: [T], b: [T]) -> [T] { 6 | var c = [T](), ai = 0, bi = 0 7 | while aib[bi] { 9 | c.append(b[bi]) 10 | bi++ 11 | } else { 12 | c.append(a[ai]) 13 | ai++ 14 | } 15 | } 16 | return ai==a.count ? c+b[bi.. 2 | -------------------------------------------------------------------------------- /swift/Minimum Window Substring.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | extension String { 6 | subscript (i: Int) -> String { 7 | return String(Array(self)[i]) 8 | } 9 | subscript (r: Range) -> String { 10 | return String(Array(self)[r]) 11 | } 12 | } 13 | 14 | func minimumWindow(s: String, t: String) -> [String] { 15 | let slen = count(s), tlen = count(t) 16 | 17 | 18 | var minLen = Int.max, minString = "" 19 | var lower = 0, upper = 0 20 | 21 | var windows = [String]() 22 | 23 | for upper in 0.. Bool { 36 | var dict = [Character: Int]() 37 | for c in s { 38 | if let n = dict[c] { 39 | dict[c] = n+1 40 | } else { 41 | dict[c] = 1 42 | } 43 | } 44 | 45 | for c in t { 46 | if let n = dict[c] { 47 | } else { 48 | return false 49 | } 50 | } 51 | 52 | return true 53 | } 54 | 55 | minimumWindow("ADOBECODEBANC", "ABC") 56 | 57 | func minimumWindow2(s: String, t: String) -> String { 58 | let slen = count(s), tlen = count(t) 59 | 60 | var dictS = [Character: Int]() 61 | for c in s { 62 | if let n = dictS[c] { 63 | dictS[c] = n+1 64 | } else { 65 | dictS[c] = 1 66 | } 67 | } 68 | 69 | var dictT = [Character: Int]() 70 | for c in t { 71 | dictT[c] = 1 72 | if let n = dictS[c] { 73 | } else { 74 | return "" 75 | } 76 | } 77 | 78 | var lower = 0, upper = 0 79 | for lower = 0; lower=0; upper-- { 92 | var c = Array(s)[upper] 93 | if let isInT = dictT[c] { 94 | if let countInS = dictS[c] { 95 | dictS[c] = countInS-1 96 | if countInS-1 == 0 { 97 | break 98 | } 99 | } 100 | } 101 | } 102 | 103 | lower 104 | upper 105 | return s[lower...upper] 106 | } 107 | 108 | minimumWindow2("ADOBECODEBANC", "ABC") 109 | minimumWindow2("ADOBECODEBANCCCCC", "ABC") 110 | 111 | 112 | /*: 113 | Given a string S and a string T , find the minimum window in S which will contain all the characters in T in complexity O(n). For example, S = ”ADOBECODEBANC”, T = ”ABC” Minimum window is ”BANC”. Note: • If there is no such window in S that covers all characters in T, return the emtpy string ””. • If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. 114 | */ -------------------------------------------------------------------------------- /swift/Minimum Window Substring.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Multiply Strings.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | /*: 6 | Given two numbers represented as strings, return multiplication of the numbers as a string. Note: The numbers can be arbitrarily large and are non-negative. 7 | */ -------------------------------------------------------------------------------- /swift/Multiply Strings.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/N-Queens.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | /*: 6 | The n-queens puzzle is the problem of placing n queens on an n × n chessboard such that no two queens attack each other. 7 | Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens’ placement, where 'Q' and '.' both indicate a queen and an empty space respectively. For example, There exist two distinct solutions to the 4-queens puzzle: [ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ] 8 | */ -------------------------------------------------------------------------------- /swift/N-Queens.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Next Permutation.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | /*: 6 | Implement next permutation, which rearranges numbers into the lexicographically next greater permu- tation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascend- ing order). The replacement must be in-place, do not allocate extra memory. Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 1,2,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1 7 | */ 8 | 9 | func nextPermutation(a: [Int]) -> [Int] { 10 | var r = [Int](a) 11 | 12 | var t = 0, tIndex = 0 13 | for var i = r.count-1; i>=1; i-- { 14 | if r[i] > r[i-1] { 15 | t = r[i-1] 16 | tIndex = i-1 17 | break 18 | } 19 | } 20 | 21 | if tIndex==0 { 22 | return r.sorted(<) 23 | } 24 | 25 | for var i = r.count-1; i>tIndex; i-- { 26 | if r[i] > t { 27 | r[tIndex] = r[i] 28 | r[i] = t 29 | break 30 | } 31 | } 32 | 33 | return [Int](r[0...tIndex])+[Int](r[tIndex+1...r.count-1]).sorted(<) 34 | } 35 | 36 | nextPermutation([1,2,3]) 37 | 38 | nextPermutation([3,2,1]) 39 | 40 | nextPermutation([1,1,5]) 41 | 42 | nextPermutation([1,2,4,3]) 43 | 44 | nextPermutation([1,2,5,4,3]) -------------------------------------------------------------------------------- /swift/Next Permutation.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Palindrome Number.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func isPalindromeNumber(n: Int) -> Bool { 6 | var n = n 7 | if n < 0 { 8 | return false 9 | } 10 | var d = 1 11 | while n/d >= 10 { 12 | d *= 10 13 | } 14 | d 15 | while n>0 { 16 | var q = n/d 17 | var r = n%10 18 | if q != r { 19 | return false 20 | } 21 | n = n%d / 10 //remove first and last digit 22 | d/=100 23 | } 24 | return true 25 | } 26 | 27 | isPalindromeNumber(1223221) 28 | 29 | /*: 30 | Determine whether an integer is a palindrome. Do this without extra space. Some hints: Could negative integers be palindromes? (ie, -1) If you are thinking of converting the integer to string, note the restriction of using extra space. You could also try reversing an integer. However, if you have solved the problem ”Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case? There is a more generic way of solving this problem. 31 | */ -------------------------------------------------------------------------------- /swift/Palindrome Number.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Palindrome Partitioning II.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | extension String { 6 | subscript (i: Int) -> String { 7 | return String(Array(self)[i]) 8 | } 9 | subscript (r: Range) -> String { 10 | return String(Array(self)[r]) 11 | } 12 | } 13 | 14 | func isPalindrome(s: String) -> Bool { 15 | return s == String(Array(s).reverse()) 16 | } 17 | 18 | isPalindrome("aa") 19 | isPalindrome("aab") 20 | 21 | func palindromePartition(s: String) -> [[String]] { 22 | let strlen = count(s) 23 | var opt = [[Bool]](count: strlen, repeatedValue: [Bool](count: strlen, repeatedValue: false)) 24 | for var from=0; from Bool in 30 | return acc || (opt[0][f] && isPalindrome(s[f.. Int { 61 | let strlen = count(s) 62 | var opt = [Int](count: strlen+1, repeatedValue: Int.max) 63 | opt [0] = 0 64 | for var to = 1; to<=strlen; to++ { 65 | opt[to] = reduce(0.. Int in 66 | var subStr = s[from.. 2 | -------------------------------------------------------------------------------- /swift/Palindrome Partitioning.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | extension String { 6 | subscript (i: Int) -> String { 7 | return String(Array(self)[i]) 8 | } 9 | subscript (r: Range) -> String { 10 | return String(Array(self)[r]) 11 | } 12 | } 13 | 14 | func isPalindrome(s: String) -> Bool { 15 | return s == String(Array(s).reverse()) 16 | } 17 | 18 | func palindromePartition(s: String) -> [[String]] { 19 | var path = [String]() 20 | var result = [[String]]() 21 | helper(s, count(s), &path, &result) 22 | return result 23 | } 24 | 25 | func helper(s: String, to: Int, inout path: [String], inout result: [[String]]) { 26 | if to == 0 { 27 | result.append(path.reverse()) 28 | } 29 | for var from=0; from 2 | -------------------------------------------------------------------------------- /swift/Permutation Sequence.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | 6 | /*: 7 | The set [1,2,3,⋯,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, We get the following sequence (ie, for n = 3): "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9 inclusive. 8 | */ 9 | 10 | /*: 11 | 12 | 1,2,3,4 13 | 1,2,4,3 14 | 1,3,2,4 15 | 1,3,4,2 16 | 1,4,2,3 17 | 1,4,3,2 18 | 19 | 20 | 1, 2, 6, 24... 21 | 22 | 23 | 1,4,3,2 24 | 0,3,2,1 -> 0*6+3*2+1 25 | 26 | 27 | sort digits, 28 | n=4, k=6 29 | nn = [1,2,3,4] 30 | m = [1,2,6,24] 31 | 32 | k1 = k 33 | 34 | a1 = k(nFact[n-1]) 35 | k2 = k%(nFact[n-1]) 36 | 37 | a2 = k2/(nFact[n-2]) 38 | ... 39 | 40 | 3, 6 41 | nn = [1,2,3] 42 | nFact = [1,1,2,6] 43 | 44 | k1 = 6 45 | 46 | a1 = 6/2 = 3 47 | k2 = 6%2 = 0 48 | 49 | a2 = 0/1 = 0 50 | ak = 0%1 = 0 51 | 52 | 53 | 54 | 55 | */ 56 | 57 | func kthPermutationSequence(n:Int, k:Int) -> [Int] { 58 | var nFact = [1] 59 | for index in 1...n { 60 | nFact.append(index*(nFact[index-1])) 61 | } 62 | nFact 63 | var m = [Int]() 64 | for index in 1...n { 65 | m.append(index) 66 | } 67 | m 68 | 69 | var sequence = [Int]() 70 | var d = k 71 | for var i=n-1; i>0; i-- { 72 | var f = nFact[i+1] 73 | var a = d/f 74 | println("m before: \(m), a: \(a), d: \(d), nfact: \(f)") 75 | 76 | sequence.append(m[a]) 77 | m.removeAtIndex(a) 78 | println("m after: \(m)") 79 | d = d%(f) 80 | 81 | } 82 | sequence.append(m.first!) 83 | 84 | return sequence 85 | } 86 | 87 | kthPermutationSequence(3, 6 -------------------------------------------------------------------------------- /swift/Permutation Sequence.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /swift/Permutation Sequence.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /swift/Permutations II.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func permutations(s: [Int]) -> [[Int]] { 6 | var path = [Int]() 7 | var result = [[Int]]() 8 | helper(s.sorted(<), &path, &result) 9 | return result 10 | } 11 | 12 | func helper(s: [Int], inout path: [Int], inout result: [[Int]]) { 13 | if s.count == 0 { 14 | result.append(path) 15 | } else { 16 | for i in 0..0 && s[i] == s[i-1] { 18 | continue 19 | } 20 | let e = s[i] 21 | path.append(e) 22 | var newS = [Int](s) 23 | newS.removeAtIndex(i) 24 | helper(newS, &path, &result) 25 | path.removeLast() 26 | } 27 | } 28 | } 29 | 30 | permutations([1,1,2]) 31 | 32 | 33 | /*: 34 | Given a collection of numbers that might contain duplicates, return all possible unique permutations. 35 | 36 | For example, 37 | [1,1,2] have the following unique permutations: 38 | [1,1,2], [1,2,1], and [2,1,1]. 39 | */ -------------------------------------------------------------------------------- /swift/Permutations II.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /swift/Permutations II.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /swift/Permutations.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func permutations(s: [Int]) -> [[Int]] { 6 | var path = [Int]() 7 | var result = [[Int]]() 8 | helper(s, &path, &result) 9 | return result 10 | } 11 | 12 | func helper(s: [Int], inout path: [Int], inout result: [[Int]]) { 13 | if s.count == 0 { 14 | result.append(path) 15 | } else { 16 | for i in 0.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /swift/Permutations.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /swift/Plus One.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func plusOne(digits: [Int]) -> [Int] { 6 | var carry = 1 7 | var cur = digits.count-1 8 | var ret = [Int]() 9 | 10 | while cur>=0 { 11 | var digit = digits[cur] 12 | if digit+carry > 9 { 13 | digit = digit+carry-10 14 | carry = 1 15 | } else { 16 | digit += carry 17 | carry = 0 18 | } 19 | ret.insert(digit, atIndex: 0) 20 | cur-- 21 | } 22 | 23 | if carry != 0 { 24 | ret.insert(carry, atIndex: 0) 25 | carry = 0 26 | } 27 | 28 | return ret 29 | } 30 | 31 | plusOne([1]) 32 | plusOne([1,2,3]) 33 | plusOne([9,2,3]) 34 | plusOne([9,9,9]) 35 | 36 | 37 | func plusOne2(digits: [Int]) -> [Int] { 38 | var carry = 1 39 | var cur = digits.count-1 40 | var ret = [Int]() 41 | 42 | while cur>=0 { 43 | var digit = digits[cur] 44 | digit += carry 45 | carry = digit/10 46 | digit %= 10 47 | ret.insert(digit, atIndex: 0) 48 | cur-- 49 | } 50 | 51 | if carry != 0 { 52 | ret.insert(carry, atIndex: 0) 53 | carry = 0 54 | } 55 | 56 | return ret 57 | } 58 | 59 | plusOne2([1]) 60 | plusOne2([1,2,3]) 61 | plusOne2([9,2,3]) 62 | plusOne2([9,9,9]) 63 | 64 | /*: 65 | Given a number represented as an array of digits, plus one to the number. 66 | */ -------------------------------------------------------------------------------- /swift/Plus One.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Regular Expression Matching.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | extension String { 6 | subscript (i: Int) -> String { 7 | return String(Array(self)[i]) 8 | } 9 | } 10 | 11 | func isMatch(s: String, p: String) -> Bool { 12 | var startS = 0 13 | var startP = 0 14 | 15 | while startS 2 | -------------------------------------------------------------------------------- /swift/Remove Duplicates from Sorted Array.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | /*: 4 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 5 | Do not allocate extra space for another array, you must do this in place with constant memory. 6 | For example, Given input array A = [1,1,2], 7 | Your function should return length = 2, and A is now [1,2]. 8 | */ 9 | 10 | func removeDuplicates(a: [Int]) -> [Int] { 11 | var index = 0, array = [Int](a) 12 | 13 | for var i=0; i [Int] { 24 | var index = 0, array = [Int](a) 25 | 26 | for var i=1; i Int { 46 | var index = 0 47 | 48 | for var i=0; i [Int] { 73 | var r = 2; 74 | var a = [Int](a) 75 | for var i = 2; i < a.count; i++ { 76 | if (a[i] != a[r-2]) { 77 | a[r] = a[i] 78 | r++ 79 | } 80 | } 81 | return [Int](a[0.. [Int] { 86 | var index = 0, array = [Int](a) 87 | 88 | for var i=1; i [Int] { 112 | var index = 0, array = [Int](a) 113 | 114 | for var i=1; i 2 | -------------------------------------------------------------------------------- /swift/Remove Duplicates from Sorted Array.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /swift/Remove Element.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | /*: 6 | Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn’t matter what you leave beyond the new length. 7 | */ 8 | 9 | var A = [1,2,2,2,3,4,5,5,6,7] 10 | 11 | func removeElement(a:[Int], e:Int) -> [Int] { 12 | var index = 0, r = [Int](a) 13 | for var i=0; i 2 | 3 | 4 | -------------------------------------------------------------------------------- /swift/Remove Element.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /swift/Restore IP Addresses.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | extension String { 6 | subscript (i: Int) -> String { 7 | return String(Array(self)[i]) 8 | } 9 | subscript (r: Range) -> String { 10 | return String(Array(self)[r]) 11 | } 12 | } 13 | 14 | func restoreIpAddresses(s: String) -> [String] { 15 | var result = [String]() 16 | var path = [String]() 17 | helper(s, 0, &path, &result) 18 | return result 19 | } 20 | 21 | func helper(s: String, from: Int, inout path: [String], inout result: [String]) { 22 | let strlen = count(s) 23 | if from==strlen { 24 | result.append(".".join(path)) 25 | } 26 | for var to=from+1; to<=strlen; to++ { 27 | let subStr = s[from.. 2 | -------------------------------------------------------------------------------- /swift/Reverse Integer.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func reverse(n: Int) -> Int { 6 | var r = 0 7 | for var n=n; n != 0; n /= 10 { 8 | r = r*10 + n%10 9 | } 10 | return r 11 | } 12 | 13 | reverse(123) 14 | reverse(-123) 15 | 16 | /*: 17 | Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 Have you thought about this? Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100. Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases? Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter). 18 | */ -------------------------------------------------------------------------------- /swift/Reverse Integer.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Scramble String.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | 6 | /*: Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = ”great”: great /\ gr eat /\/\ g r e at /\ at 7 | To scramble the string, we may choose any non-leaf node and swap its two children. For example, if we choose the node ”gr” and swap its two children, it produces a scrambled string ”rgeat”. rgeat /\ rg eat /\/\ r g e at /\ at We say that ”rgeat” is a scrambled string of ”great”. Similarly, if we continue to swap the children of nodes ”eat” and ”at”, it produces a scrambled string ”rgtae”. rgtae /\ rg tae /\/\ r g ta e /\ ta We say that ”rgtae” is a scrambled string of ”great”. Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1. 8 | 9 | */ -------------------------------------------------------------------------------- /swift/Scramble String.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Search for a Range.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func searchForRange(a: [Int], target: Int) { 6 | 7 | } 8 | 9 | /*: 10 | Given a sorted array of integers, find the starting and ending position of a given target value. Your algorithm’s runtime complexity must be in the order of O(log n). 11 | If the target is not found in the array, return [-1, -1] 12 | For example, given [5,7,7,8,8,10] and target value 8, return [3,4] 13 | */ -------------------------------------------------------------------------------- /swift/Search for a Range.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Search in Rotated Sorted Array.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | /*: 4 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 5 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. 6 | */ 7 | 8 | func binarySearch(a:[Int], t:Int) -> Int { 9 | var f = 0, l = a.count 10 | while f != l { 11 | var mid = f+(l-f)/2 12 | if a[mid] == t { 13 | return mid 14 | } else if a[mid] > t { 15 | l = mid 16 | } else { 17 | f = mid+1 18 | } 19 | } 20 | return -1 21 | } 22 | 23 | var A = [0,1,2,3,4,5,6,7,8] 24 | binarySearch(A, 0) 25 | binarySearch(A, 3) 26 | binarySearch(A, 4) 27 | binarySearch(A, 8) 28 | binarySearch(A, 9) 29 | 30 | 31 | func search(a:[Int], t:Int) -> Int { 32 | var f = 0, l = a.count 33 | while f != l { 34 | var mid = f+(l-f)/2 35 | if a[mid] == t { 36 | return mid 37 | } 38 | // println("\(f) \(l) \(mid)") 39 | // the first half is continuous 40 | if a[mid]>a[l-1] { 41 | if a[f] <= t && t <= a[mid] { 42 | l = mid 43 | } else { 44 | f = mid+1 45 | } 46 | } else { 47 | if a[mid] < t && t <= a[l-1] { 48 | f = mid+1 49 | } else { 50 | l = mid 51 | } 52 | } 53 | } 54 | return -1 55 | } 56 | 57 | var B = [3,4,5,6,7,8,0,1,2] 58 | 59 | search(B, 3) 60 | search(B, 4) 61 | search(B, 5) 62 | search(B, 6) 63 | search(B, 7) 64 | search(B, 8) 65 | search(B, 0) 66 | search(B, 2) 67 | search(B, 9) 68 | 69 | 70 | -------------------------------------------------------------------------------- /swift/Search in Rotated Sorted Array.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Simplify Path.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func simplifyPath(path: String) -> String { 6 | var subPathsFiltered = path.componentsSeparatedByString("/").filter({$0 != "" && $0 != "."}) 7 | 8 | var subPathsDown = [String]() 9 | var subPathsUp = [String]() 10 | 11 | for subPath in subPathsFiltered { 12 | if subPath != ".." { 13 | if subPathsUp.count>0 { 14 | subPathsUp.removeLast() 15 | } else { 16 | subPathsDown.append(subPath) 17 | } 18 | } else { 19 | if subPathsDown.count>0 { 20 | subPathsDown.removeLast() 21 | } else { 22 | subPathsUp.append(subPath) 23 | } 24 | } 25 | } 26 | 27 | return "/"+"/".join(subPathsDown.count>0 ? subPathsDown : subPathsUp) 28 | } 29 | 30 | simplifyPath("/./") 31 | simplifyPath("/home/") 32 | simplifyPath("/a/./b/../../c/") 33 | simplifyPath("/../aa/") 34 | simplifyPath("/home//foo/") 35 | simplifyPath("/..//../") 36 | 37 | /*: 38 | Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" Corner Cases: • Did you consider the case where path="/../"? In this case, you should return "/". • Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". In this case, you should ignore redundant slashes and return "/home/foo". 39 | */ -------------------------------------------------------------------------------- /swift/Simplify Path.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Single Number II.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | 6 | 7 | /*: 8 | Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 9 | */ -------------------------------------------------------------------------------- /swift/Single Number II.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Single Number.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func singleNumber(a: [Int]) -> Int { 6 | return a.reduce(0, combine: ^) 7 | } 8 | 9 | singleNumber([1,1,2]) 10 | singleNumber([1,1,3,2,4,3,4]) 11 | 12 | /*: 13 | Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 14 | */ -------------------------------------------------------------------------------- /swift/Single Number.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Subsets II.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | 2 | // Playground - noun: a place where people can play 3 | 4 | import UIKit 5 | 6 | func subsets(s: [Int]) -> [[Int]] { 7 | var ret = [[Int]]() 8 | var path = [Int]() 9 | helper(s.sorted(<), 0, &path, &ret) 10 | return ret 11 | } 12 | 13 | func helper(s: [Int], from: Int, inout path: [Int], inout result: [[Int]]) { 14 | result.append(path) 15 | 16 | println(path) 17 | 18 | for i in from.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /swift/Subsets II.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /swift/Subsets.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | 6 | //func subsets(s: [Int]) -> [[Int]] { 7 | // var ret = [[Int]]() 8 | // for from in 0.. [[Int]] { 19 | var ret = [[Int]]() 20 | var path = [Int]() 21 | helper(s, 0, &path, &ret) 22 | return ret 23 | } 24 | 25 | func helper(s: [Int], from: Int, inout path: [Int], inout result: [[Int]]) { 26 | if from == s.count { 27 | result.append(path) 28 | } else { 29 | path.append(s[from]) 30 | helper(s, from+1, &path, &result) 31 | path.removeLast() 32 | 33 | helper(s, from+1, &path, &result) 34 | } 35 | } 36 | 37 | subsets2([1,2,3]) 38 | 39 | /*: 40 | Given a set of distinct integers, S, return all possible subsets. 41 | Note: 42 | • Elements in a subset must be in non-descending order. 43 | • The solution set must not contain duplicate subsets. 44 | For example, If S = [1,2,3], a solution is: 45 | 46 | [ 47 | [3], 48 | [1], 49 | [2], 50 | [1,2,3], 51 | [1,3], 52 | [2,3], 53 | [1,2], 54 | [] 55 | ] 56 | */ -------------------------------------------------------------------------------- /swift/Subsets.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /swift/Subsets.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /swift/Text Justification.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func textJustification(s: [String], max: Int) -> [String] { 6 | 7 | } 8 | 9 | 10 | 11 | 12 | /*: 13 | Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. 14 | You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters. 15 | 16 | Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. 17 | For the last line of text, it should be left justified and no extra space is inserted between words. 18 | For example, words: ["This", "is", "an", "example", "of", "text", "justification."] 19 | L: 16. 20 | Return the formatted lines as: 21 | [ 22 | "This is an", 23 | "example of text", 24 | "justification. " 25 | ] 26 | Note: Each word is guaranteed not to exceed L in length. 27 | Corner Cases: 28 | • A line other than the last line might contain only one word. What should you do in this case? 29 | • Inthiscase,thatlineshouldbeleft 30 | */ 31 | -------------------------------------------------------------------------------- /swift/Text Justification.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Trapping Rain Water.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | 6 | func trappingRainWater(heights: [Int]) -> Int { 7 | var maxLeft = [Int](count: heights.count, repeatedValue: 0) 8 | var maxRight = [Int](count: heights.count, repeatedValue: 0) 9 | 10 | for i in 1..heights[i] { 19 | sum += waterHeight-heights[i] 20 | } 21 | } 22 | 23 | return sum 24 | } 25 | 26 | trappingRainWater([0,1,0,2,1,0,1,3,2,1,2,1]) 27 | 28 | func trappingRainWater2(heights: [Int]) -> Int { 29 | 30 | var maxHeightIndex = 0 31 | var maxHeight = 0 32 | for i in 0..maxHeight { 35 | maxHeight = h 36 | maxHeightIndex = i 37 | } 38 | } 39 | 40 | var sum = 0 41 | var peakLeft = 0 42 | for i in 0..peakLeft { 45 | peakLeft = h 46 | } else { 47 | sum += peakLeft-h 48 | } 49 | } 50 | 51 | var peakRight = 0 52 | for var i = heights.count-1; i>=maxHeightIndex; i-- { 53 | let h = heights[i] 54 | if h>peakRight { 55 | peakRight = h 56 | } else { 57 | sum += peakRight-h 58 | } 59 | } 60 | return sum 61 | } 62 | 63 | trappingRainWater2([0,1,0,2,1,0,1,3,2,1,2,1]) 64 | 65 | 66 | /*: 67 | 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. 68 | 69 | For example, 70 | Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 71 | */ -------------------------------------------------------------------------------- /swift/Trapping Rain Water.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Triangle.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | 6 | func triangle(t: [[Int]]) -> Int { 7 | 8 | var opt = [[Int]](count: t.count, repeatedValue: [Int](count: t.count, repeatedValue: 0)) 9 | opt[t.count-1] = t[t.count-1] 10 | for var i=t.count-2; i>=0; i-- { 11 | for var j=0; j 2 | 3 | 4 | -------------------------------------------------------------------------------- /swift/Triangle.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /swift/Two Sum.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | /*: Given an array of integers, find two numbers such that they add up to a specific target number. 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. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2 6 | */ 7 | 8 | // O(n) 9 | func twoSum(a:[Int], t: Int) -> (Int, Int) { 10 | var dict = [Int:Int]() 11 | 12 | for var i=0; ii { 20 | return (i+1, found+1) 21 | } 22 | } 23 | } 24 | 25 | return (0,0) 26 | } 27 | 28 | twoSum([2,7,11,15], 9) 29 | twoSum([-3,1,3,15], 0) 30 | 31 | // nlog(n) 32 | func twoSum2(a:[Int], t: Int) -> [(Int, Int)] { 33 | var r = a.sorted(<) 34 | var ret = [(Int, Int)]() 35 | 36 | var start = 0, end = r.count-1 37 | 38 | while start t { 42 | end-- 43 | } else { 44 | ret.append((r[start], r[end])) 45 | start++ 46 | end-- 47 | } 48 | } 49 | 50 | return ret 51 | } 52 | 53 | twoSum2([2,7,11,15], 9) 54 | twoSum2([-3,1,3,15,-6,6], 0) 55 | 56 | //func twoSum2(a:[Int], t: Int) -> [(Int, Int)] { 57 | // var r = a.sorted(<) 58 | // var ret = [(Int, Int)]() 59 | // 60 | // for var i=0; i0 && r[i]==r[i-1] { 62 | // continue 63 | // } 64 | // var start = i, end = r.count-1 65 | // 66 | // while start 2 | -------------------------------------------------------------------------------- /swift/Unique Paths.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func uniquePaths(m: Int, n: Int) -> Int { 6 | var count = 0 7 | helper(0, 0, m-1, n-1, &count) 8 | return count 9 | } 10 | 11 | func helper(toM: Int, toN: Int, m: Int, n: Int, inout result: Int) { 12 | if toM==m && toN==n { 13 | result += 1 14 | } 15 | if toM < m { 16 | helper(toM+1, toN, m, n, &result) 17 | } 18 | if toN < n { 19 | helper(toM, toN+1, m, n, &result) 20 | } 21 | } 22 | 23 | uniquePaths(1,1) 24 | uniquePaths(2,2) 25 | uniquePaths(3,3) 26 | uniquePaths(3,7) 27 | 28 | /*: 29 | A robot is located at the top-left corner of a m × n grid (marked ’Start’ in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ’Finish’ in the diagram below). How many possible unique paths are there? 30 | */ -------------------------------------------------------------------------------- /swift/Unique Paths.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Valid Palindrome.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | /*: 6 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, ”A man, a plan, a canal: Panama” is a palindrome. ”race a car” is not a palindrome. Note: Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose of this problem, we define empty string as valid palindrome. 7 | */ 8 | 9 | 10 | func validPalindrome(s: String) -> Bool { 11 | var s = s.lowercaseString 12 | 13 | var start=0, end=Int(count(s))-1 14 | while !s[start].isAlpha() { 15 | start++ 16 | } 17 | while !s[end].isAlpha() { 18 | end-- 19 | } 20 | 21 | while (start String { 42 | return String(Array(self)[i]) 43 | } 44 | 45 | func isAlpha() -> Bool { 46 | return ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"].reduce(false, combine: { (acc, s1) -> Bool in 47 | acc || self==s1 48 | }) 49 | } 50 | 51 | } 52 | 53 | validPalindrome("aba") 54 | validPalindrome("acbca") 55 | validPalindrome("acbcaa") 56 | validPalindrome("A man, a plan, a canal: Panama") -------------------------------------------------------------------------------- /swift/Valid Palindrome.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Valid Parentheses.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | extension String { 6 | func contains(c: Character) -> Bool { 7 | for char in self { 8 | if char == c { 9 | return true 10 | } 11 | } 12 | return false 13 | } 14 | func indexOf(c: Character) -> Int { 15 | for i in 0.. Bool { 26 | let left = "({[" 27 | let right = ")}]" 28 | 29 | var stack = [Character]() 30 | 31 | for c in s { 32 | if left.contains(c) { 33 | stack.append(c) 34 | } else if right.contains(c) { 35 | if stack.count>0 { 36 | let leftC = stack.removeLast() 37 | if left.indexOf(leftC) != right.indexOf(c) { 38 | return false 39 | } 40 | } else { 41 | return false 42 | } 43 | } 44 | } 45 | return stack.count == 0 46 | } 47 | 48 | validParentheses("[](") 49 | validParentheses("]") 50 | validParentheses("([)]") 51 | validParentheses("()[]{}") 52 | validParentheses("()[d(]{}") 53 | 54 | /*: 55 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 56 | 57 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 58 | */ -------------------------------------------------------------------------------- /swift/Valid Parentheses.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Word Break II.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | extension String { 6 | subscript (i: Int) -> String { 7 | return String(Array(self)[i]) 8 | } 9 | subscript (r: Range) -> String { 10 | return String(Array(self)[r]) 11 | } 12 | } 13 | 14 | func wordBreak2(s: String, dict: [String]) -> [String] { 15 | let strlen = count(s) 16 | 17 | var opt = [[Bool]](count: strlen+1, repeatedValue: [Bool](count: strlen+1, repeatedValue: false)) 18 | for var from=0;from<=strlen;from++ { 19 | opt[from][from] = true 20 | for var to=from+1;to<=strlen;to++ { 21 | opt[from][to] = reduce((0.. Bool in 22 | if acc { 23 | return acc 24 | } 25 | return acc || (opt[from][n] && contains(dict, s[n.. 2 | -------------------------------------------------------------------------------- /swift/Word Break.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | /*: 6 | Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s = "leetcode", dict = ["leet", "code"]. Return true because "leetcode" can be segmented as "leet code". 7 | */ 8 | 9 | extension String { 10 | subscript (i: Int) -> String { 11 | return String(Array(self)[i]) 12 | } 13 | subscript (r: Range) -> String { 14 | return String(Array(self)[r]) 15 | } 16 | } 17 | 18 | func wordBreak(s: String, dict: [String]) -> Bool { 19 | let strlen = count(s) 20 | 21 | var opt = [Bool](count: strlen+1, repeatedValue: false) 22 | opt[0] = true 23 | for var to=1;to<=strlen;to++ { 24 | opt[to] = reduce((0.. Bool in 25 | return acc || (opt[n] && contains(dict, s[n.. 2 | -------------------------------------------------------------------------------- /swift/Word Ladder II.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func wordLadder(start: String, end: String, dict: [String]) -> [[String]] { 6 | 7 | func differByOneChar(s1: String, s2: String) -> Bool { 8 | if count(s1) != count(s2) { 9 | return false 10 | } 11 | var nDiff = 0 12 | for i in 0..0 { 26 | var (curWord, depth, path) = queue.removeAtIndex(0) 27 | if differByOneChar(curWord, end) { 28 | paths.append([start]+path+[end]) 29 | } 30 | for word in dict { 31 | if !contains(visited, word) && differByOneChar(curWord, word) { 32 | visited.append(word) 33 | queue.append((word, depth+1, path+[word])) 34 | } 35 | } 36 | } 37 | 38 | return paths 39 | } 40 | 41 | wordLadder("hit", "cog", ["hot","dot","dog","lot","log"]) 42 | /*: 43 | Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: 44 | - Only one letter can be changed at a time 45 | - Each intermediate word must exist in the dictionary 46 | 47 | For example, Given: 48 | start = "hit" 49 | end = "cog" 50 | dict = ["hot","dot","dog","lot","log"] 51 | Return 52 | [ 53 | ["hit","hot","dot","dog","cog"], 54 | ["hit","hot","lot","log","cog"] 55 | ] 56 | 57 | Note: 58 | - All words have the same length. 59 | - All words contain only lowercase alphabetic characters. 60 | */ -------------------------------------------------------------------------------- /swift/Word Ladder II.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /swift/Word Ladder.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | // Playground - noun: a place where people can play 2 | 3 | import UIKit 4 | 5 | func wordLadder(start: String, end: String, dict: [String]) -> Int { 6 | 7 | func differByOneChar(s1: String, s2: String) -> Bool { 8 | if count(s1) != count(s2) { 9 | return false 10 | } 11 | var nDiff = 0 12 | for i in 0..0 { 25 | var (curWord, depth) = queue.removeAtIndex(0) 26 | if differByOneChar(curWord, end) { 27 | return depth+1 28 | } 29 | for word in dict { 30 | if !contains(visited, word) && differByOneChar(curWord, word) { 31 | visited.append(word) 32 | queue.append((word, depth+1)) 33 | } 34 | } 35 | } 36 | 37 | return 0 38 | } 39 | 40 | wordLadder("hit", "cog", ["hot","dot","dog","lot","log"]) 41 | 42 | /*: 43 | Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that: 44 | • Only one letter can be changed at a time 45 | • Each intermediate word must exist in the dictionary 46 | For example, Given: 47 | start = "hit" 48 | end = "cog" 49 | dict = ["hot","dot","dog","lot","log"] 50 | As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", return its length 5. 51 | Note: • Return 0 if there is no such transformation sequence. • All words have the same length. • All words contain only lowercase alphabetic characters.. 52 | */ -------------------------------------------------------------------------------- /swift/Word Ladder.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | --------------------------------------------------------------------------------