<?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 Ifte Refat on Medium]]></title>
        <description><![CDATA[Stories by Ifte Refat on Medium]]></description>
        <link>https://medium.com/@ifte_refat?source=rss-dd7950de1317------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WAtGXkSod8WBINh7FQGk4Q.jpeg</url>
            <title>Stories by Ifte Refat on Medium</title>
            <link>https://medium.com/@ifte_refat?source=rss-dd7950de1317------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:49:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ifte_refat/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 the Fractional Knapsack Problem]]></title>
            <link>https://medium.com/@ifte_refat/understanding-the-fractional-knapsack-problem-f447ddc9c4bf?source=rss-dd7950de1317------2</link>
            <guid isPermaLink="false">https://medium.com/p/f447ddc9c4bf</guid>
            <dc:creator><![CDATA[Ifte Refat]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 14:27:23 GMT</pubDate>
            <atom:updated>2024-09-13T14:27:23.077Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4FlRAmNOeodkXE4MdhNhg.jpeg" /><figcaption>bag picture</figcaption></figure><h3>Introduction</h3><p>Have you ever been in a situation where you need to pick the best candies with a limited bag size? Imagine you’re at a candy shop, and you have a small backpack that can only carry up to 10kg. You want to grab the most delicious (and expensive) candies, but some are heavier than others. What would be your strategy?</p><p>This scenario is similar to a well-known problem in computer science called the <strong>Knapsack Problem</strong>. Let’s dive into it!</p><h3>What is the Knapsack Problem?</h3><p>In the knapsack problem, you have a collection of items, and each item has two things:</p><ul><li><strong>Weight</strong> (how heavy it is)</li><li><strong>Value</strong> (how valuable or useful it is)</li></ul><p>The goal is to pick items to maximize the value you carry, without exceeding the weight limit of the knapsack (your bag).</p><h4>Two Versions of the Problem</h4><ol><li><strong>0/1 Knapsack</strong>: You either take the whole item or leave it (you can’t break an item).</li><li><strong>Fractional Knapsack</strong>: You can take parts of an item. For example, if an item weighs 5kg, and you only have space for 2kg, you can take 2/5 of that item.</li></ol><p>In this post, we’ll focus on the <strong>Fractional Knapsack Problem</strong>, where you can break items and take fractions of them to maximize the total value. And to solve it, we’ll use something called a <strong>Greedy Algorithm</strong>.</p><h3>Breaking Down the Problem</h3><h4>The Objective</h4><p>You have a list of n items, each with a specific weight and value. Your task is to fill a knapsack with a maximum weight capacity W, such that the total value you carry is as high as possible.</p><h4>The Trick: Maximize Value-to-Weight Ratio</h4><p>In the fractional knapsack problem, the best approach is to pick items that give you the most value for the least weight. This is known as <strong>value-to-weight ratio</strong>.</p><ul><li>If one item has a value of 100 and a weight of 2kg, its ratio is 100/2 = 50.</li><li>Another item with a value of 50 and weight of 2kg has a ratio of 50/2 = 25.</li></ul><p>Obviously, the first item gives you more “value per kilogram,” so you’d want to prioritize it.</p><h3>The Algorithm</h3><p>Here’s how we solve the fractional knapsack problem:</p><ol><li><strong>Sort the items</strong> by value-to-weight ratio in descending order (highest ratio first).</li><li><strong>Start filling the knapsack</strong> with the item that has the highest ratio.</li><li>If you can’t fit the entire item, take only the fraction that fits in the remaining space.</li></ol><p>To do this efficiently, we can represent each item as a structure in C++ and sort them using a comparison function.</p><h3>C++ Code for Fractional Knapsack</h3><p>Let’s see how we can implement this algorithm in C++.</p><h4>Step 1: Structure to Represent Items</h4><p>We’ll define a structure Item to hold the value and weight of each item.</p><pre>struct Item {<br>    int value, weight;<br>};</pre><h4>Step 2: Custom Comparison Function</h4><p>We need to sort items based on their value-to-weight ratio. For that, we can write a comparison function:</p><pre>bool cmp(Item a, Item b) {<br>    double r1 = (double)a.value / a.weight;<br>    double r2 = (double)b.value / b.weight;<br>    return r1 &gt; r2;<br>}</pre><p>This function will return true if the ratio of item a is greater than that of item b. We will use this to sort the items in decreasing order of their value-to-weight ratio.</p><h4>Step 3: Main Function</h4><p>Now, let’s write the <em>fractionalKnapsack</em> function to solve the problem.</p><pre>double fractionalKnapsack(int W, Item arr[], int n) {<br>    // Sort items based on value-to-weight ratio<br>    sort(arr, arr + n, cmp);<br>double totalValue = 0.0; // Total value in knapsack<br>    for (int i = 0; i &lt; n; i++) {<br>        // If the item can fully fit into the knapsack<br>        if (arr[i].weight &lt;= W) {<br>            W -= arr[i].weight;<br>            totalValue += arr[i].value;<br>        }<br>        // If the item cannot fully fit, take the fraction of it<br>        else {<br>            totalValue += arr[i].value * ((double)W / arr[i].weight);<br>            break;<br>        }<br>    }<br>    <br>    return totalValue;<br>}</pre><h4>Step 4: Example Usage</h4><p>Let’s say we have three items:</p><ul><li>Item 1: Value = 60, Weight = 10</li><li>Item 2: Value = 100, Weight = 20</li><li>Item 3: Value = 120, Weight = 30</li></ul><p>And the knapsack can hold a maximum weight of 50.</p><pre>int main() {<br>    Item arr[] = {{60, 10}, {100, 20}, {120, 30}};<br>    int W = 50;<br>    int n = sizeof(arr) / sizeof(arr[0]);<br>cout &lt;&lt; &quot;Maximum value we can obtain = &quot; &lt;&lt; fractionalKnapsack(W, arr, n);<br>    return 0;<br>}</pre><p>This will output</p><pre>Maximum value we can obtain = 240</pre><p>How does it work? The algorithm takes the full first and second items, and only a fraction of the third item, maximizing the value carried in the knapsack.</p><h3>Explaining the Code</h3><ol><li><strong>Sorting</strong>: We first sort the items based on their value-to-weight ratio using the <em>cmp</em> function.</li><li><strong>Filling the Knapsack</strong>: The loop checks if an item can fit in the knapsack. If it does, we take the whole item. Otherwise, we take only the fraction that fits and then stop.</li><li><strong>Result</strong>: The total value in the knapsack is stored in the <em>totalValue</em> variable.</li></ol><h3>Conclusion</h3><p>The <strong>Fractional Knapsack Problem</strong> is a great example of using a greedy algorithm to maximize the value you can carry. By sorting the items based on their value-to-weight ratio and filling the knapsack with the most valuable items first, you can quickly arrive at the best solution.</p><p>If you enjoyed this algorithm, try implementing it yourself in C++, and even experiment with different sets of items! And if you’re feeling adventurous, look up the <strong>0/1 Knapsack Problem</strong> and see how it compares.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f447ddc9c4bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Riddle of Code Efficiency: Understanding Time Complexity with Examples]]></title>
            <link>https://medium.com/@ifte_refat/solving-riddle-of-code-efficiency-understanding-time-complexity-with-examples-3aaf4b363af0?source=rss-dd7950de1317------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aaf4b363af0</guid>
            <category><![CDATA[time-complexity]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ifte Refat]]></dc:creator>
            <pubDate>Sat, 27 Jan 2024 16:25:04 GMT</pubDate>
            <atom:updated>2024-01-27T16:25:04.396Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>In the coding world, we often want to know how fast or slow our code is, especially when dealing with large amounts of data. Big-O notation is like a cheat sheet that helps us understand and compare the efficiency of different code solutions.</p><h3>What’s Big-O Notation?</h3><p>Big-O notation is a fancy way of saying, “Hey, how does the speed of our code change when we throw more stuff at it?” It’s like predicting how your favorite game might slow down when there are too many players. In one line it’s like comparing the efficiency of different code solutions.</p><h3>Why Do We Care About Time Complexity?</h3><p>Imagine we have a magic recipe to solve a problem. Time complexity helps us figure out if our recipe is great for a few friends (small problems) or a big party (huge problems). It helps us choose the right solution based on how much work our computer needs to do. It’s like measuring the capability of your code on a broad factor.</p><h3>Asymptotic notation simplification</h3><p>Imagine you have an algorithm, and someone tells you its time complexity is <em>T</em>(<em>n</em>)=3<em>n²+2n</em>+1, where <em>n</em> is the size of the input.</p><p>Now, we want to make this simpler to understand:</p><ol><li><strong>Find the Big Part:</strong></li></ol><p>Look at the terms and find the one that grows the fastest. In our case, it’s 3n^2.</p><p>2)<strong>Ignore the Smaller Parts:</strong></p><p>Forget about the terms that don’t grow as fast. Here, 2<em>n</em> and 1 are not as important.</p><p><em>T</em>(<em>n</em>) simplifies to <em>O</em>(<em>n</em>2)</p><ul><li>We don’t worry about the exact number (3) because we care more about how things grow.</li></ul><p>So, instead of saying <em>T</em>(<em>n</em>)=3<em>n</em>2+2<em>n</em>+1, we can simply say the time complexity is <em>O</em>(*n^*2). This way, we express how the algorithm’s performance changes as the input gets larger in a much simpler way. <strong>There’s a big mathematical description about this topic but we skip the boring part.</strong></p><h3>Big-O Notation: Code Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZlYIBLyEdKqQ5uhtDzqvw.jpeg" /></figure><ol><li><strong>O(1) — Constant Time:</strong></li></ol><p><strong>Example:</strong> Accessing an element in an array using its index.<strong>Visual Representation:</strong> A flat line because it takes the same amount of time regardless of the input size.</p><p><strong>O(log n) — Logarithmic Time:</strong></p><ul><li><strong>Example:</strong> Binary search in a sorted array.</li><li><strong>Visual Representation:</strong> A gradually increasing curve, showing that the algorithm becomes less sensitive to input size as it grows.</li></ul><pre>    def binary_search(arr, target):<br>        &quot;&quot;&quot;<br>        Binary search implementation with logarithmic time complexity.<br>    <br>        Parameters:<br>        - arr: A sorted list of elements.<br>        - target: The element to search for in the list.<br>    <br>        Returns:<br>        - index: The index of the target element if found, otherwise -1.<br>        &quot;&quot;&quot;<br>        low, high = 0, len(arr) - 1<br>    <br>        while low &lt;= high:<br>            mid = (low + high) // 2  # Calculate the middle index<br>    <br>            if arr[mid] == target:<br>                return mid  # Target found, return the index<br>            elif arr[mid] &lt; target:<br>                low = mid + 1  # Discard the left half<br>            else:<br>                high = mid - 1  # Discard the right half<br>    <br>        return -1  # Target not found in the list<br>    <br>    # Example Usage:<br>    sorted_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]<br>    target_element = 7<br>    <br>    result = binary_search(sorted_list, target_element)<br>    if result != -1:<br>        print(f&quot;Element {target_element} found at index {result}.&quot;)<br>    else:<br>        print(f&quot;Element {target_element} not found in the list.&quot;)</pre><p><strong>O(n) — Linear Time:</strong></p><ul><li><strong>Example:</strong> Finding the maximum element in an unsorted array by scanning each element once.</li><li><strong>Visual Representation:</strong> A straight line, indicating a direct relationship between the input size and the algorithm’s performance.</li></ul><pre>  def linear_search(arr, target):<br>      &quot;&quot;&quot;<br>      Linear search implementation with linear time complexity.<br>  <br>      Parameters:<br>      - arr: A list of elements.<br>      - target: The element to search for in the list.<br>  <br>      Returns:<br>      - index: The index of the target element if found, otherwise -1.<br>      &quot;&quot;&quot;<br>      for i in range(len(arr)):<br>          if arr[i] == target:<br>              return i  # Target found, return the index<br>  <br>      return -1  # Target not found in the list<br>  <br>  # Example Usage:<br>  example_list = [3, 7, 1, 9, 4, 6, 8, 2, 5]<br>  target_element = 6<br>  <br>  result = linear_search(example_list, target_element)<br>  if result != -1:<br>      print(f&quot;Element {target_element} found at index {result}.&quot;)<br>  else:<br>      print(f&quot;Element {target_element} not found in the list.&quot;)</pre><p><strong>O(n log n) — Linearithmic Time:</strong></p><ul><li><strong>Example:</strong> Many efficient sorting algorithms like Merge Sort and Heap Sort.</li><li><strong>Visual Representation:</strong> A curve that grows faster than linear but not as fast as quadratic. It’s often more efficient than O(n²) for large datasets.</li><li>Merge Sort implementation with linearithmic time complexity.</li></ul><p><strong>O(n²) — Quadratic Time:</strong></p><ul><li><strong>Example:</strong> Nested loops to compare all pairs of elements in an array (Bubble Sort).</li><li><strong>Visual Representation:</strong> An upward-sloping curve, indicating that the algorithm’s performance grows quadratically with the input size.</li></ul><p><strong>O(2^n) — Exponential Time:</strong></p><ul><li><strong>Example:</strong> Brute-force solutions for problems like the Traveling Salesman Problem.</li><li><strong>Visual Representation:</strong> A very steep curve, showing a significant increase in time as the input size grows. This is generally less efficient and should be avoided for large datasets.</li></ul><h3>Wrapping Up</h3><p>Big-O notation is our secret code to talk about how fast our code can handle different amounts of work. By keeping things simple and visualizing with graphs, we become coding superheroes, ready to tackle any challenge efficiently!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aaf4b363af0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Selection Sort: A Step-by-Step Guide with Examples]]></title>
            <link>https://medium.com/@ifte_refat/understanding-selection-sort-a-step-by-step-guide-with-examples-a898529b64f1?source=rss-dd7950de1317------2</link>
            <guid isPermaLink="false">https://medium.com/p/a898529b64f1</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Ifte Refat]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 14:40:56 GMT</pubDate>
            <atom:updated>2024-01-25T14:45:26.158Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction:</h4><p>Sorting is like tidying up your room, but for computers. They have different ways of doing it, and one basic method is called Selection Sort. This blog post will help you understand Selection Sort from the ground up, with easy explanations and a hands-on example.</p><h4>Understanding Selection Sort:</h4><p>Think of Selection Sort as organizing a deck of cards. You go through the deck, find the smallest card, and put it at the beginning. Then, you repeat this process until the whole deck is sorted.</p><h4>Step-by-Step Guide to Selection Sort:</h4><h4>Getting Started:</h4><p>Imagine you have a list of numbers, like [4, 8, 1, 19, 3, 6].</p><p>Pretend the list has two parts: the sorted part (currently empty) and the unsorted part (the whole list).</p><h4>Finding the Smallest Number:</h4><p>Look at the unsorted part and find the smallest number.</p><p>Remember where you found it; this is like marking the smallest card in our deck.</p><h4>Swapping Numbers:</h4><p>Swap the smallest number you found with the first number in the unsorted part.</p><p>It&#39;s like putting the smallest card at the beginning of the deck.</p><h4>Moving On:</h4><p>Move the imaginary line between the sorted and unsorted parts one step to the right.</p><p>Now, the sorted part has one more number, and the unsorted part has one less.</p><h4>Repeat Until Done:</h4><p>Keep finding the smallest number, swapping it, and moving the line until the whole list is sorted.</p><h4>Complexity Check:</h4><p>Selection Sort has a time complexity of O(n^2) in the worst and average cases.</p><p>It has a space complexity of O(1) since it doesn&#39;t require additional memory.</p><h4>Example of Selection Sort:</h4><p>Let’s use our list [4, 8, 1, 19, 3, 6] to see how Selection Sort works.</p><h4>Start:</h4><p>Unsorted: [4, 8, 1, 19, 3, 6]</p><p>Sorted: []</p><h4>Iteration 1:</h4><p>Find 1 (at index 2), swap with 4.</p><p>Unsorted: [1, 8, 4, 19, 3, 6]</p><p>Sorted: [ ]</p><h4>Iteration 2:</h4><p>Find 3 (at index 4), swap with 1.</p><p>Unsorted: [3, 8, 4, 19, 1, 6]</p><p>Sorted: [1]</p><h4>Iterations 3-6:</h4><p>Repeat until the list is sorted.</p><p>Finish:</p><p>Sorted List: [1, 3, 4, 6, 8, 19]</p><pre>#include&lt;iostream&gt;<br>using namespace std;<br><br>// Function to input elements into the array<br>void scanArray(int arrayToScan[], int size) {<br>    for (int i = 0; i &lt; size; i++) {<br>        cin &gt;&gt; arrayToScan[i];<br>    }<br>}<br><br>// Function to print elements of the array<br>void printArray(int arrayToPrint[], int size) {<br>    for (int i = 0; i &lt; size; i++) {<br>        cout &lt;&lt; arrayToPrint[i] &lt;&lt; &quot; &quot;;<br>    }<br>}<br><br>// Function to perform selection sort on the array<br>void selectionSort(int arrayToSort[], int size) {<br>    for (int i = 0; i &lt; size - 1; i++) {<br>        // Assume the current index is the minimum<br>        int minIndex = i;<br><br>        // Loop to find the index of the minimum element in the unsorted part<br>        for (int j = i + 1; j &lt; size; j++) {<br>            if (arrayToSort[j] &lt; arrayToSort[minIndex])<br>                minIndex = j;<br>        }<br><br>        // Swap the found minimum element with the element at the current index<br>        if (minIndex != i)<br>            swap(arrayToSort[i], arrayToSort[minIndex]);<br>    }<br>}<br><br>int main() {<br>    // Set the size of the array<br>    int arraySize = 10;<br><br>    // Declare an array of size &#39;arraySize&#39;<br>    int myArray[arraySize];<br><br>    // Input elements into the array<br>    scanArray(myArray, arraySize);<br><br>    // Perform selection sort on the array<br>    selectionSort(myArray, arraySize);<br><br>    // Print the sorted array<br>    printArray(myArray, arraySize);<br><br>    return 0;<br>}<br></pre><h4>Conclusion:</h4><p>Selection Sort might not be the fastest, but it&#39;s a simple way to understand how computers sort things.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a898529b64f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Insertion Sorting: A Comprehensive Guide to Insertion Sort]]></title>
            <link>https://medium.com/@ifte_refat/mastering-insertion-sorting-a-comprehensive-guide-to-insertion-sort-3d466e33e70e?source=rss-dd7950de1317------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d466e33e70e</guid>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[sorting]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <dc:creator><![CDATA[Ifte Refat]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 14:17:07 GMT</pubDate>
            <atom:updated>2024-01-24T14:53:17.510Z</atom:updated>
            <content:encoded><![CDATA[<p>.</p><h4>Introduction:</h4><p>Sorting things is like putting them in order. Imagine you have a bunch of numbers, and you want to arrange them from smallest to biggest. One way to do this is by using a neat trick called &quot;Insertion Sort.&quot; It&#39;s like organizing a deck of cards in your hand!</p><h4>Step-by-Step Example:</h4><p>Let&#39;s sort a list of numbers:</p><p>5, 2, 9, 1, 5, 6.</p><p><strong>Step 1: Initial State</strong></p><p>We start with the first number (5) as our sorted part.<br>The unsorted part is</p><p>2, 9, 1, 5, 6.<br><strong>Sorted</strong>: [5]<br><strong>Unsorted</strong>: [2, 9, 1, 5, 6]<br><strong>Sorted</strong>: [5] <strong>Unsorted</strong>: [2, 9, 1, 5, 6]</p><p><strong>Step 2:</strong> Insert 2 into the Sorted Part</p><p>Compare 2 with 5. Since 2 is smaller, it goes before 5.<br><strong>Sorted</strong>: [2, 5]<br><strong>Unsorted</strong>: [9, 1, 5, 6]<br><strong>Sorted</strong>: [2, 5] <strong>Unsorted</strong>: [9, 1, 5, 6]</p><p><strong>Step 3:</strong> Insert 9 into the Sorted Part</p><p>9 is bigger than 5, so it stays in its place.<br><strong>Sorted</strong>: [2, 5, 9]<br><strong>Unsorted</strong>: [1, 5, 6]<br><strong>Sorted</strong>: [2, 5, 9] <strong>Unsorted</strong> :[1,5, 6]</p><p><strong>Step 4:</strong> Insert 1 into the Sorted Part</p><p>Compare 1 with 9, then 5, and finally 2. Move them to make space for 1.<br><strong>Sorted</strong>: [1, 2, 5, 9]<br><strong>Unsorted</strong>: [5, 6]<br><strong>Sorted</strong>: [1, 2, 5, 9] <strong>Unsorted</strong>: [5, 6]</p><p><strong>Step 5:</strong> Insert 5 into the Sorted Part</p><p>5 is already in the right spot.<br><strong>Sorted</strong>: [1, 2, 5, 9]<br><strong>Unsorted</strong>: [6]<br><strong>Sorted</strong>: [1, 2, 5, 9] <strong>Unsorted</strong>: [6]</p><p><strong>Step 6:</strong> Insert 6 into the Sorted Part</p><p>Compare 6 with 9, then 5. Move them to make space for 6.<br><strong>Sorted</strong>: [1, 2, 5, 6, 9]<br><strong>Unsorted</strong>: []<br><strong>Sorted</strong>: [1, 2, 5, 6, 9] <strong>Unsorted</strong>: []</p><p><strong>Step 7:</strong> Final Sorted List</p><p>The numbers are now in order!<br>Sorted: [1, 2, 5, 6, 9]<br>Unsorted: []<br><strong>Sorted</strong>: [1, 2, 5, 6, 9]Unsorted: []</p><h4>Time Complexity:</h4><p>Insertion Sort has an average and worst-case time complexity of <br>O(n^2), where n is the number of elements in the array. However, its best-case time complexity is O(n) when the array is already sorted.</p><pre>#include&lt;iostream&gt;<br>using namespace std;<br><br>void scanArray(int arr[], int size) {<br>    for (int i = 0; i &lt; size; i++) {<br>        cin &gt;&gt; arr[i];<br>    }<br>}<br><br>void printArray(int arr[], int size) {<br>    for (int i = 0; i &lt; size; i++) {<br>        cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;<br>    }<br>}<br><br>void insertSort(int arr[], int sizee) {<br>    for (int i = 0; i &lt; sizee; i++) {<br>        int j = i;<br>        while (j &gt; 0 and arr[j - 1] &gt; arr[j]) {<br>            // Swap adjacent elements if they are in the wrong order<br>            swap(arr[j], arr[j - 1]);<br>            j--;<br>        }<br>        // Uncomment the line below to visualize each step of the sorting process<br>        // printArray(arr, sizee);<br>    }<br>}<br><br>int main() {<br>    int n = 10;<br>    int arr[n];<br><br>    // Input array elements<br>    scanArray(arr, n);<br><br>    // Sort the array using Insertion Sort<br>    insertSort(arr, n);<br><br>    // Print the sorted array<br>    printArray(arr, n);<br><br>    return 0;<br>}<br><br></pre><p>Now, the insertSort function includes a comment to visualize each step of the sorting process. Uncomment the line //printArray(arr, sizee);</p><p>to see the array at each step of the Insertion Sort algorithm.</p><h4>Conclusion:</h4><p>Insertion Sort is like playing cards or sorting toys. It&#39;s not the fastest for lots of things, but it&#39;s handy when you don&#39;t have too much stuff to organize. Learning Insertion Sort helps us understand how to arrange things in order</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d466e33e70e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Trees Unpacked]]></title>
            <link>https://medium.com/@ifte_refat/binary-trees-unpacked-7e0d84c75fba?source=rss-dd7950de1317------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e0d84c75fba</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[searching-algorithm]]></category>
            <category><![CDATA[binary-tree]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Ifte Refat]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 05:18:23 GMT</pubDate>
            <atom:updated>2024-01-24T14:24:37.048Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>In the world of computer science, binary trees are like family trees for data. They help organize information in a special way. Let’s take a closer look at what makes binary trees interesting and useful.</p><h4>What’s a Binary Tree?</h4><p>Imagine data arranged like a tree. In a binary tree, each member (node) can have, at most, two kids - a left one and a right one. The top node is the &quot;boss&quot; or root, and those with no kids are like the leaves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*napEAlCkyNMMA7LQtrJZZg.png" /></figure><h4>Real-Life Example:Family Tree</h4><p>Just like a binary tree, a family tree represents relationships in a structured way. Each person in the family has a specific place in the tree, with parents branching into children.</p><h4>Parts of a Tree Node:</h4><p>Think of a node like a data box. Each box has a value (the data it holds) and two arrows pointing to its left and right kids.</p><pre>class TreeNode:<br>    def __init__(self, value):<br>        self.value = value<br>        self.left = None<br>        self.right = None<br></pre><h4>Interesting Facts about Binary Trees</h4><h4><strong>Maximum Nodes on Each Level</strong></h4><p>On each level of the tree, there can be lots of nodes. If it&#39;s the first level (the root), there&#39;s only one node. For the next level, there can be two, and it keeps doubling.</p><h4>Maximum Nodes in a Tree</h4><p>If a tree has a height of &#39;h&#39;, the most nodes it can have is &#39;2^h - 1&#39;. This is like having a full family tree.</p><h4>Minimum Nodes in a Tree</h4><p>The least nodes a tree can have is &#39;h + 1&#39;. This happens when each level is filled, except maybe the last one.</p><h4>Different Kinds of Binary Trees</h4><h4>Full Binary Tree</h4><p>Every node in this tree has either 0 or 2 kids. No middle child here!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*v2jj6oTqox_QLdTz0a1CCQ.png" /></figure><h4>Complete Binary Tree</h4><p>This tree&#39;s levels are filled from the left, and it tries to be as compact as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*5T2-3gNnUaENfacZ58afQw.png" /></figure><h4>Perfect Binary Tree</h4><p>Every level is full – it&#39;s like having the perfect family size at every generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*xDw4qN0eiL2W_AI42eOz8w.png" /></figure><h4>Balanced Binary Tree</h4><p>The left and right parts of the tree aren&#39;t too different in height. It&#39;s like having a balanced family album.</p><h4>Walking through a Tree - Traversal</h4><p>Going through a tree is like taking a stroll, but in a specific order.</p><h4>Inorder Traversal</h4><p>You start from the left, then check the middle, and finally go to the right.</p><pre># Inorder Traversal<br>def inorder_traversal(node):<br>    &quot;&quot;&quot;<br>    Inorder traversal: left -&gt; root -&gt; right<br>    &quot;&quot;&quot;<br>    if node:<br>        # Traverse the left subtree<br>        inorder_traversal(node.left)<br>        # Visit the root<br>        print(node.value, end=&quot; &quot;)<br>        # Traverse the right subtree<br>        inorder_traversal(node.right)<br></pre><h4>Preorder Traversal</h4><p>You begin with the middle (root), then move to the left, and end on the right.</p><pre># Preorder Traversal<br>def preorder_traversal(node):<br>    &quot;&quot;&quot;<br>    Preorder traversal: root -&gt; left -&gt; right<br>    &quot;&quot;&quot;<br>    if node:<br>        # Visit the root<br>        print(node.value, end=&quot; &quot;)<br>        # Traverse the left subtree<br>        preorder_traversal(node.left)<br>        # Traverse the right subtree<br>        preorder_traversal(node.right)<br></pre><h4>Postorder Traversal</h4><p>It’s the opposite: left first, then right, and finally, you check the root.</p><pre># Postorder Traversal<br>def postorder_traversal(node):<br>    &quot;&quot;&quot;<br>    Postorder traversal: left -&gt; right -&gt; root<br>    &quot;&quot;&quot;<br>    if node:<br>        # Traverse the left subtree<br>        postorder_traversal(node.left)<br>        # Traverse the right subtree<br>        postorder_traversal(node.right)<br>        # Visit the root<br>        print(node.value, end=&quot; &quot;)<br></pre><h4>Where Trees Work in Real Life</h4><p>Trees help out in many areas, like:</p><h4>Expression Trees</h4><p>They&#39;re like math trees, making sure equations are solved the right way.</p><h4>Binary Search Trees</h4><p>These trees organize information so you can find things quickly – like a well-arranged bookshelf.</p><h4>Huffman Coding</h4><p>This is a fancy way of squeezing data. Binary trees help in this clever process.</p><h4>File System Organization</h4><p>Just like how you organize files in folders, binary trees help organize information in computer systems.</p><h4>Conclusion</h4><p>In conclusion, binary trees are a foundational concept in computer science with applications in various domains. Understanding their structure, properties, and traversal methods is essential for anyone working with algorithms and data structures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e0d84c75fba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connecting the Dots: Floyd’s Cycle Detection Algorithm and Real-Life Scenarios]]></title>
            <link>https://medium.com/@ifte_refat/connecting-the-dots-floyds-cycle-detection-algorithm-and-real-life-scenarios-b4ecaf8daa2d?source=rss-dd7950de1317------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4ecaf8daa2d</guid>
            <category><![CDATA[linked-list-cycle]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Ifte Refat]]></dc:creator>
            <pubDate>Tue, 16 Jan 2024 16:40:45 GMT</pubDate>
            <atom:updated>2024-01-16T16:53:14.972Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*k-JU3sZV8t2rh7PeUG18Jg.jpeg" /><figcaption>Collected from Pinterest</figcaption></figure><h4>Introduction:</h4><p>Floyd’s Cycle Detection Algorithm, also known as the Hair and Tortoise Algorithm, is a clever concept in computer science. This algorithm helps us find repeating patterns in a list of things, like numbers or objects. We can compare how it works to real-life situations to better understand it. In this blog, we&#39;ll explore the Floyd’s Cycle Detection Algorithm, explain how it works using simple math, and show how it can be related to everyday life.</p><h4>Understanding Floyd&#39;s Cycle Detection Algorithm:</h4><p>Floyd’s Cycle Detection Algorithm uses two pointers to go through a list of things. One pointer moves faster (the ‘hair’), and the other moves slower (the ‘tortoise’). By comparing where these pointers are, the algorithm figures out if there’s a repeating pattern in the list.</p><h4>Real-Life Analogy:</h4><p>Think of two cyclists on a circular track – one cyclist goes faster (‘hair’), while the other takes it easy (‘tortoise’). By watching where they are at different times, we can tell if they’ll meet again, which shows there’s a repeating pattern in their journey.</p><h4>Mathematical Explanation:</h4><p>In simple math terms, let’s say we have a starting point ‘a’, a meeting point ‘b’ inside the repeating pattern, and the length of the repeating pattern ‘c’. When the slower pointer reaches step ‘k’, the faster pointer is at step ‘2k’. There’s an actual mathematical explanation where it’s proved why exactly the both pointers meet . We will overlook that right now because that is kinda theoretical,we now focus on actions xD.</p><h4>Algorithmic Procedure:</h4><p>1. Start with two pointers at the beginning of the linked list.<br>2. Move the slower pointer one step at a time and the faster pointer two steps at a time.<br>3. If the two pointers meet, there is a cycle. If the faster pointer reaches the end of the list, there’s no cycle.<br>4. If a cycle is detected, we can find the start of the cycle by using the meeting point of the two pointers.</p><pre># Definition of a node in the linked list<br><br>class ListNode:<br><br>	def __init__(self, value):<br><br>    	self.val = value<br><br>    	self.next = None<br><br><br><br><br># Function to detect a cycle in a linked list using Floyd&#39;s Cycle Detection Algorithm<br><br>def detectCycle(head):<br><br>	# Initialize the hair and tortoise pointers<br><br>	hair = head<br><br>	tortoise = head<br><br>	<br><br>	# Move the pointers until they meet or reach the end of the list<br><br>	while hair and hair.next:<br><br>    	tortoise = tortoise.next  # Tortoise moves one step<br><br>    	hair = hair.next.next 	# Hair moves two steps<br><br>    	if tortoise == hair:   	# If the pointers meet, a cycle is detected<br><br>        	return True<br><br>	<br><br>	# No cycle found<br><br>	return False<br><br><br><br><br># Example usage<br><br># Create a linked list with a cycle<br><br>head  = ListNode(3)<br><br>node2 = ListNode(2)<br><br>node3 = ListNode(0)<br><br>node4 = ListNode(2)<br><br><br><br>head.next = node2<br><br>node2.next = node3<br><br>node3.next = node4<br><br>node4.next = node2  # This creates a cycle, as node4 points back to node2<br><br><br><br><br># Call the detectCycle function and print the result<br><br>print(detectCycle(head))  # This should print True since the linked list contains a cycle<br><br><br></pre><h4>Conclusion:</h4><p>Floyd’s Cycle Detection Algorithm is a valuable tool for handling linked data structures. Understanding how it works and its practical applications can help developers manage data effectively. Its real-life example shows how this algorithm is more than just a theory and can be applied to real-world scenarios for practical purposes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4ecaf8daa2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Priority Queue Data Structure Unpacked : A task scheduler perspective]]></title>
            <link>https://medium.com/@ifte_refat/priority-queue-data-structure-unpacked-a-task-scheduler-perspective-082cafc7a9e5?source=rss-dd7950de1317------2</link>
            <guid isPermaLink="false">https://medium.com/p/082cafc7a9e5</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[priority-queue]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ifte Refat]]></dc:creator>
            <pubDate>Fri, 12 Jan 2024 21:33:43 GMT</pubDate>
            <atom:updated>2024-01-12T21:33:43.856Z</atom:updated>
            <content:encoded><![CDATA[<p>A priority queue is like a special to-do list where each task has its own level of importance. Unlike a regular to-do list, where tasks are done in the order they are added, a priority queue makes sure the most important task gets done first.</p><h4>What&#39;s Inside a Priority Queue?</h4><h4>Adding Tasks (Enqueue):</h4><p>When you add a task to a priority queue, you also say how important it is. The more important, the sooner it gets done.</p><h4>Doing Tasks (Dequeue):</h4><p>The priority queue takes care of doing the most important task first. It&#39;s like automatically picking the task with the highest priority.</p><h4>Checking the Top Task(peek):</h4><p>You can peek at the top task without actually doing it. This is useful when you want to see what&#39;s the most important thing right now.</p><h4>Changing Importance:</h4><p>If something becomes more urgent or less critical, you can change its priority in the queue.</p><h4>Implementation Approaches:</h4><h4>Heap-based Priority Queue:</h4><h4><strong>Heap Structure:</strong></h4><p>A binary heap is frequently used to implement a priority queue. It ensures that the element with the highest priority is at the root of the heap.<br><strong>Time Complexity:</strong><br>Insertion: O(log n)<br>Deletion: O(log n)<br><strong>Space Complexity:</strong><br>O(n)</p><pre>pimport heapq<br><br>class HeapPriorityQueue:<br>    def __init__(self):<br>        self.heap = []<br><br>    def insert(self, element, priority):<br>        &quot;&quot;&quot;<br>        Insert an element into the heap-based priority queue.<br>        Time Complexity: O(log n)<br>        &quot;&quot;&quot;<br>        heapq.heappush(self.heap, (priority, element))<br><br>    def delete_max(self):<br>        &quot;&quot;&quot;<br>        Delete the element with the highest priority from the heap-based priority queue.<br>        Time Complexity: O(log n)<br>        &quot;&quot;&quot;<br>        if self.heap:<br>            return heapq.heappop(self.heap)<br>        else:<br>            return None<br><br>    def peek_max(self):<br>        &quot;&quot;&quot;<br>        Peek at the element with the highest priority without removing it.<br>        Time Complexity: O(1)<br>        &quot;&quot;&quot;<br>        if self.heap:<br>            return self.heap[0]<br>        else:<br>            return None<br><br>    def change_priority(self, element, new_priority):<br>        &quot;&quot;&quot;<br>        Change the priority of an element in the heap-based priority queue.<br>        Time Complexity: O(n) - Inefficient, better approaches are possible.<br>        &quot;&quot;&quot;<br>        # Remove the element with the old priority<br>        self.heap = [(priority, elem) for priority, elem in self.heap if elem != element]<br><br>        # Insert the element with the new priority<br>        self.insert(element, new_priority)<br><br># Example Usage<br>heap_priority_queue = HeapPriorityQueue()<br>heap_priority_queue.insert(&quot;Task A&quot;, 3)<br>heap_priority_queue.insert(&quot;Task B&quot;, 1)<br>heap_priority_queue.insert(&quot;Task C&quot;, 2)<br><br>print(&quot;Heap-based Priority Queue (Before):&quot;, heap_priority_queue.heap)<br><br># Change the priority of &quot;Task B&quot; to 4<br>heap_priority_queue.change_priority(&quot;Task B&quot;, 4)<br><br>print(&quot;Heap-based Priority Queue (After):&quot;, heap_priority_queue.heap)<br><br><br></pre><h4>2.Array-based Priority Queue:<br>Sorted Array:</h4><p>Elements are stored in a sorted manner based on their priorities.<br>Time Complexity:<br>Insertion: O(n)<br>Deletion: O(1)<br>Space Complexity:<br>O(n)</p><pre>class ArrayPriorityQueue:<br>    def __init__(self):<br>        self.array = []<br><br>    def insert(self, element, priority):<br>        &quot;&quot;&quot;<br>        Insert an element into the array-based priority queue.<br>        Time Complexity: O(n)<br>        &quot;&quot;&quot;<br>        self.array.append((element, priority))<br>        self.array.sort(key=lambda x: x[1])  # Sort based on priority<br><br>    def delete_max(self):<br>        &quot;&quot;&quot;<br>        Delete the element with the highest priority from the array-based priority queue.<br>        Time Complexity: O(1)<br>        &quot;&quot;&quot;<br>        if self.array:<br>            return self.array.pop()<br>        else:<br>            return None<br><br>    def peek_max(self):<br>        &quot;&quot;&quot;<br>        Peek at the element with the highest priority without removing it.<br>        Time Complexity: O(1)<br>        &quot;&quot;&quot;<br>        if self.array:<br>            return self.array[-1]<br>        else:<br>            return None<br><br>    def change_priority(self, element, new_priority):<br>        &quot;&quot;&quot;<br>        Change the priority of an element in the array-based priority queue.<br>        Time Complexity: O(n)<br>        &quot;&quot;&quot;<br>        for i in range(len(self.array)):<br>            if self.array[i][0] == element:<br>                # Update the priority of the element<br>                self.array[i] = (element, new_priority)<br>                # Re-sort the array based on priorities<br>                self.array.sort(key=lambda x: x[1])<br>                return<br><br># Example Usage<br>array_priority_queue = ArrayPriorityQueue()<br>array_priority_queue.insert(&quot;Task A&quot;, 3)<br>array_priority_queue.insert(&quot;Task B&quot;, 1)<br>array_priority_queue.insert(&quot;Task C&quot;, 2)<br><br>print(&quot;Array-based Priority Queue (Before):&quot;, array_priority_queue.array)<br><br># Change the priority of &quot;Task B&quot; to 4<br>array_priority_queue.change_priority(&quot;Task B&quot;, 4)<br><br>print(&quot;Array-based Priority Queue (After):&quot;, array_priority_queue.array)<br><br></pre><h4>Where You See Priority Queues</h4><h4>Getting Things Done:</h4><p>It&#39;s like managing your tasks with a sense of priority – doing the most important things first.</p><h4>Video Games:</h4><p>In some games, characters or actions are prioritized based on their importance in the game&#39;s logic.</p><h4>Emergency Rooms:</h4><p>Patients are treated based on the urgency of their condition – just like a priority queue</p><h4>Real-world Applications</h4><p>Understanding the synergy between Priority Queues and task schedulers is crucial for designing efficient algorithms. Real-world applications include:</p><p><strong>Operating Systems</strong>: Managing processes and system resources.<br><strong>Job Scheduling:</strong> Prioritizing and scheduling jobs based on criticality.<br><strong>Networking</strong>: Handling data packets with varying levels of priority during transmission.</p><p><strong>Dijkstra&#39;s Shortest Path Algorithm:</strong></p><p>Network Routing: Priority queues are integral to algorithms like Dijkstra&#39;s, which is used for finding the shortest path in network routing.</p><h4>In a nutshell</h4><p>A priority queue is like having a smart to-do list that always helps you focus on the most important things first – a helpful concept in the busy world of computing and problem-solving.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=082cafc7a9e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Queue Data Structures Unpacked: A Ticket Line Adventure]]></title>
            <link>https://medium.com/@ifte_refat/queue-data-structures-unpacked-a-ticket-line-adventure-134c30c3ad98?source=rss-dd7950de1317------2</link>
            <guid isPermaLink="false">https://medium.com/p/134c30c3ad98</guid>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Ifte Refat]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 22:26:49 GMT</pubDate>
            <atom:updated>2024-01-11T22:30:22.230Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever stood in line to buy tickets for a concert, movie, or any event? Well, that waiting line is not just a part of your daily life; it’s also a real-life example of a queue data structure. In this blog post, I’ll explain queues by drawing parallels with the experience of waiting in line for tickets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hIoS-xn8YvJoMEgtsKQP3g.jpeg" /><figcaption>Taken from flickr.com/photos/huntr/</figcaption></figure><h4>What is a Queue?</h4><p>A queue is a linear data structure that follows the <strong>FIFO</strong> principle.</p><h4>First In, First Out (FIFO):</h4><p>The first person to join the ticket line is the first one to get their tickets. This follows the First In, First Out principle of queues, where the element that arrives first is the first to be served.</p><h4>Operations of Queue:</h4><h4>1)Enqueue (Joining the Line):</h4><p>Imagine you decide to attend a concert, and there’s a line to buy tickets. By getting in line, you are essentially &quot;enqueueing&quot; yourself – taking your place at the end of the queue.</p><h4>2. Dequeue (Purchasing Tickets):</h4><p>As the person at the front of the line buys their tickets and leaves, they’ve been &quot;dequeued&quot; – removed from the front. The next person in line then becomes the new front and gets their tickets.</p><h4>4. Front and Rear of the Line:</h4><p>The front of the ticket line is where the tickets are being sold, and the back is where new people join. Just like a queue, there&#39;s a front and back to keep things organized.</p><h3>4. Waiting Your Turn:</h3><p>Waiting in the ticket line is all about patiently waiting for your turn. It ensures fairness – everyone gets a chance to buy tickets in the order they arrived, similar to how elements wait for processing in a computer queue.</p><h4>5)isEmpty:</h4><p>Checks if the queue is empty.</p><h4>6)isFull:</h4><p>Checks if the queue is full (applies to fixed-size queues).</p><h4>Implementation of Queues:</h4><p>There are various ways to implement a queue data structure, each with its own advantages and disadvantages. The two most common implementations are:</p><h4>Array Implementation:</h4><p>In this approach, a fixed-size array is used to store elements of the queue.<br>Enqueue and dequeue operations have O(1) time complexity.<br>However, this implementation may lead to wastage of memory if the array size is fixed.</p><pre>class Queue:<br>    def __init__(self, capacity):<br>        &quot;&quot;&quot;<br>        Initialize an empty queue with a specified capacity.<br><br>        Parameters:<br>        - capacity: Maximum number of elements the queue can hold.<br>        &quot;&quot;&quot;<br>        self.capacity = capacity<br>        self.queue = [None] * capacity  # Initialize an array with the given capacity<br>        self.front = self.rear = -1  # Initialize front and rear pointers<br><br>    def is_empty(self):<br>        &quot;&quot;&quot;<br>        Check if the queue is empty.<br><br>        Returns:<br>        - True if the queue is empty, False otherwise.<br>        &quot;&quot;&quot;<br>        return self.front == -1<br><br>    def is_full(self):<br>        &quot;&quot;&quot;<br>        Check if the queue is full.<br><br>        Returns:<br>        - True if the queue is full, False otherwise.<br>        &quot;&quot;&quot;<br>        return (self.rear + 1) % self.capacity == self.front<br><br>    def enqueue(self, item):<br>        &quot;&quot;&quot;<br>        Add an element to the rear of the queue.<br><br>        Parameters:<br>        - item: The element to be added to the queue.<br>        &quot;&quot;&quot;<br>        if self.is_full():<br>            print(&quot;Queue is full. Cannot enqueue.&quot;)<br>        else:<br>            if self.is_empty():<br>                self.front = self.rear = 0<br>            else:<br>                self.rear = (self.rear + 1) % self.capacity<br>            self.queue[self.rear] = item<br>            print(f&quot;Enqueued: {item}&quot;)<br><br>    def dequeue(self):<br>        &quot;&quot;&quot;<br>        Remove and return the element from the front of the queue.<br><br>        Returns:<br>        - The element removed from the front of the queue.<br>        &quot;&quot;&quot;<br>        if self.is_empty():<br>            print(&quot;Queue is empty. Cannot dequeue.&quot;)<br>            return None<br>        else:<br>            item = self.queue[self.front]<br>            if self.front == self.rear:<br>                self.front = self.rear = -1<br>            else:<br>                self.front = (self.front + 1) % self.capacity<br>            print(f&quot;Dequeued: {item}&quot;)<br>            return item<br><br>    def get_front(self):<br>        &quot;&quot;&quot;<br>        Get the element at the front of the queue without removing it.<br><br>        Returns:<br>        - The element at the front of the queue.<br>        &quot;&quot;&quot;<br>        if self.is_empty():<br>            print(&quot;Queue is empty.&quot;)<br>            return None<br>        else:<br>            return self.queue[self.front]<br><br>    def get_rear(self):<br>        &quot;&quot;&quot;<br>        Get the element at the rear of the queue without removing it.<br><br>        Returns:<br>        - The element at the rear of the queue.<br>        &quot;&quot;&quot;<br>        if self.is_empty():<br>            print(&quot;Queue is empty.&quot;)<br>            return None<br>        else:<br>            return self.queue[self.rear]<br><br>    def display(self):<br>        &quot;&quot;&quot;<br>        Display the elements of the queue.<br>        &quot;&quot;&quot;<br>        if self.is_empty():<br>            print(&quot;Queue is empty.&quot;)<br>        else:<br>            print(&quot;Queue elements:&quot;, end=&quot; &quot;)<br>            i = self.front<br>            while i != self.rear:<br>                print(self.queue[i], end=&quot; &quot;)<br>                i = (i + 1) % self.capacity<br>            print(self.queue[self.rear])<br><br></pre><h4>Linked List Implementation:</h4><p>In this approach, a linked list is used to represent the elements of the queue.<br>Enqueue and dequeue operations also have O(1) time complexity.<br>This implementation doesn’t have a fixed size, allowing dynamic memory allocation.</p><pre>class Node:<br>    def __init__(self, data):<br>        &quot;&quot;&quot;<br>        Node class to represent an element in the queue.<br><br>        Parameters:<br>        - data: The data to be stored in the node.<br>        &quot;&quot;&quot;<br>        self.data = data<br>        self.next = None<br><br><br>class QueueLinkedList:<br>    def __init__(self):<br>        &quot;&quot;&quot;<br>        Initialize an empty queue using a linked list.<br>        &quot;&quot;&quot;<br>        self.front = self.rear = None<br><br>    def is_empty(self):<br>        &quot;&quot;&quot;<br>        Check if the queue is empty.<br><br>        Returns:<br>        - True if the queue is empty, False otherwise.<br>        &quot;&quot;&quot;<br>        return self.front is None<br><br>    def enqueue(self, item):<br>        &quot;&quot;&quot;<br>        Add an element to the rear of the queue.<br><br>        Parameters:<br>        - item: The element to be added to the queue.<br>        &quot;&quot;&quot;<br>        new_node = Node(item)<br>        if self.is_empty():<br>            self.front = self.rear = new_node<br>        else:<br>            self.rear.next = new_node<br>            self.rear = new_node<br>        print(f&quot;Enqueued: {item}&quot;)<br><br>    def dequeue(self):<br>        &quot;&quot;&quot;<br>        Remove and return the element from the front of the queue.<br><br>        Returns:<br>        - The element removed from the front of the queue.<br>        &quot;&quot;&quot;<br>        if self.is_empty():<br>            print(&quot;Queue is empty. Cannot dequeue.&quot;)<br>            return None<br>        else:<br>            item = self.front.data<br>            if self.front == self.rear:<br>                self.front = self.rear = None<br>            else:<br>                self.front = self.front.next<br>            print(f&quot;Dequeued: {item}&quot;)<br>            return item<br><br>    def get_front(self):<br>        &quot;&quot;&quot;<br>        Get the element at the front of the queue without removing it.<br><br>        Returns:<br>        - The element at the front of the queue.<br>        &quot;&quot;&quot;<br>        if self.is_empty():<br>            print(&quot;Queue is empty.&quot;)<br>            return None<br>        else:<br>            return self.front.data<br><br>    def get_rear(self):<br>        &quot;&quot;&quot;<br>        Get the element at the rear of the queue without removing it.<br><br>        Returns:<br>        - The element at the rear of the queue.<br>        &quot;&quot;&quot;<br>        if self.is_empty():<br>            print(&quot;Queue is empty.&quot;)<br>            return None<br>        else:<br>            return self.rear.data<br><br>    def display(self):<br>        &quot;&quot;&quot;<br>        Display the elements of the queue.<br>        &quot;&quot;&quot;<br>        if self.is_empty():<br>            print(&quot;Queue is empty.&quot;)<br>        else:<br>            current = self.front<br>            print(&quot;Queue elements:&quot;, end=&quot; &quot;)<br>            while current:<br>                print(current.data, end=&quot; &quot;)<br>                current = current.next<br>            print()<br><br><br><br></pre><h4>More Queue-Like Scenarios in Real Life:<br>1. Bus Stops:</h4><p>People waiting for a bus form a queue. The first person at the bus stop is the first to board the bus, just like the first in line for tickets.</p><p>2. Post Office:<br>At the post office, customers wait in line to be served. The first one in line is the first to reach the counter.</p><h4>3. Amusement Park Rides:</h4><p>Queues for rides at an amusement park operate on a similar principle. The person who gets in line first experiences the thrill first.</p><h4>4. Airport Check-in:</h4><p>At the airport, passengers queue up at check-in counters. The first one to arrive at the counter is the first to complete the check-in process.</p><h4>The Beauty of Queues Beyond Ticket Lines:</h4><h4>1. Task Scheduling in Operating Systems:</h4><p>Computers use queues to manage tasks, ensuring that the first task that arrives is the first to be executed.</p><h4>2. Print Queues in Offices:</h4><p>Print jobs wait in a queue, ensuring that documents are printed in the order they are sent to the printer.</p><h4>3. Network Data Transmission:</h4><p>Queues play a vital role in managing data transmission, ensuring that information flows smoothly without overload.</p><h4>Overall:</h4><p>Queue data structures are a fundamental concept in computer science, providing an efficient and organized way to handle data. Whether it’s managing processes in an operating system or ensuring fairness in a print queue, queues play a crucial role in various applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=134c30c3ad98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cargo Stack: Unpacking the Basics of Stack Data Structure]]></title>
            <link>https://medium.com/@ifte_refat/cargo-stack-unpacking-the-basics-of-stack-data-structure-22862ae9fda6?source=rss-dd7950de1317------2</link>
            <guid isPermaLink="false">https://medium.com/p/22862ae9fda6</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[python-data-structures]]></category>
            <dc:creator><![CDATA[Ifte Refat]]></dc:creator>
            <pubDate>Wed, 10 Jan 2024 21:32:21 GMT</pubDate>
            <atom:updated>2024-01-10T21:50:02.156Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stack: Unpacking the Basics of Stack Data Structure</h3><p>Let’s talk about a cool Data Structure called a &quot;<strong>Stack</strong>&quot; by imagining a cargo shipment. It’s like putting different things in a pile, but there’s a special way to take them out.We call this the <strong>Last In, First Out (LIFO)</strong> rule. Let’s make it simple and fun!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*1DbgBA2W28cAyP2RYuRwAA.jpeg" /><figcaption>Taken from universal cargo</figcaption></figure><h4>How Stacks Work:</h4><h4>Array/List Trick:</h4><p>Sometimes, we use an array/list to make a stack. We just add or take away from the top section.We will be using List to demonstrate the stack operations.</p><pre>class Stack:<br>    def __init__(self):<br>        # Initialize an empty list to represent the stack<br>        self.items = []<br></pre><h4>Linked List Magic:</h4><p>Another way is using something called a <a href="https://medium.com/@ifte_refat/lets-explore-linked-lists-understanding-linked-lists-through-trains-58cf7cf4b97c">linked list</a>. It’s like a chain of container, and each container knows where the next one is.</p><h4>Basic Moves:</h4><p>1. <strong>Cargo Loading: Adding Boxes to the Pile</strong><br>Think of a big ship loading boxes onto its deck. Every new box added to the top of the pile is like a &quot;push.&quot; So, the last box you put in is the first one you take out.</p><p><strong>Real-life Example:</strong> Loading boxes onto a ship is like stacking things. The newest box is on the very top.</p><pre>def push(self, item):<br>        # Add a new item to the top of the stack<br>        self.items.append(item)<br>        print(f&quot;Pushed {item} onto the stack.&quot;)<br></pre><p>2. <strong>Unloading Cargo: Taking Boxes off the Pile</strong></p><p>When it&#39;s time to get the boxes off the ship, you start from the top. This is similar to a &quot;pop&quot; operation in stacks. The box on the very top is the first one you take away.</p><p><strong>Real-life Example</strong>: Unloading boxes from a ship is like popping items off a stack. The box on the top comes off first.</p><pre>def pop(self):<br>        if not self.isEmpty():<br>            # Remove and return the top item from the stack<br>            popped_item = self.items.pop()<br>            print(f&quot;Popped {popped_item} from the stack.&quot;)<br>            return popped_item<br>        else:<br>            print(&quot;Cannot pop from an empty stack<br></pre><p>3. <strong>Checking the Box without Moving It: Sneak Peek</strong><br>Imagine checking what&#39;s inside the top box without lifting it. That&#39;s like a &quot;peek&quot; in stacks. You can look at the top item without changing the pile.</p><p>Real-life Example: Looking into the top box without moving it is like peeking at the top of a stack without taking anything out.</p><pre>def peek(self):<br>        if not self.isEmpty():<br>            # Return the top item without removing it from the stack<br>            top_item = self.items[-1]<br>            print(f&quot;The top item on the stack is {top_item}.&quot;)<br>            return top_item<br>        else:<br>            print(&quot;Cannot peek into an empty stack.&quot;)<br></pre><p>4. <strong>Checking for an Empty Pile: Before Unloading</strong><br>Before trying to take a box off the ship, it&#39;s good to check if there are any boxes left. In computer talk, it&#39;s like checking if the &quot;cargo hold&quot; is empty before trying to take a box off.</p><p><strong>Real-life Example</strong>: Before unloading a box, checking if there are any more prevents trying to take a box that isn&#39;t there.</p><pre>def isEmpty(self):<br>        # Check if the stack is empty<br>        is_empty = len(self.items) == 0<br>        if is_empty:<br>            print(&quot;The stack is empty.&quot;)<br>        else:<br>            print(&quot;The stack is not empty.&quot;)<br>        return is_empty<br></pre><h4>Fun Uses of Stacks:</h4><h4>To-Do List:</h4><p>Think of your to-do list as a stack. You add new tasks on top, and when you finish one, you cross it off – just like eating a pancake!</p><h4>Puzzle Solving:</h4><p>Ever tried solving a maze or puzzle step by step? Stacks help computers backtrack and figure out the best path.</p><h4>Undo Button:</h4><p>Imagine if you could undo mistakes in real life. Stacks make it possible in computer programs. Each action is like a pancake, and you can undo by taking them off the top.</p><h4>Time Talk:</h4><p><strong>Fast and Simple:</strong><br>Adding or taking away a container is super quick – like snapping your fingers! No matter how big the stack is, it happens in the same amount of time.</p><h4><strong>Conclusion:</strong></h4><p>Understanding stacks is like solving a cargo puzzle. Whether it’s loading and unloading boxes or adding and taking away things in computer programs, the idea is pretty similar. So, the next time you see a pile of stuff, think of it as a cool stack adventure, where the last thing in is the first thing out! Happy stacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22862ae9fda6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Explore Linked Lists: Understanding Linked Lists through Trains]]></title>
            <link>https://medium.com/@ifte_refat/lets-explore-linked-lists-understanding-linked-lists-through-trains-58cf7cf4b97c?source=rss-dd7950de1317------2</link>
            <guid isPermaLink="false">https://medium.com/p/58cf7cf4b97c</guid>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[understanding]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ifte Refat]]></dc:creator>
            <pubDate>Tue, 09 Jan 2024 19:30:50 GMT</pubDate>
            <atom:updated>2024-01-10T03:31:41.826Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, we will explore the concept of linked lists uniquely, their types, advantages, and common use cases. I’ll try to teach you a linked list using the train concept.</p><h3>Concepts of Linked List</h3><p><strong>Linked</strong> lists are like digital trains carrying important information on each car! They’re super useful in organizing data on computers, connecting one piece to the next seamlessly. Efficient and flexible, linked lists are the unsung heroes of the digital world!</p><h3>Understanding Linked Lists through Trains <a href="https://emojipedia.org/locomotive">🚂</a>:</h3><p>Imagine a train system where each train car is like a node in a linked list. Let’s break down the comparison:</p><h3>Components of a Linked List:</h3><h3>1. Train Car (Node):</h3><ul><li>In a train, each car holds cargo and connects to the next car.</li><li>Each node holds data and links to the next node.</li></ul><pre><br># Node class for a Linked List<br>class Node:<br>    &quot;&quot;&quot;<br>    Represents a node in a linked list.<br><br>    Attributes:<br>        data: Information stored in the node.<br>        next: Reference to the next node in the linked list.<br>    &quot;&quot;&quot;<br><br>    # Initialize the node object<br>    def __init__(self, data):<br>        &quot;&quot;&quot;<br>        Constructor to initialize a new node with given data.<br><br>        Parameters:<br>            data: Information to be stored in the node.<br>        &quot;&quot;&quot;<br>        self.data = data  # Assign data to the node<br>        self.next = None   # Initialize next as null (to be updated when adding a new node)</pre><h3>2. Engine (Head):</h3><ul><li>The front of the train is the engine, leading the way.</li><li>In a linked list, the head is like the engine, pointing to the first node.</li></ul><pre># LinkedList class<br>class LinkedList:<br>    &quot;&quot;&quot;<br>    Represents a linked list.<br><br>    Attributes:<br>        head: Reference to the first node in the linked list.<br>    &quot;&quot;&quot;<br><br>    # Initialize the linked list<br>    def __init__(self):<br>        &quot;&quot;&quot;<br>        Constructor to initialize an empty linked list.<br>        &quot;&quot;&quot;<br>        self.head = None  # Initially, the list is empty, so the head points to None</pre><h3>3. Last Car (Tail):</h3><ul><li>The last car signals the end of the train.</li><li>In a linked list, the tail is the final node, pointing to nothing (null) to mark the end.</li></ul><h3>Different Types of Linked Lists:</h3><h3>1. Train Cars in a Row (Singly Linked List):</h3><ul><li>Train cars are connected one after another.</li><li>In a singly linked list, nodes are linked in a single chain.</li></ul><pre># Node class for a Singly Linked List<br>class Node:<br>    &quot;&quot;&quot;<br>    Represents a node in a singly linked list.<br><br>    Attributes:<br>        data: Information stored in the node.<br>        next: Reference to the next node in the linked list.<br>    &quot;&quot;&quot;<br><br>    # Initialize the node object<br>    def __init__(self, data):<br>        &quot;&quot;&quot;<br>        Constructor to initialize a new node with given data.<br><br>        Parameters:<br>            data: Information to be stored in the node.<br>        &quot;&quot;&quot;<br>        self.data = data  # Assign data to the node<br>        self.next = None   # Initialize next as null (to be updated when adding a new node)<br><br><br># SinglyLinkedList class<br>class SinglyLinkedList:<br>    &quot;&quot;&quot;<br>    Represents a singly linked list.<br><br>    Attributes:<br>        head: Reference to the first node in the linked list.<br>    &quot;&quot;&quot;<br><br>    # Initialize the linked list<br>    def __init__(self):<br>        &quot;&quot;&quot;<br>        Constructor to initialize an empty singly linked list.<br>        &quot;&quot;&quot;<br>        self.head = None  # Initially, the list is empty, so the head points to None</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y4fCcCJkkMlBwmuKdOlmcw.jpeg" /></figure><h3>2. Train Cars with Doors on Both Sides (Doubly Linked List):</h3><ul><li>Some trains have doors on both sides of the cars.</li><li>In a doubly linked list, nodes have links to both the next and previous nodes.</li></ul><pre># Node class for a Doubly Linked List<br>class Node:<br>    &quot;&quot;&quot;<br>    Represents a node in a doubly linked list.<br><br>    Attributes:<br>        data: Information stored in the node.<br>        next: Reference to the next node in the linked list.<br>        prev: Reference to the previous node in the linked list.<br>    &quot;&quot;&quot;<br><br>    # Initialize the node object<br>    def __init__(self, data):<br>        &quot;&quot;&quot;<br>        Constructor to initialize a new node with given data.<br><br>        Parameters:<br>            data: Information to be stored in the node.<br>        &quot;&quot;&quot;<br>        self.data = data  # Assign data to the node<br>        self.next = None   # Initialize next as null (to be updated when adding a new node)<br>        self.prev = None   # Initialize prev as null (to be updated when adding a new node)<br><br><br># DoublyLinkedList class<br>class DoublyLinkedList:<br>    &quot;&quot;&quot;<br>    Represents a doubly linked list.<br><br>    Attributes:<br>        head: Reference to the first node in the linked list.<br>        tail: Reference to the last node in the linked list.<br>    &quot;&quot;&quot;<br><br>    # Initialize the linked list<br>    def __init__(self):<br>        &quot;&quot;&quot;<br>        Constructor to initialize an empty doubly linked list.<br>        &quot;&quot;&quot;<br>        self.head = None  # Initially, the list is empty, so the head points to None<br>        self.tail = None  # Initially, the list is empty, so the tail points to None</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P2MlqqyB6O8HpywvJYhZQA.jpeg" /></figure><h3>3. Train in a Loop (Circular Linked List):</h3><ul><li>Imagine a train moving in a loop with the last car connected to the first.</li><li>A circular linked list forms a loop, with the tail pointing back to the head.</li></ul><pre># Node class for a Circular Linked List<br>class Node:<br>    &quot;&quot;&quot;<br>    Represents a node in a circular linked list.<br><br>    Attributes:<br>        data: Information stored in the node.<br>        next: Reference to the next node in the linked list.<br>    &quot;&quot;&quot;<br><br>    # Initialize the node object<br>    def __init__(self, data):<br>        &quot;&quot;&quot;<br>        Constructor to initialize a new node with given data.<br><br>        Parameters:<br>            data: Information to be stored in the node.<br>        &quot;&quot;&quot;<br>        self.data = data  # Assign data to the node<br>        self.next = None   # Initialize next as null (to be updated when adding a new node)<br><br><br># CircularLinkedList class<br>class CircularLinkedList:<br>    &quot;&quot;&quot;<br>    Represents a circular linked list.<br><br>    Attributes:<br>        head: Reference to the first node in the linked list.<br>    &quot;&quot;&quot;<br><br>    # Initialize the linked list<br>    def __init__(self):<br>        &quot;&quot;&quot;<br>        Constructor to initialize an empty circular linked list.<br>        &quot;&quot;&quot;<br>        self.head = None  # Initially, the list is empty, so the head points to None</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rdgbqr7Gqeccl3tXPP4Sg.jpeg" /></figure><h3>Train Operations (Linked List Tasks):</h3><h4>Adding a New Car (Node):</h4><blockquote>Attach a new car to the front, middle, or end of the train.</blockquote><h4>2.Removing a Car (Node):</h4><blockquote>Detach a car from the train, leaving the rest connected.</blockquote><h4>3.Checking Each Car (Node):</h4><blockquote>Go through each car in the train, just like traversing nodes in a linked list.</blockquote><h4>4.Finding a Specific Cargo (Node with Specific Data):</h4><blockquote>Look for a particular cargo in a train, similar to finding a node with specific data in a linked list.</blockquote><h3>Advantages of Linked Lists:</h3><h4>Dynamic Size:</h4><ul><li>Can easily grow or shrink during runtime.</li></ul><h4>Efficient Insertion and Deletion:</h4><ul><li>Inserting or deleting nodes is more efficient compared to arrays.</li></ul><h4>No Pre-allocation of Memory:</h4><ul><li>Memory is allocated as needed, avoiding wasted space.</li></ul><h3>Where Do We See Linked Lists?</h3><h4>Remembering Stuff in Apps:</h4><ul><li>Apps use linked lists to remember things that might change a lot.</li></ul><h4>Stacking and Queuing:</h4><ul><li>Linked lists help in making stacks (like plates in a restaurant) and queues (like people waiting in line).</li></ul><h4>Undo Buttons in Apps:</h4><ul><li>Ever made a mistake in a drawing app and pressed undo? Linked lists help make that magic happen!</li></ul><h3>Conclusion:</h3><p>Understanding linked lists through the analogy of trains helps simplify the concept. Just as trains efficiently transport cargo, linked lists are dynamic structures that efficiently manage and organize data in a flexible manner.</p><h4>Thank You, Guys, For reading all the way through. Hope You guys understand the basic concept of LinkedList.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58cf7cf4b97c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>