[
  {
    "path": "Problems/2d inf grid shortest path.playground/Contents.swift",
    "content": "//: Playground - noun: a place where people can play\n\nimport UIKit\n\n/*\nYou are in an infinite 2D grid where you can move in any of the 8 directions:\n\n(x,y) to\n(x+1, y),\n(x - 1, y),\n(x, y+1),\n(x, y-1),\n(x-1, y-1),\n(x+1,y+1),\n(x-1,y+1),\n(x+1,y-1)\nYou are given a sequence of points and the order in which you need to cover the points. Give the minimum number of steps in which you can achieve it. You start from the first point.\n\nExample:\n\nInput: [(0, 0), (1, 1), (1, 2)]\nOutput: 2\nIt takes 1 step to move from (0, 0) to (1, 1). It takes one more step to move from (1, 1) to (1, 2).\n\n*/\n\nlet input = [(0, 0), (1, 1), (1, 2)]\nfunc shortest(current: Int, visited: inout [Bool], score: Int) -> Int {\n    \n    var min: Int?\n    \n    for i in 0 ..< input.count {\n        if visited[i] == true { continue }\n        visited[i] = true\n        let x = abs(input[i].0 - input[current].0)\n        let y = abs(input[i].1 - input[current].1)\n        let currentDistance = sqrt(Double(x * x + y * y))\n        let possible = Int(currentDistance) + shortest(current: i, visited: &visited, score: score)\n        if possible < min ?? Int.max {\n            min = possible\n        }\n    }\n    return score + (min ?? 0)\n}\n\nvar visited = Array(repeating: false, count: input.count)\nvisited[0] = true\nprint(shortest(current: 0, visited: &visited, score: 0))\n"
  },
  {
    "path": "Problems/2d inf grid shortest path.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/2d inf grid shortest path.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/2d inf grid shortest path.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/2d inf grid shortest path.playground/playground.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict/>\n</plist>\n"
  },
  {
    "path": "Problems/2d inf grid shortest path.playground/playground.xcworkspace/xcuserdata/denislitvin.xcuserdatad/WorkspaceSettings.xcsettings",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>BuildLocationStyle</key>\n\t<string>UseAppPreferences</string>\n\t<key>BuildSystemType</key>\n\t<string>Original</string>\n\t<key>CustomBuildLocationType</key>\n\t<string>RelativeToDerivedData</string>\n\t<key>DerivedDataLocationStyle</key>\n\t<string>Default</string>\n\t<key>EnabledFullIndexStoreVisibility</key>\n\t<false/>\n\t<key>IssueFilterStyle</key>\n\t<string>ShowActiveSchemeOnly</string>\n\t<key>LiveSourceIssuesEnabled</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/BTtoDLL.playground/Contents.swift",
    "content": "import UIKit\n\n/*\n Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be same as Inorder of the given Binary Tree. The first node of Inorder traversal (left most node in BT) must be head node of the DLL.\n */\nclass Node: CustomStringConvertible {\n    var description: String {\n        return String(value)\n    }\n    \n    let value: Int\n    var left: Node?\n    var right: Node?\n    init(_ value: Int) { self.value = value }\n}\n\nlet n1 = Node(1)\nlet n2 = Node(2)\nlet n3 = Node(3)\nlet n10 = Node(10)\nlet n20 = Node(20)\n\nn1.right = n20\nn1.left = n10\nn20.left = n2\nn20.right = n3\n\nprint(n1)\n\nfunc flaten(_ node: Node) {\n    let l = flattenHelper(node.left!, node)\n    let r = flattenHelper(node.right!, node)\n    node.left = l.right\n    node.right = r.left\n    l.right.right = node\n    r.left.left = node\n}\n\nfunc flattenHelper(_ node: Node, _ root: Node) -> (left: Node, right: Node) {\n    var leftReturn: Node?\n    var rightReturn: Node?\n    \n    if let left = node.left {\n        let l = flattenHelper(left, node)\n        leftReturn = l.left\n        node.left = l.right\n        l.right.right = node\n    }\n\n    if let right = node.right {\n        let r = flattenHelper(right, node)\n        rightReturn = r.right\n        node.right = r.left\n        r.left.left = node\n    }\n    return (left: leftReturn ?? node, right: rightReturn ?? node)\n}\n\nflaten(n1)\nn1.left\nn2.right\nn20.right\n"
  },
  {
    "path": "Problems/BTtoDLL.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/BTtoDLL.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/BTtoDLL.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/BitSet.playground/Contents.swift",
    "content": "import UIKit\n\n/*\n For [1, 2, 3], all possible subsets are {1},\n {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}\n print them\n */\n\nfunc bitSet(of array: [String]) {\n    let m = Int(pow(Double(2), Double(array.count)))\n    let BITS = Int.bitWidth\n    for i in 1 ..< m {\n        var current = [String]()\n        for b in 0 ..< BITS {\n            if 1 << b & i > 0 {\n                current.append(array[b])\n            }\n        }\n        print(current.reversed().joined())\n    }\n}\n\nbitSet(of: [\"0\",\"1\",\"2\", \"3\"])\n"
  },
  {
    "path": "Problems/BitSet.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/BitSet.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/BitSet.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/BrickWall.playground/Contents.swift",
    "content": "import Foundation\n\n/*\n There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.\n \n The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right.\n \n If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.\n \n You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.\n */\n\nfunc leastBricks(_ wall: [[Int]]) -> Int {\n    guard wall.count > 0 else { return 0 }\n    var offsetsWithHoles = Array(repeating: 0, count: 1000)\n    for row in wall {\n        var offset = 0\n        for brick in row.dropLast() {\n            offset += brick\n            offsetsWithHoles[offset] += 1\n        }\n    }\n    return wall.count - offsetsWithHoles.max()!\n}\n\nlet wall = [[1,2,2,1],\n            [3,1,2],\n            [1,3,2],\n            [2,4],\n            [3,1,2],\n            [1,3,1,1]]\nleastBricks(wall)\n"
  },
  {
    "path": "Problems/BrickWall.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/CalculateHealthInGenoms.playground/Contents.swift",
    "content": "import Foundation\n\nstruct Anchor {\n    let index: Int\n    let health: Int\n}\n\nstruct Strand {\n    let value: [Character]\n    let lowerBound: Int\n    let higherBound: Int\n}\n\nclass Node {\n    var value: Character!\n    var branches = [Character: Node]()\n    var anchors = [Anchor]()\n\n    init(value: Character? = nil) {\n        self.value = value\n    }\n    \n    func insertGene(string: String, index: Int, health: Int) {\n        if string.isEmpty { return }\n        var lastNode = self\n        for char in string {\n            lastNode = lastNode.makeBranch(with: char)\n        }\n        lastNode.anchors.append(Anchor(index: index, health: health))\n    }\n    \n    private func makeBranch(with char: Character) -> Node {\n        let node = branches[char] ?? Node(value: char)\n        branches[char] = node\n        return node\n    }\n}\n\nextension Node: CustomStringConvertible {\n    var description: String {\n        return \"anchors - \\(self.anchors) \\nbranches - \\(self.branches)\"\n    }\n}\n\n/*\n Calculate overall health in strand of genes.\n You presented with a table of genes, each gene has index and health value.\n Strand has requirements for possible genes indices it comprises of.\n Strand may contain repetitive genes with the same genom.\n \n Example:\n idx     0  1  2\n gen     a aa ab\n hp      2  3  4\n */\n\n\n//O(n) - time\n//O(n) - space\nfunc calculate(in strand: Strand, root: Node) -> Int {\n    var result = 0\n    for startIdx in 0 ..< strand.value.count {\n        result += calculateHelper(in: Strand(value: Array(strand.value.dropFirst(startIdx)),\n                                             lowerBound: strand.lowerBound,\n                                             higherBound: strand.higherBound),\n                                  node: root)\n    }\n    return result\n}\n\nfunc calculateHelper(in strand: Strand, node: Node) -> Int {\n    guard let char = strand.value.first else { return 0 }\n    var health = 0\n    if let branch = node.branches[char] {\n        branch.anchors.forEach { health += strand.lowerBound ... strand.higherBound ~= $0.index ? $0.health : 0 }\n        health += calculateHelper(in: Strand(value: Array(strand.value.dropFirst()),\n                                             lowerBound: strand.lowerBound,\n                                             higherBound: strand.higherBound),\n                                  node: branch)\n    }\n    return health\n}\n\nfunc findResult(for strands: [Strand], root: Node, health: [Int], genes: [String]) -> (min: Int, max: Int) {\n    var min: Int = Int.max\n    var max: Int = Int.min\n    \n    for strand in strands {\n        let result = calculate(in: strand, root: root)\n        if result < min { min = result }\n        if result > max { max = result }\n    }\n    return (min, max)\n}\n\n// SETUP\nlet rootNode = Node()\nlet genes = [\"a\", \"b\", \"c\", \"aa\", \"d\", \"b\"]\nlet health = [1, 2, 3, 4, 5, 6]\nlet strands = [\n    Strand(value: Array(\"caaab\"), lowerBound: 1, higherBound: 5),\n    Strand(value: Array(\"xyz\"), lowerBound: 0, higherBound: 4),\n    Strand(value: Array(\"bcdybc\"), lowerBound: 2, higherBound: 4)\n]\nfor i in 0 ..< genes.count {\n    rootNode.insertGene(string: genes[i], index: i, health: health[i])\n}\n\nfindResult(for: strands, root: rootNode, health: health, genes: genes)\n"
  },
  {
    "path": "Problems/CalculateHealthInGenoms.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/CoinChange.playground/Contents.swift",
    "content": "import UIKit\n\nlet arr = [1,2,3,4,5,6,7]\nlet sum = 10\n\nfunc count(s: [Int], n: Int, idx: Int, str: String) -> Int {\n    if n == 0 {\n        print(str)\n        return 1\n    }\n    if n < 0 {\n        return 0\n    }\n    var idx = idx\n    \n    while idx < s.count && s[idx] <= n {\n        let c = count(s: s, n: n - s[idx], idx: idx, str: str + \"\\(s[idx])\")\n        idx += 1\n    }\n    return 0\n}\n\ncount(s: arr, n: sum, idx: 0, str: \"\")\n\nfunc count2(_ S: [Int],_ m: Int, _ n: Int ) -> Int {\n    // If n is 0 then there is 1 solution\n    // (do not include any coin)\n    if (n == 0) {\n        return 1\n    }\n    \n    // If n is less than 0 then no\n    // solution exists\n    if (n < 0) {\n        return 0\n    }\n    // If there are no coins and n\n    // is greater than 0, then no\n    // solution exist\n    if (m <= 0 && n >= 1) {\n        return 0\n    }\n    // count is sum of solutions (i)\n    // including S[m-1] (ii) excluding S[m-1]\n    return count2( S, m - 1, n ) + count2( S, m, n-S[m-1] );\n}\n\ncount2(arr, arr.count, sum)\n\nfunc count3(_ S: [Int], _ m: Int,_ n: Int ) -> Int {\n    var x, y: Int\n    \n    // We need n+1 rows as the table\n    // is constructed in bottom up\n    // manner using the base case 0\n    // value case (n = 0)\n    var table = Array(repeating: Array(repeating: 0, count: m), count: n + 1)\n    \n    // Fill the enteries for 0\n    // value case (n = 0)\n    for i in 0 ..< m {\n        table[0][i] = 1\n    }\n    \n    // Fill rest of the table entries\n    // in bottom up manner\n    for i in 1 ..< n + 1 {\n        for j in 0 ..< m {\n            // Count of solutions including S[j]\n            x = (i-S[j] >= 0) ? table[i - S[j]][j] : 0\n            \n            // Count of solutions excluding S[j]\n            y = (j >= 1) ? table[i][j - 1] : 0\n            \n            // total count\n            table[i][j] = x + y\n        }\n    }\n    return table[n][m - 1]\n}\n\ncount3(arr, arr.count, sum)\n"
  },
  {
    "path": "Problems/CoinChange.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/CoinChange.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/CoinChange.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/DecodeWays.playground/Contents.swift",
    "content": "import Foundation\n/*\nA message containing letters from A-Z is being encoded to numbers using the following mapping:\n\n'A' -> 1\n'B' -> 2\n...\n'Z' -> 26\nGiven a non-empty string containing only digits, determine the total number of ways to decode it.\n\nExample 1:\n\nInput: \"12\"\nOutput: 2\nExplanation: It could be decoded as \"AB\" (1 2) or \"L\" (12).\nExample 2:\n\nInput: \"226\"\nOutput: 3\nExplanation: It could be decoded as \"BZ\" (2 26), \"VF\" (22 6), or \"BBF\" (2 2 6).\n*/\n\n//O(n)\nfunc numDecodings(_ s: String) -> Int {\n    guard !s.starts(with: \"0\") else { return 0}\n    var cache = [String.Index: Int]()\n    return decodeHelper(s, idx: s.startIndex, cache: &cache)\n}\n\nfunc decodeHelper(_ s: String, idx: String.Index, cache: inout [String.Index: Int]) -> Int {\n    guard idx < s.endIndex else { return 1 }\n    var res = 0\n    let nextIdx = s.index(after: idx)\n    \n    if let saved = cache[idx] { return saved }\n    \n    if s[idx] > \"0\" {\n        res += decodeHelper(s, idx: nextIdx, cache: &cache)\n        if  idx < s.index(before: s.endIndex) {\n            if s[idx] == \"1\" {\n                res += decodeHelper(s, idx: s.index(after: nextIdx), cache: &cache)\n            }\n            else if s[idx] == \"2\",\n                s[nextIdx] <= \"6\" {\n                res += decodeHelper(s, idx: s.index(after: nextIdx), cache: &cache)\n            }\n        }\n    }\n    \n    cache[idx] = res\n    \n    return res\n}\n\nnumDecodings(\"121212121212121212121212121212121212121121212121212\")\n"
  },
  {
    "path": "Problems/DecodeWays.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/DecodeWays.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/DecodeWays.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/DeepCopyLinkedList.playground/Contents.swift",
    "content": "import Foundation\n\nprecedencegroup LongArrowPrecedence {\n    associativity: left\n    higherThan: AssignmentPrecedence\n}\ninfix operator ~>: LongArrowPrecedence\n\nclass Node: CustomStringConvertible {\n    var description: String {\n        if next == nil { return \"\\(value)\" }\n        return \"\\(value) ~> \\(next!.description)\"\n    }\n    \n    var next: Node?\n    var random: Node?\n    var value: Int\n    \n    init(_ value: Int) {\n        self.value = value\n    }\n    \n    func copy() -> Node {\n        let node = Node(self.value)\n        return node\n    }\n    \n    static func ~>(lhs: Node, rhs: Node) -> Node {\n        lhs.next = rhs\n        return rhs\n    }\n    \n}\nextension Node: Hashable {\n    static func == (lhs: Node, rhs: Node) -> Bool {\n        return lhs === rhs\n    }\n    func hash(into hasher: inout Hasher) {\n        hasher.combine(value)\n        hasher.finalize()\n    }\n    \n}\n/*\nThis question was asked by Snapchat.\n\nGiven the head to a singly linked list, where each node also has a “random” pointer that points to anywhere in the linked list, deep clone the list.\n*/\n\nfunc copy(head: Node) -> Node {\n    let copyHead = head.copy()\n    var mapper = Dictionary<Node, Node>()\n    copyHelper(head: head, copyHead: copyHead, mapper: &mapper)\n    randomHelper(head: head, copyHead: copyHead, mapper: &mapper)\n    return copyHead\n}\nfunc copyHelper(head: Node, copyHead: Node, mapper: inout Dictionary<Node, Node>) {\n    if let next = head.next {\n        let nextCopy = next.copy()\n        copyHead.next = nextCopy\n        mapper[next] = nextCopy\n        copyHelper(head: next, copyHead: nextCopy, mapper: &mapper)\n    }\n}\n\nfunc randomHelper(head: Node?, copyHead: Node?, mapper: inout Dictionary<Node, Node>) {\n    if let head = head, let copyHead = copyHead {\n        if let random = head.random {\n            if let created = mapper[random] {\n                copyHead.random = created\n            }\n            else {\n                let newRandom = random.copy()\n                copyHead.random = newRandom\n                mapper[random] = newRandom\n            }\n        }\n        randomHelper(head: head.next, copyHead: copyHead.next, mapper: &mapper)\n        \n    }\n}\n\nlet head = Node(1)\nlet random3 = Node(3)\nlet random4 = Node(4)\nhead ~> Node(2) ~> random3 ~> random4 ~> Node(5)\nhead.random = random3\nrandom3.random = random4\nlet copyHead = copy(head: head)\nhead == copyHead //check false\nhead.random == copyHead.random //check false\ncopyHead.random == copyHead.next!.next! // check random3 true\n"
  },
  {
    "path": "Problems/DeepCopyLinkedList.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/DeepCopyLinkedList.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/DeepCopyLinkedList.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/Form a Palindrome.playground/Contents.swift",
    "content": "//: Playground - noun: a place where people can play\n\nimport UIKit\n\n//\n//Minimum insertions to form a palindrome | DP-28\n//Given a string, find the minimum number of characters to be inserted to convert it to palindrome.\n//\n//Before we go further, let us understand with few examples:\n//\n//ab: Number of insertions required is 1 i.e. bab\n//aa: Number of insertions required is 0 i.e. aa\n//abcd: Number of insertions required is 3 i.e. dcbabcd\n//abcda: Number of insertions required is 2 i.e. adcbcda which is same as number of insertions in the substring bcd(Why?).\n//abcde: Number of insertions required is 4 i.e. edcbabcde\n//\n\n//Let the input string be str[l……h]. The problem can be broken down into three parts:\n//1. Find the minimum number of insertions in the substring str[l+1,…….h].\n//2. Find the minimum number of insertions in the substring str[l…….h-1].\n//3. Find the minimum number of insertions in the substring str[l+1……h-1].\n//\n//Recursive Solution\n//The minimum number of insertions in the string str[l…..h] can be given as:\n//\n//minInsertions(str[l+1…..h-1]) if str[l] is equal to str[h]\n//min(minInsertions(str[l…..h-1]), minInsertions(str[l+1…..h])) + 1 otherwise\n\n//Naive approach\n//O(2^n) time\nfunc minToPalindrom(str: Array<Character>, left: Int, right: Int) -> Int {\n    \n    if left > right { return Int.max }\n    if left == right { return 0 }\n    if left == right - 1 { return str[left] == str[right] ? 0 : 1 }\n    \n    return str[left] == str[right]\n        ? minToPalindrom(str: str, left: left + 1, right: right - 1)\n        : min(\n            minToPalindrom(str: str, left: left + 1, right: right),\n            minToPalindrom(str: str, left: left, right: right - 1)\n        ) + 1\n}\nlet str = \"abqaa\"\nminToPalindrom(str: Array(str), left: 0, right: str.count - 1)\n\n\n//Dynamic Programming based Solution\n//If we observe the above approach carefully, we can find that it exhibits overlapping subproblems.\n//Suppose we want to find the minimum number of insertions in string “abcde”:\n//\n//                  abcde\n//           /            |      \\\n//          /             |        \\\n//        bcde           abcd    bcd  <- case 3 is discarded as str[l] != str[h]\n//     /   |   \\       /   |   \\\n//    /    |    \\     /    |    \\\n//  cde   bcd  cd   bcd abc bc\n// / | \\  / | \\ /|\\ / | \\\n//de cd d cd bc c………………….\n//The substrings in bold show that the recursion to be terminated and the recursion tree cannot originate from there. Substring in the same color indicates overlapping subproblems.\n//\n//How to reuse solutions of subproblems?\n//We can create a table to store results of subproblems so that they can be used directly if same subproblem is encountered again.\n//\n//The below table represents the stored values for the string abcde.\n//\n//a b c d e\n//----------\n//0 1 2 3 4\n//0 0 1 2 3\n//0 0 0 1 2\n//0 0 0 0 1\n//0 0 0 0 0\n//How to fill the table?\n//The table should be filled in diagonal fashion. For the string abcde, 0….4, the following should be order in which the table is filled:\n//\n//Gap = 1:\n//(0, 1) (1, 2) (2, 3) (3, 4)\n//\n//Gap = 2:\n//(0, 2) (1, 3) (2, 4)\n//\n//Gap = 3:\n//(0, 3) (1, 4)\n//\n//Gap = 4:\n//(0, 4)\n"
  },
  {
    "path": "Problems/Form a Palindrome.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/Form a Palindrome.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/Form a Palindrome.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/GenerateParenteses.playground/Contents.swift",
    "content": "import Foundation\n\n\n/*\n Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.\n \n For example, given n = 3, a solution set is:\n \n [\n \"((()))\",\n \"(()())\",\n \"(())()\",\n \"()(())\",\n \"()()()\"\n ]\n */\n\nfunc generateParenthesis(_ n: Int) -> [String] {\n    var result = [String]()\n    parenthesesHelper(n: n, openLeft: 0, stream: \"\", result: &result)\n    return result\n}\n\nfunc parenthesesHelper(n: Int, openLeft: Int, stream: String, result: inout [String]) {\n    if n != 0 {\n        parenthesesHelper(n: n - 1, openLeft: openLeft + 1, stream: stream + \"(\", result: &result)\n    }\n    if openLeft > 0 {\n        let newS = stream + \")\"\n        parenthesesHelper(n: n, openLeft: openLeft - 1, stream: newS, result: &result)\n    }\n    if n == 0 && openLeft == 0 {\n        result.append(stream)\n    }\n    return\n}\n\ngenerateParenthesis(2)\n"
  },
  {
    "path": "Problems/GenerateParenteses.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/LargestRect.playground/Contents.swift",
    "content": "import Foundation\n\nstruct Index: Hashable {\n    let row: Int\n    let column: Int\n    \n    func right() -> Index {\n        return Index(row: row, column: column + 1)\n    }\n    func left() -> Index {\n        return Index(row: row, column: column - 1)\n    }\n    func bottom() -> Index {\n        return Index(row: row + 1, column: column)\n    }\n    func top() -> Index {\n        return Index(row: row - 1, column: column)\n    }\n}\n/*\nThis question was asked by Google.\n\nGiven an N by M matrix consisting only of 1's and 0's, find the largest rectangle containing only 1's and return its area.\n\nFor example, given the following matrix:\n\n[[1, 0, 0, 0],\n[1, 0, 1, 1],\n[1, 0, 1, 1],\n[0, 1, 0, 0]]\n Return 4\n*/\n\nfunc largest(in matrix: [[Int]]) -> Int {\n    var visited = Set<Index>()\n    var max = 0\n    for row in 0 ..< matrix.count {\n        for column in 0 ..< matrix[row].count {\n            var rect = 0\n            largestHelper(index: Index(row: row, column: column), in: matrix, visited: &visited, count: &rect)\n            if rect > max { max = rect }\n        }\n    }\n    return max\n}\n\nfunc largestHelper(index: Index, in matrix: [[Int]], visited: inout Set<Index>, count: inout Int) {\n    if matrix[index.row][index.column] == 0\n        || visited.contains(index) { return }\n\n    count += 1\n    visited.insert(index)\n    \n    if withinBounds(index: index.right(), in: matrix) {\n        largestHelper(index: index.right(), in: matrix, visited: &visited, count: &count)\n    }\n    if withinBounds(index: index.left(), in: matrix) {\n        largestHelper(index: index.left(), in: matrix, visited: &visited, count: &count)\n    }\n    if withinBounds(index: index.top(), in: matrix) {\n        largestHelper(index: index.top(), in: matrix, visited: &visited, count: &count)\n    }\n    if withinBounds(index: index.bottom(), in: matrix) {\n        largestHelper(index: index.bottom(), in: matrix, visited: &visited, count: &count)\n    }\n    return\n}\n\nfunc withinBounds(index: Index, in matrix: [[Int]]) -> Bool {\n    return index.row < matrix.count\n        && index.row >= 0\n        && index.column < matrix[index.row].count\n        && index.column >= 0\n}\n\nlargest(in: [[1, 0, 0, 0],\n             [1, 0, 1, 1],\n             [1, 0, 1, 1],\n             [1, 0, 0, 0]])\n"
  },
  {
    "path": "Problems/LargestRect.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/LargestRect.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/LargestRect.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/LinkedListNumbersSum.playground/Contents.swift",
    "content": "import Foundation\n\nprecedencegroup LongArrowPrecedence {\n    associativity: left\n    higherThan: AssignmentPrecedence\n}\ninfix operator ~>: LongArrowPrecedence\n\nclass Node: CustomStringConvertible{\n    var description: String {\n        if next == nil { return \"\\(value)\" }\n        return \"\\(value) ~> \\(next!.description)\"\n    }\n    \n    var next: Node?\n    var value: Int\n    init(_ value: Int) {\n        self.value = value\n    }\n    static func ~>(lhs: Node, rhs: Node) -> Node {\n        lhs.next = rhs\n        return rhs\n    }\n    \n}\n/*\nThis problem was asked by Microsoft.\n\nLet's represent an integer in a linked list format by having each node represent a digit in the number. The nodes make up the number in reversed order.\n\nFor example, the following linked list:\n\n1 -> 2 -> 3 -> 4 -> 5\nis the number 54321.\n\nGiven two linked lists in this format, return their sum in the same linked list format.\n\nFor example, given\n\n9 -> 9\n5 -> 2\nreturn 124 (99 + 25) as:\n\n4 -> 2 -> 1\n*/\n\n//time O(n)\n//space O(n)\nfunc sum(left: Node, right: Node) -> Node {\n    return sumHelper(left: left, right: right, additionalValue: 0)!\n}\n\nfunc sumHelper(left: Node?, right: Node?, additionalValue: Int) -> Node? {\n    guard left != nil\n        || right != nil\n        || additionalValue != 0\n        else { return nil }\n    \n    let lValue = left?.value ?? 0\n    let rValue = right?.value ?? 0\n    let result = lValue + rValue + additionalValue\n    let resultNode = Node(result % 10)\n    resultNode.next = sumHelper(left: left?.next, right: right?.next, additionalValue: result / 10)\n    \n    return resultNode\n}\n\nlet left = Node(9)\nleft ~> Node(2) ~> Node(3) //329\n\nlet right = Node(1)\nright ~> Node(2) ~> Node(10) //1021\nsum(left: left, right: right) //1350\n"
  },
  {
    "path": "Problems/LinkedListNumbersSum.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/LinkedListNumbersSum.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/LinkedListNumbersSum.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/Longest Palindromic Substring.playground/Contents.swift",
    "content": "//: Playground - noun: a place where people can play\n\nimport UIKit\n\n\n//Longest Palindromic Substring\n//Given a string, find the longest substring which is palindrome. For example, if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”.\n\n//O(n^2) time and O(1) space\nfunc longestPalindrom(str: Array<Character>) -> String {\n    \n    //helper\n    let longest: (Int, Int, Array<Character>)  -> (length: Int, start: Int) = { (left: Int, right: Int, str: Array<Character>) -> (Int, Int) in\n        \n        var maxLength = 0\n        var maxStart = 0\n        var left = left\n        var right = right\n        \n        while left >= 0,\n            right < str.count,\n            str[left] == str[right] {\n                let length = right - left + 1\n                maxLength = length\n                maxStart = left\n                left -= 1\n                right += 1\n        }\n        return (maxLength, maxStart)\n    }\n    \n    var maxLength = 1\n    var maxStart = 0\n    \n    for i in 1 ..< str.count {\n        \n        //case 'aba'\n        var left = i - 1\n        var right = i + 1\n        var result = longest(left, right, str)\n        if result.length > maxLength {\n            maxLength = result.length\n            maxStart = result.start\n        }\n        \n        //case 'aa'\n        left = i - 1\n        right = i\n        result = longest(left, right, str)\n        if result.length > maxLength {\n            maxLength = result.length\n            maxStart = result.start\n        }\n    }\n    return String(str[maxStart ..< maxStart + maxLength])\n}\n\nlongestPalindrom(str: Array(\"bbacbabb\"))\n"
  },
  {
    "path": "Problems/Longest Palindromic Substring.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/Longest Palindromic Substring.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/Longest Palindromic Substring.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/LongestRepeatingCharacterReplacement.playground/Contents.swift",
    "content": "import UIKit\n\npublic struct Heap<T> {\n    \n    /** The array that stores the heap's nodes. */\n    var nodes = [T]()\n    \n    /**\n     * Determines how to compare two nodes in the heap.\n     * Use '>' for a max-heap or '<' for a min-heap,\n     * or provide a comparing method if the heap is made\n     * of custom elements, for example tuples.\n     */\n    private var orderCriteria: (T, T) -> Bool\n    \n    /**\n     * Creates an empty heap.\n     * The sort function determines whether this is a min-heap or max-heap.\n     * For comparable data types, > makes a max-heap, < makes a min-heap.\n     */\n    public init(sort: @escaping (T, T) -> Bool) {\n        self.orderCriteria = sort\n    }\n    \n    /**\n     * Creates a heap from an array. The order of the array does not matter;\n     * the elements are inserted into the heap in the order determined by the\n     * sort function. For comparable data types, '>' makes a max-heap,\n     * '<' makes a min-heap.\n     */\n    public init(array: [T], sort: @escaping (T, T) -> Bool) {\n        self.orderCriteria = sort\n        configureHeap(from: array)\n    }\n    \n    /**\n     * Configures the max-heap or min-heap from an array, in a bottom-up manner.\n     * Performance: This runs pretty much in O(n).\n     */\n    private mutating func configureHeap(from array: [T]) {\n        nodes = array\n        for i in stride(from: (nodes.count/2-1), through: 0, by: -1) {\n            shiftDown(i)\n        }\n    }\n    \n    public var isEmpty: Bool {\n        return nodes.isEmpty\n    }\n    \n    public var count: Int {\n        return nodes.count\n    }\n    \n    /**\n     * Returns the index of the parent of the element at index i.\n     * The element at index 0 is the root of the tree and has no parent.\n     */\n    @inline(__always) internal func parentIndex(ofIndex i: Int) -> Int {\n        return (i - 1) / 2\n    }\n    \n    /**\n     * Returns the index of the left child of the element at index i.\n     * Note that this index can be greater than the heap size, in which case\n     * there is no left child.\n     */\n    @inline(__always) internal func leftChildIndex(ofIndex i: Int) -> Int {\n        return 2*i + 1\n    }\n    \n    /**\n     * Returns the index of the right child of the element at index i.\n     * Note that this index can be greater than the heap size, in which case\n     * there is no right child.\n     */\n    @inline(__always) internal func rightChildIndex(ofIndex i: Int) -> Int {\n        return 2*i + 2\n    }\n    \n    /**\n     * Returns the maximum value in the heap (for a max-heap) or the minimum\n     * value (for a min-heap).\n     */\n    public func peek() -> T? {\n        return nodes.first\n    }\n    \n    /**\n     * Adds a new value to the heap. This reorders the heap so that the max-heap\n     * or min-heap property still holds. Performance: O(log n).\n     */\n    public mutating func insert(_ value: T) {\n        nodes.append(value)\n        shiftUp(nodes.count - 1)\n    }\n    \n    /**\n     * Adds a sequence of values to the heap. This reorders the heap so that\n     * the max-heap or min-heap property still holds. Performance: O(log n).\n     */\n    public mutating func insert<S: Sequence>(_ sequence: S) where S.Iterator.Element == T {\n        for value in sequence {\n            insert(value)\n        }\n    }\n    \n    /**\n     * Allows you to change an element. This reorders the heap so that\n     * the max-heap or min-heap property still holds.\n     */\n    public mutating func replace(index i: Int, value: T) {\n        guard i < nodes.count else { return }\n        \n        remove(at: i)\n        insert(value)\n    }\n    \n    /**\n     * Removes the root node from the heap. For a max-heap, this is the maximum\n     * value; for a min-heap it is the minimum value. Performance: O(log n).\n     */\n    @discardableResult public mutating func remove() -> T? {\n        guard !nodes.isEmpty else { return nil }\n        \n        if nodes.count == 1 {\n            return nodes.removeLast()\n        } else {\n            // Use the last node to replace the first one, then fix the heap by\n            // shifting this new first node into its proper position.\n            let value = nodes[0]\n            nodes[0] = nodes.removeLast()\n            shiftDown(0)\n            return value\n        }\n    }\n    \n    /**\n     * Removes an arbitrary node from the heap. Performance: O(log n).\n     * Note that you need to know the node's index.\n     */\n    @discardableResult public mutating func remove(at index: Int) -> T? {\n        guard index < nodes.count else { return nil }\n        \n        let size = nodes.count - 1\n        if index != size {\n            nodes.swapAt(index, size)\n            shiftDown(from: index, until: size)\n            shiftUp(index)\n        }\n        return nodes.removeLast()\n    }\n    \n    /**\n     * Takes a child node and looks at its parents; if a parent is not larger\n     * (max-heap) or not smaller (min-heap) than the child, we exchange them.\n     */\n    internal mutating func shiftUp(_ index: Int) {\n        var childIndex = index\n        let child = nodes[childIndex]\n        var parentIndex = self.parentIndex(ofIndex: childIndex)\n        \n        while childIndex > 0 && orderCriteria(child, nodes[parentIndex]) {\n            nodes[childIndex] = nodes[parentIndex]\n            childIndex = parentIndex\n            parentIndex = self.parentIndex(ofIndex: childIndex)\n        }\n        \n        nodes[childIndex] = child\n    }\n    \n    /**\n     * Looks at a parent node and makes sure it is still larger (max-heap) or\n     * smaller (min-heap) than its childeren.\n     */\n    internal mutating func shiftDown(from index: Int, until endIndex: Int) {\n        let leftChildIndex = self.leftChildIndex(ofIndex: index)\n        let rightChildIndex = leftChildIndex + 1\n        \n        // Figure out which comes first if we order them by the sort function:\n        // the parent, the left child, or the right child. If the parent comes\n        // first, we're done. If not, that element is out-of-place and we make\n        // it \"float down\" the tree until the heap property is restored.\n        var first = index\n        if leftChildIndex < endIndex && orderCriteria(nodes[leftChildIndex], nodes[first]) {\n            first = leftChildIndex\n        }\n        if rightChildIndex < endIndex && orderCriteria(nodes[rightChildIndex], nodes[first]) {\n            first = rightChildIndex\n        }\n        if first == index { return }\n        \n        nodes.swapAt(index, first)\n        shiftDown(from: first, until: endIndex)\n    }\n    \n    internal mutating func shiftDown(_ index: Int) {\n        shiftDown(from: index, until: nodes.count)\n    }\n    \n}\n\n// MARK: - Searching\nextension Heap where T: Equatable {\n    \n    /** Get the index of a node in the heap. Performance: O(n). */\n    public func index(of node: T) -> Int? {\n        return nodes.index(where: { $0 == node })\n    }\n    \n    /** Removes the first occurrence of a node from the heap. Performance: O(n log n). */\n    @discardableResult public mutating func remove(node: T) -> T? {\n        if let index = index(of: node) {\n            return remove(at: index)\n        }\n        return nil\n    }\n    \n}\n\n\npublic struct PriorityQueue<T> {\n    fileprivate var heap: Heap<T>\n    \n    /*\n     To create a max-priority queue, supply a > sort function. For a min-priority\n     queue, use <.\n     */\n    public init(sort: @escaping (T, T) -> Bool) {\n        heap = Heap(sort: sort)\n    }\n    \n    public var isEmpty: Bool {\n        return heap.isEmpty\n    }\n    \n    public var count: Int {\n        return heap.count\n    }\n    \n    public func peek() -> T? {\n        return heap.peek()\n    }\n    \n    public mutating func enqueue(_ element: T) {\n        heap.insert(element)\n    }\n    \n    public mutating func dequeue() -> T? {\n        return heap.remove()\n    }\n    \n    /*\n     Allows you to change the priority of an element. In a max-priority queue,\n     the new priority should be larger than the old one; in a min-priority queue\n     it should be smaller.\n     */\n    public mutating func changePriority(index i: Int, value: T) {\n        return heap.replace(index: i, value: value)\n    }\n}\n\nextension PriorityQueue where T: Equatable {\n    public func index(of element: T) -> Int? {\n        return heap.index(of: element)\n    }\n}\n\n\nstruct Element {\n    let char: Character\n    let occurrence: Int\n}\n\n//424. Longest Repeating Character Replacement\n/*\n Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.\n \n Note:\n Both the string's length and k will not exceed 104.\n \n Example 1:\n \n Input:\n s = \"ABAB\", k = 2\n \n Output:\n 4\n \n Explanation:\n Replace the two 'A's with two 'B's or vice versa.\n Example 2:\n \n Input:\n s = \"AABABBA\", k = 1\n \n Output:\n 4\n \n Explanation:\n Replace the one 'A' in the middle with 'B' and form \"AABBBBA\".\n The substring \"BBBB\" has the longest repeating letters, which is 4.\n */\n\nfunc characterReplacement(_ s: String, _ k: Int) -> Int {\n    var occurrences = [Character: Int]()\n    for c in s {\n        if let oldValue = occurrences[c] {\n            occurrences[c] = oldValue + 1\n        }\n        else {\n            occurrences[c] = 1\n        }\n    }\n    \n    var priorityQueue = PriorityQueue<Element>(sort: { left, right in\n        return left.occurrence > right.occurrence\n    })\n    for pair in occurrences {\n        priorityQueue.enqueue(Element(char: pair.key, occurrence: pair.value))\n    }\n    \n    var max = 0\n    while let element = priorityQueue.dequeue() {\n        if element.occurrence + k < max { continue }\n        var left = s.startIndex\n        var right = s.startIndex\n        var swapsLeft = k\n        //        print(swapsLeft, \"total swaps\")\n        while right < s.endIndex {\n            //            print(\"******start\")\n            if s[right] == element.char {\n            }\n            else if swapsLeft > 0 {\n                swapsLeft -= 1\n            }\n            else {\n                //                print(s[left] != element.char, \"\\(s[left]) != \\(element.char)\")\n                \n                if s[right] != element.char {\n                    swapsLeft -= 1\n                }\n                while swapsLeft < 0 {\n                    if s[left] != element.char {\n                        swapsLeft += 1\n                    }\n                    left = s.index(after: left)\n                }\n            }\n            right = s.index(after: right)\n            let dif = right.encodedOffset - left.encodedOffset\n            //                print(dif, \"dif\")\n            //                print(swapsLeft, \"swaps\")\n            //                print(s[left ..< right])\n            max = dif > max ? dif : max\n        }\n    }\n    return max\n}\n\ncharacterReplacement(\"BRJRRKNRBFOOKDEEGODTGMHNABMTHFNPTFRHRSEKKTFEQIKSIAJJMSDSLNSCNRNJFNFSIQDNMHDRIJIACLCJKATTFHDASGLRQSFN\", 10)\n"
  },
  {
    "path": "Problems/LongestRepeatingCharacterReplacement.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/LongestRepeatingCharacterReplacement.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/LongestRepeatingCharacterReplacement.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/LongestValidParentheses.playground/Contents.swift",
    "content": "import Foundation\n\n/*\n Given a string containing just the characters '(' and ')',\n find the length of the longest valid (well-formed)\n parentheses substring.\n */\n\n\n\n//O(n) - time\n//O(n) - space\nfunc longestValidParentheses(in string: String) -> Int {\n    let array = Array(string)\n    if array.count < 2 { return 0 }\n    \n    var history = Array(repeating: false, count: array.count)\n    var stack: [(char: Character, index: Int)] = []\n    \n    for i in 0 ..< array.count {\n        if array[i] == \"(\" {\n            stack.append((char: array[i], index: i))\n        }\n        else if array[i] == \")\",\n            let last = stack.last,\n            last.char == \"(\" {\n            \n            history[last.index] = true\n            history[i] = true\n            stack.removeLast()\n        }\n    }\n    var max = 0\n    var count = 0\n    \n    history.forEach { valid in\n        count = valid ? count + 1 : 0\n        if count > max { max = count }\n    }\n    return max\n}\n\nvar str = \"()(()\"\nlongestValidParentheses(in: str)\n"
  },
  {
    "path": "Problems/LongestValidParentheses.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/LongestValidParentheses.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/LongestValidParentheses.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/MaxLengthZeroSum.playground/Contents.swift",
    "content": "import Foundation\n\n/*\n Find the length of largest subarray with 0 sum\n Given an array of integers, find length of the largest subarray with sum equals to 0.\n \n Examples :\n \n Input: arr[] = {15, -2, 2, -8, 1, 7, 10, 23};\n Output: 5\n The largest subarray with 0 sum is -2, 2, -8, 1, 7\n \n Input: arr[] = {1, 2, 3}\n Output: 0\n There is no subarray with 0 sum\n \n Input: arr[] = {1, 0, 3}\n Output: 1\n */\n\nfunc find(in array: [Int]) -> Int {\n//    var\n    var max = 0\n    var sum = 0\n    var store = Dictionary<Int, Int>()\n    \n    for i in 0 ..< array.count {\n        sum += array[i]\n        if max == 0, array[i] == 0 {\n            max = 1\n        }\n        if sum == 0 {\n            max = i + 1\n        }\n        if let saved = store[sum] {\n            let new = i - saved\n            if new > max { max = new }\n        }\n        else {\n            store[sum] = i\n        }\n    }\n    return max\n}\n\nfind(in: [15, -2, 2, -8, 1, 7, 10, 23])\n"
  },
  {
    "path": "Problems/MaxLengthZeroSum.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/MaxWeightPyramid.playground/Contents.swift",
    "content": "import UIKit\n\n/*\nThis problem was asked by Google.\n\nYou are given an array of arrays of integers, where each array corresponds to a row in a triangle of numbers. For example, [[1], [2, 3], [1, 5, 1]] represents the triangle:\n\n1\n2 3\n1 5 1\nWe define a path in the triangle to start at the top and go down one row at a time to an adjacent value, eventually ending with an entry on the bottom row. For example, 1 -> 3 -> 5. The weight of the path is the sum of the entries.\n\nWrite a program that returns the weight of the maximum weight path.\n*/\n\nfunc maxWeightPath(row: Int = 0, idx: Int = 0, triangle: [[Int]], cache: inout [[Int]]) -> Int {\n    if row > triangle.count - 1 { return 0 }\n    let value = triangle[row][idx]\n    let result: Int\n    \n    if cache[row][idx] != 0 {\n        result = cache[row][idx]\n    }\n    else {\n        result = value + max(\n            maxWeightPath(row: row + 1, idx: idx, triangle: triangle, cache: &cache),\n            maxWeightPath(row: row + 1, idx: idx + 1, triangle: triangle, cache: &cache)\n        )\n    }\n    cache[row][idx] = result\n    return result\n}\n\nlet triangle =\n    [\n        [1],\n        [2,3],\n        [1,5,1],\n        [2,3,1,9],\n        [3,6,7,-5,4]\n]\nvar cache = triangle.map { (row) in\n    return row.map { _ in\n        return 0\n    }\n}\nmaxWeightPath(triangle: triangle, cache: &cache)\n"
  },
  {
    "path": "Problems/MaxWeightPyramid.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/MedianOf2Arrays.playground/Contents.swift",
    "content": "import Foundation\n/*\n There are two sorted arrays nums1 and nums2 of size m and n respectively.\n \n Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).\n \n You may assume nums1 and nums2 cannot be both empty.\n \n Example 1:\n \n nums1 = [1, 3]\n nums2 = [2]\n \n The median is 2.0\n Example 2:\n \n nums1 = [1, 2]\n nums2 = [3, 4]\n \n The median is (2 + 3)/2 = 2.5\n */\n\nfunc findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double {\n    var i = 0, j = 0\n    var m = nums1.count, n = nums2.count\n    var arr1 = nums1, arr2 = nums2\n    if m > n {\n        swap(&m, &n)\n        swap(&arr1, &arr2)\n    }\n    let half = (m + n) / 2\n    \n    var leftMax = 0, rightMin = 0\n\n    var min = 0, max = m\n    while min <= max {\n        i = (min + max) / 2\n        j = half - i\n        if i > 0 && arr1[i-1] > arr2[j] {\n            max = i - 1\n        } else if i < m && arr2[j-1] > arr1[i] {\n            min = i + 1\n        } else {\n            if i == m {\n                rightMin = arr2[j]\n            } else if j == n {\n                rightMin = arr1[i]\n            } else {\n                rightMin = arr1[i] > arr2[j] ? arr2[j] : arr1[i]\n            }\n            \n            if (m + n) % 2 == 1 {\n                return Double(rightMin)\n            }\n            \n            if i == 0 {\n                leftMax = arr2[j - 1]\n            } else if j == 0 {\n                leftMax = arr1[i - 1]\n            } else {\n                leftMax = arr1[i-1] > arr2[j-1] ? arr1[i-1] : arr2[j-1]\n            }\n            return Double(leftMax + rightMin) / 2.0\n        }\n    }\n    return 0\n}\n"
  },
  {
    "path": "Problems/MedianOf2Arrays.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/Min Common Interval.playground/Contents.swift",
    "content": "import Foundation\n\n/*(\nThis problem was asked by Google.\n\nGiven a set of closed intervals, find the smallest set of numbers that covers all the intervals. If there are multiple smallest sets, return any of them.\n\nFor example, given the intervals [0, 3], [2, 6], [3, 4], [6, 9], one set of numbers that covers all these intervals is {3, 6}.\n*/\n\nfunc interval(intervals: [[Int]]) -> (Int, Int){\n    \n    var min = Int.max\n    var max = Int.min\n    \n    for pair in intervals {\n        if pair[0] > max {\n            max = pair[0]\n        }\n        if pair[1] < min {\n            min = pair[1]\n        }\n    }\n    return (min,max)\n}\n\ninterval(intervals: [[0, 3], [2, 6], [3, 4], [6, 9]])\n"
  },
  {
    "path": "Problems/Min Common Interval.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/Min Common Interval.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/Min Common Interval.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/Min Common Interval.playground/timeline.xctimeline",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Timeline\n   version = \"3.0\">\n   <TimelineItems>\n      <LoggerValueHistoryTimelineItem\n         documentLocation = \"file:///Users/denislitvin/Downloads/MyPlayground.playground#CharacterRangeLen=685&amp;CharacterRangeLoc=0&amp;EndingColumnNumber=0&amp;EndingLineNumber=27&amp;StartingColumnNumber=0&amp;StartingLineNumber=0&amp;Timestamp=559445785.140404\"\n         selectedRepresentationIndex = \"0\"\n         shouldTrackSuperviewWidth = \"NO\">\n      </LoggerValueHistoryTimelineItem>\n   </TimelineItems>\n</Timeline>\n"
  },
  {
    "path": "Problems/MinDistanceBetweenWords.playground/Contents.swift",
    "content": "//: Playground - noun: a place where people can play\n\nimport Foundation\n\n/*\n Find an efficient algorithm to find the smallest distance (measured in number of words) between any two given words in a string.\n \n For example, given words \"hello\", and \"world\" and a text content of \"dog cat hello cat dog dog hello cat world\",\n return 1 because there's only one word \"cat\" in between the two words.\n */\n\nfunc distanceBetweenClosest(pair: (String, String), in string: String) -> Int {\n    let words = string.components(separatedBy: \" \")\n    var bitArray = Array(repeating: UInt8(0), count: words.count)\n    \n    words.enumerated().forEach {\n        if $0.element == pair.0 {\n            bitArray[$0.offset] = 1\n        }\n        else if $0.element == pair.1 {\n            bitArray[$0.offset] = 2\n        }\n    }\n    let index = bitArray.index { $0 == 1 || $0 == 2 }!\n    let type = bitArray[index]\n    return distanceHelper(for: type, startIdx: index + 1, in: bitArray)\n}\n\nfunc distanceHelper(for type: UInt8, startIdx: Int, in array: [UInt8]) -> Int {\n    \n    for i in startIdx ..< array.count {\n        let element = array[i]\n        \n        if element == type {\n            return distanceHelper(for: type, startIdx: i + 1, in: array)\n        }\n        if element == 0 {\n            continue\n        }\n        return min(i - startIdx, distanceHelper(for: element, startIdx: i + 1, in: array))\n    }\n    return Int.max\n}\n\ndistanceBetweenClosest(pair: (\"cat\", \"dog\"), in: \"cat and dadd dog bb j j kj dog 1 cat\")\n"
  },
  {
    "path": "Problems/MinDistanceBetweenWords.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/MinDistanceBetweenWords.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/MinDistanceBetweenWords.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/N Node From End Linked List.playground/Contents.swift",
    "content": "import Foundation\n\nprecedencegroup LongArrowPrecedence {\n    associativity: left\n    higherThan: AssignmentPrecedence\n}\ninfix operator ~>: LongArrowPrecedence\n\nclass Node: CustomStringConvertible{\n    var description: String {\n        if next == nil { return \"\\(value)\" }\n        return \"\\(value) ~> \\(next!.description)\"\n    }\n    \n    var next: Node?\n    var value: Int\n    init(_ value: Int) {\n        self.value = value\n    }\n    static func ~>(lhs: Node, rhs: Node) -> Node {\n        lhs.next = rhs\n        return rhs\n    }\n}\n\n/*\n Asked in: Accolite    Adobe    Amazon    Citicorp    Epic Systems    MAQ Software    Monotype Solutions    Snapdeal\n\nGiven a linked list, the task is to find the n'th node from the end.  It is needed to complete a method that takes two argument, head of linked list and an integer n. There are multiple test cases. For each test case, this method will be called individually.\n\n*/\n\n//fastest approach\n//time O(n)\n//space O(1)\nfunc nNode(in head: Node, n: Int) -> Int {\n    \n    var current = head\n    var count = 0\n    var nNode = head\n    \n    while let next = current.next {\n        count += 1\n        if count >= n {\n            nNode = nNode.next!\n        }\n        current = next\n    }\n    \n    return nNode.value\n}\n\nlet head = Node(1)\nhead ~> Node(2) ~> Node(3) ~> Node(4) ~> Node(5)\n\nnNode(in: head, n: 2)\n"
  },
  {
    "path": "Problems/N Node From End Linked List.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/N Node From End Linked List.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/N Node From End Linked List.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/NearestKPoints.playground/Contents.swift",
    "content": "//: Playground - noun: a place where people can play\n\nimport Foundation\n\n/*\n This problem was asked by LinkedIn.\n \n Given a list of points, a central point, and an integer k, find the nearest k points from the central point.\n \n For example, given the list of points [(0, 0), (5, 4), (3, 1)], the central point (1, 2), and k = 2, return [(0, 0), (3, 1)].\n */\n\ntypealias Point = (x: Int, y: Int)\ntypealias Item = (offset: Int, element: Int)\n\nfunc nearest(in array: [Point], pivot: Point, k: Int) -> [Point] {\n    var left = k\n    var result = [Point]()\n    let pivotSqr = pivot.x * pivot.x + pivot.y * pivot.y\n    let arraySqr = array.map { $0.x * $0.x + $0.y * $0.y }\n    \n    var heap = Heap<(offset: Int, element: Int)> {\n        return abs($0.element - pivotSqr) < abs($1.element - pivotSqr)\n    }\n    arraySqr.enumerated().forEach { heap.insert($0) }\n    \n    while !heap.isEmpty, left > 0 {\n        result.append(array[heap.remove()!.offset])\n        left -= 1\n    }\n    return result\n}\n\nlet points = [\n    (x: 2, y: 10),\n    (x: 7, y: 3),\n    (x: 9, y: 3),\n    (x: 18, y: 4),\n    (x: 5, y: 3)\n]\n\nnearest(in: points, pivot: (x: 11, y: 13), k: 3)\n"
  },
  {
    "path": "Problems/NearestKPoints.playground/Sources/Heap.swift",
    "content": "import Foundation\n\npublic struct Heap<T> {\n    \n    /** The array that stores the heap's nodes. */\n    public var nodes = [T]()\n    \n    /**\n     * Determines how to compare two nodes in the heap.\n     * Use '>' for a max-heap or '<' for a min-heap,\n     * or provide a comparing method if the heap is made\n     * of custom elements, for example tuples.\n     */\n    private var orderCriteria: (T, T) -> Bool\n    \n    /**\n     * Creates an empty heap.\n     * The sort function determines whether this is a min-heap or max-heap.\n     * For comparable data types, > makes a max-heap, < makes a min-heap.\n     */\n    public init(sort: @escaping (T, T) -> Bool) {\n        self.orderCriteria = sort\n    }\n    \n    /**\n     * Creates a heap from an array. The order of the array does not matter;\n     * the elements are inserted into the heap in the order determined by the\n     * sort function. For comparable data types, '>' makes a max-heap,\n     * '<' makes a min-heap.\n     */\n    public init(array: [T], sort: @escaping (T, T) -> Bool) {\n        self.orderCriteria = sort\n        configureHeap(from: array)\n    }\n    \n    /**\n     * Configures the max-heap or min-heap from an array, in a bottom-up manner.\n     * Performance: This runs pretty much in O(n).\n     */\n    private mutating func configureHeap(from array: [T]) {\n        nodes = array\n        for i in stride(from: (nodes.count/2-1), through: 0, by: -1) {\n            shiftDown(i)\n        }\n    }\n    \n    public var isEmpty: Bool {\n        return nodes.isEmpty\n    }\n    \n    public var count: Int {\n        return nodes.count\n    }\n    \n    /**\n     * Returns the index of the parent of the element at index i.\n     * The element at index 0 is the root of the tree and has no parent.\n     */\n    @inline(__always) internal func parentIndex(ofIndex i: Int) -> Int {\n        return (i - 1) / 2\n    }\n    \n    /**\n     * Returns the index of the left child of the element at index i.\n     * Note that this index can be greater than the heap size, in which case\n     * there is no left child.\n     */\n    @inline(__always) internal func leftChildIndex(ofIndex i: Int) -> Int {\n        return 2*i + 1\n    }\n    \n    /**\n     * Returns the index of the right child of the element at index i.\n     * Note that this index can be greater than the heap size, in which case\n     * there is no right child.\n     */\n    @inline(__always) internal func rightChildIndex(ofIndex i: Int) -> Int {\n        return 2*i + 2\n    }\n    \n    /**\n     * Returns the maximum value in the heap (for a max-heap) or the minimum\n     * value (for a min-heap).\n     */\n    public func peek() -> T? {\n        return nodes.first\n    }\n    \n    /**\n     * Adds a new value to the heap. This reorders the heap so that the max-heap\n     * or min-heap property still holds. Performance: O(log n).\n     */\n    public mutating func insert(_ value: T) {\n        nodes.append(value)\n        shiftUp(nodes.count - 1)\n    }\n    \n    /**\n     * Adds a sequence of values to the heap. This reorders the heap so that\n     * the max-heap or min-heap property still holds. Performance: O(log n).\n     */\n    public mutating func insert<S: Sequence>(_ sequence: S) where S.Iterator.Element == T {\n        for value in sequence {\n            insert(value)\n        }\n    }\n    \n    /**\n     * Allows you to change an element. This reorders the heap so that\n     * the max-heap or min-heap property still holds.\n     */\n    public mutating func replace(index i: Int, value: T) {\n        guard i < nodes.count else { return }\n        \n        remove(at: i)\n        insert(value)\n    }\n    \n    /**\n     * Removes the root node from the heap. For a max-heap, this is the maximum\n     * value; for a min-heap it is the minimum value. Performance: O(log n).\n     */\n    @discardableResult public mutating func remove() -> T? {\n        guard !nodes.isEmpty else { return nil }\n        \n        if nodes.count == 1 {\n            return nodes.removeLast()\n        } else {\n            // Use the last node to replace the first one, then fix the heap by\n            // shifting this new first node into its proper position.\n            let value = nodes[0]\n            nodes[0] = nodes.removeLast()\n            shiftDown(0)\n            return value\n        }\n    }\n    \n    /**\n     * Removes an arbitrary node from the heap. Performance: O(log n).\n     * Note that you need to know the node's index.\n     */\n    @discardableResult public mutating func remove(at index: Int) -> T? {\n        guard index < nodes.count else { return nil }\n        \n        let size = nodes.count - 1\n        if index != size {\n            nodes.swapAt(index, size)\n            shiftDown(from: index, until: size)\n            shiftUp(index)\n        }\n        return nodes.removeLast()\n    }\n    \n    /**\n     * Takes a child node and looks at its parents; if a parent is not larger\n     * (max-heap) or not smaller (min-heap) than the child, we exchange them.\n     */\n    internal mutating func shiftUp(_ index: Int) {\n        var childIndex = index\n        let child = nodes[childIndex]\n        var parentIndex = self.parentIndex(ofIndex: childIndex)\n        \n        while childIndex > 0 && orderCriteria(child, nodes[parentIndex]) {\n            nodes[childIndex] = nodes[parentIndex]\n            childIndex = parentIndex\n            parentIndex = self.parentIndex(ofIndex: childIndex)\n        }\n        \n        nodes[childIndex] = child\n    }\n    \n    /**\n     * Looks at a parent node and makes sure it is still larger (max-heap) or\n     * smaller (min-heap) than its childeren.\n     */\n    internal mutating func shiftDown(from index: Int, until endIndex: Int) {\n        let leftChildIndex = self.leftChildIndex(ofIndex: index)\n        let rightChildIndex = leftChildIndex + 1\n        \n        // Figure out which comes first if we order them by the sort function:\n        // the parent, the left child, or the right child. If the parent comes\n        // first, we're done. If not, that element is out-of-place and we make\n        // it \"float down\" the tree until the heap property is restored.\n        var first = index\n        if leftChildIndex < endIndex && orderCriteria(nodes[leftChildIndex], nodes[first]) {\n            first = leftChildIndex\n        }\n        if rightChildIndex < endIndex && orderCriteria(nodes[rightChildIndex], nodes[first]) {\n            first = rightChildIndex\n        }\n        if first == index { return }\n        \n        nodes.swapAt(index, first)\n        shiftDown(from: first, until: endIndex)\n    }\n    \n    internal mutating func shiftDown(_ index: Int) {\n        shiftDown(from: index, until: nodes.count)\n    }\n    \n}\n\n// MARK: - Searching\nextension Heap where T: Equatable {\n    \n    /** Get the index of a node in the heap. Performance: O(n). */\n    public func index(of node: T) -> Int? {\n        return nodes.index(where: { $0 == node })\n    }\n    \n    /** Removes the first occurrence of a node from the heap. Performance: O(n log n). */\n    @discardableResult public mutating func remove(node: T) -> T? {\n        if let index = index(of: node) {\n            return remove(at: index)\n        }\n        return nil\n    }\n    \n}\n"
  },
  {
    "path": "Problems/NearestKPoints.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/NearestKPoints.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/NumberOfSquares.playground/Contents.swift",
    "content": "//: Playground - noun: a place where people can play\n\nimport Foundation\n\n/*\nThis problem was asked by Facebook.\n\nGiven a positive integer n, find the smallest number of squared integers which sum to n.\n\nFor example, given n = 13, return 2 since 13 = 32 + 22 = 9 + 4.\n\nGiven n = 27, return 3 since 27 = 32 + 32 + 32 = 9 + 9 + 9.\n*/\n\n//time complexity - O(n^n)\nfunc numOfSquares(in int: Int) -> Int {\n    if isSquared(int) { return 1 }\n    var min = Int.max\n    \n    for i in 1 ..< int {\n        let potential = int - i\n        if isSquared(potential) {\n            let num = 1 + numOfSquares(in: i)\n            if num == 2 { return num }\n            if num < min { min = num }\n        }\n    }\n    return min\n}\n\n//func numOfSquaresHelper(in int: Int, current: Int) -> Int {\n//    return 0\n//}\n\nfunc isSquared(_ int: Int) -> Bool {\n    return Int(exactly: sqrt(Double(int))) != nil\n}\n\nnumOfSquares(in: 3899)\n"
  },
  {
    "path": "Problems/NumberOfSquares.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/NumberOfSquares.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/NumberOfSquares.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/Reverse Linked List for Groups.playground/Contents.swift",
    "content": "//: Playground - noun: a place where people can play\n\nimport UIKit\n\nprecedencegroup LongArrowPrecedence {\n    associativity: left\n    higherThan: AssignmentPrecedence\n}\ninfix operator ~>: LongArrowPrecedence\n\nclass Node: CustomStringConvertible{\n    var description: String {\n        if next == nil { return \"\\(value)\" }\n        return \"\\(value) ~> \\(next!.description)\"\n    }\n    \n    var next: Node?\n    var value: Int\n    init(_ value: Int) {\n        self.value = value\n    }\n    static func ~>(lhs: Node, rhs: Node) -> Node {\n        lhs.next = rhs\n        return rhs\n    }\n}\n\n\n//Reverse a Linked List in groups of given size | Set 1\n//Given a linked list, write a function to reverse every k nodes (where k is an input to the function).\n//\n//Example:\n//Inputs:  1->2->3->4->5->6->7->8->NULL and k = 3\n//Output:  3->2->1->6->5->4->8->7->NULL.\n//\n//Inputs:   1->2->3->4->5->6->7->8->NULL and k = 5\n//Output:  5->4->3->2->1->8->7->6->NULL.\n\nfunc reverse(node: Node?, k: Int) -> Node? {\n    guard let node = node else { return nil }\n    var boundK = 1\n    var next = node.next\n    var previous = node\n    node.next = nil\n\n    for _ in 1 ..< k {\n        if let nextUnwraped = next {\n            boundK += 1\n            next = nextUnwraped.next\n            nextUnwraped.next = previous\n            previous = nextUnwraped\n        }\n        else {\n            return reverse(node: current, k: boundK)\n        }\n    }\n    node.next = reverse(node: next, k: k)\n    return previous\n}\n\nlet start = Node(0)\nstart ~> Node(1) ~> Node(2) ~> Node(3) ~> Node(4) ~> Node(5)\n\nreverse(node: start, k: 5)\n\n\n\n"
  },
  {
    "path": "Problems/Reverse Linked List for Groups.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/Reverse Linked List for Groups.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/Reverse Linked List for Groups.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/Sort Linked Matrix.playground/Contents.swift",
    "content": "import Foundation\n\n\n\nprecedencegroup LongArrowPrecedence {\n    associativity: left\n    higherThan: AssignmentPrecedence\n}\ninfix operator ~>: LongArrowPrecedence\ninfix operator ~~>: LongArrowPrecedence\n\nclass Node: CustomStringConvertible{\n    var description: String {\n        if next == nil { return \"\\(value)\" }\n        return \"\\(value) ~> \\(next!.description)\"\n    }\n    \n    var next: Node?\n    var value: Int\n    var right: Node?\n    \n    init(_ value: Int) {\n        self.value = value\n    }\n    static func ~>(lhs: Node, rhs: Node) -> Node {\n        lhs.next = rhs\n        return rhs\n    }\n    static func ~~>(lhs: Node, rhs: Node) -> Node {\n        lhs.right = rhs\n        return rhs\n    }\n}\n\n/*\n \n Given a linked list where every node represents a linked list and contains two pointers of its type:\n (i) Pointer to next node in the main list (we call it ‘right’ pointer in below code)\n (ii) Pointer to a linked list where this node is head (we call it ‘down’ pointer in below code).\n All linked lists are sorted. See the following example\n \n5 -> 10 -> 19 -> 28\n|    |     |     |\nV    V     V     V\n7    20    22    35\n|          |     |\nV          V     V\n8          50    40\n*/\n\n//time O(nlogn)\n//space O(n)\nfunc sorted(in head: Node) -> Node {\n    return merge(head, head.right)\n}\n\nfunc merge(_ left: Node, _ right: Node?) -> Node {\n    guard let right = right else { return left }\n    \n    var lCurrent: Node? = left\n    var rCurrent: Node? = right\n    var head: Node?\n    var last: Node?\n    \n    rCurrent = merge(right, right.right)\n    \n    while let left = lCurrent, let right = rCurrent {\n        let next: Node\n        if left.value < right.value {\n            next = left\n            lCurrent = left.next\n        }\n        else {\n            next = right\n            rCurrent = right.next\n        }\n        if last != nil {\n            last!.next = next\n        }\n        last = next\n        \n        if head == nil {\n            head = next\n        }\n\n    }\n    last?.next = lCurrent ?? rCurrent\n    return head!\n}\n\nlet head = Node(0)\nlet secondHead = Node(2)\nhead ~> Node(1) ~> Node(3) ~> Node(5) ~> Node(7) ~> Node(11)\nhead ~~> secondHead\nsecondHead ~> Node(4) ~> Node(6) ~> Node(8) ~> Node(10)\n\nsorted(in: head)\n"
  },
  {
    "path": "Problems/Sort Linked Matrix.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/Splitwize.playground/Contents.swift",
    "content": "import Foundation\n\nclass Person {\n    typealias ID = Int\n    \n    let id: ID\n    var credit: [ID: Int] = [:]\n    \n    init(_ id: ID) {\n        self.id = id\n    }\n    \n    func give(to person: Person, amount: Int) {\n        if amount == 0 { return }\n        \n        credit[person.id] = (credit[person.id] ?? 0) - amount\n        person.credit[id] = (person.credit[id] ?? 0) + amount\n        \n        //clean up if settled\n        if credit[person.id] == 0 {\n            credit[person.id] = nil\n        }\n        if person.credit[id] == 0 {\n            person.credit[id] = nil\n        }\n    }\n}\n\nextension Person: CustomStringConvertible {\n    var description: String {\n        let negative = credit.filter { $0.value < 0 }\n        let positive = credit.filter { $0.value >= 0 }\n        return \"Person \\(id)\\n-debit: \\(negative)\\n-credit: \\(positive)\\n\"\n    }\n}\n\nlet p1 = Person(1)\nlet p2 = Person(2)\nlet p3 = Person(3)\nlet p4 = Person(4)\nlet p5 = Person(5)\nlet people = [p1,p2,p3,p4,p5]\n\np1.give(to: p4, amount: 4)\np1.give(to: p5, amount: 1)\np2.give(to: p4, amount: 5)\np2.give(to: p5, amount: 2)\np3.give(to: p4, amount: 3)\np3.give(to: p5, amount: 8)\n\nprint(\"Before\")\nprint(p1)\nprint(p2)\nprint(p3)\nprint(p4)\nprint(p5)\n\nfunc splitwizeSimple(between people: [Person]) {\n    \n    var lookUpTable = [Person.ID: Person]()\n    for person in people {\n        lookUpTable[person.id] = person\n    }\n    \n    for person in people {\n        for connection in person.credit {\n            print(\"Person \\(person.credit[connection.key] ?? 0 > 0 ? connection.key : person.id) pays \\(connection.value) to Person \\(person.credit[connection.key] ?? 0 > 0 ? person.id : connection.key)\")\n            person.credit[connection.key] = nil\n            lookUpTable[connection.key] = nil\n        }\n    }\n}\n\n//print(\"Splitwize Simple\")\n//splitwizeSimple(between: people)\n//print()\n\nfunc splitwizeMinimumCashflow(between people: [Person]) {\n    var balance = [Person.ID: Int]()\n    \n    for person in people {\n        //sum all credit\n        balance[person.id] = person.credit.reduce(0) { return $0 + $1.value }\n    }\n    print(balance)\n    splitwizeMinimumCashflowHelper(balance: &balance)\n}\n\nfunc splitwizeMinimumCashflowHelper(balance: inout [Person.ID: Int]) {\n    \n    let maxDebetor = balance.min { $0.value < $1.value }!\n    let maxCredetor = balance.max { $0.value < $1.value }!\n    \n    if maxDebetor.value == 0 && maxCredetor.value == 0 {\n        return\n    }\n    \n    //non negative\n    let minAmount = min(-maxDebetor.value, maxCredetor.value)\n    balance[maxCredetor.key] = (balance[maxCredetor.key] ?? 0) - minAmount\n    balance[maxDebetor.key] = (balance[maxDebetor.key] ?? 0) + minAmount\n\n    print(\"Person \\(maxCredetor.key) pays \\(minAmount) to Person \\(maxDebetor.key)\")\n    \n    splitwizeMinimumCashflowHelper(balance: &balance)\n}\n\nprint(\"splitwize minimum cashflow\")\nsplitwizeMinimumCashflow(between: people)\nprint()\n\nprint(\"After\")\nprint(p1)\nprint(p2)\nprint(p3)\nprint(p4)\nprint(p5)\n\n/*\n Person 4 pays 5 to Person 1\n Person 4 pays 7 to Person 2\n Person 5 pays 11 to Person 3\n**/\n"
  },
  {
    "path": "Problems/Splitwize.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/Splitwize.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/Splitwize.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/Squared Int Sorted.playground/Contents.swift",
    "content": "import UIKit\n\n/*\nThis problem was asked by Google.\n\nGiven a sorted list of integers, square the elements and give the output in sorted order.\n\nFor example, given [-9, -2, 0, 2, 3], return [0, 4, 4, 9, 81].\n\n*/\n\n//O(n) - time complexity\n//O(n) - space complexity\nfunc squaredSort(elements: [Int]) -> [Int] {\n    \n    var negative = [Int]()\n    var positive = [Int]()\n    var result = [Int]()\n    \n    for i in elements {\n        if i < 0 {\n            negative.append(i * i)\n        }\n        else if i > 0 {\n            positive.append(i * i)\n        }\n        else {\n            result.append(i)\n        }\n    }\n    negative.reverse()\n    \n    while !negative.isEmpty && !positive.isEmpty {\n        if negative[0] < positive[0] {\n            result.append(negative.removeFirst())\n        }\n        else {\n            result.append(positive.removeFirst())\n        }\n    }\n    \n    return result + positive + negative\n}\n\nsquaredSort(elements: [-10,-2,-2,0,1,5,100])\n"
  },
  {
    "path": "Problems/Squared Int Sorted.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/SurroundedRegions.playground/Contents.swift",
    "content": "import Foundation\n\n/*\n Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.\n \n A region is captured by flipping all 'O's into 'X's in that surrounded region.\n \n Example:\n \n X X X X\n X O O X\n X X O X\n X O X X\n After running your function, the board should be:\n \n X X X X\n X X X X\n X X X X\n X O X X\n Explanation:\n \n Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.\n */\n\nfunc solve(_ board: inout [[Character]]) {\n    if board.count == 0 { return }\n    var visited = Array(repeating: Array(repeating: 0, count: board[0].count), count: board.count)\n    solveHelper(&board, visited: &visited)\n}\n\nfunc solveHelper(_ board: inout [[Character]], visited: inout [[Int]]) {\n    for row in 0 ..< board.count {\n        for column in 0 ..< board[row].count {\n            if  row > 0,\n                row < board.count - 1,\n                column > 0,\n                column < board[row].count - 1\n            {\n                continue\n            }\n            findAdjacent(row: row, column: column, board: &board, visited: &visited)\n        }\n    }\n    for row in 0 ..< board.count {\n        for column in 0 ..< board[row].count {\n            if visited[row][column] == 0 {\n                board[row][column] = \"X\"\n            }\n        }\n    }\n}\nfunc findAdjacent(row: Int, column: Int, board: inout [[Character]], visited: inout [[Int]]) {\n    guard row >= 0, row < board.count else { return }\n    guard column >= 0, column < board[row].count else { return }\n    \n    if  board[row][column] == \"O\",\n        visited[row][column] == 0\n    {\n        visited[row][column] = 1\n        //up\n        findAdjacent(row: row - 1, column: column, board: &board, visited: &visited)\n        //left\n        findAdjacent(row: row, column: column - 1, board: &board, visited: &visited)\n        //right\n        findAdjacent(row: row, column: column + 1, board: &board, visited: &visited)\n        //down\n        findAdjacent(row: row + 1, column: column, board: &board, visited: &visited)\n    }\n}\nvar board: [[Character]] = [[\"X\",\"O\",\"X\",\"O\",\"X\",\"O\"],[\"O\",\"X\",\"O\",\"X\",\"O\",\"X\"],[\"X\",\"O\",\"X\",\"O\",\"X\",\"O\"],[\"O\",\"X\",\"O\",\"X\",\"O\",\"X\"]]\n\nsolve(&board)\n"
  },
  {
    "path": "Problems/SurroundedRegions.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/SwapWordsInSentence.playground/Contents.swift",
    "content": "import UIKit\n\n/*\n Given an input string, reverse the string word by word.\n \n Example:\n \n Input: \"the sky is blue\",\n Output: \"blue is sky the\".\n Note:\n \n A word is defined as a sequence of non-space characters.\n Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.\n You need to reduce multiple spaces between two words to a single space in the reversed string.\n Follow up: For C programmers, try to solve it in-place in O(1) space.\n */\n\n// O(n + m) - time complexity\n// O(1) - space complexity\nfunc swapWords(str: inout [Character]) {\n    var left = 0\n    var right = str.count - 1\n    \n    swapInside(str: &str, left: left, right: right)\n    \n    for i in 0 ..< str.count {\n        if str[i] == \" \" {\n            right = i - 1\n            swapInside(str: &str, left: left, right: right)\n            left = i + 1\n        }\n    }\n    swapInside(str: &str, left: left, right: str.count - 1)\n}\n\nfunc swapInside(str: inout [Character], left: Int, right: Int) {\n    var left = left\n    var right = right\n    \n    while left <= right {\n        str.swapAt(left, right)\n        left += 1\n        right -= 1\n    }\n}\n\nvar arr = Array(\"error or\")\nswapWords(str: &arr)\narr\n"
  },
  {
    "path": "Problems/SwapWordsInSentence.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/ThreeSum.playground/Contents.swift",
    "content": "import Foundation\n\n/*\n Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.\n \n Note:\n \n The solution set must not contain duplicate triplets.\n \n Example:\n \n Given array nums = [-1, 0, 1, 2, -1, -4],\n \n A solution set is:\n [\n [-1, 0, 1],\n [-1, -1, 2]\n ]\n */\n\n//O(n^2) - time\n//O(n) - space\nfunc threeSum(_ nums: [Int]) -> [[Int]] {\n    var nums = nums.sorted { (a, b) -> Bool in\n        return a < b\n    }\n    guard nums.count > 2 else{\n        return []\n    }\n    \n    var solutions = [[Int]]()\n    for i in 0..<nums.count - 2{\n        let f1 = nums[i]\n        if i > 0 && f1 == nums[i-1]{\n            continue\n        }\n        if f1 > 0 {\n            break\n        }\n        var leftPtr = i + 1,rightPtr = nums.count - 1,sum = 0 - f1\n        while leftPtr < rightPtr{\n            let s = nums[leftPtr] + nums[rightPtr]\n            if  s == sum{\n                solutions.append([f1,nums[leftPtr],nums[rightPtr]])\n                while leftPtr < rightPtr && nums[leftPtr] == nums[leftPtr + 1]{\n                    leftPtr += 1\n                }\n                while leftPtr < rightPtr && nums[rightPtr] == nums[rightPtr - 1]{\n                    rightPtr -= 1\n                }\n                leftPtr += 1\n                rightPtr -= 1\n            }else{\n                if s < sum{\n                    leftPtr += 1\n                }else{\n                    rightPtr -= 1\n                }\n            }\n        }\n    }\n    return solutions\n}\n\nthreeSum([-13,5,13,12,-2,-11,-1,12,-3,0,-3,-7])\n"
  },
  {
    "path": "Problems/ThreeSum.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/ThreeSum.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/ThreeSum.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/ThreeSum.playground/timeline.xctimeline",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Timeline\n   version = \"3.0\">\n   <TimelineItems>\n      <LoggerValueHistoryTimelineItem\n         documentLocation = \"file:///Users/dl13653/Downloads/MyPlayground.playground#CharacterRangeLen=1239&amp;CharacterRangeLoc=366&amp;EndingColumnNumber=0&amp;EndingLineNumber=65&amp;StartingColumnNumber=0&amp;StartingLineNumber=19&amp;Timestamp=566073017.814894\"\n         selectedRepresentationIndex = \"0\"\n         shouldTrackSuperviewWidth = \"NO\">\n      </LoggerValueHistoryTimelineItem>\n   </TimelineItems>\n</Timeline>\n"
  },
  {
    "path": "Problems/TowerOfHanoi.playground/Contents.swift",
    "content": "import UIKit\n\n/*\nTower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:\n1) Only one disk can be moved at a time.\n2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.\n3) No disk may be placed on top of a smaller disk.\n\n\n\nApproach :\n\nTake an example for 2 disks :\nLet rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'.\n\nStep 1 : Shift first disk from 'A' to 'B'.\nStep 2 : Shift second disk from 'A' to 'C'.\nStep 3 : Shift first disk from 'B' to 'C'.\n\nThe pattern here is :\nShift 'n-1' disks from 'A' to 'B'.\nShift last disk from 'A' to 'C'.\nShift 'n-1' disks from 'B' to 'C'.\n\n*/\n\nfunc tower(n: Int, fromRod: String, toRod: String, auxRod: String) {\n    if n == 1 {\n     print(\"Move disk 1 from rod \" + fromRod + \" to rod \" + toRod)\n    }\n    else {\n        tower(n: n-1, fromRod: fromRod, toRod: auxRod, auxRod: toRod)\n        print(\"Move disk \\(n) fromRod \" + fromRod + \" to rod \" + toRod)\n        tower(n: n-1, fromRod: auxRod, toRod: toRod, auxRod: fromRod)\n    }\n}\n\ntower(n: 4, fromRod: \"A\", toRod: \"C\", auxRod: \"B\")\n"
  },
  {
    "path": "Problems/TowerOfHanoi.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/TowerOfHanoi.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/TowerOfHanoi.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/TradeStockPrice.playground/Contents.swift",
    "content": "import Foundation\n\n/*\nThis problem was asked by Facebook.\n\nGiven an array of numbers representing the stock prices of a company in chronological order and an integer k, return the maximum profit you can make from k buys and sells. You must buy the stock before you can sell it, and you must sell the stock before you can buy it again.\n\nFor example, given k = 2 and the array [5, 2, 4, 0, 1], you should return 3.\n*/\n\nfunc trade(_ array: [Int]) -> Int {\n    var count = 0\n    var canSell = false\n    var boughtFor = 0\n    for index in 0 ..< array.count {\n        if isPeak(index: index, in: array), canSell {\n            canSell.toggle()\n            count += array[index] - boughtFor\n        }\n        else if isLow(index: index, in: array), !canSell {\n            canSell.toggle()\n            boughtFor = array[index]\n        }\n    }\n    return count\n}\n\nfunc isPeak(index: Int, in array: [Int]) -> Bool{\n    if index + 1 < array.count {\n        return array[index + 1] < array[index]\n    }\n    return true\n}\n\nfunc isLow(index: Int, in array: [Int]) -> Bool {\n    if index + 1 < array.count {\n        return array[index + 1] > array[index]\n    }\n    return false\n}\n\ntrade([0,4,1,3,4,4,2,3])\n"
  },
  {
    "path": "Problems/TradeStockPrice.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/TreeBundaryTraversal.playground/Contents.swift",
    "content": "import UIKit\n\n/*\n Given a binary tree, print boundary nodes of the binary tree Anti-Clockwise starting from the root. For example, boundary traversal of the following tree is “20 8 4 10 14 25 22”\n \n We break the problem in 3 parts:\n 1. Print the left boundary in top-down manner.\n 2. Print all leaf nodes from left to right, which can again be sub-divided into two sub-parts:\n …..2.1 Print all leaf nodes of left sub-tree from left to right.\n …..2.2 Print all leaf nodes of right subtree from left to right.\n 3. Print the right boundary in bottom-up manner.\n\n We need to take care of one thing that nodes are not printed again. e.g. The left most node is also the leaf node of the tree.\n\n */\nclass Node: CustomStringConvertible {\n    var description: String {\n        return String(value)\n    }\n    \n    let value: Int\n    var left: Node?\n    var right: Node?\n    init(_ value: Int) { self.value = value }\n}\n\nlet n20 = Node(20)\nlet n8 = Node(8)\nlet n4 = Node(4)\nlet n22 = Node(22)\nlet n12 = Node(12)\nlet n10 = Node(10)\nlet n25 = Node(25)\nlet n14 = Node(14)\n\nn20.left = n8\nn20.right = n22\nn8.left = n4\nn8.right = n12\nn12.left = n10\nn12.right = n14\nn22.right = n25\n\nfunc printLeafs(of node: Node?) {\n    guard let node = node else { return }\n    if node.left == nil && node.right == nil {\n        print(node)\n    }\n    printLeafs(of: node.left)\n    printLeafs(of: node.right)\n}\n\nfunc printLeftNodes(of node: Node?) {\n    guard let node = node else { return }\n    if node.left == nil && node.right == nil {\n        return\n    }\n    print(node)\n    printLeftNodes(of: node.left)\n}\n\nfunc printRightNodes(of node: Node?) {\n    guard let node = node else { return }\n    if node.left == nil && node.right == nil {\n        return\n    }\n    printLeftNodes(of: node.right)\n    print(node)\n}\n\nprintLeftNodes(of: n20)\nprintLeafs(of: n20)\nprintRightNodes(of: n20)\n"
  },
  {
    "path": "Problems/TreeBundaryTraversal.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/ValidateParentheses.playground/Contents.swift",
    "content": "import UIKit\n\n/*\nGiven a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:\n\nAny left parenthesis '(' must have a corresponding right parenthesis ')'.\nAny right parenthesis ')' must have a corresponding left parenthesis '('.\nLeft parenthesis '(' must go before the corresponding right parenthesis ')'.\n'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.\nAn empty string is also valid.\nExample 1:\n\nInput: \"()\"\nOutput: True\nExample 2:\n\nInput: \"(*)\"\nOutput: True\nExample 3:\n\nInput: \"(*))\"\nOutput: True\nNote:\n\nThe string size will be in the range [1, 100].\n*/\n\nfunc checkValidString(_ s: String) -> Bool {\n    guard s.count > 0 else {return true}\n    var lower = 0\n    var upper = 0\n    for c in s {\n        switch c {\n        case \"(\":\n            lower += 1\n            upper += 1\n        case \"*\":\n            lower -= 1\n            upper += 1\n        case \")\":\n            upper -= 1\n            lower -= 1\n\n        default:\n            fatalError()\n        }\n        lower = max(0,lower)\n        guard upper >= 0 else {return false}\n    }\n    return lower == 0 && upper >= 0\n}\ncheckValidString(\"(*)(*)\")\n\n"
  },
  {
    "path": "Problems/ValidateParentheses.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/ValidateParentheses.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/ValidateParentheses.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/Water Trap.playground/Contents.swift",
    "content": "//: Playground - noun: a place where people can play\n\nimport UIKit\n\n/*\n 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.\n */\n\n//O(n*m) m - height\n    func rainDrops(in array: [Int]) -> Int {\n    var l = true\n    var r = true\n    var dropsCountTotal = 0\n    var layer = 1\n    \n    let max = array.max() ?? 0\n    while layer <= max {\n        r = false\n        l = false\n        var dropsCount = 0\n        \n        for i in array {\n            if i >= layer {\n                if !l { l = true }\n                else if !r { r = dropsCount == 0 ? false : true }\n            }\n            \n            if l, r, dropsCount > 0 {\n//                print(l, r, dropsCount, \"in layer -\", layer, \"position -\", i)\n                dropsCountTotal += dropsCount\n                dropsCount = 0\n                r = false\n            }\n            else if i < layer, l || r {\n                dropsCount += 1\n            }\n        }\n        layer += 1\n    }\n    return dropsCountTotal\n}\n\n//O(n)\nfunc rainDrops2(in array: [Int]) -> Int {\n    guard array.count > 0 else { return 0 }\n    \n    var left = 0\n    var right = array.count - 1\n    var moveLeft = true\n    var level: (Int, Int) = (0, 0)\n    var count = 0\n    \n    while left != right {\n        let value = moveLeft ? array[left] : array [right]\n        let oppositeLevel = moveLeft ? level.1 : level.0\n        let selfLevel = moveLeft ? level.0 : level.1\n        \n        if value > oppositeLevel {\n            if moveLeft { level.0 = value } else { level.1 = value } //increment\n            moveLeft = !moveLeft //switch side\n//            print(value, \"move left - \", !moveLeft)\n            continue\n        }\n        if value > selfLevel {\n            if moveLeft { level.0 = value } else { level.1 = value } //increment\n        }\n        else if value < min(level.0, level.1) {\n            count += min(level.0, level.1) - value\n        }\n        if moveLeft {\n            left += 1\n        }\n        else {\n            right -= 1\n        }\n    }\n    return count\n}\nrainDrops2(in: [0,1,0,2,1,0,1,3,2,1,2,1])\n"
  },
  {
    "path": "Problems/Water Trap.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/Water Trap.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/Water Trap.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/atoi.playground/Contents.swift",
    "content": "//: Playground - noun: a place where people can play\n\nimport UIKit\n//Implement atoi which converts a string to an integer.\n//\n//The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.\n//\n//The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.\n//\n//If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.\n//\n//If no valid conversion could be performed, a zero value is returned.\n//\n//Note:\n//\n//Only the space character ' ' is considered as whitespace character.\n//Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.\n//Example 1:\n//\n//Input: \"42\"\n//Output: 42\n//Example 2:\n//\n//Input: \"   -42\"\n//Output: -42\n//Explanation: The first non-whitespace character is '-', which is the minus sign.\n//Then take as many numerical digits as possible, which gets 42.\n\nclass Solution {\n    func myAtoi(_ str: String) -> Int {\n        var isNegative = false\n        var isStarted = false\n        var currentNumber = 0;\n        for char in str {\n            switch (char) {\n            case \"+\":\n                if (!isStarted) {\n                    isNegative = false\n                    isStarted = true\n                }\n                else {\n                    return 0\n                }\n            case \"-\":\n                if (!isStarted) {\n                    isNegative = true\n                    isStarted = true\n                }\n                else {\n                    return 0\n                }\n                \n            case \"0\":\n                isStarted = true\n                currentNumber = multiplyValue(value: currentNumber, add: 0, isNegative: isNegative)\n            case \"1\":\n                isStarted = true\n                currentNumber = multiplyValue(value: currentNumber, add: 1, isNegative: isNegative)\n            case \"2\":\n                isStarted = true\n                currentNumber = multiplyValue(value: currentNumber, add: 2, isNegative: isNegative)\n            case \"3\":\n                isStarted = true\n                currentNumber = multiplyValue(value: currentNumber, add: 3, isNegative: isNegative)\n            case \"4\":\n                isStarted = true\n                currentNumber = multiplyValue(value: currentNumber, add: 4, isNegative: isNegative)\n            case \"5\":\n                isStarted = true\n                currentNumber = multiplyValue(value: currentNumber, add: 5, isNegative: isNegative)\n            case \"6\":\n                isStarted = true\n                currentNumber = multiplyValue(value: currentNumber, add: 6, isNegative: isNegative)\n            case \"7\":\n                isStarted = true\n                currentNumber = multiplyValue(value: currentNumber, add: 7, isNegative: isNegative)\n            case \"8\":\n                isStarted = true\n                currentNumber = multiplyValue(value: currentNumber, add: 8, isNegative: isNegative)\n            case \"9\":\n                isStarted = true\n                currentNumber = multiplyValue(value: currentNumber, add: 9, isNegative: isNegative)\n            default:\n                if (isStarted) {\n                    if (isNegative) {\n                        return currentNumber * -1;\n                    }\n                    else {\n                        return currentNumber\n                    }\n                }\n                else if (char != \" \") {\n                    return 0\n                }\n            }\n        }\n        \n        if (isNegative) {\n            return currentNumber * -1;\n        }\n        else {\n            return currentNumber\n        }\n    }\n    \n    func multiplyValue(value: Int, add: Int, isNegative: Bool) -> Int {\n        var checkValue: Int\n        if isNegative {\n            checkValue = 2147483648\n        }\n        else {\n            checkValue = 2147483647\n        }\n        \n        \n        if (((checkValue - add) / 10) >= value)\n        {\n            return (value * 10) + add\n        }\n        else {\n            \n            return checkValue\n        }\n    }\n}\n"
  },
  {
    "path": "Problems/atoi.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/atoi.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/atoi.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "Problems/swapBits.playground/Contents.swift",
    "content": "import Foundation\n\n/*\n This problem was asked by Facebook.\n \n Given a 32-bit integer, return the number with its bits reversed.\n \n For example, given the binary number 1111 0000 1111 0000 1111 0000 1111 0000, return 0000 1111 0000 1111 0000 1111 0000 1111.\n */\n\nfunc reverse(_ int: Int32) -> Int32 {\n    var newInt: Int32 = 0\n    var offset = 0\n    while offset <= 24 {\n        for i in 0 ..< 4 {\n            reverseHelper(shift: offset + i + 4, offset: offset + i, newInt: &newInt, oldInt: int)\n        }\n        for i in 4 ..< 8 {\n            reverseHelper(shift: offset + i - 4, offset: offset + i, newInt: &newInt, oldInt: int)\n        }\n        offset += 8\n    }\n   \n    return newInt\n}\n\nfunc reverseHelper(shift: Int, offset: Int, newInt: inout Int32, oldInt: Int32) {\n    if 1 << (offset) & oldInt > 0 {\n        newInt |= 1 << shift\n    }\n}\n\n\n\nreverse(1 << 4) == 1\n\nreverse(1) == 1 << 4\n\nreverse(1 << 27) == 1 << 31\n"
  },
  {
    "path": "Problems/swapBits.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>\n    <timeline fileName='timeline.xctimeline'/>\n</playground>"
  },
  {
    "path": "Problems/swapBits.playground/playground.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Problems/swapBits.playground/playground.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "README.md",
    "content": "\n* [Problems](#problems)\n  * [Form a Palindrome](Problems/Form%20a%20Palindrome.playground/Contents.swift)\n  * [Longest Palindromic Substring](Problems/Longest%20Palindromic%20Substring.playground/Contents.swift)\n  * [Reverse Linked List for Groups](Problems/Reverse%20Linked%20List%20for%20Groups.playground/Contents.swift)\n  * [Atoi](Problems/atoi.playground/Contents.swift)\n  * [Water Trap](Problems/Water%20Trap.playground/Contents.swift)\n  * [Find Shortest path in 2d matrix](Problems/2d%20inf%20grid%20shortest%20path.playground/Contents.swift)\n  * [Min Common Interval](Problems/Min%20Common%20Interval.playground/Contents.swift)\n  * [Squared Int Sorted](Problems/Squared%20Int%20Sorted.playground/Contents.swift)\n  * [N Node From End Linked List](Problems/N%20Node%20From%20End%20Linked%20List.playground/Contents.swift)\n  * [Sort Linked Matrix](Problems/Sort%20Linked%20Matrix.playground/Contents.swift)\n  * [Max Length Zero Sum](Problems/MaxLengthZeroSum.playground/Contents.swift)\n  * [Linked List Numbers Sum](Problems/LinkedListNumbersSum.playground/Contents.swift)\n  * [Deep Copy Linked List](Problems/DeepCopyLinkedList.playground/Contents.swift)\n  * [Trade Stock Price](Problems/TradeStockPrice.playground/Contents.swift)\n  * [Largest Rect](Problems/LargestRect.playground/Contents.swift)\n  * [Tower Of Hanoi](Problems/TowerOfHanoi.playground/Contents.swift)\n  * [Longest Valid Parentheses](Problems/LongestValidParentheses.playground/Contents.swift)\n  * [Calculate Health In Genoms](Problems/CalculateHealthInGenoms.playground/Contents.swift)\n  * [Nearest K Points](Problems/NearestKPoints.playground/Contents.swift)\n  * [Min Distance Between Words](Problems/MinDistanceBetweenWords.playground/Contents.swift)\n  * [Swap Bits](Problems/swapBits.playground/Contents.swift)\n  * [Median Of Two Arrays](Problems/MedianOf2Arrays.playground/Contents.swift)\n  * [Number Of Squares](Problems/NumberOfSquares.playground/Contents.swift)\n  * [Swap Words In Sentence](Problems/SwapWordsInSentence.playground/Contents.swift)\n  * [Generate Parenteses](Problems/GenerateParenteses.playground/Contents.swift)\n  * [Bit Set](Problems/BitSet.playground/Contents.swift)\n  * [Three Sum](Problems/ThreeSum.playground/Contents.swift)\n  * [Validate Parentheses](Problems/ValidateParentheses.playground/Contents.swift)\n  * [Max Weight Pyramid](Problems/MaxWeightPyramid.playground/Contents.swift)\n  * [BitSet](Problems/BitSet.playground/Contents.swift)\n  * [Brick Wall](Problems/BrickWall.playground/Contents.swift)\n  * [Decode Ways](Problems/DecodeWays.playground/Contents.swift)\n  * [Coin Change](Problems/CoinChange.playground/Contents.swift)\n  * [Surrounded Regions](Problems/SurroundedRegions.playground/Contents.swift)\n  * [Longest Repeating Character Replacement](Problems/LongestRepeatingCharacterReplacement.playground/Contents.swift)\n  * [Splitwize](Problems/Splitwize.playground/Contents.swift)\n  * [Binary Tree to Linked List](Problems/BTtoDLL.playground/Contents.swift)\n  * [Tree Bundary Traversal](Problems/TreeBundaryTraversal.playground/Contents.swift)\n* [Data Structures](#data-structures)\n* [iOS Frameworks](#ios-frameworks)\n* [iOS Core](#ios-core)\n  * [Common](#common)\n  * [Objective-C](#objective-c)\n  * [Swift](#swift)\n\n# Data Structures\n\n### Variations on arrays\n- Array2D. A two-dimensional array with fixed dimensions. Useful for board games.\n- Bit Set. A fixed-size sequence of n bits.\n- Fixed Size Array. When you know beforehand how large your data will be, it might be more efficient to use an old-fashioned array with a fixed size.\n- Ordered Array. An array that is always sorted.\n- Rootish Array Stack. A space and time efficient variation on Swift arrays.\n\n### Queues\n- Stack. Last-in, first-out!\n- Queue. First-in, first-out!\n- Deque. A double-ended queue.\n- Priority Queue. A queue where the most important element is always at the front.\n- Ring Buffer. Also known as a circular buffer. An array of a certain size that conceptually wraps around back to the beginning.\n\n### Lists\n- Linked List. A sequence of data items connected through links. Covers both singly and doubly linked lists.\n- Skip-List. Skip List is a probabilistic data-structure with same logarithmic time bound and efficiency as AVL/ or Red-Black tree and provides a clever compromise to efficiently support search and update operations.\n\n### Trees\n- Tree. A general-purpose tree structure.\n- Binary Tree. A tree where each node has at most two children.\n- Binary Search Tree (BST). A binary tree that orders its nodes in a way that allows for fast queries.\n- Red-Black Tree. A self balancing binary search tree.\n- Splay Tree. A self balancing binary search tree that enables fast retrieval of recently updated elements.\n- Threaded Binary Tree. A binary tree that maintains a few extra variables for cheap and fast in-order traversals.\n- Segment Tree. Can quickly compute a function over a portion of an array.\n- Lazy Propagation\n- kd-Tree\n- Sparse Table. Another take on quickly computing a function over a portion of an array, but this time we'll make it even quicker!.\n- Heap. A binary tree stored in an array, so it doesn't use pointers. Makes a great priority queue.\n- Fibonacci Heap\n- Trie. A special type of tree used to store associative data structures.\n- B-Tree. A self-balancing search tree, in which nodes can have more than two children.\n- QuadTree. A tree with 4 children.\n- Octree. A tree with 8 children.\n\n### Hashing\n- Hash Table. Allows you to store and retrieve objects by a key. This is how the dictionary type is usually implemented.\n- Hash Functions\n\n### Sets\n- Bloom Filter. A constant-memory data structure that probabilistically tests whether an element is in a set.\n- Hash Set. A set implemented using a hash table.\n- Multiset. A set where the number of times an element is added matters. (Also known as a bag.)\n- Ordered Set. A set where the order of items matters.\n\n### Graphs\n- Graph\n- Breadth-First Search (BFS)\n- Depth-First Search (DFS)\n- Shortest Path on an unweighted tree\n- Single-Source Shortest Paths\n- Minimum Spanning Tree on an unweighted tree\n- Minimum Spanning Tree\n- All-Pairs Shortest Paths\n- Dijkstra's shortest path algorithm\n\n\n### What Are B-Trees?\nB-trees are search trees that provide an ordered key-value store with excellent performance characteristics. In principle, each node maintains a sorted array of its own elements, and another array for its children.\n\n\n# iOS Frameworks\n\n### What is CoreData ?\nCore data is an object graph manager which also has the ability to persist object graphs to the persistent store on a disk. An object graph is like a map of all the different model objects in a typical model view controller iOS application. CoreData has also integration with Core Spotlight.\n\nBut Core Data is not thread safe, meaning that, if you load a managed object on one thread, you can’t pass it to another thread and use it safely. This becomes an issue when we want to start introducing threading for performance, so we have two choices.\n\nThe first is to keep everything on the main thread, which just means it’s single threaded. Or the second, means making changes on background threads and passing managed object IDs and then loading those objects again on the main thread, but that would mean that you’re on the main thread, which puts us right back where we started. Both of these kind of ruin the point of using threading within Core Data and they can add a lot of complexity to the data layer.\n\nThere’s also another option for that and it’s to convert the managed object to a plain old Swift object, or a POSO.\n\n### What is iOS 11 SDK Features for Developers ?\nNew MapKit Markers\nConfigurable File Headers\nBlock Based UITableView Updates\nMapKit Clustering\nClosure Based KVO\nVector UIImage Support\nNew MapKit Display Type\nNamed colors in Asset Catalog\nPassword Autofill\nFace landmarks, Barcode and Text Detection\nMultitasking using the new floating Dock, slide-over apps, pinned apps, and the new App Switcher\nLocation Permission: A flashing blue status bar anytime an app is collecting your location data in the background. Updated locations permissions that always give the user the ability to choose only to share location while using the app.\n\n### When bounds origin will be different from 0,0?\nLet's take an example of UIScrollView: UIScrollView's bounds.origin will not be (0, 0) when its contentOffset is not (0, 0).\n\n### Unit Tests\nTests the smallest unit of functionality, typically a method/function (e.g. given a class with a particular state, calling x method on the class should cause y to happen). Unit tests should be focussed on one particular feature (e.g., calling the pop method when the stack is empty should throw an InvalidOperationException). Everything it touches should be done in memory; this means that the test code and the code under test shouldn't:\n\nCall out into (non-trivial) collaborators\nAccess the network\n\nHit a database\n\nUse the file system\n\nSpin up a thread\n\nAny kind of dependency that is slow / hard to understand / initialise / manipulate should be stubbed / mocked / whatevered using the appropriate techniques so you can focus on what the unit of code is doing, not what its dependencies do. In short, unit tests are as simple as possible, easy to debug, reliable (due to reduced external factors), fast to execute and help to prove that the smallest building blocks of your program function as intended before they're put together. The caveat is that, although you can prove they work perfectly in isolation, the units of code may blow up when combined which brings us to ...\n\n - Integration Tests\n\nIntegration tests build on unit tests by combining the units of code and testing that the resulting combination functions correctly. This can be either the innards of one system, or combining multiple systems together to do something useful. Also, another thing that differentiates integration tests from unit tests is the environment. Integration tests can and will use threads, access the database or do whatever is required to ensure that all of the code and the different environment changes will work correctly. If you've built some serialization code and unit tested its innards without touching the disk, how do you know that it'll work when you are loading and saving to disk? Maybe you forgot to flush and dispose filestreams. Maybe your file permissions are incorrect and you've tested the innards using in memory streams. The only way to find out for sure is to test it 'for real' using an environment that is closest to production. The main advantage is that they will find bugs that unit tests can't such as wiring bugs (e.g. an instance of class A unexpectedly receives a null instance of B) and environment bugs (it runs fine on my single-CPU machine, but my colleague's 4 core machine can't pass the tests). The main disadvantage is that integration tests touch more code, are less reliable, failures are harder to diagnose and the tests are harder to maintain. Also, integration tests don't necessarily prove that a complete feature works. The user may not care about the internal details of my programs, but I do!\n\n- Functional Tests\n\nFunctional tests check a particular feature for correctness by comparing the results for a given input against the specification. Functional tests don't concern themselves with intermediate results or side-effects, just the result (they don't care that after doing x, object y has state z). They are written to test part of the specification such as, \"calling function Square(x) with the argument of 2 returns 4\".\n\n- Acceptance Tests\n\nAcceptance testing seems to be split into two types: Standard acceptance testing involves performing tests on the full system (e.g. using your web page via a web browser) to see whether the application's functionality satisfies the specification. E.g. \"clicking a zoom icon should enlarge the document view by 25%.\" There is no real continuum of results, just a pass or fail outcome. The advantage is that the tests are described in plain English and ensures the software, as a whole, is feature complete. The disadvantage is that you've moved another level up the testing pyramid. Acceptance tests touch mountains of code, so tracking down a failure can be tricky. Also, in agile software development, user acceptance testing involves creating tests to mirror the user stories created by/for the software's customer during development. If the tests pass, it means the software should meet the customer's requirements and the stories can be considered complete. An acceptance test suite is basically an executable specification written in a domain specific language that describes the tests in the language used by the users of the system.\n\n### File owner\n\nTwo points to be remembered:\n\nThe File owner is the object that loads the nib, i.e. that object which receives the message loadNibNamed: or initWithNibName:.\nIf you want to access any objects in the nib after loading it, you can set an outlet in the file owner.\nSo you created a fancy view with lots of buttons, subviews etc . If you want to modify any of these views / objects any time after loading the nib FROM the loading object (usually a view or window controller) you set outlets for these objects to the file owner. It's that simple.\n\nThis is the reason why by default all View Controllers or Window Controllers act as file owners, and also have an outlet to the main window or view object in the nib file: because duh, if you're controlling something you'll definitely need to have an outlet to it so that you can send messages to it.\n\nThe reason it's called file owner and given a special place, is because unlike the other objects in the nib, the file owner is external to the nib and is not part of it. In fact, it only becomes available when the nib is loaded. So the file owner is a stand-in or proxy for the actual object which will later load the nib.\n\n### You’ve just been alerted that your new app is prone to crashing. What do you do?\n\nThis classic interview question is designed to see how well your prospective programmer can solve problems. What you’re looking for is a general methodology for isolating a bug, and their ability to troubleshoot issues like sudden crashes or freezing. In general, when something goes wrong within an app, a standard approach might look something like this:\n\nDetermine the iOS version and make or model of the device.\n\nGather enough information to reproduce the issue.\n\nAcquire device logs, if possible.\n\nOnce you have an idea as to the nature of the issue, acquire tooling or create a unit test and begin debugging. A great answer would include all of the above, with specific examples of debugging tools like Buglife or ViewMonitor, and a firm grasp of software debugging theory—knowledge on what to do with compile time errors, run-time errors, and logical errors. The one answer you don’t want to hear is the haphazard approach—visually scanning through hundreds of lines of code until the error is found. When it comes to debugging software, a methodical approach is must.\n\n### What are layer objects and what do they represent?\n\nLayer objects are data objects which represent visual content. Layer objects are used by views to render their content. Custom layer objects can also be added to the interface to implement complex animations and other types of sophisticated visual effects.\n\n### What makes React Native special for iOS?\n\n(Unlike PhoneGap) with React Native your application logic is written and runs in JavaScript, whereas your application UI is fully native; therefore you have none of the compromises typically associated with HTML5 UI.\nAdditionally (unlike Titanium), React introduces a novel, radical and highly functional approach to constructing user interfaces. In brief, the application UI is simply expressed as a function of the current application state.\n\n### What is NSFetchRequest ?\n\nNSFetchRequest is the class responsible for fetching from Core Data. Fetch requests are both powerful and flexible. You can use fetch requests to fetch a set of objects meeting the provided criteria, individual values and more.\n\n### Explain NSPersistentContainer ?\n\nThe persistent container creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.\n\n### NSFetchedResultsController ?\n\nNSFetchedResultsController is a controller, but it’s not a view controller. It has no user interface. Its purpose is to make developers’ lives easier by abstracting away much of the code needed to synchronize a table view with a data source backed by Core Data.\n\nSet up an NSFetchedResultsController correctly, and your table will mimic its data source without you have to write more than a few lines of code.\n\n### What is the three major debugging improvements in Xcode 8 ?\n\nThe View Debugger lets us visualize our layouts and see constraint definitions at runtime. Although this has been around since Xcode 6, Xcode 8 introduces some handy new warnings for constraint conflicts and other great convenience features.\nThe Thread Sanitizer is an all new runtime tool in Xcode 8 that alerts you to threading issues — most notably, potential race conditions.\nThe Memory Graph Debugger is also brand new to Xcode 8. It provides visualization of your app’s memory graph at a point in time and flags leaks in the Issue navigator.\n\n### How could you setup Live Rendering ?\n\nWith @IBInspectable and @IBDesignable, it’s possible to build a custom interface for configuring your custom controls and have them rendered in real-time while designing your project.\n\n@IBInspectable properties provide new access to an old feature: user-defined runtime attributes. Currently accessible from the identity inspector, these attributes have been available since before Interface Builder was integrated into Xcode. They provide a powerful mechanism for configuring any key-value coded property of an instance in a NIB, XIB, or storyboard.\n\nBuilt-in Cocoa types can also be extended to have inspectable properties beyond the ones already in Interface Builder’s attribute inspector. If you like rounded corners, you’ll love this UIView extension:\n\n```swift\nextension UIView {\n    @IBInspectable var cornerRadius: CGFloat {\n        get {\n            return layer.cornerRadius\n        }\n        set {\n            layer.cornerRadius = newValue\n            layer.masksToBounds = newValue > 0\n        }\n    }\n}\n```\n\nThe attribute @IBDesignable lets Interface Builder perform live updates on a particular view. This allows seeing how your custom views will appear without building and running your app after each change.\n\nTo mark a custom view as IBDesignable, prefix the class name with @IBDesignable (or the IB_DESIGNABLE macro in Objective-C). Your initializers, layout, and drawing methods will be used to render your custom view right on the canvas:\n\n```swift\n@IBDesignable\nclass MyCustomView: UIView {\n    ...\n}\n```\n\n### What is TVMLKit ?\nTVMLKit is the glue between TVML, JavaScript, and your native tvOS application.\n\n### What is Platform limitations of tvOS ?\nFirst, tvOS provides no browser support of any kind, nor is there any WebKit or other web-based rendering engine you can program against. This means your app can’t link out to a web browser for anything, including web links, OAuth, or social media sites.\nSecond, tvOS apps cannot explicitly use local storage. At product launch, the devices ship with either 32 GB or 64 GB of hard drive space, but apps are not permitted to write directly to the on-board storage.\ntvOS app bundle cannot exceed 4 GB.\n\n### What are Realm benefits ?\nAn open-source database framework.\nEasy to set up.\nAll changes are made to objects in store directly.\nSupports observing changes.\nSupports encryption.\nFast.\n\n### What is JSON/PLIST limits ?\nWe create your objects and then serialized them to disk..\nIt’s great and very limited use cases.\nWe can’t obviously use complex queries to filter your results.\nIt’s very slow.\nEach time we need something, we need to either serialize or deserialize it.\nit’s not thread-safe.\n\n### What are SQLite limits ?\nWe need to define the relations between the tables. Define the schema of all the tables.\nWe have to manually write queries to fetch data.\nWe need to query results and then map those to models.\nQueries are very fast.\n\n### How many are there APIs for battery-efficient location tracking ?\nThere are 3 apis.\nSignificant location changes — the location is delivered approximately every 500 meters (usually up to 1 km)\nRegion monitoring — track enter/exit events from circular regions with a radius equal to 100m or more. Region monitoring is the most precise API after GPS.\nVisit events — monitor place Visit events which are enters/exits from a place (home/office).\n\n# iOS Core\n\n## Common\n\n### What is Remote Notifications attacment’s limits ?\nWe can be sent with video or image with push notification. But maximum payload is 4kb.\n\n### What is three triggers for a local notification ?\nLocation, Calendar, and Time Interval. A Location notification fires when the GPS on your phone is at a location or geographic region. Calendar trigger is based on calendar data broken into date components. Time Interval is a count of seconds until the timer goes off.\n\n### How could we get device token ?\nThere are two steps to get device token. First, we must show the user’s permission screen, after we can register for remote notifications. If these steps go well, the system will provide device token. If we uninstall or reinstall the app, the device token would change.\n\n### What is Encapsulation ?\nEncapsulation is an object-oriented design principles and hides the internal states and functionality of objects. That means objects keep their state information private.\n\n### What is big-o notation ?\nAn algorithm is an impression method used to determine the working time for an input N size. The big-o notation grade is expressed by the highest value. And the big-o notation is finding the answer with the question of O(n). Here is a cheat sheet and swift algorithm club. For example;\n\nFor Loops big-o notation is O(N). Because For Loops work n times.\nVariables (var number:Int = 4) big-o notation is O(1).\n\n### What Is Dependency Management?\nIf we want to integrate open source project, add a framework from a third party project, or even reuse code across our own projects, dependency management helps us to manage these relationships. Check this out\n\n### What is UML Class Diagrams?\nUML Class Diagram is a set of rules and notations for the specification of a software system, managed and created by the Object Management Group.\n\n### Explain throw\nWe are telling the compiler that it can throw errors by using the throws keyword. Before we can throw an error, we need to make a list of all the possible errors you want to throw.\n\n### What is GraphQL ?\nGraphQL is trying to solve creating a query interface for the clients at the application level. Apollo iOS is a strongly-typed, caching GraphQL client for iOS, written in Swift.\n\n### Explain Common features of Protocols & superclasses\nimplementation reuse\nprovide points for customization\ninterface reuse\nsupporting modular design via dynamic dispatch on reused interfaces\n\n### What is Continuous Integration ?\nContinuous Integration allows us to get early feedback when something is going wrong during application development. There are a lot of continuous integration tools available.\n\n**Self hosted server**\n- Xcode Server\n- Jenkins\n- TeamCity\n- Cloud solutions\n- TravisCI\n- Bitrise\n- Buddybuild\n\n### What is the difference Delegates and Callbacks ?\nThe difference between delegates and callbacks is that with delegates, the NetworkService is telling the delegate “There is something changed.” With callbacks, the delegate is observing the NetworkService.\n\n### Explain Linked List\nLinked List basically consist of the structures we named the Node. These nodes basically have two things. The first one is the one we want to keep. (we do not have to hold single data, we can keep as much information as we want), and the other is the address information of the other node.\n\nDisadvantages of Linked Lists, at the beginning, there is extra space usage. Because the Linked List have an address information in addition to the existing information. This means more space usage.\n\n### Do you know Back End development ?\nDepends. I have experienced PARSE and I am awarded FBStart. I decided to learn pure back end. You have two choices. Either you can learn node.js + express.js and mongodb. OR, you can learn Vapor or Kitura.\n\nDon’t you like or use Firebase?\n\nFirebase doesn't have a path for macOS X developers.\nIf you want to learn Firebase, please just follow one month of Firebase Google Group.\n\n### Explain AutoLayout\nAutoLayout provides a flexible and powerful layout system that describes how views and the UI controls calculates the size and position in the hierarchy.\n\n### What is the disadvantage to hard-coding log statements ?\nFirst, when you start to log. This starts to accumulate. It may not seem like a lot, but every minute adds up. By the end of a project, those stray minutes will equal to hours.\n\nSecond, Each time we add one to the code base, we take a risk of injecting new bugs into our code.\n\n### What is Pointer ?\nA pointer is a direct reference to a memory address. Whereas a variable acts as a transparent container for a value, pointers remove a layer of abstraction and let you see how that value is stored.\n\n### Explain Core ML Pros and Cons\n**Pros of Core ML:**\nReally easy to add into your app.\nNot just for deep learning: also does logistic regression, decision trees, and other “classic” machine learning models.\nComes with a handy converter tool that supports several different training packages (Keras, Caffe, scikit-learn, and others).\n\n**Cons:**\nCore ML only supports a limited number of model types. If you trained a model that does something Core ML does not support, then you cannot use Core ML.\nThe conversion tools currently support only a few training packages. A notable omission is TensorFlow, arguably the most popular machine learning tool out there. You can write your own converters, but this isn’t a job for a novice. (The reason TensorFlow is not supported is that it is a low-level package for making general computational graphs, while Core ML works at a much higher level of abstraction.)\nNo flexibility, little control. The Core ML API is very basic, it only lets you load a model and run it. There is no way to add custom code to your models.\niOS 11 and later only.\n\n### What is pair programming?\nPair programming is a tool to share information with junior developers. Junior and senior developer sitting side-by-side this is the best way for the junior to learn from senior developers.\n\nCheck out Martin Fowler on “Pair Programming Misconceptions”, WikiHow on Pair Programming\n\n### Explain blocks\nBlocks are a way of defining a single task or unit of behavior without having to write an entire Objective-C class. they are anonymous functions.\n\n### What is Keychain ?\nKeychain is an API for persisting data securly in iOS App. There is a good library - Locksmith\n\n### What is the biggest changes in UserNotifications ?\nWe can add audio, video and images.\nWe can create custom interfaces for notifications.\nWe can manage notifications with interfaces in the notification center.\nNew Notification extensions allow us to manage remote notification payloads before they’re delivered.\n\n### Explain to using Class and Inheritance benefits\nWith Overriding provides a mechanism for customization\nReuse implementation\nSubclassing provides reuse interface\nModularity\nSubclasses provide dynamic dispatch\n\n### Explain Priority Inversion and Priority Inheritance.\nIf high priority thread waits for low priority thread, this is called Priority Inversion. if low priority thread temporarily inherit the priority of the highest priority thread, this is called Priority Inheritance.\n\n### Where do we use Dependency Injection ?\nWe use a storyboard or xib in our iOS app, then we created IBOutlets. IBOutlet is a property related to a view. These are injected into the view controller when it is instantiated, which is essentially a form of Dependency Injection.\n\nThere are forms of dependency injection: constructor injection, property injection and method injection.\n\n### What is RGR ( Red — Green — Refactor ) ?\nRed, Green and Refactor are stages of the TDD (Test Driven Development).\n\nRed: Write a small amount of test code usually no more than seven lines of code and watch it fail.\nGreen: Write a small amount of production code. Again, usually no more than seven lines of code and make your test pass.\nRefactor: Tests are passing, you can make changes without worrying. Clean up your code. There are great workshop notes here.\n\n### Please explain SOAP and REST Basics differences ?\nBoth of them helps us access Web services. SOAP relies exclusively on XML to provide messaging services. SOAP is definitely the heavyweight choice for Web service access. Originally developed by Microsoft.\n\nREST ( Representational State Transfer ) provides a lighter weight alternative. Instead of using XML to make a request, REST relies on a simple URL in many cases. REST can use four different HTTP 1.1 verbs (GET, POST, PUT, and DELETE) to perform tasks.\n\n### What kind of JSONSerialization have ReadingOptions ?\nmutableContainers Specifies that arrays and dictionaries are created as variables objects, not constants.\nmutableLeaves Specifies that leaf strings in the JSON object graph are created as instances of variable String.\nallowFragments Specifies that the parser should allow top-level objects that are not an instance of Array or Dictionary.\n\n### Please explain types of notifications.\nThere are two type of notifications: Remote and Local. Remote notification requires connection to a server. Local notifications don’t require server connection. Local notifications happen on device.\n\n### What is you favorite Visualize Chart library ?\nCharts has support iOS,tvOS,OSX The Apple side of the cross platform MPAndroidChart.\n\nCore Plot is a 2D plotting framework for macOS, iOS, and tvOS\n\nTEAChart has iOS support\n\n### When is a good time for dependency injection in our projects?\nThere is a few guidelines that you can follow.\n\nRule 1. Is Testability important to us? If so, then it is essential to identify external dependencies within the class that you wish to test. Once dependencies can be injected we can easily replace real services for mock ones to make it easy to testing easy.\n\nRules 2. Complex classes have complex dependencies, include application-level logic, or access external resources such as the disk or the network. Most of the classes in your application will be complex, including almost any controller object and most model objects. The easiest way to get started is to pick a complex class in your application and look for places where you initialize other complex objects within that class.\n\nRules 3. If an object is creating instances of other objects that are shared dependencies within other objects then it is a good candidate for a dependency injection.\n\n### REST, HTTP, JSON — What’s that?\nHTTP is the application protocol, or set of rules, web sites use to transfer data from the web server to client. The client (your web browser or app) use to indicate the desired action:\n\n**GET**: Used to retrieve data, such as a web page, but doesn’t alter any data on the server.\nHEAD: Identical to GET but only sends back the headers and none of the actual data.\n\n**POST**: Used to send data to the server, commonly used when filling a form and clicking submit.\n\n**PUT**: Used to send data to the specific location provided.\n\n**DELETE**: Deletes data from the specific location provided.\n\n**REST**, or REpresentational State Transfer, is a set of rules for designing consistent, easy-to-use and maintainable web APIs.\n\n**JSON** stands for JavaScript Object Notation; it provides a straightforward, human-readable and portable mechanism for transporting data between two systems. Apple supplies the JSONSerialization class to help convert your objects in memory to JSON and vice-versa.\n\n## What is the difference between LLVM and Clang?\nClang is the front end of LLVM tool chain ( “clang” C Language Family Frontend for LLVM ). Every Compiler has three parts .\n1. Front end ( lexical analysis, parsing )\n2. Optimizer ( Optimizing abstract syntax tree )\n3. Back end ( machine code generation )\n\nFront end ( Clang ) takes the source code and generates abstract syntax tree ( LLVM IR ).\n\n### What is Class ?\nA class is meant to define a functionality of an object. In this way, a class is like a blueprint of an object.\n\n### What is Object?\nEntity that representable in code, holds memory address.\n\nUnderlying entity exposes interface and functionality.\n\n### What is the difference between property and instance variable?\nA property is an instance variable with associated getter and setter methods. Property syntax creates all three components implicitly.\nA calculated (readonly) property is a getter method with no underlying instance variable.\n\n### Explain difference between SDK and Framework ?\nSDK is a more broad set of software development tools. This set is used for creation of applications.\n\nFramework is basically a platform which is used for developing software applications. It provides the necessary foundation on which the programs can be developed for a specific platform. SDK and Framework complement each other, and SDKs are available for frameworks.\n\n### What is Downcasting ?\nWhen we’re casting an object to another type in Objective-C, it’s pretty simple since there’s only one way to do it. In Swift, though, there are two ways to cast — one that’s safe and one that’s not .\n\n* In swift:\n\n  * as used for upcasting and type casting to bridged type\n\n  * as? used for safe casting, return nil if failed\n\n  * as! used to force casting, crash if failed. should only be used when we know the downcast will succeed.\n\n* In Objc: `(Object *)variable`\n\n### What is bitcode ?\nBitcode refers to to the type of code: “LLVM Bitcode” that is sent to iTunes Connect. This allows Apple to use certain calculations to re-optimize apps further (e.g: possibly downsize executable sizes). If Apple needs to alter your executable then they can do this without a new build being uploaded.\n\n### What is the difference SVN and Git ?\nSVN relies on a centralised system for version management. It’s a central repository where working copies are generated and a network connection is required for access.\n\nGit relies on a distributed system for version management. You will have a local repository on which you can work, with a network connection only required to synchronise.\n\n### What are the most important application delegate methods a developer should handle ?\nThe operating system calls specific methods within the application delegate to facilitate transitioning to and from various states. The seven most important application delegate methods a developer should handle are:\n\n- application:willFinishLaunchingWithOptions\n\nMethod called when the launch process is initiated. This is the first opportunity to execute any code within the app.\n\n- application:didFinishLaunchingWithOptions\n\nMethod called when the launch process is nearly complete. Since this method is called is before any of the app’s windows are displayed, it is the last opportunity to prepare the interface and make any final adjustments.\n\n- applicationDidBecomeActive\n\nOnce the application has become active, the application delegate will receive a callback notification message via the method applicationDidBecomeActive.\n\nThis method is also called each time the app returns to an active state from a previous switch to inactive from a resulting phone call or SMS.\n\n- applicationWillResignActive\n\nThere are several conditions that will spawn the applicationWillResignActive method. Each time a temporary event, such as a phone call, happens this method gets called. It is also important to note that “quitting” an iOS app does not terminate the processes, but rather moves the app to the background.\n\n- applicationDidEnterBackground\n\nThis method is called when an iOS app is running, but no longer in the foreground. In other words, the user interface is not currently being displayed. According to Apple’s UIApplicationDelegate Protocol Reference, the app has approximately five seconds to perform tasks and return. If the method does not return within five seconds, the application is terminated.\n\n- applicationWillEnterForeground\n\nThis method is called as an app is preparing to move from the background to the foreground. The app, however, is not moved into an active state without the applicationDidBecomeActive method being called. This method gives a developer the opportunity to re-establish the settings of the previous running state before the app becomes active.\n\n- applicationWillTerminate\n\nThis method notifies your application delegate when a termination event has been triggered. Hitting the home button no longer quits the application. Force quitting the iOS app, or shutting down the device triggers the applicationWillTerminate method. This is the opportunity to save the application configuration, settings, and user preferences.\n\n### What does code signing do?\nSigning our app allows iOS to identify who signed our app and to verify that our app hasn’t been modified since you signed it. The Signing Identity consists of a public-private key pair that Apple creates for us.\n\n### What problems does delegation solve?\n* Avoiding tight coupling of objects\n\n* Modifying behavior and appearance without the need to subclass objects\n\n* Allowing tasks to be handed off to any arbitrary object\n\n### What is the difference between a delegate and an NSNotification?\nDelegates and NSNotifications can be used to accomplish nearly the same functionality. However, delegates are one-to-one while NSNotifications are one-to-many.\n\nExplain SiriKit Limitations\n\n* SiriKit cannot use all app types\n\n* Not a substitute for a full app only an extension\n\n* Siri requires a consistent Internet connection to work\n\n* Siri service needs to communicate Apple Servers.\n\n### Why do we use a delegate pattern to be notified of the text field’s events?\nBecause at most only a single object needs to know about the event.\n\n### Explain View Controller Lifecycle events order ?\nThere are a few different lifecycle event\n\n- loadView\n\nCreates the view that the controller manages. It’s only called when the view controller is created and only when done programatically.\n- viewDidLoad\n\nCalled after the controller’s view is loaded into memory. It’s only called when the view is created.\n- viewWillAppear\n\nIt’s called whenever the view is presented on the screen. In this step the view has bounds defined but the orientation is not applied.\n- viewWillLayoutSubviews\n\nCalled to notify the view controller that its view is about to layout its subviews. This method is called every time the frame changes\n- viewDidLayoutSubviews\n\nCalled to notify the view controller that its view has just laid out its subviews. Make additional changes here after the view lays out its subviews.\n- viewDidAppear\n\nNotifies the view controller that its view was added to a view hierarchy.\n- viewWillDisappear\n\nBefore the transition to the next view controller happens and the origin view controller gets removed from screen, this method gets called.\n- viewDidDisappear\n\nAfter a view controller gets removed from the screen, this method gets called. You usually override this method to stop tasks that are should not run while a view controller is not on screen.\n- viewWillTransition(to:with:)\n\nWhen the interface orientation changes, UIKit calls this method on the window’s root view controller before the size changes are about to be made. The root view controller then notifies its child view controllers, propagating the message throughout the view controller hierarchy.\n\n### What is the major purposes of Frameworks?\nFrameworks have three major purposes:\n\n- Code encapsulation\n\n- Code modularity\n\n- Code reuse\n\nYou can share your framework with your other apps, team members, or the iOS community. When combined with Swift’s access control, frameworks help define strong, testable interfaces between code modules.\n\n### What is ARC ?\nARC is a compile time feature that is Apple’s version of automated memory management. It stands for Automatic Reference Counting. This means that it only frees up memory for objects when there are zero strong references/ to them.\nWhat is difference between BDD and TDD ?\n\nThe main difference between BDD and TDD is the fact that BDD test cases can be read by non-engineers, which can be very useful in teams.\n\niOS I prefer Quick BDD framework and its “matcher framework,” called Nimble.\n\n### How to educate app with Context ?\nEducation in context technique helping users interact with an element or surface in a way they have not done so previously. This technique often includes slight visual cues and subtle animation.\n\n### Please explain “Arrange-Act-Assert”\nAAA is a pattern for arranging and formatting code in Unit Tests. If we were to write XCTests each of our tests would group these functional sections, separated by blank lines:\n\nArrange all necessary preconditions and inputs.\nAct on the object or method under test.\nAssert that the expected results have occurred.\n\n### What is the benefit writing tests in iOS apps ?\nWriting tests first gives us a clear perspective on the API design, by getting into the mindset of being a client of the API before it exists.\nGood tests serve as great documentation of expected behavior.\nIt gives us confidence to constantly refactor our code because we know that if we break anything our tests fail.\nIf tests are hard to write its usually a sign architecture could be improved. Following RGR ( Red — Green — Refactor ) helps you make improvements early on.\n\n### What is five essential practical guidelines to improve your typographic quality of mobile product designs ?\n1. Start by choosing your body text typeface.\n2. Try to avoid mixing typefaces.\n3. Watch your line length.\n4. Balance line height and point size.\n5. Use proper Apostrophes and Dashes.\n\n\n### What does Yak Shaving mean ?\nYak shaving is a programing term that refers to a series of tasks that need to be performed before a project can progress to its next milestone.\n\n\n### What is the Test Driven Development of three simple rules ?\nYou are not allowed to write any production code unless it is to make a failing unit test pass.\nYou are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.\nYou are not allowed to write any more production code than is sufficient to pass the one failing unit test.\n\n### Why it is better to use higher order functions?\nFunctions that take another function as a parameter, or return a function, as a result, are known as higher-order functions. Swift defines these functions as CollectionType.\nThe very basic higher order function is a filter.\n\n### What is Concurrency ?\nConcurrency is dividing up the execution paths of your program so that they are possibly running at the same time. The common terminology: process, thread, multithreading, and others. Terminology;\nProcess, An instance of an executing app\nThread, Path of execution for code\nMultithreading, Multiple threads or multiple paths of execution running at the same time.\n\nConcurrency, Execute multiple tasks at the same time in a scalable manner.\nQueues, Queues are lightweight data structures that manage objects in the order of First-in, First-out (FIFO).\nSynchronous vs Asynchronous tasks\n\n### Grand Central Dispatch (GCD)\nGCD is a library that provides a low-level and object-based API to run tasks concurrently while managing threads behind the scenes. Terminology;\nDispatch Queues, A dispatch queue is responsible for executing a task in the first-in, first-out order.\n\nSerial Dispatch Queue A serial dispatch queue runs tasks one at a time.\nConcurrent Dispatch Queue A concurrent dispatch queue runs as many tasks as it can without waiting for the started tasks to finish.\nMain Dispatch Queue A globally available serial queue that executes tasks on the application’s main thread.\n\n### Readers-Writers\nMultiple threads reading at the same time while there should be only one thread writing. The solution to the problem is a readers-writers lock which allows concurrent read-only access and an exclusive write access. Terminology;\nRace Condition A race condition occurs when two or more threads can access shared data and they try to change it at the same time.\n\nDeadlock A deadlock occurs when two or sometimes more tasks wait for the other to finish, and neither ever does.\n\nReaders-Writers problem Multiple threads reading at the same time while there should be only one thread writing.\n\nReaders-writer lock Such a lock allows concurrent read-only access to the shared resource while write operations require exclusive access.\nDispatch Barrier Block Dispatch barrier blocks create a serial-style bottleneck when working with concurrent queues.\n\n### NSOperation — NSOperationQueue — NSBlockOperation\nNSOperation adds a little extra overhead compared to GCD, but we can add dependency among various operations and re-use, cancel or suspend them.\nNSOperationQueue, It allows a pool of threads to be created and used to execute NSOperations in parallel. Operation queues aren’t part of GCD.\nNSBlockOperation allows you to create an NSOperation from one or more closures. NSBlockOperations can have multiple blocks, that run concurrently.\n\n### What is the difference between Synchronous & Asynchronous task ?\nSynchronous: waits until the task has completed Asynchronous: completes a task in background and can notify you when complete\n\n### Explain #keyPath() ?\nUsing #keyPath(), a static type check will be performed by virtue of the key-path literal string being used as a StaticString or StringLiteralConvertible. At this point, it’s then checked to ensure that it\n\nA) is actually a thing that exists and\nB) is properly exposed to Objective-C.\n\n### What is bounding box?\nBounding box is a term used in geometry; it refers to the smallest measure (area or volume) within which a given set of points.\n\n### What is Dynamic Dispatch ?\nDynamic Dispatch is the process of selecting which implementation\nof a polymorphic operation that’s a method or a function to call at run time.\n\nThis means, that when we wanna invoke our methods like object method. (Swift does not default to dynamic dispatch)\n\n### What’s Code Coverage ?\nIt is a metric used to measure the percentage of source code covered when tests run.\n\n### What’s Completion Handler ?\nCompletion handlers are super convenient when our app is making an API call, and we need to do something when that task is done, like updating the UI to show the data from the API call.\n\nWe’ll see completion handlers in Apple’s APIs like dataTaskWithRequest and they can be pretty handy in your own code.\nThe completion handler takes a chunk of code with 3 arguments:(NSData?, NSURLResponse?, NSError?) that returns nothing: Void. It’s a closure.\nThe completion handlers have to marked @escaping since they are executed some point after the enclosing function has been executed.\n\n### What is Functions ?\nFunctions let us group a series of statements together to perform some task. Once a function is created, it can be reused over and over in your code. If you find yourself repeating statements in your code, then a function may be the answer to avoid that repetition.\nPro Tip, Good functions accept input and return output. Bad functions set global variables and rely on other functions to work.\n\n### What is ABI ?\nABIs are important when it comes to applications that use external libraries. If a program is built to use a particular library and that library is later updated, you don’t want to have to re-compile that application (and from the end-user’s standpoint, you may not have the source). If the updated library uses the same ABI, then your program will not need to change. ABI stability will come with Swift 5.0\n\n### Why is design pattern very important ?\nDesign patterns are reusable solutions to common problems in software design. They’re templates designed to help you write code that’s easy to understand and reuse. Most common Cocoa design patterns:\n\nCreational: Singleton.\n\nStructural: Decorator, Adapter, Facade.\n\nBehavioral: Observer, and, Memento\n\n### Explain MVC\nModels — responsible for the domain data or a data access layer which manipulates the data, think of ‘Person’ or ‘PersonDataProvider’ classes.\nViews — responsible for the presentation layer (GUI), for iOS environment think of everything starting with ‘UI’ prefix.\n\nController/Presenter/ViewModel — the glue or the mediator between the Model and the View, in general responsible for altering the Model by reacting to the user’s actions performed on the View and updating the View with changes from the Model.\n\n### Explain MVVM\nUIKit independent representation of your View and its state. The View Model invokes changes in the Model and updates itself with the updated Model, and since we have a binding between the View and the View Model, the first is updated accordingly.\n\nYour view model will actually take in your model, and it can format the information that’s going to be displayed on your view.\nThere is a more known framework called RxSwift. It contains RxCocoa, which are reactive extensions for Cocoa and CocoaTouch.\n\n### How to Prioritize Usability in Design ?\nBroke down its design process to prioritize usability in 4 steps:\nThink like the user, then design the UX.\nRemember that users are people, not demographics.\nWhen promoting an app, consider all the situations in which it could be useful.\nKeep working on the utility of the app even after launch.\n\n### What’s the difference between the frame and the bounds?\nThe bounds of a UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).\nThe frame of a UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.\n\n### Application States\nThe iOS application states are as follows:\n\n* Not running state: The app has not been launched or was running but was terminated by the system.\n\n* Inactive state:\n\nThe app is running in the foreground but is currently not receiving events. (It may be executing other code though.) An app usually stays in this state only briefly as it transitions to a different state. The only time it stays inactive for any period of time is when the user locks the screen or the system prompts the user to respond to some event (such as an incoming phone call or SMS message).\n\n- Active state:\n\nThe app is running in the foreground and is receiving events. This is the normal mode for foreground apps.\n\n- Background state:\n\nThe app is in the background and executing code. Most apps enter this state briefly on their way to being suspended. However, an app that requests extra execution time may remain in this state for a period of time. In addition, an app being launched directly into the background enters this state instead of the inactive state.\n\n- Suspended state:\n\nWhile suspended, an app remains in memory but does not execute any code. When a low-memory condition occurs, the system may purge suspended apps without notice to make more space for the foreground app.\n\n### What is Responder Chain ?\nA ResponderChain is a hierarchy of objects that have the opportunity to respond to events received.\n\n### What kind of order functions can we use on collection types ?\nmap(_:): Returns an array of results after transforming each element in the sequence using the provided closure.\nfilter(_:): Returns an array of elements that satisfy the provided closure predicate.\nreduce(_:_:): Returns a single value by combining each element in the sequence using the provided closure.\nsorted(by:): Returns an array of the elements in the sequence sorted based on the provided closure predicate.\nTo see all methods available from Sequence\n\n### What allows you to combine your commits ?\nlast commit - `git rebase -i HEAD~1`\ncombine - `git squash`\n\n### What is the difference ANY and ANYOBJECT ?\nAccording to Apple’s Swift documentation:\n\nAny can represent an instance of any type at all, including function types and optional types.\nAnyObject can represent an instance of any class type.\n\n### What is Regular expressions ?\nRegular expressions are special string patterns that describe how to search through a string.\n\n## Objective-C\n\n### What is a property? How can you create one? What is the benefits to use properties?\n@property, (auto)synthesize;\ngetter/setter method (also send KVO notifications).\nHides the iVars (safety and flexibility)\n\n### Method visibility\nprivate/public – no protected. anyone can call a private\n\n### How to check an optional protocol method existence on an object?\nCall `respondsToSelector`\n\n### + and - methods\nclass vs instance methods\n\n### How to add a method to a class (extend) without the source of the class and without recompiling the class?\nCategories\n\n### Difference between extensions () and (named) in categories implementations?\n`()`  should be only one and for main interface\n`(name)`  for categories\n\n### Benefits of extension category?\nprivate property declaration, compile time method check.\n\n### Can you re-declare a property in subclass or extension?\nYES. If you declare a property in one class as readonly, you can redeclare it as readwrite in a class extension, in a protocol, or in a subclass.\n\n### Limitations and problems with categories?\nCannot override an existing method and call it in the extension method\n\n### What are formal and informal protocols?\nFormal are the real protocols, informal are categories on NSObject (with optional methods)\n\n### Property modifiers and the meaning\nnonatomic/atomic, assign/retain/copy/readonly vs strong/weak/unsafe_unretained, getter=, setter=\n\n### How to declare protected-like methods (accessible only for some dedicated classes)?\nSeparate header file with (named) category, and include it in other class\n\n### Explain Selectors in ObjC\nIn Objective-C, a selector is the name used to select a method to execute on an object, or, more succinctly, the unique identifier that replaces the name when the source code is compiled. A selector is represented by the special Objective-C type called SEL .\n\n### KVC — KVO\nKVC adds stands for Key-Value Coding. It’s a mechanism by which an object’s properties can be accessed using string’s at runtime rather than having to statically know the property names at development time.\nKVO stands for Key-Value Observing and allows a controller or class to observe changes to a property value. In KVO, an object can ask to be notified of any changes to a specific property, whenever that property changes value, the observer is automatically notified.\n\n### What is interface?\nDefines the functions and properties of an object that is exposed to outside\n\n### How many different annotations available in Objective-C ?\n\\_Null_unspecified, which bridges to a Swift implicitly unwrapped optional. This is the default.\n\\_Nonnull, the value won’t be nil it bridges to a regular reference.\n\\_Nullable the value can be nil, it bridges to an optional.\n\\_Null_resettable the value can never be nil, when read but you can set it to know to reset it. This is only apply property.\n\n### What is made up of NSError object?\nThere are three parts of NSError object a domain, an error code, and a user info dictionary. The domain is a string that identifies what categories of errors this error is coming from.\n\n### Why do we use @synchronized ?\nsynchronized guarantees that only one thread can be executing that code in the block at any given time.\n\n### What is @synthesize in Objective-C ?\nsynthesize generates getter and setter methods for your property.\n\n### What is @dynamic in Objective-C ?\nWe use dynamic for subclasses of NSManagedObject. @dynamic tells the compiler that getter and setters are implemented using dynamic dispatch of Objective-C runtime.\n\n### What is the difference strong, weak, readonly and copy ?\nstrong, weak, assign property attributes define how memory for that property will be managed.\nStrong means that the reference count will be increased and\nthe reference to it will be maintained through the life of the object\nWeak ( non-strong reference ), means that we are pointing to an object but not increasing its reference count. It’s often used when creating a parent child relationship. The parent has a strong reference to the child but the child only has a weak reference to the parent.\nEvery time used on var\nEvery time used on an optional type\nAutomatically changes itself to nil\nRead only, we can set the property initially but then it can’t be changed.\nCopy, means that we’re copying the value of the object when it’s created. Also prevents its value from changing.\nfor more details check this out\n\n### Why don’t we use strong for enum property in Objective-C ?\nBecause enums aren’t objects, so we don’t specify strong or weak here. (C Enum)\n\n## Swift\n\n### What is Protocol Extensions?\nWe can adopt protocols using extensions as well as on the original type declaration. This allows you to add protocols to types you don’t necessarily own.\n\n### Why do we use availability attributes ?\nApple wants to support one system version back, meaning that we should support iOS9 or iOS8. [Availability Attributes](https://docs.swift.org/swift-book/ReferenceManual/Attributes.html) lets us to support previous version iOS.\n\n###  What’s the difference optional between nil and .None?\nThere is no difference. Optional.None (.None for short) is the correct way of initializing an optional variable lacking a value, whereas nil is just syntactic sugar for .None.\n\n###  How do you follow up clean code for this project ?\nI follow style guide and coding conventions for Swift projects of [Github](https://github.com/raywenderlich/swift-style-guide) and SwiftLint.\n\n### How many different ways to pass data in Swift ?\nThere are many different ways such as Delegate, KVO, Segue, and NSNotification, Target-Action, Callbacks.\n\n### When do you use optional chaining vs. if let or guard ?\nWe use optional chaining when we do not really care if the operation fails; otherwise, we use if let or guard. Optional chaining lets us run code only if our optional has a value.\n\nUsing the question mark operator like this is called optional chaining. Apple’s documentation explains it like this:\n\nOptional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.\n\n### Could you explain Associatedtype ?\nIf you want to create Generic Protocol we can use associatedtype. For more details check this out.\n\n### What is the difference Filter and Map Function ?\nMap, we pass in a function that returns a value for each element in an array. The return value of this function represents what an element becomes in our new array.\n\nFilter, we pass in a function that returns either true or false for each element. If the function that we pass returns true for a given element, then the element is included in the final array.\n\n### What is DispatchGroup ?\nDispatchGroup allows for aggregate synchronization of work. We can use them to submit multiple different work items and track when they all complete, even though they might run on different queues. This behavior can be helpful when progress can’t be made until all of the specified tasks are complete. \n\n### Explain subscripts ?\nClasses, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence.\n\n### What is Nil Coalescing & Ternary Operator ?\nnil coalescing - `??`\nteranry - `? :`\nIt is an easily return an unwrapped optional, or a default value. If we do not have value, we can set zero or default value.\n\n\n### What is the Swift main advantage ?\nTo mention some of the main advantages of Swift:\n\nOptional Types, which make applications crash-resistant.\n\nBuilt-in error handling.\n\nClosures.\n\nGenerics, Protocol Extensions and Constraints make it easy to reuse code and implement new functionality.\n\nFaster in execution when using best practices (Slower in compilation).\n\nType-safe language.\n\nSupports pattern matching.\n\nMore human readable code.\n\n### What is the difference CollectionViews & TableViews ?\nTableViews display a list of items, in a single column, a vertical fashion, and limited to vertical scrolling only.\n\nCollectionViews also display a list of items, however, they can have multiple columns and rows.\n\n### What is Alamofire doing ?\nAlamofire uses URL Loading System in the background, so it does integrate well with the Apple-provided mechanisms for all the network development. This means, It provides chainable request/response methods, JSON parameter and response serialization, authentication, and many other features. It has thread mechanics and execute requests on a background thread and call completion blocks on the main thread.\n\n### Explain [weak self] and [unowned self] ?\nunowned ( non-strong reference ) does the same as weak with one exception: The variable will not become nil and must not be an optional.\n\nWhen you try to access the variable after its instance has been deallocated. That means, you should only use unowned when you are sure, that this variable will never be accessed after the corresponding instance has been deallocated.\n\nHowever, if you don’t want the variable to be weak AND you are sure that it can’t be accessed after the corresponding instance has been deallocated, you can use unowned.\n\nEvery time used with non-optional types\nEvery time used with let\nBy declaring it [weak self] you get to handle the case that it might be nil inside the closure at some point and therefore the variable must be an optional. A case for using [weak self] in an asynchronous network request, is in a view controller where that request is used to populate the view.\n\n### Method Swizzling in Swift\nMethod Swizzling is a well known practice in Objective-C and in other languages that support dynamic method dispatching.\n\nThrough swizzling, the implementation of a method can be replaced with a different one at runtime, by changing the mapping between a specific #selector(method) and the function that contains its implementation.\n\nTo use method swizzling with your Swift classes there are two requirements that you must comply with:\n\nThe class containing the methods to be swizzled must extend NSObject\nThe methods you want to swizzle must have the dynamic attribute\n\n### What is the difference Non-Escaping and Escaping Closures ?\n\nThe lifecycle of a non-escaping closure is simple:\n\nPass a closure into a function\nThe function runs the closure (or not)\nThe function returns\nEscaping closure means, inside the function, you can still run the closure (or not); the extra bit of the closure is stored some place that will outlive the function. There are several ways to have a closure escape its containing function:\n\nAsynchronous execution: If you execute the closure asynchronously on a dispatch queue, the queue will hold onto the closure for you. You have no idea when the closure will be executed and there’s no guarantee it will complete before the function returns.\nStorage: Storing the closure to a global variable, property, or any other bit of storage that lives on past the function call means the closure has also escaped.\n\n### Explain generics ?\nGenerics create code that does not get specific about underlying data types.\n\nGenerics allow us to know what type it is going to contain.\n\nGenerics provide code reusability.\n\n### Explain lazy ?\nAn initial value of the lazy stored properties is calculated only when the property is called for the first time. There are situations when the lazy properties come very handy to developers.\n\n### Explain what is defer ?\ndefer keyword which provides a block of code that will be executed in the case when execution is leaving the current scope.\n\n### What is Enum ?\n\"OR\" Type. Enum represents a group of all possible values the Object can represent.\n\n### What is Operator Overloading ?\nOperator overloading allows us to change how existing operators behave with types that both already exist.\n\n### How to pass a variable as a reference ?\nWe need to mention that there are two types of variables: reference and value types. The difference between these two types is that by passing value type, the variable will create a copy of its data, and the reference type variable will just point to the original data in the memory.\nTo pass value type as a reference we use &valueTypeVariable as an inout parameter in the function.\n\n### Please explain Swift’s pattern matching techniques\nTuple patterns are used to match values of corresponding tuple types.\nType-casting patterns allow you to cast or match types.\nWildcard patterns match and ignore any kind and type of value.\nOptional patterns are used to match optional values.\nEnumeration case patterns match cases of existing enumeration types.\nExpression patterns allow you to compare a given value against a given expression.\n\n### Please explain final keyword ?\nBy adding the keyword final in front of the method name, we prevent the method from being overridden. Can substitute `final class` keyword with a single word `static` and get the same behavior.\n\nFinal classes can't be subclassed\n\n### What is the difference `open` & `public` access level ?\nopen allows other modules to use the class and inherit the class; for members, it allows others modules to use the member and override it.\n\npublic only allows other modules to use the public classes and the public members. Public classes can no longer be subclassed, nor public members can be overridden.\n\n### What is the difference `fileprivate`, `private` and `public private(set)` access level ?\nfileprivate is accessible within the current file, private is accessible within the current declaration.\n\npublic private(set) means getter is public, but the setter is private.\n\n### What is Internal access ?\nInternal access enables entities to be used within any source file from their defining module, but not in any source file outside of the module.\n\nInternal access is the default level of access. So even though we haven’t been writing any access control specifiers in our code, our code has been at an internal level by default.\n\n### Explain Forced Unwrapping\nWhen we defined a variable as optional, then to get the value from this variable, we will have to unwrap it. This just means putting an exclamation mark at the end of the variable.\n\n### Explain Swift Standard Library Protocol ?\nThere are a few different protocol. Equatable protocol, that governs how we can distinguish between two instances of the same type. That means we can analyze. If we have a specific value is in our array. The comparable protocol, to compare two instances of the same type and sequence protocol: prefix(while:) and drop(while:) [SE-0045].\n\nSwift 4 introduces a new `Codable` protocol that lets us serialize and deserialize custom data types without writing any special code.\n\n### Explain Swift Package Manager\nThe Swift Package Manager will help to vastly improve the Swift ecosystem, making Swift much easier to use and deploy on platforms without Xcode such as Linux. The Swift Package Manager also addresses the problem of dependency hell that can happen when using many interdependent libraries.\n\nThe Swift Package Manager only supports using the master branch. Swift Package Manager now supports packages with Swift, C, C++ and Objective-C.\n\n### How is an inout parameter different from a regular parameter?\nAn Inout is passed as function parameter.\n\nInside a function **the local copy** is modified\n\nBefore function returns it takes `inout` object and sets it's value equal to that local copy\n\nSo it seems like you pass parameter by reference, however it's not actually the case\n\n### What are benefits of Guard ?\nThere are two big benefits to guard. One is avoiding the pyramid of doom, as others have mentioned — lots of annoying if let statements nested inside each other moving further and further to the right. The other benefit is provide an early exit out of the function using break or using return.\n"
  }
]