<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohammed Hussien on Medium]]></title>
        <description><![CDATA[Stories by Mohammed Hussien on Medium]]></description>
        <link>https://medium.com/@mohammedhussien10101010?source=rss-1d3d9451b665------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TeowUpEcuNd_8zVOuAM_hw.jpeg</url>
            <title>Stories by Mohammed Hussien on Medium</title>
            <link>https://medium.com/@mohammedhussien10101010?source=rss-1d3d9451b665------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 04:44:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohammedhussien10101010/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding Arrays in Swift: A Complete Guide to Time and Space Complexity]]></title>
            <link>https://blog.stackademic.com/understanding-arrays-in-swift-a-complete-guide-to-time-and-space-complexity-33cdc0910165?source=rss-1d3d9451b665------2</link>
            <guid isPermaLink="false">https://medium.com/p/33cdc0910165</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Mohammed Hussien]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 07:11:17 GMT</pubDate>
            <atom:updated>2026-04-09T07:54:00.537Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FGKy5klRIsqm8qYREeyJAQ.png" /></figure><h4>Before we dive into arrays, let’s quickly talk about an important concept:</h4><p><em>The </em><strong><em>Swift Standard Library</em></strong><em> is the </em><strong><em>core library of Swift</em></strong><em>.</em></p><p>It contains the basic tools and data structures that every Swift program uses, such as:<em> (Array,Set,Dictionary,String,etc…)</em></p><p><em>It’s like a toolbox that Swift gives you before you write any code.</em></p><h4><strong><em>Definition of Array:</em></strong></h4><p><em>An </em><strong><em>Array</em></strong><em> is: An ordered collection of elements.</em></p><p><em>Ordered here means That You can access elements using the </em><strong><em>index</em></strong><em>.</em></p><p><em>note:Array index </em><strong><em>starts from 0</em></strong></p><p>Example<em>:</em></p><pre>let persons = [&quot;Sam&quot;, &quot;Elon&quot;, &quot;Bill&quot;]<br>persons[0] // Sam<br>persons[1] // Elon<br>persons[2] // Bill</pre><h4><strong><em>Generic Collection:</em></strong></h4><p><em>Swift arrays are </em><strong><em>generic</em></strong><em> Which means They can store </em><strong><em>any type</em></strong><em>.</em></p><p>Example<em>:</em></p><pre>let numbers = [1,2,3]<br>let names = [&quot;Ali&quot;,&quot;Omar&quot;]<br>let prices = [10.5, 20.7]</pre><p><em>Or</em></p><pre>let numbers: Array&lt;Int&gt; = [1, 2, 3]<br>let names: Array&lt;String&gt; = [&quot;Ali&quot;, &quot;Omar&quot;]<br>let prices: Array&lt;Double&gt; = [10.5, 20.7]</pre><p><em>Or</em></p><pre>struct Person {<br>    let name: String<br>}<br><br>let people: Array&lt;Person&gt; = [<br>    Person(name: &quot;Ali&quot;),<br>    Person(name: &quot;Omar&quot;)<br>]</pre><h3>Protocols of Array</h3><p>Swift builds arrays using <strong>protocols </strong>Like<strong> </strong>Sequence, Collection, RandomAccessCollection</p><h3>1-Sequence</h3><p>This means you can iterate over its elements.</p><pre>for name in people {<br>    print(name)<br>}</pre><h3>2-Collection</h3><p>This means You can:</p><ul><li>access by index</li></ul><pre>people[0]<br>people[1]<br>people[2]</pre><ul><li>Count</li></ul><pre>people.count // 3</pre><ul><li>traverse multiple times</li></ul><pre>for person in people {<br>    print(person)<br>}<br><br>for person in people {<br>    print(person.uppercased())<br>}</pre><h3>3-RandomAccessCollection</h3><p>It allows you to access any element in constant time.</p><pre>people[2]</pre><p><strong>Note: Constant time means the time taken by an operation doesn’t change as the amount of data increases In Big O notation, this is represented as O(1).</strong></p><p>This means that even if the array has:</p><pre>10 elements <br>or<br>1,000 elements<br>or<br>1,000,000 elements</pre><p>Access time is still:</p><pre>O(1) → Time Complexity</pre><h3>Array Performance</h3><h3>■ <strong>Time Complexity</strong></h3><p>How the running time of an algorithm grows as the size of the input increases.</p><h4><strong>1-Access by Index → O(1)</strong></h4><p>How Array Access Works Internally ?</p><ul><li>for Example</li></ul><pre>let numbers = [10, 20, 30, 40]<br>print(numbers[2]) //30</pre><pre>Assume:<br><br>Index   Value   Address<br>0       10      1000<br>1       20      1004<br>2       30      1008<br>3       40      1012<br><br>Base address = 1000<br>Each element size = 4 bytes<br>Address = base address + (index × element size)<br><br><br>so:<br><br>Address = 1000 + (2 × 4)<br>Address = 1008 //30</pre><h4>Why This is O(1)?</h4><h4>The Reason is:</h4><ul><li>Does not loop through elements</li><li>Does not check one by one</li><li>Just calculates the address and jumps directly</li></ul><h4>2-Append → O(1) Best case / O(n) Worst case</h4><h4>O(1) Best case</h4><pre>var numbers = [1, 2, 3]<br>numbers.append(4) // [1,2,3,4]</pre><h4>O(n) Worst case</h4><pre>// When capacity is full<br>numbers.append(5)</pre><h4>The Reason is:</h4><p>Appending is usually <strong>O(1)</strong>, but when the array runs out of capacity, Swift must:</p><ul><li>Allocate a new larger memory block</li><li>Copy all elements</li></ul><p>Let me explain here:</p><pre>var numbers = [1, 2, 3]<br><br>print(numbers.count)     // 3<br>print(numbers.capacity) // 3 or greater (capacity may be larger than count)<br>/* if count == capacity <br>then make new resize from 3 to 6<br>(so everytime append element to array...double it)<br>*/<br>numbers.append(4) // [1, 2, 3, 4]<br>print(numbers.capacity)  // 6<br><br>// so Appending in this case O(n)</pre><ul><li>If you want to pre-allocate capacity for an array from the beginning, you can use <strong>reserveCapacity( )</strong></li></ul><pre>var numbers: [Int] = []<br>numbers.reserveCapacity(100)<br><br>for i in 0..&lt;100 {<br>    numbers.append(i) // So appending in this case becomes O(1)<br>}</pre><h4>3. Insert (Beginning / Middle) — O(n)</h4><pre>var numbers = [10, 20, 30, 40]<br>numbers.insert(5, at: 0)</pre><h4>Reason:</h4><p>All existing elements must be <strong>shifted one position to the right</strong> to make space for the new element so will be O(n).</p><h4>4. Remove (Beginning / Middle) — O(n)</h4><pre>var numbers = [10, 20, 30, 40]<br>numbers.remove(at: 1)</pre><h4>Reason:</h4><p>After removing an element, all subsequent elements must be <strong>shifted left</strong> to fill the gap so will be O(n).</p><h4>5. Remove from End — O(1)</h4><pre>var numbers = [10, 20, 30]<br>numbers.removeLast()</pre><h4>Reason:</h4><p>No shifting is needed because the last element is simply removed so will be O(1).</p><h4>6. Search (contains) — O(n)</h4><pre>let numbers = [10, 20, 30, 40]<br>numbers.contains(100)</pre><h4>Reason:</h4><p>The array performs a <strong>linear search</strong>, checking elements one by one until:</p><ul><li>The element is found</li><li>Or the array ends</li></ul><p>In the worst case, all elements must be checked → <strong>O(n)</strong>.</p><h4>7. Iteration — O(n)</h4><pre>let numbers = [10, 20, 30, 40]</pre><pre>for number in numbers {<br>    print(number)<br>}</pre><h4>Reason:</h4><p>Iteration visits <strong>every element exactly once</strong>, so the time grows linearly with the size of the array.</p><h3>Test Yourself:</h3><p>What is the time complexity (Big O) of the following code? <br>Is it O(1) or O(n)? Why?</p><pre>let numbers = [10, 20, 30, 40]<br>numbers.contains(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*JFGeIpCXGBWv7h4J1jZjMA.png" /></figure><h4>Answer:</h4><p>Your thinking is correct this is O(1) in this specific case(best case) because the element is found at the first position. However, in general, Array.contains is O(n) due to the worst-case scenario.</p><h3><strong>Summary</strong></h3><pre>Operation                Time Complexity<br>---------------------------------------<br>Access by index          O(1)<br>Append                   O(1) amortized / O(n)<br>Insert                   O(n)<br>Remove                   O(n)<br>Search (contains)        O(n)<br>Iteration                O(n)</pre><h3>■ Space Complexity</h3><p>How much memory an algorithm uses as the input size increases.</p><h4><strong>1-Constant Space O(1)</strong></h4><ul><li>for Example</li></ul><pre>func sumFromOne(upto n: Int) -&gt; Int {<br>    return (n + 1) * n / 2<br>}</pre><h3>Why O(1)?</h3><ul><li>Uses only a few variables</li><li>No arrays, no extra storage</li><li>The input size (n) does not affect memory usage.</li></ul><h4><strong>Another Example in Constant Space O(1):</strong></h4><pre>func printSorted(_ array: [Int]) {<br>    guard !array.isEmpty else { return }<br><br>    var currentCount = 0<br>    var minValue = Int.min<br><br>    for value in array {<br>        if value == minValue {<br>            print(value)<br>            currentCount += 1<br>        }<br>    }<br><br>    while currentCount &lt; array.count {<br>        var currentValue = array.max()!<br><br>        for value in array {<br>            if value &lt; currentValue &amp;&amp; value &gt; minValue {<br>                currentValue = value<br>            }<br>        }<br><br>        for value in array {<br>            if value == currentValue {<br>                print(value)<br>                currentCount += 1<br>            }<br>        }<br><br>        minValue = currentValue<br>    }<br>}</pre><h3>Why is this O(1) even though it looks complex?</h3><p>This algorithm only uses <strong>constant variables :</strong></p><pre>currentCount<br>minValue<br>currentValue</pre><ul><li>No new arrays created.</li></ul><h4>2-Linear Space O(n)</h4><pre>func printSorted(_ array: [Int]) {<br>    let sorted = array.sorted()<br>    <br>    for element in sorted {<br>        print(element)<br>    }<br>}</pre><h3>Why O(n)?</h3><ul><li>array.sorted() creates a <strong>new array </strong>in memory</li><li>Same size as input</li></ul><p>// Note: Using sort() modifies the original array and avoids creating a new array, which helps reduce space complexity.</p><h4>Keep in mind:</h4><ul><li>Want faster code → use more memory</li><li>Want less memory → sacrifice speed</li></ul><p>There is no perfect solution — it depends on your system and requirements.</p><h3>Test Yourself:</h3><p>What is the space complexity of the following code?</p><pre>func example(_ array: [Int]) {<br> var temp = [Int]()<br> <br> for element in array {<br> temp.append(element)<br> }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*JFGeIpCXGBWv7h4J1jZjMA.png" /></figure><h4>Answer:</h4><p>O(n), because a new array is created with the same size as the input.</p><h3>Summary</h3><p>Space complexity is not about how complex the code looks, but about how much additional memory it uses.</p><h4>So How to determine space complexity?</h4><pre>1. Ignore the input itself.<br>2. Focus on additional memory allocation:<br> - New arrays<br> - Dictionaries / Sets<br> - Recursion stack<br>3. If memory usage grows with the input size → O(n)<br>4. If memory usage remains constant → O(1)</pre><h4><strong>Resources:</strong></h4><p>Book: Data Structures &amp; Algorithms in Swift by<strong> </strong>Kelvin Lau &amp; Vincent Ngo</p><h4><strong>Contact me:</strong></h4><p><a href="https://www.linkedin.com/in/mohammed-hussein-14123b2a0/"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33cdc0910165" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/understanding-arrays-in-swift-a-complete-guide-to-time-and-space-complexity-33cdc0910165">Understanding Arrays in Swift: A Complete Guide to Time and Space Complexity</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>