<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Swift &#8211; Inga X</title>
	<atom:link href="https://ingax.com/tag/swift/feed/" rel="self" type="application/rss+xml" />
	<link>https://ingax.com</link>
	<description>An education platform for people passionate about software engineering to learn problem solving techniques and useful algorithms and data structures</description>
	<lastBuildDate>Sat, 12 Nov 2022 17:35:06 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.5.25</generator>
	<item>
		<title>Binary Tree Traversal</title>
		<link>https://ingax.com/binary-tree-traversal/</link>
					<comments>https://ingax.com/binary-tree-traversal/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Mon, 14 Feb 2022 22:45:05 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[BST Traversal]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[GIP]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6498</guid>

					<description><![CDATA[How to Recall Tree Traversal Orders Let L denote the left child. Let R denote the right child. Let P denote the parent and position....]]></description>
										<content:encoded><![CDATA[
<h3>How to Recall Tree Traversal Orders</h3>



<p>Let <strong>L</strong> denote the left child.</p>



<p>Let <strong>R</strong> denote the right child.</p>



<p>Let <strong>P</strong> denote the parent and position.</p>



<p>To easily remember tree traversal orders, pay attention to the position of <strong>P</strong> in the following strings.</p>



<p>When <strong>P</strong> is in the center, it is <strong>In Order</strong>. When it is first, it is <strong>Pre Order</strong>. And when it is last, it is <strong>Post Order</strong>.</p>



<p>L &#8211; <span style="text-decoration: underline;">P</span> &#8211; R |    <strong>In Order</strong></p>



<p><span style="text-decoration: underline;">P</span> &#8211; L &#8211; R |    <strong>Pre Order</strong></p>



<p>L &#8211; R &#8211; <span style="text-decoration: underline;">P</span> |    <strong>Post Order</strong></p>



<p>Note that L and R are always in the same order. The only element changing order is the parent.</p>



<h3>In Order</h3>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">leftChild -> parent -> rightChild</code></pre>



<p>Integer values come out in order when traversing a Binary Search Tree.</p>



<h3>Pre Order</h3>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">parent -> leftChild -> rightChild</code></pre>



<p>Traverse parent first (pre).</p>



<h3>Post Order</h3>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">leftChild -> rightChild -> parent</code></pre>



<p>Traverse parent last (post).</p>



<h3>Code</h3>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">class BST {
    var value: Int?
    var left: BST?
    var right: BST?
    
    init(value: Int) {
        self.value = value
        left = nil
        right = nil
    }
}

// O(n) time | O(n) space, because we're storing all values in array
// Note: If were were just printing values, space will be O(h), where
// h is the height of the tree.

func inOrderTraversal(tree: BST?, array: inout [Int]) -> [Int] {
    guard let node = tree, let value = node.value else { return array }
    
    inOrderTraversal(tree: node.left, array: &array)
    array.append(value)
    inOrderTraversal(tree: node.right, array: &array)
    
    return array
}

func preOrderTraversal(tree: BST?, array: inout [Int]) -> [Int] {
    guard let node = tree, let value = node.value else { return array }
    
    array.append(value)
    preOrderTraversal(tree: node.left, array: &array)
    preOrderTraversal(tree: node.right, array: &array)
    
    return array
}

func postOrderTraversal(tree: BST?, array: inout [Int]) -> [Int] {
    guard let node = tree, let value = node.value else { return array }
    
    postOrderTraversal(tree: node.left, array: &array)
    postOrderTraversal(tree: node.right, array: &array)
    array.append(value)
    
    return array
}</code></pre>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/binary-tree-traversal/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Principle of Recursion</title>
		<link>https://ingax.com/principle-of-recursion/</link>
					<comments>https://ingax.com/principle-of-recursion/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Wed, 02 Dec 2020 21:21:44 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Recursion]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6937</guid>

					<description><![CDATA[Print string in reverse order. You can easily solve this problem iteratively,&#160;i.e.&#160;looping through the string starting from its last character. But how about solving it...]]></description>
										<content:encoded><![CDATA[
<h3>Print string in reverse order.</h3>



<p>You can easily solve this problem iteratively,&nbsp;<em>i.e.</em>&nbsp;looping through the string starting from its last character. But how about solving it recursively?</p>



<p>First, we can define the desired function as&nbsp;<code>printReverse(str[0...n-1])</code>, where&nbsp;<code>str[0]</code>&nbsp;represents the first character in the string. Then we can accomplish the given task in two steps:</p>



<ol><li><code>printReverse(str[1...n-1])</code>: print the substring&nbsp;<code>str[1...n-1]</code>&nbsp;in reverse order.</li><li><code>print(str[0])</code>: print the first character in the string.</li></ol>



<p>Notice that we call the function itself in the first step, which by definition makes the function recursive.</p>



<p>Here is the code snippet:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">func printReverse(_ string: String) {
    let charArray = Array(string)
    helper(charArray, index: 0)
}

func helper(_ string: [Character], index: Int) {
    guard index < string.count else {
        return
    }
    
    helper(string, index: index + 1)
    print(string[index])
}</code></pre>



<h3>Reverse String</h3>



<p>Write a function that reverses a string. The input string is given as an array of characters&nbsp;<code>char[]</code>.</p>



<p>Do not allocate extra space for another array, you must do this by&nbsp;<strong>modifying the input array&nbsp;<a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank" rel="noreferrer noopener">in-place</a></strong>&nbsp;with O(1) extra memory.</p>



<p>You may assume all the characters consist of&nbsp;<a href="https://en.wikipedia.org/wiki/ASCII#Printable_characters" target="_blank" rel="noreferrer noopener">printable ascii characters</a>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted"><strong>Input: </strong>["h","e","l","l","o"]
<strong>Output: </strong>["o","l","l","e","h"]
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted"><strong>Input: </strong>["H","a","n","n","a","h"]
<strong>Output: </strong>["h","a","n","n","a","H"]</pre>



<p>Here's my solution. I noticed it's only necessary to recurse halfway through the input.</p>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">    func reverseString(_ s: inout [Character]) {
        helper(&s, index: 0)
    }
    func helper(_ s: inout [Character], index: Int) {
        guard index < s.count / 2 else {
            return
        }
        helper(&#038;s, index: index + 1)
        s.swapAt(index, s.count - 1 - index)
    }</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/principle-of-recursion/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Find the Largest Value in a BST that is Smaller than the Target Value</title>
		<link>https://ingax.com/find-the-largest-value-in-a-bst-that-is-smaller-than-the-target-value/</link>
					<comments>https://ingax.com/find-the-largest-value-in-a-bst-that-is-smaller-than-the-target-value/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Thu, 26 Nov 2020 01:24:39 +0000</pubDate>
				<category><![CDATA[Programming Problems]]></category>
		<category><![CDATA[Pramp]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6919</guid>

					<description><![CDATA[Pramp Largest Smaller BST Key Problem Given a root of a&#160;Binary Search Tree (BST)&#160;and a number&#160;num, implement an efficient function&#160;findLargestSmallerKey&#160;that finds the largest key in...]]></description>
										<content:encoded><![CDATA[
<h3>Pramp Largest Smaller BST Key Problem</h3>



<p>Given a root of a&nbsp;<a href="http://en.wikipedia.org/wiki/Binary_search_tree" target="_blank" rel="noreferrer noopener">Binary Search Tree (BST)</a>&nbsp;and a number&nbsp;<code>num</code>, implement an efficient function&nbsp;<code>findLargestSmallerKey</code>&nbsp;that finds the largest key in the tree that is smaller than&nbsp;<code>num</code>. If such a number doesn’t exist, return -1. Assume that all keys in the tree are nonnegative.</p>



<p>Analyze the time and space complexities of your solution.</p>



<p><strong>For example:</strong></p>



<p>For&nbsp;<code>num = 17</code>&nbsp;and the binary search tree below:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img width="549" height="460" src="https://ingax.com/wp-content/uploads/2020/11/BST_Example.png" alt="" class="wp-image-6920" title="Binary Tree" srcset="https://ingax.com/wp-content/uploads/2020/11/BST_Example.png 549w, https://ingax.com/wp-content/uploads/2020/11/BST_Example-300x251.png 300w" sizes="(max-width: 549px) 100vw, 549px" /></figure></div>



<p><strong>Your function would return:</strong></p>



<p><code>14</code>&nbsp;since it’s the largest key in the tree that is still smaller than&nbsp;<code>17</code>.</p>



<p><strong>Constraints:</strong></p>



<ul><li><strong>[time limit] 5000ms</strong></li><li><strong>[input] Node</strong>&nbsp;<code>rootNode</code></li><li><strong>[output] integer</strong></li></ul>



<h3>Solution</h3>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">public class Node {
    
    private(set) public var value: Int
    private(set) public var parent: Node?
    private(set) public var left: Node?
    private(set) public var right: Node?
    
    public init(_ value: Int) {
        self.value = value
    }
    
    public func insert(_ value: Int) {
        if value < self.value {
            if let left = left {
                left.insert(value)
            } else {
                left = Node(value)
                left?.parent = self
            }
        } else {
            if let right = right {
                right.insert(value)
            } else {
                right = Node(value)
                right?.parent = self
            }
        }
    }
    
    public convenience init(array: [Int]) {
        precondition(array.count > 0)
        self.init(array.first!)
        for v in array.dropFirst() {
            insert(v)
        }
    }
}

func findLargestSmallerKey(rootNode: Node, num: Int, result: Int) -> Int {
    var result = result
    
    if rootNode.value < num &#038;&#038; rootNode.value > result  {
        result = rootNode.value
        print(result)
    }
    
    if rootNode.value > num {
        if rootNode.left == nil { return result }
        result = findLargestSmallerKey(rootNode: rootNode.left!, num: num, result: result)
    } else {
        if rootNode.right == nil { return result }
        result = findLargestSmallerKey(rootNode: rootNode.right!, num: num, result: result)
    }
    
    return result
}

func findLargestSmallerKey(rootNode: Node, num: Int) -> Int {
    return findLargestSmallerKey(rootNode: rootNode, num: num, result: -1)
}</code></pre>



<h3>Time and Space Complexity</h3>



<p>The time complexity is \(O(logn) \). Because of the nature of a binary tree, after each recursive call, the problem space is halved.</p>



<p>The space complexity is also \(O(logn) \) because of the stack space used during the recursive calls. </p>



<h3>Think Different</h3>



<ul><li>Thought about DFS or BFS as possible solutions before realizing that they weren&#8217;t necessary.</li><li>Forgot to include my base case.</li><li>Realized that I needed to overload my function to include the result. </li></ul>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/find-the-largest-value-in-a-bst-that-is-smaller-than-the-target-value/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Copy a Matrix with a Spiral Sequence</title>
		<link>https://ingax.com/copy-a-matrix-with-a-spiral-sequence/</link>
					<comments>https://ingax.com/copy-a-matrix-with-a-spiral-sequence/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Tue, 24 Nov 2020 23:00:05 +0000</pubDate>
				<category><![CDATA[Programming Problems]]></category>
		<category><![CDATA[Pramp]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6912</guid>

					<description><![CDATA[Pramp Matrix Spiral Copy Problem Given a 2D array (matrix)&#160;inputMatrix&#160;of integers, create a function&#160;spiralCopy&#160;that copies&#160;inputMatrix’s values into a 1D array in a spiral order, clockwise....]]></description>
										<content:encoded><![CDATA[
<h3>Pramp Matrix Spiral Copy Problem</h3>



<p>Given a 2D array (matrix)&nbsp;<code>inputMatrix</code>&nbsp;of integers, create a function&nbsp;<code>spiralCopy</code>&nbsp;that copies&nbsp;<code>inputMatrix</code>’s values into a 1D array in a spiral order, clockwise. Your function then should return that array. Analyze the time and space complexities of your solution.</p>



<p><strong>Example:</strong></p>



<pre class="wp-block-preformatted">input:  inputMatrix  = [ [1,    2,   3,  4,    5],
                         [6,    7,   8,  9,   10],
                         [11,  12,  13,  14,  15],
                         [16,  17,  18,  19,  20] ]

output: [1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12]
</pre>



<p>See the illustration below to understand better what a clockwise spiral order looks like.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img width="1024" height="515" src="https://ingax.com/wp-content/uploads/2020/11/matrix_spiral_copy_example-1024x515.png" alt="" class="wp-image-6913" srcset="https://ingax.com/wp-content/uploads/2020/11/matrix_spiral_copy_example-1024x515.png 1024w, https://ingax.com/wp-content/uploads/2020/11/matrix_spiral_copy_example-300x151.png 300w, https://ingax.com/wp-content/uploads/2020/11/matrix_spiral_copy_example-768x386.png 768w, https://ingax.com/wp-content/uploads/2020/11/matrix_spiral_copy_example.png 1474w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption>Clockwise Spiral Order</figcaption></figure></div>



<p><strong>Constraints:</strong></p>



<ul><li><strong>[time limit] 5000ms</strong></li><li><strong>[input] array.array.integer</strong>&nbsp;<code>inputMatrix</code><ul><li>1 ≤ inputMatrix[0].length ≤ 100</li><li>1 ≤ inputMatrix.length ≤ 100</li></ul></li><li><strong>[output] array.integer</strong></li></ul>



<h3>Solution</h3>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">func spiralCopy(inputMatrix: [[Int]]) -> [Int] {
    var result = [Int]()
    var pos = (row: 0, col: 0)
    var rowEnd = inputMatrix.count - 1
    var colEnd = inputMatrix[0].count - 1
    var isComplete: Bool {
        return rowEnd < 0 || colEnd < 0
    }
    
    while true {
        // move right
        guard !isComplete else { break }
        for _ in 0...colEnd {
            if !result.isEmpty {
                pos.col += 1
            }
            result += [inputMatrix[pos.row][pos.col]]
        }
        rowEnd -= 1

        // move down
        guard !isComplete else { break }
        for _ in 0...rowEnd {
            pos.row += 1
            result += [inputMatrix[pos.row][pos.col]]
        }
        colEnd -= 1
        
        // move left
        guard !isComplete else { break }
        for _ in (0...colEnd).reversed() {
            pos.col -= 1
            result += [inputMatrix[pos.row][pos.col]]
        }
        rowEnd -= 1
        
        // move up
        guard !isComplete else { break }
        for _ in (0...rowEnd).reversed() {
            pos.row -= 1
            result += [inputMatrix[pos.row][pos.col]]
        }
        colEnd -= 1
    }
    
    return result
}</code></pre>



<h3>Space and Time Complexity</h3>



<p>This algorithm loops through all elements of the input array one time. We also create an output array with the same number of elements as the input array. Therefore, both space and time complexity are \(O(n) \).</p>



<h3>Think Different</h3>



<ul><li>Index out of range.</li><li>Used pos.col &lt; &gt; colEnd instead of iterating up to colEnd.</li><li>Important to increment pos.row and pos.col prior to appending to avoid double append.</li><li>Move isComplete check outside of inner loops.</li><li>Put condition to check for first append at index (0,0).</li></ul>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/copy-a-matrix-with-a-spiral-sequence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Sorting Pancakes</title>
		<link>https://ingax.com/sorting-pancakes/</link>
					<comments>https://ingax.com/sorting-pancakes/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Fri, 20 Nov 2020 19:10:36 +0000</pubDate>
				<category><![CDATA[Programming Problems]]></category>
		<category><![CDATA[Pramp]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6906</guid>

					<description><![CDATA[Pramp Pancake Sort Problem Given an array of integers&#160;arr: Write a function&#160;flip(arr, k)&#160;that reverses the order of the first&#160;kelements in the array&#160;arr. Write a function&#160;pancakeSort(arr)&#160;that...]]></description>
										<content:encoded><![CDATA[
<h3>Pramp Pancake Sort Problem</h3>



<p>Given an array of integers&nbsp;<code>arr</code>:</p>



<ol><li>Write a function&nbsp;<code>flip(arr, k)</code>&nbsp;that reverses the order of the first&nbsp;<code>k</code>elements in the array&nbsp;<code>arr</code>.</li><li>Write a function&nbsp;<code>pancakeSort(arr)</code>&nbsp;that sorts and returns the input array. You are allowed to use only the function&nbsp;<code>flip</code>&nbsp;you wrote in the first step in order to make changes in the array.</li></ol>



<p><strong>Example:</strong></p>



<pre class="wp-block-preformatted">input:  arr = [1, 5, 4, 3, 2]

output: [1, 2, 3, 4, 5] # to clarify, this is pancakeSort's output
</pre>



<p>Analyze the time and space complexities of your solution.</p>



<p><strong>Note:</strong>&nbsp;it’s called pancake sort because it resembles sorting pancakes on a plate with a spatula, where you can only use the spatula to flip some of the top pancakes in the plate. To read more about the problem, see the&nbsp;<a href="https://en.wikipedia.org/wiki/Pancake_sorting" target="_blank" rel="noreferrer noopener">Pancake Sorting Wikipedia page</a>.</p>



<p><strong>Constraints:</strong></p>



<ul><li><strong>[time limit] 5000ms</strong></li><li><strong>[input] array.integer</strong>&nbsp;<code>arr</code></li><li><strong>[input] integer</strong>&nbsp;<code>k</code><ul><li>0 ≤ k</li></ul></li><li><strong>[output] array.integer</strong></li></ul>



<h3>Solution</h3>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">func flip(_ arr: [Int], _ k: Int) -> [Int] {
    return arr[0...k].reversed() + arr[k+1..<arr.count]
}

func pancakeSort(arr: [Int]) -> [Int] {
    var arr = arr
    var partition = arr.count - 1
    var maxValue = 0
    var maxIndex = 0
    while partition > 0 {
        for (i, val) in arr[0...partition].enumerated() {
            if val >= maxValue {
                maxValue = val
                maxIndex = i
            }
        }
        arr = flip(arr, maxIndex)
        arr = flip(arr, partition)
        partition -= 1
        maxValue = 0
        maxIndex = 0
    }
    
    return arr
}</code></pre>



<h3>Time and Space Complexity</h3>



<p>Time complexity is \(O(n^2) \). This is a comparison sorting algorithm. We utilize a double loop. The outer loop iterates through every element. The inner loop decreases in size by 1 on each iteration of the outer loop.</p>



<p>The space complexity is \(O(n) \). We never utilize more space than the size of the original input array.</p>



<h3>Think Different</h3>



<ol><li>Forgot to reset my values back to 0 before looping through again.</li><li>Partition while loop incorrectly set to while partition &gt; 1.</li></ol>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/sorting-pancakes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Decoding a Secret Message</title>
		<link>https://ingax.com/decoding-a-secret-message/</link>
					<comments>https://ingax.com/decoding-a-secret-message/#comments</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Thu, 19 Nov 2020 01:24:15 +0000</pubDate>
				<category><![CDATA[Programming Problems]]></category>
		<category><![CDATA[Pramp]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6878</guid>

					<description><![CDATA[Pramp Secret Message Problem An infamous gang of cyber criminals named “The Gray Cyber Mob”, which is behind many hacking attacks and drug trafficking, has...]]></description>
										<content:encoded><![CDATA[
<h3>Pramp Secret Message Problem</h3>



<p>An infamous gang of cyber criminals named “The Gray Cyber Mob”, which is behind many hacking attacks and drug trafficking, has recently become a target for the FBI. After intercepting some of their messages, which looked like complete nonsense, the agency learned that they indeed encrypt their messages, and studied their method of encryption.</p>



<p>Their messages consist of lowercase latin letters only, and every word is encrypted separately as follows:</p>



<p>Convert every letter to its&nbsp;<a href="http://asciitable.com/" target="_blank" rel="noreferrer noopener">ASCII value</a>. Add&nbsp;<code>1</code>&nbsp;to the first letter, and then for every letter from the second one to the last one, add the value of the previous letter. Subtract&nbsp;<code>26</code>&nbsp;from every letter until it is in the range of lowercase letters&nbsp;<code>a-z</code>&nbsp;in ASCII. Convert the values back to letters.</p>



<p>For instance, to encrypt the word&nbsp;<code>“crime”</code></p>



<figure class="wp-block-table"><table><thead><tr><th><strong>Decrypted message:</strong></th><th><strong>c</strong></th><th><strong>r</strong></th><th><strong>i</strong></th><th><strong>m</strong></th><th><strong>e</strong></th></tr></thead><tbody><tr><td><strong>Step 1:</strong></td><td>99</td><td>114</td><td>105</td><td>109</td><td>101</td></tr><tr><td><strong>Step 2:</strong></td><td>100</td><td>214</td><td>319</td><td>428</td><td>529</td></tr><tr><td><strong>Step 3:</strong></td><td>100</td><td>110</td><td>111</td><td>116</td><td>113</td></tr><tr><td><strong>Encrypted message:</strong></td><td><strong>d</strong></td><td><strong>n</strong></td><td><strong>o</strong></td><td><strong>t</strong></td><td><strong>q</strong></td></tr></tbody></table></figure>



<p>The FBI needs an efficient method to decrypt messages. Write a function named&nbsp;<code>decrypt(word)</code>&nbsp;that receives a string that consists of small latin letters only, and returns the decrypted word.</p>



<p>Explain your solution and analyze its time and space complexities.</p>



<p><strong>Examples:</strong></p>



<pre class="wp-block-preformatted">input:  word = "dnotq"
output: "crime"

input:  word = "flgxswdliefy"
output: "encyclopedia"
</pre>



<p>Since the function should be used on messages with many words, make sure the function is as efficient as possible in both time and space. Explain the correctness of your function, and analyze its asymptotic runtime and space complexity.</p>



<p><strong>Note:</strong>&nbsp;Most programing languages have built-in methods of converting letters to ASCII values and vica versa. You may search the internet for the appropriate method.</p>



<p><strong>Constraints:</strong></p>



<ul><li><strong>[time limit] 5000ms</strong></li><li><strong>[input] string</strong>&nbsp;<code>word</code><ul><li>The ASCII value of every char is in the range of lowercase letters&nbsp;<code>a-z</code>.</li></ul></li><li><strong>[output] string</strong></li></ul>



<h3>Solution</h3>



<pre class="wp-block-code"><code>import Foundation

func decrypt(word: String) -> String {
    var ascii = word.map { Int($0.asciiValue!) }
    
    let count = ascii.count
    
    var prev = ascii&#91;0]
    for i in 1..&lt;count {
        let temp = ascii&#91;i]
        ascii&#91;i] = ascii&#91;i] - prev
        prev = temp
    }
    
    ascii&#91;0] -= 1
    
    for i in 0..&lt;count {
        while ascii&#91;i] &lt; 96 {
            ascii&#91;i] += 26
        }
    }
    
    return String(ascii.map {
        Character(UnicodeScalar(UInt8($0)))
    })
}</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/decoding-a-secret-message/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Indexing Strings in Swift</title>
		<link>https://ingax.com/swift-string-index-extension-for-interviews/</link>
					<comments>https://ingax.com/swift-string-index-extension-for-interviews/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Sat, 31 Oct 2020 18:45:27 +0000</pubDate>
				<category><![CDATA[Interviews]]></category>
		<category><![CDATA[Extension]]></category>
		<category><![CDATA[Interview]]></category>
		<category><![CDATA[Strings]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6817</guid>

					<description><![CDATA[Manipulating strings comes up a lot in interview problems. Unfortunately, indexing strings in Swift isn&#8217;t so simple. Strings in Swift can be indexed using the...]]></description>
										<content:encoded><![CDATA[
<p>Manipulating strings comes up a lot in interview problems. Unfortunately, indexing strings in Swift isn&#8217;t so simple. Strings in Swift can be indexed using the <code>String.Index</code> type, but I would much prefer to use an <code>Int</code>.</p>



<p>I&#8217;ve come up with a couple solutions that will allow you to index strings with an <code>Int</code>. This code will not work in special cases, such as when the string contains special accents or emojis. This has to do with <a href="https://developer.apple.com/documentation/swift/string">the way Swift treats strings inherently</a>.</p>



<h3>Currently, my favorite solution is to map the string to an array. </h3>



<p>The upside is that it is simple and can be done quickly in an interview. The downside is the additional space required to create the array.</p>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">// String
let s = "ingax"

// String mapped to Array
let a = s.map { String($0) }</code></pre>



<h3>Another solution is to write a simple extension. </h3>



<p>The downside of this solution is the time complexity. Each time we call a particular index with this method, we run through a loop. So if we could very easily write a program with a double loop.</p>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">extension String {
    subscript(_ i: Int) -> String {
        return String(self[index(startIndex, offsetBy: i)])
    }
}</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/swift-string-index-extension-for-interviews/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Valid Parentheses</title>
		<link>https://ingax.com/valid-parentheses-leetcode-problem-20/</link>
					<comments>https://ingax.com/valid-parentheses-leetcode-problem-20/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Thu, 16 Jan 2020 00:57:42 +0000</pubDate>
				<category><![CDATA[Programming Problems]]></category>
		<category><![CDATA[Easy]]></category>
		<category><![CDATA[LeetCode]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6798</guid>

					<description><![CDATA[LeetCode Problem #20 Given a string containing just the characters&#160;'(',&#160;')',&#160;'{',&#160;'}',&#160;'['&#160;and&#160;']', determine if the input string is valid. An input string is valid if: Open brackets...]]></description>
										<content:encoded><![CDATA[
<h3>LeetCode Problem #20</h3>



<p>Given a string containing just the characters&nbsp;<code>'('</code>,&nbsp;<code>')'</code>,&nbsp;<code>'{'</code>,&nbsp;<code>'}'</code>,&nbsp;<code>'['</code>&nbsp;and&nbsp;<code>']'</code>, determine if the input string is valid.</p>



<p>An input string is valid if:</p>



<ol><li>Open brackets must be closed by the same type of brackets.</li><li>Open brackets must be closed in the correct order.</li></ol>



<p>Note that an empty string is&nbsp;also considered valid.</p>



<p><strong>Constraints</strong></p>



<ul><li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li><li><code>s</code>&nbsp;consists of parentheses only&nbsp;<code>'()[]{}'</code>.</li></ul>



<h3>Solution</h3>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">func isValid(_ s: String) -> Bool {
    var stack = [Character]()
    let pairs: [Character : Character] = ["(" : ")", "[" : "]", "{" : "}"]
    
    for char in s {
        switch char {
        case "(", "[", "{":
            stack.append(char)
        default:
            if !stack.isEmpty, char == pairs[stack.last!]! {
                stack.removeLast()
            } else {
                return false
            }
        }
    }
    return stack.isEmpty
}</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/valid-parentheses-leetcode-problem-20/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Reverse a Linked List</title>
		<link>https://ingax.com/reverse-a-linked-list/</link>
					<comments>https://ingax.com/reverse-a-linked-list/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Tue, 17 Dec 2019 19:18:59 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6764</guid>

					<description><![CDATA[Resources https://www.geeksforgeeks.org/reverse-a-linked-list/]]></description>
										<content:encoded><![CDATA[
<pre class="wp-block-prismatic-blocks"><code class="language-swift">public class ListNode {
  public var val: Int
  public var next: ListNode?
  public init(_ val: Int) {
    self.val = val
    self.next = nil
  }
}

func reverseList(_ head: ListNode?) -> ListNode? {
  var curr = head
  var prev: ListNode?
  var next: ListNode?
  
  while curr != nil {
    next = curr?.next
    curr?.next = prev
    prev = curr
    curr = next
  }
  
  return prev
}</code></pre>



<h3>Resources</h3>



<ul><li><a href="https://www.geeksforgeeks.org/reverse-a-linked-list/">https://www.geeksforgeeks.org/reverse-a-linked-list/</a></li></ul>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/reverse-a-linked-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Return the nth Fibonacci Number (Iterative)</title>
		<link>https://ingax.com/return-the-nth-fibonacci-number-iterative/</link>
					<comments>https://ingax.com/return-the-nth-fibonacci-number-iterative/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Tue, 17 Dec 2019 00:06:43 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6750</guid>

					<description><![CDATA[Aside from using an equation to calculate the nth Fibonacci number, the following iterative method has the best time and space complexity. Time complexity is...]]></description>
										<content:encoded><![CDATA[
<p>Aside from using an <a href="http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html#section1" target="_blank" rel="noreferrer noopener" aria-label="equation to calculate the nth Fibonacci number (opens in a new tab)">equation to calculate the nth Fibonacci number</a>, the following iterative method has the best time and space complexity.</p>



<p>Time complexity is \(O(n)\) and space complexity is \(O(1)\). This method saves on space, since we only need to store the previous two Fibonacci numbers.</p>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">func fib(_ n: Int) -> Int? {
  if n < 1 { return nil }
  if n < 3 { return 1 }
  
  var i = 1
  var ii = 1
  var an = 0
  
  for _ in 3...n {
    an = i + ii
    ii = i
    i = an
  }
  
  return an
}</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/return-the-nth-fibonacci-number-iterative/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/

Object Caching 8/144 objects using disk
Page Caching using disk: enhanced 
Database Caching using disk

Served from: ingax.com @ 2026-11-21 12:39:46 by W3 Total Cache
-->