<?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 Kitana Toft on Medium]]></title>
        <description><![CDATA[Stories by Kitana Toft on Medium]]></description>
        <link>https://medium.com/@kitanatoft?source=rss-26467efcf386------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*hEHB7TV0GCpAD9ey</url>
            <title>Stories by Kitana Toft on Medium</title>
            <link>https://medium.com/@kitanatoft?source=rss-26467efcf386------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:24:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kitanatoft/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[AI Agents]]></title>
            <link>https://medium.com/@kitanatoft/ai-agents-4850de3a6d0c?source=rss-26467efcf386------2</link>
            <guid isPermaLink="false">https://medium.com/p/4850de3a6d0c</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Kitana Toft]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 16:50:54 GMT</pubDate>
            <atom:updated>2026-08-05T16:50:54.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*57QoBLYUj6RmzcEjAqdmWw@2x.jpeg" /></figure><p>An agent isn’t a smarter model. It’s a model that controls its own control flow.</p><p>That’s the whole distinction, and everything else follows from it:</p><p>Tools — the agent chooses which one to call. A pipeline that always calls the same function in the same order isn’t using tools, it’s just a program.</p><p>Memory — context carries across steps, so each iteration doesn’t re-derive what the last one already figured out.</p><p>Reactivity — it responds to what actually came back. The empty result set, the failed call, the rate limit — not the plan it made before it had information.</p><p>Delegation — recognizing a subtask belongs to someone else. Knowing when to escalate is a capability, not a failure.</p><p>Human control vs. autonomous action — full autonomy is fast and occasionally catastrophic. Full review is safe and defeats the purpose. Where you land between them should be a decision, not an accident.</p><p>None of this requires a bigger model. It requires giving the model a loop and permission to use it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4850de3a6d0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Trees Explained]]></title>
            <link>https://medium.com/@kitanatoft/binary-trees-explained-a39113f06bd5?source=rss-26467efcf386------2</link>
            <guid isPermaLink="false">https://medium.com/p/a39113f06bd5</guid>
            <category><![CDATA[binary-tree]]></category>
            <dc:creator><![CDATA[Kitana Toft]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 23:25:35 GMT</pubDate>
            <atom:updated>2023-06-03T06:17:07.531Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we will review <strong>Binary Trees</strong>. Binary Trees are composed of nodes which have at most two pointers, which are referred to as the left child and right child. Unlike ListNodes (nodes for <a href="https://medium.com/@kitanatoft/linked-list-explained-ee6fd9c4f418">Linked Lists</a>), TreeNodes point downwards rather than side by side.</p><h3>Introduction</h3><p>A <strong>binary tree</strong> is a tree-like data structure composed of nodes (often referred to as TreeNode), where each node can have at most two child nodes referred to as the left child and the right child. The <strong>binary tree</strong> consists of a hierarchical arrangement of nodes, starting from the root node at the top and branching downwards.</p><h3>Overview</h3><p>Let’s review some important terminology associated with <strong>binary trees</strong> and other sorts of <strong>trees</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*QHy2ZiL2DM8qQakMUqgisQ.png" /></figure><ul><li>TreeNode or Node: an entity that contains a value and pointers to its child nodes.</li></ul><pre>def tree_node(self, val):<br>  self.data = data<br>  self.left = None<br>  self.right = None</pre><ul><li>Root: the topmost node in the tree</li><li>Leaf or External Node: the last node in the tree that has pointers referencing null (i.e., they have no children or sub-nodes).</li><li>Parent or Ancestor: each node, aside from the root node, that has at least one sub-node.</li><li>Child or Descendant: a node that directly comes from a parent node moving away from the root.</li><li>Edge: the link between any two nodes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*280LY2Dh8NhYX1QE14adXw.png" /></figure><p>A tree data structure is a widely used abstract data structure that represents a hierarchical structure with a set of connected nodes. In a binary tree there are each node is connected to exactly one parent, the topmost node in the structure is the root node. Each node can have at most two children, a left child and a right child. Leafs are nodes that point to null.</p><p>A tree is an undirected and connected acyclic graph that does NOT have loops or cycles. Unlike a <strong>Linked List</strong> data structure that is able to have cycles. Meaning that nodes that are descendants of an ancestor cannot have a child that refers back to an ancestor node.</p><h3>Traversals</h3><p>Given the image from above, let’s traverse the binary tree in three different wats</p><p><strong>In-order traversal</strong>: Left → Root → Right</p><ul><li>Result: 1, 3, 2, 4, 7</li></ul><p><strong>Pre-order traversal</strong>: Root → Left → Right</p><ul><li>Result: 4, 3, 1, 2, 7</li></ul><p><strong>Post-order traversal</strong>: Left → Right → Root</p><ul><li>Result: 1,2,3,7,4</li></ul><p>Note that an <strong>in-order</strong> traversal of a <strong>binary tree</strong> has the properties of a <strong>Binary Search Tree</strong> (or BST), more on that in a later article.</p><h3>Time complexity</h3><p>Operation: Big-O</p><ul><li><strong>Access</strong>: O(log(n))</li><li><strong>Search</strong>: O(log(n))</li><li><strong>Insert</strong>: O(log(n))</li><li><strong>Remove</strong>: O(log(n))</li></ul><h3>Space complexity</h3><ul><li>O(1)</li></ul><h3>Edge Cases</h3><ul><li>empty tree</li><li>single node</li><li>two nodes</li><li>very skewed tree (similar to a linked list)</li></ul><h3>Common Techniques</h3><ul><li>It is common to use recursion when traversing trees.</li><li>If using recursion, remember that to check for a null base case</li><li>If traversing by level, use Breadth First Search</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a39113f06bd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linked List Explained]]></title>
            <link>https://medium.com/@kitanatoft/linked-list-explained-ee6fd9c4f418?source=rss-26467efcf386------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee6fd9c4f418</guid>
            <category><![CDATA[linked-list-cycle]]></category>
            <dc:creator><![CDATA[Kitana Toft]]></dc:creator>
            <pubDate>Wed, 24 May 2023 01:56:42 GMT</pubDate>
            <atom:updated>2023-06-03T03:57:33.593Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello there! I’d like to take a moment to introduce you to one of the fundamental data structures in computer science: the <strong>linked list</strong>. In this article, we will explore what a linked list is, discuss scenarios where it is commonly used, analyze its time and space complexity, and present its pros and cons.</p><h3>Overview</h3><p>A <strong>linked list</strong> is a linear data structure consisting of <strong>nodes</strong>, where each node contains <strong>data</strong> and a <strong>reference</strong> (or <strong>pointer</strong>) to the next node in the sequence. Unlike arrays, which use contiguous memory, <em>linked lists use dynamic memory allocation</em>. This allows for efficient memory utilization and provides flexibility in adding, removing, or modifying elements within the list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hhddaGQytUNqz0Y0A8m8Q.png" /><figcaption>Fig. Singly Linked List</figcaption></figure><blockquote><em>To put it more simply, a </em><strong><em>Linked List</em></strong><em> is a </em><strong>linear data structure</strong><em>, where elements are stored at non-contiguous locations. A </em><strong><em>Linked List</em></strong><em> is like a chain made of </em><strong><em>nodes</em></strong><em> and the links are pointers.</em></blockquote><p><strong>Pointers</strong> are connections that hold the pieces of linked structures together.<br>Pointers represent the addresses of a location in memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hB9yJkTZvmeZGtVq2eDkKg.png" /><figcaption>Fig. Pointer</figcaption></figure><p>A <strong>node</strong> is a fundamental building block that stores both <em>data</em> and a reference (or pointer) to the next node in the sequence. Each node can be thought of as a container that holds a piece of information or data.</p><p>Depending on the type of linked list, nodes can have <strong>both</strong> a nextand previouspointer allowing list <strong>bi-directional traversal</strong> or <strong>only</strong> have a nextpointer which allows <strong>uni-directional traversing</strong> (i.e., you can only go forward, rather than both forwards and backwards).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*6OXm7gVNAXBT_Oo60UYRlQ.png" /><figcaption>Fig. Verious Pointers on a Node</figcaption></figure><h3>Let’s break down the components of a node:</h3><ul><li><strong>Data</strong>: The data component of a node represents the actual information that the node is intended to store. It can be any type of data, such as integers, strings, objects, or even complex data structures.</li><li><strong>Next Pointer</strong>: The next pointer is a reference or address that points to the next node in the linked list. It establishes the connection between nodes and enables traversal from one node to another. In a singly linked list, the next pointer points to the succeeding node, while in a doubly linked list, there can be additional pointers for the previous node as well.</li></ul><p>In Python, the node class is defined as such:</p><pre>class Node:<br>  def __init__(self, data):<br>    self.data = data<br>    self.next - None</pre><p>In this example, the Node class has two attributes: data to store the actual data and next to hold the reference to the next node. The next attribute is initialized to None as the node is not initially connected to any other node.</p><p>To create a linked list, multiple nodes are linked together by updating the next pointer of each node to point to the next node in the sequence. The last node in the list typically has its next pointer set to None to indicate the end of the list.</p><p>Nodes serve as the building blocks of linked lists, allowing for efficient traversal, insertion, and deletion operations within the list. They encapsulate both data and the connectivity information necessary to form a linked structure.</p><h3>There are many different types of linked lists</h3><ul><li><strong>Singly Linked List</strong>: consists of a list of nodes, each with next pointers, allowing <strong>uni-directional travel</strong></li><li><strong>Doubly Linked List</strong>: <em>each node has two pointers</em>, this allows you to <strong>traverse bi-directionally</strong>, backwards and forwards, rather uni-directionally for a linked list</li><li><strong>Circularly Linked List</strong>: the <strong>tail node points to the head node</strong>, can be either singly linked or doubly linked</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mAj6AQFD-wOci8HRGNX3Ng.png" /><figcaption>Fig. Linked Lists</figcaption></figure><h3>Why use a Linked List?</h3><ul><li><strong>Linked Lists</strong> can be used to implement other common <strong>abstract data types</strong>, including <strong>lists</strong>, <strong>stacks</strong>, &amp; <strong>queues</strong>.</li><li>Preferred data structures over arrays because elements can be easily inserted or removed without reallocation or reorganization of the entire structure</li></ul><h3>Advantages</h3><ul><li>Dynamic Size (there is no need to ever resize a linked list)</li><li>Quick insertion / deletion of nodes because you can change the pointers for each node</li></ul><h3>Disadvantages</h3><ul><li>Very slow when it comes to access and search; we have to sequentially iterate over each element starting at the head. Unlike an array, you don&#39;t have the option of random access.</li><li>Extra space for the pointer</li><li>More memory is required than compared to an <strong>array</strong> or <strong>list</strong> data structure due to the fact that <strong>linked lists</strong> require <strong>pointers</strong></li></ul><h3>Big-O Analysis</h3><p>The <strong>time</strong> and <strong>space complexity</strong> for a <strong>linked list</strong> with n elements are as follows:</p><h4>Time Complexity</h4><ul><li><strong>Accessing an element</strong>: O(n) - In a <strong>singly linked list</strong>, accessing an element requires traversing the list from the head node to the desired position, which takes <em>linear time proportional to the number of elements </em><em>n</em>.</li><li><strong>Insertion/Deletion at the beginning</strong>: O(1) - Inserting or deleting a node at the beginning of a linked list can be done in <em>constant time as it involves updating the </em><em>head pointer</em>.<br>Insertion/Deletion at the end: O(n)<br>Inserting or deleting a node at the end of a linked list requires traversing the entire list, which takes linear time.</li><li><strong>Insertion/Deletion at a specific position</strong>: O(n)- Inserting or deleting a node at a <em>specific position</em> in the linked list requires traversing the list to reach that position, which takes <strong>linear time</strong>.</li><li><strong>Searching for an element</strong>: O(n) - Searching for an element in a linked list requires traversing the list until the element is found or the end of the list is reached, resulting in a time complexity of O(n).</li></ul><h4>Space Complexity</h4><p>The space complexity of a linked list is O(n) as it requires memory to store n nodes. Each node contains data and a reference to the next node, which contributes to the overall space complexity linearly with the number of elements.</p><p>It’s important to note that these time and space complexities are general for a standard singly linked list implementation. However, specific optimizations or additional data structures within the linked list implementation might affect the complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XTJKB3i6nbw__35KcL5VRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*eDRWfab60l7trIFmP4WuiQ.png" /><figcaption>Fig. <strong>Big-O Visualized</strong>: Lines made with the very excellent <strong>Desmos</strong> graph calculator. You can <a href="https://www.desmos.com/calculator/xpfyjl1lbn">play with this graph here</a>.</figcaption></figure><h3>Linked List Code Implementation</h3><pre>class Node:<br>  # Node constructor for a Singly Linked List<br>    def __init__(self, data=None):<br>        self.data = data<br>        self.next = None<br><br>class LinkedList:<br>    # SLL constructor<br>    def __init__(self):<br>        self.head = None<br><br>    # Insert new node into list<br>    def insert_node(self, data):<br>       # Create a new node from given data<br>        new_node = Node(data)<br>         # Check if the list is empty<br>        if self.head is None:<br>          # If so, set the new node to be the head<br>            self.head = new_node<br>        else:<br>           # Otherwise, start at the head of the list<br>            current = self.head<br>            while current.next is not None:<br>                # update the current node to point to the next node<br>                current = current.next<br>             # update the next node to be the current node<br>            current.next = new_node<br><br>    # delete a node from the list<br>    def delete_node(self, data):<br>        # Check if the list is empty first to avoid bugs<br>        if self.head is None:<br>            return<br>        # Check if the node we are looking for is at the head<br>        if self.head.data == data:<br>            # if so, remove it by assigning it to the next value<br>            self.head = self.head.next<br>            return<br>        current = self.head<br><br>        # Loop to the end of the list<br>        while current.next is not None:<br>            # start searching for the matching node<br>            if current.next.data == data:<br>                # when a match is found, update the pointers to skip over it<br>                current.next = current.next.next<br>                return<br>            # clean up<br>            current = current.next<br><br>    # search for a node in the list<br>    def search_list(self, data):<br>        # Start at the head of the list<br>        current = self.head<br>        # Loop to the end of the list<br>        while current is not None:<br>          # start searching for the matching node<br>            if current.data == data:<br>                # match found<br>                return True<br>            current = current.next<br>        # match NOT found<br>        return False<br><br>    # access a given node out of the list<br>    def access_node(self, index):<br>        # Start at the head of the list with a count size of zero<br>        current = self.head<br>        count = 0<br>        # Loop to the end of the list<br>        while current is not None:<br>            # check if we find a match<br>            if count == index:<br>                return current.data<br>            # update the count and move onto the next node<br>            count += 1<br>            current = current.next<br>        return None<br><br>    # display the values in the list<br>    def display(self):<br>      # Create a new node from given data<br>        current = self.head<br>        # Loop to the end of the list<br>        while current is not None:<br>            # print every value with a space<br>            print(current.data, end=&quot; &quot;)<br>            current = current.next<br>        print()<br><br># Example usage:<br>my_list = LinkedList()<br>my_list.insert_node(5)<br>my_list.insert_node(10)<br>my_list.insert_node(15)<br>my_list.insert_node(20)<br>my_list.display()  # Output: 5 10 15 20<br><br>print(my_list.search_list(15))  # Output: True<br>print(my_list.search_list(25))  # Output: False<br><br>print(my_list.access_node(2))  # Output: 15<br>print(my_list.access_node(5))  # Output: None<br><br>my_list.delete_node(10)<br>my_list.display()  # Output: 5 15 20</pre><h3>Let’s run through an example</h3><p>Let’s go over a problem together to better understand <strong>linked Lists</strong>. Today we will attempt LeetCode problem 206 <a href="https://leetcode.com/problems/reverse-linked-list">Reverse Linked List</a>. In this problem, we are given the head of a <strong>singly linked list</strong> and are asked to return the list in reversed order.</p><p>For example, we are given a linked list with the input value of head = [1, 2, 3, 4, 5]. The desired output should be [5, 4, 3, 2, 1].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*NZ7-uank4AEU9KW5XNL3pw.png" /></figure><blockquote><em>So, how do we achieve this?</em></blockquote><p>Let’s use the <a href="https://medium.com/@kitanatoft/two-pointer-algorithm-explained-52fee6a2438a">Two Pointer</a> technique. Note that because we are given a <strong>singly linked list</strong> we do NOT have previous pointers, thus we are unable to simply refer back to a previous node.</p><h3>Pseudocode</h3><p>To reverse a <strong>singly linked list</strong> using <strong>two pointers</strong>, you can use the following approach:</p><p>Initialize three pointers: previous to keep track of the previous node, current to keep track of the current node, and next_node to keep track of the next node.<br>Start with previous and current pointing to None and head (the first node of the list), respectively.<br>Iterate through the list using a loop until the current pointer becomes None:</p><ul><li>Update next_node to the next node of current.</li><li>Reverse the link of current by pointing it to the previous node.</li><li>Move previous and current one step forward by assigning current to previous and next_node to current.</li></ul><p>Finally, update the head pointer to previous, which will now be pointing to the new first node of the reversed list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*znNcg7OfB0NT3uz-SAZhHg.gif" /><figcaption>Fig. Example RLL</figcaption></figure><h3>Code Implementation</h3><pre># Using the two pointer technique<br>def reverseList(self, head):<br>        &quot;&quot;&quot;<br>        :type head: ListNode<br>        :rtype: ListNode<br>        &quot;&quot;&quot;<br>        # Initialize prev pointer as NULL<br>        prev = None<br>        # Initialize the cur pointer as the head<br>        cur = head<br>        # Run a loop util cur points to NULL<br>        while cur:<br>            # Initialize next pointer as the next pointer of cur<br>            next = cur.next<br>            # Now assign the prev pointer to cur’s next pointer<br>            cur.next = prev<br>            # Assign cur to prev, next to cur<br>            prev = cur<br>            cur = next<br>        # Return the prev pointer to get the reverse<br>        return prev</pre><h3>When to Use a Linked List</h3><p>A linked list is a good choice in the following situations:</p><ul><li><strong>Unknown number of items</strong>: If you don’t know how many items will be in the list, a linked list is convenient because it allows for easy addition of items.</li><li><strong>No need for random access</strong>: If you don’t need to access elements at specific indexes in the list, unlike with an array, a linked list can be used.</li><li><strong>Insertion in the middle</strong>: If you need to insert items in the middle of the list, a linked list is suitable for this task.</li><li><strong>Efficient insertion and deletion</strong>: If you require fast insertion and deletion operations without the need to shift other elements, a linked list performs these operations in constant time.</li></ul><h3>Test Yourself</h3><ul><li><a href="https://leetcode.com/problems/reverse-linked-list">Reverse Linked List</a></li><li><a href="https://leetcode.com/problems/reverse-linked-list/">Reverse a Linked List</a></li><li><a href="https://leetcode.com/problems/linked-list-cycle/">Detect Cycle in a Linked List</a></li><li><a href="https://leetcode.com/problems/merge-two-sorted-lists/">Merge Two Sorted Lists</a></li><li><a href="https://leetcode.com/problems/merge-k-sorted-lists/">Merge K Sorted Lists</a></li><li><a href="https://leetcode.com/problems/remove-nth-node-from-end-of-list/">Remove Nth Node From End Of List</a></li><li><a href="https://leetcode.com/problems/reorder-list/">Reorder List</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTQ31TP5j0o-hiCVo7WhpQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee6fd9c4f418" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Search Explained]]></title>
            <link>https://medium.com/@kitanatoft/binary-search-explained-a46ea6e2ae35?source=rss-26467efcf386------2</link>
            <guid isPermaLink="false">https://medium.com/p/a46ea6e2ae35</guid>
            <category><![CDATA[binary-search]]></category>
            <dc:creator><![CDATA[Kitana Toft]]></dc:creator>
            <pubDate>Sun, 21 May 2023 22:15:28 GMT</pubDate>
            <atom:updated>2023-12-05T19:22:39.235Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s learn about another sorting algorithm, <strong>Binary Search</strong>. Now, this sorting algorithm is actually something our brains use everyday. First, let’s review <strong>Linear Search</strong>. It is a simple algorithm for finding a specific item in an unsorted list by <strong>checking each element in the list one-by-one</strong>. Searching for a specific item in a list, one-by-one, takes much more time and computing power. NOTE: <strong>It can only work on data that is sorted, usually in increasing order</strong>.</p><h3>Overview</h3><p><strong>Binary Search</strong> is an efficient algorithm for finding a specific item in a <strong>sorted list</strong> by <strong>repeatedly dividing the search interval in half</strong>.</p><p>Imagine you’re playing a game where someone has hidden a letter of the alphabet in a list of letters, and you have to find it by guessing. The person who hid the letter tells you “hotter” or “colder” depending on whether you’re getting closer or farther away from the letter. If we use <strong>binary search</strong>, we can eliminate half of the wrong answers every iteration until we either reach our target or figure out that the value doesn’t exist in the given list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*hVdTKQiILiPnTNtNuxNIMA.png" /></figure><h3>Why should I use Binary Search?</h3><p>You should use <strong>binary search</strong> when you need to <strong>search for a specific item in a large and sorted list</strong> because it’s a <strong><em>highly efficient</em></strong> algorithm that can quickly locate the desired item by repeatedly dividing the search space in half. Compared to <strong>linear search</strong>, which checks every element in the list one by one, <strong>binary search</strong> can <strong>significantly reduce the number of comparisons needed to find the item</strong>, <strong><em>especially for larger lists</em></strong>. This makes <strong>binary search</strong> an ideal choice for performance-critical applications, where speed and efficiency are crucial.</p><h3>Big-O Analysis</h3><p>In this article, the concept of reducing the time utilized and number of comparisons when searching is a big deal. I’ve mentioned <em>linear time</em>, but I think it is actually very helpful visualize the various functions that represent <strong>time complexity</strong>.</p><h3>Time Complexity</h3><p><strong>Time complexity</strong> is a mathematical approximation. An algorithm’s <strong>time complexity</strong> approximates its worst case run time. Note that <strong>binary search</strong> has a <strong>linear</strong> or <strong>constant time complexity</strong>, which is denoted as O(log n). This value is illustrated in black below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*eDRWfab60l7trIFmP4WuiQ.png" /><figcaption><em>Lines made with the very excellent Desmos graph calculator. You can </em><a href="https://www.desmos.com/calculator/xpfyjl1lbn"><em>play with this graph here</em></a><em>. </em><a href="https://victoria.dev/blog/a-coffee-break-introduction-to-time-complexity-of-algorithms/#what-is-time-complexity-anyway"><em>Image credit</em></a><em>.</em></figcaption></figure><p>Let’s visualize this concept before diving into the details by playing a simple guessing game. Imagine you’re playing a game where someone has hidden a letter of the alphabet in a list of letters, and you have to find it by guessing. The person who hid the letter tells you “<em>hotter</em>” or “<em>colder</em>” depending on whether you’re getting closer or farther away from the letter.</p><p>Now, let’s say you have a sorted list of letters from “a&quot; to &quot;h,&quot; and you&#39;re looking for the letter &quot;f.&quot; You could start at the beginning of the list and search one letter at a time, but that would take a long time. Instead, you can use <strong>binary search</strong> to make it faster and more efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*xbrdS52sZ_no9oQ_Bl5fCA.png" /></figure><p>Here’s how it works: you start by looking at the middle letter in the list, which is “d.&quot; You compare it to your target letter, &quot;f.&quot; If &quot;d&quot; comes before &quot;f&quot; in the alphabet, you know the target letter must be in the second half of the list. So you discard the first half of the list and focus on the second half.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*8cOpAsrqBiD3XQuUcxQCHw.png" /></figure><p>Now, you repeat the process with the new, smaller list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*2zZqVgEnTHMmIkQXrADx4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*L9uo-P6OFDRdeLqvLGqZGQ.png" /></figure><p>You look at the middle letter, which is “f,&quot; and compare it to your target letter, also &quot;f.&quot; You&#39;ve found your target letter!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/110/1*J2LSWGWL-ur7gXAixSeYZA.png" /></figure><blockquote><em>You keep dividing the remaining list in half and comparing the middle letter to your target letter until you either find the letter “</em><em>f&quot; or </em><strong><em>determine that it&#39;s not in the list</em></strong><em>.</em></blockquote><p>This is an example of a “<strong>divide and conquer</strong>” algorithm because you divide the search space (the list) into smaller and smaller parts until you find what you’re looking for. And just like in the “hot and cold” game, each time you eliminate half of the remaining possibilities, you’re getting “<em>hotter</em>” and closer to your target.</p><p>So, <strong>binary search</strong> is a “<strong>divide and conquer</strong>” algorithm that uses the “<em>hot and cold</em>” reference to quickly find a specific item in a sorted list of items by repeatedly dividing the search interval in half.</p><h3>Let’s run through an example</h3><p>Let’s attempt Leetcode problem <a href="https://leetcode.com/problems/binary-search/">704. Binary Search</a>. In this problem, we are given a sorted array of integers nums which goes from smallest to largest number. We are asked to write an algorithm which searches for a targetand returns either the index the element resides at or -1 if no match is found.</p><p>We will use the first example:</p><p>nums = [-1,0,3,5,9,12], target = 9</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*BLufkKMAo6d8Vel7PL2qUg.png" /></figure><p>To apply the <strong>binary search</strong> algorithm, let’s first write out the pseudo code in steps to understand the bird’s eye view.</p><h3>Pseudocode</h3><pre>def binary_search(self, nums, target):<br>  # create two points for either end of the sorted array `nums`<br>  # iterate over the array<br>    # find the current midpoint<br>    # check if the midpoint is bigger than target<br>    # if else the midpoint is smaller than target<br>    # otherwise, we have a match<br>  # if after all iterations, no matech is found, return -1</pre><p>So, if we put that information to use we can label the first index and last index as our l and r pointers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*NXwoyZwUKGRJGES5km4V8A.png" /></figure><p>We will be looping over this array every time we do a lookup. Therefore, inside the loop we can assign the mid-point since this value will be updated each iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*kAydqOJ4JeufvrEcVeNMOw.png" /></figure><p>You can either choose to have a lower bounded mid-point or an upper bounded mid-point. Keep in mind that there may be different edge cases to consider. For this problem, to avoid an edge case, I will use floor division to isolate the mid-point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*KjQoC9yTpz5t3v4WfomDxA.png" /></figure><p>This is the first iteration where we will checking whether or not the midpoint is equal to the target we are looking for. In the case that the target value is either greater OR equal to or less than the midpoint, we need to update the corresponding pointers. Finally, we can check if the midpoint is a match for the target, if so we return that index. Otherwise, we return the value -1. Below is an animation to illustrate this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*Mqjt1D1FPGZaXkhcb8KiSQ.gif" /></figure><h3>Code Implementation</h3><pre>def search(self, nums: List[int], target: int) -&gt; int:<br>        # create two points for either end of the sorted array `nums`<br>        l, r = 0, len(nums) - 1<br>        <br>        # iterate over the array<br>        while l &lt;= r:<br>            m = l + ((r-l) // 2) # floor division<br><br>            # check if the midpoint is bigger than target<br>            if nums[m] &gt; target:<br>                # update RHS<br>                r = m - 1<br>            # midpoint is smaller than target<br>            elif nums[m] &lt; target:<br>                l = m + 1<br>            # match is found<br>            else:<br>                return m<br>        # no match found<br>        return -1</pre><h3>When should I use this algorithm?</h3><p>You would want to use <strong>binary search</strong> for any of the following scenarios below (remember that <strong>binary search</strong> has a <strong>time complexity</strong> of O(log n)):</p><ul><li><strong>Sorted data</strong>: Binary search works best on sorted data.</li><li><strong>Efficiency</strong>: Binary search offers faster searching for large datasets.</li><li><strong>Random access</strong>: Binary search requires direct access to elements.</li><li><strong>Elimination-based search</strong>: Binary search eliminates half of the search space in each iteration.</li><li><strong>Infrequent modifications</strong>: Binary search is most suitable for static or infrequently changing data.</li><li>If the problem statement wants a solution that has <strong>time complexity</strong> of O(log n), this may be a hint to use <strong>Binary Search.</strong></li></ul><h3>Test Yourself</h3><ul><li><a href="https://leetcode.com/problems/binary-search/">Binary Search</a></li><li><a href="https://leetcode.com/problems/search-a-2d-matrix/">Search a 2D Matrix</a></li><li><a href="https://leetcode.com/problems/koko-eating-bananas/">Koko Eating Bananas</a></li><li><a href="https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/">Find Minimum In Rotated Sorted Array</a></li><li><a href="https://leetcode.com/problems/search-in-rotated-sorted-array/">Search In Rotated Sorted Array</a></li><li><a href="https://leetcode.com/problems/time-based-key-value-store/">Time Based Key Value Store</a></li><li><a href="https://leetcode.com/problems/median-of-two-sorted-arrays/">Median of Two Sorted Arrays</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a46ea6e2ae35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Merge Sort Explained]]></title>
            <link>https://medium.com/@kitanatoft/merge-sort-explained-93a6bad7cccb?source=rss-26467efcf386------2</link>
            <guid isPermaLink="false">https://medium.com/p/93a6bad7cccb</guid>
            <category><![CDATA[merge-sort]]></category>
            <dc:creator><![CDATA[Kitana Toft]]></dc:creator>
            <pubDate>Sun, 07 May 2023 00:28:41 GMT</pubDate>
            <atom:updated>2023-05-07T00:28:41.619Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s face it, studying and mastering algorithms can often seem daunting and overwhelming. However, it’s important to remember that not all algorithms are equally difficult to understand, and they can vary in terms of their complexity and applications. While some algorithms may appear challenging at first glance, there are simpler algorithms that are easier to grasp and build upon.</p><p><strong>Merge Sort</strong> is one of the more simple algorithms to understand. Let me prove it to you!</p><h3>Overview</h3><p>One of the most commonly used sorting algorithms is <strong>Merge Sort</strong>. The procedure of <strong>merge sort</strong> involves <strong><em>dividing the original list into two equal halves</em></strong>, applying the same splitting process <strong><em>recursively</em></strong> to each half, and ultimately <strong><em>merging the resulting sorted sub-lists</em></strong> to obtain the fully sorted list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojX8w59yisWuWYluNrkTCg.png" /><figcaption>Fig. Merge Sort Visualized</figcaption></figure><h3>Divide &amp; Conquer with a Simple Approach</h3><p><strong>Divide and conquer</strong> algorithms are a class of algorithms that solve a problem by breaking it down into smaller, simpler subproblems. The subproblems are solved <strong>recursively</strong>, and their solutions are combined to produce a solution to the original problem.</p><h3>What is recursion?</h3><blockquote><em>In computer science, </em><strong><em>recursion</em></strong><em> is a programming technique where a function refers to itself within its own body of code.</em></blockquote><p>In other words, recursion involves solving a problem by breaking it down into smaller subproblems, and then solving each subproblem by applying the same method recursively.</p><p>There are two parts to <strong>recursion</strong>: a <strong>base case</strong> and the <strong>recursive cases</strong>. Let’s use a code example of the factorial of each element in the <em>Fibonacci Series</em> to better understand this concept.</p><pre>def factorial(n):<br>   if n == 1:<br>       return 1<br>   else:<br>       return n * factorial(n-1)</pre><p>In this example, the <strong>base case</strong> is when n is equal to 1, in which case the function returns 1. The <strong>recursive case</strong> is when n is greater than 1, in which case the function multiplies n by the factorial of n-1.</p><h3>Divide &amp; Conquer Steps</h3><p>The basic steps of a <strong>divide and conquer</strong> algorithm are as follows:</p><ol><li><strong>Divide</strong>: continuously break down the problem by dividing into smaller sub-problems that are easier to solve. This is done until the sub-problems are simple enough to be solved directly.</li><li><strong>Conquer</strong>: The sub-problems are solved <em>recursively</em>. This step involves applying the same algorithm to each of the sub-problems until they are simple enough to be solved directly.</li><li><strong>Combine</strong>: The solutions to the sub-problems are merged together to form a solution to the original problem.</li></ol><h3>Merge Sort: A Visual Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tOdRSkrm6i7tXmGJxBT0Pw.png" /><figcaption>Fig. Example unsorted array `nums`</figcaption></figure><p>Let’s say you have an unsorted list of integers nums equal to [10, 7, 3, 9, 2, 4, 8, 1, 6, 5]. And you want to sort it using the <strong>merge sort algorithm</strong>. Here&#39;s how you can solve this problem step by step:</p><p>(1) Our first step is to <strong>divide</strong> nums into two halves:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7Uq5c0VXgwoFdWDHv0UHg.png" /></figure><p>(2) Next, we need to <strong>conquer</strong>. Recursively divide each sub-list into two smaller sub-lists, until each sub-list contains only one element:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x5OP0Cdd4XuhCvOmLj_ogA.gif" /><figcaption>Fig. Recursively divide each sublist</figcaption></figure><p>At this point in the algorithm, the array should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Qlp-Xtjxmc5_peNOI1dMg.png" /><figcaption>Fig. Split arrays</figcaption></figure><p>(3) Finally, we can <strong>combine</strong> the singleton elements into sorted subarrays. At this point, we are applying the sorting algorithm <em>in-place</em> as we combine the elements. Merge the sub-lists pairwise to form new sub-lists in sorted order (do this recursively until all elements are merged):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yp8zFjSt2SwsLq6bWTNBmQ.gif" /><figcaption>Fig. Combine sorted subarrays</figcaption></figure><p>The sorted and merged solution will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojX8w59yisWuWYluNrkTCg.png" /><figcaption>Fig. Sorted Array using Merge Sort</figcaption></figure><h3>Let’s run through an example</h3><p>Learning by doing is the best way to cement a new concept. So, don’t be afraid, let’s solve a problem together. Today we will cover LeetCode’s <a href="https://leetcode.com/problems/sort-an-array/">Sort an Array</a> problem.</p><p>In this problem, we given an array of integers nums. We are asked to return the sorted the array in assending order.</p><p>Using the knowledge we have gained earlier, we can come up with a general idea for the steps necessary by gaining the bird’s eye perspective.</p><h3>Pseudocode</h3><pre>  def merge_sort(self, arr):<br>  ## Edge case: if arr less than 1, return itself<br>  ## take the floor value for mid point<br>  ## split the array into two halves: left_half &amp; right_half</pre><pre>  # recursive call on each half</pre><pre>  # set up index iterators for each half and the initial array</pre><pre>  # in a loop<br>  ## merge the two SORTED halves into the original array<br>  ## check: which half goes in first, add elements one-by-one<br>  ### LHS &lt;= RHS, favor LHS &amp; move the LHS iterator forward<br>  ### else, favor RHS &amp; move the RHS iterator forward</pre><pre>  # for all the remaining values, i.e. one half may be larger than the other<br>  # add the remaining sorted elements to the end of the sorted list</pre><pre>  # return the sorted list</pre><h3>Code Implementation</h3><p>Great, I think we have a good grasp of the problem. Let’s code it up.</p><pre>def sortArray(self, nums):<br>        &quot;&quot;&quot;<br>        :type nums: List[int]<br>        :rtype: List[int]<br>        &quot;&quot;&quot;<br>        # base case<br>        if len(nums) &lt; 2: return nums<br><br>        # take the floor value for mid point<br>        mid = len(nums) // 2<br>        # split the array into two halves<br>        left = nums[:mid]<br>        right = nums[mid:]<br><br>        # recursive call on each half<br>        self.sortArray(left)<br>        self.sortArray(right)<br><br>        # two iterators for traversing the two halves<br>        i = 0<br>        j = 0<br><br>        # iterator for the main list<br>        k = 0<br><br>        # merge the two SORTED halves into the original array<br>        while i &lt; len(left) and j &lt; len(right):<br>            # determine which half to take from &amp; add to sorted array<br>            if left[i] &lt;= right[j]:<br>                # the value from the left half has been used<br>                nums[k] = left[i]<br>                # move the iterator forward<br>                i += 1<br>            else:<br>                nums[k] = right[j]<br>                j += 1<br>            # move to the next slot in the array<br>            k += 1<br><br>        # for all the remaining values, add which ever half was bigger<br>        # and add the remaining sorted values into the array<br>        while i &lt; len(left):<br>            nums[k] = left[i]<br>            i += 1<br>            k += 1<br><br>        while j &lt; len(right):<br>            nums[k]=right[j]<br>            j += 1<br>            k += 1<br><br>        return nums</pre><h3>Recap</h3><blockquote><em>Q: How do I recognize the pattern?</em></blockquote><h3>Helpful Hints</h3><p>Here are some hints that might suggest using merge sort when attempting a coding problem:</p><ul><li>The problem involves <strong>sorting</strong>: <strong>Merge sort</strong> is a popular algorithm for sorting lists, so if a problem requires you to sort a list, merge sort could be a good algorithm to consider.</li><li>The <strong>input size is large</strong>: <strong>Merge sort</strong> has a <strong>time complexity</strong> of O(n log n), which <strong><em>makes it an efficient algorithm for large input sizes</em></strong>. If the problem requires you to sort a large list, merge sort could be a good choice.</li><li>The problem requires you to <strong>divide and conquer</strong>: <strong>Merge sort</strong> is a divide and conquer algorithm.</li><li>The problem requires you to <strong>merge sorted lists</strong>: <strong>Merge sort</strong> involves merging sorted sub-lists to form a sorted list. If a problem requires you to merge sorted lists, merge sort could be a good algorithm to use.</li><li>The problem involves <strong>finding the </strong><strong>kth smallest or largest element in an unsorted list</strong>. <strong>Merge sort</strong> can be used to find the kth smallest or largest element in an unsorted list by sorting the list and then indexing into the kth element.</li><li>The problem involves <strong>finding duplicates</strong> or <strong>unique elements</strong> in an <strong>unsorted list</strong>. <strong>Merge sort</strong> can be used to find duplicates or unique elements in an unsorted list by sorting the list and then comparing adjacent elements for duplicates or unique values.</li></ul><blockquote>Keep in mind that these are just <em>general hints</em>, and the best algorithm to use will depend on the specifics of the problem. It’s always a good idea to carefully read the problem statement and understand the constraints and requirements before deciding on an algorithm to use.</blockquote><h3>Test Yourself</h3><ul><li><a href="https://leetcode.com/problems/sort-an-array/">Sort an Array</a></li><li><a href="https://leetcode.com/problems/merge-k-sorted-lists">Merge k Sorted Lists</a></li><li><a href="https://leetcode.com/problems/sort-list">Sort List</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93a6bad7cccb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Insertion Sort Explained]]></title>
            <link>https://medium.com/@kitanatoft/insertion-sort-explained-3fac433149e0?source=rss-26467efcf386------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fac433149e0</guid>
            <category><![CDATA[insertion-sort]]></category>
            <dc:creator><![CDATA[Kitana Toft]]></dc:creator>
            <pubDate>Sat, 06 May 2023 05:38:49 GMT</pubDate>
            <atom:updated>2023-05-06T05:38:49.804Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p><strong>Insertion Sort</strong> is a simple algorithm that sorts a list of <em>unsorted elements</em> by repeatedly inserting each element into its proper place in a <em>partially sorted list</em>. NOTE: <strong>Insertion Sort</strong> is best used on <strong><em>small datasets</em></strong> because of its <strong>simplicity</strong> and <strong>relatively low overhead</strong>. It has a <strong>time complexity</strong> of O(<em>n</em>²), meaning that its worst-case running time increases rapidly as the number of elements in the dataset grows. This makes <strong>insertion sort</strong> impractical for sorting very large datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*ljLSlBy_Y8fW2nXJB3KP8w.gif" /><figcaption>Fig. InsertionSort</figcaption></figure><h3>How do I recognize the pattern?</h3><p><strong>Insertion sort</strong> involves sorting an array by inserting each element into its proper position within a partially sorted array. The pattern for insertion sort involves iterating through the unsorted portion of the array and moving each element to its correct position within the sorted portion of the array.</p><p>Here are a few hints you can look for to determine if insertion sort is a good choice:</p><ul><li><strong>Small dataset</strong>: If the problem involves sorting a small dataset, insertion sort may be the best choice. <strong>Insertion sort</strong> is a simple algorithm that has a low overhead, making it efficient for small datasets.</li><li><strong>Partially sorted data</strong>: If the dataset is partially sorted, insertion sort can be a good choice because it will only need to perform a small number of swaps to put the remaining elements in their correct positions.</li><li><strong>In-place sorting</strong>: If the problem requires an in-place sorting algorithm, insertion sort is a good choice. Insertion sort is an in-place sorting algorithm, which means it does not require additional memory to sort the dataset.</li><li><strong>Preserving the order of equal elements</strong>: If the problem requires that the order of equal elements in the dataset is preserved after sorting, insertion sort can be a good choice. Insertion sort is a <strong><em>stable sorting algorithm</em></strong>, which means <em>it preserves the order of equal elements</em>.</li></ul><p>Overall, the best sorting algorithm to use depends on the specific problem requirements and the characteristics of the dataset.</p><h3>Pseudocode</h3><p>Here are the general steps for the pattern of insertion sort:</p><ol><li>Start with an <strong>unsorted array</strong> of numbers.</li><li><strong>Iterate through the unsorted portion</strong> of the array, <em>starting from the second element</em>.</li><li>For each element in the unsorted portion of the array, <strong>compare it to the elements before it</strong> in the sorted portion of the array.</li><li>If the current element is smaller than the previous element, <strong>swap them</strong>.</li><li><strong>Continue to move</strong> the current element to the left within the sorted portion of the array until it is in its correct position.</li></ol><p><strong>Repeat steps 2–5</strong> until all elements in the unsorted portion of the array have been moved to their correct positions.</p><p>The array is now sorted.</p><h3>Let’s run through an example</h3><p>Let’s review an easy problem.We have an unsorted array s and we are asked to return the sorted array.</p><p>Here’s an example of the pattern for insertion sort on the array s, where sis equal to [5, 2, 4, 6, 1, 3]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*kxvDb8a26Q0tzcxrQVvtGw.png" /><figcaption>Fig. Insertion Sort Example</figcaption></figure><ul><li>First, we start with the <strong><em>unsorted array</em></strong> [5, 2, 4, 6, 1, 3].</li><li>We start iterating through the unsorted portion of the array from the second element 2.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*rOJEjT0-xdVTnAvXJUVrYg.png" /><figcaption>Fig. Start with the Second (2nd) Element during iteration</figcaption></figure><ul><li>We compare 2 to the first element 5in the sorted portion of the array and <strong>swap them</strong> to get [2, 5, 4, 6, 1, 3].</li><li>We continue to move 2 to the left within the <strong>sorted portion of the array</strong> <em>until it is in its correct position</em>, resulting in [2, 5, 4, 6, 1, 3].</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*yjEW5UGdMEqtyoSqJhXPFg.png" /><figcaption>Fig. Swap elements 2 and 5 , then move forward</figcaption></figure><ul><li>Next, we move on to the next element 4in the <strong>unsorted portion of the array</strong> and <strong>compare it</strong> to the elements in the <strong>sorted portion of the array</strong>.</li><li>We <strong>swap</strong> 4with 5to get [2, 4, 5, 6, 1, 3].</li><li>We continue to move 4 to the left within the sorted portion of the array until it is in its correct position, resulting in [2, 4, 5, 6, 1, 3].</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*VAHR8B8HqW22fkPA9HGndQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*W2a1qH62iWnfvJQV6fZgWA.png" /><figcaption>Fig. Swap elements 4 and 5, then move forward</figcaption></figure><p>We repeat this process for the remaining elements until the entire array is sorted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*ljLSlBy_Y8fW2nXJB3KP8w.gif" /><figcaption>Fig. Animated Solution</figcaption></figure><h3><strong>Code Implementation</strong></h3><pre># remember: start with the **2nd element**<br>  # traverse through 1 to len(arr)<br>    for i in range(1, len(arr)):<br>        target = arr[i]<br>        j = i - 1<br><br>        # arr[j] and arr[j + 1] are out of order, so swap them<br>        while j &gt;= 0 and arr[j] &gt; target:<br>            arr[j + 1] = arr[j]<br>            j -= 1<br><br>        arr[j + 1] = target<br><br>    return arr</pre><p><strong>## Important things to note</strong></p><ul><li><strong>Insertion Sort</strong> has a <em>worst-case time complexity</em> of O(<em>n</em>²), which means <em>it can become slow for very large lists</em>.</li><li>It has some advantages over other sorting algorithms, such as being <strong>easy to implement</strong> and <strong>taking up very little memory</strong>.</li><li>It is also an “<strong>in-place</strong>” algorithm, meaning it modifies the original list rather than creating a new one.</li><li>Finally, it is a <strong>stable sorting algorithm</strong>, which means that it <em>preserves the relative order</em> of equal elements in the list.</li></ul><h3>Test Yourself</h3><ul><li><a href="https://leetcode.com/problems/sort-an-array/">Sort an Array</a></li><li><a href="https://leetcode.com/problems/insertion-sort-list/">Insertion Sort List</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fac433149e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sliding Window Technique Explained]]></title>
            <link>https://medium.com/@kitanatoft/sliding-window-technique-explained-653a011d1eae?source=rss-26467efcf386------2</link>
            <guid isPermaLink="false">https://medium.com/p/653a011d1eae</guid>
            <category><![CDATA[sliding-windows]]></category>
            <category><![CDATA[sliding-window-algorithm]]></category>
            <dc:creator><![CDATA[Kitana Toft]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 05:12:18 GMT</pubDate>
            <atom:updated>2023-04-25T05:12:18.154Z</atom:updated>
            <content:encoded><![CDATA[<p>The <strong>sliding window</strong> technique is a continuation of the <strong>two pointer</strong> technique, which uses two pointers to act as boundary points for a fixed-size segment, i.e “<em>window</em>”, that moves along the data structure performing some operation to obtain a desired result. The operation(s) and size of the chunk rely on the problem statement. The sliding window technique is a computational method aimed to reduce time complexity and number of nested loops, therefore boosting efficiency. To better understand this concept, let’s take a deep dive and go over an example together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*sC0wRbX2Ui5XeQIyuVkskg.gif" /><figcaption>Fig. Sliding Window Technique Visualized (Fixed Window Size)</figcaption></figure><h3>Overview</h3><p>The <strong>sliding window</strong> technique uses two pointers to set up a bounded segment, the “<em>window</em>”. This “<em>window</em>” is a sublist of elements formed over an iterable <strong>data structure</strong> such as an array or list. Unlike the <strong>two pointer</strong> technique which isolates two individual points, the sliding window technique encapsulates a set of elements between two points. The <strong>sliding window</strong> technique can either use a <strong>window size</strong> that is <em>fixed</em> or <em>variable</em>. During each iteration, there is an operation or series of operations being done to the given chunk. This computation will continue each iteration. This concept is primarily based on ideas such as shortest or longest sequences given to a subset of a given array or list. It is often used to reduce the time complexity of the problem from O(n²) to O(n).</p><h3>How do I recognize the pattern?</h3><p>Questions to ask yourself when reading the problem statement can include:</p><ul><li>Does this problem involve an iterable <strong>data structure</strong> that is an <strong>array</strong>, <strong>string</strong> or <strong>list </strong>(i.e., a data structure that is ordered/iterable)?</li><li>Are you <strong>looking for a chunk</strong> or <strong>subrange</strong> of the given data structure?</li><li>Is the naive approach (i.e., <strong>brute force solution</strong>) time complexity O(n²) or O(<em>k</em>n)?</li><li>Does the question involve key words like “<em>optimal</em>”, “<em>longest</em>”, or “<em>shortest</em>” in a sequence of something that requires an exact condition.</li></ul><h3>How do I use the Sliding Window technique?</h3><p>The <strong>sliding window</strong> algorithm can be solved generally with the following steps:</p><ol><li>Identify <strong>window size</strong> by initializing two pointers at the border of the window (<strong><em>Ask Yourself</em></strong>: Is it a <em>fixed</em> or <em>variable</em> size?)</li><li><strong>Iterate</strong> over the data structure and <strong>check the condition</strong>(s) as you move the window each iteration</li><li><strong>Update the window size</strong> as necessary</li></ol><pre>def sliding_window(nums):<br>  # iterate over elements in the input array<br>  # check condition, expand if necessary<br>    # evaluate current window<br>    # contract window</pre><ul><li>Initialize two pointers: one that starts at index 0 and another that is some distance away (i.e., this is our <strong>window size</strong>). Find the size of window on which the algorithm will be performed (<strong><em>Ask</em></strong>: Is it a <em>fixed</em> or <em>variable</em> size?)</li><li>Calculate the result of the first window frame, identify the naive pattern</li><li>Loop over each iteration, moving the sliding window by updating the pointer(s) and keeping track of the results of each iteration</li><li>Check the condition(s) each iteration: either increase window size and/or proceed OR the condition is NOT met in the given iteration</li></ul><p>Note that the window size can either be <em>fixed </em>size<strong> </strong>or of <em>variable</em><strong> </strong>size. See the example gifs below for reference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*MMUb5y0VvYLTE7huo0gLEA.gif" /><figcaption>fig. Fixed Window size (k = 2)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*w6ZIk0_eZ4b2H7K_zildsw.gif" /><figcaption>fig. Variable Window size (k ≤ 3)</figcaption></figure><h3>Let’s run through an example</h3><p>I learn the best when I go through an example so let’s try one together. Today we will be covering <a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/">Longest Substring Without Repeating Characters </a>from LeetCode using the <strong>sliding window</strong> technique.</p><p>PROMT: We are given a string s and we are asked to find the <strong>longest substring without repeating characters</strong>.</p><p>We will be using the input string s where s = &quot;abcabcbb&quot;. The output is equal to a length of 3.</p><p>Let’s try to pick this apart for a second. The <strong>buzz words</strong> in the problem statement mentioned “<strong><em>longest</em> substring</strong>” and some condition(s). This should ring a bell in your mind, triggering you to say “Aha! This problem requires <strong>sliding window</strong> technique.”</p><p>Notice that the problem statement <strong>did not provide a static window size</strong>, which means that our window is <em>dynamic</em> / of <em>variable size</em>. We will need to initialize two pointers: one at the head of the data structure and one that travels during each iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*9bW44qejCdCWzACrABwU3Q.gif" /><figcaption>fig. Initialize two pointers</figcaption></figure><p>We will need to devise a way to keep track of the elements that we have already seen. Let’s use a <strong>hashmap </strong>(i.e., in Python it’s referred to as a <strong>“dictionary</strong>”) to store each character as a <strong>key</strong> and the <strong>value</strong> is the respective index in the [<strong>key : value]</strong> pair.</p><p>We need to make a list of the possible edge cases. For example, in the string s where s = &quot;abcabcbb&quot; we can continue adding each character to the hashmap one at a time. We don’t run into a duplicate element in the hashmap until we reach index 3, which means we need to adjust our window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*I5UVbiDfz1rhxQoOEmdnVg.gif" /></figure><p>Since the problem statement requires us to return the length of “<strong>longest substring without repeating characters</strong>” — in other words we need to have a contiguous window. Whenever there is a duplicate element, we need to move Ptr 1on the left up by one. This will be a necessary check.</p><p>For each iteration we will do a check, then increment the right pointer, Ptr 2, by 1 until we reach the length of the string s. Keep in mind that our goal is to achieve the longest substring. Once we’ve gone over all elements in the string, we can return the maximum length.</p><p>Now that we have a basic idea of what to do, let’s try to explain our approach using pseudocode.</p><pre># Pseudocode<br>def lengthOfLongestSubstring(self, s: str) -&gt; int:<br>  # Create 2 pointers where ptr1 = index 0 and ptr2 expands the window size<br>  # Create a hashmap to store seen values --&gt; key/value : character/index<br><br>  # Iterate over the all elements in the string s<br>      # Check if the element is already in the hashmap<br>      # if it is, update the LHS pointer by moving it left by 1<br>  # Add element to seen hashmap<br>  # Increment the window size by one<br>  # Return the maximum length of the largest substring</pre><h3>Code Implementation</h3><p>We have a clear idea of how to tackle this problem, let’s code it up!</p><pre>def lengthOfLongestSubstring(self, s):<br>        &quot;&quot;&quot;<br>        :type s: str<br>        :rtype: int<br>        &quot;&quot;&quot;<br>        # Create pointers for each end of the window<br>        left = 0<br>        max_len = 0<br><br>        # Create a hashmap --&gt; key/value : character/index<br>        seen = {}<br><br>        # Iterate over the all elements in the string s<br>        for right in range(len(s)):<br>          # check if the element is already in the hashmap<br>          if s[right] in seen:<br>            # if it is, update the LHS pointer by moving it left by 1<br>            left = max(left, seen[s[right]] + 1)<br><br>          # add the new element to the hashmap<br>          seen[s[right]] = right<br>          # increment the window size by one<br>          max_len = max(max_len, right - left + 1)<br>        <br>        # return the maximum length of the given substring<br>        return max_len</pre><p>We can see this in action in the given animation below. The maximum contiguous length that we can achieve with this string is a length of 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*DIPEcqQ0sG2i14G9fVHOxg.gif" /></figure><h3>Recap</h3><p>To find the length of the longest substring without repeating characters in a given string:</p><ul><li>Initialize two pointers, left and right, to mark the start and end of the current window. Start with left and right at index 0.</li><li>Create an empty hashmap, seen, to store the characters in the current substring and their indices.</li><li>While right is less than the length of the string:</li></ul><ol><li>Check if the character at the right index is already in seen.</li><li>If the character is not in the hash seen, add it with its index to the hashmap, and increment right.</li><li>If the character is already in seen, update left to be the maximum of its current value and the index of the character in the seen plus 1. This removes the old character from the dictionary and updates the new character with its current index.</li></ol><ul><li>After each iteration, update the length of the longest substring by taking the maximum of the current length and the difference between right and left plus 1.</li><li>Repeat steps 3–4 until right is equal to the length of the string.</li><li>The final result is the length of the longest substring without repeating characters.</li></ul><h3>Other Variations</h3><p>There are many different methods for the <strong>sliding window</strong> algorithm (note that these are not all-inclusive):</p><ol><li><strong>Fixed Size Sliding Window</strong>: In this variation, a <em>fixed-size window</em> is moved over the input array or string, and the result is calculated for each window. This approach is useful when the size of the window is fixed, and the result needs to be computed for each subarray of the given size.</li><li><strong>Dynamic Size Sliding Window</strong>: In this variation, the size of the sliding window <em>changes dynamically based on some condition</em>. For example, if we are given an array of integers and we want to find a subarray whose sum is equal to a target value, we can start with a window of size 1 and keep increasing the window size until we find a subarray whose sum is equal to the target.</li><li><strong>Two Pointers Sliding Window</strong>: In this variation, two pointers are used to maintain a sliding window. One pointer represents the start of the window, and the other pointer represents the end of the window. The window is moved by incrementing the end pointer, and if the condition is not satisfied, the start pointer is incremented until the condition is satisfied again.</li><li><strong>Multiple Sliding Windows</strong>: In this variation, multiple sliding windows are used to solve a problem. For example, if we are given two arrays A and B, and we want to find all the common elements between the two arrays, we can use two sliding windows, one for array A and one for array B, and move them together until we find a common element.</li></ol><h3><strong>Test Yourself</strong></h3><p><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/">Best Time to Buy and Sell Stock</a></p><p><a href="https://leetcode.com/problems/contains-duplicate-ii/">Contains Duplicate II</a></p><p><a href="http://Longest Substring Without Repeating Characters">Longest Substring Without Repeating Characters</a></p><p><a href="https://leetcode.com/problems/longest-repeating-character-replacement/">Longest Repeating Character Replacement</a></p><p><a href="https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/">Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold</a></p><p><a href="https://leetcode.com/problems/minimum-size-subarray-sum/">Minimum Size Subarray Sum</a></p><p><a href="https://leetcode.com/problems/permutation-in-string/">Permutation in String</a></p><p><a href="https://leetcode.com/problems/minimum-window-substring/">Minimum Window Substring</a></p><p><a href="https://leetcode.com/problems/sliding-window-maximum/">Sliding Window Maximum</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=653a011d1eae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kadane’s Algorithm Explained]]></title>
            <link>https://medium.com/@kitanatoft/kadanes-algorithm-explained-c8c3c4d626a?source=rss-26467efcf386------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8c3c4d626a</guid>
            <category><![CDATA[kadanes-algorithm]]></category>
            <dc:creator><![CDATA[Kitana Toft]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 23:11:46 GMT</pubDate>
            <atom:updated>2023-04-06T23:11:46.732Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Kadane</strong>’s Algorithm (a.k.a. <em>maximum sum subarray problem</em>) is a greedy dynamic programming algorithm that calculates the maximum subarray at a particular position. It also helps reduce the time complexity to linear time O(<em>n</em>).</p><h3><strong>Overview</strong></h3><p><strong>Kadane</strong>’s Algorithm is an iterative <strong>greedy</strong> dynamic programming algorithm. It is used to <strong>calculate the maximum sum contiguous sub-array at a particular position</strong>. The <strong>maximum subarray problem</strong> is the task of finding the largest possible sum of a contiguous sub-array, within a given one-dimensional array of numbers. This algorithm has a <strong>time complexity of O(n)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*LtiucQqWzNZc4vEz_pdgOw.png" /></figure><p>I think that the best way to understand a concept is by solving a problem, so today we will first go over the brute force method, then attempt <strong>Kadane</strong>’s algorithm.</p><h3><strong>Let’s run through an example</strong></h3><p>Let’s go over the problem <a href="https://leetcode.com/problems/maximum-subarray/">Maximum Subarray</a> from LeetCode.</p><p>We are given an integer array numsand are asked to find the sub-array that is the largest possible sum, and return that value. We will use the first example. See the array below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*bpJQYF2iL7qL3OLnTNJhhw.png" /></figure><p>We need to keep track of several things:</p><ul><li>cur_sum denotes the current sum we have in the given sub-array, we do not want this value to be negative</li><li>max_sum denotes the maximum sum of the sub-array, initialize this value at the first position in the array nums[0]</li><li>cur_sum size of the input array</li></ul><h4><strong>Brute Force Method</strong></h4><p>The naive approach is to:</p><p>1. Find all possible contiguous sub-arrays</p><p>2. Calculate &amp; keep track of the sum of every possible contiguous sub-array (see the figures below)</p><p>3. Find the maximum sub-array value given all of the sums</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*sjJprF0aVIkwemcdpuIV4g.png" /></figure><p>The brute force method calculates all of the sub arrays starting with index zero, e.g. nums[0], and calculates their respective sums. However, by doing this approach, we would then need to calculate every possible sub-array starting with nums[0], nums[1]` and so on until we reach the length of nums (i.e. the last index of nums).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X79yafAPWHds9CwI3h8-pQ.png" /></figure><blockquote><strong>Q</strong>: How would we code it up?</blockquote><p>Essentially, we would need two loops: an outer loop to keep track of which iteration we are on and an inner loop to do all of the work.</p><pre>def kadaneBruteForce(nums):<br>  max_sum = nums[0]<br>  for i in range(len(nums)):<br>    cur_sum = 0<br>    for j in range(i, len(nums)):<br>      cur_sum += nums[j]<br>      max_sum = max(cur_sum, max_sum)<br>  return max_sum</pre><p>Are you starting to notice how expensive this could get given a large array? Using the <strong>brute force</strong> approach, we get <strong>time complexity</strong> of O(n²). This method would work, but there is duplication and a lot of unnecessary work. We can improve our approach.</p><h3><strong>Kadane’s Algorithm</strong></h3><p><strong>Kadane</strong>’s Algorithm is a way of calculating the maximum sum of a contiguous sub-array using linear time.</p><h4><strong>Pseudocode</strong></h4><p>Here are the steps to implement <strong>Kadane</strong>’s Algorithm:</p><ol><li>Initialize two variables cur_sumand max_sum equal to the first index of the array nums[0]</li><li>Iteratively traverse through the array starting at index one, nums[1]</li></ol><p>Then for each iteration:</p><ul><li>Add the current element to cur_sum</li><li>If the current sum becomes negative, reset it to the current index (we don’t want negative numbers since that will bring down our maximum sum)</li><li>If the max_sum is greater than cur_sum, update the max_sum</li><li>Return the max_sum</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*1V_Ax4n6iQO5LeJLnmbFsA.gif" /></figure><p>Recall that we want to have the maximum contiguous sub-array. Negative values are not desirable, but not necessary to remove each time.</p><h4><strong>Code Implementation</strong></h4><pre>def maxSubArray(self, nums):<br>  cur_sum = max_sum = nums[0]<br>    for n in nums[1:]:<br>      cur_sum = max(n, cur_sum + n)<br>      max_sum = max(cur_sum, max_sum)<br>  return max_sum</pre><p>With <strong>Kadane</strong>’s Algorithm we now have linear time, O(n) and reduce the code duplication of a nested loop.</p><h3><strong>How do I recognize the pattern?</strong></h3><p>You can ask yourself a few questions:</p><p>1. Is the problem statement asking me to use a greedy algorithm?</p><p>2. Am I trying to find the maximum contiguous subarray?</p><p>Keywords to look out for:</p><ul><li><em>Contiguous increasing array</em></li><li><em>Contiguous subarray</em></li><li><em>Maximum (or largest) subarray</em></li><li><em>Subsequence Sum</em></li></ul><p>This algorithm is very similar to the <strong>Sliding Window</strong> technique (let’s try that algorithm together in another post).</p><h3><strong>Recap</strong></h3><p><strong>Kadane</strong>’s Algorithm is a <strong>greedy</strong> dynamic programming algorithm that <strong>calculates the maximum subarray</strong> at a particular position. It helps reduce the time complexity to <strong>linear time</strong> O(<em>n</em>).</p><h3><strong>Test Yourself</strong></h3><ul><li><a href="https://leetcode.com/problems/maximum-subarray/">Maximum Subarray</a></li><li><a href="https://leetcode.com/problems/maximum-ascending-subarray-sum/">Maximum Ascending Subarray Sum</a></li><li><a href="https://leetcode.com/problems/maximum-sum-circular-subarray/">Maximum Sum Circular array</a></li><li><a href="https://leetcode.com/problems/continuous-subarray-sum/">Continuous Subarray Sum</a></li><li><a href="https://leetcode.com/problems/longest-turbulent-subarray/">Longest Turbulent Subarray</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8c3c4d626a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two Pointer Algorithm Explained]]></title>
            <link>https://medium.com/@kitanatoft/two-pointer-algorithm-explained-52fee6a2438a?source=rss-26467efcf386------2</link>
            <guid isPermaLink="false">https://medium.com/p/52fee6a2438a</guid>
            <dc:creator><![CDATA[Kitana Toft]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 01:46:33 GMT</pubDate>
            <atom:updated>2023-03-31T01:53:14.744Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to my mini-series “<strong><em>Explained</em></strong>” where I will do my best to describe commonly used Data Structures &amp; Algorithms.</p><h3>Introduction</h3><p>In this article, we will learn about the <strong>Two Pointer</strong> algorithm. I will provide a brief overview, give an example, and we will learn how to recognize when to use this technique. I will also mention other variations that two pointers can be used for. Let’s go!</p><h3>Overview</h3><p>The Two Pointer algorithm uses two pointers to iterate an array or list until conditions are met. This technique is useful because it allows us to keep track of two values and different indexes in a single iteration. Try using this technique whenever you see a problem that requires you to keep track of two different values in an array. The Two Pointer technique should come to mind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*OHcnRJFU3eniA1PKwrXfkQ.png" /><figcaption>Fig. Two Pointers</figcaption></figure><p>A <strong>pointer</strong> (see image below) in computer science is a reference to an object. In many programming languages, a pointer is an object that stores a memory address that references a value in computer memory, or in some cases, a memory-mapped computer hardware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hB9yJkTZvmeZGtVq2eDkKg.png" /><figcaption>Fig. Pointer Visualized</figcaption></figure><h3>How do I recognize the pattern?</h3><p>We want to use the Two Pointer technique because it saves us both time and space. By having two pointers, we can half the time it takes to iterate over the data structure and check the validity of the problem’s conditions.</p><ol><li>Naive approach using nested loops which has a time complexity of O(n²)</li><li>Optimized approach using the Two Pointer technique which exploits the symmetric property of palindromes which has a time complexity of O(n)</li></ol><p>There are two different approaches to the Two Pointer technique:</p><ol><li>Pointers at opposite ends of the data structure (at indexes 0 and n)</li><li>Pointers at the same end of the data structure (at indexes 0 and 1)</li></ol><p>Your solution depends on the problem statement. In some instances, we may need to create an additional data structure to iterate over these values. The first approach moves both pointers towards the center after each iteration. The second approach is often referred to as the “<strong>Fast &amp; Slow</strong>” technique (more details on this in another article).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*AxAaoGx-4VrwiZxdErcyfQ.png" /><figcaption>Fig. Two Pointer Direction Options</figcaption></figure><p>The algorithm can be solved generally with the following steps:</p><ol><li>Initialize two pointers</li><li>Determine what condition(s) needs to be checked during each iteration</li><li>Update the pointers</li><li>Evaluate the values of the pointers</li></ol><h3>Let’s run through an example</h3><p>Let’s try a LeetCode example of <a href="https://leetcode.com/problems/valid-palindrome/">Valid Palindrome</a>. For example, say you have a string sand want to check if the letters within it are a valid palindrome. Return Trueif it is valid, Falseotherwise.</p><blockquote>A <strong>palindrome</strong> is a sequence that reads the same forward as it does backward.</blockquote><p>You could use the Two Pointer technique to solve this problem. *Note that a valid palindrome equals the length of characters in the string and therefore a string with an odd length is invalid.</p><pre>Example 1:<br>input: s = “abccba”<br>output: True <br>explanation: “abccba” is a palindrome<br><br>Eample 2:<br>input: s = “abc”<br>output: False<br>explaination: “abc” is NOT a palindrome</pre><p>In this example, we set up two pointers on either end of the string s. Lets refer to Pointer 1 as “<em>left</em>” and Pointer 2 as “<em>right</em>” in the code. Below is a visual followed with the full code and comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*dHiCIQkUYY32urWq6N_1mA.gif" /><figcaption>Fig. Symmetric pointers</figcaption></figure><pre># Initialize pointers<br>left = 0<br>right = len(s) — 1<br><br># Iterate through all the characters in `s`<br>while left &lt; right: <br># check that the characters NOT are equal, return False <br>  if s[left] != s[right]:<br>    return False <br># otherwise, the characters are equal, <br># continue to move pointers in by one and compare <br>  else:<br>   left += 1<br>   right -= 1<br>return True</pre><h3>Pointers on the same side</h3><p>Using the example above, it would not make sense to have the pointers at the same end. *Note that both of the pointers could start on either the left or right ends of the array. Please check out my next article “Fast &amp; Slow Technique Explained” for more details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*SCxnVyG6N4sNLJlupysEjA.gif" /><figcaption>Fig. Pointers on the same end</figcaption></figure><h3>Recap</h3><p>You would want to use a two pointer technique whenever you need to keep track of two elements within an array or list. Important questions to ask yourself to see if we should use a two pointer technique:</p><ul><li>Is the sequence sorted or unsorted?</li><li>Do we need to compare the values of two different indexes?</li><li>Do we need to swap those values?</li><li>Do we need to partition the array?</li><li>Do we want to reduce the number of nested loops?</li></ul><h3>Varieties</h3><p>Two pointer problems come in different varieties:</p><ul><li>Binary Search (searching for a sorted array by repetitively splitting in half)</li><li>Symmetric Two Pointers (this example)</li><li>Fast &amp; Slow Pointers (a.k.a. the tortoise &amp; hare algorithm)</li><li>Boundary &amp; Search pointers (one pointer remains the same as the other does a comparison with the other elements in the data structure)</li><li>Sliding Window (a fixed size window using two pointers to search through the data structure)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52fee6a2438a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>