<?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 leetcodeWithMe on Medium]]></title>
        <description><![CDATA[Stories by leetcodeWithMe on Medium]]></description>
        <link>https://medium.com/@omarabozeid60?source=rss-c7e847b5f304------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by leetcodeWithMe on Medium</title>
            <link>https://medium.com/@omarabozeid60?source=rss-c7e847b5f304------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:55:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@omarabozeid60/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 Data Structures: Queues Module 1, Part 3]]></title>
            <link>https://medium.com/@omarabozeid60/understanding-data-structures-queues-module-1-part-2-56d09016133e?source=rss-c7e847b5f304------2</link>
            <guid isPermaLink="false">https://medium.com/p/56d09016133e</guid>
            <dc:creator><![CDATA[leetcodeWithMe]]></dc:creator>
            <pubDate>Fri, 30 Aug 2024 04:19:50 GMT</pubDate>
            <atom:updated>2024-09-01T05:29:05.183Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Before diving into queues, I recommend checking out my earlier post on </strong><a href="https://medium.com/@omarabozeid60/understanding-data-structures-stacks-module-1-part-2-1ba150df49cd"><strong>stacks </strong></a><strong>therefor I provided an introduction to stacks and queues, where I explained the structure of each and highlighted the differences between them.</strong></p><p>I‘ll assume you’ve already read the previous blog, so you now understand what queues are. Now, let’s dive into the details of how to implement queues.</p><p><strong>Queues: abstract data structure with following operation</strong></p><h4><strong>core operations:</strong></h4><ul><li><strong>Enqueue:</strong> This operation adds a key to the collection. The key represents the data or task you’re adding to the queue.</li><li><strong>Dequeue:</strong> This removes and returns the key that was added the earliest, ensuring that the least recently added key is the first to be processed. This is the opposite of how a stack works, where the most recently added key is the first to be removed.</li><li><strong>Is Empty:</strong> This operation checks whether the queue is empty, helping you determine if there are any more elements to process.</li></ul><h4>so ,How Do we Implement Queues?</h4><p>Similar to stacks, queues can be implemented using either arrays or linked lists. We will explore each implementation in depth. <strong>Let’s start with the linked list implementation.</strong></p><p>To implement a queue using a linked list, the core idea is simple: you add new elements to the back and remove them from the front. This way, you maintain the “First In, First Out” (FIFO) property of a queue. Let’s explore how this works in detail.</p><p><strong>Enqueue Operation: Adding to the Back</strong></p><p>Imagine we start with an empty linked list and want to add elements to our queue. We use the Enqueue operation for this. When we Enqueue(a), the element &#39;a&#39; is added to the back of the linked list. If we Enqueue(b) next, it’s also added to the end of the list, right after &#39;a&#39;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*xZWVJbsvSbw5pOynBSfQWw.png" /></figure><p>Let’s keep adding more elements. If we Enqueue(c), it again goes to the tail, maintaining the order: a -&gt; b -&gt; c. But what happens when we start removing elements with Dequeue?</p><p>Here’s where things get interesting. If we call Dequeue now, which element gets removed? Since it&#39;s not a stack, the element &#39;c&#39; (the last added) will not be removed. Instead, the element &#39;a&#39;, which has been in the queue the longest, is removed. This is because a queue follows the &quot;First In, First Out&quot; rule. So, calling Dequeue pops &#39;a&#39; from the front.</p><p>After removing ‘a’, our queue now looks like: b -&gt; c.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*cJBmb3ElLdP3LzlQvuvbKA.png" /></figure><p><strong>Understanding the Operations Under the Hood</strong></p><ul><li><strong>Enqueue</strong> uses the list’s PushBack method to add elements to the end.</li><li><strong>Dequeue</strong> combines two operations: TopFront to retrieve the front element and PopFront to remove it.</li><li><strong>Empty</strong> simply checks if the list’s head is nil.</li></ul><h4>How to Implement Queues Using Arrays</h4><p>Now, let’s look at how to create a queue with an array. This approach is simple and shows how a queue works with a fixed amount of space in memory.</p><p>When thinking about arrays, we might first consider simply adding items to the end and removing them from the front, similar to how a queue works. However, this would make the dequeuing process slow, taking O(n) time, which isn’t ideal. To keep both enqueue (adding) and dequeue (removing) operations efficient (O(1) time),so how we could solve that.</p><p>we can use a circular array , <strong>How Does the Circular Array Work</strong>?</p><p>In a circular array, we use two pointers: a “write index” that shows where to add the next item and a “read index” that shows where to remove the next item.</p><p><strong>Enqueue Operations</strong>:</p><ul><li>We start by adding an item, like (a), at the current write index.</li><li>Every time we enqueue, we increase the write index.</li><li>This continues, so when we enqueue (b), it’s added after (a), and the write index moves forward.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*7PLfr7T-TDIfN-yxU7Cw0g.png" /></figure><p><strong>so, how could I check for “Is empty” </strong>To check if the queue is empty, we simply compare the read and write indices. If they are the same, the queue is empty.</p><p><strong>Dequeue Operations</strong>:</p><ul><li>For dequeuing, we remove the item at the read index and then move the read index forward.</li><li>When we dequeue (a), the read index moves from the first position to the next.</li><li>If we continue dequeuing, we remove items in the order they were added, maintaining the “first in, first out” behavior.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*XyGhn9Gdt8ObrkZJaH2QiQ.png" /></figure><ul><li><strong>Circular Behavior</strong>:</li><li>When the write index reaches the end of the array, it wraps around to the beginning, continuing in a circular manner.</li><li>This circular approach helps efficiently use space and avoid shifting elements around in the array.</li><li><strong>Handling Full Queues</strong>:</li><li>If the write index reaches a point where adding another item would make it match the read index, we know the queue is full. To avoid confusion, we keep a buffer space of one element to clearly distinguish between a full and empty queue.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*gpg17TQDPBEGEHw5Vwf97g.png" /></figure><p>By implementing a queue this way, all operations (enqueue, dequeue, check if empty) remain O(1) in time complexity. However, one limitation is that the array has a fixed size. If you need a dynamic size, a linked list might be a better choice, though it comes with its own trade-offs, like additional memory for pointers.</p><p>Overall, both implementations have their uses depending on whether you want a fixed or flexible size for your queue.</p><p>At the end understanding these queue implementations helps you choose the best way to handle queue operations in your projects. Whether you use an array or a linked list, you can manage your data efficiently and keep performance high.</p><p><strong>thanks for reading happy coding !</strong></p><h3>Resources</h3><p>For those interested in exploring data structures and algorithms further, here are some valuable resources:</p><ul><li><strong>Coursera Course:</strong></li><li><a href="https://www.coursera.org/learn/data-structures/home/module/1">Data Structures on Coursera</a> — An in-depth course that covers a wide range of data structures and their applications.</li><li><strong>Books:</strong></li><li><em>“Introduction to Algorithms”</em> by Cormen, Leiserson, Rivest, and Stein — A comprehensive textbook on algorithms and data structures.</li></ul><p>I encourage you to share your thoughts, experiences, or any questions you have in the comments below. If you found this blog post helpful, please share it with others who might benefit from it. Your feedback and engagement help us create more valuable content!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56d09016133e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Data Structures: Stacks Module 1, Part 2]]></title>
            <link>https://medium.com/@omarabozeid60/understanding-data-structures-stacks-module-1-part-2-1ba150df49cd?source=rss-c7e847b5f304------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ba150df49cd</guid>
            <dc:creator><![CDATA[leetcodeWithMe]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 09:40:28 GMT</pubDate>
            <atom:updated>2024-08-19T09:40:28.645Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction: What Are Stacks and Queues?</h3><p>Stacks and queues are essential data structures used to manage collections of elements with specific rules about how elements are added and removed. Here’s a simple breakdown of how they work:</p><p><strong>Stacks</strong> follow a <strong>Last-In, First-Out (LIFO)</strong> policy. Imagine a stack of plates in a cafeteria: you place new plates on top and take the top plate when you need one. In a stack, the most recently added element is the first to be removed. This makes stacks ideal for tasks where you need to reverse the order of operations, like handling function calls (recursive ).</p><p><strong>Queues</strong> operate on a <strong>First-In, First-Out (FIFO)</strong> basis. Think of a queue as a line at a ticket counter: the person who joins the line first is the first to be served. Similarly, in a queue, the element that has been in the set the longest is the first to be removed. This approach is perfect for scenarios where you need to process items in the order they arrive, such as managing tasks in a print queue or handling requests in a server.</p><p>In simple words ,Stacks and queues are both dynamic sets, but they differ from each other in the way they operate. The difference lies in their handling of elements: a stack follows a Last-In, First-Out (LIFO) policy, where the most recently added element is the first to be removed, whereas a queue adheres to a First-In, First-Out (FIFO) policy, where the oldest element is removed first.</p><h3>So, Let’s Begin with Stacks</h3><p><strong>Stacks: abstract data structure with following operation</strong></p><h4>core operations:</h4><ul><li><strong>Push(Key)</strong>: Adds a key to the top of the stack, akin to placing a new plate on top of a stack.</li><li><strong>Key Top()</strong>: Retrieves the most recently added key without removing it, similar to peeking at the top plate.</li><li><strong>Key Pop()</strong>: Removes and returns the top key from the stack, just like taking the top plate off the stack.</li><li><strong>Boolean Empty()</strong>: Checks whether the stack is empty, helping determine if there are any elements left.</li></ul><p>To better understand stack operations, let’s look at a common problem that uses stacks: <strong>Balancing Parentheses</strong>. This problem will help us see how stacks handle nested structures and check if parentheses are properly matched.</p><h3>Problem Statement: Balancing Parentheses</h3><p>Given a string of parentheses, brackets, and braces, determine if the sequence is balanced. A sequence is considered balanced if:</p><ol><li>Every opening parenthesis ((, [) has a corresponding closing parenthesis (), ]).</li><li>The parentheses are correctly nested. For example, [()] is balanced, but [(]) is not.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*UaJmCS4s6J00fRhpbRagDA.png" /></figure><p>Here’s the algorithm for solving this problem. Let’s GO through each step to understand how it works.</p><h4>Why Use a Stack?</h4><p>Stacks are a perfect fit for this problem due to their Last-In, First-Out (LIFO) nature. This matches the way nested structures work. Here’s how you can use a stack to solve the balancing problem:</p><ol><li><strong>Set Up Your Stack</strong>: Start with an empty stack to keep track of opening brackets.</li><li><strong>Process the String</strong>:(loop through each character in the string)</li></ol><ul><li><strong>Push</strong>: Whenever you encounter an opening bracket ((, [), push it onto the stack. This keeps track of the brackets that are still waiting to be matched.</li><li><strong>Pop and Match</strong>: When you encounter a closing bracket (), ]), check if it matches the bracket on top of the stack:</li><li>If the stack is empty, it means there’s no opening bracket for the current closing bracket — the string is not balanced.</li><li>If the stack is not empty, pop the top element and check if it matches the closing bracket. If it matches, continue; otherwise, the string is unbalanced.</li></ul><p><strong>Final Check</strong>: Once you’ve processed the entire string, ensure the stack is empty. If it is, all brackets were matched correctly. If not, some opening brackets were never closed.</p><h4>After gaining a deep understanding of how stacks work and how to apply them to problems, let’s explore the low-level implementation of stacks to understand how they function from a lower-level perspective.</h4><p>So, how do you actually implement a stack? Let’s break it down.</p><p>You can easily implement a stack using an array. Start by allocating an array with a predefined maximum size. For the sake of example, let’s say our stack has a maximum size of five elements.</p><h4>Pushing Elements onto the Stack</h4><p>To add an element to the stack, you “push” it onto the array. This involves placing the new element at the next available position in the array. Initially, the array is empty, so the first element, say a, will occupy the first spot. As you add more elements—like b and c—they simply fill in the subsequent positions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*rlFlemIt2VGvz8SqCWkl1g.png" /></figure><p>Each time you push an element, you also increment a variable that tracks the number of elements in the stack. This makes it easy to know how full your stack is at any given moment. Pushing elements is a straightforward operation and is performed in constant time, O(1).</p><h4>Accessing the Top Element</h4><p>Need to know what’s on top of your stack? It’s as simple as looking at the last element you added. Since the stack keeps track of the number of elements, accessing the top element is also an O(1) operation. For example, if you’ve added a, b, and c to the stack, the top element would be c.</p><h4>Popping Elements from the Stack</h4><p>When it’s time to remove an element, you “pop” the top element off the stack. This involves retrieving the last element and then decrementing the element count. For instance, if you pop c, the stack now only contains a and b.</p><h4>Handling Stack Overflow</h4><p>What happens if you try to push another element when the stack is already full? This would cause a stack overflow — an error because there’s no more space in the array.<br><strong>A stack overflow</strong> is a common error that occurs when we try to run code that exceeds the stack’s capacity. This typically happens when a function calls itself recursively without a proper base case, leading to an infinite loop of function calls (<strong>When dealing with function calls, the system uses a stack to manage them. This stack isn’t a fixed size like an array; it grows dynamically until it hits the system’s memory limit)</strong>. As each call is added to the stack, it eventually fills up, causing the program to crash. Another scenario could be when you attempt to push more elements onto a stack than it was designed to hold, surpassing its maximum size and resulting in an overflow error.</p><h4>Checking If the Stack is Empty</h4><p>Finally, to check if the stack is empty, simply see if the element count is zero. If it’s greater than zero, your stack still has elements in it. Again, this is a quick O(1) operation.</p><h3>Handling Wasted Space in Stack Implementations</h3><p>One issue with using an array to implement a stack is the potential for wasted space. If you allocate a large array to allow for a possibly large stack, but only end up using a small portion of it, the unused space is wasted. This is where a linked list can offer a more efficient alternative.</p><p>In a linked list, each element in the list represents an element in the stack. When you push a new item onto the stack, it gets added to the front of the list — essentially transforming a push operation into a PushFront operation. If you want to access the top element, you simply retrieve the head of the list, making Top a TopFront operation. Both pushing and popping elements are O(1) operations, meaning they take constant time regardless of the number of elements.</p><p>One major advantage of using a linked list for your stack is that there’s no predetermined limit on the number of elements you can add. As long as you have available memory, the stack can continue to grow. However, there’s an overhead: each element in the linked list not only stores the data but also a pointer to the next element. This extra space is the trade-off for the flexibility offered by linked lists.</p><p>In contrast, an array-based stack has a fixed maximum size. If you allocate too much space, you risk wasting memory; allocate too little, and you risk running out of space. Despite these differences, both implementations allow for stack operations in constant time, O(1).</p><p>At the end By understanding how stacks work, you can better appreciate how computers manage data and perform tasks. As you keep learning about data structures, remember to think about which one is best for the job at hand.</p><p><strong>thanks for reading happy coding !</strong></p><h3>Resources</h3><p>For those interested in exploring data structures and algorithms further, here are some valuable resources:</p><ul><li><strong>Coursera Course:</strong></li><li><a href="https://www.coursera.org/learn/data-structures/home/module/1">Data Structures on Coursera</a> — An in-depth course that covers a wide range of data structures and their applications.</li><li><strong>Books:</strong></li><li><em>“Introduction to Algorithms”</em> by Cormen, Leiserson, Rivest, and Stein — A comprehensive textbook on algorithms and data structures.</li></ul><p>I encourage you to share your thoughts, experiences, or any questions you have in the comments below. If you found this blog post helpful, please share it with others who might benefit from it. Your feedback and engagement help us create more valuable content!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ba150df49cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Data Structures: Arrays and Linked Lists (Modula 1 Part 1)]]></title>
            <link>https://medium.com/@omarabozeid60/understanding-data-structures-arrays-and-linked-lists-modula-1-part-1-26fb05403b17?source=rss-c7e847b5f304------2</link>
            <guid isPermaLink="false">https://medium.com/p/26fb05403b17</guid>
            <dc:creator><![CDATA[leetcodeWithMe]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 06:20:13 GMT</pubDate>
            <atom:updated>2024-08-13T06:20:13.210Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction and overview</h3><p>As I approach learning a new concept, I begin by understanding the overview and big picture of the topic. This initial step allows me to grasp the overall structure and context before delving into the details.</p><p>So, what are arrays and linked lists? What are their main differences, uses, and real-life applications?</p><p><strong>Array </strong>: Contiguous area of memory consisting of equal-size elements indexed by contiguous integers.</p><p><strong>Linked lists</strong>: A linear data structure used to store a collection of data with the help of nodes.<br>- Characteristics:<br> — Consecutive elements are connected by pointers/references.<br> — The last node points to <strong>null</strong>.<br> — The entry point is called the <strong>head</strong>.<br> — Common variations: Singly, Doubly, Singly Circular, Doubly Circular.</p><h3>Arrays vs. Linked Lists: Choosing the Right Data Structure for Your Needs</h3><p>When diving into data structures, the choice between arrays and linked lists can significantly impact the efficiency and performance of your application. Both have their unique strengths and weaknesses. Let’s explore how they differ and which scenarios are best suited for each.</p><h4>Arrays: The Classic Choice</h4><p><strong>Why Use Arrays?</strong></p><p>Arrays are one of the most fundamental data structures. They’re ideal when you need a collection of elements with a fixed size. Here’s why arrays might be the right choice:</p><ul><li><strong>Fast Access</strong>: Arrays allow for quick access to elements. You can retrieve any item instantly using its index. This constant-time access (O(1)) is perfect for scenarios where speed is crucial, like retrieving specific records or handling data in real-time applications.</li><li><strong>Cache-Friendly</strong>: Since elements are stored in contiguous memory, arrays are efficient for cache utilization. This can make array-based operations faster and more efficient, especially in computational-heavy tasks.</li><li><strong>Simplicity</strong>: Arrays are straightforward to implement and use. Their structure is easy to understand, making them a go-to option for many programming tasks.</li></ul><p><strong>Drawbacks to Consider</strong></p><p>Despite their advantages, arrays have some limitations:</p><ul><li><strong>Fixed Size</strong>: Once you create an array, its size is set. This rigidity can be a drawback if your data size needs to change dynamically.</li><li><strong>Insertions and Deletions</strong>: Adding or removing elements, especially in the middle, can be costly(O(N)) since it requires shifting other elements, leading to potential performance issues.</li></ul><p><strong>Typical Use Cases</strong></p><ul><li><strong>Static Data Storage</strong>: Perfect for storing elements like a list of predefined options or daily temperatures.</li><li><strong>Mathematical Computations</strong>: Ideal for tasks involving matrices or grids, such as in image processing or game development.</li></ul><h4>Linked Lists: Flexibility and Efficiency</h4><p><strong>Why Choose Linked Lists?</strong></p><p>Linked lists offer dynamic memory allocation, making them suitable for various applications:</p><ul><li><strong>Dynamic Size</strong>: Unlike arrays, linked lists can grow and shrink as needed. This flexibility is useful for applications where the number of elements isn’t known in advance or changes frequently.</li><li><strong>Efficient Modifications</strong>: Adding or removing elements, especially at the beginning or middle of the list, is efficient. Linked lists excel in scenarios where frequent insertions and deletions are required.</li><li><strong>Versatility</strong>: They’re often used to implement other data structures like stacks, queues, and deques, making them a foundational tool in many algorithms.</li></ul><p><strong>Challenges to Be Aware Of</strong></p><p>Linked lists are not without their challenges:</p><ul><li><strong>Slower Access Time</strong>: Retrieving an element requires traversing the list from the head, which can be time-consuming (O(n)).</li><li><strong>Memory Overhead</strong>: Each node in a linked list requires additional memory for pointers, which can add up and impact overall memory usage.</li><li><strong>Complexity</strong>: Managing pointers and ensuring correct linkage between nodes can make linked lists more complex to implement and debug.</li></ul><p><strong>Typical Use Cases</strong></p><ul><li><strong>Dynamic Data Structures</strong>: Ideal for applications that require frequent changes to the dataset, such as a playlist in a music player or maintaining a list of active users in a chat application.</li><li><strong>Real-World Systems</strong>: Used in web browsers for managing page history or in operating systems for process scheduling with circular linked lists.</li></ul><h4>Choosing the Right Structure</h4><p><strong>Choose for Arrays When</strong>:</p><ul><li>You need fast, direct access to elements.</li><li>The size of your data is known and doesn’t change.</li><li>Simplicity and ease of use are priorities.</li></ul><p><strong>Choose Linked Lists When</strong>:</p><ul><li>You need a flexible, dynamic structure that can adjust in size.</li><li>Frequent insertions and deletions are part of your operations.</li><li>You’re implementing complex data structures or systems with dynamic data needs.</li></ul><p><strong>After understanding arrays and linked lists, let’s dive into more details about their operations, the cost of these operations, and the technical specifics.</strong></p><h3>Time cost for operation on arrays</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*z7NT1PuL5weV0lgYq8lCGA.png" /></figure><p>Any addition or removal of elements in an array requires adjusting the indices of all subsequent elements. This adjustment leads to a linear time cost, as every element must be shifted to maintain the correct order. However, inserting or removing elements at the end of the array typically requires only a constant amount of work, as there’s no need to shift other elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*6JvySPSmKeDvFWv7FHm5mA.png" /></figure><h4>Next, let’s talk about linked lists. We’ll look at how they work, their operation costs, and what makes them different from arrays. This will help you understand when and why to use linked lists.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*1AAaNrcQWs33wV53KoVtNQ.png" /></figure><p>A <strong>singly linked list</strong> is a type of data structure where each node has two parts:</p><p>1. <strong>Data(key)</strong>: The value or information.<br>2.<strong> Next Pointer</strong>: A link to the next item in the list.</p><p>Each node points to the next one, and the last node points to `null` to show the end of the list. This setup allows easy addition and removal of items, but you have to start from the beginning to find a specific item(without tail).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*optTGIGAOnp9DsVN9es_ng.png" /></figure><h4>Time for some operations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*uJP_8cPDqHor6KUlq0ki9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ZtzMHRE1GwpZlrN9ivda1g.png" /></figure><ul><li>To add a new node to the front of a singly linked list, you simply create a new node and set its <strong>next </strong>pointer to the current head of the list.</li><li>Then, you update the head of the list to point to this new node.</li></ul><p>This process only involves a constant number of steps, regardless of the size of the list. Therefore, the operation is performed in constant time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*E71dVOayVdrAh0z6YDTp-Q.png" /></figure><p><strong>To remove the first item, you just update the list to point to the next item.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*eXwLzzJqIfSe9oanSAtczw.png" /></figure><p><strong>You then get rid of the old first item.</strong> Also This process only involves a constant number of steps, regardless of the size of the list. Therefore, the operation is performed in constant time.</p><p><strong>For pushback, we have two conditions: one with a tail and one without.</strong></p><p>Without a tail pointer:</p><ul><li>Pushing back: If there is no tail pointer, adding an element to the end of the list requires traversing the entire list from the head to find the last node, which takes O(n) time.</li></ul><p>With a tail pointer:</p><ul><li>Pushing back: If there is a tail pointer, adding an element to the end of the list becomes an O(1) operation. You can simply update the next pointer of the current tail node to point to the new node, and then update the tail pointer to the new node.</li></ul><p><strong>The same applies to popback, where we have two conditions: one with a tail and one without</strong></p><p>Without a tail pointer:</p><ul><li>Popping back: If there is no tail pointer, removing the last element from the list requires traversing the entire list from the head to find the second-to-last node. Once the second-to-last node is found, its next pointer needs to be updated to null, and the tail pointer needs to be updated to point to the second-to-last node. This operation takes O(n) time since you have to traverse the entire list.</li></ul><p>With a tail pointer:</p><ul><li>Popping back: If there is a tail pointer, removing the last element from the list becomes more efficient. You can simply update the tail pointer to point to the second-to-last node, and set the next pointer of the second-to-last node to null. This operation still takes O(n) time because you need to traverse the list to find the second-to-last node (and that’s why we have doubly linked list ).</li></ul><p>In summary, having a tail pointer in a linked list does not significantly improve the efficiency of popping back. The time complexity remains O(n) regardless of whether a tail pointer is present or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*84aKC3Y3JRpGNoaw-o7ecQ.png" /></figure><p><strong>As we can see, a problem with singly linked lists is that some operations can be expensive.</strong></p><p>There is a way to make popping the back and adding elements before the current one more efficient. The issue we faced was that while we could move from one element to the next, we couldn’t easily move back to the previous one. A doubly-linked list solves this problem by introducing a way to traverse both directions. We achieve this by adding two pointers to each node: a forward pointer and a back pointer. Conceptually, this creates a bidirectional link between nodes. In practice, this is implemented by adding an extra pointer to the node. For example, in a doubly-linked list, a node containing the value 10 would have a ‘next’ pointer pointing to the node with value 4, and a ‘previous’ pointer pointing to the node with value 7. This allows traversal in both directions, enabling us to move forward or backward from any given node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*4XyFl0BmwNTM62S9kCHYjQ.png" /></figure><h4>Coach</h4><p>In a doubly linked list, the pop back operation removes the last element from the list. Here’s how it works:</p><p>The tail pointer of the doubly linked list is updated to point to the previous element, which becomes the new last element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*ZiQYp6oL076Jq93swsMJQg.png" /></figure><p>The next pointer of the new last element is set to nil, indicating that it is now the last element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*ithTGP9K-ro2cbZwd59gSA.png" /></figure><p>Finally, the node that was removed is deleted from memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*VkH0JiF2GFot0UNbUrnz6A.png" /></figure><p>This operation has a time complexity of O(1) because accessing the tail pointer and updating the pointers can be done in constant time.</p><p>By adding a previous pointer in addition to the next pointer, a doubly linked list allows for bidirectional traversal. This means that we can easily navigate both forward and backward through the list, making operations like pop back more efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*Lsh9nD-8CNgF-rBS3gaG2Q.png" /></figure><h4>So now we’ve solved the problem with popback :)</h4><p><strong>One thing to point out as we contrast arrays versus linked lists</strong></p><p>One key difference between arrays and linked lists is the concept of random access. In arrays, we have random access, meaning that accessing any element takes constant time. This makes operations like binary search straightforward; you can start searching in the middle of the array, and if the array is sorted, quickly determine which side to continue searching on. However, this approach doesn’t work with linked lists. In a linked list, finding the middle element is an expensive operation because you have to start at either the head or the tail and traverse to the middle. This makes it an O(n) operation to access any particular element, which is a significant difference compared to arrays.</p><p>Linked lists have an advantage over arrays in that they offer constant-time insertion and removal operations at the front. In contrast, with arrays, inserting or removing elements from the front takes O(n) time because you have to shift many elements. For a doubly-linked list with a tail pointer, operations at the end of the list are also constant time. However, finding an arbitrary element in a linked list is a linear-time operation because the elements are not contiguous like in an array. Instead, each element is stored in a separately allocated memory location with pointers linking them. With a doubly-linked list, it is also constant time to insert or remove nodes between other nodes.</p><h3>Resources</h3><p>For those interested in exploring data structures and algorithms further, here are some valuable resources:</p><ul><li><strong>Coursera Course:</strong></li><li><a href="https://www.coursera.org/learn/data-structures/home/module/1">Data Structures on Coursera</a> — An in-depth course that covers a wide range of data structures and their applications.</li><li><strong>Books:</strong></li><li><em>“Introduction to Algorithms”</em> by Cormen, Leiserson, Rivest, and Stein — A comprehensive textbook on algorithms and data structures.</li></ul><p>I encourage you to share your thoughts, experiences, or any questions you have in the comments below. If you found this blog post helpful, please share it with others who might benefit from it. Your feedback and engagement help us create more valuable content!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26fb05403b17" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>